title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Java Examples - Remove an element
|
How to remove an element of array?
Following example shows how to remove an element from array.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList objArray = new ArrayList();
objArray.clear();
objArray.add(0,"0th element");
objArray.add(1,"1st element");
objArray.add(2,"2nd element");
System.out.println("Array before removing an element"+objArray);
objArray.remove(1);
objArray.remove("0th element");
System.out.println("Array after removing an element"+objArray);
}
}
The above code sample will produce the following result.
Array before removing an element[0th element, 1st element, 2nd element]
Array after removing an element[2nd element]
Another sample example of Arrays Remove
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>(5);
arr.add(20);
arr.add(15);
arr.add(30);
arr.add(45);
System.out.println("Size of list: " + arr.size());
for (Integer number : arr) {
System.out.println("Number = " + number);
}
arr.remove(2);
System.out.println("Now, Size of list: " + arr.size());
for (Integer number : arr) {
System.out.println("Number = " + number);
}
}
}
The above code sample will produce the following result.
Size of list: 4
Number = 20
Number = 15
Number = 30
Number = 45
Now, Size of list: 3
Number = 20
Number = 15
Number = 45
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2103,
"s": 2068,
"text": "How to remove an element of array?"
},
{
"code": null,
"e": 2164,
"s": 2103,
"text": "Following example shows how to remove an element from array."
},
{
"code": null,
"e": 2648,
"s": 2164,
"text": "import java.util.ArrayList;\n\npublic class Main {\n public static void main(String[] args) {\n ArrayList objArray = new ArrayList();\n objArray.clear();\n objArray.add(0,\"0th element\");\n objArray.add(1,\"1st element\");\n objArray.add(2,\"2nd element\");\n System.out.println(\"Array before removing an element\"+objArray);\n objArray.remove(1);\n objArray.remove(\"0th element\");\n System.out.println(\"Array after removing an element\"+objArray);\n }\n}"
},
{
"code": null,
"e": 2705,
"s": 2648,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 2824,
"s": 2705,
"text": "Array before removing an element[0th element, 1st element, 2nd element]\nArray after removing an element[2nd element]\n"
},
{
"code": null,
"e": 2864,
"s": 2824,
"text": "Another sample example of Arrays Remove"
},
{
"code": null,
"e": 3454,
"s": 2864,
"text": "import java.util.ArrayList;\n\npublic class ArrayListDemo {\n public static void main(String[] args) {\n ArrayList<Integer> arr = new ArrayList<Integer>(5);\n arr.add(20);\n arr.add(15);\n arr.add(30);\n arr.add(45);\n \n System.out.println(\"Size of list: \" + arr.size());\n for (Integer number : arr) {\n System.out.println(\"Number = \" + number);\n } \n arr.remove(2);\n System.out.println(\"Now, Size of list: \" + arr.size());\n \n for (Integer number : arr) {\n System.out.println(\"Number = \" + number);\n } \n }\n} "
},
{
"code": null,
"e": 3511,
"s": 3454,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3633,
"s": 3511,
"text": "Size of list: 4\nNumber = 20\nNumber = 15\nNumber = 30\nNumber = 45\nNow, Size of list: 3\nNumber = 20\nNumber = 15\nNumber = 45\n"
},
{
"code": null,
"e": 3640,
"s": 3633,
"text": " Print"
},
{
"code": null,
"e": 3651,
"s": 3640,
"text": " Add Notes"
}
] |
d-*-block class in Bootstrap 4
|
Use the d-*block class in Bootstrap to create block on a specific screen width.
You can set it for small, medium, large, and extra large screen size −
<span class="d-sm-block bg-primary">
d-sm-block
</span>
<span class="d-md-block bg-success">
d-md-block
</span>
<span class="d-lg-block bg-info">
d-lg-block
</span>
<span class="d-xl-block bg-warning">
d-xl-block
</span>
You can try to run the following code to implement the d-*-block 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>Blocks</h2>
<p>Resize the browser to check the effect</p>
<span class="d-block bg-info">block</span>
<span class="d-sm-block bg-primary">Small Screen Size</span>
<span class="d-md-block bg-success">Medium Screen Size</span>
<span class="d-lg-block bg-info">Large Screen Size</span>
<span class="d-xl-block bg-warning">Extra Large Screen Size</span>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "Use the d-*block class in Bootstrap to create block on a specific screen width."
},
{
"code": null,
"e": 1213,
"s": 1142,
"text": "You can set it for small, medium, large, and extra large screen size −"
},
{
"code": null,
"e": 1442,
"s": 1213,
"text": "<span class=\"d-sm-block bg-primary\">\n d-sm-block\n</span>\n<span class=\"d-md-block bg-success\">\n d-md-block\n</span>\n<span class=\"d-lg-block bg-info\">\n d-lg-block\n</span>\n<span class=\"d-xl-block bg-warning\">\n d-xl-block\n</span>"
},
{
"code": null,
"e": 1515,
"s": 1442,
"text": "You can try to run the following code to implement the d-*-block class −"
},
{
"code": null,
"e": 1525,
"s": 1515,
"text": "Live Demo"
},
{
"code": null,
"e": 2437,
"s": 1525,
"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>Blocks</h2>\n <p>Resize the browser to check the effect</p>\n <span class=\"d-block bg-info\">block</span>\n <span class=\"d-sm-block bg-primary\">Small Screen Size</span>\n <span class=\"d-md-block bg-success\">Medium Screen Size</span>\n <span class=\"d-lg-block bg-info\">Large Screen Size</span>\n <span class=\"d-xl-block bg-warning\">Extra Large Screen Size</span>\n</div>\n\n</body>\n</html>"
}
] |
Deep Learning Analysis Using Large Model Support | by Pier Paolo Ippolito | Towards Data Science
|
1
2
3
4
5
6
7
8
9
10
Powered by Play.ht
Create audio with Play.ht
Create Audio Narrations with Play.ht
Memory management is now a really important topic in Machine Learning. Because of memory constraints, it is becoming quite common to train Deep Learning models using cloud tools such as Kaggle and Google Colab thanks to their free NVIDIA Graphical Processing Unit (GPU) support. Nonetheless, memory can still be a huge constraint in the cloud when working with large amounts of data.
In my last article, I explained how to speed up Machine Learning workflow execution. This article aims instead to explain to you how to efficiently reduce memory usage when implementing Deep Learning models. In this way, you might be able to train your Deep Learning model using the same amount of memory (even if before you couldn’t because of memory errors).
There are three main reasons for which a model can lead to running out of memory:
Model depth/complexity = number of layers and nodes in a Neural Network.
Data Size = number of samples/features in the dataset used.
Batch Size = number of samples that get propagated through a Neural Network.
One solution to this problem has traditionally been to reduce the model size by trying to get rid of less relevant features during the preprocessing stage. This can be done using either Feature Importance or Feature Extraction techniques (eg. PCA, LDA).
Using this approach can possibly lead to reduced noise (decreasing the chance of overfitting) and faster training times. One downside though to this approach can be a consistent decrease in accuracy.
If the model needs a high complexity to capture all the important characteristics of a dataset, reducing the dataset size will in fact inevitably lead to worse performances. In this case, Large Model Support can be the solution to this problem.
Large Model Support (LMS) is a Python library recently launched by IBM. This library has been ideated in order to train large Deep Learning models which can’t fit in GPU memory. In fact, GPUs have generally smaller memory space compared to Central Processing Units (CPUs).
When Neural Networks are implemented using libraries such as Tensorflow and PyTorch, a set of mathematical operations gets automatically generated to construct this model. These mathematical operations can then be represented using computational graphs.
A computational graph is a directed graph where the nodes correspond to operations or variables. Variables can feed their value into operations, and operations can feed their output into other operations. This way, every node in the graph defines a function of the variables.
— deep ideas [1]
The values that enter and comes out of nodes in computational graphs are called tensors (multi-dimensional arrays).
In Figure 1 is represented a simple example of how a mathematical operation can be represented using a computational graph ( z = (x + y) ∗ (x − 5) ):
LMS is able to alleviate GPUs memory problems by redesigning Neural Networks computational graphs. This is done by making possible to transfer tensor operations by storing intermediate results on CPUs (instead of GPUs).
The IBM documentation outlines three different methods to use Large Model Support using the Tensorflow library:
Session-based training.
Estimator-based training.
Keras-based training.
In this article, I will provide an example using Keras-based training. If you are interested in finding out more about the two other methods, IBM documentation is a great place where to start [3].
When working with LMS there are two main parameters we can tune in order to improve our model efficiency. The objective is to be able to find out the minimum number of tensors we need to swap out without incurring in memory errors.
The two main parameters to tune are:
n_tensors = number of swapped tensors (eg. swiping out more tensors than needed, can lead to communication overheads).
lb = how soon tensors are swapped back in before use (eg. using a low value for lb can make GPU training pause).
I will now walk you through a simple example to get you started with LMS. All the code used for this exercise is available in this Google Colaboratory notebook and on my GitHub.
In this example, I will train a simple Neural Network using first Keras with Large Model Support and then just plain Keras. I both cases, I will record the memory usage required for the training.
In order to install all the required dependencies to follow this example, just run the following cell in your notebook and enable your GPU environment (eg. Kaggle, Google Colab).
! git clone https://github.com/IBM/tensorflow-large-model-support.git! pip install ./tensorflow-large-model-support! pip install memory_profiler
Once is everything set up, we can then import all the necessary libraries.
In order to record the memory usage, I decided to use Python memory_profiler.
Successively, I defined the LMS Keras Callback which will be used during training. The definition of a Callback according to Keras documentation is:
A callback is a set of functions to be applied at given stages of the training procedure. You can use callbacks to get a view on internal states and statistics of the model during training.
— Keras Documentation [4]
Callbacks are typically used to take control of a model training process by automating certain tasks during every training iteration (in this case by adding Large Model Support optimization).
I then decided to fabricate a simple dataset of 200000 rows using Gaussian Distributions consisting of three features and two labels (0/1).
The values of the means and standard deviations of the distributions have been chosen so that to make this classification problem fairly easy (linearly separable data).
Once created the dataset, I divided it into features and labels and then defined a function to preprocess it.
Now that we got our Training/Test sets, we are finally ready to get started with Deep Learning. I, therefore, defined a simple Sequential model for binary classification and selected a batch size of 8 elements.
When using LMS, a Keras model is trained using Keras fit_generator function. The first input this function needs, is a generator. A generator is a function used to generate a dataset on multiple cores in real-time and then input its results in a Deep Learning model [5].
In order to create the generator function used in this example, I took reference to this implementation.
In case you are interested in a more detailed explanation about Keras Generators, it is available here.
Once defined our generator function I then trained our model using the LMS Keras Callback defined before.
In the code above, I additionally added on the first line the %%memit command to print out the memory usage of running this cell. The results are shown below:
Epoch 1/2 200000/200000 [==============================] - 601s 3ms/step - loss: 0.0222 - acc: 0.9984 Epoch 2/2 200000/200000 [==============================] - 596s 3ms/step - loss: 0.0203 - acc: 0.9984 peak memory: 2834.80 MiB, increment: 2.88 MiB
The registered Peak Memory to train this model using LMS was equal to 2.83GB and the Increment 2.8MB.
Finally, I decided to test the accuracy of our trained model to validate our training results.
Model accuracy using Large Model Support: 99.9995 %
Repeating the same procedure using plain Keras, the following results were obtained:
Epoch 1/2 1600000/1600000 [==============================] - 537s 336us/step - loss: 0.0449 - acc: 0.9846 Epoch 2/2 1600000/1600000 [==============================] - 538s 336us/step - loss: 0.0403 - acc: 0.9857 peak memory: 2862.26 MiB, increment: 26.15 MiB
The registered Peak Memory to train this model using Keras was equal to 2.86GB and the Increment 26.15MB.
Testing our Keras model lead instead to 98.47% accuracy.
Model accuracy using Sklearn: 98.4795 %
Comparing the results obtained using Keras + LMS vs Plain Keras it can be noticed that using LMS can lead to a decrease in memory consumption and as well to an increase in model accuracy. LMS performance can even be even improved if given more GPU/CPU resources (which can be used to optimise training) and using larger datasets.
In addition to this, IBM and NVIDIA also decided to create a deep learning computer cluster of 27000 NVIDIA TESLA GPUs to further researchers in this area. If you are interested in finding out more, you can find more information here.
If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details:
Linkedin
Personal Blog
Personal Website
Medium Profile
GitHub
Kaggle
[1] Deep Learning From Scratch I: Computational Graphs — deep ideas. Accessed at: http://www.deepideas.net/deep-learning-from-scratch-i-computational-graphs/
[2] TFLMS: Large Model Support in TensorFlow by Graph Rewriting. Tung D. Le, Haruki Imai et al. Accessed at: https://arxiv.org/pdf/1807.02037.pdf
[3] Getting started with TensorFlow Large Model Support (TFLMS) — IBM Knowledge Center. Accessed at: https://www.ibm.com/support/knowledgecenter/en/SS5SF7_1.5.4/navigation/pai_tflms.html
[4] Kears Documentation. Docs -> Callbacks. Accessed at: https://keras.io/callbacks/?source=post_page---------------------------
[5] A detailed example of how to use data generators with Keras. Shervine Amidi. Accessed at: https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly
|
[
{
"code": null,
"e": 174,
"s": 172,
"text": "1"
},
{
"code": null,
"e": 176,
"s": 174,
"text": "2"
},
{
"code": null,
"e": 178,
"s": 176,
"text": "3"
},
{
"code": null,
"e": 180,
"s": 178,
"text": "4"
},
{
"code": null,
"e": 182,
"s": 180,
"text": "5"
},
{
"code": null,
"e": 184,
"s": 182,
"text": "6"
},
{
"code": null,
"e": 186,
"s": 184,
"text": "7"
},
{
"code": null,
"e": 188,
"s": 186,
"text": "8"
},
{
"code": null,
"e": 190,
"s": 188,
"text": "9"
},
{
"code": null,
"e": 193,
"s": 190,
"text": "10"
},
{
"code": null,
"e": 212,
"s": 193,
"text": "Powered by Play.ht"
},
{
"code": null,
"e": 238,
"s": 212,
"text": "Create audio with Play.ht"
},
{
"code": null,
"e": 275,
"s": 238,
"text": "Create Audio Narrations with Play.ht"
},
{
"code": null,
"e": 659,
"s": 275,
"text": "Memory management is now a really important topic in Machine Learning. Because of memory constraints, it is becoming quite common to train Deep Learning models using cloud tools such as Kaggle and Google Colab thanks to their free NVIDIA Graphical Processing Unit (GPU) support. Nonetheless, memory can still be a huge constraint in the cloud when working with large amounts of data."
},
{
"code": null,
"e": 1020,
"s": 659,
"text": "In my last article, I explained how to speed up Machine Learning workflow execution. This article aims instead to explain to you how to efficiently reduce memory usage when implementing Deep Learning models. In this way, you might be able to train your Deep Learning model using the same amount of memory (even if before you couldn’t because of memory errors)."
},
{
"code": null,
"e": 1102,
"s": 1020,
"text": "There are three main reasons for which a model can lead to running out of memory:"
},
{
"code": null,
"e": 1175,
"s": 1102,
"text": "Model depth/complexity = number of layers and nodes in a Neural Network."
},
{
"code": null,
"e": 1235,
"s": 1175,
"text": "Data Size = number of samples/features in the dataset used."
},
{
"code": null,
"e": 1312,
"s": 1235,
"text": "Batch Size = number of samples that get propagated through a Neural Network."
},
{
"code": null,
"e": 1566,
"s": 1312,
"text": "One solution to this problem has traditionally been to reduce the model size by trying to get rid of less relevant features during the preprocessing stage. This can be done using either Feature Importance or Feature Extraction techniques (eg. PCA, LDA)."
},
{
"code": null,
"e": 1766,
"s": 1566,
"text": "Using this approach can possibly lead to reduced noise (decreasing the chance of overfitting) and faster training times. One downside though to this approach can be a consistent decrease in accuracy."
},
{
"code": null,
"e": 2011,
"s": 1766,
"text": "If the model needs a high complexity to capture all the important characteristics of a dataset, reducing the dataset size will in fact inevitably lead to worse performances. In this case, Large Model Support can be the solution to this problem."
},
{
"code": null,
"e": 2284,
"s": 2011,
"text": "Large Model Support (LMS) is a Python library recently launched by IBM. This library has been ideated in order to train large Deep Learning models which can’t fit in GPU memory. In fact, GPUs have generally smaller memory space compared to Central Processing Units (CPUs)."
},
{
"code": null,
"e": 2538,
"s": 2284,
"text": "When Neural Networks are implemented using libraries such as Tensorflow and PyTorch, a set of mathematical operations gets automatically generated to construct this model. These mathematical operations can then be represented using computational graphs."
},
{
"code": null,
"e": 2814,
"s": 2538,
"text": "A computational graph is a directed graph where the nodes correspond to operations or variables. Variables can feed their value into operations, and operations can feed their output into other operations. This way, every node in the graph defines a function of the variables."
},
{
"code": null,
"e": 2831,
"s": 2814,
"text": "— deep ideas [1]"
},
{
"code": null,
"e": 2947,
"s": 2831,
"text": "The values that enter and comes out of nodes in computational graphs are called tensors (multi-dimensional arrays)."
},
{
"code": null,
"e": 3097,
"s": 2947,
"text": "In Figure 1 is represented a simple example of how a mathematical operation can be represented using a computational graph ( z = (x + y) ∗ (x − 5) ):"
},
{
"code": null,
"e": 3317,
"s": 3097,
"text": "LMS is able to alleviate GPUs memory problems by redesigning Neural Networks computational graphs. This is done by making possible to transfer tensor operations by storing intermediate results on CPUs (instead of GPUs)."
},
{
"code": null,
"e": 3429,
"s": 3317,
"text": "The IBM documentation outlines three different methods to use Large Model Support using the Tensorflow library:"
},
{
"code": null,
"e": 3453,
"s": 3429,
"text": "Session-based training."
},
{
"code": null,
"e": 3479,
"s": 3453,
"text": "Estimator-based training."
},
{
"code": null,
"e": 3501,
"s": 3479,
"text": "Keras-based training."
},
{
"code": null,
"e": 3698,
"s": 3501,
"text": "In this article, I will provide an example using Keras-based training. If you are interested in finding out more about the two other methods, IBM documentation is a great place where to start [3]."
},
{
"code": null,
"e": 3930,
"s": 3698,
"text": "When working with LMS there are two main parameters we can tune in order to improve our model efficiency. The objective is to be able to find out the minimum number of tensors we need to swap out without incurring in memory errors."
},
{
"code": null,
"e": 3967,
"s": 3930,
"text": "The two main parameters to tune are:"
},
{
"code": null,
"e": 4086,
"s": 3967,
"text": "n_tensors = number of swapped tensors (eg. swiping out more tensors than needed, can lead to communication overheads)."
},
{
"code": null,
"e": 4199,
"s": 4086,
"text": "lb = how soon tensors are swapped back in before use (eg. using a low value for lb can make GPU training pause)."
},
{
"code": null,
"e": 4377,
"s": 4199,
"text": "I will now walk you through a simple example to get you started with LMS. All the code used for this exercise is available in this Google Colaboratory notebook and on my GitHub."
},
{
"code": null,
"e": 4573,
"s": 4377,
"text": "In this example, I will train a simple Neural Network using first Keras with Large Model Support and then just plain Keras. I both cases, I will record the memory usage required for the training."
},
{
"code": null,
"e": 4752,
"s": 4573,
"text": "In order to install all the required dependencies to follow this example, just run the following cell in your notebook and enable your GPU environment (eg. Kaggle, Google Colab)."
},
{
"code": null,
"e": 4897,
"s": 4752,
"text": "! git clone https://github.com/IBM/tensorflow-large-model-support.git! pip install ./tensorflow-large-model-support! pip install memory_profiler"
},
{
"code": null,
"e": 4972,
"s": 4897,
"text": "Once is everything set up, we can then import all the necessary libraries."
},
{
"code": null,
"e": 5050,
"s": 4972,
"text": "In order to record the memory usage, I decided to use Python memory_profiler."
},
{
"code": null,
"e": 5199,
"s": 5050,
"text": "Successively, I defined the LMS Keras Callback which will be used during training. The definition of a Callback according to Keras documentation is:"
},
{
"code": null,
"e": 5389,
"s": 5199,
"text": "A callback is a set of functions to be applied at given stages of the training procedure. You can use callbacks to get a view on internal states and statistics of the model during training."
},
{
"code": null,
"e": 5415,
"s": 5389,
"text": "— Keras Documentation [4]"
},
{
"code": null,
"e": 5607,
"s": 5415,
"text": "Callbacks are typically used to take control of a model training process by automating certain tasks during every training iteration (in this case by adding Large Model Support optimization)."
},
{
"code": null,
"e": 5747,
"s": 5607,
"text": "I then decided to fabricate a simple dataset of 200000 rows using Gaussian Distributions consisting of three features and two labels (0/1)."
},
{
"code": null,
"e": 5916,
"s": 5747,
"text": "The values of the means and standard deviations of the distributions have been chosen so that to make this classification problem fairly easy (linearly separable data)."
},
{
"code": null,
"e": 6026,
"s": 5916,
"text": "Once created the dataset, I divided it into features and labels and then defined a function to preprocess it."
},
{
"code": null,
"e": 6237,
"s": 6026,
"text": "Now that we got our Training/Test sets, we are finally ready to get started with Deep Learning. I, therefore, defined a simple Sequential model for binary classification and selected a batch size of 8 elements."
},
{
"code": null,
"e": 6508,
"s": 6237,
"text": "When using LMS, a Keras model is trained using Keras fit_generator function. The first input this function needs, is a generator. A generator is a function used to generate a dataset on multiple cores in real-time and then input its results in a Deep Learning model [5]."
},
{
"code": null,
"e": 6613,
"s": 6508,
"text": "In order to create the generator function used in this example, I took reference to this implementation."
},
{
"code": null,
"e": 6717,
"s": 6613,
"text": "In case you are interested in a more detailed explanation about Keras Generators, it is available here."
},
{
"code": null,
"e": 6823,
"s": 6717,
"text": "Once defined our generator function I then trained our model using the LMS Keras Callback defined before."
},
{
"code": null,
"e": 6982,
"s": 6823,
"text": "In the code above, I additionally added on the first line the %%memit command to print out the memory usage of running this cell. The results are shown below:"
},
{
"code": null,
"e": 7232,
"s": 6982,
"text": "Epoch 1/2 200000/200000 [==============================] - 601s 3ms/step - loss: 0.0222 - acc: 0.9984 Epoch 2/2 200000/200000 [==============================] - 596s 3ms/step - loss: 0.0203 - acc: 0.9984 peak memory: 2834.80 MiB, increment: 2.88 MiB"
},
{
"code": null,
"e": 7334,
"s": 7232,
"text": "The registered Peak Memory to train this model using LMS was equal to 2.83GB and the Increment 2.8MB."
},
{
"code": null,
"e": 7429,
"s": 7334,
"text": "Finally, I decided to test the accuracy of our trained model to validate our training results."
},
{
"code": null,
"e": 7481,
"s": 7429,
"text": "Model accuracy using Large Model Support: 99.9995 %"
},
{
"code": null,
"e": 7566,
"s": 7481,
"text": "Repeating the same procedure using plain Keras, the following results were obtained:"
},
{
"code": null,
"e": 7825,
"s": 7566,
"text": "Epoch 1/2 1600000/1600000 [==============================] - 537s 336us/step - loss: 0.0449 - acc: 0.9846 Epoch 2/2 1600000/1600000 [==============================] - 538s 336us/step - loss: 0.0403 - acc: 0.9857 peak memory: 2862.26 MiB, increment: 26.15 MiB"
},
{
"code": null,
"e": 7931,
"s": 7825,
"text": "The registered Peak Memory to train this model using Keras was equal to 2.86GB and the Increment 26.15MB."
},
{
"code": null,
"e": 7988,
"s": 7931,
"text": "Testing our Keras model lead instead to 98.47% accuracy."
},
{
"code": null,
"e": 8028,
"s": 7988,
"text": "Model accuracy using Sklearn: 98.4795 %"
},
{
"code": null,
"e": 8358,
"s": 8028,
"text": "Comparing the results obtained using Keras + LMS vs Plain Keras it can be noticed that using LMS can lead to a decrease in memory consumption and as well to an increase in model accuracy. LMS performance can even be even improved if given more GPU/CPU resources (which can be used to optimise training) and using larger datasets."
},
{
"code": null,
"e": 8593,
"s": 8358,
"text": "In addition to this, IBM and NVIDIA also decided to create a deep learning computer cluster of 27000 NVIDIA TESLA GPUs to further researchers in this area. If you are interested in finding out more, you can find more information here."
},
{
"code": null,
"e": 8751,
"s": 8593,
"text": "If you want to keep updated with my latest articles and projects follow me on Medium and subscribe to my mailing list. These are some of my contacts details:"
},
{
"code": null,
"e": 8760,
"s": 8751,
"text": "Linkedin"
},
{
"code": null,
"e": 8774,
"s": 8760,
"text": "Personal Blog"
},
{
"code": null,
"e": 8791,
"s": 8774,
"text": "Personal Website"
},
{
"code": null,
"e": 8806,
"s": 8791,
"text": "Medium Profile"
},
{
"code": null,
"e": 8813,
"s": 8806,
"text": "GitHub"
},
{
"code": null,
"e": 8820,
"s": 8813,
"text": "Kaggle"
},
{
"code": null,
"e": 8978,
"s": 8820,
"text": "[1] Deep Learning From Scratch I: Computational Graphs — deep ideas. Accessed at: http://www.deepideas.net/deep-learning-from-scratch-i-computational-graphs/"
},
{
"code": null,
"e": 9124,
"s": 8978,
"text": "[2] TFLMS: Large Model Support in TensorFlow by Graph Rewriting. Tung D. Le, Haruki Imai et al. Accessed at: https://arxiv.org/pdf/1807.02037.pdf"
},
{
"code": null,
"e": 9311,
"s": 9124,
"text": "[3] Getting started with TensorFlow Large Model Support (TFLMS) — IBM Knowledge Center. Accessed at: https://www.ibm.com/support/knowledgecenter/en/SS5SF7_1.5.4/navigation/pai_tflms.html"
},
{
"code": null,
"e": 9440,
"s": 9311,
"text": "[4] Kears Documentation. Docs -> Callbacks. Accessed at: https://keras.io/callbacks/?source=post_page---------------------------"
}
] |
Derive the string “abb” for leftmost and rightmost derivation
|
Let’s consider a grammar to derive “abb” string using LMD and RMD
S->AB/ ε
A-> aB
B-> Sb
We have to use context free grammar.
Derivation is a sequence of production rules, which is used to get input strings.
During parsing, we have to take two decisions, which are as follows −
We have to decide which non-terminal has to be replaced.
We have to decide which non-terminal has to be replaced by using which production rule.
There are two options to decide which non-terminal has to be replaced with production rule −
Leftmost derivation
Rightmost derivation
The input is scanned and replaced with production rules from left to right.
The given production rules are:
S->AB/ ε
A-> aB
B-> Sb
Let’s derive the string “abb” using LMD
S->AB
->aBB {A->aB}
->aSbB {B->Sb}
->abB {S-> ε}
->abSb {B->Sb}
->abb {S-> ε}
Which is our final string
The input is scanned and replaced with a production rule from right to left.
The given production rules are:
S->AB/ ε
A-> aB
B-> Sb
Let’s derive the string “abb” using RMD
S -> AB
->ASb {B->Sb}
->Ab {S-> ε}
->aBb {A->aB}
->aSbb {B->Sb}
->abb {S-> ε}
Reached our final string
|
[
{
"code": null,
"e": 1128,
"s": 1062,
"text": "Let’s consider a grammar to derive “abb” string using LMD and RMD"
},
{
"code": null,
"e": 1140,
"s": 1128,
"text": " S->AB/ ε"
},
{
"code": null,
"e": 1150,
"s": 1140,
"text": " A-> aB"
},
{
"code": null,
"e": 1160,
"s": 1150,
"text": " B-> Sb"
},
{
"code": null,
"e": 1197,
"s": 1160,
"text": "We have to use context free grammar."
},
{
"code": null,
"e": 1279,
"s": 1197,
"text": "Derivation is a sequence of production rules, which is used to get input strings."
},
{
"code": null,
"e": 1349,
"s": 1279,
"text": "During parsing, we have to take two decisions, which are as follows −"
},
{
"code": null,
"e": 1406,
"s": 1349,
"text": "We have to decide which non-terminal has to be replaced."
},
{
"code": null,
"e": 1494,
"s": 1406,
"text": "We have to decide which non-terminal has to be replaced by using which production rule."
},
{
"code": null,
"e": 1587,
"s": 1494,
"text": "There are two options to decide which non-terminal has to be replaced with production rule −"
},
{
"code": null,
"e": 1607,
"s": 1587,
"text": "Leftmost derivation"
},
{
"code": null,
"e": 1628,
"s": 1607,
"text": "Rightmost derivation"
},
{
"code": null,
"e": 1704,
"s": 1628,
"text": "The input is scanned and replaced with production rules from left to right."
},
{
"code": null,
"e": 1930,
"s": 1704,
"text": "The given production rules are:\n S->AB/ ε\n A-> aB\n B-> Sb\nLet’s derive the string “abb” using LMD\n S->AB\n ->aBB {A->aB}\n ->aSbB {B->Sb}\n ->abB {S-> ε}\n ->abSb {B->Sb}\n ->abb {S-> ε}\nWhich is our final string"
},
{
"code": null,
"e": 2007,
"s": 1930,
"text": "The input is scanned and replaced with a production rule from right to left."
},
{
"code": null,
"e": 2232,
"s": 2007,
"text": "The given production rules are:\n S->AB/ ε\n A-> aB\n B-> Sb\nLet’s derive the string “abb” using RMD\n S -> AB\n ->ASb {B->Sb}\n ->Ab {S-> ε}\n ->aBb {A->aB}\n ->aSbb {B->Sb}\n ->abb {S-> ε}\nReached our final string"
}
] |
How to get content of entire page using Selenium?
|
We can get the content of the entire page using Selenium. There are more than one ways of achieving it. To get the text of the visible on the page we can use the method findElement(By.tagname()) method to get hold of . Next can then use the getText() method to extract text from the body tag.
Syntax −
WebElement l=driver.findElement(By.tagName("body"));
String t = l.getText();
The next approach to get the content of the entire page is to use the getPageSource() method.
Syntax −
String l = driver.getPageSource();
Code Implementation with <body> tag.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class TextContent{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.google.com/";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element and input text inside it
WebElement l =driver.findElement(By.tagName("body"));
System.out.println("Text content: "+ l.getText());
driver.quit();
}
}
Code Implementation with getPageSource().
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PageSrc{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.google.com/";
driver.get(url);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// getPageSource() and print
String l = driver.getPageSource();
System.out.println("Page source: "+ l);
driver.quit();
}
}
|
[
{
"code": null,
"e": 1355,
"s": 1062,
"text": "We can get the content of the entire page using Selenium. There are more than one ways of achieving it. To get the text of the visible on the page we can use the method findElement(By.tagname()) method to get hold of . Next can then use the getText() method to extract text from the body tag."
},
{
"code": null,
"e": 1364,
"s": 1355,
"text": "Syntax −"
},
{
"code": null,
"e": 1441,
"s": 1364,
"text": "WebElement l=driver.findElement(By.tagName(\"body\"));\nString t = l.getText();"
},
{
"code": null,
"e": 1535,
"s": 1441,
"text": "The next approach to get the content of the entire page is to use the getPageSource() method."
},
{
"code": null,
"e": 1544,
"s": 1535,
"text": "Syntax −"
},
{
"code": null,
"e": 1579,
"s": 1544,
"text": "String l = driver.getPageSource();"
},
{
"code": null,
"e": 1616,
"s": 1579,
"text": "Code Implementation with <body> tag."
},
{
"code": null,
"e": 2368,
"s": 1616,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class TextContent{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.google.com/\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify element and input text inside it\n WebElement l =driver.findElement(By.tagName(\"body\"));\n System.out.println(\"Text content: \"+ l.getText());\n driver.quit();\n }\n}"
},
{
"code": null,
"e": 2410,
"s": 2368,
"text": "Code Implementation with getPageSource()."
},
{
"code": null,
"e": 3113,
"s": 2410,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class PageSrc{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.google.com/\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // getPageSource() and print\n String l = driver.getPageSource();\n System.out.println(\"Page source: \"+ l);\n driver.quit();\n }\n}"
}
] |
C Program to list all files and sub-directories in a directory - GeeksforGeeks
|
20 May, 2017
#include <stdio.h>#include <dirent.h> int main(void){ struct dirent *de; // Pointer for directory entry // opendir() returns a pointer of DIR type. DIR *dr = opendir("."); if (dr == NULL) // opendir returns NULL if couldn't open directory { printf("Could not open current directory" ); return 0; } // Refer http://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html // for readdir() while ((de = readdir(dr)) != NULL) printf("%s\n", de->d_name); closedir(dr); return 0;}
Output:
All files and subdirectories
of current directory
cpp-file-handling
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Arrow operator -> in C/C++ with Examples
Storage Classes in C
Ways to copy a vector in C++
Smart Pointers in C++ and How to Use Them
Switch Statement in C/C++
|
[
{
"code": null,
"e": 24232,
"s": 24204,
"text": "\n20 May, 2017"
},
{
"code": "#include <stdio.h>#include <dirent.h> int main(void){ struct dirent *de; // Pointer for directory entry // opendir() returns a pointer of DIR type. DIR *dr = opendir(\".\"); if (dr == NULL) // opendir returns NULL if couldn't open directory { printf(\"Could not open current directory\" ); return 0; } // Refer http://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html // for readdir() while ((de = readdir(dr)) != NULL) printf(\"%s\\n\", de->d_name); closedir(dr); return 0;}",
"e": 24783,
"s": 24232,
"text": null
},
{
"code": null,
"e": 24791,
"s": 24783,
"text": "Output:"
},
{
"code": null,
"e": 24872,
"s": 24791,
"text": " All files and subdirectories \n of current directory "
},
{
"code": null,
"e": 24890,
"s": 24872,
"text": "cpp-file-handling"
},
{
"code": null,
"e": 24901,
"s": 24890,
"text": "C Language"
},
{
"code": null,
"e": 24999,
"s": 24901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25008,
"s": 24999,
"text": "Comments"
},
{
"code": null,
"e": 25021,
"s": 25008,
"text": "Old Comments"
},
{
"code": null,
"e": 25059,
"s": 25021,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 25085,
"s": 25059,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 25105,
"s": 25085,
"text": "Multithreading in C"
},
{
"code": null,
"e": 25127,
"s": 25105,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 25165,
"s": 25127,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 25206,
"s": 25165,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 25227,
"s": 25206,
"text": "Storage Classes in C"
},
{
"code": null,
"e": 25256,
"s": 25227,
"text": "Ways to copy a vector in C++"
},
{
"code": null,
"e": 25298,
"s": 25256,
"text": "Smart Pointers in C++ and How to Use Them"
}
] |
Detecting low contrast images with OpenCV, scikit-image, and Python - GeeksforGeeks
|
04 Jan, 2022
In this article, we are going to see how to detect low contrast images with OpenCV, scikit-image using Python
A low contrast image has the minimal distinction between light and dark parts, making it difficult to tell where an object’s boundary begins and the scene’s background begins. For example
The left one is low contrast and the right one is a high contrast image. Using low contrast image detection, you can programmatically detect images that are not sufficient for your image processing pipeline.
First Let’s see how we can manually see the contrast of a picture using histograms. The histogram for a high contrast image(Right) spans the entire dynamic range, but the histogram for a low contrast image(Left) just covers a narrow range, as seen below.
Now let’s do it programmatically using the is_low_contrast method of scikit-image library.
Import all the libraries needed.
Read the image in grayscale mode.
Check if image is low contrast image or high contrast image using some threshold value provided.
Syntax: is_low_contrast(img,”threshold value”)
Input Image:
Code:
Python3
import cv2from skimage.exposure import is_low_contrast img = cv2.imread("low_contrast_img(1).jpg")gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if(is_low_contrast(gray,0.35)): cv2.putText(img, "low contrast image", (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,0), 2)else: cv2.putText(img, "high contrast image", (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,0), 2) cv2.imshow("output",img)cv2.imwrite("output.jpg",img)cv2.waitKey(0) # closing all open windows cv2.destroyAllWindows()
Output:
Input:
Code:
Python3
import cv2from skimage.exposure import is_low_contrast img = cv2.imread("high contrast image(2).jpg")gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)if(is_low_contrast(gray,0.35)): cv2.putText(img, "low contrast image", (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,0), 2)else: cv2.putText(img, "high contrast image", (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,0), 2) cv2.imshow("output",img)cv2.imwrite("output.jpg",img)cv2.waitKey(0) # closing all open windows cv2.destroyAllWindows()
Output:
You can further find the contours on high contrast images for image preprocessing and extract the object from the image.
Image-Processing
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25665,
"s": 25637,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 25775,
"s": 25665,
"text": "In this article, we are going to see how to detect low contrast images with OpenCV, scikit-image using Python"
},
{
"code": null,
"e": 25963,
"s": 25775,
"text": "A low contrast image has the minimal distinction between light and dark parts, making it difficult to tell where an object’s boundary begins and the scene’s background begins. For example"
},
{
"code": null,
"e": 26171,
"s": 25963,
"text": "The left one is low contrast and the right one is a high contrast image. Using low contrast image detection, you can programmatically detect images that are not sufficient for your image processing pipeline."
},
{
"code": null,
"e": 26427,
"s": 26171,
"text": "First Let’s see how we can manually see the contrast of a picture using histograms. The histogram for a high contrast image(Right) spans the entire dynamic range, but the histogram for a low contrast image(Left) just covers a narrow range, as seen below. "
},
{
"code": null,
"e": 26519,
"s": 26427,
"text": "Now let’s do it programmatically using the is_low_contrast method of scikit-image library."
},
{
"code": null,
"e": 26552,
"s": 26519,
"text": "Import all the libraries needed."
},
{
"code": null,
"e": 26586,
"s": 26552,
"text": "Read the image in grayscale mode."
},
{
"code": null,
"e": 26683,
"s": 26586,
"text": "Check if image is low contrast image or high contrast image using some threshold value provided."
},
{
"code": null,
"e": 26730,
"s": 26683,
"text": "Syntax: is_low_contrast(img,”threshold value”)"
},
{
"code": null,
"e": 26744,
"s": 26730,
"text": "Input Image: "
},
{
"code": null,
"e": 26750,
"s": 26744,
"text": "Code:"
},
{
"code": null,
"e": 26758,
"s": 26750,
"text": "Python3"
},
{
"code": "import cv2from skimage.exposure import is_low_contrast img = cv2.imread(\"low_contrast_img(1).jpg\")gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if(is_low_contrast(gray,0.35)): cv2.putText(img, \"low contrast image\", (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,0), 2)else: cv2.putText(img, \"high contrast image\", (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,0), 2) cv2.imshow(\"output\",img)cv2.imwrite(\"output.jpg\",img)cv2.waitKey(0) # closing all open windows cv2.destroyAllWindows() ",
"e": 27294,
"s": 26758,
"text": null
},
{
"code": null,
"e": 27302,
"s": 27294,
"text": "Output:"
},
{
"code": null,
"e": 27309,
"s": 27302,
"text": "Input:"
},
{
"code": null,
"e": 27315,
"s": 27309,
"text": "Code:"
},
{
"code": null,
"e": 27323,
"s": 27315,
"text": "Python3"
},
{
"code": "import cv2from skimage.exposure import is_low_contrast img = cv2.imread(\"high contrast image(2).jpg\")gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)if(is_low_contrast(gray,0.35)): cv2.putText(img, \"low contrast image\", (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,0), 2)else: cv2.putText(img, \"high contrast image\", (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,0), 2) cv2.imshow(\"output\",img)cv2.imwrite(\"output.jpg\",img)cv2.waitKey(0) # closing all open windows cv2.destroyAllWindows() ",
"e": 27862,
"s": 27323,
"text": null
},
{
"code": null,
"e": 27870,
"s": 27862,
"text": "Output:"
},
{
"code": null,
"e": 27991,
"s": 27870,
"text": "You can further find the contours on high contrast images for image preprocessing and extract the object from the image."
},
{
"code": null,
"e": 28008,
"s": 27991,
"text": "Image-Processing"
},
{
"code": null,
"e": 28015,
"s": 28008,
"text": "Picked"
},
{
"code": null,
"e": 28029,
"s": 28015,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 28036,
"s": 28029,
"text": "Python"
},
{
"code": null,
"e": 28134,
"s": 28036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28166,
"s": 28134,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28208,
"s": 28166,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28250,
"s": 28208,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28306,
"s": 28250,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28333,
"s": 28306,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28364,
"s": 28333,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28393,
"s": 28364,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28415,
"s": 28393,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28454,
"s": 28415,
"text": "Python | Get unique values from a list"
}
] |
Materialize CSS | Typography - GeeksforGeeks
|
12 Jun, 2020
Materialize CSS provides several elements that can be used for the typography of the page:
Headers
Blockquotes
Flow Text
Headers: Materialize CSS provides basic styling to be used on the header tags. The tags below show the available header tags that are styled by Materialize CSS:
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
Blockquotes: A Blockquote is used to give emphasis to a quote or citation. It can also be used for extra text hierarchy and emphasis.
<blockquote>
This is an example quotation using blockquote tag.
</blockquote>
Flow Text: The flow-text class can be used to fluidly resize the font size and line-height of the text that has to be scaled. To use flow-text, one needs to add the class flow-text to the needed tag. The below example shows the usage of this class.
<p class="flow-text">I am Flow Text</p>
Note: The standard font used by Materialize CSS is the Roboto 2.0 font. This font can be replaced by simply changing the font stack. This can be done by modifying the code below to include the needed font and add to the custom CSS.
html {
font-family: GillSans, Calibri, Trebuchet, sans-serif;
}
Example:
HTML
<!DOCTYPE html><html> <head> <!-- Include the Google Icon Font --> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- Include compiled and minified Materialize CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <!-- Include jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"> </script></head> <body> <h3>Headings</h3> <div class="card-panel green"> <!-- Using all the headers --> <h1>Heading 1</h1> <h2>Heading 2</h2> <h3>Heading 3</h3> <h4>Heading 4</h4> <h5>Heading 5</h5> <h6>Heading 6</h6> </div> <!-- Using blockquotes --> <h3>Blockquote</h3> <h5> <blockquote> <p> This is an example quotation that uses the blockquote tag. <br> This is a basic tutorial for the Materialize CSS Typography. </p> </blockquote> </h5> <div class="card-panel"> <h3>Free Flow</h3> <!-- Using the flow-text class --> <p class="flow-text"> GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and courses. GeeksforGeeks is a very fast growing community among programmers and have a reach of around 10 million+ readers globally. </p> </div> <!-- Include the compiled and minified Materialize JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script></body> </html>
Output:
Materialize-CSS
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 28046,
"s": 28018,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 28137,
"s": 28046,
"text": "Materialize CSS provides several elements that can be used for the typography of the page:"
},
{
"code": null,
"e": 28145,
"s": 28137,
"text": "Headers"
},
{
"code": null,
"e": 28157,
"s": 28145,
"text": "Blockquotes"
},
{
"code": null,
"e": 28167,
"s": 28157,
"text": "Flow Text"
},
{
"code": null,
"e": 28328,
"s": 28167,
"text": "Headers: Materialize CSS provides basic styling to be used on the header tags. The tags below show the available header tags that are styled by Materialize CSS:"
},
{
"code": null,
"e": 28455,
"s": 28328,
"text": "<h1>Heading 1</h1> \n<h2>Heading 2</h2> \n<h3>Heading 3</h3> \n<h4>Heading 4</h4> \n<h5>Heading 5</h5> \n<h6>Heading 6</h6> \n"
},
{
"code": null,
"e": 28589,
"s": 28455,
"text": "Blockquotes: A Blockquote is used to give emphasis to a quote or citation. It can also be used for extra text hierarchy and emphasis."
},
{
"code": null,
"e": 28672,
"s": 28589,
"text": "<blockquote>\n This is an example quotation using blockquote tag.\n</blockquote>\n"
},
{
"code": null,
"e": 28921,
"s": 28672,
"text": "Flow Text: The flow-text class can be used to fluidly resize the font size and line-height of the text that has to be scaled. To use flow-text, one needs to add the class flow-text to the needed tag. The below example shows the usage of this class."
},
{
"code": null,
"e": 28962,
"s": 28921,
"text": "<p class=\"flow-text\">I am Flow Text</p>\n"
},
{
"code": null,
"e": 29194,
"s": 28962,
"text": "Note: The standard font used by Materialize CSS is the Roboto 2.0 font. This font can be replaced by simply changing the font stack. This can be done by modifying the code below to include the needed font and add to the custom CSS."
},
{
"code": null,
"e": 29261,
"s": 29194,
"text": "html {\n font-family: GillSans, Calibri, Trebuchet, sans-serif;\n}"
},
{
"code": null,
"e": 29270,
"s": 29261,
"text": "Example:"
},
{
"code": null,
"e": 29275,
"s": 29270,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Include the Google Icon Font --> <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\"> <!-- Include compiled and minified Materialize CSS --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css\"> <!-- Include jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"> </script></head> <body> <h3>Headings</h3> <div class=\"card-panel green\"> <!-- Using all the headers --> <h1>Heading 1</h1> <h2>Heading 2</h2> <h3>Heading 3</h3> <h4>Heading 4</h4> <h5>Heading 5</h5> <h6>Heading 6</h6> </div> <!-- Using blockquotes --> <h3>Blockquote</h3> <h5> <blockquote> <p> This is an example quotation that uses the blockquote tag. <br> This is a basic tutorial for the Materialize CSS Typography. </p> </blockquote> </h5> <div class=\"card-panel\"> <h3>Free Flow</h3> <!-- Using the flow-text class --> <p class=\"flow-text\"> GeeksforGeeks is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and courses. GeeksforGeeks is a very fast growing community among programmers and have a reach of around 10 million+ readers globally. </p> </div> <!-- Include the compiled and minified Materialize JavaScript --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js\"> </script></body> </html>",
"e": 31134,
"s": 29275,
"text": null
},
{
"code": null,
"e": 31142,
"s": 31134,
"text": "Output:"
},
{
"code": null,
"e": 31158,
"s": 31142,
"text": "Materialize-CSS"
},
{
"code": null,
"e": 31162,
"s": 31158,
"text": "CSS"
},
{
"code": null,
"e": 31179,
"s": 31162,
"text": "Web Technologies"
},
{
"code": null,
"e": 31277,
"s": 31179,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31286,
"s": 31277,
"text": "Comments"
},
{
"code": null,
"e": 31299,
"s": 31286,
"text": "Old Comments"
},
{
"code": null,
"e": 31361,
"s": 31299,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31411,
"s": 31361,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 31459,
"s": 31411,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31517,
"s": 31459,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 31554,
"s": 31517,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 31596,
"s": 31554,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 31629,
"s": 31596,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31672,
"s": 31629,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 31734,
"s": 31672,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Maximize profit that can be earned by selling an item among N buyers - GeeksforGeeks
|
05 Apr, 2022
Given an array arr[] of size N, the task is to find the price of the item such that the profit earned by selling the item among N buyers is maximum possible consisting of budgets of N buyers. An item can be sold to any buyer if the budget of the buyer is greater than or equal to the price of the item.
Examples:
Input: arr[] = {34, 78, 90, 15, 67}Output: 67Explanation: For the item with price 67, the number of buyers who can buy the item is 3. Therefore, the profit earned is 67 * 3 = 201, which is maximum.
Input: arr[] = {300, 50, 32, 43, 42}Output: 300
Naive Approach: Follow the steps below to solve the problem:
Initialize two variables, say price and profit as 0, to store the profit by selling an item and the possible price of the item respectively.
Traverse the given array arr[] and perform the following steps:Set the price of the item as arr[i].Find the number of buyers whose budget is at least arr[i] by traversing the given array. Let the value be count.If the value of count*arr[i] is greater than the profit then update the profit as count*arr[i] and the price as arr[i].
Set the price of the item as arr[i].
Find the number of buyers whose budget is at least arr[i] by traversing the given array. Let the value be count.
If the value of count*arr[i] is greater than the profit then update the profit as count*arr[i] and the price as arr[i].
After completing the above steps, print the value of the price as the resultant price.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
#include <iostream>#include <climits>#include <algorithm>using namespace std;// Function to find the maximum profit// earned by selling an item among// N buyersint maximumProfit(int arr[],int n){ // Stores the maximum profit int ans = INT_MIN; // Stores the price of the item int price = 0; // Traverse the array for (int i = 0; i < n; i++) { // Count of buyers with // budget >= arr[i] int count = 0; for (int j = 0; j < n; j++) { if (arr[i] <= arr[j]) { // Increment count count++; } } // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price;} // Driver codeint main(){ int arr[] = { 22, 87, 9, 50, 56, 43 }; cout<<maximumProfit(arr,6); return 0;}
// Java program for the above approachimport java.util.*; class GFG { // Function to find the maximum profit // earned by selling an item among // N buyers public static int maximumProfit(int arr[]) { // Stores the maximum profit int ans = Integer.MIN_VALUE; // Stores the price of the item int price = 0; int n = arr.length; // Traverse the array for (int i = 0; i < n; i++) { // Count of buyers with // budget >= arr[i] int count = 0; for (int j = 0; j < n; j++) { if (arr[i] <= arr[j]) { // Increment count count++; } } // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price; } // Driver Code public static void main(String[] args) { int arr[] = { 22, 87, 9, 50, 56, 43 }; System.out.print( maximumProfit(arr)); }}
import sys # Function to find the maximum profit# earned by selling an item among# N buyersdef maximumProfit(arr, n): # Stores the maximum profit ans = -sys.maxsize - 1 # Stores the price of the item price = 0 # Traverse the array for i in range(n): # Count of buyers with # budget >= arr[i] count = 0 for j in range(n): if (arr[i] <= arr[j]): # Increment count count += 1 # Update the maximum profit if (ans < count * arr[i]): price = arr[i] ans = count * arr[i] # Return the maximum possible # price return price; # Driver codeif __name__ == '__main__': arr = [22, 87, 9, 50, 56, 43] print(maximumProfit(arr,6)) # This code is contributed by SURENDRA_GANGWAR.
// C# program for the above approachusing System; class GFG{ // Function to find the maximum profit // earned by selling an item among // N buyers public static int maximumProfit(int[] arr) { // Stores the maximum profit int ans = Int32.MinValue; // Stores the price of the item int price = 0; int n = arr.Length; // Traverse the array for (int i = 0; i < n; i++) { // Count of buyers with // budget >= arr[i] int count = 0; for (int j = 0; j < n; j++) { if (arr[i] <= arr[j]) { // Increment count count++; } } // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price; } // Driver Code public static void Main(string[] args) { int[] arr = { 22, 87, 9, 50, 56, 43 }; Console.Write( maximumProfit(arr)); }} // This code is contributed by sanjoy_62.
<script> // Function to find the maximum profit// earned by selling an item among// N buyersfunction maximumProfit(arr, n){// Stores the maximum profitvar ans = -100000;; // Stores the price of the itemvar price = 0; // Traverse the arrayfor (var i = 0; i < n; i++) { // Count of buyers with // budget >= arr[i] var count = 0; for (var j = 0; j < n; j++) { if (arr[i] <= arr[j]) { // Increment count count++; } } // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; }} // Return the maximum possible// pricereturn price;} arr = [ 22, 87, 9, 50, 56, 43 ]; document.write(maximumProfit(arr,6)); </script>
43
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by sorting the array such that the count of elements greater than the current element can be calculated in O(1) time. Follow the steps below to solve the problem:
Initialize two variables, say price and profit as 0, to store the profit by selling an item and the possible price of the item respectively.
Sort the array in ascending order.
Traverse the given array arr[i] and perform the following steps:Set the price of the item as arr[i].Now, the number of buyers whose budget is at least arr[i] is given by (N – i). Let the value be count.If the value of count*arr[i] is greater than the profit then update the profit as count*arr[i] and the price as arr[i].
Set the price of the item as arr[i].
Now, the number of buyers whose budget is at least arr[i] is given by (N – i). Let the value be count.
If the value of count*arr[i] is greater than the profit then update the profit as count*arr[i] and the price as arr[i].
After completing the above steps, print the value of the price as the resultant price.
Below is the implementation of the above approach:
C++
Java
C#
Python3
Javascript
// C++ program for the above approach#include <iostream>#include <climits>#include <algorithm>using namespace std; // Function to find the maximum profit// earned by selling an item among// N buyersint maximumProfit(int arr[],int N){ // Stores the maximum profit int ans = INT_MIN; // Stores the price of the item int price = 0; // Sort the array sort(arr, arr + N); // Traverse the array for (int i = 0; i < N; i++) { // Count of buyers with // budget >= arr[i] int count = (N - i); // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price;} // Driver codeint main(){ int arr[] = { 22, 87, 9, 50, 56, 43 }; cout << maximumProfit(arr,6); return 0;} // This code is contributed by le0.
// Java program for the above approachimport java.util.*; class GFG { // Function to find the maximum profit // earned by selling an item among // N buyers public static int maximumProfit(int arr[]) { // Stores the maximum profit int ans = Integer.MIN_VALUE; // Stores the price of the item int price = 0; // Sort the array Arrays.sort(arr); int N = arr.length; // Traverse the array for (int i = 0; i < N; i++) { // Count of buyers with // budget >= arr[i] int count = (N - i); // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price; } // Driver Code public static void main(String[] args) { int arr[] = { 22, 87, 9, 50, 56, 43 }; System.out.print( maximumProfit(arr)); }}
// C# Program to implement// the above approachusing System;class GFG{ // Function to find the maximum profit // earned by selling an item among // N buyers public static int maximumProfit(int[] arr) { // Stores the maximum profit int ans = Int32.MinValue; // Stores the price of the item int price = 0; // Sort the array Array.Sort(arr); int N = arr.Length; // Traverse the array for (int i = 0; i < N; i++) { // Count of buyers with // budget >= arr[i] int count = (N - i); // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price; } // Driver Code public static void Main(String[] args) { int[] arr = { 22, 87, 9, 50, 56, 43 }; Console.WriteLine( maximumProfit(arr)); }} // This code is contributed by splevel62.
# Python3 program for the above approachimport sys # Function to find the maximum profit# earned by selling an item among# N buyersdef maximumProfit(arr, N): # Stores the maximum profit ans = -sys.maxsize - 1 # Stores the price of the item price = 0 # Sort the array arr.sort() # Traverse the array for i in range(N): # Count of buyers with # budget >= arr[i] count = (N - i) # Update the maximum profit if (ans < count * arr[i]): price = arr[i] ans = count * arr[i] # Return the maximum possible # price return price # Driver codeif __name__ == "__main__": arr = [22, 87, 9, 50, 56, 43] print(maximumProfit(arr, 6)) # This code is contributed by ukasp
<script> // JavaScript program for the above approach // Function to find the maximum profit// earned by selling an item among// N buyersfunction maximumProfit( arr, N){ // Stores the maximum profit let ans = Number.MIN_VALUE; // Stores the price of the item let price = 0; // Sort the array arr.sort(function(a,b){return a-b}); // Traverse the array for (let i = 0; i < N; i++) { // Count of buyers with // budget >= arr[i] let count = (N - i); // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price;} // Driver codelet arr = [ 22, 87, 9, 50, 56, 43 ];document.write( maximumProfit(arr,6)); </script>
43
Time Complexity: O(N * log N)Auxiliary Space: O(1)
le0
sanjoy_62
ukasp
splevel62
SURENDRA_GANGWAR
akshitsaxenaa09
rohitsingh07052
harendrakumar123
Arrays
Mathematical
Searching
Sorting
Arrays
Searching
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
Coin Change | DP-7
|
[
{
"code": null,
"e": 24574,
"s": 24546,
"text": "\n05 Apr, 2022"
},
{
"code": null,
"e": 24877,
"s": 24574,
"text": "Given an array arr[] of size N, the task is to find the price of the item such that the profit earned by selling the item among N buyers is maximum possible consisting of budgets of N buyers. An item can be sold to any buyer if the budget of the buyer is greater than or equal to the price of the item."
},
{
"code": null,
"e": 24887,
"s": 24877,
"text": "Examples:"
},
{
"code": null,
"e": 25085,
"s": 24887,
"text": "Input: arr[] = {34, 78, 90, 15, 67}Output: 67Explanation: For the item with price 67, the number of buyers who can buy the item is 3. Therefore, the profit earned is 67 * 3 = 201, which is maximum."
},
{
"code": null,
"e": 25133,
"s": 25085,
"text": "Input: arr[] = {300, 50, 32, 43, 42}Output: 300"
},
{
"code": null,
"e": 25194,
"s": 25133,
"text": "Naive Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25335,
"s": 25194,
"text": "Initialize two variables, say price and profit as 0, to store the profit by selling an item and the possible price of the item respectively."
},
{
"code": null,
"e": 25666,
"s": 25335,
"text": "Traverse the given array arr[] and perform the following steps:Set the price of the item as arr[i].Find the number of buyers whose budget is at least arr[i] by traversing the given array. Let the value be count.If the value of count*arr[i] is greater than the profit then update the profit as count*arr[i] and the price as arr[i]."
},
{
"code": null,
"e": 25703,
"s": 25666,
"text": "Set the price of the item as arr[i]."
},
{
"code": null,
"e": 25816,
"s": 25703,
"text": "Find the number of buyers whose budget is at least arr[i] by traversing the given array. Let the value be count."
},
{
"code": null,
"e": 25936,
"s": 25816,
"text": "If the value of count*arr[i] is greater than the profit then update the profit as count*arr[i] and the price as arr[i]."
},
{
"code": null,
"e": 26023,
"s": 25936,
"text": "After completing the above steps, print the value of the price as the resultant price."
},
{
"code": null,
"e": 26074,
"s": 26023,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26078,
"s": 26074,
"text": "C++"
},
{
"code": null,
"e": 26083,
"s": 26078,
"text": "Java"
},
{
"code": null,
"e": 26091,
"s": 26083,
"text": "Python3"
},
{
"code": null,
"e": 26094,
"s": 26091,
"text": "C#"
},
{
"code": null,
"e": 26105,
"s": 26094,
"text": "Javascript"
},
{
"code": "#include <iostream>#include <climits>#include <algorithm>using namespace std;// Function to find the maximum profit// earned by selling an item among// N buyersint maximumProfit(int arr[],int n){ // Stores the maximum profit int ans = INT_MIN; // Stores the price of the item int price = 0; // Traverse the array for (int i = 0; i < n; i++) { // Count of buyers with // budget >= arr[i] int count = 0; for (int j = 0; j < n; j++) { if (arr[i] <= arr[j]) { // Increment count count++; } } // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price;} // Driver codeint main(){ int arr[] = { 22, 87, 9, 50, 56, 43 }; cout<<maximumProfit(arr,6); return 0;}",
"e": 26933,
"s": 26105,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG { // Function to find the maximum profit // earned by selling an item among // N buyers public static int maximumProfit(int arr[]) { // Stores the maximum profit int ans = Integer.MIN_VALUE; // Stores the price of the item int price = 0; int n = arr.length; // Traverse the array for (int i = 0; i < n; i++) { // Count of buyers with // budget >= arr[i] int count = 0; for (int j = 0; j < n; j++) { if (arr[i] <= arr[j]) { // Increment count count++; } } // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price; } // Driver Code public static void main(String[] args) { int arr[] = { 22, 87, 9, 50, 56, 43 }; System.out.print( maximumProfit(arr)); }}",
"e": 28077,
"s": 26933,
"text": null
},
{
"code": "import sys # Function to find the maximum profit# earned by selling an item among# N buyersdef maximumProfit(arr, n): # Stores the maximum profit ans = -sys.maxsize - 1 # Stores the price of the item price = 0 # Traverse the array for i in range(n): # Count of buyers with # budget >= arr[i] count = 0 for j in range(n): if (arr[i] <= arr[j]): # Increment count count += 1 # Update the maximum profit if (ans < count * arr[i]): price = arr[i] ans = count * arr[i] # Return the maximum possible # price return price; # Driver codeif __name__ == '__main__': arr = [22, 87, 9, 50, 56, 43] print(maximumProfit(arr,6)) # This code is contributed by SURENDRA_GANGWAR.",
"e": 28916,
"s": 28077,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the maximum profit // earned by selling an item among // N buyers public static int maximumProfit(int[] arr) { // Stores the maximum profit int ans = Int32.MinValue; // Stores the price of the item int price = 0; int n = arr.Length; // Traverse the array for (int i = 0; i < n; i++) { // Count of buyers with // budget >= arr[i] int count = 0; for (int j = 0; j < n; j++) { if (arr[i] <= arr[j]) { // Increment count count++; } } // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price; } // Driver Code public static void Main(string[] args) { int[] arr = { 22, 87, 9, 50, 56, 43 }; Console.Write( maximumProfit(arr)); }} // This code is contributed by sanjoy_62.",
"e": 29914,
"s": 28916,
"text": null
},
{
"code": "<script> // Function to find the maximum profit// earned by selling an item among// N buyersfunction maximumProfit(arr, n){// Stores the maximum profitvar ans = -100000;; // Stores the price of the itemvar price = 0; // Traverse the arrayfor (var i = 0; i < n; i++) { // Count of buyers with // budget >= arr[i] var count = 0; for (var j = 0; j < n; j++) { if (arr[i] <= arr[j]) { // Increment count count++; } } // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; }} // Return the maximum possible// pricereturn price;} arr = [ 22, 87, 9, 50, 56, 43 ]; document.write(maximumProfit(arr,6)); </script>",
"e": 30616,
"s": 29914,
"text": null
},
{
"code": null,
"e": 30619,
"s": 30616,
"text": "43"
},
{
"code": null,
"e": 30663,
"s": 30619,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30882,
"s": 30663,
"text": "Efficient Approach: The above approach can be optimized by sorting the array such that the count of elements greater than the current element can be calculated in O(1) time. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 31023,
"s": 30882,
"text": "Initialize two variables, say price and profit as 0, to store the profit by selling an item and the possible price of the item respectively."
},
{
"code": null,
"e": 31058,
"s": 31023,
"text": "Sort the array in ascending order."
},
{
"code": null,
"e": 31380,
"s": 31058,
"text": "Traverse the given array arr[i] and perform the following steps:Set the price of the item as arr[i].Now, the number of buyers whose budget is at least arr[i] is given by (N – i). Let the value be count.If the value of count*arr[i] is greater than the profit then update the profit as count*arr[i] and the price as arr[i]."
},
{
"code": null,
"e": 31417,
"s": 31380,
"text": "Set the price of the item as arr[i]."
},
{
"code": null,
"e": 31520,
"s": 31417,
"text": "Now, the number of buyers whose budget is at least arr[i] is given by (N – i). Let the value be count."
},
{
"code": null,
"e": 31640,
"s": 31520,
"text": "If the value of count*arr[i] is greater than the profit then update the profit as count*arr[i] and the price as arr[i]."
},
{
"code": null,
"e": 31727,
"s": 31640,
"text": "After completing the above steps, print the value of the price as the resultant price."
},
{
"code": null,
"e": 31778,
"s": 31727,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 31782,
"s": 31778,
"text": "C++"
},
{
"code": null,
"e": 31787,
"s": 31782,
"text": "Java"
},
{
"code": null,
"e": 31790,
"s": 31787,
"text": "C#"
},
{
"code": null,
"e": 31798,
"s": 31790,
"text": "Python3"
},
{
"code": null,
"e": 31809,
"s": 31798,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <iostream>#include <climits>#include <algorithm>using namespace std; // Function to find the maximum profit// earned by selling an item among// N buyersint maximumProfit(int arr[],int N){ // Stores the maximum profit int ans = INT_MIN; // Stores the price of the item int price = 0; // Sort the array sort(arr, arr + N); // Traverse the array for (int i = 0; i < N; i++) { // Count of buyers with // budget >= arr[i] int count = (N - i); // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price;} // Driver codeint main(){ int arr[] = { 22, 87, 9, 50, 56, 43 }; cout << maximumProfit(arr,6); return 0;} // This code is contributed by le0.",
"e": 32643,
"s": 31809,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG { // Function to find the maximum profit // earned by selling an item among // N buyers public static int maximumProfit(int arr[]) { // Stores the maximum profit int ans = Integer.MIN_VALUE; // Stores the price of the item int price = 0; // Sort the array Arrays.sort(arr); int N = arr.length; // Traverse the array for (int i = 0; i < N; i++) { // Count of buyers with // budget >= arr[i] int count = (N - i); // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price; } // Driver Code public static void main(String[] args) { int arr[] = { 22, 87, 9, 50, 56, 43 }; System.out.print( maximumProfit(arr)); }}",
"e": 33666,
"s": 32643,
"text": null
},
{
"code": "// C# Program to implement// the above approachusing System;class GFG{ // Function to find the maximum profit // earned by selling an item among // N buyers public static int maximumProfit(int[] arr) { // Stores the maximum profit int ans = Int32.MinValue; // Stores the price of the item int price = 0; // Sort the array Array.Sort(arr); int N = arr.Length; // Traverse the array for (int i = 0; i < N; i++) { // Count of buyers with // budget >= arr[i] int count = (N - i); // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price; } // Driver Code public static void Main(String[] args) { int[] arr = { 22, 87, 9, 50, 56, 43 }; Console.WriteLine( maximumProfit(arr)); }} // This code is contributed by splevel62.",
"e": 34596,
"s": 33666,
"text": null
},
{
"code": "# Python3 program for the above approachimport sys # Function to find the maximum profit# earned by selling an item among# N buyersdef maximumProfit(arr, N): # Stores the maximum profit ans = -sys.maxsize - 1 # Stores the price of the item price = 0 # Sort the array arr.sort() # Traverse the array for i in range(N): # Count of buyers with # budget >= arr[i] count = (N - i) # Update the maximum profit if (ans < count * arr[i]): price = arr[i] ans = count * arr[i] # Return the maximum possible # price return price # Driver codeif __name__ == \"__main__\": arr = [22, 87, 9, 50, 56, 43] print(maximumProfit(arr, 6)) # This code is contributed by ukasp",
"e": 35359,
"s": 34596,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find the maximum profit// earned by selling an item among// N buyersfunction maximumProfit( arr, N){ // Stores the maximum profit let ans = Number.MIN_VALUE; // Stores the price of the item let price = 0; // Sort the array arr.sort(function(a,b){return a-b}); // Traverse the array for (let i = 0; i < N; i++) { // Count of buyers with // budget >= arr[i] let count = (N - i); // Update the maximum profit if (ans < count * arr[i]) { price = arr[i]; ans = count * arr[i]; } } // Return the maximum possible // price return price;} // Driver codelet arr = [ 22, 87, 9, 50, 56, 43 ];document.write( maximumProfit(arr,6)); </script>",
"e": 36109,
"s": 35359,
"text": null
},
{
"code": null,
"e": 36112,
"s": 36109,
"text": "43"
},
{
"code": null,
"e": 36163,
"s": 36112,
"text": "Time Complexity: O(N * log N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 36167,
"s": 36163,
"text": "le0"
},
{
"code": null,
"e": 36177,
"s": 36167,
"text": "sanjoy_62"
},
{
"code": null,
"e": 36183,
"s": 36177,
"text": "ukasp"
},
{
"code": null,
"e": 36193,
"s": 36183,
"text": "splevel62"
},
{
"code": null,
"e": 36210,
"s": 36193,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 36226,
"s": 36210,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 36242,
"s": 36226,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 36259,
"s": 36242,
"text": "harendrakumar123"
},
{
"code": null,
"e": 36266,
"s": 36259,
"text": "Arrays"
},
{
"code": null,
"e": 36279,
"s": 36266,
"text": "Mathematical"
},
{
"code": null,
"e": 36289,
"s": 36279,
"text": "Searching"
},
{
"code": null,
"e": 36297,
"s": 36289,
"text": "Sorting"
},
{
"code": null,
"e": 36304,
"s": 36297,
"text": "Arrays"
},
{
"code": null,
"e": 36314,
"s": 36304,
"text": "Searching"
},
{
"code": null,
"e": 36327,
"s": 36314,
"text": "Mathematical"
},
{
"code": null,
"e": 36335,
"s": 36327,
"text": "Sorting"
},
{
"code": null,
"e": 36433,
"s": 36335,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36501,
"s": 36433,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36545,
"s": 36501,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 36593,
"s": 36545,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 36616,
"s": 36593,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 36648,
"s": 36616,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 36678,
"s": 36648,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 36693,
"s": 36678,
"text": "C++ Data Types"
},
{
"code": null,
"e": 36736,
"s": 36693,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 36796,
"s": 36736,
"text": "Write a program to print all permutations of a given string"
}
] |
How to display most frequent value in a Pandas series? - GeeksforGeeks
|
18 Aug, 2020
In this article, our basic task is to print the most frequent value in a series. We can find the number of occurrences of elements using the value_counts() method. From that the most frequent element can be accessed by using the mode() method.
Example 1 :
# importing the moduleimport pandas as pd # creating the seriesseries = pd.Series(['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'])print("Printing the Original Series:")display(series) # counting the frequency of each elementfreq = series.value_counts()print("Printing the frequency")display(freq) # printing the most frequent elementprint("Printing the most frequent element of series")display(series.mode());
Output :
Example 2 : Replacing the every element except the most frequent element with None.
# importing the moduleimport pandas as pd # creating the seriesseries = pd.Series(['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']) # counting the frequency of each elementfreq = series.value_counts() # replacing everything else as Otherseries[~series.isin(freq .index[:1])] = Noneprint(series)
Output :
Python Pandas-exercise
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 25891,
"s": 25647,
"text": "In this article, our basic task is to print the most frequent value in a series. We can find the number of occurrences of elements using the value_counts() method. From that the most frequent element can be accessed by using the mode() method."
},
{
"code": null,
"e": 25903,
"s": 25891,
"text": "Example 1 :"
},
{
"code": "# importing the moduleimport pandas as pd # creating the seriesseries = pd.Series(['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'])print(\"Printing the Original Series:\")display(series) # counting the frequency of each elementfreq = series.value_counts()print(\"Printing the frequency\")display(freq) # printing the most frequent elementprint(\"Printing the most frequent element of series\")display(series.mode());",
"e": 26375,
"s": 25903,
"text": null
},
{
"code": null,
"e": 26384,
"s": 26375,
"text": "Output :"
},
{
"code": null,
"e": 26468,
"s": 26384,
"text": "Example 2 : Replacing the every element except the most frequent element with None."
},
{
"code": "# importing the moduleimport pandas as pd # creating the seriesseries = pd.Series(['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']) # counting the frequency of each elementfreq = series.value_counts() # replacing everything else as Otherseries[~series.isin(freq .index[:1])] = Noneprint(series)",
"e": 26824,
"s": 26468,
"text": null
},
{
"code": null,
"e": 26833,
"s": 26824,
"text": "Output :"
},
{
"code": null,
"e": 26856,
"s": 26833,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 26877,
"s": 26856,
"text": "Python pandas-series"
},
{
"code": null,
"e": 26891,
"s": 26877,
"text": "Python-pandas"
},
{
"code": null,
"e": 26898,
"s": 26891,
"text": "Python"
},
{
"code": null,
"e": 26996,
"s": 26898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27028,
"s": 26996,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27070,
"s": 27028,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27112,
"s": 27070,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27168,
"s": 27112,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27195,
"s": 27168,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27226,
"s": 27195,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27255,
"s": 27226,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27277,
"s": 27255,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27313,
"s": 27277,
"text": "Python | Pandas dataframe.groupby()"
}
] |
HTTP headers | Connection - GeeksforGeeks
|
07 Nov, 2019
The HTTP Connection header is a general type header that allows the sender or client to specify options that are desired for that particular connection. Instead of opening a new connection for every single request/response, Connection helps in sending or receiving multiple HTTP requests/responses using a single TCP connection. It also controls whether or not the network stays open or close after the current transaction finishes.
Syntax:
Connection: keep-alive
Connection: close
Directives: This HTTP Connection header accept two directives mentioned above and described below:
keep-alive This directive indicates that the client wants to keep the connection open or alive after sending the response message. In HTTP 1.1 version, by default uses a persistent connection where it doesn’t close automatically after a transaction. But the HTTP 1.0 will not consider the connections as persistent, so if you want to keep it alive, you need to include a keep-alive connection header.
close This close connection directive indicates that the client wants to close the connection after sending the response message. In HTTP 1.0, by default, the connection gets closed. But in HTTP 1.1, you need to include it in the header if you want your connection to close.
Note: Both the directives are also headers that represent the connection in combine.
Example:
Here, in the below example, the connection is keep-alive (i.e) the client wants to keep it open and the value is 100. Usually, the value 100 is sufficient for almost every scenario. However, you can increase it depending on the number of files the server needs to deliver within the web page.Keep-Alive: 100
Connection: keep-alive
Keep-Alive: 100
Connection: keep-alive
The below example is the request message sent by a client in which it wants the connection to close after the response message is delivered.Connection: close
Connection: close
To check this Connection in action go to Inspect Element -> Network check the header for Connection like below.
Browser Compatibility: The browsers are compatible with HTTP Connection header are listed below:
Google Chrome
Internet Explorer
Edge
Firefox
Safari
OperaMy Personal Notes
arrow_drop_upSave
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to Insert Form Data into Database using PHP ?
How to redirect to another page in ReactJS ?
How to execute PHP code using command line ?
|
[
{
"code": null,
"e": 24906,
"s": 24878,
"text": "\n07 Nov, 2019"
},
{
"code": null,
"e": 25339,
"s": 24906,
"text": "The HTTP Connection header is a general type header that allows the sender or client to specify options that are desired for that particular connection. Instead of opening a new connection for every single request/response, Connection helps in sending or receiving multiple HTTP requests/responses using a single TCP connection. It also controls whether or not the network stays open or close after the current transaction finishes."
},
{
"code": null,
"e": 25347,
"s": 25339,
"text": "Syntax:"
},
{
"code": null,
"e": 25388,
"s": 25347,
"text": "Connection: keep-alive\nConnection: close"
},
{
"code": null,
"e": 25487,
"s": 25388,
"text": "Directives: This HTTP Connection header accept two directives mentioned above and described below:"
},
{
"code": null,
"e": 25888,
"s": 25487,
"text": "keep-alive This directive indicates that the client wants to keep the connection open or alive after sending the response message. In HTTP 1.1 version, by default uses a persistent connection where it doesn’t close automatically after a transaction. But the HTTP 1.0 will not consider the connections as persistent, so if you want to keep it alive, you need to include a keep-alive connection header."
},
{
"code": null,
"e": 26163,
"s": 25888,
"text": "close This close connection directive indicates that the client wants to close the connection after sending the response message. In HTTP 1.0, by default, the connection gets closed. But in HTTP 1.1, you need to include it in the header if you want your connection to close."
},
{
"code": null,
"e": 26248,
"s": 26163,
"text": "Note: Both the directives are also headers that represent the connection in combine."
},
{
"code": null,
"e": 26257,
"s": 26248,
"text": "Example:"
},
{
"code": null,
"e": 26588,
"s": 26257,
"text": "Here, in the below example, the connection is keep-alive (i.e) the client wants to keep it open and the value is 100. Usually, the value 100 is sufficient for almost every scenario. However, you can increase it depending on the number of files the server needs to deliver within the web page.Keep-Alive: 100\nConnection: keep-alive"
},
{
"code": null,
"e": 26627,
"s": 26588,
"text": "Keep-Alive: 100\nConnection: keep-alive"
},
{
"code": null,
"e": 26785,
"s": 26627,
"text": "The below example is the request message sent by a client in which it wants the connection to close after the response message is delivered.Connection: close"
},
{
"code": null,
"e": 26803,
"s": 26785,
"text": "Connection: close"
},
{
"code": null,
"e": 26915,
"s": 26803,
"text": "To check this Connection in action go to Inspect Element -> Network check the header for Connection like below."
},
{
"code": null,
"e": 27012,
"s": 26915,
"text": "Browser Compatibility: The browsers are compatible with HTTP Connection header are listed below:"
},
{
"code": null,
"e": 27026,
"s": 27012,
"text": "Google Chrome"
},
{
"code": null,
"e": 27044,
"s": 27026,
"text": "Internet Explorer"
},
{
"code": null,
"e": 27049,
"s": 27044,
"text": "Edge"
},
{
"code": null,
"e": 27057,
"s": 27049,
"text": "Firefox"
},
{
"code": null,
"e": 27064,
"s": 27057,
"text": "Safari"
},
{
"code": null,
"e": 27105,
"s": 27064,
"text": "OperaMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 27118,
"s": 27105,
"text": "HTTP-headers"
},
{
"code": null,
"e": 27125,
"s": 27118,
"text": "Picked"
},
{
"code": null,
"e": 27142,
"s": 27125,
"text": "Web Technologies"
},
{
"code": null,
"e": 27240,
"s": 27142,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27249,
"s": 27240,
"text": "Comments"
},
{
"code": null,
"e": 27262,
"s": 27249,
"text": "Old Comments"
},
{
"code": null,
"e": 27304,
"s": 27262,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27347,
"s": 27304,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27392,
"s": 27347,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27436,
"s": 27392,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 27497,
"s": 27436,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27569,
"s": 27497,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27627,
"s": 27569,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 27677,
"s": 27627,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27722,
"s": 27677,
"text": "How to redirect to another page in ReactJS ?"
}
] |
Using KDTree to detect similarities in a multidimensional dataset | by Thomas Vie | Towards Data Science
|
Most of data science is oriented towards the Train, Test, Predict paradigm. Who doesn’t want to guess the future! But there are some cases where other implementations are needed like unsupervised classification or discovering patterns in existing data. In other words, how to take advantage of the data which is already owned.
I think this aspect is a little bit disregarded and the literature about it is scarcer, compared to other branches of data science. Hence the reason for this little contribution.
Here’s the story: A client of ours needed a way to find similar items (neighbours) for a given entity, according to a fixed number of parameters. Practically, the dataset is composed of votes from Human Resources Professionals who could attribute up to 5 skills to an arbitrary amount of World universities. It means that Edouard from HR could vote for MIT as a good institution for Digitalisation, Oxford for Internationality and La Sorbonne for Soft Skills.
I prepared the data, output a Spiderweb chart where the client could choose any Institution and compare it with the others, here is an example for three random universities:
At that point, it seemed interesting to search for universities that would have been voted the same way, maybe to compare their actions and study what they were doing good and what wrong.
The data came in a spss file, with one row by vote, and according to our brief, the output had to be fast, because it was meant to be used as a Backend service, with near real time responses.
After some research, I thought that the best processing format for that would be a KD Tree for its multi-dimensional nature and its relatively easy and fast processing possibilities. I won’t explain in detail what KD Trees are but you can refer to the wikipedia article.
It is fully integrated into the sklearn module, and very easy to use as we’ll see below.
But first, let's do some prep!
Our dataset, as property of the client, has been anonymised. The names of the universities have been taken away, but the values are real.
We’ll start by importing the libraries:
import pandas as pdfrom sklearn.neighbors import KDTree
Pandas will be used to import and process our data. It is very fast and useful for database-like processing
sklearn stands for scikit-learn, one the most famous library for data analysis. It is used for classification, clustering, regression and more. We’ll just import KDTree from the Nearest Neighbors sub-library
We already converted the spss file to a csv file, so we just have to import it using pandas read_csv method and display its first rows:
df = pd.read_csv("https://bitbucket.org/zeerobug/material/raw/12301e73580ce6b623a7a6fd601c08549eed1c45/datasets/votes_skills_anon.csv", index_col=0)df.head()
Each row corresponds to a vote where:
SUID is the Unique ID of the voter
univid: the unique ID of the institution
response: the voted skill
So for example that means the user #538 voted “Internationality” as an important skill for University #5c9e7a6834cda4f3677e662b.
Our next step consists in grouping by institution and skill (response). We do it with the excellent groupby method that generates a SeriesGroupBy object that we can use to count the number of similar pairs of (univid, response) in the dataset.
skills = df.groupby(["univid", "response"])["response"].count().reset_index(name='value')
We use reset_index, to get a DataFrame back from the series which is output by the count() function, and to create the “value” column that contains that count. Here is our table now:
Even if a lot more readable, this format is useless for our goal. It is difficult to distinguish between institutions as the number of rows is arbitrary (some skills may have not been voted), and lots of tools work best with row values instead of columns values.
Luckily, Pandas offers a very powerful tool which swaps rows and columns: pivot_table. Its arguments are self explanatory so I won’t enter into details.
univSkills = skills.pivot_table(values="value", columns="response", index=["univid"])univSkills.head()
Our data is almost ready for processing, but we still have an issue: To be comparable, each row must be in the same range and if we calculate the sum of values in a row, the total is far from being similar from one row to another:
univSkills.sum(axis=1).head()univid5c9e345f34cda4f3677e1047 69.05c9e349434cda4f3677e109f 51.05c9e34a834cda4f3677e10bd 40.05c9e34ae34cda4f3677e10c7 66.05c9e34d534cda4f3677e1107 70.0
This is because universities like Harvard have had a lot more votes that some remote and unknown university. It could be interesting to use that parameter in some other calculation but for the present problem, we need to get rid of that disparity. We comply by using percentages instead of absolute values.
So we have to sum each line and divide each value by that sum. This is done in a one-liner, and then we get rid of some Nan values to finish polishing the dataset.
univSkills = univSkills.div(univSkills.sum(axis=1), axis=0)univSkills.fillna(0, inplace=True )
Our dataset is now clean, ready, the values are in the same range, we can start playing with some more interesting processing.
So our algorithm has to detect amongst all the universities in our dataset which ones have the closest values to our 5 variables at the same time. We can immediately think of a brute force algorithm with nested loops that would compare value by value until it finds the 5 closest values for each variable but that would be far from optimal and not fast enough for our appplication!
The KD Tree algorithm is way more effective, it consists of a geometrical approach of the data, which, by subsequent divisions of a n-dimensional space, generates a tree that re-organises the data in a way that allows complex queries to run very fast. So let’s generate a tree with that method:
tree = KDTree(univSkills)
Our tree is ready to be queried. The first step consists in choosing a university to start with, for example the row of index 9 (univSkills[9:10]), we want a result set of the 5 closest universities (k=5) and the "query" function applied to our tree will return a tuple of 2 numpy arrays (dist, index), which will be respectively the distance and the index of the result, sorted from the closest to the furthest.
dist, ind = tree.query(univSkills[9:10], k=5)
And then we can display the values of our neighbors:
univSkills.iloc[ind.tolist()[0]]
We notice right away that the values are very close, we can confirm it with a new Radar chart:
You can try with different starting row, in most of the cases, the radar charts will remain very similar in shape.
You can also play with the other KDTree method variables that you will find in the documentation. Let me know if your experiments lead to better results.
I think there are a lot of other applications of this algorithm. It can be used in recommender systems, dating sites, and generally any processing that relies on proximity between multidimensional matrices
Relationship, for example: by determining a maximum distance and apply the query function to each row of the whole dataset, we could spot unseen relations and generate a GraphQL-like database.
Due to its speed, simplicity and effectivity, the KDTree can also be employed in some simple cases as a replacement for far more complicated libraries like TensorFlow or Pytorch. We’ll look into that in my next article.
Et voilà! I hope that this article will be of use to someone. You can find the complete notebook here. Don’t hesitate to leave a comment and send me an email, or message for any inquiry.
|
[
{
"code": null,
"e": 374,
"s": 47,
"text": "Most of data science is oriented towards the Train, Test, Predict paradigm. Who doesn’t want to guess the future! But there are some cases where other implementations are needed like unsupervised classification or discovering patterns in existing data. In other words, how to take advantage of the data which is already owned."
},
{
"code": null,
"e": 553,
"s": 374,
"text": "I think this aspect is a little bit disregarded and the literature about it is scarcer, compared to other branches of data science. Hence the reason for this little contribution."
},
{
"code": null,
"e": 1013,
"s": 553,
"text": "Here’s the story: A client of ours needed a way to find similar items (neighbours) for a given entity, according to a fixed number of parameters. Practically, the dataset is composed of votes from Human Resources Professionals who could attribute up to 5 skills to an arbitrary amount of World universities. It means that Edouard from HR could vote for MIT as a good institution for Digitalisation, Oxford for Internationality and La Sorbonne for Soft Skills."
},
{
"code": null,
"e": 1187,
"s": 1013,
"text": "I prepared the data, output a Spiderweb chart where the client could choose any Institution and compare it with the others, here is an example for three random universities:"
},
{
"code": null,
"e": 1375,
"s": 1187,
"text": "At that point, it seemed interesting to search for universities that would have been voted the same way, maybe to compare their actions and study what they were doing good and what wrong."
},
{
"code": null,
"e": 1567,
"s": 1375,
"text": "The data came in a spss file, with one row by vote, and according to our brief, the output had to be fast, because it was meant to be used as a Backend service, with near real time responses."
},
{
"code": null,
"e": 1838,
"s": 1567,
"text": "After some research, I thought that the best processing format for that would be a KD Tree for its multi-dimensional nature and its relatively easy and fast processing possibilities. I won’t explain in detail what KD Trees are but you can refer to the wikipedia article."
},
{
"code": null,
"e": 1927,
"s": 1838,
"text": "It is fully integrated into the sklearn module, and very easy to use as we’ll see below."
},
{
"code": null,
"e": 1958,
"s": 1927,
"text": "But first, let's do some prep!"
},
{
"code": null,
"e": 2096,
"s": 1958,
"text": "Our dataset, as property of the client, has been anonymised. The names of the universities have been taken away, but the values are real."
},
{
"code": null,
"e": 2136,
"s": 2096,
"text": "We’ll start by importing the libraries:"
},
{
"code": null,
"e": 2192,
"s": 2136,
"text": "import pandas as pdfrom sklearn.neighbors import KDTree"
},
{
"code": null,
"e": 2300,
"s": 2192,
"text": "Pandas will be used to import and process our data. It is very fast and useful for database-like processing"
},
{
"code": null,
"e": 2508,
"s": 2300,
"text": "sklearn stands for scikit-learn, one the most famous library for data analysis. It is used for classification, clustering, regression and more. We’ll just import KDTree from the Nearest Neighbors sub-library"
},
{
"code": null,
"e": 2644,
"s": 2508,
"text": "We already converted the spss file to a csv file, so we just have to import it using pandas read_csv method and display its first rows:"
},
{
"code": null,
"e": 2802,
"s": 2644,
"text": "df = pd.read_csv(\"https://bitbucket.org/zeerobug/material/raw/12301e73580ce6b623a7a6fd601c08549eed1c45/datasets/votes_skills_anon.csv\", index_col=0)df.head()"
},
{
"code": null,
"e": 2840,
"s": 2802,
"text": "Each row corresponds to a vote where:"
},
{
"code": null,
"e": 2875,
"s": 2840,
"text": "SUID is the Unique ID of the voter"
},
{
"code": null,
"e": 2916,
"s": 2875,
"text": "univid: the unique ID of the institution"
},
{
"code": null,
"e": 2942,
"s": 2916,
"text": "response: the voted skill"
},
{
"code": null,
"e": 3071,
"s": 2942,
"text": "So for example that means the user #538 voted “Internationality” as an important skill for University #5c9e7a6834cda4f3677e662b."
},
{
"code": null,
"e": 3315,
"s": 3071,
"text": "Our next step consists in grouping by institution and skill (response). We do it with the excellent groupby method that generates a SeriesGroupBy object that we can use to count the number of similar pairs of (univid, response) in the dataset."
},
{
"code": null,
"e": 3405,
"s": 3315,
"text": "skills = df.groupby([\"univid\", \"response\"])[\"response\"].count().reset_index(name='value')"
},
{
"code": null,
"e": 3588,
"s": 3405,
"text": "We use reset_index, to get a DataFrame back from the series which is output by the count() function, and to create the “value” column that contains that count. Here is our table now:"
},
{
"code": null,
"e": 3851,
"s": 3588,
"text": "Even if a lot more readable, this format is useless for our goal. It is difficult to distinguish between institutions as the number of rows is arbitrary (some skills may have not been voted), and lots of tools work best with row values instead of columns values."
},
{
"code": null,
"e": 4004,
"s": 3851,
"text": "Luckily, Pandas offers a very powerful tool which swaps rows and columns: pivot_table. Its arguments are self explanatory so I won’t enter into details."
},
{
"code": null,
"e": 4107,
"s": 4004,
"text": "univSkills = skills.pivot_table(values=\"value\", columns=\"response\", index=[\"univid\"])univSkills.head()"
},
{
"code": null,
"e": 4338,
"s": 4107,
"text": "Our data is almost ready for processing, but we still have an issue: To be comparable, each row must be in the same range and if we calculate the sum of values in a row, the total is far from being similar from one row to another:"
},
{
"code": null,
"e": 4534,
"s": 4338,
"text": "univSkills.sum(axis=1).head()univid5c9e345f34cda4f3677e1047 69.05c9e349434cda4f3677e109f 51.05c9e34a834cda4f3677e10bd 40.05c9e34ae34cda4f3677e10c7 66.05c9e34d534cda4f3677e1107 70.0"
},
{
"code": null,
"e": 4841,
"s": 4534,
"text": "This is because universities like Harvard have had a lot more votes that some remote and unknown university. It could be interesting to use that parameter in some other calculation but for the present problem, we need to get rid of that disparity. We comply by using percentages instead of absolute values."
},
{
"code": null,
"e": 5005,
"s": 4841,
"text": "So we have to sum each line and divide each value by that sum. This is done in a one-liner, and then we get rid of some Nan values to finish polishing the dataset."
},
{
"code": null,
"e": 5100,
"s": 5005,
"text": "univSkills = univSkills.div(univSkills.sum(axis=1), axis=0)univSkills.fillna(0, inplace=True )"
},
{
"code": null,
"e": 5227,
"s": 5100,
"text": "Our dataset is now clean, ready, the values are in the same range, we can start playing with some more interesting processing."
},
{
"code": null,
"e": 5609,
"s": 5227,
"text": "So our algorithm has to detect amongst all the universities in our dataset which ones have the closest values to our 5 variables at the same time. We can immediately think of a brute force algorithm with nested loops that would compare value by value until it finds the 5 closest values for each variable but that would be far from optimal and not fast enough for our appplication!"
},
{
"code": null,
"e": 5904,
"s": 5609,
"text": "The KD Tree algorithm is way more effective, it consists of a geometrical approach of the data, which, by subsequent divisions of a n-dimensional space, generates a tree that re-organises the data in a way that allows complex queries to run very fast. So let’s generate a tree with that method:"
},
{
"code": null,
"e": 5930,
"s": 5904,
"text": "tree = KDTree(univSkills)"
},
{
"code": null,
"e": 6343,
"s": 5930,
"text": "Our tree is ready to be queried. The first step consists in choosing a university to start with, for example the row of index 9 (univSkills[9:10]), we want a result set of the 5 closest universities (k=5) and the \"query\" function applied to our tree will return a tuple of 2 numpy arrays (dist, index), which will be respectively the distance and the index of the result, sorted from the closest to the furthest."
},
{
"code": null,
"e": 6389,
"s": 6343,
"text": "dist, ind = tree.query(univSkills[9:10], k=5)"
},
{
"code": null,
"e": 6442,
"s": 6389,
"text": "And then we can display the values of our neighbors:"
},
{
"code": null,
"e": 6475,
"s": 6442,
"text": "univSkills.iloc[ind.tolist()[0]]"
},
{
"code": null,
"e": 6570,
"s": 6475,
"text": "We notice right away that the values are very close, we can confirm it with a new Radar chart:"
},
{
"code": null,
"e": 6685,
"s": 6570,
"text": "You can try with different starting row, in most of the cases, the radar charts will remain very similar in shape."
},
{
"code": null,
"e": 6839,
"s": 6685,
"text": "You can also play with the other KDTree method variables that you will find in the documentation. Let me know if your experiments lead to better results."
},
{
"code": null,
"e": 7045,
"s": 6839,
"text": "I think there are a lot of other applications of this algorithm. It can be used in recommender systems, dating sites, and generally any processing that relies on proximity between multidimensional matrices"
},
{
"code": null,
"e": 7238,
"s": 7045,
"text": "Relationship, for example: by determining a maximum distance and apply the query function to each row of the whole dataset, we could spot unseen relations and generate a GraphQL-like database."
},
{
"code": null,
"e": 7458,
"s": 7238,
"text": "Due to its speed, simplicity and effectivity, the KDTree can also be employed in some simple cases as a replacement for far more complicated libraries like TensorFlow or Pytorch. We’ll look into that in my next article."
}
] |
Node.js console.timeStamp() Method - GeeksforGeeks
|
06 Sep, 2020
The console module provides a simple debugging console that is provided by web browsers which export two specific components:
A Console class that can be used to write to any Node.js stream. Example: console.log(), console.error(), etc.
A global console that can be used without importing console. Example: process.stdout, process.stderr, etc.
The console.timeStamp() (Added in v8.0.0) method is an inbuilt application programming interface of the ‘console‘ module which does not display anything unless used in the inspector. This method adds an event with the label ‘label‘ to the Timeline panel of the inspector.
Note: The global console methods are neither consistently synchronous nor consistently asynchronous.
Syntax:
console.timeStamp([label])
Parameters: This function accepts a single parameter as mentioned above and described below:
label <string>: It accepts the label name that is further to be used in the inspector.
Return Value: It doesn’t print anything in console instead, prints timestamp at the call in Inspector.
The Below examples illustrate the use of console.timeStamp() method in Node.js.
Example 1: Filename: index.js
// Node.js program to demonstrate the
// console.timeStamp() Method
// Starting newProfile() console profile
console.profile("Hello()");
// Printing timestamp
console.timeStamp("Hello()");
// Finishing profile
console.profileEnd("Hello()");
Run index.js file using the following command:
node index.js
Output in Console:
*Doesn’t print anything in Console...
Output in Inspector(edge):
Example 2: Filename: index.js
// Node.js program to demonstrate the
// console.timeStamp() Method
// Starting Hello() console profile
console.profile("Hello()");
// Printing timeStamp
console.timeStamp("Hello()");
// Performing some action
for(var i=0; i<1; i++) {
console.log("doing some task...");
}
// Finishing profile
console.profileEnd("Hello()");
// Printing timeStamp again
console.timeStamp("Hello()");
Run index.js file using the following command:
node index.js
Output in Console:
Doing some task...
Output in Inspector (edge):
Reference: https://nodejs.org/api/console.html#console_console_timestamp_label
Node.js-console-module
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Mongoose find() Function
Mongoose Populate() Method
Node.js Export Module
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26449,
"s": 26418,
"text": " \n06 Sep, 2020\n"
},
{
"code": null,
"e": 26575,
"s": 26449,
"text": "The console module provides a simple debugging console that is provided by web browsers which export two specific components:"
},
{
"code": null,
"e": 26687,
"s": 26575,
"text": "A Console class that can be used to write to any Node.js stream. Example: console.log(), console.error(), etc."
},
{
"code": null,
"e": 26794,
"s": 26687,
"text": "A global console that can be used without importing console. Example: process.stdout, process.stderr, etc."
},
{
"code": null,
"e": 27066,
"s": 26794,
"text": "The console.timeStamp() (Added in v8.0.0) method is an inbuilt application programming interface of the ‘console‘ module which does not display anything unless used in the inspector. This method adds an event with the label ‘label‘ to the Timeline panel of the inspector."
},
{
"code": null,
"e": 27167,
"s": 27066,
"text": "Note: The global console methods are neither consistently synchronous nor consistently asynchronous."
},
{
"code": null,
"e": 27175,
"s": 27167,
"text": "Syntax:"
},
{
"code": null,
"e": 27202,
"s": 27175,
"text": "console.timeStamp([label])"
},
{
"code": null,
"e": 27295,
"s": 27202,
"text": "Parameters: This function accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 27384,
"s": 27295,
"text": "\nlabel <string>: It accepts the label name that is further to be used in the inspector.\n"
},
{
"code": null,
"e": 27487,
"s": 27384,
"text": "Return Value: It doesn’t print anything in console instead, prints timestamp at the call in Inspector."
},
{
"code": null,
"e": 27567,
"s": 27487,
"text": "The Below examples illustrate the use of console.timeStamp() method in Node.js."
},
{
"code": null,
"e": 27599,
"s": 27567,
"text": "Example 1: Filename: index.js"
},
{
"code": "\n\n\n\n\n\n\n// Node.js program to demonstrate the \n// console.timeStamp() Method \n \n// Starting newProfile() console profile \nconsole.profile(\"Hello()\"); \n \n// Printing timestamp \nconsole.timeStamp(\"Hello()\"); \n \n// Finishing profile \nconsole.profileEnd(\"Hello()\"); \n\n\n\n\n\n",
"e": 27881,
"s": 27609,
"text": null
},
{
"code": null,
"e": 27928,
"s": 27881,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 27942,
"s": 27928,
"text": "node index.js"
},
{
"code": null,
"e": 27961,
"s": 27942,
"text": "Output in Console:"
},
{
"code": null,
"e": 28001,
"s": 27961,
"text": "\n*Doesn’t print anything in Console...\n"
},
{
"code": null,
"e": 28028,
"s": 28001,
"text": "Output in Inspector(edge):"
},
{
"code": null,
"e": 28060,
"s": 28028,
"text": "Example 2: Filename: index.js"
},
{
"code": "\n\n\n\n\n\n\n// Node.js program to demonstrate the \n// console.timeStamp() Method \n \n// Starting Hello() console profile \nconsole.profile(\"Hello()\"); \n \n// Printing timeStamp \nconsole.timeStamp(\"Hello()\"); \n \n// Performing some action \nfor(var i=0; i<1; i++) { \n console.log(\"doing some task...\"); \n} \n \n// Finishing profile \nconsole.profileEnd(\"Hello()\"); \n \n// Printing timeStamp again \nconsole.timeStamp(\"Hello()\"); \n\n\n\n\n\n",
"e": 28497,
"s": 28070,
"text": null
},
{
"code": null,
"e": 28544,
"s": 28497,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 28558,
"s": 28544,
"text": "node index.js"
},
{
"code": null,
"e": 28577,
"s": 28558,
"text": "Output in Console:"
},
{
"code": null,
"e": 28598,
"s": 28577,
"text": "\nDoing some task...\n"
},
{
"code": null,
"e": 28626,
"s": 28598,
"text": "Output in Inspector (edge):"
},
{
"code": null,
"e": 28705,
"s": 28626,
"text": "Reference: https://nodejs.org/api/console.html#console_console_timestamp_label"
},
{
"code": null,
"e": 28730,
"s": 28705,
"text": "\nNode.js-console-module\n"
},
{
"code": null,
"e": 28748,
"s": 28730,
"text": "\nNode.js-Methods\n"
},
{
"code": null,
"e": 28758,
"s": 28748,
"text": "\nNode.js\n"
},
{
"code": null,
"e": 28777,
"s": 28758,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 28982,
"s": 28777,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 29052,
"s": 28982,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 29091,
"s": 29052,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 29116,
"s": 29091,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 29143,
"s": 29116,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 29165,
"s": 29143,
"text": "Node.js Export Module"
},
{
"code": null,
"e": 29205,
"s": 29165,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29250,
"s": 29205,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29293,
"s": 29250,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29343,
"s": 29293,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
C program to calculate range of values and an average cost of a personal system.
|
A personal system is sold at different costs by the vendors.
Let’s take the list of costs (in hundreds) quoted by some vendors −
25.00, 30.50, 15.00, 28.25, 58.15,
37.00, 16.65, 42.00 68.45, 53.50
Calculate the average cost and range of values.
The difference between the highest and the lowest values in the series is called range Hence, Range = highest value - lowest value.
Now, find the highest and the lowest values in the series.
Following is the C program to calculate the range of values and average cost of a personal system −
Live Demo
#include<stdio.h>
main(){
int count;
float value, high, low, sum, average, range;
sum = 0;
count = 0;
printf("enter no's in line and at end press any negative number\n");
input:
scanf("%f", &value);
if (value < 0)
goto output;
count = count + 1;
if (count == 1)
high = low = value;
else if (value > high)
high = value;
else if (value < low)
low = value;
sum = sum + value;
goto input;
output:
average = sum/count;
range = high - low;
printf("\n\n");
printf("Total values : %d\n", count);
printf("Highest-value: %f\nLowest-value : %f\n", high, low);
printf("Range : %f\nAverage : %f\n", range, average);
}
When the above program is executed, it produces the following output −
Enter numbers in line and at end press any negative number
22.4 56.8 12.3 48.6 31.4 19.0 -1
Total values: 6
Highest-value: 56.799999
Lowest-value: 12.300000
Range: 44.500000
Average: 31.750000
|
[
{
"code": null,
"e": 1123,
"s": 1062,
"text": "A personal system is sold at different costs by the vendors."
},
{
"code": null,
"e": 1191,
"s": 1123,
"text": "Let’s take the list of costs (in hundreds) quoted by some vendors −"
},
{
"code": null,
"e": 1226,
"s": 1191,
"text": "25.00, 30.50, 15.00, 28.25, 58.15,"
},
{
"code": null,
"e": 1259,
"s": 1226,
"text": "37.00, 16.65, 42.00 68.45, 53.50"
},
{
"code": null,
"e": 1307,
"s": 1259,
"text": "Calculate the average cost and range of values."
},
{
"code": null,
"e": 1439,
"s": 1307,
"text": "The difference between the highest and the lowest values in the series is called range Hence, Range = highest value - lowest value."
},
{
"code": null,
"e": 1498,
"s": 1439,
"text": "Now, find the highest and the lowest values in the series."
},
{
"code": null,
"e": 1598,
"s": 1498,
"text": "Following is the C program to calculate the range of values and average cost of a personal system −"
},
{
"code": null,
"e": 1609,
"s": 1598,
"text": " Live Demo"
},
{
"code": null,
"e": 2307,
"s": 1609,
"text": "#include<stdio.h>\nmain(){\n int count;\n float value, high, low, sum, average, range;\n sum = 0;\n count = 0;\n printf(\"enter no's in line and at end press any negative number\\n\");\n input:\n scanf(\"%f\", &value);\n if (value < 0)\n goto output;\n count = count + 1;\n if (count == 1)\n high = low = value;\n else if (value > high)\n high = value;\n else if (value < low)\n low = value;\n sum = sum + value;\n goto input;\n output:\n average = sum/count;\n range = high - low;\n printf(\"\\n\\n\");\n printf(\"Total values : %d\\n\", count);\n printf(\"Highest-value: %f\\nLowest-value : %f\\n\", high, low);\n printf(\"Range : %f\\nAverage : %f\\n\", range, average);\n}"
},
{
"code": null,
"e": 2378,
"s": 2307,
"text": "When the above program is executed, it produces the following output −"
},
{
"code": null,
"e": 2571,
"s": 2378,
"text": "Enter numbers in line and at end press any negative number\n22.4 56.8 12.3 48.6 31.4 19.0 -1\nTotal values: 6\nHighest-value: 56.799999\nLowest-value: 12.300000\nRange: 44.500000\nAverage: 31.750000"
}
] |
accumulate() and partial_sum() in C++ STL : Numeric header - GeeksforGeeks
|
04 Jan, 2022
The numeric header is part of the numeric library in C++ STL. This library consists of basic mathematical functions and types, as well as optimized numeric arrays and support for random number generation. Some of the functions in the numeric header:
iota
accumulate
reduce
inner_product
partial_sum etc.
This article explains accumulate() and partial_sum() in the numeric header which can be used during competitive programming to save time and effort.
1) accumulate(): This function returns the sum of all the values lying in a range between [first, last) with the variable sum. We usually find out the sum of elements in a particular range or a complete array using a linear operation which requires adding all the elements in the range one by one and storing it into some variable after each iteration.
Syntax:
accumulate(first, last, sum);
or
accumulate(first, last, sum, myfun);
Parameters:
first, last: first and last elements of range whose elements are to be added
sum: initial value of the sum
myfun: a function for performing any specific task.
For example, we can find the product of elements between first and last.
CPP
// C++ program to demonstrate working of accumulate()#include <iostream>#include <numeric>using namespace std; // User defined functionint myfun(int x, int y){ // for this example we have taken product // of adjacent numbers return x * y;} int main(){ // Initialize sum = 1 int sum = 1; int a[] = { 5, 10, 15 }; // Simple default accumulate function cout << "\nResult using accumulate: "; cout << accumulate(a, a + 3, sum); // Using accumulate function with // defined function cout << "\nResult using accumulate with" "user-defined function: "; cout << accumulate(a, a + 3, sum, myfun); // Using accumulate function with // pre-defined function cout << "\nResult using accumulate with " "pre-defined function: "; cout << accumulate(a, a + 3, sum, std::minus<int>()); return 0;}
Result using accumulate: 31
Result using accumulate withuser-defined function: 750
Result using accumulate with pre-defined function: -29
See this Example Problem for more reference: Sum of all elements between k1’th and k2’th smallest elements
2) partial_sum( ): This function assigns a partial sum of the corresponding elements of an array to every position of the second array. It returns the partial sum of all the set of values lying between [first, last) and stores it in another array b.
For example, if x represents an element in [first, last) and y represents an element in the result, the ys can be calculated as:
y0 = x0
y1 = x0 + x1
y2 = x0 + x1 + x2
y3 = x0 + x1 + x2 + x3
y4 = x0 + x1 + x2 + x3 + x4
Syntax:
partial_sum(first, last, b);
or
partial_sum(first, last, b, myfun);
Parameters:
first, last: first and last element of range whose elements are to be added
b: index of array where corresponding partial sum will be stored
myfun: a user-defined function for performing any specific task
CPP
// C++ program to demonstrate working of partial_sum()#include <iostream>#include <numeric>using namespace std; // user defined functionint myfun(int x, int y){ // the sum of element is twice of its // adjacent element return x + 2 * y;} int main(){ int a[] = { 1, 2, 3, 4, 5 }; int b[5]; // Default function partial_sum(a, a + 5, b); cout << "Partial Sum - Using Default function: "; for (int i = 0; i < 5; i++) cout << b[i] << ' '; cout << '\n'; // Using user defined function partial_sum(a, a + 5, b, myfun); cout << "Partial sum - Using user defined function: "; for (int i = 0; i < 5; i++) cout << b[i] << ' '; cout << '\n'; return 0;}
Partial Sum - Using Default function: 1 3 6 10 15
Partial sum - Using user defined function: 1 5 11 19 29
This article is contributed by Abhinav Tiwari. 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.
anshikajain26
CPP-Library
cpp-numerics-library
STL
C Language
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Function Pointer in C
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Operator Overloading in C++
|
[
{
"code": null,
"e": 24572,
"s": 24544,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 24822,
"s": 24572,
"text": "The numeric header is part of the numeric library in C++ STL. This library consists of basic mathematical functions and types, as well as optimized numeric arrays and support for random number generation. Some of the functions in the numeric header:"
},
{
"code": null,
"e": 24827,
"s": 24822,
"text": "iota"
},
{
"code": null,
"e": 24838,
"s": 24827,
"text": "accumulate"
},
{
"code": null,
"e": 24845,
"s": 24838,
"text": "reduce"
},
{
"code": null,
"e": 24859,
"s": 24845,
"text": "inner_product"
},
{
"code": null,
"e": 24876,
"s": 24859,
"text": "partial_sum etc."
},
{
"code": null,
"e": 25026,
"s": 24876,
"text": "This article explains accumulate() and partial_sum() in the numeric header which can be used during competitive programming to save time and effort. "
},
{
"code": null,
"e": 25379,
"s": 25026,
"text": "1) accumulate(): This function returns the sum of all the values lying in a range between [first, last) with the variable sum. We usually find out the sum of elements in a particular range or a complete array using a linear operation which requires adding all the elements in the range one by one and storing it into some variable after each iteration."
},
{
"code": null,
"e": 25387,
"s": 25379,
"text": "Syntax:"
},
{
"code": null,
"e": 25417,
"s": 25387,
"text": "accumulate(first, last, sum);"
},
{
"code": null,
"e": 25420,
"s": 25417,
"text": "or"
},
{
"code": null,
"e": 25458,
"s": 25420,
"text": "accumulate(first, last, sum, myfun); "
},
{
"code": null,
"e": 25470,
"s": 25458,
"text": "Parameters:"
},
{
"code": null,
"e": 25547,
"s": 25470,
"text": "first, last: first and last elements of range whose elements are to be added"
},
{
"code": null,
"e": 25578,
"s": 25547,
"text": "sum: initial value of the sum"
},
{
"code": null,
"e": 25631,
"s": 25578,
"text": "myfun: a function for performing any specific task. "
},
{
"code": null,
"e": 25704,
"s": 25631,
"text": "For example, we can find the product of elements between first and last."
},
{
"code": null,
"e": 25708,
"s": 25704,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate working of accumulate()#include <iostream>#include <numeric>using namespace std; // User defined functionint myfun(int x, int y){ // for this example we have taken product // of adjacent numbers return x * y;} int main(){ // Initialize sum = 1 int sum = 1; int a[] = { 5, 10, 15 }; // Simple default accumulate function cout << \"\\nResult using accumulate: \"; cout << accumulate(a, a + 3, sum); // Using accumulate function with // defined function cout << \"\\nResult using accumulate with\" \"user-defined function: \"; cout << accumulate(a, a + 3, sum, myfun); // Using accumulate function with // pre-defined function cout << \"\\nResult using accumulate with \" \"pre-defined function: \"; cout << accumulate(a, a + 3, sum, std::minus<int>()); return 0;}",
"e": 26567,
"s": 25708,
"text": null
},
{
"code": null,
"e": 26705,
"s": 26567,
"text": "Result using accumulate: 31\nResult using accumulate withuser-defined function: 750\nResult using accumulate with pre-defined function: -29"
},
{
"code": null,
"e": 26812,
"s": 26705,
"text": "See this Example Problem for more reference: Sum of all elements between k1’th and k2’th smallest elements"
},
{
"code": null,
"e": 27063,
"s": 26812,
"text": "2) partial_sum( ): This function assigns a partial sum of the corresponding elements of an array to every position of the second array. It returns the partial sum of all the set of values lying between [first, last) and stores it in another array b. "
},
{
"code": null,
"e": 27192,
"s": 27063,
"text": "For example, if x represents an element in [first, last) and y represents an element in the result, the ys can be calculated as:"
},
{
"code": null,
"e": 27286,
"s": 27192,
"text": "y0 = x0 \ny1 = x0 + x1 \ny2 = x0 + x1 + x2 \ny3 = x0 + x1 + x2 + x3 \ny4 = x0 + x1 + x2 + x3 + x4"
},
{
"code": null,
"e": 27294,
"s": 27286,
"text": "Syntax:"
},
{
"code": null,
"e": 27323,
"s": 27294,
"text": "partial_sum(first, last, b);"
},
{
"code": null,
"e": 27326,
"s": 27323,
"text": "or"
},
{
"code": null,
"e": 27362,
"s": 27326,
"text": "partial_sum(first, last, b, myfun);"
},
{
"code": null,
"e": 27374,
"s": 27362,
"text": "Parameters:"
},
{
"code": null,
"e": 27450,
"s": 27374,
"text": "first, last: first and last element of range whose elements are to be added"
},
{
"code": null,
"e": 27516,
"s": 27450,
"text": "b: index of array where corresponding partial sum will be stored"
},
{
"code": null,
"e": 27580,
"s": 27516,
"text": "myfun: a user-defined function for performing any specific task"
},
{
"code": null,
"e": 27584,
"s": 27580,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate working of partial_sum()#include <iostream>#include <numeric>using namespace std; // user defined functionint myfun(int x, int y){ // the sum of element is twice of its // adjacent element return x + 2 * y;} int main(){ int a[] = { 1, 2, 3, 4, 5 }; int b[5]; // Default function partial_sum(a, a + 5, b); cout << \"Partial Sum - Using Default function: \"; for (int i = 0; i < 5; i++) cout << b[i] << ' '; cout << '\\n'; // Using user defined function partial_sum(a, a + 5, b, myfun); cout << \"Partial sum - Using user defined function: \"; for (int i = 0; i < 5; i++) cout << b[i] << ' '; cout << '\\n'; return 0;}",
"e": 28292,
"s": 27584,
"text": null
},
{
"code": null,
"e": 28400,
"s": 28292,
"text": "Partial Sum - Using Default function: 1 3 6 10 15 \nPartial sum - Using user defined function: 1 5 11 19 29 "
},
{
"code": null,
"e": 28823,
"s": 28400,
"text": "This article is contributed by Abhinav Tiwari. 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": 28837,
"s": 28823,
"text": "anshikajain26"
},
{
"code": null,
"e": 28849,
"s": 28837,
"text": "CPP-Library"
},
{
"code": null,
"e": 28870,
"s": 28849,
"text": "cpp-numerics-library"
},
{
"code": null,
"e": 28874,
"s": 28870,
"text": "STL"
},
{
"code": null,
"e": 28885,
"s": 28874,
"text": "C Language"
},
{
"code": null,
"e": 28889,
"s": 28885,
"text": "C++"
},
{
"code": null,
"e": 28893,
"s": 28889,
"text": "STL"
},
{
"code": null,
"e": 28897,
"s": 28893,
"text": "CPP"
},
{
"code": null,
"e": 28995,
"s": 28897,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29023,
"s": 28995,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 29069,
"s": 29023,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 29081,
"s": 29069,
"text": "fork() in C"
},
{
"code": null,
"e": 29113,
"s": 29081,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 29135,
"s": 29113,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 29181,
"s": 29135,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29200,
"s": 29181,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29243,
"s": 29200,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29267,
"s": 29243,
"text": "C++ Classes and Objects"
}
] |
Data Transformation in PySpark. A step by step walkthrough of certain... | by Neel Iyer | Towards Data Science
|
Data is now growing faster than processing speeds. One of the many solutions to this problem is to parallelise our computing on large clusters. Enter PySpark.
However, PySpark requires you to think about data differently.
Instead of looking at a dataset row-wise. PySpark encourages you to look at it column-wise. This was a difficult transition for me at first. I’ll tell you the main tricks I learned so you don’t have to waste your time searching for the answers.
I’ll be using the Hazardous Air Pollutants dataset from Kaggle.
This Dataset is 8,097,069 rows.
df = spark.read.csv(‘epa_hap_daily_summary.csv’,inferSchema=True, header =True)df.show()
The first transformation we’ll do is a conditional if statement transformation. This is as follows: if a cell in our dataset contains a particular string we want to change the cell in another column.
Basically we want to go from this:
To this:
If local site name contains the word police then we set the is_police column to 1. Otherwise we set it to 0.
This kind of condition if statement is fairly easy to do in Pandas. We would use pd.np.where or df.apply. In the worst case scenario, we could even iterate through the rows. We can’t do any of that in Pyspark.
In Pyspark we can use the F.when statement or a UDF. This allows us to achieve the same result as above.
from pyspark.sql import functions as Fdf = df.withColumn('is_police',\ F.when(\ F.lower(\ F.col('local_site_name')).contains('police'),\ F.lit(1)).\ otherwise(F.lit(0)))df.select('is_police', 'local_site_name').show()
Now suppose we want to extend what we’ve done above. This time if a cell contains any one of 3 strings then we change the corresponding cell in another column.
If any one of strings: 'Police', 'Fort' , 'Lab' are in the local_site_name column then we'll mark the corresponding cell as High Rating.
Therlike function combined with the F.when function we saw earlier allows to us to do just that.
parameter_list = ['Police', 'Fort' , 'Lab']df = df.withColumn('rating',\ F.when(\ F.col('local_site_name').rlike('|'.join(parameter_list)),\ F.lit('High Rating')).\ otherwise(F.lit('Low Rating')))df.select('rating', 'local_site_name').show()
F.when is actually useful for a lot of different things. In fact you can even do a chained F.when:
df = df.withColumn('rating', F.when(F.lower(F.col('local_site_name')).contains('police'), F.lit('High Rating'))\ .when(F.lower(F.col('local_site_name')).contains('fort'), F.lit('High Rating'))\ .when(F.lower(F.col('local_site_name')).contains('lab'), F.lit('High Rating'))\ .otherwise(F.lit('Low Rating')))df.select('rating', 'local_site_name').show(
This achieves exactly the same thing we saw in the previous example. However, it’s more code to write and it’s more code to maintain.
I prefer the rlike method discussed above.
Whitespace can be really annoying. It really affects string matches and can cause unnecessary bugs in queries.
In my opinion it’s a good idea to remove whitespace as soon as possible.
F.trimallows us to do just that. It will remove all the whitespace for every row in the specified column.
df = df.withColumn('address', F.trim(F.col('address')))df.show()
Suppose we want to remove null rows on only one column. If we encounter NaN values in the pollutant_standard column drop that entire row.
This can accomplished fairly simply.
filtered_data = df.filter((F.col('pollutant_standard').isNotNull())) # filter out nullsfiltered_data.count()
The conditional OR parameter allows to remove rows where we event_type or site_num are NaN.
This is referred to as `|`.
filtered_data = df.filter((F.col('event_type').isNotNull()) | (F.col('site_num').isNotNull())) # filter out nullsfiltered_data.count()
df.na.drop allows us to remove rows where all our columns are NaN.
filtered_data = df.na.drop(how = 'all') # filter out nullsfiltered_data.show()
PySpark is still fairly a new language. Probably as a result of that there isn’t a lot of help on the internet. With something like Pandas or R there’s a wealth of information out there. With Spark that’s not the case at all.
So I hope these bits of code help someone out there. They certainly would’ve helped me and saved me a lot of time. The transformations I went through might seem small or trivial but there aren’t a lot of people talking about this stuff when it pertains to Spark. I hope this helps you in some way.
If I’ve made a mistake or you’d like reach out to me feel free to contact me on twitter.
Originally published at https://spiyer99.github.io on September 6, 2020.
|
[
{
"code": null,
"e": 330,
"s": 171,
"text": "Data is now growing faster than processing speeds. One of the many solutions to this problem is to parallelise our computing on large clusters. Enter PySpark."
},
{
"code": null,
"e": 393,
"s": 330,
"text": "However, PySpark requires you to think about data differently."
},
{
"code": null,
"e": 638,
"s": 393,
"text": "Instead of looking at a dataset row-wise. PySpark encourages you to look at it column-wise. This was a difficult transition for me at first. I’ll tell you the main tricks I learned so you don’t have to waste your time searching for the answers."
},
{
"code": null,
"e": 702,
"s": 638,
"text": "I’ll be using the Hazardous Air Pollutants dataset from Kaggle."
},
{
"code": null,
"e": 734,
"s": 702,
"text": "This Dataset is 8,097,069 rows."
},
{
"code": null,
"e": 823,
"s": 734,
"text": "df = spark.read.csv(‘epa_hap_daily_summary.csv’,inferSchema=True, header =True)df.show()"
},
{
"code": null,
"e": 1023,
"s": 823,
"text": "The first transformation we’ll do is a conditional if statement transformation. This is as follows: if a cell in our dataset contains a particular string we want to change the cell in another column."
},
{
"code": null,
"e": 1058,
"s": 1023,
"text": "Basically we want to go from this:"
},
{
"code": null,
"e": 1067,
"s": 1058,
"text": "To this:"
},
{
"code": null,
"e": 1176,
"s": 1067,
"text": "If local site name contains the word police then we set the is_police column to 1. Otherwise we set it to 0."
},
{
"code": null,
"e": 1386,
"s": 1176,
"text": "This kind of condition if statement is fairly easy to do in Pandas. We would use pd.np.where or df.apply. In the worst case scenario, we could even iterate through the rows. We can’t do any of that in Pyspark."
},
{
"code": null,
"e": 1491,
"s": 1386,
"text": "In Pyspark we can use the F.when statement or a UDF. This allows us to achieve the same result as above."
},
{
"code": null,
"e": 1744,
"s": 1491,
"text": "from pyspark.sql import functions as Fdf = df.withColumn('is_police',\\ F.when(\\ F.lower(\\ F.col('local_site_name')).contains('police'),\\ F.lit(1)).\\ otherwise(F.lit(0)))df.select('is_police', 'local_site_name').show()"
},
{
"code": null,
"e": 1904,
"s": 1744,
"text": "Now suppose we want to extend what we’ve done above. This time if a cell contains any one of 3 strings then we change the corresponding cell in another column."
},
{
"code": null,
"e": 2041,
"s": 1904,
"text": "If any one of strings: 'Police', 'Fort' , 'Lab' are in the local_site_name column then we'll mark the corresponding cell as High Rating."
},
{
"code": null,
"e": 2138,
"s": 2041,
"text": "Therlike function combined with the F.when function we saw earlier allows to us to do just that."
},
{
"code": null,
"e": 2396,
"s": 2138,
"text": "parameter_list = ['Police', 'Fort' , 'Lab']df = df.withColumn('rating',\\ F.when(\\ F.col('local_site_name').rlike('|'.join(parameter_list)),\\ F.lit('High Rating')).\\ otherwise(F.lit('Low Rating')))df.select('rating', 'local_site_name').show()"
},
{
"code": null,
"e": 2495,
"s": 2396,
"text": "F.when is actually useful for a lot of different things. In fact you can even do a chained F.when:"
},
{
"code": null,
"e": 2933,
"s": 2495,
"text": "df = df.withColumn('rating', F.when(F.lower(F.col('local_site_name')).contains('police'), F.lit('High Rating'))\\ .when(F.lower(F.col('local_site_name')).contains('fort'), F.lit('High Rating'))\\ .when(F.lower(F.col('local_site_name')).contains('lab'), F.lit('High Rating'))\\ .otherwise(F.lit('Low Rating')))df.select('rating', 'local_site_name').show("
},
{
"code": null,
"e": 3067,
"s": 2933,
"text": "This achieves exactly the same thing we saw in the previous example. However, it’s more code to write and it’s more code to maintain."
},
{
"code": null,
"e": 3110,
"s": 3067,
"text": "I prefer the rlike method discussed above."
},
{
"code": null,
"e": 3221,
"s": 3110,
"text": "Whitespace can be really annoying. It really affects string matches and can cause unnecessary bugs in queries."
},
{
"code": null,
"e": 3294,
"s": 3221,
"text": "In my opinion it’s a good idea to remove whitespace as soon as possible."
},
{
"code": null,
"e": 3400,
"s": 3294,
"text": "F.trimallows us to do just that. It will remove all the whitespace for every row in the specified column."
},
{
"code": null,
"e": 3465,
"s": 3400,
"text": "df = df.withColumn('address', F.trim(F.col('address')))df.show()"
},
{
"code": null,
"e": 3603,
"s": 3465,
"text": "Suppose we want to remove null rows on only one column. If we encounter NaN values in the pollutant_standard column drop that entire row."
},
{
"code": null,
"e": 3640,
"s": 3603,
"text": "This can accomplished fairly simply."
},
{
"code": null,
"e": 3749,
"s": 3640,
"text": "filtered_data = df.filter((F.col('pollutant_standard').isNotNull())) # filter out nullsfiltered_data.count()"
},
{
"code": null,
"e": 3841,
"s": 3749,
"text": "The conditional OR parameter allows to remove rows where we event_type or site_num are NaN."
},
{
"code": null,
"e": 3869,
"s": 3841,
"text": "This is referred to as `|`."
},
{
"code": null,
"e": 4004,
"s": 3869,
"text": "filtered_data = df.filter((F.col('event_type').isNotNull()) | (F.col('site_num').isNotNull())) # filter out nullsfiltered_data.count()"
},
{
"code": null,
"e": 4071,
"s": 4004,
"text": "df.na.drop allows us to remove rows where all our columns are NaN."
},
{
"code": null,
"e": 4150,
"s": 4071,
"text": "filtered_data = df.na.drop(how = 'all') # filter out nullsfiltered_data.show()"
},
{
"code": null,
"e": 4376,
"s": 4150,
"text": "PySpark is still fairly a new language. Probably as a result of that there isn’t a lot of help on the internet. With something like Pandas or R there’s a wealth of information out there. With Spark that’s not the case at all."
},
{
"code": null,
"e": 4674,
"s": 4376,
"text": "So I hope these bits of code help someone out there. They certainly would’ve helped me and saved me a lot of time. The transformations I went through might seem small or trivial but there aren’t a lot of people talking about this stuff when it pertains to Spark. I hope this helps you in some way."
},
{
"code": null,
"e": 4763,
"s": 4674,
"text": "If I’ve made a mistake or you’d like reach out to me feel free to contact me on twitter."
}
] |
brk() - Unix, Linux System Call
|
Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
brk, sbrk - change data segment size
#include <unistd.h>
int brk(void *end_data_segment);
void *sbrk(intptr_t increment);
#include <unistd.h>
int brk(void *end_data_segment);
void *sbrk(intptr_t increment);
brk() sets the end of the data segment to the value specified by
end_data_segment, when that value is reasonable, the system does have enough memory
and the process does not exceed its max data size (see
setrlimit(2)).
sbrk() increments the program’s data space by
increment bytes.
sbrk() isn’t a system call, it is just a C library wrapper.
Calling sbrk() with an increment of 0 can be used to find the current
location of the program break.
On success,
brk() returns zero, and
sbrk() returns a pointer to the start of the new area. On error, -1 is returned,
and
errno is set to
ENOMEM.
brk() and
sbrk() are not defined in the C Standard and are deliberately excluded from the
POSIX.1 standard (see paragraphs B.1.1.1.3 and B.8.3.3).
Various systems use various types for the parameter of sbrk(). Common are int, ssize_t, ptrdiff_t, intptr_t.
execve (2)
execve (2)
getrlimit (2)
getrlimit (2)
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1466,
"s": 1454,
"text": "Unix - Home"
},
{
"code": null,
"e": 1489,
"s": 1466,
"text": "Unix - Getting Started"
},
{
"code": null,
"e": 1512,
"s": 1489,
"text": "Unix - File Management"
},
{
"code": null,
"e": 1531,
"s": 1512,
"text": "Unix - Directories"
},
{
"code": null,
"e": 1554,
"s": 1531,
"text": "Unix - File Permission"
},
{
"code": null,
"e": 1573,
"s": 1554,
"text": "Unix - Environment"
},
{
"code": null,
"e": 1596,
"s": 1573,
"text": "Unix - Basic Utilities"
},
{
"code": null,
"e": 1619,
"s": 1596,
"text": "Unix - Pipes & Filters"
},
{
"code": null,
"e": 1636,
"s": 1619,
"text": "Unix - Processes"
},
{
"code": null,
"e": 1657,
"s": 1636,
"text": "Unix - Communication"
},
{
"code": null,
"e": 1678,
"s": 1657,
"text": "Unix - The vi Editor"
},
{
"code": null,
"e": 1700,
"s": 1678,
"text": "Unix - What is Shell?"
},
{
"code": null,
"e": 1723,
"s": 1700,
"text": "Unix - Using Variables"
},
{
"code": null,
"e": 1748,
"s": 1723,
"text": "Unix - Special Variables"
},
{
"code": null,
"e": 1768,
"s": 1748,
"text": "Unix - Using Arrays"
},
{
"code": null,
"e": 1791,
"s": 1768,
"text": "Unix - Basic Operators"
},
{
"code": null,
"e": 1814,
"s": 1791,
"text": "Unix - Decision Making"
},
{
"code": null,
"e": 1833,
"s": 1814,
"text": "Unix - Shell Loops"
},
{
"code": null,
"e": 1853,
"s": 1833,
"text": "Unix - Loop Control"
},
{
"code": null,
"e": 1880,
"s": 1853,
"text": "Unix - Shell Substitutions"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "Unix - Quoting Mechanisms"
},
{
"code": null,
"e": 1929,
"s": 1906,
"text": "Unix - IO Redirections"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Unix - Shell Functions"
},
{
"code": null,
"e": 1972,
"s": 1952,
"text": "Unix - Manpage Help"
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Unix - Regular Expressions"
},
{
"code": null,
"e": 2025,
"s": 1999,
"text": "Unix - File System Basics"
},
{
"code": null,
"e": 2052,
"s": 2025,
"text": "Unix - User Administration"
},
{
"code": null,
"e": 2078,
"s": 2052,
"text": "Unix - System Performance"
},
{
"code": null,
"e": 2100,
"s": 2078,
"text": "Unix - System Logging"
},
{
"code": null,
"e": 2125,
"s": 2100,
"text": "Unix - Signals and Traps"
},
{
"code": null,
"e": 2148,
"s": 2125,
"text": "Unix - Useful Commands"
},
{
"code": null,
"e": 2167,
"s": 2148,
"text": "Unix - Quick Guide"
},
{
"code": null,
"e": 2192,
"s": 2167,
"text": "Unix - Builtin Functions"
},
{
"code": null,
"e": 2212,
"s": 2192,
"text": "Unix - System Calls"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "Unix - Commands List"
},
{
"code": null,
"e": 2255,
"s": 2233,
"text": "Unix Useful Resources"
},
{
"code": null,
"e": 2273,
"s": 2255,
"text": "Computer Glossary"
},
{
"code": null,
"e": 2284,
"s": 2273,
"text": "Who is Who"
},
{
"code": null,
"e": 2319,
"s": 2284,
"text": "Copyright © 2014 by tutorialspoint"
},
{
"code": null,
"e": 2356,
"s": 2319,
"text": "brk, sbrk - change data segment size"
},
{
"code": null,
"e": 2444,
"s": 2356,
"text": "\n#include <unistd.h>\nint brk(void *end_data_segment);\nvoid *sbrk(intptr_t increment); \n"
},
{
"code": null,
"e": 2531,
"s": 2444,
"text": "\n#include <unistd.h>\nint brk(void *end_data_segment);\nvoid *sbrk(intptr_t increment); "
},
{
"code": null,
"e": 2750,
"s": 2531,
"text": "brk() sets the end of the data segment to the value specified by\nend_data_segment, when that value is reasonable, the system does have enough memory\nand the process does not exceed its max data size (see\nsetrlimit(2))."
},
{
"code": null,
"e": 2974,
"s": 2750,
"text": "sbrk() increments the program’s data space by\nincrement bytes.\nsbrk() isn’t a system call, it is just a C library wrapper.\nCalling sbrk() with an increment of 0 can be used to find the current\nlocation of the program break."
},
{
"code": null,
"e": 3121,
"s": 2974,
"text": "On success,\nbrk() returns zero, and\nsbrk() returns a pointer to the start of the new area. On error, -1 is returned,\nand\nerrno is set to\nENOMEM. "
},
{
"code": null,
"e": 3268,
"s": 3121,
"text": "brk() and\nsbrk() are not defined in the C Standard and are deliberately excluded from the\nPOSIX.1 standard (see paragraphs B.1.1.1.3 and B.8.3.3)."
},
{
"code": null,
"e": 3377,
"s": 3268,
"text": "Various systems use various types for the parameter of sbrk(). Common are int, ssize_t, ptrdiff_t, intptr_t."
},
{
"code": null,
"e": 3388,
"s": 3377,
"text": "execve (2)"
},
{
"code": null,
"e": 3399,
"s": 3388,
"text": "execve (2)"
},
{
"code": null,
"e": 3413,
"s": 3399,
"text": "getrlimit (2)"
},
{
"code": null,
"e": 3427,
"s": 3413,
"text": "getrlimit (2)"
},
{
"code": null,
"e": 3444,
"s": 3427,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 3479,
"s": 3444,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 3507,
"s": 3479,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3541,
"s": 3507,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3558,
"s": 3541,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3591,
"s": 3558,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3602,
"s": 3591,
"text": " Pradeep D"
},
{
"code": null,
"e": 3637,
"s": 3602,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3653,
"s": 3637,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 3686,
"s": 3653,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3698,
"s": 3686,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 3730,
"s": 3698,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3738,
"s": 3730,
"text": " Uplatz"
},
{
"code": null,
"e": 3745,
"s": 3738,
"text": " Print"
},
{
"code": null,
"e": 3756,
"s": 3745,
"text": " Add Notes"
}
] |
The Top 7 Best Github Repositories to Learn Python | by Byron Dolon | Towards Data Science
|
All roads lead to GitHub.
You may remember a similar article I published called “Top 4 Repositories on GitHub to Learn Pandas”. There, I said I was afraid of using anything more than git commit + git push because GitHub is scary. I’ve progressed a little bit: now I remember to hit git pull every time I have fresh work (instead of screaming internally when I try to push my edits and realize that my local repository wasn’t up to date with the master branch).
This time, I decided to compile a similar list of learning resources for Python! Some of them contain tutorial-style Jupyter notebooks, whereas others feature extensive collections of programming problems. All of them have the potential to be useful, depending on your preferred learning style.
If you haven’t used Python at all before, you may benefit from the repositories that have resources for complete beginners. If you’re already comfortable with Python and you’re looking to brush up on a particular subject, say algorithms, there’s also a repository just for you!
This repository takes you through 19 Jupyter notebooks in its beginner section. It covers foundation-level like strings and conditionals, then goes a bit deeper by discussing classes (a really quick introduction to object-oriented programming), exceptions (what they are and how to handle them), and some features included in the Python standard library (datetime, regular expressions, and more).
Each topic has a “notebook” link, which brings you to an introduction of the topic and some sample code. After you go through that, there’s an “exercise” link, which takes you to a notebook with sample problems that you can fill in and test.
Then, there’s an intermediate “idiomatic” section. This section describes “Pythonic features”, which are features in Python that aren’t present in many other programming languages. If you’re already familiar with a different language, you may want to check this section out for tips and tricks on working specifically with Python. For example, there’s a section on how to approach loops in Python differently than with other languages.
This repository also has a link to a handy “best practices” notebook, which you can use to learn about what practices you should implement when creating Python projects. It covers things like setting up a virtual environment with pipenv and using pytest for (you guessed right) testing.
This repository also serves as an introduction to Python that can bring you from beginner to intermediate (and by intermediate I mean comfortable with using the language beyond simple loops and arithmetic). Instead of using notebooks, the repository is a collection of Python scripts, each of which is a sub-topic of a core category like “Operators”, “Data Types”, and “Control Flow”.
Each Python file demonstrates the sub-topic in question as well as a helpful link that you can visit for more information. This can be helpful if you’re unclear on what the code does and need to quickly review some theory.
Two important features included in the repository as you work with the Python files are testing and style checking. You can see the full details under “How to Use This Repository”, but for testing, the author includes lines with assert at the bottom of the main function to see if the function is performing as it should. This can be useful if you want to make changes to the code and see if it still functions properly. There are instructions for how you can actually run the tests with pytest. Also, to get into a habit of following Python’s main style guide (PEP 8), there are further instructions for you to run pylint on the code to see if the Python files comply with the style guide.
You don’t have to follow the course in its entirety, as the author notes that you can also use the repository as a cheat-sheet. You could simply find the section you’re looking for, review the documentation, play around with the code, then run tests and lint the code to see if it’s working and written as it should be.
This repository features a book that quickly goes through the basics of strings and lists, then dives quickly into relatively more advanced topics like “Classes”, “Coroutines” and “Asynchronous Programming”. The author wrote the book with a practical approach in mind, briefly introducing each topic with code examples and then jumping straight to practice problems that readers can try on their own.
You can either download the pdf/epub file from the link the Readme, or you can clone the repository and build it yourself.
The author writes that “Distributed Computing students taking a software engineering degree became familiar with Python in two weeks and could implement a distributed client-server application with sockets in the third week”. If you already have some software engineering experience in another language, or if this isn’t your first programming language, using this book may help quickly get you up to speed with Python.
This repository is not a tutorial-style resource with groups of concepts like the previous repositories. Instead, this repository is more of a collection of different notebooks on intermediate-level topics like “SQLite database operations in Python” and “Parallel processing via the multiprocessing module”. If you already have a solid foundation in Python, this resource may be useful to help you really take advantage of different features of the language. As with the previous repositories, this one also includes notebooks with code that you can edit and run.
The aptly named “not so obvious Python stuff” notebook (snippet above) gives a rundown of various Python and Python module features that you may not have learned while studying the absolute basics. You never know when that random tip could help your work in the future. While it’s great to build depth of understanding when you’re just starting with Python, once you’ve learned enough of the basics, it can help to go through a compilation of unrelated tips like to broaden and fill gaps in your knowledge.
There are also helpful non-code resources which the author has linked to which serve more as “theory resources”. For example, the author created one called “Unit testing in Python — Why we want to make it a habit”.
The author has also linked many other external resources they found useful for learning Python, including forums, books, and existing Python projects. The r/Python on Reddit, for example, is a great place to find helpful Python tips as well as personal projects that community members showcase.
This repository currently features one hundred Python programming exercises, ranging from beginner to advanced in difficulty. The questions and solutions were originally written in Python 2, but the author has since updated all 100 questions to include solutions written in Python 3.
If you’re already familiar with Python, some of these questions may seem too easy. I’d say being able to solve the easy questions is one thing, but being able to whiz through them is another. Going through all these problems, maybe in tandem with an online course you follow or the resources from one of the GitHub repositories here, can help prepare train you to solve programming exercises.
If you get stuck, you can use the “hint” line present at every problem to try and figure out how to approach the problem. Try not to scroll too far down for each question so you don’t see the solution right away because the process of trying to figure out the solution to a problem help you really remember the solution (instead of just trying to read and memorize the solution).
There’s also an “extended version” of this repository by a different author with the same questions and alternate solutions. In this extended repository, the author attempts to show the different ways one problem could be solved, which may be more efficient or “Pythonic” than the original solution.
Just like the previous repository, this one contains a comprehensive list of programming and algorithmic exercises that you can solve. However, instead of having all the exercises in a notebook, this repository has a Python file for each exercise, with a description of the problem and then what a solution for it would look like.
These questions don’t start at a complete beginner level of difficulty, so I would suggest coming to these once you already have a solid grasp of the basics (using functions, control flow, etc.).
The author also writes that “algorithms and structures and not language-specific”. Because of this, he wrote the solutions in Python because of the language’s readability, but people comfortable in other languages should be able to use this repository as well to see how to approach algorithmic problems.
The problems in this repository are not written originally by the author, as he explicitly states that they come from problem-solving sites like LeetCode. His contribution is providing solutions and explanations to help people learn how to solve these types of problems.
You’ll find that many problems can be grouped under a one main topic, so the approach to solving those problems may be somewhat similar. As you keep practicing the same types of problems in one topic, you should find that they become progressively easier for you to solve.
In addition to the Python files with algorithm questions and solutions, he also includes a comprehensive list of other resources for you to use. There are many online courses, recommended books, and links to popular sites for programming problems.
This repository also features a collection of files that show you how different algorithms can be implemented in Python. These algorithms are grouped into categories from “Arithmetic Analysis” to “Blockchain” to “Data Structures” and even more. There isn’t as much explanation on how to solve each problem, as this repository can serve as a solution guide to implementing different algorithms.
Some files do give you a bit of context (and a link or two to get you started), but you may have to do some research on your own before you try to solve these algorithms. If you’re completely new to Python, I would suggest building your fundamental knowledge first, as this repository is really for those that are already comfortable with the language and are looking to deepen their knowledge on algorithms.
The author has also created similar “learning algorithms” repositories for a few other major languages (Java, C++, C, Go, Javascript), which you can check out on the profile’s pinned repositories.
GitHub repositories contain a wealth of valuable learning resources, but that doesn’t mean you need to use all of them. My suggestion is to first take one of the “beginner to intermediate” type repositories and work through all the learning material in it. You should work through the repository that best fits your learning style. For example, if you want to learn through editable Jupyter notebooks that take you from basic to intermediate topics, you should try the first repository in this piece.
In addition, the two 100+ Python problems are great for you to use as an introduction to solving programming problems. You can choose to either start trying a few every day or wait until you have a more solid foundation in Python first. These can eventually help you build some basic knowledge for the types of programming questions that could come up in technical job interviews. You could progress from these to sites like HackerRank and LeetCode, which also give you various programming problems to solve every day. They can also help you prepare for job interviews at specific companies, like Facebook, Amazon, and Google.
Learning Python (and anything really) is all about staying motivated and practicing. Python isn’t magic- make a plan and use one of these repositories if they fit (or use something completely different if they don’t) and stick with it.
You got this!
More by me:- 2 Easy Ways to Get Tables From a Website- An Introduction to the Cohort Analysis With Tableau- How to Quickly Create and Unpack Lists with Pandas- Rename Screenshots on Mac with 21 Lines of Python
|
[
{
"code": null,
"e": 73,
"s": 47,
"text": "All roads lead to GitHub."
},
{
"code": null,
"e": 508,
"s": 73,
"text": "You may remember a similar article I published called “Top 4 Repositories on GitHub to Learn Pandas”. There, I said I was afraid of using anything more than git commit + git push because GitHub is scary. I’ve progressed a little bit: now I remember to hit git pull every time I have fresh work (instead of screaming internally when I try to push my edits and realize that my local repository wasn’t up to date with the master branch)."
},
{
"code": null,
"e": 803,
"s": 508,
"text": "This time, I decided to compile a similar list of learning resources for Python! Some of them contain tutorial-style Jupyter notebooks, whereas others feature extensive collections of programming problems. All of them have the potential to be useful, depending on your preferred learning style."
},
{
"code": null,
"e": 1081,
"s": 803,
"text": "If you haven’t used Python at all before, you may benefit from the repositories that have resources for complete beginners. If you’re already comfortable with Python and you’re looking to brush up on a particular subject, say algorithms, there’s also a repository just for you!"
},
{
"code": null,
"e": 1478,
"s": 1081,
"text": "This repository takes you through 19 Jupyter notebooks in its beginner section. It covers foundation-level like strings and conditionals, then goes a bit deeper by discussing classes (a really quick introduction to object-oriented programming), exceptions (what they are and how to handle them), and some features included in the Python standard library (datetime, regular expressions, and more)."
},
{
"code": null,
"e": 1720,
"s": 1478,
"text": "Each topic has a “notebook” link, which brings you to an introduction of the topic and some sample code. After you go through that, there’s an “exercise” link, which takes you to a notebook with sample problems that you can fill in and test."
},
{
"code": null,
"e": 2156,
"s": 1720,
"text": "Then, there’s an intermediate “idiomatic” section. This section describes “Pythonic features”, which are features in Python that aren’t present in many other programming languages. If you’re already familiar with a different language, you may want to check this section out for tips and tricks on working specifically with Python. For example, there’s a section on how to approach loops in Python differently than with other languages."
},
{
"code": null,
"e": 2443,
"s": 2156,
"text": "This repository also has a link to a handy “best practices” notebook, which you can use to learn about what practices you should implement when creating Python projects. It covers things like setting up a virtual environment with pipenv and using pytest for (you guessed right) testing."
},
{
"code": null,
"e": 2828,
"s": 2443,
"text": "This repository also serves as an introduction to Python that can bring you from beginner to intermediate (and by intermediate I mean comfortable with using the language beyond simple loops and arithmetic). Instead of using notebooks, the repository is a collection of Python scripts, each of which is a sub-topic of a core category like “Operators”, “Data Types”, and “Control Flow”."
},
{
"code": null,
"e": 3051,
"s": 2828,
"text": "Each Python file demonstrates the sub-topic in question as well as a helpful link that you can visit for more information. This can be helpful if you’re unclear on what the code does and need to quickly review some theory."
},
{
"code": null,
"e": 3742,
"s": 3051,
"text": "Two important features included in the repository as you work with the Python files are testing and style checking. You can see the full details under “How to Use This Repository”, but for testing, the author includes lines with assert at the bottom of the main function to see if the function is performing as it should. This can be useful if you want to make changes to the code and see if it still functions properly. There are instructions for how you can actually run the tests with pytest. Also, to get into a habit of following Python’s main style guide (PEP 8), there are further instructions for you to run pylint on the code to see if the Python files comply with the style guide."
},
{
"code": null,
"e": 4062,
"s": 3742,
"text": "You don’t have to follow the course in its entirety, as the author notes that you can also use the repository as a cheat-sheet. You could simply find the section you’re looking for, review the documentation, play around with the code, then run tests and lint the code to see if it’s working and written as it should be."
},
{
"code": null,
"e": 4463,
"s": 4062,
"text": "This repository features a book that quickly goes through the basics of strings and lists, then dives quickly into relatively more advanced topics like “Classes”, “Coroutines” and “Asynchronous Programming”. The author wrote the book with a practical approach in mind, briefly introducing each topic with code examples and then jumping straight to practice problems that readers can try on their own."
},
{
"code": null,
"e": 4586,
"s": 4463,
"text": "You can either download the pdf/epub file from the link the Readme, or you can clone the repository and build it yourself."
},
{
"code": null,
"e": 5006,
"s": 4586,
"text": "The author writes that “Distributed Computing students taking a software engineering degree became familiar with Python in two weeks and could implement a distributed client-server application with sockets in the third week”. If you already have some software engineering experience in another language, or if this isn’t your first programming language, using this book may help quickly get you up to speed with Python."
},
{
"code": null,
"e": 5570,
"s": 5006,
"text": "This repository is not a tutorial-style resource with groups of concepts like the previous repositories. Instead, this repository is more of a collection of different notebooks on intermediate-level topics like “SQLite database operations in Python” and “Parallel processing via the multiprocessing module”. If you already have a solid foundation in Python, this resource may be useful to help you really take advantage of different features of the language. As with the previous repositories, this one also includes notebooks with code that you can edit and run."
},
{
"code": null,
"e": 6077,
"s": 5570,
"text": "The aptly named “not so obvious Python stuff” notebook (snippet above) gives a rundown of various Python and Python module features that you may not have learned while studying the absolute basics. You never know when that random tip could help your work in the future. While it’s great to build depth of understanding when you’re just starting with Python, once you’ve learned enough of the basics, it can help to go through a compilation of unrelated tips like to broaden and fill gaps in your knowledge."
},
{
"code": null,
"e": 6292,
"s": 6077,
"text": "There are also helpful non-code resources which the author has linked to which serve more as “theory resources”. For example, the author created one called “Unit testing in Python — Why we want to make it a habit”."
},
{
"code": null,
"e": 6587,
"s": 6292,
"text": "The author has also linked many other external resources they found useful for learning Python, including forums, books, and existing Python projects. The r/Python on Reddit, for example, is a great place to find helpful Python tips as well as personal projects that community members showcase."
},
{
"code": null,
"e": 6871,
"s": 6587,
"text": "This repository currently features one hundred Python programming exercises, ranging from beginner to advanced in difficulty. The questions and solutions were originally written in Python 2, but the author has since updated all 100 questions to include solutions written in Python 3."
},
{
"code": null,
"e": 7264,
"s": 6871,
"text": "If you’re already familiar with Python, some of these questions may seem too easy. I’d say being able to solve the easy questions is one thing, but being able to whiz through them is another. Going through all these problems, maybe in tandem with an online course you follow or the resources from one of the GitHub repositories here, can help prepare train you to solve programming exercises."
},
{
"code": null,
"e": 7644,
"s": 7264,
"text": "If you get stuck, you can use the “hint” line present at every problem to try and figure out how to approach the problem. Try not to scroll too far down for each question so you don’t see the solution right away because the process of trying to figure out the solution to a problem help you really remember the solution (instead of just trying to read and memorize the solution)."
},
{
"code": null,
"e": 7944,
"s": 7644,
"text": "There’s also an “extended version” of this repository by a different author with the same questions and alternate solutions. In this extended repository, the author attempts to show the different ways one problem could be solved, which may be more efficient or “Pythonic” than the original solution."
},
{
"code": null,
"e": 8275,
"s": 7944,
"text": "Just like the previous repository, this one contains a comprehensive list of programming and algorithmic exercises that you can solve. However, instead of having all the exercises in a notebook, this repository has a Python file for each exercise, with a description of the problem and then what a solution for it would look like."
},
{
"code": null,
"e": 8471,
"s": 8275,
"text": "These questions don’t start at a complete beginner level of difficulty, so I would suggest coming to these once you already have a solid grasp of the basics (using functions, control flow, etc.)."
},
{
"code": null,
"e": 8776,
"s": 8471,
"text": "The author also writes that “algorithms and structures and not language-specific”. Because of this, he wrote the solutions in Python because of the language’s readability, but people comfortable in other languages should be able to use this repository as well to see how to approach algorithmic problems."
},
{
"code": null,
"e": 9047,
"s": 8776,
"text": "The problems in this repository are not written originally by the author, as he explicitly states that they come from problem-solving sites like LeetCode. His contribution is providing solutions and explanations to help people learn how to solve these types of problems."
},
{
"code": null,
"e": 9320,
"s": 9047,
"text": "You’ll find that many problems can be grouped under a one main topic, so the approach to solving those problems may be somewhat similar. As you keep practicing the same types of problems in one topic, you should find that they become progressively easier for you to solve."
},
{
"code": null,
"e": 9568,
"s": 9320,
"text": "In addition to the Python files with algorithm questions and solutions, he also includes a comprehensive list of other resources for you to use. There are many online courses, recommended books, and links to popular sites for programming problems."
},
{
"code": null,
"e": 9962,
"s": 9568,
"text": "This repository also features a collection of files that show you how different algorithms can be implemented in Python. These algorithms are grouped into categories from “Arithmetic Analysis” to “Blockchain” to “Data Structures” and even more. There isn’t as much explanation on how to solve each problem, as this repository can serve as a solution guide to implementing different algorithms."
},
{
"code": null,
"e": 10371,
"s": 9962,
"text": "Some files do give you a bit of context (and a link or two to get you started), but you may have to do some research on your own before you try to solve these algorithms. If you’re completely new to Python, I would suggest building your fundamental knowledge first, as this repository is really for those that are already comfortable with the language and are looking to deepen their knowledge on algorithms."
},
{
"code": null,
"e": 10568,
"s": 10371,
"text": "The author has also created similar “learning algorithms” repositories for a few other major languages (Java, C++, C, Go, Javascript), which you can check out on the profile’s pinned repositories."
},
{
"code": null,
"e": 11069,
"s": 10568,
"text": "GitHub repositories contain a wealth of valuable learning resources, but that doesn’t mean you need to use all of them. My suggestion is to first take one of the “beginner to intermediate” type repositories and work through all the learning material in it. You should work through the repository that best fits your learning style. For example, if you want to learn through editable Jupyter notebooks that take you from basic to intermediate topics, you should try the first repository in this piece."
},
{
"code": null,
"e": 11696,
"s": 11069,
"text": "In addition, the two 100+ Python problems are great for you to use as an introduction to solving programming problems. You can choose to either start trying a few every day or wait until you have a more solid foundation in Python first. These can eventually help you build some basic knowledge for the types of programming questions that could come up in technical job interviews. You could progress from these to sites like HackerRank and LeetCode, which also give you various programming problems to solve every day. They can also help you prepare for job interviews at specific companies, like Facebook, Amazon, and Google."
},
{
"code": null,
"e": 11932,
"s": 11696,
"text": "Learning Python (and anything really) is all about staying motivated and practicing. Python isn’t magic- make a plan and use one of these repositories if they fit (or use something completely different if they don’t) and stick with it."
},
{
"code": null,
"e": 11946,
"s": 11932,
"text": "You got this!"
}
] |
Tracking current Maximum Element in a Stack
|
19 Jan, 2022
Given a Stack, keep track of the maximum value in it. The maximum value may be the top element of the stack, but once a new element is pushed or an element is popped from the stack, the maximum element will be now from the rest of the elements.Examples:
Input : 4 19 7 14 20
Output : Max Values in stack are
4 19 19 19 20
Input : 40 19 7 14 20 5
Output : Max Values in stack are
40 40 40 40 40 40
Method 1 (Brute-force): We keep pushing the elements in the main stack and whenever we are asked to return the maximum element, we traverse the stack and print the max element.Time Complexity : O(n) Auxiliary Space : O(1)Method 2 (Efficient): An efficient approach would be to maintain an auxiliary stack while pushing element in the main stack. This auxiliary stack will keep track of the maximum element. Below is the step by step algorithm to do this:
Create an auxiliary stack, say ‘trackStack’ to keep the track of maximum elementPush the first element to both mainStack and the trackStack. Now from the second element, push the element to the main stack. Compare the element with the top element of the track stack, if the current element is greater than the top of trackStack then push the current element to trackStack otherwise push the top element of trackStack again into it. If we pop an element from the main stack, then pop an element from the trackStack as well. Now to compute the maximum of the main stack at any point, we can simply print the top element of Track stack.
Create an auxiliary stack, say ‘trackStack’ to keep the track of maximum element
Push the first element to both mainStack and the trackStack.
Now from the second element, push the element to the main stack. Compare the element with the top element of the track stack, if the current element is greater than the top of trackStack then push the current element to trackStack otherwise push the top element of trackStack again into it.
If we pop an element from the main stack, then pop an element from the trackStack as well.
Now to compute the maximum of the main stack at any point, we can simply print the top element of Track stack.
Step by step explanation : Suppose the elements are pushed on to the stack in the order {4, 2, 14, 1, 18} Step 1 : Push 4, Current max : 4 Step 2 : Push 2, Current max : 4 Step 3 : Push 14, Current max : 14 Step 4 : Push 1, Current max : 14 Step 5 : Push 18, Current max : 18 Step 6 : Pop 18, Current max : 14
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to keep track of maximum// element in a stack#include <bits/stdc++.h>using namespace std; class StackWithMax{ // main stack stack<int> mainStack; // stack to keep track of max element stack<int> trackStack; public: void push(int x) { mainStack.push(x); if (mainStack.size() == 1) { trackStack.push(x); return; } // If current element is greater than // the top element of track stack, push // the current element to track stack // otherwise push the element at top of // track stack again into it. if (x > trackStack.top()) trackStack.push(x); else trackStack.push(trackStack.top()); } int getMax() { return trackStack.top(); } int pop() { mainStack.pop(); trackStack.pop(); }}; // Driver program to test above functionsint main(){ StackWithMax s; s.push(20); cout << s.getMax() << endl; s.push(10); cout << s.getMax() << endl; s.push(50); cout << s.getMax() << endl; return 0;}
// Java program to keep track of maximum// element in a stackimport java.util.*;class GfG { static class StackWithMax{ // main stack static Stack<Integer> mainStack = new Stack<Integer> (); // Stack to keep track of max element static Stack<Integer> trackStack = new Stack<Integer> (); static void push(int x) { mainStack.push(x); if (mainStack.size() == 1) { trackStack.push(x); return; } // If current element is greater than // the top element of track stack, push // the current element to track stack // otherwise push the element at top of // track stack again into it. if (x > trackStack.peek()) trackStack.push(x); else trackStack.push(trackStack.peek()); } static int getMax() { return trackStack.peek(); } static void pop() { mainStack.pop(); trackStack.pop(); }}; // Driver program to test above functionspublic static void main(String[] args){ StackWithMax s = new StackWithMax(); s.push(20); System.out.println(s.getMax()); s.push(10); System.out.println(s.getMax()); s.push(50); System.out.println(s.getMax());}}
# Python3 program to keep track of# maximum element in a stack class StackWithMax: def __init__(self): # main stack self.mainStack = [] # stack to keep track of # max element self.trackStack = [] def push(self, x): self.mainStack.append(x) if (len(self.mainStack) == 1): self.trackStack.append(x) return # If current element is greater than # the top element of track stack, # append the current element to track # stack otherwise append the element # at top of track stack again into it. if (x > self.trackStack[-1]): self.trackStack.append(x) else: self.trackStack.append(self.trackStack[-1]) def getMax(self): return self.trackStack[-1] def pop(self): self.mainStack.pop() self.trackStack.pop() # Driver Codeif __name__ == '__main__': s = StackWithMax() s.push(20) print(s.getMax()) s.push(10) print(s.getMax()) s.push(50) print(s.getMax()) # This code is contributed by PranchalK
// C# program to keep track of maximum// element in a stackusing System;using System.Collections.Generic; class GfG{ public class StackWithMax{ // main stack static Stack<int> mainStack = new Stack<int> (); // stack to keep track of max element static Stack<int> trackStack = new Stack<int> (); public void push(int x) { mainStack.Push(x); if (mainStack.Count == 1) { trackStack.Push(x); return; } // If current element is greater than // the top element of track stack, push // the current element to track stack // otherwise push the element at top of // track stack again into it. if (x > trackStack.Peek()) trackStack.Push(x); else trackStack.Push(trackStack.Peek()); } public int getMax() { return trackStack.Peek(); } public void pop() { mainStack.Pop(); trackStack.Pop(); }}; // Driver codepublic static void Main(){ StackWithMax s = new StackWithMax(); s.push(20); Console.WriteLine(s.getMax()); s.push(10); Console.WriteLine(s.getMax()); s.push(50); Console.WriteLine(s.getMax());}} /* This code contributed by PrinciRaj1992 */
<script> // Javascript program to keep track of maximum // element in a stack // main stack let mainStack = []; // stack to keep track of max element let trackStack = []; function push(x) { mainStack.push(x); if (mainStack.length == 1) { trackStack.push(x); return; } // If current element is greater than // the top element of track stack, push // the current element to track stack // otherwise push the element at top of // track stack again into it. if (x > trackStack[trackStack.length - 1]) trackStack.push(x); else trackStack.push(trackStack[trackStack.length - 1]); } function getMax() { return trackStack[trackStack.length - 1]; } function pop() { mainStack.pop(); trackStack.pop(); } push(20); document.write(getMax() + "</br>"); push(10); document.write(getMax() + "</br>"); push(50); document.write(getMax()); // This code is contributed by rameshtravel07.</script>
Output:
20
20
50
Time Complexity : O(1) Auxiliary Complexity : O(n)This article is contributed by Rohit. 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.
prerna saini
princiraj1992
PranchalKatiyar
19bcs1298
rameshtravel07
surinderdawra388
Stack
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack in Python
Stack Class in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Introduction to Data Structures
Stack | Set 2 (Infix to Postfix)
What is Data Structure: Types, Classifications and Applications
Inorder Tree Traversal without Recursion
Program for Tower of Hanoi
Merge Overlapping Intervals
Implement a stack using singly linked list
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 308,
"s": 52,
"text": "Given a Stack, keep track of the maximum value in it. The maximum value may be the top element of the stack, but once a new element is pushed or an element is popped from the stack, the maximum element will be now from the rest of the elements.Examples: "
},
{
"code": null,
"e": 473,
"s": 308,
"text": "Input : 4 19 7 14 20\nOutput : Max Values in stack are \n 4 19 19 19 20\n\nInput : 40 19 7 14 20 5\nOutput : Max Values in stack are \n 40 40 40 40 40 40"
},
{
"code": null,
"e": 932,
"s": 475,
"text": "Method 1 (Brute-force): We keep pushing the elements in the main stack and whenever we are asked to return the maximum element, we traverse the stack and print the max element.Time Complexity : O(n) Auxiliary Space : O(1)Method 2 (Efficient): An efficient approach would be to maintain an auxiliary stack while pushing element in the main stack. This auxiliary stack will keep track of the maximum element. Below is the step by step algorithm to do this: "
},
{
"code": null,
"e": 1571,
"s": 932,
"text": "Create an auxiliary stack, say ‘trackStack’ to keep the track of maximum elementPush the first element to both mainStack and the trackStack. Now from the second element, push the element to the main stack. Compare the element with the top element of the track stack, if the current element is greater than the top of trackStack then push the current element to trackStack otherwise push the top element of trackStack again into it. If we pop an element from the main stack, then pop an element from the trackStack as well. Now to compute the maximum of the main stack at any point, we can simply print the top element of Track stack. "
},
{
"code": null,
"e": 1652,
"s": 1571,
"text": "Create an auxiliary stack, say ‘trackStack’ to keep the track of maximum element"
},
{
"code": null,
"e": 1715,
"s": 1652,
"text": "Push the first element to both mainStack and the trackStack. "
},
{
"code": null,
"e": 2008,
"s": 1715,
"text": "Now from the second element, push the element to the main stack. Compare the element with the top element of the track stack, if the current element is greater than the top of trackStack then push the current element to trackStack otherwise push the top element of trackStack again into it. "
},
{
"code": null,
"e": 2101,
"s": 2008,
"text": "If we pop an element from the main stack, then pop an element from the trackStack as well. "
},
{
"code": null,
"e": 2214,
"s": 2101,
"text": "Now to compute the maximum of the main stack at any point, we can simply print the top element of Track stack. "
},
{
"code": null,
"e": 2525,
"s": 2214,
"text": "Step by step explanation : Suppose the elements are pushed on to the stack in the order {4, 2, 14, 1, 18} Step 1 : Push 4, Current max : 4 Step 2 : Push 2, Current max : 4 Step 3 : Push 14, Current max : 14 Step 4 : Push 1, Current max : 14 Step 5 : Push 18, Current max : 18 Step 6 : Pop 18, Current max : 14 "
},
{
"code": null,
"e": 2578,
"s": 2525,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2582,
"s": 2578,
"text": "C++"
},
{
"code": null,
"e": 2587,
"s": 2582,
"text": "Java"
},
{
"code": null,
"e": 2595,
"s": 2587,
"text": "Python3"
},
{
"code": null,
"e": 2598,
"s": 2595,
"text": "C#"
},
{
"code": null,
"e": 2609,
"s": 2598,
"text": "Javascript"
},
{
"code": "// C++ program to keep track of maximum// element in a stack#include <bits/stdc++.h>using namespace std; class StackWithMax{ // main stack stack<int> mainStack; // stack to keep track of max element stack<int> trackStack; public: void push(int x) { mainStack.push(x); if (mainStack.size() == 1) { trackStack.push(x); return; } // If current element is greater than // the top element of track stack, push // the current element to track stack // otherwise push the element at top of // track stack again into it. if (x > trackStack.top()) trackStack.push(x); else trackStack.push(trackStack.top()); } int getMax() { return trackStack.top(); } int pop() { mainStack.pop(); trackStack.pop(); }}; // Driver program to test above functionsint main(){ StackWithMax s; s.push(20); cout << s.getMax() << endl; s.push(10); cout << s.getMax() << endl; s.push(50); cout << s.getMax() << endl; return 0;}",
"e": 3712,
"s": 2609,
"text": null
},
{
"code": "// Java program to keep track of maximum// element in a stackimport java.util.*;class GfG { static class StackWithMax{ // main stack static Stack<Integer> mainStack = new Stack<Integer> (); // Stack to keep track of max element static Stack<Integer> trackStack = new Stack<Integer> (); static void push(int x) { mainStack.push(x); if (mainStack.size() == 1) { trackStack.push(x); return; } // If current element is greater than // the top element of track stack, push // the current element to track stack // otherwise push the element at top of // track stack again into it. if (x > trackStack.peek()) trackStack.push(x); else trackStack.push(trackStack.peek()); } static int getMax() { return trackStack.peek(); } static void pop() { mainStack.pop(); trackStack.pop(); }}; // Driver program to test above functionspublic static void main(String[] args){ StackWithMax s = new StackWithMax(); s.push(20); System.out.println(s.getMax()); s.push(10); System.out.println(s.getMax()); s.push(50); System.out.println(s.getMax());}}",
"e": 4942,
"s": 3712,
"text": null
},
{
"code": "# Python3 program to keep track of# maximum element in a stack class StackWithMax: def __init__(self): # main stack self.mainStack = [] # stack to keep track of # max element self.trackStack = [] def push(self, x): self.mainStack.append(x) if (len(self.mainStack) == 1): self.trackStack.append(x) return # If current element is greater than # the top element of track stack, # append the current element to track # stack otherwise append the element # at top of track stack again into it. if (x > self.trackStack[-1]): self.trackStack.append(x) else: self.trackStack.append(self.trackStack[-1]) def getMax(self): return self.trackStack[-1] def pop(self): self.mainStack.pop() self.trackStack.pop() # Driver Codeif __name__ == '__main__': s = StackWithMax() s.push(20) print(s.getMax()) s.push(10) print(s.getMax()) s.push(50) print(s.getMax()) # This code is contributed by PranchalK",
"e": 6041,
"s": 4942,
"text": null
},
{
"code": "// C# program to keep track of maximum// element in a stackusing System;using System.Collections.Generic; class GfG{ public class StackWithMax{ // main stack static Stack<int> mainStack = new Stack<int> (); // stack to keep track of max element static Stack<int> trackStack = new Stack<int> (); public void push(int x) { mainStack.Push(x); if (mainStack.Count == 1) { trackStack.Push(x); return; } // If current element is greater than // the top element of track stack, push // the current element to track stack // otherwise push the element at top of // track stack again into it. if (x > trackStack.Peek()) trackStack.Push(x); else trackStack.Push(trackStack.Peek()); } public int getMax() { return trackStack.Peek(); } public void pop() { mainStack.Pop(); trackStack.Pop(); }}; // Driver codepublic static void Main(){ StackWithMax s = new StackWithMax(); s.push(20); Console.WriteLine(s.getMax()); s.push(10); Console.WriteLine(s.getMax()); s.push(50); Console.WriteLine(s.getMax());}} /* This code contributed by PrinciRaj1992 */",
"e": 7285,
"s": 6041,
"text": null
},
{
"code": "<script> // Javascript program to keep track of maximum // element in a stack // main stack let mainStack = []; // stack to keep track of max element let trackStack = []; function push(x) { mainStack.push(x); if (mainStack.length == 1) { trackStack.push(x); return; } // If current element is greater than // the top element of track stack, push // the current element to track stack // otherwise push the element at top of // track stack again into it. if (x > trackStack[trackStack.length - 1]) trackStack.push(x); else trackStack.push(trackStack[trackStack.length - 1]); } function getMax() { return trackStack[trackStack.length - 1]; } function pop() { mainStack.pop(); trackStack.pop(); } push(20); document.write(getMax() + \"</br>\"); push(10); document.write(getMax() + \"</br>\"); push(50); document.write(getMax()); // This code is contributed by rameshtravel07.</script>",
"e": 8401,
"s": 7285,
"text": null
},
{
"code": null,
"e": 8411,
"s": 8401,
"text": "Output: "
},
{
"code": null,
"e": 8420,
"s": 8411,
"text": "20\n20\n50"
},
{
"code": null,
"e": 8884,
"s": 8420,
"text": "Time Complexity : O(1) Auxiliary Complexity : O(n)This article is contributed by Rohit. 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": 8897,
"s": 8884,
"text": "prerna saini"
},
{
"code": null,
"e": 8911,
"s": 8897,
"text": "princiraj1992"
},
{
"code": null,
"e": 8927,
"s": 8911,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 8937,
"s": 8927,
"text": "19bcs1298"
},
{
"code": null,
"e": 8952,
"s": 8937,
"text": "rameshtravel07"
},
{
"code": null,
"e": 8969,
"s": 8952,
"text": "surinderdawra388"
},
{
"code": null,
"e": 8975,
"s": 8969,
"text": "Stack"
},
{
"code": null,
"e": 8981,
"s": 8975,
"text": "Stack"
},
{
"code": null,
"e": 9079,
"s": 8981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9095,
"s": 9079,
"text": "Stack in Python"
},
{
"code": null,
"e": 9115,
"s": 9095,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 9190,
"s": 9115,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 9222,
"s": 9190,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9255,
"s": 9222,
"text": "Stack | Set 2 (Infix to Postfix)"
},
{
"code": null,
"e": 9319,
"s": 9255,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9360,
"s": 9319,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 9387,
"s": 9360,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 9415,
"s": 9387,
"text": "Merge Overlapping Intervals"
}
] |
Kotlin | Lambdas Expressions and Anonymous Functions
|
09 May, 2022
In this article, we are going to learn lambdas expression and anonymous function in Kotlin. While syntactically similar, Kotlin and Java lambdas have very different features.
Lambdas expression and Anonymous function both are function literals means these functions are not declared but passed immediately as an expression.
As we know, syntax of Kotlin lambdas is similar to Java Lambdas. A function without name is called anonymous function. For lambda expression we can say that it is anonymous function.
Example:
Kotlin
fun main(args: Array<String>) { val company = { println("GeeksforGeeks")} // invoking function method1 company() // invoking function method2 company.invoke()}
Output:
GeeksforGeeks
GeeksforGeeks
Syntax of Lambda expression –
val lambda_name : Data_type = { argument_List -> code_body }
A lambda expression is always surrounded by curly braces, argument declarations go inside curly braces and have optional type annotations, the code_body goes after an arrow -> sign. If the inferred return type of the lambda is not Unit, then the last expression inside the lambda body is treated as return value.
Example:
val sum = {a: Int , b: Int -> a + b}
In Kotlin, the lambda expression contains optional part except code_body. Below is the lambda expression after eliminating the optional part.
val sum:(Int,Int) -> Int = { a, b -> a + b}
Note: We don’t always require a variable because it can be passed directly as an argument to a function.
Kotlin program of using lambda expression-
Kotlin
// with type annotation in lambda expressionval sum1 = { a: Int, b: Int -> a + b } // without type annotation in lambda expressionval sum2:(Int,Int)-> Int = { a , b -> a + b} fun main(args: Array<String>) { val result1 = sum1(2,3) val result2 = sum2(3,4) println("The sum of two numbers is: $result1") println("The sum of two numbers is: $result2") // directly print the return value of lambda // without storing in a variable. println(sum1(5,7))}
Output:
The sum of two numbers is: 5
The sum of two numbers is: 7
12
Kotlin’s type inference helps the compiler to evaluate the type of a lambda expression. Below is the lambda expression using which we can compute the sum of two integers.
val sum = {a: Int , b: Int -> a + b}
Here, Kotlin compiler self evaluate it as a function which take two parameters of type Int and returns Int value.
(Int,Int) -> Int
If we wanted to return String value than we can do it with help of toString() inbuilt function.
Kotlin
val sum1 = { a: Int, b: Int -> val num = a + b num.toString() //convert Integer to String}fun main(args: Array<String>) { val result1 = sum1(2,3) println("The sum of two numbers is: $result1")}
Output:
The sum of two numbers is: 5
In above program, Kotlin compiler self evaluate it as a function which takes two integer values and returns String.
(Int,Int) -> String
We must explicitly declare the type of our lambda expression. If lambda returns no value then we can use: Unit Pattern: (Input) -> Output
Lambdas examples with return type –
val lambda1: (Int) -> Int = (a -> a * a)
val lambda2: (String,String) -> String = { a , b -> a + b }
val lambda3: (Int)-> Unit = {print(Int)}
Lambdas can be used as class extension:
val lambda4: String.(Int) -> String = {this + it}
Here, it represents the implicit name of single parameter and we will discuss later.
Kotlin program when lambdas used as class extension –
Kotlin
val lambda4 : String.(Int) -> String = { this + it } fun main(args: Array<String>) { val result = "Geeks".lambda4(50) print(result)}
Output:
Geeks50
Explanation: In the above example, we are using the lambda expression as class extension. We have passed the parameters according to the format given above. this keyword is used for the string and it keyword is used for the Int parameter passed in the lambda. Then the code_body concatenates both the values and returns to variable result.
In most of cases lambdas contains the single parameter. Here, it is used to represent the single parameter we pass to lambda expression.
Kotlin program using shorthand form of lambda function –
Kotlin
val numbers = arrayOf(1,-2,3,-4,5) fun main(args: Array<String>) { println(numbers.filter { it > 0 })}
Output:
[1, 3, 5]
Kotlin program using longhand form of lambda function –
Kotlin
val numbers = arrayOf(1,-2,3,-4,5) fun main(args: Array<String>) { println(numbers.filter {item -> item > 0 })}
Output:
[1, 3, 5]
After execution of lambda the final value returned by the lambda expression. Any of these Integer, String or Boolean value can be returned by the lambda function.
Kotlin program to return String value by lambda function –
Kotlin
val find =fun(num: Int): String{if(num % 2==0 && num < 0) { return "Number is even and negative" } else if (num %2 ==0 && num >0){ return "Number is even and positive" } else if(num %2 !=0 && num < 0){ return "Number is odd and negative" } else { return "Number is odd and positive" }}fun main(args: Array<String>) { val result = find(112) println(result)}
Output:
Number is even and positive
An anonymous function is very similar to regular function except for the name of the function which is omitted from the declaration. The body of the anonymous function can be either an expression or block.
Example 1: Function body as an expression
fun(a: Int, b: Int) : Int = a * b
Example 2: Function body as a block
fun(a: Int, b: Int): Int {
val mul = a * b
return mul
}
Return type and parameters-
The return type and parameters are also specified in same way as for regular function but we can omit the parameters if they can be inferred from the context.The return type of the function can be inferred automatically from the function if it is an expression and has to be specified explicitly for the anonymous function if it is body block.
The return type and parameters are also specified in same way as for regular function but we can omit the parameters if they can be inferred from the context.
The return type of the function can be inferred automatically from the function if it is an expression and has to be specified explicitly for the anonymous function if it is body block.
Difference between lambda expressions and anonymous functions-The only difference is the behavior of non-local returns. A return statement without a label always returns from the function declared with the fun keyword. This means that a return inside a lambda expression will return from the enclosing function, whereas a return inside an anonymous function will return from the anonymous function itself.
Kotlin program to call the anonymous function-
Kotlin
// anonymous function with body as an expressionval anonymous1 = fun(x: Int, y: Int): Int = x + y // anonymous function with body as a blockval anonymous2 = fun(a: Int, b: Int): Int { val mul = a * b return mul }fun main(args: Array<String>) { //invoking functions val sum = anonymous1(3,5) val mul = anonymous2(3,5) println("The sum of two numbers is: $sum") println("The multiply of two numbers is: $mul")}
Output:
The sum of two numbers is: 8
The multiply of two numbers is: 15
kevilpy
anikakapoor
rajeev0719singh
ubedk
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 228,
"s": 52,
"text": "In this article, we are going to learn lambdas expression and anonymous function in Kotlin. While syntactically similar, Kotlin and Java lambdas have very different features. "
},
{
"code": null,
"e": 378,
"s": 228,
"text": "Lambdas expression and Anonymous function both are function literals means these functions are not declared but passed immediately as an expression. "
},
{
"code": null,
"e": 561,
"s": 378,
"text": "As we know, syntax of Kotlin lambdas is similar to Java Lambdas. A function without name is called anonymous function. For lambda expression we can say that it is anonymous function."
},
{
"code": null,
"e": 571,
"s": 561,
"text": "Example: "
},
{
"code": null,
"e": 578,
"s": 571,
"text": "Kotlin"
},
{
"code": "fun main(args: Array<String>) { val company = { println(\"GeeksforGeeks\")} // invoking function method1 company() // invoking function method2 company.invoke()}",
"e": 756,
"s": 578,
"text": null
},
{
"code": null,
"e": 765,
"s": 756,
"text": "Output: "
},
{
"code": null,
"e": 793,
"s": 765,
"text": "GeeksforGeeks\nGeeksforGeeks"
},
{
"code": null,
"e": 824,
"s": 793,
"text": "Syntax of Lambda expression – "
},
{
"code": null,
"e": 885,
"s": 824,
"text": "val lambda_name : Data_type = { argument_List -> code_body }"
},
{
"code": null,
"e": 1198,
"s": 885,
"text": "A lambda expression is always surrounded by curly braces, argument declarations go inside curly braces and have optional type annotations, the code_body goes after an arrow -> sign. If the inferred return type of the lambda is not Unit, then the last expression inside the lambda body is treated as return value."
},
{
"code": null,
"e": 1208,
"s": 1198,
"text": "Example: "
},
{
"code": null,
"e": 1245,
"s": 1208,
"text": "val sum = {a: Int , b: Int -> a + b}"
},
{
"code": null,
"e": 1388,
"s": 1245,
"text": "In Kotlin, the lambda expression contains optional part except code_body. Below is the lambda expression after eliminating the optional part. "
},
{
"code": null,
"e": 1432,
"s": 1388,
"text": "val sum:(Int,Int) -> Int = { a, b -> a + b}"
},
{
"code": null,
"e": 1537,
"s": 1432,
"text": "Note: We don’t always require a variable because it can be passed directly as an argument to a function."
},
{
"code": null,
"e": 1582,
"s": 1537,
"text": "Kotlin program of using lambda expression- "
},
{
"code": null,
"e": 1589,
"s": 1582,
"text": "Kotlin"
},
{
"code": "// with type annotation in lambda expressionval sum1 = { a: Int, b: Int -> a + b } // without type annotation in lambda expressionval sum2:(Int,Int)-> Int = { a , b -> a + b} fun main(args: Array<String>) { val result1 = sum1(2,3) val result2 = sum2(3,4) println(\"The sum of two numbers is: $result1\") println(\"The sum of two numbers is: $result2\") // directly print the return value of lambda // without storing in a variable. println(sum1(5,7))}",
"e": 2060,
"s": 1589,
"text": null
},
{
"code": null,
"e": 2069,
"s": 2060,
"text": "Output: "
},
{
"code": null,
"e": 2130,
"s": 2069,
"text": "The sum of two numbers is: 5\nThe sum of two numbers is: 7\n12"
},
{
"code": null,
"e": 2303,
"s": 2130,
"text": "Kotlin’s type inference helps the compiler to evaluate the type of a lambda expression. Below is the lambda expression using which we can compute the sum of two integers. "
},
{
"code": null,
"e": 2340,
"s": 2303,
"text": "val sum = {a: Int , b: Int -> a + b}"
},
{
"code": null,
"e": 2455,
"s": 2340,
"text": "Here, Kotlin compiler self evaluate it as a function which take two parameters of type Int and returns Int value. "
},
{
"code": null,
"e": 2472,
"s": 2455,
"text": "(Int,Int) -> Int"
},
{
"code": null,
"e": 2569,
"s": 2472,
"text": "If we wanted to return String value than we can do it with help of toString() inbuilt function. "
},
{
"code": null,
"e": 2576,
"s": 2569,
"text": "Kotlin"
},
{
"code": "val sum1 = { a: Int, b: Int -> val num = a + b num.toString() //convert Integer to String}fun main(args: Array<String>) { val result1 = sum1(2,3) println(\"The sum of two numbers is: $result1\")}",
"e": 2786,
"s": 2576,
"text": null
},
{
"code": null,
"e": 2795,
"s": 2786,
"text": "Output: "
},
{
"code": null,
"e": 2824,
"s": 2795,
"text": "The sum of two numbers is: 5"
},
{
"code": null,
"e": 2941,
"s": 2824,
"text": "In above program, Kotlin compiler self evaluate it as a function which takes two integer values and returns String. "
},
{
"code": null,
"e": 2963,
"s": 2941,
"text": "(Int,Int) -> String "
},
{
"code": null,
"e": 3101,
"s": 2963,
"text": "We must explicitly declare the type of our lambda expression. If lambda returns no value then we can use: Unit Pattern: (Input) -> Output"
},
{
"code": null,
"e": 3139,
"s": 3101,
"text": "Lambdas examples with return type – "
},
{
"code": null,
"e": 3281,
"s": 3139,
"text": "val lambda1: (Int) -> Int = (a -> a * a)\nval lambda2: (String,String) -> String = { a , b -> a + b }\nval lambda3: (Int)-> Unit = {print(Int)}"
},
{
"code": null,
"e": 3323,
"s": 3281,
"text": "Lambdas can be used as class extension: "
},
{
"code": null,
"e": 3374,
"s": 3323,
"text": "val lambda4: String.(Int) -> String = {this + it} "
},
{
"code": null,
"e": 3459,
"s": 3374,
"text": "Here, it represents the implicit name of single parameter and we will discuss later."
},
{
"code": null,
"e": 3515,
"s": 3459,
"text": "Kotlin program when lambdas used as class extension – "
},
{
"code": null,
"e": 3522,
"s": 3515,
"text": "Kotlin"
},
{
"code": "val lambda4 : String.(Int) -> String = { this + it } fun main(args: Array<String>) { val result = \"Geeks\".lambda4(50) print(result)}",
"e": 3661,
"s": 3522,
"text": null
},
{
"code": null,
"e": 3670,
"s": 3661,
"text": "Output: "
},
{
"code": null,
"e": 3678,
"s": 3670,
"text": "Geeks50"
},
{
"code": null,
"e": 4019,
"s": 3678,
"text": "Explanation: In the above example, we are using the lambda expression as class extension. We have passed the parameters according to the format given above. this keyword is used for the string and it keyword is used for the Int parameter passed in the lambda. Then the code_body concatenates both the values and returns to variable result. "
},
{
"code": null,
"e": 4156,
"s": 4019,
"text": "In most of cases lambdas contains the single parameter. Here, it is used to represent the single parameter we pass to lambda expression."
},
{
"code": null,
"e": 4215,
"s": 4156,
"text": "Kotlin program using shorthand form of lambda function – "
},
{
"code": null,
"e": 4222,
"s": 4215,
"text": "Kotlin"
},
{
"code": "val numbers = arrayOf(1,-2,3,-4,5) fun main(args: Array<String>) { println(numbers.filter { it > 0 })}",
"e": 4331,
"s": 4222,
"text": null
},
{
"code": null,
"e": 4340,
"s": 4331,
"text": "Output: "
},
{
"code": null,
"e": 4350,
"s": 4340,
"text": "[1, 3, 5]"
},
{
"code": null,
"e": 4407,
"s": 4350,
"text": "Kotlin program using longhand form of lambda function – "
},
{
"code": null,
"e": 4414,
"s": 4407,
"text": "Kotlin"
},
{
"code": "val numbers = arrayOf(1,-2,3,-4,5) fun main(args: Array<String>) { println(numbers.filter {item -> item > 0 })}",
"e": 4530,
"s": 4414,
"text": null
},
{
"code": null,
"e": 4539,
"s": 4530,
"text": "Output: "
},
{
"code": null,
"e": 4550,
"s": 4539,
"text": "[1, 3, 5] "
},
{
"code": null,
"e": 4713,
"s": 4550,
"text": "After execution of lambda the final value returned by the lambda expression. Any of these Integer, String or Boolean value can be returned by the lambda function."
},
{
"code": null,
"e": 4774,
"s": 4713,
"text": "Kotlin program to return String value by lambda function – "
},
{
"code": null,
"e": 4781,
"s": 4774,
"text": "Kotlin"
},
{
"code": "val find =fun(num: Int): String{if(num % 2==0 && num < 0) { return \"Number is even and negative\" } else if (num %2 ==0 && num >0){ return \"Number is even and positive\" } else if(num %2 !=0 && num < 0){ return \"Number is odd and negative\" } else { return \"Number is odd and positive\" }}fun main(args: Array<String>) { val result = find(112) println(result)}",
"e": 5176,
"s": 4781,
"text": null
},
{
"code": null,
"e": 5185,
"s": 5176,
"text": "Output: "
},
{
"code": null,
"e": 5213,
"s": 5185,
"text": "Number is even and positive"
},
{
"code": null,
"e": 5419,
"s": 5213,
"text": "An anonymous function is very similar to regular function except for the name of the function which is omitted from the declaration. The body of the anonymous function can be either an expression or block."
},
{
"code": null,
"e": 5463,
"s": 5419,
"text": "Example 1: Function body as an expression "
},
{
"code": null,
"e": 5497,
"s": 5463,
"text": "fun(a: Int, b: Int) : Int = a * b"
},
{
"code": null,
"e": 5534,
"s": 5497,
"text": "Example 2: Function body as a block "
},
{
"code": null,
"e": 5598,
"s": 5534,
"text": "fun(a: Int, b: Int): Int {\n val mul = a * b\n return mul\n}"
},
{
"code": null,
"e": 5627,
"s": 5598,
"text": "Return type and parameters- "
},
{
"code": null,
"e": 5971,
"s": 5627,
"text": "The return type and parameters are also specified in same way as for regular function but we can omit the parameters if they can be inferred from the context.The return type of the function can be inferred automatically from the function if it is an expression and has to be specified explicitly for the anonymous function if it is body block."
},
{
"code": null,
"e": 6130,
"s": 5971,
"text": "The return type and parameters are also specified in same way as for regular function but we can omit the parameters if they can be inferred from the context."
},
{
"code": null,
"e": 6316,
"s": 6130,
"text": "The return type of the function can be inferred automatically from the function if it is an expression and has to be specified explicitly for the anonymous function if it is body block."
},
{
"code": null,
"e": 6722,
"s": 6316,
"text": "Difference between lambda expressions and anonymous functions-The only difference is the behavior of non-local returns. A return statement without a label always returns from the function declared with the fun keyword. This means that a return inside a lambda expression will return from the enclosing function, whereas a return inside an anonymous function will return from the anonymous function itself."
},
{
"code": null,
"e": 6771,
"s": 6722,
"text": "Kotlin program to call the anonymous function- "
},
{
"code": null,
"e": 6778,
"s": 6771,
"text": "Kotlin"
},
{
"code": "// anonymous function with body as an expressionval anonymous1 = fun(x: Int, y: Int): Int = x + y // anonymous function with body as a blockval anonymous2 = fun(a: Int, b: Int): Int { val mul = a * b return mul }fun main(args: Array<String>) { //invoking functions val sum = anonymous1(3,5) val mul = anonymous2(3,5) println(\"The sum of two numbers is: $sum\") println(\"The multiply of two numbers is: $mul\")}",
"e": 7235,
"s": 6778,
"text": null
},
{
"code": null,
"e": 7244,
"s": 7235,
"text": "Output: "
},
{
"code": null,
"e": 7308,
"s": 7244,
"text": "The sum of two numbers is: 8\nThe multiply of two numbers is: 15"
},
{
"code": null,
"e": 7318,
"s": 7310,
"text": "kevilpy"
},
{
"code": null,
"e": 7330,
"s": 7318,
"text": "anikakapoor"
},
{
"code": null,
"e": 7346,
"s": 7330,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 7352,
"s": 7346,
"text": "ubedk"
},
{
"code": null,
"e": 7359,
"s": 7352,
"text": "Kotlin"
}
] |
GATE CS 2019 - GeeksforGeeks
|
06 Oct, 2021
The data breaks down into three main categories.
revolve: move in a circle on a central axis.
play: engage in activity for enjoyment and recreation rather than a serious or practical purpose.
sink: go down below the surface of something, especially of a liquid; become submerged.
burst: break open or apart suddenly and violently, especially as a result of an impact or internal pressure.
P says “Q committed the crime.”
Q says “S committed the crime.”
R says “ I did not do it.”
S says “What Q said about me is false”.
When P is correct and Q, R, S are false: it implies,Q committed crime,
S did not commit crime,
R committed crime,
S committed crime. This situation is impossible.
Q committed crime,
S did not commit crime,
R committed crime,
S committed crime.
When Q is correct and P, R, S are false: it implies,Q did not commit crime,
S committed crime,
R committed crime,
S committed crime. This situation is impossible.
Q did not commit crime,
S committed crime,
R committed crime,
S committed crime.
When R is correct and P, Q, S are false: it implies,Q did not commit crime,
S did not commit crime,
R did not commit crime,
S committed crime. This situation is impossible.
Q did not commit crime,
S did not commit crime,
R did not commit crime,
S committed crime.
When S is correct and P, Q, R are false: it implies,Q did not commit crime,
S did not commit crime,
R committed crime,
S did not commit crime. This situation is possible means R has committed crime.
Q did not commit crime,
S did not commit crime,
R committed crime,
S did not commit crime.
distance traveled by first car (with speed of 50 km/h) = 50*1 = 50 km
And, distance traveled by second car (with speed of 60 km/h) = 60*1 = 60 km
So, distance between these cars = 60 - 50 = 10 km
distance traveled by first car (with speed of 50 km/h) = 50*2 = 100 km
And, distance traveled by second car (with speed of 60 km/h) = 60*2 = 120 km
So, distance between these cars = 120 - 100 = 20 km
→ (distance traveled by second car) - (distance traveled by first car) = 20 km
→ (S2*T) - (S1*T) = 20
→ (60*T) - (50*T) = 20
→ 10*T = 20
→ T = 2
→ 10*x = 8*(x + 150)
→ 10*x = 8*x + 8*150
→ 2*x = 8*150
→ x = 8*150 / 2
→ x = 600
10*x = 10*600 = 6000
= 10+20+20
= 50
= 80+20+20+40
= 160
= (50/160)*100
= 31.25 %
= 60 + 80 + 30 + 38 + 2 + 10 + 5
= 225
x*0.25 = 225
= 225/0.25
= 900
Request by X: Due to pollen allergy, I want to avoid a wing next to the garden.
Request by Y: I want to live as far from the washrooms as possible since I am very much sensitive to smell.
Request by Z: I believe in Vaastu and so I want to stay in South-West wing.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Software Testing - Web Based Testing
What are the different ways of Data Representation?
Bash Script - Command Substitution
SDE SHEET - A Complete Guide for SDE Preparation
7 Highest Paying Programming Languages For Freelancers in 2022
DSA Sheet by Love Babbar
How to Create a Shell Script in linux
How To Convert Numpy Array To Tensor?
7 Best React Project Ideas For Beginners in 2022
|
[
{
"code": null,
"e": 29577,
"s": 29549,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 29626,
"s": 29577,
"text": "The data breaks down into three main categories."
},
{
"code": null,
"e": 29671,
"s": 29626,
"text": "revolve: move in a circle on a central axis."
},
{
"code": null,
"e": 29769,
"s": 29671,
"text": "play: engage in activity for enjoyment and recreation rather than a serious or practical purpose."
},
{
"code": null,
"e": 29857,
"s": 29769,
"text": "sink: go down below the surface of something, especially of a liquid; become submerged."
},
{
"code": null,
"e": 29966,
"s": 29857,
"text": "burst: break open or apart suddenly and violently, especially as a result of an impact or internal pressure."
},
{
"code": null,
"e": 30097,
"s": 29966,
"text": "P says “Q committed the crime.”\nQ says “S committed the crime.”\nR says “ I did not do it.”\nS says “What Q said about me is false”."
},
{
"code": null,
"e": 30260,
"s": 30097,
"text": "When P is correct and Q, R, S are false: it implies,Q committed crime,\nS did not commit crime,\nR committed crime,\nS committed crime. This situation is impossible."
},
{
"code": null,
"e": 30342,
"s": 30260,
"text": "Q committed crime,\nS did not commit crime,\nR committed crime,\nS committed crime. "
},
{
"code": null,
"e": 30505,
"s": 30342,
"text": "When Q is correct and P, R, S are false: it implies,Q did not commit crime,\nS committed crime,\nR committed crime,\nS committed crime. This situation is impossible."
},
{
"code": null,
"e": 30587,
"s": 30505,
"text": "Q did not commit crime,\nS committed crime,\nR committed crime,\nS committed crime. "
},
{
"code": null,
"e": 30760,
"s": 30587,
"text": "When R is correct and P, Q, S are false: it implies,Q did not commit crime,\nS did not commit crime,\nR did not commit crime,\nS committed crime. This situation is impossible."
},
{
"code": null,
"e": 30852,
"s": 30760,
"text": "Q did not commit crime,\nS did not commit crime,\nR did not commit crime,\nS committed crime. "
},
{
"code": null,
"e": 31051,
"s": 30852,
"text": "When S is correct and P, Q, R are false: it implies,Q did not commit crime,\nS did not commit crime,\nR committed crime,\nS did not commit crime. This situation is possible means R has committed crime."
},
{
"code": null,
"e": 31143,
"s": 31051,
"text": "Q did not commit crime,\nS did not commit crime,\nR committed crime,\nS did not commit crime. "
},
{
"code": null,
"e": 31341,
"s": 31143,
"text": "distance traveled by first car (with speed of 50 km/h) = 50*1 = 50 km\nAnd, distance traveled by second car (with speed of 60 km/h) = 60*1 = 60 km\n\nSo, distance between these cars = 60 - 50 = 10 km "
},
{
"code": null,
"e": 31543,
"s": 31341,
"text": "distance traveled by first car (with speed of 50 km/h) = 50*2 = 100 km\nAnd, distance traveled by second car (with speed of 60 km/h) = 60*2 = 120 km\n\nSo, distance between these cars = 120 - 100 = 20 km "
},
{
"code": null,
"e": 31692,
"s": 31543,
"text": "→ (distance traveled by second car) - (distance traveled by first car) = 20 km\n→ (S2*T) - (S1*T) = 20 \n→ (60*T) - (50*T) = 20 \n→ 10*T = 20 \n→ T = 2 "
},
{
"code": null,
"e": 31776,
"s": 31692,
"text": "→ 10*x = 8*(x + 150) \n→ 10*x = 8*x + 8*150\n→ 2*x = 8*150\n→ x = 8*150 / 2\n→ x = 600 "
},
{
"code": null,
"e": 31798,
"s": 31776,
"text": "10*x = 10*600 = 6000 "
},
{
"code": null,
"e": 31816,
"s": 31798,
"text": "= 10+20+20 \n= 50 "
},
{
"code": null,
"e": 31838,
"s": 31816,
"text": "= 80+20+20+40 \n= 160 "
},
{
"code": null,
"e": 31864,
"s": 31838,
"text": "= (50/160)*100\n= 31.25 % "
},
{
"code": null,
"e": 31904,
"s": 31864,
"text": "= 60 + 80 + 30 + 38 + 2 + 10 + 5\n= 225 "
},
{
"code": null,
"e": 31935,
"s": 31904,
"text": "x*0.25 = 225\n= 225/0.25\n= 900 "
},
{
"code": null,
"e": 32015,
"s": 31935,
"text": "Request by X: Due to pollen allergy, I want to avoid a wing next to the garden."
},
{
"code": null,
"e": 32123,
"s": 32015,
"text": "Request by Y: I want to live as far from the washrooms as possible since I am very much sensitive to smell."
},
{
"code": null,
"e": 32199,
"s": 32123,
"text": "Request by Z: I believe in Vaastu and so I want to stay in South-West wing."
},
{
"code": null,
"e": 32297,
"s": 32199,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 32371,
"s": 32297,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 32408,
"s": 32371,
"text": "Software Testing - Web Based Testing"
},
{
"code": null,
"e": 32460,
"s": 32408,
"text": "What are the different ways of Data Representation?"
},
{
"code": null,
"e": 32495,
"s": 32460,
"text": "Bash Script - Command Substitution"
},
{
"code": null,
"e": 32544,
"s": 32495,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 32607,
"s": 32544,
"text": "7 Highest Paying Programming Languages For Freelancers in 2022"
},
{
"code": null,
"e": 32632,
"s": 32607,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32670,
"s": 32632,
"text": "How to Create a Shell Script in linux"
},
{
"code": null,
"e": 32708,
"s": 32670,
"text": "How To Convert Numpy Array To Tensor?"
}
] |
Django Interview Questions & Answers With Practical Tips For Junior Developers
|
09 Sep, 2021
Django... Isn’t it your favorite framework? (especially if you are new to the programming world)
Yes! It is...
Did you try to learn this framework and build some projects?
If the answer is Yes then here is the next question...
Did you understand the complete flow of the project?
Again if the answer is Yes then here is another question (don’t get annoyed now...lol...)
Can you articulate the concepts in your own words which you have learned from your project?
If the answer is again Yes then congratulations you don’t need to read tons of articles about the Django interview questions... You just need to take a look at the questions and the answer will automatically pop up in your mind.
This framework is the most popular framework in industries and this is the reason most people are jumping into it (surely money is another factor). If you’re an experienced developer then surely you will check the reason behind its popularity and for that, you will check what problems Django can resolve in an application? Why it’s better than other frameworks or why it’s good to build the application on Django?
If you already have put your efforts into building some projects and understanding the concept of this framework then all you just need to do is to apply for the right jobs and face the interviews.
Now coming to the main title of this blog, we will discuss some Django interview questions which you may encounter in interviews but before we go ahead we recommend you carefully read the lines given below.
If you’re someone who is just looking for the interview questions and believes that reading these questions and remembering the answer to them will help you in clearing the interview rounds then my friend this is not going to work when you will be facing the interviews.
Always remember that an interviewer will prefer to hire a candidate who can have practical exposure and who can solve the problems in Django applications. Most probably they won’t hire someone who has come for the interview reading some 20-30 Django interview questions without any practical exposure.
Reading only the 30-40 interview questions (any language or the framework) and facing the interview without any practical exposure won’t work in software development. Because there you won’t be asked to write the papers for some theoretical exams.
There you will have to build the actual software and in this case, no matter what kind of questions the interviewer will ask, his/her only intention would be to check the ability of the candidate about the understanding of the framework, about the understanding of the concepts, about the understanding of how things are connected, about the understanding of the complete flow of the framework.
You can read the theory, read the question and then build some projects, or you can build some projects and then read the theory and the interview question. But here the whole idea is to do both...don’t miss a single thing.
Now let’s start discussing the interview questions...
We will also discuss what kind of answer an interviewer is looking for or why he/she asked a specific question.
Whatever questions we are going to discuss here, do not expect the same questions in each interview. Not every interview is going to be the same. The questions can be different and depend on the person who is taking your interview. But yes these are the most basic ones and the most common questions, and we have compiled the question considering the position of junior level Django developer.
Most likely these questions are asked in the interviews to check the ability of the candidate for at least a basic understanding of the framework. Before applying for the jobs make sure that you mention the project in your portfolio. Mention the things that you have done in your project using this amazing framework. What features you have built, or what problems you have resolved. This will give you an insight that how deeply you understand this framework.
The interviewer doesn’t want to conduct a Q&A session. He/she will try to build a relationship with you and he/she will try to understand you. So in case if the interviewer is asking about the project or what you’re currently working on then smoothly speak about it and try to control the interview. Expand your answer and go into the details instead of just giving the answer in yes or no.
Don’t be fake in interviews. Build a rapport with the interviewer and treat your interviewer as a team member or mentor who is going to work with you on some project in the future. When you get into the detail of the project the interviewer understand that what things you already know. You just limit the number of questions for yourself and the interviewer won’t be asking the 50 numbers of questions from his/her list.
If you are stuck on some question then don’t give a wrong answer just let the interviewers know if you know anything about the project. You can say that “I have done this in my project, but things are just blanking out. I don’t remember what the exact command was, but I think it’s something like this “. Now you can try to elaborate on those questions. It’s completely ok for the interviewer, and it won’t make any negative impression.
Let’s start with the questions now...
1. How comfortable are you with Python?
Note: The interviewer is looking for some prerequisites. He/she wants to know your Python skills. How familiar are you with it and what have you done with Python. He won’t be spending too much time on that but obviously, if you’re a Django developer then you will need to know that.
Answer: Let the interviewer know what courses you have taken, what kind of project you have built, how much you have expanded yourself in this language. Books, and the other resources, etc.
2. What is Django?
Note: From here the interviewer will dig into the detail and he/she will try to understand that how well you know about Django. Of course, this question is also depends on how well you explained your Django project mentioned in your portfolio. If the interviewer will be in doubt about your knowledge in Django then he/she will throw this question for sure.
Answer: “Django is a Python-based web framework. Just like we use ExpressJS or NodeJS for JavaScript and Laravel for PHP to build the backend part of the application, Django is for Python for the same purpose”. It’s not restricted to give the same response, but this response will clarify that you know “what frameworks are”. If you mention a couple of frameworks in your response then the interviewer will understand that you know the concept of frameworks, and it’s not needed to get into the detail of the concept of the framework.
3. What can you build with Django?
Note: Basically the interviewer is expecting the answer that you know the capabilities of Django. You understand what Django is used for. Typically, people give the example that Django can be used to build social media networks, e-commerce websites but if you want to give a good response then mention some companies’ names.
Answer: “Django capabilities are anything and companies like Udemy, Pinterest, Instagram, Dropbox uses it.” The interviewer will understand that you know Django and you understand that it’s capable of a lot. You’re understanding what is done and what it can do. You can also mention the APIs and how APIs are helpful in building some good applications.
Proper explanation of questions no. 4 and 5 is really important. If you won’t be able to explain that what Django is and what it’s capable to do, then the interviewer will be concerned.
From here the interviewer may get into the detail and he/she is will rapid-fire some questions to make sure that you have worked with it. You haven’t just heard about this framework, or you haven’t done any kind of rote learning. The interviewer will judge pretty lightly here because nobody remembers each and every command or the exact code in development. Most people just Google out the things and solves the problem. But you should remember the most basic commands or the most basic things in Django.
4. What’s the difference between a Project and App?
Note: Include examples in your answer to differentiate between both.
Answer: “A project is like an overall environment. It’s the base of your website and an app is like a component of that website that holds the project logic. Project is like configuration of your website and app is the component of your project which are created to do a specific thing in your application.
A project is composed of many apps, so a single project can have n number of apps and a single app can be in several projects.” Here you can give the example of facebook.com and structure it out to explain it better. Facebook will be treated as a project and news feed, profile, groups are the components of the different apps within the entire Facebook.
So for different tasks, a project can be divided into various small apps and these apps are focused on a specific functional area.
5. How do we initialize a project?
Answer: $ django-admin startproject projectname
6. How do we initialize an app?
Answer: $ python manage.py startapp appname
7. What does the settings.py file do?
Note: settings.py is the most important file in your project that holds all the configurations of your application. Give your best explanation of the settings.py file. The interviewer will check your technical understanding of Django.
Answer: settings.py holds the configuration of the project like your database connection, apps configuration, absolute path values, static files configuration, and the overall command center to the project.
8. How do we start our development server?
Answer: $ python manage.py runserver
9. What is the MVT structure in Django? What are models? What are views? What are templates?
Answer: Models are the class-based representations of database tables. It represents the database structures.
The view is basically the business logic, and it doesn’t deal with how the data looks (like in MVC structure). It represents what the data actually is. View decides what data should be triggered when a specific URL is hit. What needs to be returned like templates, responses, and so on. Basically, views return the templates, and it is the connection between the model and the templates.
The template layer returns the HTML layout. It deals with the presentation part of the responses. How the response will be presented to the user.
With this answer, the interviewer will see your understanding of the model, view, and template.
10. What is Django Admin Panel?
Note: This is one of the key features of Django so the interviewer may ask this question to you.
Answer: Django admin panel is a kind of graphical user interface that is used for administrative tasks. Admin panel comes by default built with Django and you don’t need to build it from scratch as we do in other languages. You get the quick setup of the admin panel to manage your data and to access it. The development process becomes faster and also it becomes easy for the developers to perform administrative activities.
11. What are URL patterns?
Note: This is another basic stuff in Django which you should definitely know. The interviewer wants to know that you understand how to configure URLs in Django app.
Answer: Explain properly that how routing works in Django using URL patterns.
URLs decide the website routing. We create a python module or a file urls.py in the app. This file decides the navigation of your website. When a user hits a specific URL path in the browser it gets matched with the URLs present in the urls.py file. After that, a corresponding view method is retrieved and then the user gets the response back for the requested URL.
12. What do the following commands do?
python manage.py makemigrations
python manage.py migrate
Note: This is another basic stuff in Django. You just need to explain what is the role of both commands in the Django application.
Answer: makemigration command scan the model in your application and create a new set of migration based on the changes we make in the model file. This command generates the SQL command, and we get a new migration file after executing this command. Tables won’t be created in the database after running this command.
Now to apply these changes in our database we execute migrate command. migrate command executes the SQL commands (generated in makemigrations) and enforces the changes to the database. Tables will be created after running this command.
13. Where do we store templates?
Answer: There are different ways to store templates. We can store it in the default app structure. Django apps typically tell you to store in a folder called templates, in a subfolder (whatever your app name is), and then you can put all the templates there. You can also manually assign this value into the settings.py file. In this file, you will find a variable ‘templates’ and in this variable, you will find a list called DIRS. Here you can mention the path of your template and let Django know where to find them.
14. Django Templating Language: What do double curly braces mean and what does it mean with the percent signs? (the interviewer may show an example of that)
<h2>{{name}}</h2>
Note: The interviewer wants to know that you know very well that how to work with templating. You have a good understanding of it, and you know how to pass data and then set variables in the template.
Answer: Curly braces are just a placeholder for variables. This way we can output dynamic data. Curly braces with percent signs are code blocks where we can write the backend Pythonic logic in our templates. Now you can write one of the examples here. You can write a for loop or an if statement in the code block of the template.
{% for customer in customers %}
<tr>
<td>{{customer.name}}</td>
</tr>
{% endfor %}
15. How you can include and inherit files in your application?
Answer: “Using the include tag we can include the section of another HTML template”. A proper explanation of inherit and extends would be “If we have a main.html file, and we need to inherit this file then we can use the extends tag in the template where we want to extend it, and then we can add in block tags to extend the template.” (Read the article Django Template Tags to elaborate your answer more)
{% extends 'base/main.html' %}
{% include 'base/navbar.html' %}
{% block content %}
<h2>Template</h2>
{% endblock content %}
16. What database system do you prefer to use and how can we set up the database in Django application?
Note: By default, Django comes with the SQLite database but in real life, companies are not going to use it. So here the interviewer wants to listen that you know something beyond the SQLite database system, and you aren’t just relying on the default database system. You also understand how to connect another database like MySQL or PostgreSQL. Mention where you can configure your database in the Django project.
Answer: We need to configure our database in the settings.py file. By default, SQLite is mention there, and we need to change this setting accordingly. You can also give an example of setting a database like MySQL or PostgreSQL.
17. What are static files?
Answer: This is the place where we store the additional files like CSS files, JavaScript files, images, or any kind of static files. We typically store them in their separate folder like in the js folder all we store all the JavaScript files and in the images folder, we store all the images. We store these files in the subdirectory of the project app named static.
18. What is Media Root?
Answer: Media root is used to upload user-generated content. We can serve user-uploaded media files from MEDIA_ROOT.
19. How would you query all the items in the database table?
Answer: XYZ.objects.all() Where XYZ is some class created in the model.
20. How to query one item from the database table?
Answer: XYZ.objects.get(id=1) Where XYZ is some class created in the model.
Note: We just have mentioned two examples of questions of database queries, but the interviewer may ask more queries. He/She can add more complexity to the query, and then you will have to answer it. So prepare yourself with more database queries in Django.
21. What are CSRF Tokens?
Answer: CSRF tokens help against Cross-Site Request Forgeries attacks. This can be sent from a malicious site. Django comes with built-in protection against CSRF. We can use it in post, put or delete requests. We typically send these with our forms. In short, we’re just protecting our data from any kind of malicious activity. We can include { % csrf_token % } in our template’s form to protect our data.
22. HTML/CSS/Bootstrap skills level?
Note: This is another prerequisite question because in development you will surely encounter the code in HTML and CSS. You will have to deal with it dynamically using Django. So the interviewers want to check your basic understanding of both.
Answer: Again if you have built some projects then let them know what things you have done in HTML and CSS or how you dealt with it dynamically. How pages or the templates were built and how you coded them with Django in your application. You can also expand the answer by mentioning what kind of templates or page you designed in HTML and CSS and how you rendered it dynamically.
23. Have you worked on JavaScript? Any experience in it?
Note: If you don’t know JavaScript then most probably the interviewer is not going to dock you for this, but it would be a nice plus if you have worked on it while building your project in Django. As a web developer, you will be working with JavaScript a lot, and having prior experience in it will give you some advantage. If you don’t know then it’s completely fine but knowledge of JavaScript will increase the chances of getting selected.
Answer: If you know JavaScript then let the interviewer know that what you did in JavaScript or what kind of features you built-in JavaScript along with Django.
Interview questions are not limited here for Django. There are a lot of concepts to know, but the main thing is that what you have mentioned in your portfolio and what you have done in your project. Most of the questions you will find from there. It also depends on the interviewer, company name, nature of work, and the position you’re applying for. Build the project, face the problems, solve the issues, and you will learn more about Django. That’s how you will be more prepared for the Django interview questions.
Python Django
GBlog
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
What is Hashing | A Complete Tutorial
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa
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": 52,
"s": 24,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 149,
"s": 52,
"text": "Django... Isn’t it your favorite framework? (especially if you are new to the programming world)"
},
{
"code": null,
"e": 163,
"s": 149,
"text": "Yes! It is..."
},
{
"code": null,
"e": 224,
"s": 163,
"text": "Did you try to learn this framework and build some projects?"
},
{
"code": null,
"e": 279,
"s": 224,
"text": "If the answer is Yes then here is the next question..."
},
{
"code": null,
"e": 332,
"s": 279,
"text": "Did you understand the complete flow of the project?"
},
{
"code": null,
"e": 422,
"s": 332,
"text": "Again if the answer is Yes then here is another question (don’t get annoyed now...lol...)"
},
{
"code": null,
"e": 514,
"s": 422,
"text": "Can you articulate the concepts in your own words which you have learned from your project?"
},
{
"code": null,
"e": 743,
"s": 514,
"text": "If the answer is again Yes then congratulations you don’t need to read tons of articles about the Django interview questions... You just need to take a look at the questions and the answer will automatically pop up in your mind."
},
{
"code": null,
"e": 1159,
"s": 743,
"text": "This framework is the most popular framework in industries and this is the reason most people are jumping into it (surely money is another factor). If you’re an experienced developer then surely you will check the reason behind its popularity and for that, you will check what problems Django can resolve in an application? Why it’s better than other frameworks or why it’s good to build the application on Django? "
},
{
"code": null,
"e": 1357,
"s": 1159,
"text": "If you already have put your efforts into building some projects and understanding the concept of this framework then all you just need to do is to apply for the right jobs and face the interviews."
},
{
"code": null,
"e": 1564,
"s": 1357,
"text": "Now coming to the main title of this blog, we will discuss some Django interview questions which you may encounter in interviews but before we go ahead we recommend you carefully read the lines given below."
},
{
"code": null,
"e": 1835,
"s": 1564,
"text": "If you’re someone who is just looking for the interview questions and believes that reading these questions and remembering the answer to them will help you in clearing the interview rounds then my friend this is not going to work when you will be facing the interviews."
},
{
"code": null,
"e": 2137,
"s": 1835,
"text": "Always remember that an interviewer will prefer to hire a candidate who can have practical exposure and who can solve the problems in Django applications. Most probably they won’t hire someone who has come for the interview reading some 20-30 Django interview questions without any practical exposure."
},
{
"code": null,
"e": 2386,
"s": 2137,
"text": "Reading only the 30-40 interview questions (any language or the framework) and facing the interview without any practical exposure won’t work in software development. Because there you won’t be asked to write the papers for some theoretical exams. "
},
{
"code": null,
"e": 2782,
"s": 2386,
"text": "There you will have to build the actual software and in this case, no matter what kind of questions the interviewer will ask, his/her only intention would be to check the ability of the candidate about the understanding of the framework, about the understanding of the concepts, about the understanding of how things are connected, about the understanding of the complete flow of the framework. "
},
{
"code": null,
"e": 3007,
"s": 2782,
"text": "You can read the theory, read the question and then build some projects, or you can build some projects and then read the theory and the interview question. But here the whole idea is to do both...don’t miss a single thing. "
},
{
"code": null,
"e": 3061,
"s": 3007,
"text": "Now let’s start discussing the interview questions..."
},
{
"code": null,
"e": 3173,
"s": 3061,
"text": "We will also discuss what kind of answer an interviewer is looking for or why he/she asked a specific question."
},
{
"code": null,
"e": 3567,
"s": 3173,
"text": "Whatever questions we are going to discuss here, do not expect the same questions in each interview. Not every interview is going to be the same. The questions can be different and depend on the person who is taking your interview. But yes these are the most basic ones and the most common questions, and we have compiled the question considering the position of junior level Django developer."
},
{
"code": null,
"e": 4029,
"s": 3567,
"text": "Most likely these questions are asked in the interviews to check the ability of the candidate for at least a basic understanding of the framework. Before applying for the jobs make sure that you mention the project in your portfolio. Mention the things that you have done in your project using this amazing framework. What features you have built, or what problems you have resolved. This will give you an insight that how deeply you understand this framework."
},
{
"code": null,
"e": 4421,
"s": 4029,
"text": "The interviewer doesn’t want to conduct a Q&A session. He/she will try to build a relationship with you and he/she will try to understand you. So in case if the interviewer is asking about the project or what you’re currently working on then smoothly speak about it and try to control the interview. Expand your answer and go into the details instead of just giving the answer in yes or no. "
},
{
"code": null,
"e": 4844,
"s": 4421,
"text": "Don’t be fake in interviews. Build a rapport with the interviewer and treat your interviewer as a team member or mentor who is going to work with you on some project in the future. When you get into the detail of the project the interviewer understand that what things you already know. You just limit the number of questions for yourself and the interviewer won’t be asking the 50 numbers of questions from his/her list. "
},
{
"code": null,
"e": 5281,
"s": 4844,
"text": "If you are stuck on some question then don’t give a wrong answer just let the interviewers know if you know anything about the project. You can say that “I have done this in my project, but things are just blanking out. I don’t remember what the exact command was, but I think it’s something like this “. Now you can try to elaborate on those questions. It’s completely ok for the interviewer, and it won’t make any negative impression."
},
{
"code": null,
"e": 5319,
"s": 5281,
"text": "Let’s start with the questions now..."
},
{
"code": null,
"e": 5360,
"s": 5319,
"text": "1. How comfortable are you with Python? "
},
{
"code": null,
"e": 5644,
"s": 5360,
"text": "Note: The interviewer is looking for some prerequisites. He/she wants to know your Python skills. How familiar are you with it and what have you done with Python. He won’t be spending too much time on that but obviously, if you’re a Django developer then you will need to know that. "
},
{
"code": null,
"e": 5835,
"s": 5644,
"text": "Answer: Let the interviewer know what courses you have taken, what kind of project you have built, how much you have expanded yourself in this language. Books, and the other resources, etc. "
},
{
"code": null,
"e": 5854,
"s": 5835,
"text": "2. What is Django?"
},
{
"code": null,
"e": 6213,
"s": 5854,
"text": "Note: From here the interviewer will dig into the detail and he/she will try to understand that how well you know about Django. Of course, this question is also depends on how well you explained your Django project mentioned in your portfolio. If the interviewer will be in doubt about your knowledge in Django then he/she will throw this question for sure. "
},
{
"code": null,
"e": 6749,
"s": 6213,
"text": "Answer: “Django is a Python-based web framework. Just like we use ExpressJS or NodeJS for JavaScript and Laravel for PHP to build the backend part of the application, Django is for Python for the same purpose”. It’s not restricted to give the same response, but this response will clarify that you know “what frameworks are”. If you mention a couple of frameworks in your response then the interviewer will understand that you know the concept of frameworks, and it’s not needed to get into the detail of the concept of the framework. "
},
{
"code": null,
"e": 6784,
"s": 6749,
"text": "3. What can you build with Django?"
},
{
"code": null,
"e": 7109,
"s": 6784,
"text": "Note: Basically the interviewer is expecting the answer that you know the capabilities of Django. You understand what Django is used for. Typically, people give the example that Django can be used to build social media networks, e-commerce websites but if you want to give a good response then mention some companies’ names."
},
{
"code": null,
"e": 7463,
"s": 7109,
"text": "Answer: “Django capabilities are anything and companies like Udemy, Pinterest, Instagram, Dropbox uses it.” The interviewer will understand that you know Django and you understand that it’s capable of a lot. You’re understanding what is done and what it can do. You can also mention the APIs and how APIs are helpful in building some good applications. "
},
{
"code": null,
"e": 7650,
"s": 7463,
"text": "Proper explanation of questions no. 4 and 5 is really important. If you won’t be able to explain that what Django is and what it’s capable to do, then the interviewer will be concerned. "
},
{
"code": null,
"e": 8157,
"s": 7650,
"text": "From here the interviewer may get into the detail and he/she is will rapid-fire some questions to make sure that you have worked with it. You haven’t just heard about this framework, or you haven’t done any kind of rote learning. The interviewer will judge pretty lightly here because nobody remembers each and every command or the exact code in development. Most people just Google out the things and solves the problem. But you should remember the most basic commands or the most basic things in Django. "
},
{
"code": null,
"e": 8209,
"s": 8157,
"text": "4. What’s the difference between a Project and App?"
},
{
"code": null,
"e": 8279,
"s": 8209,
"text": "Note: Include examples in your answer to differentiate between both. "
},
{
"code": null,
"e": 8587,
"s": 8279,
"text": "Answer: “A project is like an overall environment. It’s the base of your website and an app is like a component of that website that holds the project logic. Project is like configuration of your website and app is the component of your project which are created to do a specific thing in your application. "
},
{
"code": null,
"e": 8942,
"s": 8587,
"text": "A project is composed of many apps, so a single project can have n number of apps and a single app can be in several projects.” Here you can give the example of facebook.com and structure it out to explain it better. Facebook will be treated as a project and news feed, profile, groups are the components of the different apps within the entire Facebook."
},
{
"code": null,
"e": 9073,
"s": 8942,
"text": "So for different tasks, a project can be divided into various small apps and these apps are focused on a specific functional area."
},
{
"code": null,
"e": 9108,
"s": 9073,
"text": "5. How do we initialize a project?"
},
{
"code": null,
"e": 9156,
"s": 9108,
"text": "Answer: $ django-admin startproject projectname"
},
{
"code": null,
"e": 9188,
"s": 9156,
"text": "6. How do we initialize an app?"
},
{
"code": null,
"e": 9232,
"s": 9188,
"text": "Answer: $ python manage.py startapp appname"
},
{
"code": null,
"e": 9270,
"s": 9232,
"text": "7. What does the settings.py file do?"
},
{
"code": null,
"e": 9505,
"s": 9270,
"text": "Note: settings.py is the most important file in your project that holds all the configurations of your application. Give your best explanation of the settings.py file. The interviewer will check your technical understanding of Django."
},
{
"code": null,
"e": 9713,
"s": 9505,
"text": "Answer: settings.py holds the configuration of the project like your database connection, apps configuration, absolute path values, static files configuration, and the overall command center to the project. "
},
{
"code": null,
"e": 9756,
"s": 9713,
"text": "8. How do we start our development server?"
},
{
"code": null,
"e": 9793,
"s": 9756,
"text": "Answer: $ python manage.py runserver"
},
{
"code": null,
"e": 9886,
"s": 9793,
"text": "9. What is the MVT structure in Django? What are models? What are views? What are templates?"
},
{
"code": null,
"e": 9997,
"s": 9886,
"text": "Answer: Models are the class-based representations of database tables. It represents the database structures. "
},
{
"code": null,
"e": 10387,
"s": 9997,
"text": "The view is basically the business logic, and it doesn’t deal with how the data looks (like in MVC structure). It represents what the data actually is. View decides what data should be triggered when a specific URL is hit. What needs to be returned like templates, responses, and so on. Basically, views return the templates, and it is the connection between the model and the templates. "
},
{
"code": null,
"e": 10533,
"s": 10387,
"text": "The template layer returns the HTML layout. It deals with the presentation part of the responses. How the response will be presented to the user."
},
{
"code": null,
"e": 10631,
"s": 10533,
"text": "With this answer, the interviewer will see your understanding of the model, view, and template. "
},
{
"code": null,
"e": 10663,
"s": 10631,
"text": "10. What is Django Admin Panel?"
},
{
"code": null,
"e": 10761,
"s": 10663,
"text": "Note: This is one of the key features of Django so the interviewer may ask this question to you. "
},
{
"code": null,
"e": 11187,
"s": 10761,
"text": "Answer: Django admin panel is a kind of graphical user interface that is used for administrative tasks. Admin panel comes by default built with Django and you don’t need to build it from scratch as we do in other languages. You get the quick setup of the admin panel to manage your data and to access it. The development process becomes faster and also it becomes easy for the developers to perform administrative activities."
},
{
"code": null,
"e": 11214,
"s": 11187,
"text": "11. What are URL patterns?"
},
{
"code": null,
"e": 11380,
"s": 11214,
"text": "Note: This is another basic stuff in Django which you should definitely know. The interviewer wants to know that you understand how to configure URLs in Django app. "
},
{
"code": null,
"e": 11459,
"s": 11380,
"text": "Answer: Explain properly that how routing works in Django using URL patterns. "
},
{
"code": null,
"e": 11827,
"s": 11459,
"text": "URLs decide the website routing. We create a python module or a file urls.py in the app. This file decides the navigation of your website. When a user hits a specific URL path in the browser it gets matched with the URLs present in the urls.py file. After that, a corresponding view method is retrieved and then the user gets the response back for the requested URL. "
},
{
"code": null,
"e": 11866,
"s": 11827,
"text": "12. What do the following commands do?"
},
{
"code": null,
"e": 11898,
"s": 11866,
"text": "python manage.py makemigrations"
},
{
"code": null,
"e": 11923,
"s": 11898,
"text": "python manage.py migrate"
},
{
"code": null,
"e": 12055,
"s": 11923,
"text": "Note: This is another basic stuff in Django. You just need to explain what is the role of both commands in the Django application. "
},
{
"code": null,
"e": 12373,
"s": 12055,
"text": "Answer: makemigration command scan the model in your application and create a new set of migration based on the changes we make in the model file. This command generates the SQL command, and we get a new migration file after executing this command. Tables won’t be created in the database after running this command. "
},
{
"code": null,
"e": 12609,
"s": 12373,
"text": "Now to apply these changes in our database we execute migrate command. migrate command executes the SQL commands (generated in makemigrations) and enforces the changes to the database. Tables will be created after running this command."
},
{
"code": null,
"e": 12643,
"s": 12609,
"text": "13. Where do we store templates? "
},
{
"code": null,
"e": 13164,
"s": 12643,
"text": "Answer: There are different ways to store templates. We can store it in the default app structure. Django apps typically tell you to store in a folder called templates, in a subfolder (whatever your app name is), and then you can put all the templates there. You can also manually assign this value into the settings.py file. In this file, you will find a variable ‘templates’ and in this variable, you will find a list called DIRS. Here you can mention the path of your template and let Django know where to find them. "
},
{
"code": null,
"e": 13321,
"s": 13164,
"text": "14. Django Templating Language: What do double curly braces mean and what does it mean with the percent signs? (the interviewer may show an example of that)"
},
{
"code": null,
"e": 13339,
"s": 13321,
"text": "<h2>{{name}}</h2>"
},
{
"code": null,
"e": 13541,
"s": 13339,
"text": "Note: The interviewer wants to know that you know very well that how to work with templating. You have a good understanding of it, and you know how to pass data and then set variables in the template. "
},
{
"code": null,
"e": 13873,
"s": 13541,
"text": "Answer: Curly braces are just a placeholder for variables. This way we can output dynamic data. Curly braces with percent signs are code blocks where we can write the backend Pythonic logic in our templates. Now you can write one of the examples here. You can write a for loop or an if statement in the code block of the template. "
},
{
"code": null,
"e": 13959,
"s": 13873,
"text": "{% for customer in customers %}\n<tr>\n <td>{{customer.name}}</td>\n</tr>\n{% endfor %}"
},
{
"code": null,
"e": 14022,
"s": 13959,
"text": "15. How you can include and inherit files in your application?"
},
{
"code": null,
"e": 14428,
"s": 14022,
"text": "Answer: “Using the include tag we can include the section of another HTML template”. A proper explanation of inherit and extends would be “If we have a main.html file, and we need to inherit this file then we can use the extends tag in the template where we want to extend it, and then we can add in block tags to extend the template.” (Read the article Django Template Tags to elaborate your answer more)"
},
{
"code": null,
"e": 14558,
"s": 14428,
"text": "{% extends 'base/main.html' %}\n{% include 'base/navbar.html' %}\n{% block content %}\n <h2>Template</h2>\n{% endblock content %}"
},
{
"code": null,
"e": 14662,
"s": 14558,
"text": "16. What database system do you prefer to use and how can we set up the database in Django application?"
},
{
"code": null,
"e": 15078,
"s": 14662,
"text": "Note: By default, Django comes with the SQLite database but in real life, companies are not going to use it. So here the interviewer wants to listen that you know something beyond the SQLite database system, and you aren’t just relying on the default database system. You also understand how to connect another database like MySQL or PostgreSQL. Mention where you can configure your database in the Django project. "
},
{
"code": null,
"e": 15308,
"s": 15078,
"text": "Answer: We need to configure our database in the settings.py file. By default, SQLite is mention there, and we need to change this setting accordingly. You can also give an example of setting a database like MySQL or PostgreSQL. "
},
{
"code": null,
"e": 15335,
"s": 15308,
"text": "17. What are static files?"
},
{
"code": null,
"e": 15702,
"s": 15335,
"text": "Answer: This is the place where we store the additional files like CSS files, JavaScript files, images, or any kind of static files. We typically store them in their separate folder like in the js folder all we store all the JavaScript files and in the images folder, we store all the images. We store these files in the subdirectory of the project app named static."
},
{
"code": null,
"e": 15726,
"s": 15702,
"text": "18. What is Media Root?"
},
{
"code": null,
"e": 15844,
"s": 15726,
"text": "Answer: Media root is used to upload user-generated content. We can serve user-uploaded media files from MEDIA_ROOT. "
},
{
"code": null,
"e": 15905,
"s": 15844,
"text": "19. How would you query all the items in the database table?"
},
{
"code": null,
"e": 15977,
"s": 15905,
"text": "Answer: XYZ.objects.all() Where XYZ is some class created in the model."
},
{
"code": null,
"e": 16028,
"s": 15977,
"text": "20. How to query one item from the database table?"
},
{
"code": null,
"e": 16104,
"s": 16028,
"text": "Answer: XYZ.objects.get(id=1) Where XYZ is some class created in the model."
},
{
"code": null,
"e": 16362,
"s": 16104,
"text": "Note: We just have mentioned two examples of questions of database queries, but the interviewer may ask more queries. He/She can add more complexity to the query, and then you will have to answer it. So prepare yourself with more database queries in Django."
},
{
"code": null,
"e": 16389,
"s": 16362,
"text": "21. What are CSRF Tokens? "
},
{
"code": null,
"e": 16796,
"s": 16389,
"text": "Answer: CSRF tokens help against Cross-Site Request Forgeries attacks. This can be sent from a malicious site. Django comes with built-in protection against CSRF. We can use it in post, put or delete requests. We typically send these with our forms. In short, we’re just protecting our data from any kind of malicious activity. We can include { % csrf_token % } in our template’s form to protect our data. "
},
{
"code": null,
"e": 16833,
"s": 16796,
"text": "22. HTML/CSS/Bootstrap skills level?"
},
{
"code": null,
"e": 17077,
"s": 16833,
"text": "Note: This is another prerequisite question because in development you will surely encounter the code in HTML and CSS. You will have to deal with it dynamically using Django. So the interviewers want to check your basic understanding of both. "
},
{
"code": null,
"e": 17459,
"s": 17077,
"text": "Answer: Again if you have built some projects then let them know what things you have done in HTML and CSS or how you dealt with it dynamically. How pages or the templates were built and how you coded them with Django in your application. You can also expand the answer by mentioning what kind of templates or page you designed in HTML and CSS and how you rendered it dynamically. "
},
{
"code": null,
"e": 17516,
"s": 17459,
"text": "23. Have you worked on JavaScript? Any experience in it?"
},
{
"code": null,
"e": 17960,
"s": 17516,
"text": "Note: If you don’t know JavaScript then most probably the interviewer is not going to dock you for this, but it would be a nice plus if you have worked on it while building your project in Django. As a web developer, you will be working with JavaScript a lot, and having prior experience in it will give you some advantage. If you don’t know then it’s completely fine but knowledge of JavaScript will increase the chances of getting selected. "
},
{
"code": null,
"e": 18122,
"s": 17960,
"text": "Answer: If you know JavaScript then let the interviewer know that what you did in JavaScript or what kind of features you built-in JavaScript along with Django. "
},
{
"code": null,
"e": 18641,
"s": 18122,
"text": "Interview questions are not limited here for Django. There are a lot of concepts to know, but the main thing is that what you have mentioned in your portfolio and what you have done in your project. Most of the questions you will find from there. It also depends on the interviewer, company name, nature of work, and the position you’re applying for. Build the project, face the problems, solve the issues, and you will learn more about Django. That’s how you will be more prepared for the Django interview questions. "
},
{
"code": null,
"e": 18655,
"s": 18641,
"text": "Python Django"
},
{
"code": null,
"e": 18661,
"s": 18655,
"text": "GBlog"
},
{
"code": null,
"e": 18668,
"s": 18661,
"text": "Python"
},
{
"code": null,
"e": 18766,
"s": 18668,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 18821,
"s": 18766,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 18858,
"s": 18821,
"text": "Geek Streak - 24 Days POTD Challenge"
},
{
"code": null,
"e": 18896,
"s": 18858,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 18962,
"s": 18896,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 19033,
"s": 18962,
"text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa"
},
{
"code": null,
"e": 19061,
"s": 19033,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 19111,
"s": 19061,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 19133,
"s": 19111,
"text": "Python map() function"
}
] |
Use EJS as Template Engine in Node.js
|
09 Jul, 2021
EJS: EJS or Embedded Javascript Templating is a templating engine used by Node.js. Template engine helps to create an HTML template with minimal code. Also, it can inject data into HTML template at the client side and produce the final HTML. EJS is a simple templating language which is used to generate HTML markup with plain JavaScript. It also helps to embed JavaScript to HTML pages. To begin with, using EJS as templating engine we need to install EJS using given command:
npm install ejs --save
Note: npm in the above commands stands for the node package manager, a place where install all the dependencies. –save flag is no longer needed after Node 5.0.0 version, as all the modules that we now install will be added to dependencies. Now, the first thing we need to do is to set EJS as our templating engine with Express which is a Node.js web application server framework, which is specifically designed for building single-page, multi-page, and hybrid web applications. It has become the standard server framework for node.js.
Javascript
// Set express as Node.js web application// server framework.// To install express before using it as// an application server by using// "npm install express" command.var express = require('express');var app = express(); // Set EJS as templating engineapp.set('view engine', 'ejs');
The default behavior of EJS is that it looks into the ‘views’ folder for the templates to render. So, let’s make a ‘views’ folder in our main node project folder and make a file named “home.ejs” which is to be served on some desired request in our node project. The content of this page is:
HTML
<!DOCTYPE html><html> <head> <title>Home Page</title> <style type="text/css" media="screen"> body { background-color: skyblue; text-decoration-color: white; font-size:7em; } </style></head> <body> <center>This is our home page.</center></body> </html>
Now, we will render this page on a certain request by the user as:
Javascript
app.get('/', (req, res)=>{ // The render method takes the name of the HTML// page to be rendered as input// This page should be in the views folder// in the root directory.res.render('home'); });
Now, the page home.ejs will be displayed on requesting localhost. To add dynamic content this render method takes a second parameter which is an object. This is done as:
Javascript
app.get('/', (req, res)=>{ // The render method takes the name of the HTML// page to be rendered as input.// This page should be in views folder in// the root directory.// We can pass multiple properties and values// as an object, here we are passing the only nameres.render('home', {name:'Akashdeep'}); }); var server = app.listen(4000, function(){ console.log('listening to port 4000')});
Now, We will embed name to HTML page as:
html
<!DOCTYPE html><html><head> <title>Home Page</title> <style type="text/css" media="screen"> body { background-color: skyblue; text-decoration-color: white; font-size:7em; } </style></head><body> <center> This is our home page.<br/> Welcome <%=name%>, to our home page. </center></body></html>
It is used to embed dynamic content to the page and is used to embed normal JavaScript. Now embedding normal JavaScript:
Javascript
app.get('/', (req, res)=>{ // The render method takes the name of the html// page to be rendered as input.// This page should be in views folder// in the root directory.var data = {name:'Akashdeep', hobbies:['playing football', 'playing chess', 'cycling']} res.render('home', {data:data});}); var server = app.listen(4000, function() { console.log('listening to port 4000')});
The final HTML content:
HTML
<!DOCTYPE html><html><head> <title>Home Page</title> <style type="text/css" media="screen"> body { background-color: skyblue; text-decoration-color: white; font-size:5em; } </style></head> <body> Hobbies of <%=data.name%> are:<br/> <ul> <% data.hobbies.forEach((item)=>{%> <li><%=item%></li> <%});%> </ul></body> </html>
Steps to run the program:
After creating all the files go to the root directory of your project folder.
Run command prompt in this directory.
Type node file_name.js command to run your program and see the output as displayed.
Output:
saurabh1990aror
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 531,
"s": 52,
"text": "EJS: EJS or Embedded Javascript Templating is a templating engine used by Node.js. Template engine helps to create an HTML template with minimal code. Also, it can inject data into HTML template at the client side and produce the final HTML. EJS is a simple templating language which is used to generate HTML markup with plain JavaScript. It also helps to embed JavaScript to HTML pages. To begin with, using EJS as templating engine we need to install EJS using given command: "
},
{
"code": null,
"e": 554,
"s": 531,
"text": "npm install ejs --save"
},
{
"code": null,
"e": 1089,
"s": 554,
"text": "Note: npm in the above commands stands for the node package manager, a place where install all the dependencies. –save flag is no longer needed after Node 5.0.0 version, as all the modules that we now install will be added to dependencies. Now, the first thing we need to do is to set EJS as our templating engine with Express which is a Node.js web application server framework, which is specifically designed for building single-page, multi-page, and hybrid web applications. It has become the standard server framework for node.js."
},
{
"code": null,
"e": 1100,
"s": 1089,
"text": "Javascript"
},
{
"code": "// Set express as Node.js web application// server framework.// To install express before using it as// an application server by using// \"npm install express\" command.var express = require('express');var app = express(); // Set EJS as templating engineapp.set('view engine', 'ejs');",
"e": 1383,
"s": 1100,
"text": null
},
{
"code": null,
"e": 1676,
"s": 1383,
"text": "The default behavior of EJS is that it looks into the ‘views’ folder for the templates to render. So, let’s make a ‘views’ folder in our main node project folder and make a file named “home.ejs” which is to be served on some desired request in our node project. The content of this page is: "
},
{
"code": null,
"e": 1681,
"s": 1676,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Home Page</title> <style type=\"text/css\" media=\"screen\"> body { background-color: skyblue; text-decoration-color: white; font-size:7em; } </style></head> <body> <center>This is our home page.</center></body> </html> ",
"e": 2000,
"s": 1681,
"text": null
},
{
"code": null,
"e": 2068,
"s": 2000,
"text": "Now, we will render this page on a certain request by the user as: "
},
{
"code": null,
"e": 2079,
"s": 2068,
"text": "Javascript"
},
{
"code": "app.get('/', (req, res)=>{ // The render method takes the name of the HTML// page to be rendered as input// This page should be in the views folder// in the root directory.res.render('home'); });",
"e": 2275,
"s": 2079,
"text": null
},
{
"code": null,
"e": 2447,
"s": 2275,
"text": "Now, the page home.ejs will be displayed on requesting localhost. To add dynamic content this render method takes a second parameter which is an object. This is done as: "
},
{
"code": null,
"e": 2458,
"s": 2447,
"text": "Javascript"
},
{
"code": "app.get('/', (req, res)=>{ // The render method takes the name of the HTML// page to be rendered as input.// This page should be in views folder in// the root directory.// We can pass multiple properties and values// as an object, here we are passing the only nameres.render('home', {name:'Akashdeep'}); }); var server = app.listen(4000, function(){ console.log('listening to port 4000')});",
"e": 2852,
"s": 2458,
"text": null
},
{
"code": null,
"e": 2895,
"s": 2852,
"text": "Now, We will embed name to HTML page as: "
},
{
"code": null,
"e": 2900,
"s": 2895,
"text": "html"
},
{
"code": "<!DOCTYPE html><html><head> <title>Home Page</title> <style type=\"text/css\" media=\"screen\"> body { background-color: skyblue; text-decoration-color: white; font-size:7em; } </style></head><body> <center> This is our home page.<br/> Welcome <%=name%>, to our home page. </center></body></html> ",
"e": 3288,
"s": 2900,
"text": null
},
{
"code": null,
"e": 3411,
"s": 3288,
"text": "It is used to embed dynamic content to the page and is used to embed normal JavaScript. Now embedding normal JavaScript: "
},
{
"code": null,
"e": 3422,
"s": 3411,
"text": "Javascript"
},
{
"code": "app.get('/', (req, res)=>{ // The render method takes the name of the html// page to be rendered as input.// This page should be in views folder// in the root directory.var data = {name:'Akashdeep', hobbies:['playing football', 'playing chess', 'cycling']} res.render('home', {data:data});}); var server = app.listen(4000, function() { console.log('listening to port 4000')});",
"e": 3805,
"s": 3422,
"text": null
},
{
"code": null,
"e": 3831,
"s": 3805,
"text": "The final HTML content: "
},
{
"code": null,
"e": 3836,
"s": 3831,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title>Home Page</title> <style type=\"text/css\" media=\"screen\"> body { background-color: skyblue; text-decoration-color: white; font-size:5em; } </style></head> <body> Hobbies of <%=data.name%> are:<br/> <ul> <% data.hobbies.forEach((item)=>{%> <li><%=item%></li> <%});%> </ul></body> </html>",
"e": 4248,
"s": 3836,
"text": null
},
{
"code": null,
"e": 4276,
"s": 4248,
"text": "Steps to run the program: "
},
{
"code": null,
"e": 4354,
"s": 4276,
"text": "After creating all the files go to the root directory of your project folder."
},
{
"code": null,
"e": 4392,
"s": 4354,
"text": "Run command prompt in this directory."
},
{
"code": null,
"e": 4476,
"s": 4392,
"text": "Type node file_name.js command to run your program and see the output as displayed."
},
{
"code": null,
"e": 4486,
"s": 4476,
"text": "Output: "
},
{
"code": null,
"e": 4504,
"s": 4488,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 4512,
"s": 4504,
"text": "Node.js"
},
{
"code": null,
"e": 4529,
"s": 4512,
"text": "Web Technologies"
},
{
"code": null,
"e": 4556,
"s": 4529,
"text": "Web technologies Questions"
}
] |
PostgreSQL – Copy Table
|
28 Aug, 2020
PostgreSQL allows copying an existing table including the table structure and data by using various forms of PostgreSQL copy table statement. To copy a table completely, including both table structure and data sue the below statement.
Syntax:
CREATE TABLE new_table AS
TABLE existing_table;
To copy a table structure without data, users need to add the WITH NO DATA clause to the CREATE TABLE statement as follows:
Syntax:
CREATE TABLE new_table AS
TABLE existing_table
WITH NO DATA;
To copy a table with partial data from an existing table, users can use the following statement:
Syntax:
CREATE TABLE new_table AS
SELECT
*
FROM
existing_table
WHERE
condition;
The condition in the WHERE clause of the query defines which rows of the existing table will be copied to the new table.
Note: All the statements above copy table structure and data but do not copy indexes and constraints of the existing table.
Example:Creates a new table named contacts for the demonstration using the below statement:
CREATE TABLE contacts(
id SERIAL PRIMARY KEY,
first_name VARCHAR NOT NULL,
last_name VARCHAR NOT NULL,
email VARCHAR NOT NULL UNIQUE
);
Now let’s add some data to the contacts table using the below statement:
INSERT INTO contacts(first_name, last_name, email)
VALUES('Raju', 'Kumar', '[email protected]'),
('Nikhil', 'Aggarwal', '[email protected]');
To copy the contacts to a new table, for example, contacts_backup table, you use the following statement:
CREATE TABLE contact_backup
AS TABLE contacts;
To verify the above use the below statement:
SELECT * FROM contact_backup;
Output:
We can also check the data type and structure of the contact_backup table using the below command:
\d contact_backup;
It will result in the following:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Creating a REST API Backend using Node.js, Express and Postgres
PostgreSQL - Rename Table
PostgreSQL - Loop Statement
PostgreSQL - Joins
PostgreSQL - CTE
PostgreSQL - UNION operator
PostgreSQL - MD5 Function
PostgreSQL- LPAD Function
PostgreSQL - EXISTS Operator
PostgreSQL - INSERT
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 263,
"s": 28,
"text": "PostgreSQL allows copying an existing table including the table structure and data by using various forms of PostgreSQL copy table statement. To copy a table completely, including both table structure and data sue the below statement."
},
{
"code": null,
"e": 320,
"s": 263,
"text": "Syntax:\nCREATE TABLE new_table AS \nTABLE existing_table;"
},
{
"code": null,
"e": 444,
"s": 320,
"text": "To copy a table structure without data, users need to add the WITH NO DATA clause to the CREATE TABLE statement as follows:"
},
{
"code": null,
"e": 515,
"s": 444,
"text": "Syntax:\nCREATE TABLE new_table AS \nTABLE existing_table \nWITH NO DATA;"
},
{
"code": null,
"e": 612,
"s": 515,
"text": "To copy a table with partial data from an existing table, users can use the following statement:"
},
{
"code": null,
"e": 701,
"s": 612,
"text": "Syntax:\nCREATE TABLE new_table AS \nSELECT\n*\nFROM\n existing_table\nWHERE\n condition;"
},
{
"code": null,
"e": 822,
"s": 701,
"text": "The condition in the WHERE clause of the query defines which rows of the existing table will be copied to the new table."
},
{
"code": null,
"e": 946,
"s": 822,
"text": "Note: All the statements above copy table structure and data but do not copy indexes and constraints of the existing table."
},
{
"code": null,
"e": 1038,
"s": 946,
"text": "Example:Creates a new table named contacts for the demonstration using the below statement:"
},
{
"code": null,
"e": 1190,
"s": 1038,
"text": "CREATE TABLE contacts(\n id SERIAL PRIMARY KEY,\n first_name VARCHAR NOT NULL,\n last_name VARCHAR NOT NULL,\n email VARCHAR NOT NULL UNIQUE\n);"
},
{
"code": null,
"e": 1263,
"s": 1190,
"text": "Now let’s add some data to the contacts table using the below statement:"
},
{
"code": null,
"e": 1413,
"s": 1263,
"text": "INSERT INTO contacts(first_name, last_name, email) \nVALUES('Raju', 'Kumar', '[email protected]'),\n ('Nikhil', 'Aggarwal', '[email protected]');"
},
{
"code": null,
"e": 1519,
"s": 1413,
"text": "To copy the contacts to a new table, for example, contacts_backup table, you use the following statement:"
},
{
"code": null,
"e": 1567,
"s": 1519,
"text": "CREATE TABLE contact_backup \nAS TABLE contacts;"
},
{
"code": null,
"e": 1612,
"s": 1567,
"text": "To verify the above use the below statement:"
},
{
"code": null,
"e": 1642,
"s": 1612,
"text": "SELECT * FROM contact_backup;"
},
{
"code": null,
"e": 1650,
"s": 1642,
"text": "Output:"
},
{
"code": null,
"e": 1749,
"s": 1650,
"text": "We can also check the data type and structure of the contact_backup table using the below command:"
},
{
"code": null,
"e": 1768,
"s": 1749,
"text": "\\d contact_backup;"
},
{
"code": null,
"e": 1801,
"s": 1768,
"text": "It will result in the following:"
},
{
"code": null,
"e": 1827,
"s": 1801,
"text": "postgreSQL-managing-table"
},
{
"code": null,
"e": 1838,
"s": 1827,
"text": "PostgreSQL"
},
{
"code": null,
"e": 1936,
"s": 1838,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2000,
"s": 1936,
"text": "Creating a REST API Backend using Node.js, Express and Postgres"
},
{
"code": null,
"e": 2026,
"s": 2000,
"text": "PostgreSQL - Rename Table"
},
{
"code": null,
"e": 2054,
"s": 2026,
"text": "PostgreSQL - Loop Statement"
},
{
"code": null,
"e": 2073,
"s": 2054,
"text": "PostgreSQL - Joins"
},
{
"code": null,
"e": 2090,
"s": 2073,
"text": "PostgreSQL - CTE"
},
{
"code": null,
"e": 2118,
"s": 2090,
"text": "PostgreSQL - UNION operator"
},
{
"code": null,
"e": 2144,
"s": 2118,
"text": "PostgreSQL - MD5 Function"
},
{
"code": null,
"e": 2170,
"s": 2144,
"text": "PostgreSQL- LPAD Function"
},
{
"code": null,
"e": 2199,
"s": 2170,
"text": "PostgreSQL - EXISTS Operator"
}
] |
JavaScript Array indexOf() Method
|
28 Jan, 2022
Below is the example of the Array indexOf() method.
Example:
javascript
<script> var name = [ 'gfg', 'cse', 'geeks', 'portal' ]; a = name.indexOf('gfg') // Printing result of method document.write(a);</script>
Output:
0
The arr.indexOf() method is used to find the index of the first occurrence of the search element provided as the argument to the method. Syntax:
array.indexOf(element, start)
Parameters: This method accepts two parameters as mentioned above and described below:
element: This parameter holds the element which index will be return.
start: This parameter is optional and it holds the starting point of the array, where to begin the search the default value is 0.
Return value: This method returns the index of the first occurrence of the element. If the element cannot be found in the array, then this method returns -1.Below examples illustrate the Array indexOf() method in JavaScript:
Example 1: In this example the method will searched for the element 2 in that array return that element index.
Input : [1, 2, 3, 4, 5].indexOf(2);
Output: 1
Example 2: In this example the method will searched for the element 9 in that array if not found then return -1.
Input : [1, 2, 3, 4, 5].indexOf(9);
Output: -1
Code for the above method is provided below:Program 1:
javascript
<script> // Taking input as an array A // having some elements. var A = [ 1, 2, 3, 4, 5 ]; // indexOf() method is called to // test whether the searching element // is present in given array or not. a = A.indexOf(2) // Printing result of method. document.write(a);</script>
Output:
1
Program 2:
javascript
<script> // Taking input as an array A // having some elements. var name = [ 'gfg', 'cse', 'geeks', 'portal' ]; // indexOf() method is called to // test whether the searching element // is present in given array or not. a = name.indexOf('cat') // Printing result of method document.write(a);</script>
Output:
-1
Supported Browsers: The browsers supported by JavaScript Array indexOf() method are listed below:
Google Chrome 1 and above
Edge 12 and above
Firefox 1.5 and above
Internet Explorer 9 and above
Opera 9.5 and above
Safari 3 and above
Akanksha_Rai
ysachin2314
saurabh1990aror
rkbhola5
javascript-array
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
Node.js | fs.writeFileSync() Method
JavaScript | Promises
How to filter object array based on attributes?
Lodash _.debounce() Method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 82,
"s": 28,
"text": "Below is the example of the Array indexOf() method. "
},
{
"code": null,
"e": 93,
"s": 82,
"text": "Example: "
},
{
"code": null,
"e": 104,
"s": 93,
"text": "javascript"
},
{
"code": "<script> var name = [ 'gfg', 'cse', 'geeks', 'portal' ]; a = name.indexOf('gfg') // Printing result of method document.write(a);</script>",
"e": 256,
"s": 104,
"text": null
},
{
"code": null,
"e": 266,
"s": 256,
"text": "Output: "
},
{
"code": null,
"e": 268,
"s": 266,
"text": "0"
},
{
"code": null,
"e": 415,
"s": 268,
"text": "The arr.indexOf() method is used to find the index of the first occurrence of the search element provided as the argument to the method. Syntax: "
},
{
"code": null,
"e": 445,
"s": 415,
"text": "array.indexOf(element, start)"
},
{
"code": null,
"e": 534,
"s": 445,
"text": "Parameters: This method accepts two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 604,
"s": 534,
"text": "element: This parameter holds the element which index will be return."
},
{
"code": null,
"e": 734,
"s": 604,
"text": "start: This parameter is optional and it holds the starting point of the array, where to begin the search the default value is 0."
},
{
"code": null,
"e": 961,
"s": 734,
"text": "Return value: This method returns the index of the first occurrence of the element. If the element cannot be found in the array, then this method returns -1.Below examples illustrate the Array indexOf() method in JavaScript: "
},
{
"code": null,
"e": 1074,
"s": 961,
"text": "Example 1: In this example the method will searched for the element 2 in that array return that element index. "
},
{
"code": null,
"e": 1120,
"s": 1074,
"text": "Input : [1, 2, 3, 4, 5].indexOf(2);\nOutput: 1"
},
{
"code": null,
"e": 1235,
"s": 1120,
"text": "Example 2: In this example the method will searched for the element 9 in that array if not found then return -1. "
},
{
"code": null,
"e": 1282,
"s": 1235,
"text": "Input : [1, 2, 3, 4, 5].indexOf(9);\nOutput: -1"
},
{
"code": null,
"e": 1339,
"s": 1282,
"text": "Code for the above method is provided below:Program 1: "
},
{
"code": null,
"e": 1350,
"s": 1339,
"text": "javascript"
},
{
"code": "<script> // Taking input as an array A // having some elements. var A = [ 1, 2, 3, 4, 5 ]; // indexOf() method is called to // test whether the searching element // is present in given array or not. a = A.indexOf(2) // Printing result of method. document.write(a);</script>",
"e": 1654,
"s": 1350,
"text": null
},
{
"code": null,
"e": 1664,
"s": 1654,
"text": "Output: "
},
{
"code": null,
"e": 1666,
"s": 1664,
"text": "1"
},
{
"code": null,
"e": 1679,
"s": 1666,
"text": "Program 2: "
},
{
"code": null,
"e": 1690,
"s": 1679,
"text": "javascript"
},
{
"code": "<script> // Taking input as an array A // having some elements. var name = [ 'gfg', 'cse', 'geeks', 'portal' ]; // indexOf() method is called to // test whether the searching element // is present in given array or not. a = name.indexOf('cat') // Printing result of method document.write(a);</script>",
"e": 2020,
"s": 1690,
"text": null
},
{
"code": null,
"e": 2030,
"s": 2020,
"text": "Output: "
},
{
"code": null,
"e": 2033,
"s": 2030,
"text": "-1"
},
{
"code": null,
"e": 2133,
"s": 2033,
"text": "Supported Browsers: The browsers supported by JavaScript Array indexOf() method are listed below: "
},
{
"code": null,
"e": 2159,
"s": 2133,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 2177,
"s": 2159,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 2199,
"s": 2177,
"text": "Firefox 1.5 and above"
},
{
"code": null,
"e": 2229,
"s": 2199,
"text": "Internet Explorer 9 and above"
},
{
"code": null,
"e": 2249,
"s": 2229,
"text": "Opera 9.5 and above"
},
{
"code": null,
"e": 2268,
"s": 2249,
"text": "Safari 3 and above"
},
{
"code": null,
"e": 2283,
"s": 2270,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2295,
"s": 2283,
"text": "ysachin2314"
},
{
"code": null,
"e": 2311,
"s": 2295,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2320,
"s": 2311,
"text": "rkbhola5"
},
{
"code": null,
"e": 2337,
"s": 2320,
"text": "javascript-array"
},
{
"code": null,
"e": 2348,
"s": 2337,
"text": "JavaScript"
},
{
"code": null,
"e": 2446,
"s": 2348,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2507,
"s": 2446,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2579,
"s": 2507,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2619,
"s": 2579,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2660,
"s": 2619,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2702,
"s": 2660,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2756,
"s": 2702,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 2792,
"s": 2756,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 2814,
"s": 2792,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2862,
"s": 2814,
"text": "How to filter object array based on attributes?"
}
] |
Python | Sympy Line.angle_between method
|
30 Jan, 2020
Syntax: Line.angle_between(l2)
Parameters:
l1: LinearEntity
l2: LinearEntity
Returns:
angle: angle in radians
Notes: From the dot product of vectors v1 and v2 it is known that: dot(v1, v2) = |v1|*|v2|*cos(A)where A is the angle formed between the two vectors. We can get the directional vectors of the two lines and readily find the angle between the two using the above formula.
Example #1:
# import sympy and Point, Line, pifrom sympy import Point, Line, pi # using Line() methodl1 = Line((0, 0), (1, 0))l2 = Line((0, 0), (1, 1)) # using angle_between() methodrad = l1.angle_between(l2) print(rad)
Output:
pi/4
Example #2:
# import sympy and Point, Line, pifrom sympy import Point, Line, pi # using Line() methodl1 = Line((0, 0), (1, 0))l3 = Line((1, 1), (0, 0)) # using angle_between() methodrad = l1.angle_between(l3) print(rad)
Output:
3*pi/4
Python SymPy-Geometry
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "Syntax: Line.angle_between(l2)\n\n Parameters: \n l1: LinearEntity\n l2: LinearEntity\n\nReturns:\n angle: angle in radians"
},
{
"code": null,
"e": 417,
"s": 147,
"text": "Notes: From the dot product of vectors v1 and v2 it is known that: dot(v1, v2) = |v1|*|v2|*cos(A)where A is the angle formed between the two vectors. We can get the directional vectors of the two lines and readily find the angle between the two using the above formula."
},
{
"code": null,
"e": 429,
"s": 417,
"text": "Example #1:"
},
{
"code": "# import sympy and Point, Line, pifrom sympy import Point, Line, pi # using Line() methodl1 = Line((0, 0), (1, 0))l2 = Line((0, 0), (1, 1)) # using angle_between() methodrad = l1.angle_between(l2) print(rad)",
"e": 640,
"s": 429,
"text": null
},
{
"code": null,
"e": 648,
"s": 640,
"text": "Output:"
},
{
"code": null,
"e": 653,
"s": 648,
"text": "pi/4"
},
{
"code": null,
"e": 665,
"s": 653,
"text": "Example #2:"
},
{
"code": "# import sympy and Point, Line, pifrom sympy import Point, Line, pi # using Line() methodl1 = Line((0, 0), (1, 0))l3 = Line((1, 1), (0, 0)) # using angle_between() methodrad = l1.angle_between(l3) print(rad)",
"e": 876,
"s": 665,
"text": null
},
{
"code": null,
"e": 884,
"s": 876,
"text": "Output:"
},
{
"code": null,
"e": 891,
"s": 884,
"text": "3*pi/4"
},
{
"code": null,
"e": 913,
"s": 891,
"text": "Python SymPy-Geometry"
},
{
"code": null,
"e": 920,
"s": 913,
"text": "Python"
},
{
"code": null,
"e": 1018,
"s": 920,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1036,
"s": 1018,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1078,
"s": 1036,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1100,
"s": 1078,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1135,
"s": 1100,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1161,
"s": 1135,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1193,
"s": 1161,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1222,
"s": 1193,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1249,
"s": 1222,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1279,
"s": 1249,
"text": "Iterate over a list in Python"
}
] |
How to plot a histogram with various variables in Matplotlib in Python?
|
04 Jan, 2022
In this article, we are going to see how to plot a histogram with various variables in Matplotlib using Python.
A histogram is a visual representation of data presented in the form of groupings. It is a precise approach for displaying numerical data distribution graphically. It’s a type of bar plot in which the X-axis shows bin ranges and the Y-axis represents frequency. In python, we plot histogram using plt.hist() method.
Syntax: matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, \*, data=None, \*\*kwargs)
The below code is to plot a simple histogram with no extra modifications. packages are imported, CSV file is read and the histogram is plotted using plt.hist() method.
To download and read the CSV file click schoolimprovement2010grants
Python3
# import all modulesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Read in the DataFramedf = pd.read_csv('schoolimprovement2010grants.csv') # creating a histogramplt.hist(df['Award_Amount'])plt.show()
Output:
The below histogram is plotted with the use of extra parameters such as bins, alpha, and color. alpha determines the transparency, bins determine the number of bins and color represents the color of the histogram.
Python3
# import all modulesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Read in the DataFramedf = pd.read_csv('schoolimprovement2010grants.csv') # plotting histogramplt.hist(df['Award_Amount'],bins = 35, alpha = 0.45, color = 'red')plt.show()
Output:
In the below code we plot two histograms on the same axis. we use plt.hist() method twice and use the parameters, bins, alpha, and colour just like in the previous example.
To download and view the CSV file used click here.
Python3
# import all modulesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Read in the DataFramedf = pd.read_csv('homelessness.csv') # plotting two histograms on the same axisplt.hist(df['individuals'], bins=25, alpha=0.45, color='red')plt.hist(df['family_members'], bins=25, alpha=0.45, color='blue') plt.title("histogram with multiple \variables (overlapping histogram)") plt.legend(['individuals who are homeless', 'family members who are homeless']) plt.show()
Output:
plt.hist() method is used multiple times to create a figure of three overlapping histograms. we adjust opacity, color, and number of bins as needed. Three different columns from the data frame are taken as data for the histograms.
To view or download the CSV file used click medals_by_country_2016
Python3
# import all modulesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Read in the DataFramedf = pd.read_csv('medals_by_country_2016.csv') # plotting three histograms on the same axisplt.hist(df['Bronze'],bins = 25, alpha = 0.5, color = 'red')plt.hist(df['Gold'],bins = 25, alpha = 0.5, color = 'blue')plt.hist(df['Silver'],bins = 25, alpha = 0.5, color = 'yellow') plt.title("histogram with multiple \variables (overlapping histogram)")plt.legend(['Bronze','Gold','Silver']) plt.show()
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 140,
"s": 28,
"text": "In this article, we are going to see how to plot a histogram with various variables in Matplotlib using Python."
},
{
"code": null,
"e": 456,
"s": 140,
"text": "A histogram is a visual representation of data presented in the form of groupings. It is a precise approach for displaying numerical data distribution graphically. It’s a type of bar plot in which the X-axis shows bin ranges and the Y-axis represents frequency. In python, we plot histogram using plt.hist() method."
},
{
"code": null,
"e": 716,
"s": 456,
"text": "Syntax: matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, \\*, data=None, \\*\\*kwargs)"
},
{
"code": null,
"e": 884,
"s": 716,
"text": "The below code is to plot a simple histogram with no extra modifications. packages are imported, CSV file is read and the histogram is plotted using plt.hist() method."
},
{
"code": null,
"e": 952,
"s": 884,
"text": "To download and read the CSV file click schoolimprovement2010grants"
},
{
"code": null,
"e": 960,
"s": 952,
"text": "Python3"
},
{
"code": "# import all modulesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Read in the DataFramedf = pd.read_csv('schoolimprovement2010grants.csv') # creating a histogramplt.hist(df['Award_Amount'])plt.show()",
"e": 1190,
"s": 960,
"text": null
},
{
"code": null,
"e": 1198,
"s": 1190,
"text": "Output:"
},
{
"code": null,
"e": 1412,
"s": 1198,
"text": "The below histogram is plotted with the use of extra parameters such as bins, alpha, and color. alpha determines the transparency, bins determine the number of bins and color represents the color of the histogram."
},
{
"code": null,
"e": 1420,
"s": 1412,
"text": "Python3"
},
{
"code": "# import all modulesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Read in the DataFramedf = pd.read_csv('schoolimprovement2010grants.csv') # plotting histogramplt.hist(df['Award_Amount'],bins = 35, alpha = 0.45, color = 'red')plt.show()",
"e": 1695,
"s": 1420,
"text": null
},
{
"code": null,
"e": 1703,
"s": 1695,
"text": "Output:"
},
{
"code": null,
"e": 1877,
"s": 1703,
"text": "In the below code we plot two histograms on the same axis. we use plt.hist() method twice and use the parameters, bins, alpha, and colour just like in the previous example. "
},
{
"code": null,
"e": 1929,
"s": 1877,
"text": "To download and view the CSV file used click here. "
},
{
"code": null,
"e": 1937,
"s": 1929,
"text": "Python3"
},
{
"code": "# import all modulesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Read in the DataFramedf = pd.read_csv('homelessness.csv') # plotting two histograms on the same axisplt.hist(df['individuals'], bins=25, alpha=0.45, color='red')plt.hist(df['family_members'], bins=25, alpha=0.45, color='blue') plt.title(\"histogram with multiple \\variables (overlapping histogram)\") plt.legend(['individuals who are homeless', 'family members who are homeless']) plt.show()",
"e": 2438,
"s": 1937,
"text": null
},
{
"code": null,
"e": 2446,
"s": 2438,
"text": "Output:"
},
{
"code": null,
"e": 2677,
"s": 2446,
"text": "plt.hist() method is used multiple times to create a figure of three overlapping histograms. we adjust opacity, color, and number of bins as needed. Three different columns from the data frame are taken as data for the histograms."
},
{
"code": null,
"e": 2744,
"s": 2677,
"text": "To view or download the CSV file used click medals_by_country_2016"
},
{
"code": null,
"e": 2752,
"s": 2744,
"text": "Python3"
},
{
"code": "# import all modulesimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # Read in the DataFramedf = pd.read_csv('medals_by_country_2016.csv') # plotting three histograms on the same axisplt.hist(df['Bronze'],bins = 25, alpha = 0.5, color = 'red')plt.hist(df['Gold'],bins = 25, alpha = 0.5, color = 'blue')plt.hist(df['Silver'],bins = 25, alpha = 0.5, color = 'yellow') plt.title(\"histogram with multiple \\variables (overlapping histogram)\")plt.legend(['Bronze','Gold','Silver']) plt.show()",
"e": 3293,
"s": 2752,
"text": null
},
{
"code": null,
"e": 3301,
"s": 3293,
"text": "Output:"
},
{
"code": null,
"e": 3308,
"s": 3301,
"text": "Picked"
},
{
"code": null,
"e": 3326,
"s": 3308,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3333,
"s": 3326,
"text": "Python"
},
{
"code": null,
"e": 3431,
"s": 3333,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3463,
"s": 3431,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3490,
"s": 3463,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3521,
"s": 3490,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3542,
"s": 3521,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3598,
"s": 3542,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3621,
"s": 3598,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3663,
"s": 3621,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3705,
"s": 3663,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3744,
"s": 3705,
"text": "Python | datetime.timedelta() function"
}
] |
Matplotlib.axis.Axis.set_label() function in Python
|
05 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.set_label() function in axis module of matplotlib library is used to set the label that will be displayed in the legend.
Syntax: Axis.set_label(self, s)
Parameters: This method accepts the following parameters.
s: This parameter is converted to a string by calling str.
Return value: This method return the picking behavior of the artist.
Below examples illustrate the matplotlib.axis.Axis.set_label() function in matplotlib.axis:
Example 1:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as plt import numpy as np from matplotlib.collections import EllipseCollection x = np.arange(5) y = np.arange(7) X, Y = np.meshgrid(x**2, y**3) XY = np.column_stack((X.ravel(), Y.ravel())) fig, ax = plt.subplots() ec = EllipseCollection(5, 7, 5, units ='y', offsets = XY * 0.5, transOffset = ax.transData, cmap ="plasma") ec.set_array((X * Y + X * X).ravel()) ax.add_collection(ec) ax.autoscale_view() ax.set_xlabel('X') ax.set_ylabel('y') cbar = plt.colorbar(ec) cbar.set_label('X + Y') fig.suptitle('matplotlib.axis.Axis.set_label() \function Example\n', fontweight ="bold") plt.show()
Output:
Example 2:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) n = 100000x = np.random.standard_normal(n) y = 2 * np.random.standard_normal(n) z =[1, 2, 3, 4] fig, ax = plt.subplots() hb = ax.hexbin(x, y, gridsize = 50, bins ='log', cmap ='bone') cb = fig.colorbar(hb, ax = ax) cb.set_label('log') fig.suptitle('matplotlib.axis.Axis.set_label() \function Example\n', fontweight ="bold") plt.show()
Output:
Matplotlib-Axis Class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 249,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack."
},
{
"code": null,
"e": 381,
"s": 249,
"text": "The Axis.set_label() function in axis module of matplotlib library is used to set the label that will be displayed in the legend. "
},
{
"code": null,
"e": 414,
"s": 381,
"text": "Syntax: Axis.set_label(self, s) "
},
{
"code": null,
"e": 473,
"s": 414,
"text": "Parameters: This method accepts the following parameters. "
},
{
"code": null,
"e": 532,
"s": 473,
"text": "s: This parameter is converted to a string by calling str."
},
{
"code": null,
"e": 602,
"s": 532,
"text": "Return value: This method return the picking behavior of the artist. "
},
{
"code": null,
"e": 694,
"s": 602,
"text": "Below examples illustrate the matplotlib.axis.Axis.set_label() function in matplotlib.axis:"
},
{
"code": null,
"e": 705,
"s": 694,
"text": "Example 1:"
},
{
"code": null,
"e": 713,
"s": 705,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as plt import numpy as np from matplotlib.collections import EllipseCollection x = np.arange(5) y = np.arange(7) X, Y = np.meshgrid(x**2, y**3) XY = np.column_stack((X.ravel(), Y.ravel())) fig, ax = plt.subplots() ec = EllipseCollection(5, 7, 5, units ='y', offsets = XY * 0.5, transOffset = ax.transData, cmap =\"plasma\") ec.set_array((X * Y + X * X).ravel()) ax.add_collection(ec) ax.autoscale_view() ax.set_xlabel('X') ax.set_ylabel('y') cbar = plt.colorbar(ec) cbar.set_label('X + Y') fig.suptitle('matplotlib.axis.Axis.set_label() \\function Example\\n', fontweight =\"bold\") plt.show() ",
"e": 1547,
"s": 713,
"text": null
},
{
"code": null,
"e": 1557,
"s": 1547,
"text": "Output: "
},
{
"code": null,
"e": 1568,
"s": 1557,
"text": "Example 2:"
},
{
"code": null,
"e": 1576,
"s": 1568,
"text": "Python3"
},
{
"code": "# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) n = 100000x = np.random.standard_normal(n) y = 2 * np.random.standard_normal(n) z =[1, 2, 3, 4] fig, ax = plt.subplots() hb = ax.hexbin(x, y, gridsize = 50, bins ='log', cmap ='bone') cb = fig.colorbar(hb, ax = ax) cb.set_label('log') fig.suptitle('matplotlib.axis.Axis.set_label() \\function Example\\n', fontweight =\"bold\") plt.show() ",
"e": 2152,
"s": 1576,
"text": null
},
{
"code": null,
"e": 2162,
"s": 2152,
"text": "Output: "
},
{
"code": null,
"e": 2186,
"s": 2164,
"text": "Matplotlib-Axis Class"
},
{
"code": null,
"e": 2204,
"s": 2186,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2211,
"s": 2204,
"text": "Python"
}
] |
Twitter Automation using Selenium Python
|
05 Oct, 2021
If you are someone like me who considers Twitter to be far better than Instagram, then I might be having something for you. We all know gaining followers on twitter can be pretty tough but sometimes retweeting quality content can gain you, followers, too. Obviously, you are a busy person and you don’t have time to sit around on your phone or laptop to read and retweet content. Pretty boring task right? Let’s make our smart friend do it. This article revolves around how to automate twitter using selenium Python.
First, you will be needing Python. You download python from here. Now, let’s begin coding. First, create a folder named Twitter Automation and then change the directory to the newly created folder. Now, create a file named requirements.txt and add just this one line to it.
selenium==3.141.0
Next, open up your terminal and type
pip install -r requirements.txt
Next, you will need a chrome driver. You can download it from here. After the download is complete, move the downloaded driver to your newly created folder Twitter Automation. Now all the requirements are taken care of. Now let’s begin with the coding.Now, create a file called credentials.txt and add the following lines to it.
email: {your twitter email}
password: {your twitter password}
Replace the email and password placeholder with your original credentials of twitter. I am using a text file. One could also use a .env file but here for simplicity I am using a .txt file.
Next, create another file called secrets.py and add the following lines of code to it.
Python3
""" Add your twitter handle's email and password in the credentials.txt file. This will be used to automate the login.""" def get_credentials() -> dict: # dictionary for storing credentials credentials = dict() # reading the text file # for credentials with open('credentials.txt') as f: # iterating over the lines for line in f.readlines(): try: # fetching email and password key, value = line.split(": ") except ValueError: # raises error when email and password not supplied print('Add your email and password in credentials file') exit(0) # removing trailing # white space and new line credentials[key] = value.rstrip(" \n") # returning the dictionary containing the credentials return credentials
I have added a detailed code explanation in the inline comments for better understanding. Now, let’s create the most important file, the one which does all the magic. Create a new file called twitterbot.py and add the following lines to it.
Python3
from selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.chrome.options import Options'''Uncomment the below line when running in linux'''# from pyvirtualdisplay import Displayimport time, os class Twitterbot: def __init__(self, email, password): """Constructor Arguments: email {string} -- registered twitter email password {string} -- password for the twitter account """ self.email = email self.password = password # initializing chrome options chrome_options = Options() # adding the path to the chrome driver and # integrating chrome_options with the bot self.bot = webdriver.Chrome( executable_path = os.path.join(os.getcwd(), 'chromedriver'), options = chrome_options ) def login(self): """ Method for signing in the user with the provided email and password. """ bot = self.bot # fetches the login page bot.get('https://twitter.com / login') # adjust the sleep time according to your internet speed time.sleep(3) email = bot.find_element_by_xpath( '//*[@id ="react-root"]/div / div / div[2]/main / div / div / form / div / div[1]/label / div / div[2]/div / input' ) password = bot.find_element_by_xpath( '//*[@id ="react-root"]/div / div / div[2]/main / div / div / form / div / div[2]/label / div / div[2]/div / input' ) # sends the email to the email input email.send_keys(self.email) # sends the password to the password input password.send_keys(self.password) # executes RETURN key action password.send_keys(Keys.RETURN) time.sleep(2) def like_retweet(self, hashtag): """ This function automatically retrieves the tweets and then likes and retweets them Arguments: hashtag {string} -- twitter hashtag """ bot = self.bot # fetches the latest tweets with the provided hashtag bot.get( 'https://twitter.com / search?q =% 23' + \ hashtag+'&src = typed_query&f = live' ) time.sleep(3) # using set so that only unique links # are present and to avoid unnecessary repetition links = set() # obtaining the links of the tweets for _ in range(100): # executing javascript code # to scroll the webpage bot.execute_script( 'window.scrollTo(0, document.body.scrollHeight)' ) time.sleep(4) # using list comprehension # for adding all the tweets link to the set # this particular piece of code might # look very complicated but the only reason # I opted for list comprehension because is # lot faster than traditional loops [ links.add(elem.get_attribute('href'))\ for elem in bot.find_elements_by_xpath("//a[@dir ='auto']") ] # traversing through the generated links for link in links: # opens individual links bot.get(link) time.sleep(4) try: # retweet button selector bot.find_element_by_css_selector( '.css-18t94o4[data-testid ="retweet"]' ).click() # initializes action chain actions = ActionChains(bot) # sends RETURN key to retweet without comment actions.send_keys(Keys.RETURN).perform() # like button selector bot.find_element_by_css_selector( '.css-18t94o4[data-testid ="like"]' ).click() # adding higher sleep time to avoid # getting detected as bot by twitter time.sleep(10) except: time.sleep(2) # fetches the main homepage bot.get('https://twitter.com/')
Now, it’s time to code our driver script. To do that, create a file called main.py and add the following lines to it.
Python3
import twitterbot as tbimport secrets, sys # fetches the hashtag from command line argumenthashtag = sys.argv[1]# fetches the credentials dictionary# using get_credentials functioncredentials = secrets.get_credentials()# initialize the bot with your credentialsbot = tb.Twitterbot(credentials['email'], credentials['password'])# logging inbot.login()# calling like_retweet functionbot.like_retweet(hashtag)
Now, we are done with the code. Let’s call our driver script by running the following command in your terminal.
python main.py {hashtag}
Just in place of the hashtag placeholder replace it with any trending hashtag, for example, you can try
python main.py python3
This will like and retweet 100 tweets with the hashtag python. You can check out how it would perform in the video below.So, there you have it. Go ahead and try it out and do not increase the number of tweets because twitter has a daily limit of tweets.
sooda367
simmytarika5
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 571,
"s": 54,
"text": "If you are someone like me who considers Twitter to be far better than Instagram, then I might be having something for you. We all know gaining followers on twitter can be pretty tough but sometimes retweeting quality content can gain you, followers, too. Obviously, you are a busy person and you don’t have time to sit around on your phone or laptop to read and retweet content. Pretty boring task right? Let’s make our smart friend do it. This article revolves around how to automate twitter using selenium Python."
},
{
"code": null,
"e": 846,
"s": 571,
"text": "First, you will be needing Python. You download python from here. Now, let’s begin coding. First, create a folder named Twitter Automation and then change the directory to the newly created folder. Now, create a file named requirements.txt and add just this one line to it. "
},
{
"code": null,
"e": 864,
"s": 846,
"text": "selenium==3.141.0"
},
{
"code": null,
"e": 902,
"s": 864,
"text": "Next, open up your terminal and type "
},
{
"code": null,
"e": 934,
"s": 902,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 1264,
"s": 934,
"text": "Next, you will need a chrome driver. You can download it from here. After the download is complete, move the downloaded driver to your newly created folder Twitter Automation. Now all the requirements are taken care of. Now let’s begin with the coding.Now, create a file called credentials.txt and add the following lines to it. "
},
{
"code": null,
"e": 1326,
"s": 1264,
"text": "email: {your twitter email}\npassword: {your twitter password}"
},
{
"code": null,
"e": 1515,
"s": 1326,
"text": "Replace the email and password placeholder with your original credentials of twitter. I am using a text file. One could also use a .env file but here for simplicity I am using a .txt file."
},
{
"code": null,
"e": 1602,
"s": 1515,
"text": "Next, create another file called secrets.py and add the following lines of code to it."
},
{
"code": null,
"e": 1610,
"s": 1602,
"text": "Python3"
},
{
"code": "\"\"\" Add your twitter handle's email and password in the credentials.txt file. This will be used to automate the login.\"\"\" def get_credentials() -> dict: # dictionary for storing credentials credentials = dict() # reading the text file # for credentials with open('credentials.txt') as f: # iterating over the lines for line in f.readlines(): try: # fetching email and password key, value = line.split(\": \") except ValueError: # raises error when email and password not supplied print('Add your email and password in credentials file') exit(0) # removing trailing # white space and new line credentials[key] = value.rstrip(\" \\n\") # returning the dictionary containing the credentials return credentials",
"e": 2486,
"s": 1610,
"text": null
},
{
"code": null,
"e": 2728,
"s": 2486,
"text": "I have added a detailed code explanation in the inline comments for better understanding. Now, let’s create the most important file, the one which does all the magic. Create a new file called twitterbot.py and add the following lines to it. "
},
{
"code": null,
"e": 2736,
"s": 2728,
"text": "Python3"
},
{
"code": "from selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.chrome.options import Options'''Uncomment the below line when running in linux'''# from pyvirtualdisplay import Displayimport time, os class Twitterbot: def __init__(self, email, password): \"\"\"Constructor Arguments: email {string} -- registered twitter email password {string} -- password for the twitter account \"\"\" self.email = email self.password = password # initializing chrome options chrome_options = Options() # adding the path to the chrome driver and # integrating chrome_options with the bot self.bot = webdriver.Chrome( executable_path = os.path.join(os.getcwd(), 'chromedriver'), options = chrome_options ) def login(self): \"\"\" Method for signing in the user with the provided email and password. \"\"\" bot = self.bot # fetches the login page bot.get('https://twitter.com / login') # adjust the sleep time according to your internet speed time.sleep(3) email = bot.find_element_by_xpath( '//*[@id =\"react-root\"]/div / div / div[2]/main / div / div / form / div / div[1]/label / div / div[2]/div / input' ) password = bot.find_element_by_xpath( '//*[@id =\"react-root\"]/div / div / div[2]/main / div / div / form / div / div[2]/label / div / div[2]/div / input' ) # sends the email to the email input email.send_keys(self.email) # sends the password to the password input password.send_keys(self.password) # executes RETURN key action password.send_keys(Keys.RETURN) time.sleep(2) def like_retweet(self, hashtag): \"\"\" This function automatically retrieves the tweets and then likes and retweets them Arguments: hashtag {string} -- twitter hashtag \"\"\" bot = self.bot # fetches the latest tweets with the provided hashtag bot.get( 'https://twitter.com / search?q =% 23' + \\ hashtag+'&src = typed_query&f = live' ) time.sleep(3) # using set so that only unique links # are present and to avoid unnecessary repetition links = set() # obtaining the links of the tweets for _ in range(100): # executing javascript code # to scroll the webpage bot.execute_script( 'window.scrollTo(0, document.body.scrollHeight)' ) time.sleep(4) # using list comprehension # for adding all the tweets link to the set # this particular piece of code might # look very complicated but the only reason # I opted for list comprehension because is # lot faster than traditional loops [ links.add(elem.get_attribute('href'))\\ for elem in bot.find_elements_by_xpath(\"//a[@dir ='auto']\") ] # traversing through the generated links for link in links: # opens individual links bot.get(link) time.sleep(4) try: # retweet button selector bot.find_element_by_css_selector( '.css-18t94o4[data-testid =\"retweet\"]' ).click() # initializes action chain actions = ActionChains(bot) # sends RETURN key to retweet without comment actions.send_keys(Keys.RETURN).perform() # like button selector bot.find_element_by_css_selector( '.css-18t94o4[data-testid =\"like\"]' ).click() # adding higher sleep time to avoid # getting detected as bot by twitter time.sleep(10) except: time.sleep(2) # fetches the main homepage bot.get('https://twitter.com/')",
"e": 6870,
"s": 2736,
"text": null
},
{
"code": null,
"e": 6988,
"s": 6870,
"text": "Now, it’s time to code our driver script. To do that, create a file called main.py and add the following lines to it."
},
{
"code": null,
"e": 6996,
"s": 6988,
"text": "Python3"
},
{
"code": "import twitterbot as tbimport secrets, sys # fetches the hashtag from command line argumenthashtag = sys.argv[1]# fetches the credentials dictionary# using get_credentials functioncredentials = secrets.get_credentials()# initialize the bot with your credentialsbot = tb.Twitterbot(credentials['email'], credentials['password'])# logging inbot.login()# calling like_retweet functionbot.like_retweet(hashtag)",
"e": 7403,
"s": 6996,
"text": null
},
{
"code": null,
"e": 7516,
"s": 7403,
"text": "Now, we are done with the code. Let’s call our driver script by running the following command in your terminal. "
},
{
"code": null,
"e": 7541,
"s": 7516,
"text": "python main.py {hashtag}"
},
{
"code": null,
"e": 7646,
"s": 7541,
"text": "Just in place of the hashtag placeholder replace it with any trending hashtag, for example, you can try "
},
{
"code": null,
"e": 7669,
"s": 7646,
"text": "python main.py python3"
},
{
"code": null,
"e": 7924,
"s": 7669,
"text": "This will like and retweet 100 tweets with the hashtag python. You can check out how it would perform in the video below.So, there you have it. Go ahead and try it out and do not increase the number of tweets because twitter has a daily limit of tweets. "
},
{
"code": null,
"e": 7933,
"s": 7924,
"text": "sooda367"
},
{
"code": null,
"e": 7946,
"s": 7933,
"text": "simmytarika5"
},
{
"code": null,
"e": 7953,
"s": 7946,
"text": "Python"
},
{
"code": null,
"e": 8051,
"s": 7953,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8069,
"s": 8051,
"text": "Python Dictionary"
},
{
"code": null,
"e": 8111,
"s": 8069,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 8133,
"s": 8111,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 8159,
"s": 8133,
"text": "Python String | replace()"
},
{
"code": null,
"e": 8191,
"s": 8159,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8220,
"s": 8191,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 8247,
"s": 8220,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8268,
"s": 8247,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 8304,
"s": 8268,
"text": "Convert integer to string in Python"
}
] |
How to Convert ASCII Char to Byte in C#?
|
28 May, 2020
Given a char, the task is to convert this ASCII character into a Byte in C#.
Examples:
Input: chr = 'a'
Output: 97
Input: chr = 'H'
Output: 72
Method 1: Naive Approach
Step 1: Get the character.
Step 2: Convert the character using the Byte struct
byte b = (byte) chr;
Step 3: Return or perform the operation on the byte
Below is the implementation of the above approach:
C#
// C# program to convert // ascii char to byte. using System; public class GFG{ static public void Main () { char ch = 'G'; // Creating byte byte byt; // converting character into byte byt = (byte)ch; // printing character with byte value Console.WriteLine("Byte of char \'" + ch + "\' : " + byt); } }
Output:
Byte of char 'G' : 71
Method 2: Using ToByte() Method: This method is a Convert class method. It is used to converts other base data types to a byte data type.
Syntax:
byte byt = Convert.ToByte(char);
Below is the implementation of the above approach:
C#
// C# program to convert // ascii char to byte. using System; public class GFG{ static public void Main () { char ch = 'G'; // Creating byte byte byt; // converting character into byte // using Convert.ToByte() method byt = Convert.ToByte(ch); // printing character with byte value Console.WriteLine("Byte of char \'" + ch + "\' : " + byt); } }
Output:
Byte of char 'G' : 71
Method 3: Using GetBytes()[0] Method: The Encoding.ASCII.GetBytes() method is used to accepts a string as a parameter and get the byte array. Thus GetBytes()[0] is used to get the byte after converting the character into string.
Syntax:
byte byt = Encoding.ASCII.GetBytes(string str)[0];
Step 1: Get the character.
Step 2: Convert the character into string using ToString() method.
Step 3: Convert the string into byte using the GetBytes()[0] Method and store the converted string to the byte.
Step 4: Return or perform the operation on the byte.
Below is the implementation of the above approach:
C#
// C# program to convert // ascii char to byte. using System;using System.Text; public class GFG{ static public void Main () { char ch = 'G'; // convert to string // using the ToString() method string str = ch.ToString(); // Creating byte byte byt; // converting character into byte // using GetBytes() method byt = Encoding.ASCII.GetBytes(str)[0]; // printing character with byte value Console.WriteLine("Byte of char \'" + ch + "\' : " + byt); } }
Output:
Byte of char 'G' : 71
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Data Types
Convert String to Character Array in C#
Program to Print a New Line in C#
Socket Programming in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 105,
"s": 28,
"text": "Given a char, the task is to convert this ASCII character into a Byte in C#."
},
{
"code": null,
"e": 115,
"s": 105,
"text": "Examples:"
},
{
"code": null,
"e": 175,
"s": 115,
"text": "Input: chr = 'a'\nOutput: 97\n \nInput: chr = 'H'\nOutput: 72\n"
},
{
"code": null,
"e": 200,
"s": 175,
"text": "Method 1: Naive Approach"
},
{
"code": null,
"e": 227,
"s": 200,
"text": "Step 1: Get the character."
},
{
"code": null,
"e": 279,
"s": 227,
"text": "Step 2: Convert the character using the Byte struct"
},
{
"code": null,
"e": 301,
"s": 279,
"text": "byte b = (byte) chr;\n"
},
{
"code": null,
"e": 354,
"s": 301,
"text": "Step 3: Return or perform the operation on the byte "
},
{
"code": null,
"e": 405,
"s": 354,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 408,
"s": 405,
"text": "C#"
},
{
"code": "// C# program to convert // ascii char to byte. using System; public class GFG{ static public void Main () { char ch = 'G'; // Creating byte byte byt; // converting character into byte byt = (byte)ch; // printing character with byte value Console.WriteLine(\"Byte of char \\'\" + ch + \"\\' : \" + byt); } }",
"e": 796,
"s": 408,
"text": null
},
{
"code": null,
"e": 804,
"s": 796,
"text": "Output:"
},
{
"code": null,
"e": 827,
"s": 804,
"text": "Byte of char 'G' : 71\n"
},
{
"code": null,
"e": 965,
"s": 827,
"text": "Method 2: Using ToByte() Method: This method is a Convert class method. It is used to converts other base data types to a byte data type."
},
{
"code": null,
"e": 973,
"s": 965,
"text": "Syntax:"
},
{
"code": null,
"e": 1008,
"s": 973,
"text": "byte byt = Convert.ToByte(char); \n"
},
{
"code": null,
"e": 1059,
"s": 1008,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1062,
"s": 1059,
"text": "C#"
},
{
"code": "// C# program to convert // ascii char to byte. using System; public class GFG{ static public void Main () { char ch = 'G'; // Creating byte byte byt; // converting character into byte // using Convert.ToByte() method byt = Convert.ToByte(ch); // printing character with byte value Console.WriteLine(\"Byte of char \\'\" + ch + \"\\' : \" + byt); } }",
"e": 1519,
"s": 1062,
"text": null
},
{
"code": null,
"e": 1527,
"s": 1519,
"text": "Output:"
},
{
"code": null,
"e": 1550,
"s": 1527,
"text": "Byte of char 'G' : 71\n"
},
{
"code": null,
"e": 1779,
"s": 1550,
"text": "Method 3: Using GetBytes()[0] Method: The Encoding.ASCII.GetBytes() method is used to accepts a string as a parameter and get the byte array. Thus GetBytes()[0] is used to get the byte after converting the character into string."
},
{
"code": null,
"e": 1787,
"s": 1779,
"text": "Syntax:"
},
{
"code": null,
"e": 1840,
"s": 1787,
"text": "byte byt = Encoding.ASCII.GetBytes(string str)[0]; \n"
},
{
"code": null,
"e": 1867,
"s": 1840,
"text": "Step 1: Get the character."
},
{
"code": null,
"e": 1934,
"s": 1867,
"text": "Step 2: Convert the character into string using ToString() method."
},
{
"code": null,
"e": 2046,
"s": 1934,
"text": "Step 3: Convert the string into byte using the GetBytes()[0] Method and store the converted string to the byte."
},
{
"code": null,
"e": 2099,
"s": 2046,
"text": "Step 4: Return or perform the operation on the byte."
},
{
"code": null,
"e": 2150,
"s": 2099,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2153,
"s": 2150,
"text": "C#"
},
{
"code": "// C# program to convert // ascii char to byte. using System;using System.Text; public class GFG{ static public void Main () { char ch = 'G'; // convert to string // using the ToString() method string str = ch.ToString(); // Creating byte byte byt; // converting character into byte // using GetBytes() method byt = Encoding.ASCII.GetBytes(str)[0]; // printing character with byte value Console.WriteLine(\"Byte of char \\'\" + ch + \"\\' : \" + byt); } }",
"e": 2758,
"s": 2153,
"text": null
},
{
"code": null,
"e": 2766,
"s": 2758,
"text": "Output:"
},
{
"code": null,
"e": 2789,
"s": 2766,
"text": "Byte of char 'G' : 71\n"
},
{
"code": null,
"e": 2792,
"s": 2789,
"text": "C#"
},
{
"code": null,
"e": 2804,
"s": 2792,
"text": "C# Programs"
},
{
"code": null,
"e": 2902,
"s": 2804,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2933,
"s": 2902,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 2948,
"s": 2933,
"text": "C# | Delegates"
},
{
"code": null,
"e": 2991,
"s": 2948,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 3040,
"s": 2991,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 3056,
"s": 3040,
"text": "C# | Data Types"
},
{
"code": null,
"e": 3096,
"s": 3056,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 3130,
"s": 3096,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 3155,
"s": 3130,
"text": "Socket Programming in C#"
},
{
"code": null,
"e": 3201,
"s": 3155,
"text": "Getting a Month Name Using Month Number in C#"
}
] |
Get Month from date in Pandas – Python
|
02 Jul, 2020
Pandas has many inbuilt methods that can be used to extract the month from a given date that are being generated randomly using the random function or by using Timestamp function or that are transformed to date format using the to_datetimefunction. Let’s see few examples for better understanding.
Example 1
import pandas as pd dti = pd.date_range('2020-07-01', periods = 4, freq ='M')print(dti.month)
Int64Index([7, 8, 9, 10], dtype='int64')
Example 2
import pandas as pdimport numpy as npimport datetime date1 = pd.Series(pd.date_range('2020-7-1 12:00:00', periods = 5))df = pd.DataFrame(dict(date_given = date1)) df['month_of_date'] = df['date_given'].dt.monthdf
Example 3
import pandas as pdimport datetimeimport numpy as np dates =['14 / 05 / 2017', '2017', '07 / 09 / 2017'] frame = pd.to_datetime(dates, dayfirst = True)frame = pd.DataFrame([frame]).transpose()frame['date']= frameframe['month']= frame['date'].dt.monthframe.drop(0, axis = 1, inplace = True) frame
Python pandas-dataFrame
Python-pandas
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jul, 2020"
},
{
"code": null,
"e": 326,
"s": 28,
"text": "Pandas has many inbuilt methods that can be used to extract the month from a given date that are being generated randomly using the random function or by using Timestamp function or that are transformed to date format using the to_datetimefunction. Let’s see few examples for better understanding."
},
{
"code": null,
"e": 336,
"s": 326,
"text": "Example 1"
},
{
"code": "import pandas as pd dti = pd.date_range('2020-07-01', periods = 4, freq ='M')print(dti.month)",
"e": 433,
"s": 336,
"text": null
},
{
"code": null,
"e": 475,
"s": 433,
"text": "Int64Index([7, 8, 9, 10], dtype='int64')\n"
},
{
"code": null,
"e": 485,
"s": 475,
"text": "Example 2"
},
{
"code": "import pandas as pdimport numpy as npimport datetime date1 = pd.Series(pd.date_range('2020-7-1 12:00:00', periods = 5))df = pd.DataFrame(dict(date_given = date1)) df['month_of_date'] = df['date_given'].dt.monthdf",
"e": 700,
"s": 485,
"text": null
},
{
"code": null,
"e": 710,
"s": 700,
"text": "Example 3"
},
{
"code": "import pandas as pdimport datetimeimport numpy as np dates =['14 / 05 / 2017', '2017', '07 / 09 / 2017'] frame = pd.to_datetime(dates, dayfirst = True)frame = pd.DataFrame([frame]).transpose()frame['date']= frameframe['month']= frame['date'].dt.monthframe.drop(0, axis = 1, inplace = True) frame",
"e": 1011,
"s": 710,
"text": null
},
{
"code": null,
"e": 1035,
"s": 1011,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1049,
"s": 1035,
"text": "Python-pandas"
},
{
"code": null,
"e": 1056,
"s": 1049,
"text": "Python"
},
{
"code": null,
"e": 1154,
"s": 1056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1172,
"s": 1154,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1214,
"s": 1172,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1236,
"s": 1214,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1268,
"s": 1236,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1297,
"s": 1268,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1324,
"s": 1297,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1345,
"s": 1324,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1381,
"s": 1345,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 1404,
"s": 1381,
"text": "Introduction To PYTHON"
}
] |
Double SAT is NP Complete
|
14 Oct, 2020
Problem Statement: Given a formula f, the problem is to determine if f has two satisfying assignments.
Explanation: An instance of the problem is an input specified to the problem. An instance of Double Sat problem is a boolean formula f. Since an NP-complete problem is a problem which is both NP and NP-Hard, the proof or statement that a problem is NP-Complete consists of two parts:
The problem itself is in NP class.All other problems in NP class can be polynomial-time reducible to that.(B is polynomial-time reducible to C is denoted as B ≤ PC)
The problem itself is in NP class.
All other problems in NP class can be polynomial-time reducible to that.(B is polynomial-time reducible to C is denoted as B ≤ PC)
If the 2nd condition is only satisfied then the problem is called NP-Hard.But it is not possible to reduce every NP problem into another NP problem to show its NP-Completeness all the time. Therefore to show a problem is NP-complete, then prove that the problem is in NP and any NP-Complete problem is reducible to that i.e., if B is NP-Complete and B ≤ PC . For C in NP, then C is NP-Complete. Thus, it can be verified that the Double SAT problem is NP-Complete using the following propositions:
Double Sat is in NP:If any problem is in NP, then it is given a ‘certificate’, which is a solution to the problem and an instance of the problem(a formula f) then it can identify (whether the solution is correct or not) certificate in polynomial time. This can be done by giving a set of satisfying assignments for the variables in f, and verify if each clause is satisfied in f.Double Sat is NP-Hard:In order to prove double sat is NP-Hard then reduce a known NP-Hard problem, 3-SAT (in this case) to our problem.This can be done by:Given a 3-CNF function g then create a boolean function f by adding a pair of literals (x V x’) to each clause of f, where x is an additional variable. This reduction can work in polynomial time.Now, the following two propositions hold:If g is unsatisfiable, then some clause of g must be FALSE, and therefore, f must also be unsatisfiable.If 3-SAT formula g is satisfiable, then using the same set of assignment variables comprised in g, we can have both x=0 and x=1 as the valid assignments to g.
Double Sat is in NP:If any problem is in NP, then it is given a ‘certificate’, which is a solution to the problem and an instance of the problem(a formula f) then it can identify (whether the solution is correct or not) certificate in polynomial time. This can be done by giving a set of satisfying assignments for the variables in f, and verify if each clause is satisfied in f.
Double Sat is NP-Hard:In order to prove double sat is NP-Hard then reduce a known NP-Hard problem, 3-SAT (in this case) to our problem.This can be done by:Given a 3-CNF function g then create a boolean function f by adding a pair of literals (x V x’) to each clause of f, where x is an additional variable. This reduction can work in polynomial time.Now, the following two propositions hold:If g is unsatisfiable, then some clause of g must be FALSE, and therefore, f must also be unsatisfiable.If 3-SAT formula g is satisfiable, then using the same set of assignment variables comprised in g, we can have both x=0 and x=1 as the valid assignments to g.
If g is unsatisfiable, then some clause of g must be FALSE, and therefore, f must also be unsatisfiable.
If 3-SAT formula g is satisfiable, then using the same set of assignment variables comprised in g, we can have both x=0 and x=1 as the valid assignments to g.
Therefore, Double-SAT Problem is NP-Complete.
NP Complete
Analysis
Articles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Oct, 2020"
},
{
"code": null,
"e": 131,
"s": 28,
"text": "Problem Statement: Given a formula f, the problem is to determine if f has two satisfying assignments."
},
{
"code": null,
"e": 415,
"s": 131,
"text": "Explanation: An instance of the problem is an input specified to the problem. An instance of Double Sat problem is a boolean formula f. Since an NP-complete problem is a problem which is both NP and NP-Hard, the proof or statement that a problem is NP-Complete consists of two parts:"
},
{
"code": null,
"e": 580,
"s": 415,
"text": "The problem itself is in NP class.All other problems in NP class can be polynomial-time reducible to that.(B is polynomial-time reducible to C is denoted as B ≤ PC)"
},
{
"code": null,
"e": 615,
"s": 580,
"text": "The problem itself is in NP class."
},
{
"code": null,
"e": 746,
"s": 615,
"text": "All other problems in NP class can be polynomial-time reducible to that.(B is polynomial-time reducible to C is denoted as B ≤ PC)"
},
{
"code": null,
"e": 1243,
"s": 746,
"text": "If the 2nd condition is only satisfied then the problem is called NP-Hard.But it is not possible to reduce every NP problem into another NP problem to show its NP-Completeness all the time. Therefore to show a problem is NP-complete, then prove that the problem is in NP and any NP-Complete problem is reducible to that i.e., if B is NP-Complete and B ≤ PC . For C in NP, then C is NP-Complete. Thus, it can be verified that the Double SAT problem is NP-Complete using the following propositions:"
},
{
"code": null,
"e": 2276,
"s": 1243,
"text": "Double Sat is in NP:If any problem is in NP, then it is given a ‘certificate’, which is a solution to the problem and an instance of the problem(a formula f) then it can identify (whether the solution is correct or not) certificate in polynomial time. This can be done by giving a set of satisfying assignments for the variables in f, and verify if each clause is satisfied in f.Double Sat is NP-Hard:In order to prove double sat is NP-Hard then reduce a known NP-Hard problem, 3-SAT (in this case) to our problem.This can be done by:Given a 3-CNF function g then create a boolean function f by adding a pair of literals (x V x’) to each clause of f, where x is an additional variable. This reduction can work in polynomial time.Now, the following two propositions hold:If g is unsatisfiable, then some clause of g must be FALSE, and therefore, f must also be unsatisfiable.If 3-SAT formula g is satisfiable, then using the same set of assignment variables comprised in g, we can have both x=0 and x=1 as the valid assignments to g."
},
{
"code": null,
"e": 2656,
"s": 2276,
"text": "Double Sat is in NP:If any problem is in NP, then it is given a ‘certificate’, which is a solution to the problem and an instance of the problem(a formula f) then it can identify (whether the solution is correct or not) certificate in polynomial time. This can be done by giving a set of satisfying assignments for the variables in f, and verify if each clause is satisfied in f."
},
{
"code": null,
"e": 3310,
"s": 2656,
"text": "Double Sat is NP-Hard:In order to prove double sat is NP-Hard then reduce a known NP-Hard problem, 3-SAT (in this case) to our problem.This can be done by:Given a 3-CNF function g then create a boolean function f by adding a pair of literals (x V x’) to each clause of f, where x is an additional variable. This reduction can work in polynomial time.Now, the following two propositions hold:If g is unsatisfiable, then some clause of g must be FALSE, and therefore, f must also be unsatisfiable.If 3-SAT formula g is satisfiable, then using the same set of assignment variables comprised in g, we can have both x=0 and x=1 as the valid assignments to g."
},
{
"code": null,
"e": 3415,
"s": 3310,
"text": "If g is unsatisfiable, then some clause of g must be FALSE, and therefore, f must also be unsatisfiable."
},
{
"code": null,
"e": 3574,
"s": 3415,
"text": "If 3-SAT formula g is satisfiable, then using the same set of assignment variables comprised in g, we can have both x=0 and x=1 as the valid assignments to g."
},
{
"code": null,
"e": 3620,
"s": 3574,
"text": "Therefore, Double-SAT Problem is NP-Complete."
},
{
"code": null,
"e": 3632,
"s": 3620,
"text": "NP Complete"
},
{
"code": null,
"e": 3641,
"s": 3632,
"text": "Analysis"
},
{
"code": null,
"e": 3650,
"s": 3641,
"text": "Articles"
}
] |
Text Generation with Pretrained GPT2 Using PyTorch | by Raymond Cheng | Towards Data Science
|
Text Generation is one of the most exciting applications of Natural Language Processing (NLP) in recent years. Most of us have probably heard of GPT-3, a powerful language model that can possibly generate close to human-level texts. However, models like these are extremely difficult to train because of their heavy size, so pretrained models are usually preferred where applicable.
In this article, we will teach you how to generate text using pretrained GPT-2, the lighter predecessor of GPT-3. We will be using the notable Transformers library developed by Huggingface. If you want to know how to fine-tune GPT-2 on your own custom dataset to generate domain-specific text, then you can refer to my previous post:
towardsdatascience.com
If using pretrained GPT-2 is enough, you’re in the right place! Without further ado, let’s get started with the tutorial!
Step 1: Install Library
Step 2: Import Library
Step 3: Build Text Generation Pipeline
Step 4: Define the Text to Start Generating From
Step 5: Start Generating
BONUS: Generate Text in any Language
To install Huggingface Transformers, we need to make sure PyTorch is installed. If you haven’t installed PyTorch, go to its official website and follow its instructions to install it.
After installing PyTorch, you can install Huggingface Transformers by running:
pip install transformers
After successfully installing Transformers, you can now import its pipeline module:
from transformers import pipeline
The pipeline module is an abstraction layer that takes away the complexity of code and allows an easy way of performing different NLP tasks.
Now, we can start building the pipeline for text generation. We can do so by:
text_generation = pipeline(“text-generation”)
The default model for the text generation pipeline is GPT-2, the most popular decoder-based transformer model for language generation.
Now, we can start defining the prefix text we want to generate from. Let’s give it a more general starting sentence:
The world is
prefix_text = "The world is"
After we define our starting text, now it’s time to do generation! We can simply do so by running:
generated_text= text_generation(prefix_text, max_length=50, do_sample=False)[0]print(generated_text[‘generated_text’])
The above code specifies a max_length of 50 tokens and sampling to be off. The output should be:
The world is a better place if you’re a good person.
I’m not saying that you should be a bad person. I’m saying that you should be a good person.
I’m not saying that you should be a bad
As we can see it’s quite fascinating how a computer can be able to generate text that kind of makes sense although it’s not perfect. One issue with the output is that it is repetitive at the end. This can possibly be solved by using different decoding schemes (e.g. top-k/top-p sampling) and playing around with different values, but it is out of the scope of this article. To learn more about decoding schemes and how you can implement it, check out the Huggingface’s official tutorial and the TextGeneration pipeline documentation.
First, to generate text in another language, we will need a language model previously trained on a corpus of that language; otherwise; we will have to fine-tune by ourselves, which is a tedious task. Fortunately, Huggingface provides a list of models that are released by the warm NLP community (link here), and chances are that a language model is previously fine-tuned on the language of your choice.
Let’s say we want to generate text in Chinese. This GPT2 model by CKIPLab is pretrained on a Chinese corpus, and so we can use their model without needing to fine-tune by ourselves.
Following their documentation, we can start by importing the relevant tokenizer and model modules:
from transformers import BertTokenizerFast, AutoModelWithLMHead
Then, we can build the tokenizer and the model accordingly:
tokenizer = BertTokenizerFast.from_pretrained(‘bert-base-chinese’)model = AutoModelWithLMHead.from_pretrained(‘ckiplab/gpt2-base-chinese’)
Next, we feed our new tokenizer and model as parameters to instantiate the pipeline:
text_generation = pipeline(“text-generation”, model=model, tokenizer=tokenizer)
After that, we define our prefix text again, this time in Chinese:
我 想 要 去
prefix_text = "我 想 要 去"## I want to go
Using the same code as above, we can now generate from the prefix text:
generated_text= text_generation(prefix_text, max_length=50, do_sample=False)[0]print(generated_text['generated_text'])
Now, you should see the following output:
我 想 要 去 看 看 。 」 他 說 : 「 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們
## I want to go see around.” He says: “We can’t say, we can’t say, we can’t say, we can’t say, we can’t say, we can’t say, we
Although the generated text is far from perfect, again, this is a topic for another article.
And here you have it! Hope you now know how to implement text generation using the simple API interface provided by Huggingface with pretrained models. For your convenience, I have attached a Jupyter notebook here:
from transformers import pipeline
text_generation = pipeline("text-generation")
prefix_text = "The world is"
generated_text= text_generation(prefix_text, max_length=50, do_sample=False)[0]
print(generated_text['generated_text'])
Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.
The world is a better place if you're a good person.
I'm not saying that you should be a bad person. I'm saying that you should be a good person.
I'm not saying that you should be a bad
from transformers import pipeline, BertTokenizerFast, AutoModelWithLMHead
tokenizer = BertTokenizerFast.from_pretrained('bert-base-chinese')
model = AutoModelWithLMHead.from_pretrained('ckiplab/gpt2-base-chinese')
text_generation = pipeline("text-generation", model=model, tokenizer=tokenizer)
prefix_text = "我 想 要 去"
generated_text= text_generation(prefix_text, max_length=50, do_sample=False)[0]
print(generated_text['generated_text'])
Setting `pad_token_id` to `eos_token_id`:102 for open-end generation.
我 想 要 去 看 看 。 」 他 說 : 「 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們
And that’s it! Hope you enjoyed this post. If you have any questions, feel free to comment down below. Also, please subscribe to my email list to receive new articles from me. You can also check out my previous posts if interested :)
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Brown, Tom B., et al. “Language models are few-shot learners.” arXiv preprint arXiv:2005.14165 (2020).
Radford, Alec, et al. “Language models are unsupervised multitask learners.” OpenAI blog 1.8 (2019): 9.
Transformers Github, Huggingface
Transformers Official Documentation, Huggingface
Pytorch Official Website, Facebook AI Research
Fan, Angela, Mike Lewis, and Yann Dauphin. “Hierarchical neural story generation.” arXiv preprint arXiv:1805.04833 (2018).
Welleck, Sean, et al. “Neural text generation with unlikelihood training.” arXiv preprint arXiv:1908.04319 (2019).
CKIPLab Transformers Github, Chinese Knowlege and Information Processing at the Institute of Information Science and the Institute of Linguistics of Academia Sinica
|
[
{
"code": null,
"e": 555,
"s": 172,
"text": "Text Generation is one of the most exciting applications of Natural Language Processing (NLP) in recent years. Most of us have probably heard of GPT-3, a powerful language model that can possibly generate close to human-level texts. However, models like these are extremely difficult to train because of their heavy size, so pretrained models are usually preferred where applicable."
},
{
"code": null,
"e": 889,
"s": 555,
"text": "In this article, we will teach you how to generate text using pretrained GPT-2, the lighter predecessor of GPT-3. We will be using the notable Transformers library developed by Huggingface. If you want to know how to fine-tune GPT-2 on your own custom dataset to generate domain-specific text, then you can refer to my previous post:"
},
{
"code": null,
"e": 912,
"s": 889,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1034,
"s": 912,
"text": "If using pretrained GPT-2 is enough, you’re in the right place! Without further ado, let’s get started with the tutorial!"
},
{
"code": null,
"e": 1058,
"s": 1034,
"text": "Step 1: Install Library"
},
{
"code": null,
"e": 1081,
"s": 1058,
"text": "Step 2: Import Library"
},
{
"code": null,
"e": 1120,
"s": 1081,
"text": "Step 3: Build Text Generation Pipeline"
},
{
"code": null,
"e": 1169,
"s": 1120,
"text": "Step 4: Define the Text to Start Generating From"
},
{
"code": null,
"e": 1194,
"s": 1169,
"text": "Step 5: Start Generating"
},
{
"code": null,
"e": 1231,
"s": 1194,
"text": "BONUS: Generate Text in any Language"
},
{
"code": null,
"e": 1415,
"s": 1231,
"text": "To install Huggingface Transformers, we need to make sure PyTorch is installed. If you haven’t installed PyTorch, go to its official website and follow its instructions to install it."
},
{
"code": null,
"e": 1494,
"s": 1415,
"text": "After installing PyTorch, you can install Huggingface Transformers by running:"
},
{
"code": null,
"e": 1519,
"s": 1494,
"text": "pip install transformers"
},
{
"code": null,
"e": 1603,
"s": 1519,
"text": "After successfully installing Transformers, you can now import its pipeline module:"
},
{
"code": null,
"e": 1637,
"s": 1603,
"text": "from transformers import pipeline"
},
{
"code": null,
"e": 1778,
"s": 1637,
"text": "The pipeline module is an abstraction layer that takes away the complexity of code and allows an easy way of performing different NLP tasks."
},
{
"code": null,
"e": 1856,
"s": 1778,
"text": "Now, we can start building the pipeline for text generation. We can do so by:"
},
{
"code": null,
"e": 1902,
"s": 1856,
"text": "text_generation = pipeline(“text-generation”)"
},
{
"code": null,
"e": 2037,
"s": 1902,
"text": "The default model for the text generation pipeline is GPT-2, the most popular decoder-based transformer model for language generation."
},
{
"code": null,
"e": 2154,
"s": 2037,
"text": "Now, we can start defining the prefix text we want to generate from. Let’s give it a more general starting sentence:"
},
{
"code": null,
"e": 2167,
"s": 2154,
"text": "The world is"
},
{
"code": null,
"e": 2196,
"s": 2167,
"text": "prefix_text = \"The world is\""
},
{
"code": null,
"e": 2295,
"s": 2196,
"text": "After we define our starting text, now it’s time to do generation! We can simply do so by running:"
},
{
"code": null,
"e": 2414,
"s": 2295,
"text": "generated_text= text_generation(prefix_text, max_length=50, do_sample=False)[0]print(generated_text[‘generated_text’])"
},
{
"code": null,
"e": 2511,
"s": 2414,
"text": "The above code specifies a max_length of 50 tokens and sampling to be off. The output should be:"
},
{
"code": null,
"e": 2564,
"s": 2511,
"text": "The world is a better place if you’re a good person."
},
{
"code": null,
"e": 2657,
"s": 2564,
"text": "I’m not saying that you should be a bad person. I’m saying that you should be a good person."
},
{
"code": null,
"e": 2697,
"s": 2657,
"text": "I’m not saying that you should be a bad"
},
{
"code": null,
"e": 3231,
"s": 2697,
"text": "As we can see it’s quite fascinating how a computer can be able to generate text that kind of makes sense although it’s not perfect. One issue with the output is that it is repetitive at the end. This can possibly be solved by using different decoding schemes (e.g. top-k/top-p sampling) and playing around with different values, but it is out of the scope of this article. To learn more about decoding schemes and how you can implement it, check out the Huggingface’s official tutorial and the TextGeneration pipeline documentation."
},
{
"code": null,
"e": 3634,
"s": 3231,
"text": "First, to generate text in another language, we will need a language model previously trained on a corpus of that language; otherwise; we will have to fine-tune by ourselves, which is a tedious task. Fortunately, Huggingface provides a list of models that are released by the warm NLP community (link here), and chances are that a language model is previously fine-tuned on the language of your choice."
},
{
"code": null,
"e": 3816,
"s": 3634,
"text": "Let’s say we want to generate text in Chinese. This GPT2 model by CKIPLab is pretrained on a Chinese corpus, and so we can use their model without needing to fine-tune by ourselves."
},
{
"code": null,
"e": 3915,
"s": 3816,
"text": "Following their documentation, we can start by importing the relevant tokenizer and model modules:"
},
{
"code": null,
"e": 3979,
"s": 3915,
"text": "from transformers import BertTokenizerFast, AutoModelWithLMHead"
},
{
"code": null,
"e": 4039,
"s": 3979,
"text": "Then, we can build the tokenizer and the model accordingly:"
},
{
"code": null,
"e": 4178,
"s": 4039,
"text": "tokenizer = BertTokenizerFast.from_pretrained(‘bert-base-chinese’)model = AutoModelWithLMHead.from_pretrained(‘ckiplab/gpt2-base-chinese’)"
},
{
"code": null,
"e": 4263,
"s": 4178,
"text": "Next, we feed our new tokenizer and model as parameters to instantiate the pipeline:"
},
{
"code": null,
"e": 4343,
"s": 4263,
"text": "text_generation = pipeline(“text-generation”, model=model, tokenizer=tokenizer)"
},
{
"code": null,
"e": 4410,
"s": 4343,
"text": "After that, we define our prefix text again, this time in Chinese:"
},
{
"code": null,
"e": 4418,
"s": 4410,
"text": "我 想 要 去"
},
{
"code": null,
"e": 4458,
"s": 4418,
"text": "prefix_text = \"我 想 要 去\"## I want to go "
},
{
"code": null,
"e": 4530,
"s": 4458,
"text": "Using the same code as above, we can now generate from the prefix text:"
},
{
"code": null,
"e": 4649,
"s": 4530,
"text": "generated_text= text_generation(prefix_text, max_length=50, do_sample=False)[0]print(generated_text['generated_text'])"
},
{
"code": null,
"e": 4691,
"s": 4649,
"text": "Now, you should see the following output:"
},
{
"code": null,
"e": 4785,
"s": 4691,
"text": "我 想 要 去 看 看 。 」 他 說 : 「 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們"
},
{
"code": null,
"e": 4911,
"s": 4785,
"text": "## I want to go see around.” He says: “We can’t say, we can’t say, we can’t say, we can’t say, we can’t say, we can’t say, we"
},
{
"code": null,
"e": 5004,
"s": 4911,
"text": "Although the generated text is far from perfect, again, this is a topic for another article."
},
{
"code": null,
"e": 5219,
"s": 5004,
"text": "And here you have it! Hope you now know how to implement text generation using the simple API interface provided by Huggingface with pretrained models. For your convenience, I have attached a Jupyter notebook here:"
},
{
"code": null,
"e": 5254,
"s": 5219,
"text": "from transformers import pipeline\n"
},
{
"code": null,
"e": 5301,
"s": 5254,
"text": "text_generation = pipeline(\"text-generation\")\n"
},
{
"code": null,
"e": 5331,
"s": 5301,
"text": "prefix_text = \"The world is\"\n"
},
{
"code": null,
"e": 5452,
"s": 5331,
"text": "generated_text= text_generation(prefix_text, max_length=50, do_sample=False)[0]\nprint(generated_text['generated_text'])\n"
},
{
"code": null,
"e": 5525,
"s": 5452,
"text": "Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.\n"
},
{
"code": null,
"e": 5714,
"s": 5525,
"text": "The world is a better place if you're a good person.\n\nI'm not saying that you should be a bad person. I'm saying that you should be a good person.\n\nI'm not saying that you should be a bad\n"
},
{
"code": null,
"e": 5789,
"s": 5714,
"text": "from transformers import pipeline, BertTokenizerFast, AutoModelWithLMHead\n"
},
{
"code": null,
"e": 5930,
"s": 5789,
"text": "tokenizer = BertTokenizerFast.from_pretrained('bert-base-chinese')\nmodel = AutoModelWithLMHead.from_pretrained('ckiplab/gpt2-base-chinese')\n"
},
{
"code": null,
"e": 6011,
"s": 5930,
"text": "text_generation = pipeline(\"text-generation\", model=model, tokenizer=tokenizer)\n"
},
{
"code": null,
"e": 6157,
"s": 6011,
"text": "prefix_text = \"我 想 要 去\"\n\ngenerated_text= text_generation(prefix_text, max_length=50, do_sample=False)[0]\nprint(generated_text['generated_text'])\n"
},
{
"code": null,
"e": 6228,
"s": 6157,
"text": "Setting `pad_token_id` to `eos_token_id`:102 for open-end generation.\n"
},
{
"code": null,
"e": 6323,
"s": 6228,
"text": "我 想 要 去 看 看 。 」 他 說 : 「 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們 不 能 說, 我 們\n"
},
{
"code": null,
"e": 6557,
"s": 6323,
"text": "And that’s it! Hope you enjoyed this post. If you have any questions, feel free to comment down below. Also, please subscribe to my email list to receive new articles from me. You can also check out my previous posts if interested :)"
},
{
"code": null,
"e": 6580,
"s": 6557,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6603,
"s": 6580,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6626,
"s": 6603,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6649,
"s": 6626,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6672,
"s": 6649,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6775,
"s": 6672,
"text": "Brown, Tom B., et al. “Language models are few-shot learners.” arXiv preprint arXiv:2005.14165 (2020)."
},
{
"code": null,
"e": 6879,
"s": 6775,
"text": "Radford, Alec, et al. “Language models are unsupervised multitask learners.” OpenAI blog 1.8 (2019): 9."
},
{
"code": null,
"e": 6912,
"s": 6879,
"text": "Transformers Github, Huggingface"
},
{
"code": null,
"e": 6961,
"s": 6912,
"text": "Transformers Official Documentation, Huggingface"
},
{
"code": null,
"e": 7008,
"s": 6961,
"text": "Pytorch Official Website, Facebook AI Research"
},
{
"code": null,
"e": 7131,
"s": 7008,
"text": "Fan, Angela, Mike Lewis, and Yann Dauphin. “Hierarchical neural story generation.” arXiv preprint arXiv:1805.04833 (2018)."
},
{
"code": null,
"e": 7246,
"s": 7131,
"text": "Welleck, Sean, et al. “Neural text generation with unlikelihood training.” arXiv preprint arXiv:1908.04319 (2019)."
}
] |
How to remove all CSS classes using jQuery?
|
To remove all classes, use the removeClass() method with no parameters. This will remove all of the item's classes.
You can try to run the following code to remove all CSS classes using jQuery:
Live Demo
<html>
<head>
<title>jQuery Selector</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button1").click(function(){
$("p").removeClass();
});
});
</script>
<style>
.red { color:red; }
.blue { color:blue; }
</style>
</head>
<body>
<p class = "red" >This is first paragraph.</p>
<p class = "blue">This is second paragraph.</p>
<button id="button1">Remove</button>
</body>
</html>
|
[
{
"code": null,
"e": 1178,
"s": 1062,
"text": "To remove all classes, use the removeClass() method with no parameters. This will remove all of the item's classes."
},
{
"code": null,
"e": 1256,
"s": 1178,
"text": "You can try to run the following code to remove all CSS classes using jQuery:"
},
{
"code": null,
"e": 1266,
"s": 1256,
"text": "Live Demo"
},
{
"code": null,
"e": 1889,
"s": 1266,
"text": "<html>\n <head>\n <title>jQuery Selector</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n $(\"#button1\").click(function(){\n $(\"p\").removeClass();\n });\n });\n </script>\n \n <style>\n .red { color:red; }\n .blue { color:blue; }\n </style>\n </head>\n \n <body>\n <p class = \"red\" >This is first paragraph.</p>\n <p class = \"blue\">This is second paragraph.</p>\n <button id=\"button1\">Remove</button>\n </body>\n</html>"
}
] |
SAP Cloud Platform - Quick Guide
|
SAP Cloud Platform is a cloud service provided by SAP based on platform as a service (PaaS) to develop and deploy custom web applications. SAP is responsible for managing complete infrastructure of this platform including hardware servers, maintenance cost, component upgrades, and system lifecycle.
SAP Cloud service provides full range of service catalog including database, storage and data backup, reporting service and transaction layer to develop multi-platform software development. SAP Cloud platform customers can utilize this cloud environment for managing software development or can also use a hybrid model based on cloud and on premise environment.
SAP Cloud platform can be integrated with following to get data and development −
SAP Applications
3rd party applications
Internal solutions
Note that the above mentioned can be on premise or on cloud and can be easily integrated with SAP Cloud platform for application development.
SAP Cloud platform supports business critical solutions for software development and it includes −
SAP Fieldglass
SAP Success factors
SAP Hybris
SAP Ariba
BusinessObjects
SAP ERP Business suite
Concur
You can migrate apps and extensions seamlessly to SAP Cloud platform including SAP Business suite and SAP S/4 HANA. All the data centers are managed by SAP itself, so you can expect the given key benefits associated with data center management −
Security
Compliance
Availability
SAP Cloud platform offers PaaS based in-memory and microservice based mobile enabled cloud applications. SAP Cloud Platform provides you an option to control your choice of clouds, frameworks, and applications.
To know more about SAP Cloud platform and services offered by Cloud service, you can navigate to this link − https://cloudplatform.sap.com/index.html
SAP Cloud platform also provides a free trial. For creating a trial account, you need to click “Start your free trial” button as shown below. You can also chat with SAP experts for any queries.
To register for free trail, you need to provide your work email id, and other details. Once you successfully submit all the details, you can use that for logging into the Cloud service.
Once you provide all details and login, you will get a message − “Welcome to your free trial”. To start your trial, click the blue icon - “Click here to start your trial”. SAP also assigns you a unique User Id for your trial period.
Once you login, it takes you to SAP Cloud platform cockpit.
SAP Cloud Platform cockpit is the central Web-based user interface for administrators, and you can use this for providing access to various functions for configuring and managing applications using SAP Cloud platform. You can use the cockpit to manage resources, services, security, monitor application metrics, and perform actions on cloud applications.
The service level agreement for SAP Cloud service is applicable to Cloud service mentioned in service description guide. You can check detail on Service level agreement using this link −1 https://cloudplatform.sap.com/support/service-description.html
The System Availability SLA for all Cloud Services is 99.9% per month. Any deviations from the 99.9% System Availability SLA or any aspect of the standard Service Level Agreement for SAP Cloud Services are noted in the applicable Cloud Service terms in this Service Description Guide.
You can check the details using this link − https://www.sap.com/about/agreements/cloud-services.html
As per SAP - High Availability option for HANA and ASE Service in SAP’s data centers, SAP shall provide High Availability for SAP Cloud Platform, HANA service or SAP Cloud Platform ASE service with an availability SLA of 99.95% per month if Customer has allocated to High Availability via SAP Cloud Platform provisioning self-service a duplicate of SAP Cloud Platform, HANA service or SAP Cloud Platform ASE service, as applicable. The duplicate SAP Cloud Platform services allocated to High Availability require separate subscriptions (and associated fees). In all other respects, the Service Level Agreement for SAP Cloud Services referenced in the Order Form applies to the applicable SAP Cloud Platform services.
Precondition to System Availability SLA −
Java Platform Applications need to run with minimum 2 application processes/nodes
Java Platform Applications need to run with minimum 2 application processes/nodes
Java Platform Applications need to have an availability check configured
Java Platform Applications need to have an availability check configured
SAP HANA Cloud Platform, Java server (x-small) = SAP HANA Cloud Platform, compute unit lite
SAP HANA Cloud Platform, Java server (small) = SAP HANA Cloud Platform, compute professional
SAP HANA Cloud Platform, Java server (medium) = SAP HANA Cloud Platform, compute premium
SAP HANA Cloud Platform, Java server (large) = SAP HANA Cloud Platform, compute premium plus
Customer may use the Cloud Service to host and run separately licensed SAP or third-party applications.
Customer may use the Cloud Service to host and run separately licensed SAP or third-party applications.
Customer is solely responsible for the security, maintenance, management and support of the applications installed by Customer on the Cloud Service.
Customer is solely responsible for the security, maintenance, management and support of the applications installed by Customer on the Cloud Service.
Customer is responsible for back up of Customer Data – no back up services are included in the Cloud Service.
Customer is responsible for back up of Customer Data – no back up services are included in the Cloud Service.
The Cloud Service is provided through a single data center. As such, no redundant data center is included for disaster recovery services.
The Cloud Service is provided through a single data center. As such, no redundant data center is included for disaster recovery services.
Customer is solely responsible for managing and updating the OS layer of the Cloud Service, including patching the OS with the most recent security patches made available by the OS vendor.
Customer is solely responsible for managing and updating the OS layer of the Cloud Service, including patching the OS with the most recent security patches made available by the OS vendor.
Customer shall fully compensate SAP (without effect of any limitations on liability in the GTCs) for any damages or expenses incurred by SAP as a result of a claim by a third party that any Customer or third-party software or other technology hosted or run on the Customer’s Cloud Service virtual machine infringes or otherwise violates the rights of the third party.
SAP Cloud Platform Portal is limited to access by individuals within the Customer’s organization, including employees and contractors.
SAP Cloud Platform Portal is limited to access by individuals within the Customer’s organization, including employees and contractors.
Each SAP Cloud Platform Portal subscription also includes −
Each SAP Cloud Platform Portal subscription also includes −
30 logons of SAP Cloud Platform Identity Authentication per User, per month
30 logons of SAP Cloud Platform Identity Authentication per User, per month
SAP Cloud Platform SAP HANA Server (BYOL) does not include a license to the SAP HANA database or any other database.
SAP Cloud Platform SAP HANA Server (BYOL) does not include a license to the SAP HANA database or any other database.
Customer must have a valid license agreement for the SAP HANA database in order subscribe to SAP Cloud Platform SAP HANA Server (BYOL). Customer may not use SAP Cloud Platform SAP HANA Server (BYOL) or copy, access or use the SAP HANA database software accessible through the SAP HANA HANA server (BYOL) without such current license.
Customer must have a valid license agreement for the SAP HANA database in order subscribe to SAP Cloud Platform SAP HANA Server (BYOL). Customer may not use SAP Cloud Platform SAP HANA Server (BYOL) or copy, access or use the SAP HANA database software accessible through the SAP HANA HANA server (BYOL) without such current license.
Any attempt to access the SAP HANA database without such a license is a violation of SAP’s intellectual property rights and a breach of this Agreement for which Customer will be fully liable to SAP.
Any attempt to access the SAP HANA database without such a license is a violation of SAP’s intellectual property rights and a breach of this Agreement for which Customer will be fully liable to SAP.
Customer’s use of the SAP HANA database is governed by the license agreement under which it is licensed to Customer and support for the SAP HANA database is provided under applicable support agreement, if any.
Customer’s use of the SAP HANA database is governed by the license agreement under which it is licensed to Customer and support for the SAP HANA database is provided under applicable support agreement, if any.
No support for the SAP HANA database accessible through SAP HANA Server (BYOL) provided under this Agreement.
No support for the SAP HANA database accessible through SAP HANA Server (BYOL) provided under this Agreement.
1 Piece = 1 block of Starter Package or 1 block of Professional Package
Starter Package block includes 8,500 Transactions and 25GB of disk space storage
Professional Package block includes 67,000 Transactions and 150GB of disk space storage
1 Transaction = 100 Basic API calls or 1 Advanced API call
Basic and Advanced API calls are specified in the Documentation.
The Cloud Service should not be used to process or store personal data.
The Cloud Service should not be used to process or store personal data.
Publicly available geo reference data accessible through the Cloud Service may only be used in the context of the Cloud Service, and Customer is responsible for ensuring the accuracy and completeness of such data. SAP is not responsible for any harm caused by such data.
Publicly available geo reference data accessible through the Cloud Service may only be used in the context of the Cloud Service, and Customer is responsible for ensuring the accuracy and completeness of such data. SAP is not responsible for any harm caused by such data.
The EU Access option is not available for the Cloud Service.
The EU Access option is not available for the Cloud Service.
Before you start creating your site in Cloud platform, you should have clear idea about site goals, content of the site, site navigation and site evolution. This chapter explains these aspects in detail.
The key points to be considered for site planning are as follows −
Site Goals
Site Navigation
Site Content
Site Evolution
You will have to use the following checklist for this purpose −
Purpose of site creation
Target audience
Business goals
End user goals
The target audience for a site can include the following −
Employees
Suppliers
Existing customers
New customers
Once your goals are identified, define the navigation for your site. This includes how user will navigate between site pages. Note that the site menu can be managed for all pages or only for few pages.
Site content must be defined which includes text, videos, graphics and images. SAP Cloud portal allows you to add custom widgets, video, URL’s and you can also create your own widgets.
You can define type of themes you want to use for your web site − you can use default theme or customized theme to meet your desired site design. Content of site includes −
Content Type
Branding
Theme
Links to be used
Feedback from site user
To create a new site, Site directory is your starting point. Site directory takes each site as card, contains site details and other relevant information about site creation.
In SAP Cloud platform, you use Site Directory to create new site and to manage access to sites which you have permissions. Site Directory is first point for creating new sites. It is also possible to sort the cards in the Site Directory using the filter list (Sort-by) at the top, and you can search for specific sites using the Search field at the top right.
Using Site Directory, you can also view sites from additional sources, as follows −
Sites that were previously exported as ZIP files from other accounts or landscapes, and then imported to the Site Directory.
Sites originated from a different account and deployed automatically to this account through SAP Cloud Platform.
To navigate to Site Directory, go to Services → Portal.
In the Overview tab of the Portal Section, you can see a short description of the service and a set of actions that can be performed. To access the launchpad(s) and the customization tool, navigate to go to Services
SAP Cloud Platform Portal lets you build digital experience portals for employees, customers, and partners. You can streamline access to business data so that your employees can execute their daily business tasks securely, from any device.
If you have already site defined, you can see list of all sites under Site directory page. To create a new site, click on card with cross button (+).
Next step is to enter a name and description for the site and click Create and Open. This will add site to Site Directory.
Using Site Directory, you can perform different tasks related to site management- import/export a site, publish a site, delete a site, etc. Following table lists different task you can perform using Site Directory → Site Actions
Create a new site
Click +Add Site or click the blank card with the cross on it.
In the Create Site dialog box, enter the Site Name and Description. Then click either Create and Open, or Save.
Import an existing site
Click +Add SiteImport Site
In the Import Site dialog box, browse to the location of the ZIP file, and Import
Change the name and description of a site
Hover over the card, click the next at the top, and enter your changes.
The text is saved automatically.
Open a site for editing
Hover over the site card and click Edit
The Authoring Space opens.
Publish a site
In the (Site actions) menu, click Publish
This action makes the site available on the web, for viewing by end users.
Take a site offline
In the (Site actions) menu, click Take Offline
This action does not delete the site, bur rather blocks end users access to it until you publish the site again.
Export a site
In the (Site actions) menu, click Export.
This action creates a ZIP file of your site structure, contents, and optionally, a list of your site guests.
Select a default site for the domain
In the (Site actions) menu, click Set as Default.
A default site is indicated by a star in the top-right Corner of the card:
Make an indentical copy of a site and its contents
In the (Site actions) menu, click Duplicate.
In the Duplicate Site dialog box, enter a Name and optional Description for the site copy, and select whether to include the existing list of site guests.
Delete a site
In the (Site actions) menu, click Delete
This action completely delets the site and its contents. You deleted and unpublished site or a site that has been takenn offline (You cannot delete a publish site.)
Using Authoring space of SAP Cloud Platform, sites can be build, design and published. Authoring tools are used to make changes to site design, and changes are immediately implemented without need of saving work. You have following authoring tools from side panel to make changes to your site −
Note − For site creation, you should have TENANT_ADMINrole (Administrator) in the SAP Cloud Platform Portal cockpit.
After creating a new site, you need to design your site properly. When a site is created, it has only one page and you need to add sub-pages and define their hierarchy. You can also define different access levels for the site.
To define site structure, click Page Management in side panel → Page Management. This will open Page Management menu. You can also use Add Page button to add a page to your site.
To add an empty placeholder to the site menu (whose subpages are displayed upon hover), select Add Title from the dropdown menu and this will add a new page entry. You can also add a link to an internal or external page or site using “AddLink” from the dropdown menu.
You can also create a new page using content from another site page → Click “Import Page” from the dropdown menu. You need to select the site and the page you want to import → click Import. This will add a new page entry and shows the name of the source page.
You can also use Edit option at the bottom right or select the browser tab in Site Directory.
On the left side, you can access various tools, editors, and services provided by the configuration cockpit. To configure the Launchpad catalog open menu item, go to Content Management → Catalogs or click the Catalogs tile.
You can also navigate to Properties tab to edit name and description of application.
Using Roles tab, you can assign Roles tab and assign role to everyone.
Using site themes, you can define overall appearance of your site. SAP Cloud platform offers predefined site themes and an administrator can add more themes to theme repository. In this chapter, let us see in detail the overall concepts involved in the site themes.
Themes used in site are defined in LESS stylesheet file - it is used to control UI part of site like font, color, etc.
To apply a theme, navigate to Design Settings → Services and Tools.
To assign custom theme to your site, navigate to Theme Manager. All the themes that you created are available under Theme manager. When you select a theme, you can check the following details under manage themes −
Title
ID
Updated By
Updated On
Theme Upgrade
Bottom toolbar provides you following options to manage the theme. Click “Assign to Site” option to assign a theme to your site.
Enable User selection
Assign to Site
Export
Edit
Delete
Once you apply all the changes, click Publish button to publish to your site.
To create a new theme, navigate to UI Theme Designer → “Create a New Theme” and select your base theme. You can select any of base theme from list of available themes.
The following steps are involved while creating a customized theme −
Choose Base Theme
Name your Theme
Set Options
In the next window, you must enter details under “Name your theme” - Theme ID and Title. You also have an option to define optional settings like Vendor, support, under Set Options.
To proceed with theme creation, click Create Theme.
To customize a theme, first define a Target Page that will act as a canvas to perform changes. Use Quick Theming mode change color, image background, etc. and click Add button to add the target pages.
You can select from the following options on the right side −
Quick Theming
Expert Theming
Defining Organization color
Add LESS or CSS to your theme
On right side panel, you can select Quick Theming option by clicking the paint brush icon. You can change logo, add brand and base color for foreground and background.
You can see below options under Quick theming. Select image you want to use for Company Logo → click OK to apply changes
Note that if you want to apply new theme to portal site, first step is to publish the theme using UI Theme Designer and apply the theme from Portal Theme Manager.
To Publish a theme, in UI Theme Designer top level menu → select Theme and then Save & Publish.
You can also validate the theme parameters that you defined while creating new theme- name, description, vendor, etc. Click on Save and Publish button as shown below to publish the theme.
While using Cloud Foundry environment, services are enabled by creating a service instance and bind the instance to application. You can create a Service instances based on specific service plan defined as configuration variant of a service.
To integrate any service of service instance with application, you need to pass service credentials to application. Achieving this, you can bind the service instances with application to automatically deliver these credentials to your application or other way is by using service keys to generate credentials to communicate directly with a service instance.
You can create an instance using cockpit or command line cloud foundry interface. The first step for this is to navigate to space where you want to create a service instance. Navigate to Services → Service Marketplace
Now, select the service for which you want to create an instance → In the navigation area, choose Instances on left side → You can see an option to create New Instance.
You can also use search option to search for a service. When you use an enterprise account, you need to add quotas to the services you purchased in your subaccount before they appear in the service marketplace or it will only display services available in trial account.
Select the service plan from the dropdown list → Next
Next is to specify a JSON file or specify parameters in the JSON format →Next. This is an optional filed to select for instance creation and you can leave it blank and click Next.
You can also assign an application that you want to bind to the new service instance, choose it from the list and click Next. This is an optional field to select.
Enter the instance name and validate parameters passed during the instance creation. You can edit any of the parameter as required. Click Finish button to complete the instance creation.
To create a service instance using Cloud Foundry Command Line interface, you can run the following command −
cf create-service SERVICE PLAN SERVICE_INSTANCE
The following parameters should be defined in above command to create s service instance −
SERVICE − This shows the name of the service in market place to create an instance.
SERVICE − This shows the name of the service in market place to create an instance.
PLAN − This is the name of the service plan you want to use in instance creation.
PLAN − This is the name of the service plan you want to use in instance creation.
SERVICE_INSTANCE − This is the name of the service instance. Note that you should use- alphanumeric characters, hyphens, and underscores.
SERVICE_INSTANCE − This is the name of the service instance. Note that you should use- alphanumeric characters, hyphens, and underscores.
You can bind a service instance to an application using cockpit or command line interface. The binding of an instances to applications can be performed both at the application view or at service-instance view in Cloud cockpit.
To create a binding at service instance view, navigate to Services → Service Instances
Select Bind Instance in the Actions column for your service instance as shown below.
Select your application from drop down and you can also specify parameters in the JSON format or select a JSON file → Save.
To bind a service instance to an application using Cloud Foundry command line interface, use the following command −
cf bind-service APP-NAME SERVICE_INSTANCE {-c PARAMETERS_AS_JSON}
In the above command, you have to pass the following parameters −
APP_NAME − You need to pass the application name.
APP_NAME − You need to pass the application name.
SERVICE_INSTANCE − You need to pass the service instance.
SERVICE_INSTANCE − You need to pass the service instance.
-c − You need to pass service-specific configuration parameters in a valid JSON object (OPTIONAL)
-c − You need to pass service-specific configuration parameters in a valid JSON object (OPTIONAL)
Service keys are used in an application to directly communicate with a service instance. When service keys are configured for service, apps from other space, outside entities can access your service using service keys. Service keys can be created using SAP Cloud cockpit or Cloud Foundry command line interface.
To create service keys using SAP Cloud cockpit, navigate to space where service instance has been created and go to Services → Service Marketplace
Select the service you want to create a service key → Select the Instance for which service key has to be created → Left side navigate to Service Keys tab.
To create Service key for instance, click on Create Service Key button. Enter a name for the service key → Optionally enter configuration parameters → Save
To create a service key using Cloud Foundry command line interface, you need to run the following command −
cf create-service-key SERVICE_INSTANCE SERVICE_KEY {-c PARAMETERS_AS_JSON}..
Now, enter the following parameters −
SERVICE_INSTANCE − This shows name of the service instance.
SERVICE_INSTANCE − This shows name of the service instance.
SERVICE_KEY − You need to mention the name for the service key.
SERVICE_KEY − You need to mention the name for the service key.
-c − (Optional) Here you need to provide service-specific configuration parameters in a valid JSON object
-c − (Optional) Here you need to provide service-specific configuration parameters in a valid JSON object
When your site is finalized, you can publish it to make it available to others. Before publishing site, you need to ensure site displays as expected. Let us deal with this concept in detail in this chapter.
You will have to check the following points should be checked before publishing a site −
Previewing your site
Before your publish your site, make sure that the site displays as your expect on every device that you need to support. It is much efficient to resolve any issue before your publish, rather than afterwards, when you would need to take your site offline to make any necessary changes.
Editing the Site URL
Before you publish your site, you can modify the suffix of the site URL to make it meaninful to your planned audience.
Choose a text string that includes the organization name, indicates the purpose of the site, and is as short as possible.
Publishing your site
After you have previewed your site and made sure that everything is correct, you can publish the site to make it avaialble online.
The Publishing Options in the side panel change according to the site status: You have the following site status available −
This shows that site has not yet been published or it has been offline after publishing for the maintenance.
This shows that site has published for other users.
This shows that site has been published however it has been modified after it was published. Once the site has been published, you can invite others to access it by sharing a URL in an email. The public sites can be accessed without restriction; however private sites need invite to users.
In the following table, you can see the steps that need to be performed for publishing and updating a site −
Publish the site
Make the site available on the Web for viewing by end users.
Click Publish.
View published site
View the published site on the desktop or mobile device.
Click Published Site to open the site in a new browser window (or tab).
Click Published Site to open the site in a new browser window (or tab).
Click QR Code and then scan the QR code for viewing the site on a mobile device.
Click QR Code and then scan the QR code for viewing the site on a mobile device.
Modify the published site
Add and remove content to and from the site, and to change the design settings. These changes cannot be seen by end users until you publish the site again.
Use the options on the side-panel menu to modify the site.
Take the site offline
Prevent end users form accessing the site. This action does not delete the site, but rather blocks access to it until you publish the site again. Site authors can still access the site.
Click Take Offline.
Cancel changes made to the site
Remove all changes made to the site since it was last published. This option is not availble for site that have never been published.
Click Revert to Last Published Site.
You can define a site as the default site to your account. This helps user to modify a site without taking it offline for maintenance. You can make changes to the site and then make the updated site as default site for your account. In this chapter, let us discuss such other site activities that can be done.
To assign default site to your account, navigate to Site directory and bring the cursor on the site card you want to make as default. From Site Action menu → click Set as default.
In SAP Cloud platform, you can also analyze statistics of portal sites which you have access. You can use Analytics dashboard to check statistical information related to Portal sites. Go to Analytics tab in Portal service to view charts or tables of statistical information about the usage of one or more selected sites.
You can use this information to better understand usage trends, and traffic peaks and lows, and thereby improve your sites to yield optimal results.
To enable it, navigate to Services and Tools → Data Privacy Management
Using Analytics option, you can find the following information −
You can view a gauge for Visits and Visitors to measure the web traffic during a time period and you can further break the report in day, hours, and mins.
You can view a gauge for Visits and Visitors to measure the web traffic during a time period and you can further break the report in day, hours, and mins.
You can also view the different devices from which the site was accessed- mobile devices, tablets or user PC.
You can also view the different devices from which the site was accessed- mobile devices, tablets or user PC.
You can also check the information related to OS type used and browser types to access the site.
You can also check the information related to OS type used and browser types to access the site.
When you click View Usage Analytics, you have an option to Visits and Visitors details (Hour, day, week and month), device type, Operating systems and browser details.
You can also translate the site and download the content in PDF, HTML and other formats. Once the files are translated, you can load them to the site and users can view it in the browser language. However, note that the site is still maintained in master language.
When site is translated to other account, translations are automatically available in site content; however, when you duplicate a site using same account, translations are not available, and you need to export them and import the site to that account.
To define a site master language, you have to navigate to Site Settings menu. The site master language is also a fall back language when the selected language is not supported by browser.
To download site content, navigate to Services and Tools and select Translation tiles in navigation pane → Configure option.
To download the master language of your portal site, click Download button as shown below. This will download the master language ZIP file onto your system.
To translate this site into multiple languages, you can use SAP Translation hub service and the zip file which you have downloaded.
Go to UI for Translation workflow and create properties file for all the languages selected for translation. When translation is done, you can load the files into portal site.
To upload, go to Translation tile → Configure → Upload
Now, browse for Zip file and open. This will process the zip files and all languages will be displayed on the screen. Note that all are inactive till you activate them. You can see the status of each language and to activate click “OFF” icon as shown below −
You can also perform site transfer from SAP Cloud platform or to create a prototype or to create site from other accounts. Basic site transfer can be performed using export/import option in Site directory.
To export site as a zip file, it can include −
Pages
Content in Open Social widgets
Theme files
Translation sites
Site user's details (Optional field)
To export a site, go to Site Directory → select the site to export and click on Site Actions → Export Site and save ZIP file to your system.
To import site, again go to Site Directory → Add site → Import Site.
This will create a site in the Site Directory and the transfer date is displayed in the Created field. You can also create a duplicate site, click on Site Actions → Duplicate Site.
Now enter the following in the name and description details −
Site name of the new site
Site Description of the new site
Next, click Duplicate button and this will create a copy of an existing site with name and description provided.
You can select “Include site users” checkbox if you want to include invited end users in the duplicated site.
Note − You should have “TENANT_ADMIN” role (Administrator) in the SAP Cloud Platform cockpit.
You can have different cloud repositories for site building maintained by SAP Cloud administrators. These repositories can be edited/modified by users with administrator privileges. The content of the cloud repositories is available in authoring space. In this chapter, let us discuss the available cloud repositories in SAP Cloud.
The following repositories are available in SAP Cloud −
Theme Repository − This is available in Theme tab in Portal service
Theme Repository − This is available in Theme tab in Portal service
Document Repository − This is available on Document tab in Portal service
Document Repository − This is available on Document tab in Portal service
Widget Repository − This is available in Content tab in Portal service
Widget Repository − This is available in Content tab in Portal service
In theme repository, themes are available in table form with details- name of the theme, description and theme creator name. Theme repository can be accessed from Themes tab of Portal service. The default theme for the account is represented using “star” shape symbol.
To create a new theme, navigate to Themes tab in the Portal service tab → Add Theme at the right corner and this will open “Add Theme” dialog box.
Enter the theme details, such as a name, description, and path to the theme file (LESS)location → Click Add button. You can also edit or delete an existing theme from repository.
Document repository contains all the documents which can be shared, reused in different sites. It contains all the documents for a given account. Document repository can be accessed from Document tab of Portal service in Cloud platform.
Documents can be uploaded and arranged in repository. You can also perform a search or download the documents and can also see site details where documents are used.
To access document repository, navigate to Portal service tab → SAP Cloud Platform cockpit → Repositories → Document Repositories
If document repository doesn’t exist, you can create a new Repository. Click on New Repository and enter the details −
Name
Display Name
Description
Description
Repository Key
Note − Repository key should be minimum 10 characters.
Also, to maintain the content integrity in repository, you cannot edit documents stored in the repository. Instead, you download a document, edit it, and upload the new, updated document.
You can also edit repository name, change repository key or delete a document repository using below options −
Widget repository contains all the available widgets for a given account. You can access Widget repository from Content tab of Portal service in Cloud platform. The widget in repository are listed in table format and shows the basic information about widgets. Following Widget types can be added to repository −
Social widget
URL widget
SAP Jam Feed widget
To manage and administrate sites, SAP Cloud platform provides different level of access and permissions. Administrators are responsible for managing content and themes of site and user level access is used to manage access related to site and published pages.
The following roles are commonly used in Cloud platform −
This is predefined as Tenant_Admin in SAP Cloud platform cockpit. The administrator is used for adding and managing content and themes.
This is used to manage access to published sites and pages. These are defined in SAP Cloud platform cockpit. Note that Authorization option is used to assign the roles to individual and user groups.
In Group tab, you can also create a new group and add users to it. To create a new group, click on New Group button and provide Group name as below −
This role is used to allow access to individuals outside organizations for site access.
When you publish a site, you can allow different level of site access to users- public, authenticated or role based.
When you allow public access to site, anyone on the web can access it.
This includes site users who are part of an organization and can access to site using predefined authentication mechanism.
This includes only few users assigned with specific role can access the site.
Note − You can also limit page access permissions from Access Management panel on left side to manage access to site pages for one or more groups. Like site access, following access level can be granted for pages −
Role - Based
Public
Guest
Go to Page settings → Page Authorization and you can see assigned access level to page. To make changes, click on Edit option on bottom right corner.
You can make changes to page access level using Access level drop down list from Page Authorizations. To save the changes, click on Save button.
To create a new role, navigate to Roles tab under Content Management → New (+) icon at bottom.
You have to define new Role properties like- Role Name and Role ID. Under Additional information, you can see Created, Creator and last modified date.
You can also assign more Catalogs and Groups to this role. Navigate to relevant tab and click on + sign to add new item. To save the changes, click on Save button.
When you assign this role to any of Page, by default it takes the assigned Catalogs name as per role properties.
You can also navigate to site setting options and edit different properties related to site- system, user and custom settings. Navigate to Settings tab on left side and this will open Site Setting menu. To make changes, click on Edit button at bottom right corner −
You can edit following System and User settings −
Site author access can be provided to edit and maintain existing sites. It can allow users to open and edit all sites to which they have assigned access and this access can also be extended to other users. When an assignment is created for the user, it sends an email to new author with URL that allow that person to access and author new site.
To check Site URL, you can navigate to Site setting tab → General → Site URL.
You can also maintain your login profile as per requirement. Click the top right corner drop down → User information → Edit.
In User profile information, you can maintain the following information −
In SAP Cloud platform, you can develop SAP UI5, HTML5 based applications and open social widgets and consume them using SAP Cloud portal service. Using SAP Cloud platform, you can develop and execute HTML5 applications in cloud platform. It can contain static resources and can be connected to other on-premise or on-demand REST service.
To develop a HTML5 application and consume it in Cloud Portal service, you need to perform the following steps −
Develop HTML5 application and save it in HANA Cloud
Develop HTML5 application and save it in HANA Cloud
Next is to convert HTML5 application to an OpenSocial widget
Next is to convert HTML5 application to an OpenSocial widget
Add the OpenSocial widget to the Portal service widget repository
Add the OpenSocial widget to the Portal service widget repository
To develop HTML5 applications, you can use the browser-based tool like SAP Web IDE that does not require any additional setup. Let us see how to develop “Hello World Application Using SAP Web IDE”.
Login to SAP Cloud Platform cockpit and click on Applications → HTML5 Applications. In case you have already created applications using this subaccount, it will show a list of HTML5 applications.
Now to develop a new HTML5 application → Click on New Application and enter an application name. Note that name of application must contain lower case alphanumeric characters and must not exceed 30 characters and start with a letter.
You can navigate to Applications page and click “Create Hello World App” to check the steps included in HTML5 development.
The following steps are involved for creating a HTML5 application −
Create a Project
Edit HTML5 application
Deploy the application to SAP Cloud platform
To deploy your application to SAP Cloud platform, right on application Deploy → Deploy to SAP Cloud platform.
Login to SAP Cloud platform and enter user name and password. You can keep “Activate” option checked and this will activate new version directly.
Click OK button for completing deployment process.
In SAP Cloud platform, objects in Portal site can be communicated to SAP Backend system. Portal service can be integrated with backend system like CRM, or SAP HR system. In this chapter, let us discuss them in detail.
To integrate, following perquisites should be met −
You should have gateway server and service has been installed.
You should have gateway server and service has been installed.
SAP Cloud connector should be installed, and connection should be defined between Gateway service and portal service.
SAP Cloud connector should be installed, and connection should be defined between Gateway service and portal service.
You should have destination defined in portal service.
You should have destination defined in portal service.
SAP Cloud Platform Connectivity option allows cloud application to connect internet service and on-premise system via Cloud Connector. SAP Cloud Administrator can create destinations so that users can build, test, and deploy applications. You configure the destination for SAP Web IDE to SAP Enterprise Portal in the SAP Cloud Platform cockpit.
For this purpose, navigate to Connectivity → Destinations and this will open destination editor. To create a new destination, click on New Destination option as below −
The following details should be entered to create a destination −
In the Additional Properties section, click New Property for each of the properties and click Save to save the destination.
Default: 10000(10 Secs)
Max: value: 120000(120 secs)
Default : 30000(30 secs)
Max: value: 300000(300 secs)
You can also edit an existing destination by selecting Destination name and click on Edit button. You also have other options like - Clone, Export, Delete, etc.
You can get a free SAP Cloud platform account with developer license to try and test the platform. This account can be used for non-productive usage and it only allows one member per account.
Besides, there are few other limitations in a trial account −
For productive purpose, you should use a commercial license for SAP Cloud platform. Following commercial license are available to be used −
For productive purpose, you should use a commercial license for SAP Cloud platform. Following commercial license are available to be used −
Contract Period
Subscription period(typically 12 months or more).
Contract Period
Consumption period(12+ months).
Available SAP Cloud Platform Services
You can use the services that are specified in your contract. Additional service require contract modifications.
Available SAP Cloud Platform services
You are entitled to use all eligible SAP Cloud Platform services. No additional contract is required for changes in usage.
Price / Cost
The cost is fixed for the duration of the subscription period, irrespective of consumption.
Price / Cost
You prepay for cloud credits, which are then balanced against consumption of services.
Payment
In advance, at the start of the contract period.
Payment
In advance, and again when cloud credits are used up*.
Renewal
At the end of the subscription period.
Renewal
At the end of the consumption period.
SAP Cloud trial account does not offer a service level agreement related to availability of SAP Cloud platform service.
SAP Cloud trial account does not offer a service level agreement related to availability of SAP Cloud platform service.
You cannot add any additional member to trial account.
You cannot add any additional member to trial account.
Free trial provides 1GB of storage on shared HANA instance.
Free trial provides 1GB of storage on shared HANA instance.
Trial version only supports Java and HTML5 application. It does not support HANA XS application development in trial account.
Trial version only supports Java and HTML5 application. It does not support HANA XS application development in trial account.
You can deploy multiple Java applications on your trial account however only one app can be in started state.
You can deploy multiple Java applications on your trial account however only one app can be in started state.
SAP Cloud platform developer is responsible for the development and management of application on Cloud platform.
Primary responsibilities of SAP Cloud platform developer are below −
Developer is responsible for providing a reliable, scalable, extensible and secure infrastructure for application development and deployment on cloud platform.
Developer is responsible for providing a reliable, scalable, extensible and secure infrastructure for application development and deployment on cloud platform.
Manage VMs, tools for setting up services on SAP Cloud Platform. Responsible for deploying and controlling the application development lifecycle.
Manage VMs, tools for setting up services on SAP Cloud Platform. Responsible for deploying and controlling the application development lifecycle.
Designing of new interfaces, wireframes and prototypes for new applications.
Designing of new interfaces, wireframes and prototypes for new applications.
Designing new application with help of application designers.
Designing new application with help of application designers.
It is preferred that developers have experience in following −
Exposure in configuring SAP Cloud Platform, Amazon Web Services, Azure, Google Cloud Platform.
Exposure in configuring SAP Cloud Platform, Amazon Web Services, Azure, Google Cloud Platform.
Development experience in Web UI programming using JavaScript, HTML5, CSS.
Development experience in Web UI programming using JavaScript, HTML5, CSS.
Development experience using SAP UI5 application development methods.
Development experience using SAP UI5 application development methods.
25 Lectures
6 hours
Sanjo Thomas
26 Lectures
2 hours
Neha Gupta
30 Lectures
2.5 hours
Sumit Agarwal
30 Lectures
4 hours
Sumit Agarwal
14 Lectures
1.5 hours
Neha Malik
13 Lectures
1.5 hours
Neha Malik
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2423,
"s": 2123,
"text": "SAP Cloud Platform is a cloud service provided by SAP based on platform as a service (PaaS) to develop and deploy custom web applications. SAP is responsible for managing complete infrastructure of this platform including hardware servers, maintenance cost, component upgrades, and system lifecycle."
},
{
"code": null,
"e": 2785,
"s": 2423,
"text": "SAP Cloud service provides full range of service catalog including database, storage and data backup, reporting service and transaction layer to develop multi-platform software development. SAP Cloud platform customers can utilize this cloud environment for managing software development or can also use a hybrid model based on cloud and on premise environment."
},
{
"code": null,
"e": 2867,
"s": 2785,
"text": "SAP Cloud platform can be integrated with following to get data and development −"
},
{
"code": null,
"e": 2884,
"s": 2867,
"text": "SAP Applications"
},
{
"code": null,
"e": 2907,
"s": 2884,
"text": "3rd party applications"
},
{
"code": null,
"e": 2926,
"s": 2907,
"text": "Internal solutions"
},
{
"code": null,
"e": 3068,
"s": 2926,
"text": "Note that the above mentioned can be on premise or on cloud and can be easily integrated with SAP Cloud platform for application development."
},
{
"code": null,
"e": 3167,
"s": 3068,
"text": "SAP Cloud platform supports business critical solutions for software development and it includes −"
},
{
"code": null,
"e": 3182,
"s": 3167,
"text": "SAP Fieldglass"
},
{
"code": null,
"e": 3202,
"s": 3182,
"text": "SAP Success factors"
},
{
"code": null,
"e": 3213,
"s": 3202,
"text": "SAP Hybris"
},
{
"code": null,
"e": 3223,
"s": 3213,
"text": "SAP Ariba"
},
{
"code": null,
"e": 3239,
"s": 3223,
"text": "BusinessObjects"
},
{
"code": null,
"e": 3262,
"s": 3239,
"text": "SAP ERP Business suite"
},
{
"code": null,
"e": 3269,
"s": 3262,
"text": "Concur"
},
{
"code": null,
"e": 3515,
"s": 3269,
"text": "You can migrate apps and extensions seamlessly to SAP Cloud platform including SAP Business suite and SAP S/4 HANA. All the data centers are managed by SAP itself, so you can expect the given key benefits associated with data center management −"
},
{
"code": null,
"e": 3524,
"s": 3515,
"text": "Security"
},
{
"code": null,
"e": 3535,
"s": 3524,
"text": "Compliance"
},
{
"code": null,
"e": 3548,
"s": 3535,
"text": "Availability"
},
{
"code": null,
"e": 3759,
"s": 3548,
"text": "SAP Cloud platform offers PaaS based in-memory and microservice based mobile enabled cloud applications. SAP Cloud Platform provides you an option to control your choice of clouds, frameworks, and applications."
},
{
"code": null,
"e": 3910,
"s": 3759,
"text": "To know more about SAP Cloud platform and services offered by Cloud service, you can navigate to this link − https://cloudplatform.sap.com/index.html"
},
{
"code": null,
"e": 4104,
"s": 3910,
"text": "SAP Cloud platform also provides a free trial. For creating a trial account, you need to click “Start your free trial” button as shown below. You can also chat with SAP experts for any queries."
},
{
"code": null,
"e": 4290,
"s": 4104,
"text": "To register for free trail, you need to provide your work email id, and other details. Once you successfully submit all the details, you can use that for logging into the Cloud service."
},
{
"code": null,
"e": 4524,
"s": 4290,
"text": "Once you provide all details and login, you will get a message − “Welcome to your free trial”. To start your trial, click the blue icon - “Click here to start your trial”. SAP also assigns you a unique User Id for your trial period."
},
{
"code": null,
"e": 4584,
"s": 4524,
"text": "Once you login, it takes you to SAP Cloud platform cockpit."
},
{
"code": null,
"e": 4939,
"s": 4584,
"text": "SAP Cloud Platform cockpit is the central Web-based user interface for administrators, and you can use this for providing access to various functions for configuring and managing applications using SAP Cloud platform. You can use the cockpit to manage resources, services, security, monitor application metrics, and perform actions on cloud applications."
},
{
"code": null,
"e": 5191,
"s": 4939,
"text": "The service level agreement for SAP Cloud service is applicable to Cloud service mentioned in service description guide. You can check detail on Service level agreement using this link −1 https://cloudplatform.sap.com/support/service-description.html"
},
{
"code": null,
"e": 5476,
"s": 5191,
"text": "The System Availability SLA for all Cloud Services is 99.9% per month. Any deviations from the 99.9% System Availability SLA or any aspect of the standard Service Level Agreement for SAP Cloud Services are noted in the applicable Cloud Service terms in this Service Description Guide."
},
{
"code": null,
"e": 5577,
"s": 5476,
"text": "You can check the details using this link − https://www.sap.com/about/agreements/cloud-services.html"
},
{
"code": null,
"e": 6295,
"s": 5577,
"text": "As per SAP - High Availability option for HANA and ASE Service in SAP’s data centers, SAP shall provide High Availability for SAP Cloud Platform, HANA service or SAP Cloud Platform ASE service with an availability SLA of 99.95% per month if Customer has allocated to High Availability via SAP Cloud Platform provisioning self-service a duplicate of SAP Cloud Platform, HANA service or SAP Cloud Platform ASE service, as applicable. The duplicate SAP Cloud Platform services allocated to High Availability require separate subscriptions (and associated fees). In all other respects, the Service Level Agreement for SAP Cloud Services referenced in the Order Form applies to the applicable SAP Cloud Platform services."
},
{
"code": null,
"e": 6337,
"s": 6295,
"text": "Precondition to System Availability SLA −"
},
{
"code": null,
"e": 6419,
"s": 6337,
"text": "Java Platform Applications need to run with minimum 2 application processes/nodes"
},
{
"code": null,
"e": 6501,
"s": 6419,
"text": "Java Platform Applications need to run with minimum 2 application processes/nodes"
},
{
"code": null,
"e": 6574,
"s": 6501,
"text": "Java Platform Applications need to have an availability check configured"
},
{
"code": null,
"e": 6647,
"s": 6574,
"text": "Java Platform Applications need to have an availability check configured"
},
{
"code": null,
"e": 6739,
"s": 6647,
"text": "SAP HANA Cloud Platform, Java server (x-small) = SAP HANA Cloud Platform, compute unit lite"
},
{
"code": null,
"e": 6832,
"s": 6739,
"text": "SAP HANA Cloud Platform, Java server (small) = SAP HANA Cloud Platform, compute professional"
},
{
"code": null,
"e": 6921,
"s": 6832,
"text": "SAP HANA Cloud Platform, Java server (medium) = SAP HANA Cloud Platform, compute premium"
},
{
"code": null,
"e": 7014,
"s": 6921,
"text": "SAP HANA Cloud Platform, Java server (large) = SAP HANA Cloud Platform, compute premium plus"
},
{
"code": null,
"e": 7118,
"s": 7014,
"text": "Customer may use the Cloud Service to host and run separately licensed SAP or third-party applications."
},
{
"code": null,
"e": 7222,
"s": 7118,
"text": "Customer may use the Cloud Service to host and run separately licensed SAP or third-party applications."
},
{
"code": null,
"e": 7371,
"s": 7222,
"text": "Customer is solely responsible for the security, maintenance, management and support of the applications installed by Customer on the Cloud Service."
},
{
"code": null,
"e": 7520,
"s": 7371,
"text": "Customer is solely responsible for the security, maintenance, management and support of the applications installed by Customer on the Cloud Service."
},
{
"code": null,
"e": 7630,
"s": 7520,
"text": "Customer is responsible for back up of Customer Data – no back up services are included in the Cloud Service."
},
{
"code": null,
"e": 7740,
"s": 7630,
"text": "Customer is responsible for back up of Customer Data – no back up services are included in the Cloud Service."
},
{
"code": null,
"e": 7878,
"s": 7740,
"text": "The Cloud Service is provided through a single data center. As such, no redundant data center is included for disaster recovery services."
},
{
"code": null,
"e": 8016,
"s": 7878,
"text": "The Cloud Service is provided through a single data center. As such, no redundant data center is included for disaster recovery services."
},
{
"code": null,
"e": 8205,
"s": 8016,
"text": "Customer is solely responsible for managing and updating the OS layer of the Cloud Service, including patching the OS with the most recent security patches made available by the OS vendor."
},
{
"code": null,
"e": 8394,
"s": 8205,
"text": "Customer is solely responsible for managing and updating the OS layer of the Cloud Service, including patching the OS with the most recent security patches made available by the OS vendor."
},
{
"code": null,
"e": 8762,
"s": 8394,
"text": "Customer shall fully compensate SAP (without effect of any limitations on liability in the GTCs) for any damages or expenses incurred by SAP as a result of a claim by a third party that any Customer or third-party software or other technology hosted or run on the Customer’s Cloud Service virtual machine infringes or otherwise violates the rights of the third party."
},
{
"code": null,
"e": 8897,
"s": 8762,
"text": "SAP Cloud Platform Portal is limited to access by individuals within the Customer’s organization, including employees and contractors."
},
{
"code": null,
"e": 9032,
"s": 8897,
"text": "SAP Cloud Platform Portal is limited to access by individuals within the Customer’s organization, including employees and contractors."
},
{
"code": null,
"e": 9092,
"s": 9032,
"text": "Each SAP Cloud Platform Portal subscription also includes −"
},
{
"code": null,
"e": 9152,
"s": 9092,
"text": "Each SAP Cloud Platform Portal subscription also includes −"
},
{
"code": null,
"e": 9228,
"s": 9152,
"text": "30 logons of SAP Cloud Platform Identity Authentication per User, per month"
},
{
"code": null,
"e": 9304,
"s": 9228,
"text": "30 logons of SAP Cloud Platform Identity Authentication per User, per month"
},
{
"code": null,
"e": 9421,
"s": 9304,
"text": "SAP Cloud Platform SAP HANA Server (BYOL) does not include a license to the SAP HANA database or any other database."
},
{
"code": null,
"e": 9538,
"s": 9421,
"text": "SAP Cloud Platform SAP HANA Server (BYOL) does not include a license to the SAP HANA database or any other database."
},
{
"code": null,
"e": 9872,
"s": 9538,
"text": "Customer must have a valid license agreement for the SAP HANA database in order subscribe to SAP Cloud Platform SAP HANA Server (BYOL). Customer may not use SAP Cloud Platform SAP HANA Server (BYOL) or copy, access or use the SAP HANA database software accessible through the SAP HANA HANA server (BYOL) without such current license."
},
{
"code": null,
"e": 10206,
"s": 9872,
"text": "Customer must have a valid license agreement for the SAP HANA database in order subscribe to SAP Cloud Platform SAP HANA Server (BYOL). Customer may not use SAP Cloud Platform SAP HANA Server (BYOL) or copy, access or use the SAP HANA database software accessible through the SAP HANA HANA server (BYOL) without such current license."
},
{
"code": null,
"e": 10405,
"s": 10206,
"text": "Any attempt to access the SAP HANA database without such a license is a violation of SAP’s intellectual property rights and a breach of this Agreement for which Customer will be fully liable to SAP."
},
{
"code": null,
"e": 10604,
"s": 10405,
"text": "Any attempt to access the SAP HANA database without such a license is a violation of SAP’s intellectual property rights and a breach of this Agreement for which Customer will be fully liable to SAP."
},
{
"code": null,
"e": 10814,
"s": 10604,
"text": "Customer’s use of the SAP HANA database is governed by the license agreement under which it is licensed to Customer and support for the SAP HANA database is provided under applicable support agreement, if any."
},
{
"code": null,
"e": 11024,
"s": 10814,
"text": "Customer’s use of the SAP HANA database is governed by the license agreement under which it is licensed to Customer and support for the SAP HANA database is provided under applicable support agreement, if any."
},
{
"code": null,
"e": 11134,
"s": 11024,
"text": "No support for the SAP HANA database accessible through SAP HANA Server (BYOL) provided under this Agreement."
},
{
"code": null,
"e": 11244,
"s": 11134,
"text": "No support for the SAP HANA database accessible through SAP HANA Server (BYOL) provided under this Agreement."
},
{
"code": null,
"e": 11316,
"s": 11244,
"text": "1 Piece = 1 block of Starter Package or 1 block of Professional Package"
},
{
"code": null,
"e": 11397,
"s": 11316,
"text": "Starter Package block includes 8,500 Transactions and 25GB of disk space storage"
},
{
"code": null,
"e": 11485,
"s": 11397,
"text": "Professional Package block includes 67,000 Transactions and 150GB of disk space storage"
},
{
"code": null,
"e": 11544,
"s": 11485,
"text": "1 Transaction = 100 Basic API calls or 1 Advanced API call"
},
{
"code": null,
"e": 11609,
"s": 11544,
"text": "Basic and Advanced API calls are specified in the Documentation."
},
{
"code": null,
"e": 11681,
"s": 11609,
"text": "The Cloud Service should not be used to process or store personal data."
},
{
"code": null,
"e": 11753,
"s": 11681,
"text": "The Cloud Service should not be used to process or store personal data."
},
{
"code": null,
"e": 12024,
"s": 11753,
"text": "Publicly available geo reference data accessible through the Cloud Service may only be used in the context of the Cloud Service, and Customer is responsible for ensuring the accuracy and completeness of such data. SAP is not responsible for any harm caused by such data."
},
{
"code": null,
"e": 12295,
"s": 12024,
"text": "Publicly available geo reference data accessible through the Cloud Service may only be used in the context of the Cloud Service, and Customer is responsible for ensuring the accuracy and completeness of such data. SAP is not responsible for any harm caused by such data."
},
{
"code": null,
"e": 12356,
"s": 12295,
"text": "The EU Access option is not available for the Cloud Service."
},
{
"code": null,
"e": 12417,
"s": 12356,
"text": "The EU Access option is not available for the Cloud Service."
},
{
"code": null,
"e": 12621,
"s": 12417,
"text": "Before you start creating your site in Cloud platform, you should have clear idea about site goals, content of the site, site navigation and site evolution. This chapter explains these aspects in detail."
},
{
"code": null,
"e": 12688,
"s": 12621,
"text": "The key points to be considered for site planning are as follows −"
},
{
"code": null,
"e": 12699,
"s": 12688,
"text": "Site Goals"
},
{
"code": null,
"e": 12715,
"s": 12699,
"text": "Site Navigation"
},
{
"code": null,
"e": 12728,
"s": 12715,
"text": "Site Content"
},
{
"code": null,
"e": 12743,
"s": 12728,
"text": "Site Evolution"
},
{
"code": null,
"e": 12807,
"s": 12743,
"text": "You will have to use the following checklist for this purpose −"
},
{
"code": null,
"e": 12832,
"s": 12807,
"text": "Purpose of site creation"
},
{
"code": null,
"e": 12848,
"s": 12832,
"text": "Target audience"
},
{
"code": null,
"e": 12863,
"s": 12848,
"text": "Business goals"
},
{
"code": null,
"e": 12878,
"s": 12863,
"text": "End user goals"
},
{
"code": null,
"e": 12937,
"s": 12878,
"text": "The target audience for a site can include the following −"
},
{
"code": null,
"e": 12947,
"s": 12937,
"text": "Employees"
},
{
"code": null,
"e": 12957,
"s": 12947,
"text": "Suppliers"
},
{
"code": null,
"e": 12976,
"s": 12957,
"text": "Existing customers"
},
{
"code": null,
"e": 12990,
"s": 12976,
"text": "New customers"
},
{
"code": null,
"e": 13192,
"s": 12990,
"text": "Once your goals are identified, define the navigation for your site. This includes how user will navigate between site pages. Note that the site menu can be managed for all pages or only for few pages."
},
{
"code": null,
"e": 13377,
"s": 13192,
"text": "Site content must be defined which includes text, videos, graphics and images. SAP Cloud portal allows you to add custom widgets, video, URL’s and you can also create your own widgets."
},
{
"code": null,
"e": 13551,
"s": 13377,
"text": "You can define type of themes you want to use for your web site − you can use default theme or customized theme to meet your desired site design. Content of site includes −"
},
{
"code": null,
"e": 13564,
"s": 13551,
"text": "Content Type"
},
{
"code": null,
"e": 13573,
"s": 13564,
"text": "Branding"
},
{
"code": null,
"e": 13579,
"s": 13573,
"text": "Theme"
},
{
"code": null,
"e": 13596,
"s": 13579,
"text": "Links to be used"
},
{
"code": null,
"e": 13620,
"s": 13596,
"text": "Feedback from site user"
},
{
"code": null,
"e": 13795,
"s": 13620,
"text": "To create a new site, Site directory is your starting point. Site directory takes each site as card, contains site details and other relevant information about site creation."
},
{
"code": null,
"e": 14155,
"s": 13795,
"text": "In SAP Cloud platform, you use Site Directory to create new site and to manage access to sites which you have permissions. Site Directory is first point for creating new sites. It is also possible to sort the cards in the Site Directory using the filter list (Sort-by) at the top, and you can search for specific sites using the Search field at the top right."
},
{
"code": null,
"e": 14239,
"s": 14155,
"text": "Using Site Directory, you can also view sites from additional sources, as follows −"
},
{
"code": null,
"e": 14364,
"s": 14239,
"text": "Sites that were previously exported as ZIP files from other accounts or landscapes, and then imported to the Site Directory."
},
{
"code": null,
"e": 14477,
"s": 14364,
"text": "Sites originated from a different account and deployed automatically to this account through SAP Cloud Platform."
},
{
"code": null,
"e": 14533,
"s": 14477,
"text": "To navigate to Site Directory, go to Services → Portal."
},
{
"code": null,
"e": 14749,
"s": 14533,
"text": "In the Overview tab of the Portal Section, you can see a short description of the service and a set of actions that can be performed. To access the launchpad(s) and the customization tool, navigate to go to Services"
},
{
"code": null,
"e": 14989,
"s": 14749,
"text": "SAP Cloud Platform Portal lets you build digital experience portals for employees, customers, and partners. You can streamline access to business data so that your employees can execute their daily business tasks securely, from any device."
},
{
"code": null,
"e": 15139,
"s": 14989,
"text": "If you have already site defined, you can see list of all sites under Site directory page. To create a new site, click on card with cross button (+)."
},
{
"code": null,
"e": 15262,
"s": 15139,
"text": "Next step is to enter a name and description for the site and click Create and Open. This will add site to Site Directory."
},
{
"code": null,
"e": 15491,
"s": 15262,
"text": "Using Site Directory, you can perform different tasks related to site management- import/export a site, publish a site, delete a site, etc. Following table lists different task you can perform using Site Directory → Site Actions"
},
{
"code": null,
"e": 15509,
"s": 15491,
"text": "Create a new site"
},
{
"code": null,
"e": 15571,
"s": 15509,
"text": "Click +Add Site or click the blank card with the cross on it."
},
{
"code": null,
"e": 15683,
"s": 15571,
"text": "In the Create Site dialog box, enter the Site Name and Description. Then click either Create and Open, or Save."
},
{
"code": null,
"e": 15707,
"s": 15683,
"text": "Import an existing site"
},
{
"code": null,
"e": 15734,
"s": 15707,
"text": "Click +Add SiteImport Site"
},
{
"code": null,
"e": 15816,
"s": 15734,
"text": "In the Import Site dialog box, browse to the location of the ZIP file, and Import"
},
{
"code": null,
"e": 15858,
"s": 15816,
"text": "Change the name and description of a site"
},
{
"code": null,
"e": 15930,
"s": 15858,
"text": "Hover over the card, click the next at the top, and enter your changes."
},
{
"code": null,
"e": 15963,
"s": 15930,
"text": "The text is saved automatically."
},
{
"code": null,
"e": 15987,
"s": 15963,
"text": "Open a site for editing"
},
{
"code": null,
"e": 16027,
"s": 15987,
"text": "Hover over the site card and click Edit"
},
{
"code": null,
"e": 16054,
"s": 16027,
"text": "The Authoring Space opens."
},
{
"code": null,
"e": 16069,
"s": 16054,
"text": "Publish a site"
},
{
"code": null,
"e": 16111,
"s": 16069,
"text": "In the (Site actions) menu, click Publish"
},
{
"code": null,
"e": 16186,
"s": 16111,
"text": "This action makes the site available on the web, for viewing by end users."
},
{
"code": null,
"e": 16206,
"s": 16186,
"text": "Take a site offline"
},
{
"code": null,
"e": 16253,
"s": 16206,
"text": "In the (Site actions) menu, click Take Offline"
},
{
"code": null,
"e": 16366,
"s": 16253,
"text": "This action does not delete the site, bur rather blocks end users access to it until you publish the site again."
},
{
"code": null,
"e": 16380,
"s": 16366,
"text": "Export a site"
},
{
"code": null,
"e": 16422,
"s": 16380,
"text": "In the (Site actions) menu, click Export."
},
{
"code": null,
"e": 16531,
"s": 16422,
"text": "This action creates a ZIP file of your site structure, contents, and optionally, a list of your site guests."
},
{
"code": null,
"e": 16568,
"s": 16531,
"text": "Select a default site for the domain"
},
{
"code": null,
"e": 16618,
"s": 16568,
"text": "In the (Site actions) menu, click Set as Default."
},
{
"code": null,
"e": 16693,
"s": 16618,
"text": "A default site is indicated by a star in the top-right Corner of the card:"
},
{
"code": null,
"e": 16744,
"s": 16693,
"text": "Make an indentical copy of a site and its contents"
},
{
"code": null,
"e": 16789,
"s": 16744,
"text": "In the (Site actions) menu, click Duplicate."
},
{
"code": null,
"e": 16944,
"s": 16789,
"text": "In the Duplicate Site dialog box, enter a Name and optional Description for the site copy, and select whether to include the existing list of site guests."
},
{
"code": null,
"e": 16958,
"s": 16944,
"text": "Delete a site"
},
{
"code": null,
"e": 16999,
"s": 16958,
"text": "In the (Site actions) menu, click Delete"
},
{
"code": null,
"e": 17164,
"s": 16999,
"text": "This action completely delets the site and its contents. You deleted and unpublished site or a site that has been takenn offline (You cannot delete a publish site.)"
},
{
"code": null,
"e": 17459,
"s": 17164,
"text": "Using Authoring space of SAP Cloud Platform, sites can be build, design and published. Authoring tools are used to make changes to site design, and changes are immediately implemented without need of saving work. You have following authoring tools from side panel to make changes to your site −"
},
{
"code": null,
"e": 17576,
"s": 17459,
"text": "Note − For site creation, you should have TENANT_ADMINrole (Administrator) in the SAP Cloud Platform Portal cockpit."
},
{
"code": null,
"e": 17803,
"s": 17576,
"text": "After creating a new site, you need to design your site properly. When a site is created, it has only one page and you need to add sub-pages and define their hierarchy. You can also define different access levels for the site."
},
{
"code": null,
"e": 17982,
"s": 17803,
"text": "To define site structure, click Page Management in side panel → Page Management. This will open Page Management menu. You can also use Add Page button to add a page to your site."
},
{
"code": null,
"e": 18250,
"s": 17982,
"text": "To add an empty placeholder to the site menu (whose subpages are displayed upon hover), select Add Title from the dropdown menu and this will add a new page entry. You can also add a link to an internal or external page or site using “AddLink” from the dropdown menu."
},
{
"code": null,
"e": 18511,
"s": 18250,
"text": "You can also create a new page using content from another site page → Click “Import Page” from the dropdown menu. You need to select the site and the page you want to import → click Import. This will add a new page entry and shows the name of the source page."
},
{
"code": null,
"e": 18605,
"s": 18511,
"text": "You can also use Edit option at the bottom right or select the browser tab in Site Directory."
},
{
"code": null,
"e": 18829,
"s": 18605,
"text": "On the left side, you can access various tools, editors, and services provided by the configuration cockpit. To configure the Launchpad catalog open menu item, go to Content Management → Catalogs or click the Catalogs tile."
},
{
"code": null,
"e": 18914,
"s": 18829,
"text": "You can also navigate to Properties tab to edit name and description of application."
},
{
"code": null,
"e": 18985,
"s": 18914,
"text": "Using Roles tab, you can assign Roles tab and assign role to everyone."
},
{
"code": null,
"e": 19251,
"s": 18985,
"text": "Using site themes, you can define overall appearance of your site. SAP Cloud platform offers predefined site themes and an administrator can add more themes to theme repository. In this chapter, let us see in detail the overall concepts involved in the site themes."
},
{
"code": null,
"e": 19370,
"s": 19251,
"text": "Themes used in site are defined in LESS stylesheet file - it is used to control UI part of site like font, color, etc."
},
{
"code": null,
"e": 19438,
"s": 19370,
"text": "To apply a theme, navigate to Design Settings → Services and Tools."
},
{
"code": null,
"e": 19652,
"s": 19438,
"text": "To assign custom theme to your site, navigate to Theme Manager. All the themes that you created are available under Theme manager. When you select a theme, you can check the following details under manage themes −"
},
{
"code": null,
"e": 19658,
"s": 19652,
"text": "Title"
},
{
"code": null,
"e": 19661,
"s": 19658,
"text": "ID"
},
{
"code": null,
"e": 19672,
"s": 19661,
"text": "Updated By"
},
{
"code": null,
"e": 19683,
"s": 19672,
"text": "Updated On"
},
{
"code": null,
"e": 19697,
"s": 19683,
"text": "Theme Upgrade"
},
{
"code": null,
"e": 19826,
"s": 19697,
"text": "Bottom toolbar provides you following options to manage the theme. Click “Assign to Site” option to assign a theme to your site."
},
{
"code": null,
"e": 19848,
"s": 19826,
"text": "Enable User selection"
},
{
"code": null,
"e": 19863,
"s": 19848,
"text": "Assign to Site"
},
{
"code": null,
"e": 19870,
"s": 19863,
"text": "Export"
},
{
"code": null,
"e": 19875,
"s": 19870,
"text": "Edit"
},
{
"code": null,
"e": 19882,
"s": 19875,
"text": "Delete"
},
{
"code": null,
"e": 19960,
"s": 19882,
"text": "Once you apply all the changes, click Publish button to publish to your site."
},
{
"code": null,
"e": 20128,
"s": 19960,
"text": "To create a new theme, navigate to UI Theme Designer → “Create a New Theme” and select your base theme. You can select any of base theme from list of available themes."
},
{
"code": null,
"e": 20197,
"s": 20128,
"text": "The following steps are involved while creating a customized theme −"
},
{
"code": null,
"e": 20215,
"s": 20197,
"text": "Choose Base Theme"
},
{
"code": null,
"e": 20231,
"s": 20215,
"text": "Name your Theme"
},
{
"code": null,
"e": 20243,
"s": 20231,
"text": "Set Options"
},
{
"code": null,
"e": 20425,
"s": 20243,
"text": "In the next window, you must enter details under “Name your theme” - Theme ID and Title. You also have an option to define optional settings like Vendor, support, under Set Options."
},
{
"code": null,
"e": 20477,
"s": 20425,
"text": "To proceed with theme creation, click Create Theme."
},
{
"code": null,
"e": 20678,
"s": 20477,
"text": "To customize a theme, first define a Target Page that will act as a canvas to perform changes. Use Quick Theming mode change color, image background, etc. and click Add button to add the target pages."
},
{
"code": null,
"e": 20740,
"s": 20678,
"text": "You can select from the following options on the right side −"
},
{
"code": null,
"e": 20754,
"s": 20740,
"text": "Quick Theming"
},
{
"code": null,
"e": 20769,
"s": 20754,
"text": "Expert Theming"
},
{
"code": null,
"e": 20797,
"s": 20769,
"text": "Defining Organization color"
},
{
"code": null,
"e": 20827,
"s": 20797,
"text": "Add LESS or CSS to your theme"
},
{
"code": null,
"e": 20995,
"s": 20827,
"text": "On right side panel, you can select Quick Theming option by clicking the paint brush icon. You can change logo, add brand and base color for foreground and background."
},
{
"code": null,
"e": 21116,
"s": 20995,
"text": "You can see below options under Quick theming. Select image you want to use for Company Logo → click OK to apply changes"
},
{
"code": null,
"e": 21279,
"s": 21116,
"text": "Note that if you want to apply new theme to portal site, first step is to publish the theme using UI Theme Designer and apply the theme from Portal Theme Manager."
},
{
"code": null,
"e": 21375,
"s": 21279,
"text": "To Publish a theme, in UI Theme Designer top level menu → select Theme and then Save & Publish."
},
{
"code": null,
"e": 21563,
"s": 21375,
"text": "You can also validate the theme parameters that you defined while creating new theme- name, description, vendor, etc. Click on Save and Publish button as shown below to publish the theme."
},
{
"code": null,
"e": 21805,
"s": 21563,
"text": "While using Cloud Foundry environment, services are enabled by creating a service instance and bind the instance to application. You can create a Service instances based on specific service plan defined as configuration variant of a service."
},
{
"code": null,
"e": 22163,
"s": 21805,
"text": "To integrate any service of service instance with application, you need to pass service credentials to application. Achieving this, you can bind the service instances with application to automatically deliver these credentials to your application or other way is by using service keys to generate credentials to communicate directly with a service instance."
},
{
"code": null,
"e": 22381,
"s": 22163,
"text": "You can create an instance using cockpit or command line cloud foundry interface. The first step for this is to navigate to space where you want to create a service instance. Navigate to Services → Service Marketplace"
},
{
"code": null,
"e": 22550,
"s": 22381,
"text": "Now, select the service for which you want to create an instance → In the navigation area, choose Instances on left side → You can see an option to create New Instance."
},
{
"code": null,
"e": 22821,
"s": 22550,
"text": "You can also use search option to search for a service. When you use an enterprise account, you need to add quotas to the services you purchased in your subaccount before they appear in the service marketplace or it will only display services available in trial account."
},
{
"code": null,
"e": 22875,
"s": 22821,
"text": "Select the service plan from the dropdown list → Next"
},
{
"code": null,
"e": 23055,
"s": 22875,
"text": "Next is to specify a JSON file or specify parameters in the JSON format →Next. This is an optional filed to select for instance creation and you can leave it blank and click Next."
},
{
"code": null,
"e": 23218,
"s": 23055,
"text": "You can also assign an application that you want to bind to the new service instance, choose it from the list and click Next. This is an optional field to select."
},
{
"code": null,
"e": 23405,
"s": 23218,
"text": "Enter the instance name and validate parameters passed during the instance creation. You can edit any of the parameter as required. Click Finish button to complete the instance creation."
},
{
"code": null,
"e": 23514,
"s": 23405,
"text": "To create a service instance using Cloud Foundry Command Line interface, you can run the following command −"
},
{
"code": null,
"e": 23563,
"s": 23514,
"text": "cf create-service SERVICE PLAN SERVICE_INSTANCE\n"
},
{
"code": null,
"e": 23654,
"s": 23563,
"text": "The following parameters should be defined in above command to create s service instance −"
},
{
"code": null,
"e": 23738,
"s": 23654,
"text": "SERVICE − This shows the name of the service in market place to create an instance."
},
{
"code": null,
"e": 23822,
"s": 23738,
"text": "SERVICE − This shows the name of the service in market place to create an instance."
},
{
"code": null,
"e": 23904,
"s": 23822,
"text": "PLAN − This is the name of the service plan you want to use in instance creation."
},
{
"code": null,
"e": 23986,
"s": 23904,
"text": "PLAN − This is the name of the service plan you want to use in instance creation."
},
{
"code": null,
"e": 24124,
"s": 23986,
"text": "SERVICE_INSTANCE − This is the name of the service instance. Note that you should use- alphanumeric characters, hyphens, and underscores."
},
{
"code": null,
"e": 24262,
"s": 24124,
"text": "SERVICE_INSTANCE − This is the name of the service instance. Note that you should use- alphanumeric characters, hyphens, and underscores."
},
{
"code": null,
"e": 24489,
"s": 24262,
"text": "You can bind a service instance to an application using cockpit or command line interface. The binding of an instances to applications can be performed both at the application view or at service-instance view in Cloud cockpit."
},
{
"code": null,
"e": 24576,
"s": 24489,
"text": "To create a binding at service instance view, navigate to Services → Service Instances"
},
{
"code": null,
"e": 24661,
"s": 24576,
"text": "Select Bind Instance in the Actions column for your service instance as shown below."
},
{
"code": null,
"e": 24785,
"s": 24661,
"text": "Select your application from drop down and you can also specify parameters in the JSON format or select a JSON file → Save."
},
{
"code": null,
"e": 24902,
"s": 24785,
"text": "To bind a service instance to an application using Cloud Foundry command line interface, use the following command −"
},
{
"code": null,
"e": 24969,
"s": 24902,
"text": "cf bind-service APP-NAME SERVICE_INSTANCE {-c PARAMETERS_AS_JSON}\n"
},
{
"code": null,
"e": 25035,
"s": 24969,
"text": "In the above command, you have to pass the following parameters −"
},
{
"code": null,
"e": 25085,
"s": 25035,
"text": "APP_NAME − You need to pass the application name."
},
{
"code": null,
"e": 25135,
"s": 25085,
"text": "APP_NAME − You need to pass the application name."
},
{
"code": null,
"e": 25193,
"s": 25135,
"text": "SERVICE_INSTANCE − You need to pass the service instance."
},
{
"code": null,
"e": 25251,
"s": 25193,
"text": "SERVICE_INSTANCE − You need to pass the service instance."
},
{
"code": null,
"e": 25349,
"s": 25251,
"text": "-c − You need to pass service-specific configuration parameters in a valid JSON object (OPTIONAL)"
},
{
"code": null,
"e": 25447,
"s": 25349,
"text": "-c − You need to pass service-specific configuration parameters in a valid JSON object (OPTIONAL)"
},
{
"code": null,
"e": 25759,
"s": 25447,
"text": "Service keys are used in an application to directly communicate with a service instance. When service keys are configured for service, apps from other space, outside entities can access your service using service keys. Service keys can be created using SAP Cloud cockpit or Cloud Foundry command line interface."
},
{
"code": null,
"e": 25906,
"s": 25759,
"text": "To create service keys using SAP Cloud cockpit, navigate to space where service instance has been created and go to Services → Service Marketplace"
},
{
"code": null,
"e": 26062,
"s": 25906,
"text": "Select the service you want to create a service key → Select the Instance for which service key has to be created → Left side navigate to Service Keys tab."
},
{
"code": null,
"e": 26218,
"s": 26062,
"text": "To create Service key for instance, click on Create Service Key button. Enter a name for the service key → Optionally enter configuration parameters → Save"
},
{
"code": null,
"e": 26326,
"s": 26218,
"text": "To create a service key using Cloud Foundry command line interface, you need to run the following command −"
},
{
"code": null,
"e": 26404,
"s": 26326,
"text": "cf create-service-key SERVICE_INSTANCE SERVICE_KEY {-c PARAMETERS_AS_JSON}..\n"
},
{
"code": null,
"e": 26442,
"s": 26404,
"text": "Now, enter the following parameters −"
},
{
"code": null,
"e": 26502,
"s": 26442,
"text": "SERVICE_INSTANCE − This shows name of the service instance."
},
{
"code": null,
"e": 26562,
"s": 26502,
"text": "SERVICE_INSTANCE − This shows name of the service instance."
},
{
"code": null,
"e": 26626,
"s": 26562,
"text": "SERVICE_KEY − You need to mention the name for the service key."
},
{
"code": null,
"e": 26690,
"s": 26626,
"text": "SERVICE_KEY − You need to mention the name for the service key."
},
{
"code": null,
"e": 26796,
"s": 26690,
"text": "-c − (Optional) Here you need to provide service-specific configuration parameters in a valid JSON object"
},
{
"code": null,
"e": 26902,
"s": 26796,
"text": "-c − (Optional) Here you need to provide service-specific configuration parameters in a valid JSON object"
},
{
"code": null,
"e": 27109,
"s": 26902,
"text": "When your site is finalized, you can publish it to make it available to others. Before publishing site, you need to ensure site displays as expected. Let us deal with this concept in detail in this chapter."
},
{
"code": null,
"e": 27198,
"s": 27109,
"text": "You will have to check the following points should be checked before publishing a site −"
},
{
"code": null,
"e": 27219,
"s": 27198,
"text": "Previewing your site"
},
{
"code": null,
"e": 27504,
"s": 27219,
"text": "Before your publish your site, make sure that the site displays as your expect on every device that you need to support. It is much efficient to resolve any issue before your publish, rather than afterwards, when you would need to take your site offline to make any necessary changes."
},
{
"code": null,
"e": 27525,
"s": 27504,
"text": "Editing the Site URL"
},
{
"code": null,
"e": 27644,
"s": 27525,
"text": "Before you publish your site, you can modify the suffix of the site URL to make it meaninful to your planned audience."
},
{
"code": null,
"e": 27766,
"s": 27644,
"text": "Choose a text string that includes the organization name, indicates the purpose of the site, and is as short as possible."
},
{
"code": null,
"e": 27787,
"s": 27766,
"text": "Publishing your site"
},
{
"code": null,
"e": 27918,
"s": 27787,
"text": "After you have previewed your site and made sure that everything is correct, you can publish the site to make it avaialble online."
},
{
"code": null,
"e": 28043,
"s": 27918,
"text": "The Publishing Options in the side panel change according to the site status: You have the following site status available −"
},
{
"code": null,
"e": 28152,
"s": 28043,
"text": "This shows that site has not yet been published or it has been offline after publishing for the maintenance."
},
{
"code": null,
"e": 28204,
"s": 28152,
"text": "This shows that site has published for other users."
},
{
"code": null,
"e": 28494,
"s": 28204,
"text": "This shows that site has been published however it has been modified after it was published. Once the site has been published, you can invite others to access it by sharing a URL in an email. The public sites can be accessed without restriction; however private sites need invite to users."
},
{
"code": null,
"e": 28603,
"s": 28494,
"text": "In the following table, you can see the steps that need to be performed for publishing and updating a site −"
},
{
"code": null,
"e": 28620,
"s": 28603,
"text": "Publish the site"
},
{
"code": null,
"e": 28681,
"s": 28620,
"text": "Make the site available on the Web for viewing by end users."
},
{
"code": null,
"e": 28696,
"s": 28681,
"text": "Click Publish."
},
{
"code": null,
"e": 28716,
"s": 28696,
"text": "View published site"
},
{
"code": null,
"e": 28773,
"s": 28716,
"text": "View the published site on the desktop or mobile device."
},
{
"code": null,
"e": 28845,
"s": 28773,
"text": "Click Published Site to open the site in a new browser window (or tab)."
},
{
"code": null,
"e": 28917,
"s": 28845,
"text": "Click Published Site to open the site in a new browser window (or tab)."
},
{
"code": null,
"e": 28998,
"s": 28917,
"text": "Click QR Code and then scan the QR code for viewing the site on a mobile device."
},
{
"code": null,
"e": 29079,
"s": 28998,
"text": "Click QR Code and then scan the QR code for viewing the site on a mobile device."
},
{
"code": null,
"e": 29105,
"s": 29079,
"text": "Modify the published site"
},
{
"code": null,
"e": 29261,
"s": 29105,
"text": "Add and remove content to and from the site, and to change the design settings. These changes cannot be seen by end users until you publish the site again."
},
{
"code": null,
"e": 29320,
"s": 29261,
"text": "Use the options on the side-panel menu to modify the site."
},
{
"code": null,
"e": 29342,
"s": 29320,
"text": "Take the site offline"
},
{
"code": null,
"e": 29528,
"s": 29342,
"text": "Prevent end users form accessing the site. This action does not delete the site, but rather blocks access to it until you publish the site again. Site authors can still access the site."
},
{
"code": null,
"e": 29548,
"s": 29528,
"text": "Click Take Offline."
},
{
"code": null,
"e": 29580,
"s": 29548,
"text": "Cancel changes made to the site"
},
{
"code": null,
"e": 29714,
"s": 29580,
"text": "Remove all changes made to the site since it was last published. This option is not availble for site that have never been published."
},
{
"code": null,
"e": 29751,
"s": 29714,
"text": "Click Revert to Last Published Site."
},
{
"code": null,
"e": 30061,
"s": 29751,
"text": "You can define a site as the default site to your account. This helps user to modify a site without taking it offline for maintenance. You can make changes to the site and then make the updated site as default site for your account. In this chapter, let us discuss such other site activities that can be done."
},
{
"code": null,
"e": 30241,
"s": 30061,
"text": "To assign default site to your account, navigate to Site directory and bring the cursor on the site card you want to make as default. From Site Action menu → click Set as default."
},
{
"code": null,
"e": 30562,
"s": 30241,
"text": "In SAP Cloud platform, you can also analyze statistics of portal sites which you have access. You can use Analytics dashboard to check statistical information related to Portal sites. Go to Analytics tab in Portal service to view charts or tables of statistical information about the usage of one or more selected sites."
},
{
"code": null,
"e": 30711,
"s": 30562,
"text": "You can use this information to better understand usage trends, and traffic peaks and lows, and thereby improve your sites to yield optimal results."
},
{
"code": null,
"e": 30782,
"s": 30711,
"text": "To enable it, navigate to Services and Tools → Data Privacy Management"
},
{
"code": null,
"e": 30847,
"s": 30782,
"text": "Using Analytics option, you can find the following information −"
},
{
"code": null,
"e": 31002,
"s": 30847,
"text": "You can view a gauge for Visits and Visitors to measure the web traffic during a time period and you can further break the report in day, hours, and mins."
},
{
"code": null,
"e": 31157,
"s": 31002,
"text": "You can view a gauge for Visits and Visitors to measure the web traffic during a time period and you can further break the report in day, hours, and mins."
},
{
"code": null,
"e": 31267,
"s": 31157,
"text": "You can also view the different devices from which the site was accessed- mobile devices, tablets or user PC."
},
{
"code": null,
"e": 31377,
"s": 31267,
"text": "You can also view the different devices from which the site was accessed- mobile devices, tablets or user PC."
},
{
"code": null,
"e": 31474,
"s": 31377,
"text": "You can also check the information related to OS type used and browser types to access the site."
},
{
"code": null,
"e": 31571,
"s": 31474,
"text": "You can also check the information related to OS type used and browser types to access the site."
},
{
"code": null,
"e": 31739,
"s": 31571,
"text": "When you click View Usage Analytics, you have an option to Visits and Visitors details (Hour, day, week and month), device type, Operating systems and browser details."
},
{
"code": null,
"e": 32004,
"s": 31739,
"text": "You can also translate the site and download the content in PDF, HTML and other formats. Once the files are translated, you can load them to the site and users can view it in the browser language. However, note that the site is still maintained in master language."
},
{
"code": null,
"e": 32256,
"s": 32004,
"text": "When site is translated to other account, translations are automatically available in site content; however, when you duplicate a site using same account, translations are not available, and you need to export them and import the site to that account."
},
{
"code": null,
"e": 32444,
"s": 32256,
"text": "To define a site master language, you have to navigate to Site Settings menu. The site master language is also a fall back language when the selected language is not supported by browser."
},
{
"code": null,
"e": 32569,
"s": 32444,
"text": "To download site content, navigate to Services and Tools and select Translation tiles in navigation pane → Configure option."
},
{
"code": null,
"e": 32726,
"s": 32569,
"text": "To download the master language of your portal site, click Download button as shown below. This will download the master language ZIP file onto your system."
},
{
"code": null,
"e": 32858,
"s": 32726,
"text": "To translate this site into multiple languages, you can use SAP Translation hub service and the zip file which you have downloaded."
},
{
"code": null,
"e": 33034,
"s": 32858,
"text": "Go to UI for Translation workflow and create properties file for all the languages selected for translation. When translation is done, you can load the files into portal site."
},
{
"code": null,
"e": 33089,
"s": 33034,
"text": "To upload, go to Translation tile → Configure → Upload"
},
{
"code": null,
"e": 33348,
"s": 33089,
"text": "Now, browse for Zip file and open. This will process the zip files and all languages will be displayed on the screen. Note that all are inactive till you activate them. You can see the status of each language and to activate click “OFF” icon as shown below −"
},
{
"code": null,
"e": 33554,
"s": 33348,
"text": "You can also perform site transfer from SAP Cloud platform or to create a prototype or to create site from other accounts. Basic site transfer can be performed using export/import option in Site directory."
},
{
"code": null,
"e": 33601,
"s": 33554,
"text": "To export site as a zip file, it can include −"
},
{
"code": null,
"e": 33607,
"s": 33601,
"text": "Pages"
},
{
"code": null,
"e": 33638,
"s": 33607,
"text": "Content in Open Social widgets"
},
{
"code": null,
"e": 33650,
"s": 33638,
"text": "Theme files"
},
{
"code": null,
"e": 33668,
"s": 33650,
"text": "Translation sites"
},
{
"code": null,
"e": 33705,
"s": 33668,
"text": "Site user's details (Optional field)"
},
{
"code": null,
"e": 33846,
"s": 33705,
"text": "To export a site, go to Site Directory → select the site to export and click on Site Actions → Export Site and save ZIP file to your system."
},
{
"code": null,
"e": 33915,
"s": 33846,
"text": "To import site, again go to Site Directory → Add site → Import Site."
},
{
"code": null,
"e": 34096,
"s": 33915,
"text": "This will create a site in the Site Directory and the transfer date is displayed in the Created field. You can also create a duplicate site, click on Site Actions → Duplicate Site."
},
{
"code": null,
"e": 34158,
"s": 34096,
"text": "Now enter the following in the name and description details −"
},
{
"code": null,
"e": 34184,
"s": 34158,
"text": "Site name of the new site"
},
{
"code": null,
"e": 34217,
"s": 34184,
"text": "Site Description of the new site"
},
{
"code": null,
"e": 34330,
"s": 34217,
"text": "Next, click Duplicate button and this will create a copy of an existing site with name and description provided."
},
{
"code": null,
"e": 34440,
"s": 34330,
"text": "You can select “Include site users” checkbox if you want to include invited end users in the duplicated site."
},
{
"code": null,
"e": 34534,
"s": 34440,
"text": "Note − You should have “TENANT_ADMIN” role (Administrator) in the SAP Cloud Platform cockpit."
},
{
"code": null,
"e": 34866,
"s": 34534,
"text": "You can have different cloud repositories for site building maintained by SAP Cloud administrators. These repositories can be edited/modified by users with administrator privileges. The content of the cloud repositories is available in authoring space. In this chapter, let us discuss the available cloud repositories in SAP Cloud."
},
{
"code": null,
"e": 34922,
"s": 34866,
"text": "The following repositories are available in SAP Cloud −"
},
{
"code": null,
"e": 34990,
"s": 34922,
"text": "Theme Repository − This is available in Theme tab in Portal service"
},
{
"code": null,
"e": 35058,
"s": 34990,
"text": "Theme Repository − This is available in Theme tab in Portal service"
},
{
"code": null,
"e": 35132,
"s": 35058,
"text": "Document Repository − This is available on Document tab in Portal service"
},
{
"code": null,
"e": 35206,
"s": 35132,
"text": "Document Repository − This is available on Document tab in Portal service"
},
{
"code": null,
"e": 35277,
"s": 35206,
"text": "Widget Repository − This is available in Content tab in Portal service"
},
{
"code": null,
"e": 35348,
"s": 35277,
"text": "Widget Repository − This is available in Content tab in Portal service"
},
{
"code": null,
"e": 35617,
"s": 35348,
"text": "In theme repository, themes are available in table form with details- name of the theme, description and theme creator name. Theme repository can be accessed from Themes tab of Portal service. The default theme for the account is represented using “star” shape symbol."
},
{
"code": null,
"e": 35764,
"s": 35617,
"text": "To create a new theme, navigate to Themes tab in the Portal service tab → Add Theme at the right corner and this will open “Add Theme” dialog box."
},
{
"code": null,
"e": 35944,
"s": 35764,
"text": "Enter the theme details, such as a name, description, and path to the theme file (LESS)location → Click Add button. You can also edit or delete an existing theme from repository."
},
{
"code": null,
"e": 36181,
"s": 35944,
"text": "Document repository contains all the documents which can be shared, reused in different sites. It contains all the documents for a given account. Document repository can be accessed from Document tab of Portal service in Cloud platform."
},
{
"code": null,
"e": 36347,
"s": 36181,
"text": "Documents can be uploaded and arranged in repository. You can also perform a search or download the documents and can also see site details where documents are used."
},
{
"code": null,
"e": 36477,
"s": 36347,
"text": "To access document repository, navigate to Portal service tab → SAP Cloud Platform cockpit → Repositories → Document Repositories"
},
{
"code": null,
"e": 36596,
"s": 36477,
"text": "If document repository doesn’t exist, you can create a new Repository. Click on New Repository and enter the details −"
},
{
"code": null,
"e": 36601,
"s": 36596,
"text": "Name"
},
{
"code": null,
"e": 36614,
"s": 36601,
"text": "Display Name"
},
{
"code": null,
"e": 36626,
"s": 36614,
"text": "Description"
},
{
"code": null,
"e": 36638,
"s": 36626,
"text": "Description"
},
{
"code": null,
"e": 36653,
"s": 36638,
"text": "Repository Key"
},
{
"code": null,
"e": 36708,
"s": 36653,
"text": "Note − Repository key should be minimum 10 characters."
},
{
"code": null,
"e": 36896,
"s": 36708,
"text": "Also, to maintain the content integrity in repository, you cannot edit documents stored in the repository. Instead, you download a document, edit it, and upload the new, updated document."
},
{
"code": null,
"e": 37007,
"s": 36896,
"text": "You can also edit repository name, change repository key or delete a document repository using below options −"
},
{
"code": null,
"e": 37319,
"s": 37007,
"text": "Widget repository contains all the available widgets for a given account. You can access Widget repository from Content tab of Portal service in Cloud platform. The widget in repository are listed in table format and shows the basic information about widgets. Following Widget types can be added to repository −"
},
{
"code": null,
"e": 37333,
"s": 37319,
"text": "Social widget"
},
{
"code": null,
"e": 37344,
"s": 37333,
"text": "URL widget"
},
{
"code": null,
"e": 37364,
"s": 37344,
"text": "SAP Jam Feed widget"
},
{
"code": null,
"e": 37624,
"s": 37364,
"text": "To manage and administrate sites, SAP Cloud platform provides different level of access and permissions. Administrators are responsible for managing content and themes of site and user level access is used to manage access related to site and published pages."
},
{
"code": null,
"e": 37682,
"s": 37624,
"text": "The following roles are commonly used in Cloud platform −"
},
{
"code": null,
"e": 37818,
"s": 37682,
"text": "This is predefined as Tenant_Admin in SAP Cloud platform cockpit. The administrator is used for adding and managing content and themes."
},
{
"code": null,
"e": 38017,
"s": 37818,
"text": "This is used to manage access to published sites and pages. These are defined in SAP Cloud platform cockpit. Note that Authorization option is used to assign the roles to individual and user groups."
},
{
"code": null,
"e": 38167,
"s": 38017,
"text": "In Group tab, you can also create a new group and add users to it. To create a new group, click on New Group button and provide Group name as below −"
},
{
"code": null,
"e": 38255,
"s": 38167,
"text": "This role is used to allow access to individuals outside organizations for site access."
},
{
"code": null,
"e": 38372,
"s": 38255,
"text": "When you publish a site, you can allow different level of site access to users- public, authenticated or role based."
},
{
"code": null,
"e": 38443,
"s": 38372,
"text": "When you allow public access to site, anyone on the web can access it."
},
{
"code": null,
"e": 38566,
"s": 38443,
"text": "This includes site users who are part of an organization and can access to site using predefined authentication mechanism."
},
{
"code": null,
"e": 38645,
"s": 38566,
"text": "This includes only few users assigned with specific role can access the site. "
},
{
"code": null,
"e": 38860,
"s": 38645,
"text": "Note − You can also limit page access permissions from Access Management panel on left side to manage access to site pages for one or more groups. Like site access, following access level can be granted for pages −"
},
{
"code": null,
"e": 38873,
"s": 38860,
"text": "Role - Based"
},
{
"code": null,
"e": 38880,
"s": 38873,
"text": "Public"
},
{
"code": null,
"e": 38886,
"s": 38880,
"text": "Guest"
},
{
"code": null,
"e": 39036,
"s": 38886,
"text": "Go to Page settings → Page Authorization and you can see assigned access level to page. To make changes, click on Edit option on bottom right corner."
},
{
"code": null,
"e": 39181,
"s": 39036,
"text": "You can make changes to page access level using Access level drop down list from Page Authorizations. To save the changes, click on Save button."
},
{
"code": null,
"e": 39276,
"s": 39181,
"text": "To create a new role, navigate to Roles tab under Content Management → New (+) icon at bottom."
},
{
"code": null,
"e": 39427,
"s": 39276,
"text": "You have to define new Role properties like- Role Name and Role ID. Under Additional information, you can see Created, Creator and last modified date."
},
{
"code": null,
"e": 39591,
"s": 39427,
"text": "You can also assign more Catalogs and Groups to this role. Navigate to relevant tab and click on + sign to add new item. To save the changes, click on Save button."
},
{
"code": null,
"e": 39704,
"s": 39591,
"text": "When you assign this role to any of Page, by default it takes the assigned Catalogs name as per role properties."
},
{
"code": null,
"e": 39970,
"s": 39704,
"text": "You can also navigate to site setting options and edit different properties related to site- system, user and custom settings. Navigate to Settings tab on left side and this will open Site Setting menu. To make changes, click on Edit button at bottom right corner −"
},
{
"code": null,
"e": 40020,
"s": 39970,
"text": "You can edit following System and User settings −"
},
{
"code": null,
"e": 40365,
"s": 40020,
"text": "Site author access can be provided to edit and maintain existing sites. It can allow users to open and edit all sites to which they have assigned access and this access can also be extended to other users. When an assignment is created for the user, it sends an email to new author with URL that allow that person to access and author new site."
},
{
"code": null,
"e": 40443,
"s": 40365,
"text": "To check Site URL, you can navigate to Site setting tab → General → Site URL."
},
{
"code": null,
"e": 40568,
"s": 40443,
"text": "You can also maintain your login profile as per requirement. Click the top right corner drop down → User information → Edit."
},
{
"code": null,
"e": 40642,
"s": 40568,
"text": "In User profile information, you can maintain the following information −"
},
{
"code": null,
"e": 40980,
"s": 40642,
"text": "In SAP Cloud platform, you can develop SAP UI5, HTML5 based applications and open social widgets and consume them using SAP Cloud portal service. Using SAP Cloud platform, you can develop and execute HTML5 applications in cloud platform. It can contain static resources and can be connected to other on-premise or on-demand REST service."
},
{
"code": null,
"e": 41093,
"s": 40980,
"text": "To develop a HTML5 application and consume it in Cloud Portal service, you need to perform the following steps −"
},
{
"code": null,
"e": 41145,
"s": 41093,
"text": "Develop HTML5 application and save it in HANA Cloud"
},
{
"code": null,
"e": 41197,
"s": 41145,
"text": "Develop HTML5 application and save it in HANA Cloud"
},
{
"code": null,
"e": 41258,
"s": 41197,
"text": "Next is to convert HTML5 application to an OpenSocial widget"
},
{
"code": null,
"e": 41319,
"s": 41258,
"text": "Next is to convert HTML5 application to an OpenSocial widget"
},
{
"code": null,
"e": 41385,
"s": 41319,
"text": "Add the OpenSocial widget to the Portal service widget repository"
},
{
"code": null,
"e": 41451,
"s": 41385,
"text": "Add the OpenSocial widget to the Portal service widget repository"
},
{
"code": null,
"e": 41649,
"s": 41451,
"text": "To develop HTML5 applications, you can use the browser-based tool like SAP Web IDE that does not require any additional setup. Let us see how to develop “Hello World Application Using SAP Web IDE”."
},
{
"code": null,
"e": 41845,
"s": 41649,
"text": "Login to SAP Cloud Platform cockpit and click on Applications → HTML5 Applications. In case you have already created applications using this subaccount, it will show a list of HTML5 applications."
},
{
"code": null,
"e": 42079,
"s": 41845,
"text": "Now to develop a new HTML5 application → Click on New Application and enter an application name. Note that name of application must contain lower case alphanumeric characters and must not exceed 30 characters and start with a letter."
},
{
"code": null,
"e": 42202,
"s": 42079,
"text": "You can navigate to Applications page and click “Create Hello World App” to check the steps included in HTML5 development."
},
{
"code": null,
"e": 42270,
"s": 42202,
"text": "The following steps are involved for creating a HTML5 application −"
},
{
"code": null,
"e": 42287,
"s": 42270,
"text": "Create a Project"
},
{
"code": null,
"e": 42310,
"s": 42287,
"text": "Edit HTML5 application"
},
{
"code": null,
"e": 42355,
"s": 42310,
"text": "Deploy the application to SAP Cloud platform"
},
{
"code": null,
"e": 42465,
"s": 42355,
"text": "To deploy your application to SAP Cloud platform, right on application Deploy → Deploy to SAP Cloud platform."
},
{
"code": null,
"e": 42611,
"s": 42465,
"text": "Login to SAP Cloud platform and enter user name and password. You can keep “Activate” option checked and this will activate new version directly."
},
{
"code": null,
"e": 42662,
"s": 42611,
"text": "Click OK button for completing deployment process."
},
{
"code": null,
"e": 42880,
"s": 42662,
"text": "In SAP Cloud platform, objects in Portal site can be communicated to SAP Backend system. Portal service can be integrated with backend system like CRM, or SAP HR system. In this chapter, let us discuss them in detail."
},
{
"code": null,
"e": 42932,
"s": 42880,
"text": "To integrate, following perquisites should be met −"
},
{
"code": null,
"e": 42995,
"s": 42932,
"text": "You should have gateway server and service has been installed."
},
{
"code": null,
"e": 43058,
"s": 42995,
"text": "You should have gateway server and service has been installed."
},
{
"code": null,
"e": 43176,
"s": 43058,
"text": "SAP Cloud connector should be installed, and connection should be defined between Gateway service and portal service."
},
{
"code": null,
"e": 43294,
"s": 43176,
"text": "SAP Cloud connector should be installed, and connection should be defined between Gateway service and portal service."
},
{
"code": null,
"e": 43349,
"s": 43294,
"text": "You should have destination defined in portal service."
},
{
"code": null,
"e": 43404,
"s": 43349,
"text": "You should have destination defined in portal service."
},
{
"code": null,
"e": 43750,
"s": 43404,
"text": "SAP Cloud Platform Connectivity option allows cloud application to connect internet service and on-premise system via Cloud Connector. SAP Cloud Administrator can create destinations so that users can build, test, and deploy applications. You configure the destination for SAP Web IDE to SAP Enterprise Portal in the SAP Cloud Platform cockpit. "
},
{
"code": null,
"e": 43919,
"s": 43750,
"text": "For this purpose, navigate to Connectivity → Destinations and this will open destination editor. To create a new destination, click on New Destination option as below −"
},
{
"code": null,
"e": 43985,
"s": 43919,
"text": "The following details should be entered to create a destination −"
},
{
"code": null,
"e": 44109,
"s": 43985,
"text": "In the Additional Properties section, click New Property for each of the properties and click Save to save the destination."
},
{
"code": null,
"e": 44133,
"s": 44109,
"text": "Default: 10000(10 Secs)"
},
{
"code": null,
"e": 44162,
"s": 44133,
"text": "Max: value: 120000(120 secs)"
},
{
"code": null,
"e": 44187,
"s": 44162,
"text": "Default : 30000(30 secs)"
},
{
"code": null,
"e": 44216,
"s": 44187,
"text": "Max: value: 300000(300 secs)"
},
{
"code": null,
"e": 44377,
"s": 44216,
"text": "You can also edit an existing destination by selecting Destination name and click on Edit button. You also have other options like - Clone, Export, Delete, etc."
},
{
"code": null,
"e": 44569,
"s": 44377,
"text": "You can get a free SAP Cloud platform account with developer license to try and test the platform. This account can be used for non-productive usage and it only allows one member per account."
},
{
"code": null,
"e": 44631,
"s": 44569,
"text": "Besides, there are few other limitations in a trial account −"
},
{
"code": null,
"e": 44771,
"s": 44631,
"text": "For productive purpose, you should use a commercial license for SAP Cloud platform. Following commercial license are available to be used −"
},
{
"code": null,
"e": 44911,
"s": 44771,
"text": "For productive purpose, you should use a commercial license for SAP Cloud platform. Following commercial license are available to be used −"
},
{
"code": null,
"e": 44927,
"s": 44911,
"text": "Contract Period"
},
{
"code": null,
"e": 44977,
"s": 44927,
"text": "Subscription period(typically 12 months or more)."
},
{
"code": null,
"e": 44993,
"s": 44977,
"text": "Contract Period"
},
{
"code": null,
"e": 45025,
"s": 44993,
"text": "Consumption period(12+ months)."
},
{
"code": null,
"e": 45063,
"s": 45025,
"text": "Available SAP Cloud Platform Services"
},
{
"code": null,
"e": 45176,
"s": 45063,
"text": "You can use the services that are specified in your contract. Additional service require contract modifications."
},
{
"code": null,
"e": 45214,
"s": 45176,
"text": "Available SAP Cloud Platform services"
},
{
"code": null,
"e": 45337,
"s": 45214,
"text": "You are entitled to use all eligible SAP Cloud Platform services. No additional contract is required for changes in usage."
},
{
"code": null,
"e": 45350,
"s": 45337,
"text": "Price / Cost"
},
{
"code": null,
"e": 45442,
"s": 45350,
"text": "The cost is fixed for the duration of the subscription period, irrespective of consumption."
},
{
"code": null,
"e": 45455,
"s": 45442,
"text": "Price / Cost"
},
{
"code": null,
"e": 45542,
"s": 45455,
"text": "You prepay for cloud credits, which are then balanced against consumption of services."
},
{
"code": null,
"e": 45550,
"s": 45542,
"text": "Payment"
},
{
"code": null,
"e": 45599,
"s": 45550,
"text": "In advance, at the start of the contract period."
},
{
"code": null,
"e": 45607,
"s": 45599,
"text": "Payment"
},
{
"code": null,
"e": 45662,
"s": 45607,
"text": "In advance, and again when cloud credits are used up*."
},
{
"code": null,
"e": 45670,
"s": 45662,
"text": "Renewal"
},
{
"code": null,
"e": 45709,
"s": 45670,
"text": "At the end of the subscription period."
},
{
"code": null,
"e": 45717,
"s": 45709,
"text": "Renewal"
},
{
"code": null,
"e": 45755,
"s": 45717,
"text": "At the end of the consumption period."
},
{
"code": null,
"e": 45875,
"s": 45755,
"text": "SAP Cloud trial account does not offer a service level agreement related to availability of SAP Cloud platform service."
},
{
"code": null,
"e": 45995,
"s": 45875,
"text": "SAP Cloud trial account does not offer a service level agreement related to availability of SAP Cloud platform service."
},
{
"code": null,
"e": 46050,
"s": 45995,
"text": "You cannot add any additional member to trial account."
},
{
"code": null,
"e": 46105,
"s": 46050,
"text": "You cannot add any additional member to trial account."
},
{
"code": null,
"e": 46165,
"s": 46105,
"text": "Free trial provides 1GB of storage on shared HANA instance."
},
{
"code": null,
"e": 46225,
"s": 46165,
"text": "Free trial provides 1GB of storage on shared HANA instance."
},
{
"code": null,
"e": 46351,
"s": 46225,
"text": "Trial version only supports Java and HTML5 application. It does not support HANA XS application development in trial account."
},
{
"code": null,
"e": 46477,
"s": 46351,
"text": "Trial version only supports Java and HTML5 application. It does not support HANA XS application development in trial account."
},
{
"code": null,
"e": 46587,
"s": 46477,
"text": "You can deploy multiple Java applications on your trial account however only one app can be in started state."
},
{
"code": null,
"e": 46697,
"s": 46587,
"text": "You can deploy multiple Java applications on your trial account however only one app can be in started state."
},
{
"code": null,
"e": 46810,
"s": 46697,
"text": "SAP Cloud platform developer is responsible for the development and management of application on Cloud platform."
},
{
"code": null,
"e": 46879,
"s": 46810,
"text": "Primary responsibilities of SAP Cloud platform developer are below −"
},
{
"code": null,
"e": 47039,
"s": 46879,
"text": "Developer is responsible for providing a reliable, scalable, extensible and secure infrastructure for application development and deployment on cloud platform."
},
{
"code": null,
"e": 47199,
"s": 47039,
"text": "Developer is responsible for providing a reliable, scalable, extensible and secure infrastructure for application development and deployment on cloud platform."
},
{
"code": null,
"e": 47345,
"s": 47199,
"text": "Manage VMs, tools for setting up services on SAP Cloud Platform. Responsible for deploying and controlling the application development lifecycle."
},
{
"code": null,
"e": 47491,
"s": 47345,
"text": "Manage VMs, tools for setting up services on SAP Cloud Platform. Responsible for deploying and controlling the application development lifecycle."
},
{
"code": null,
"e": 47568,
"s": 47491,
"text": "Designing of new interfaces, wireframes and prototypes for new applications."
},
{
"code": null,
"e": 47645,
"s": 47568,
"text": "Designing of new interfaces, wireframes and prototypes for new applications."
},
{
"code": null,
"e": 47707,
"s": 47645,
"text": "Designing new application with help of application designers."
},
{
"code": null,
"e": 47769,
"s": 47707,
"text": "Designing new application with help of application designers."
},
{
"code": null,
"e": 47833,
"s": 47769,
"text": "It is preferred that developers have experience in following −"
},
{
"code": null,
"e": 47928,
"s": 47833,
"text": "Exposure in configuring SAP Cloud Platform, Amazon Web Services, Azure, Google Cloud Platform."
},
{
"code": null,
"e": 48023,
"s": 47928,
"text": "Exposure in configuring SAP Cloud Platform, Amazon Web Services, Azure, Google Cloud Platform."
},
{
"code": null,
"e": 48098,
"s": 48023,
"text": "Development experience in Web UI programming using JavaScript, HTML5, CSS."
},
{
"code": null,
"e": 48173,
"s": 48098,
"text": "Development experience in Web UI programming using JavaScript, HTML5, CSS."
},
{
"code": null,
"e": 48243,
"s": 48173,
"text": "Development experience using SAP UI5 application development methods."
},
{
"code": null,
"e": 48313,
"s": 48243,
"text": "Development experience using SAP UI5 application development methods."
},
{
"code": null,
"e": 48346,
"s": 48313,
"text": "\n 25 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 48360,
"s": 48346,
"text": " Sanjo Thomas"
},
{
"code": null,
"e": 48393,
"s": 48360,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 48405,
"s": 48393,
"text": " Neha Gupta"
},
{
"code": null,
"e": 48440,
"s": 48405,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 48455,
"s": 48440,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 48488,
"s": 48455,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 48503,
"s": 48488,
"text": " Sumit Agarwal"
},
{
"code": null,
"e": 48538,
"s": 48503,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 48550,
"s": 48538,
"text": " Neha Malik"
},
{
"code": null,
"e": 48585,
"s": 48550,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 48597,
"s": 48585,
"text": " Neha Malik"
},
{
"code": null,
"e": 48604,
"s": 48597,
"text": " Print"
},
{
"code": null,
"e": 48615,
"s": 48604,
"text": " Add Notes"
}
] |
Matplotlib.figure.Figure.set_size_inches() in Python - GeeksforGeeks
|
03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The set_size_inches() method figure module of matplotlib library is used to set the figure size in inches.
Syntax: set_size_inches(self, w, h=None, forward=True)
Parameters: This method accept the following parameters that are discussed below:
w, h : These parameters are the (width, height) of the figure in inches.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.set_size_inches() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure() ax = Subplot(fig, 111) fig.add_subplot(ax) fig.set_size_inches(4, 5) fig.suptitle("""matplotlib.figure.Figure.set_size_inches()function Example\n\n""", fontweight ="bold") plt.show()
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(figsize =(7, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) fig.set_size_inches(6, 4) fig.suptitle("""matplotlib.figure.Figure.set_size_inches()function Example\n\n""", fontweight ="bold") plt.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
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 | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n03 May, 2020"
},
{
"code": null,
"e": 24212,
"s": 23901,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements."
},
{
"code": null,
"e": 24319,
"s": 24212,
"text": "The set_size_inches() method figure module of matplotlib library is used to set the figure size in inches."
},
{
"code": null,
"e": 24374,
"s": 24319,
"text": "Syntax: set_size_inches(self, w, h=None, forward=True)"
},
{
"code": null,
"e": 24456,
"s": 24374,
"text": "Parameters: This method accept the following parameters that are discussed below:"
},
{
"code": null,
"e": 24529,
"s": 24456,
"text": "w, h : These parameters are the (width, height) of the figure in inches."
},
{
"code": null,
"e": 24578,
"s": 24529,
"text": "Returns: This method does not returns any value."
},
{
"code": null,
"e": 24682,
"s": 24578,
"text": "Below examples illustrate the matplotlib.figure.Figure.set_size_inches() function in matplotlib.figure:"
},
{
"code": null,
"e": 24693,
"s": 24682,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np fig = plt.figure() ax = Subplot(fig, 111) fig.add_subplot(ax) fig.set_size_inches(4, 5) fig.suptitle(\"\"\"matplotlib.figure.Figure.set_size_inches()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show()",
"e": 25100,
"s": 24693,
"text": null
},
{
"code": null,
"e": 25108,
"s": 25100,
"text": "Output:"
},
{
"code": null,
"e": 25119,
"s": 25108,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np fig = plt.figure(figsize =(7, 6)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx)) fig.set_size_inches(6, 4) fig.suptitle(\"\"\"matplotlib.figure.Figure.set_size_inches()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show() ",
"e": 25553,
"s": 25119,
"text": null
},
{
"code": null,
"e": 25561,
"s": 25553,
"text": "Output:"
},
{
"code": null,
"e": 25585,
"s": 25561,
"text": "Matplotlib figure-class"
},
{
"code": null,
"e": 25603,
"s": 25585,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 25610,
"s": 25603,
"text": "Python"
},
{
"code": null,
"e": 25708,
"s": 25610,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25717,
"s": 25708,
"text": "Comments"
},
{
"code": null,
"e": 25730,
"s": 25717,
"text": "Old Comments"
},
{
"code": null,
"e": 25762,
"s": 25730,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25818,
"s": 25762,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25860,
"s": 25818,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25902,
"s": 25860,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25938,
"s": 25902,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 25977,
"s": 25938,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25999,
"s": 25977,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26030,
"s": 25999,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26057,
"s": 26030,
"text": "Python Classes and Objects"
}
] |
How to assign values to variables in C#?
|
A variable is a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable.
To assign values to a variable, add the value after the equal operator −
int a = 10;
Let us see how to assign values to a variable and print it
Live Demo
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int a;
a = 100;
Console.WriteLine("a = {0}", a);
Console.ReadLine();
}
}
}
a = 100
|
[
{
"code": null,
"e": 1365,
"s": 1062,
"text": "A variable is a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable."
},
{
"code": null,
"e": 1438,
"s": 1365,
"text": "To assign values to a variable, add the value after the equal operator −"
},
{
"code": null,
"e": 1450,
"s": 1438,
"text": "int a = 10;"
},
{
"code": null,
"e": 1509,
"s": 1450,
"text": "Let us see how to assign values to a variable and print it"
},
{
"code": null,
"e": 1520,
"s": 1509,
"text": " Live Demo"
},
{
"code": null,
"e": 1736,
"s": 1520,
"text": "using System;\n\nnamespace Demo {\n\n class Program {\n\n static void Main(string[] args) {\n\n int a;\n\n a = 100;\n\n Console.WriteLine(\"a = {0}\", a);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 1744,
"s": 1736,
"text": "a = 100"
}
] |
CSS - Tada Effect
|
It provides to move an element from side to side.
@keyframes tada {
0% {transform: scale(1);}
10%, 20% {transform: scale(0.9) rotate(-3deg);}
30%, 50%, 70%, 90% {transform: scale(1.1) rotate(3deg);}
40%, 60%, 80% {transform: scale(1.1) rotate(-3deg);}
100% {transform: scale(1) rotate(0);}
}
Transform − Transform applies to 2d and 3d transformation to an element.
Transform − Transform applies to 2d and 3d transformation to an element.
Opacity − Opacity applies to an element to make translucence.
Opacity − Opacity applies to an element to make translucence.
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 10s;
animation-duration: 10s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes tada {
0% {-webkit-transform: scale(1);}
10%, 20% {-webkit-transform: scale(0.9) rotate(-3deg);}
30%, 50%, 70%, 90% {-webkit-transform: scale(1.1) rotate(3deg);}
40%, 60%, 80% {-webkit-transform: scale(1.1) rotate(-3deg);}
100% {-webkit-transform: scale(1) rotate(0);}
}
@keyframes tada {
0% {transform: scale(1);}
10%, 20% {transform: scale(0.9) rotate(-3deg);}
30%, 50%, 70%, 90% {transform: scale(1.1) rotate(3deg);}
40%, 60%, 80% {transform: scale(1.1) rotate(-3deg);}
100% {transform: scale(1) rotate(0);}
}
.tada {
-webkit-animation-name: tada;
animation-name: tada;
}
</style>
</head>
<body>
<div id = "animated-example" class = "animated tada"></div>
<button onclick = "myFunction()">Reload page</button>
<script>
function myFunction() {
location.reload();
}
</script>
</body>
</html>
It will produce the following result −
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Selected Reading
UPSC IAS Exams Notes
Developer's Best Practices
Questions and Answers
Effective Resume Writing
HR Interview Questions
Computer Glossary
Who is Who
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2676,
"s": 2626,
"text": "It provides to move an element from side to side."
},
{
"code": null,
"e": 2939,
"s": 2676,
"text": "@keyframes tada {\n 0% {transform: scale(1);} \n 10%, 20% {transform: scale(0.9) rotate(-3deg);} \n 30%, 50%, 70%, 90% {transform: scale(1.1) rotate(3deg);} \n 40%, 60%, 80% {transform: scale(1.1) rotate(-3deg);} \n 100% {transform: scale(1) rotate(0);} \n} "
},
{
"code": null,
"e": 3012,
"s": 2939,
"text": "Transform − Transform applies to 2d and 3d transformation to an element."
},
{
"code": null,
"e": 3085,
"s": 3012,
"text": "Transform − Transform applies to 2d and 3d transformation to an element."
},
{
"code": null,
"e": 3147,
"s": 3085,
"text": "Opacity − Opacity applies to an element to make translucence."
},
{
"code": null,
"e": 3209,
"s": 3147,
"text": "Opacity − Opacity applies to an element to make translucence."
},
{
"code": null,
"e": 4790,
"s": 3209,
"text": "<html>\n <head>\n <style>\n .animated { \n background-image: url(/css/images/logo.png); \n background-repeat: no-repeat;\n background-position: left top; \n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s; \n -webkit-animation-fill-mode: both; \n animation-fill-mode: both; \n }\n \n @-webkit-keyframes tada { \n 0% {-webkit-transform: scale(1);}\n 10%, 20% {-webkit-transform: scale(0.9) rotate(-3deg);} \n 30%, 50%, 70%, 90% {-webkit-transform: scale(1.1) rotate(3deg);}\n 40%, 60%, 80% {-webkit-transform: scale(1.1) rotate(-3deg);} \n 100% {-webkit-transform: scale(1) rotate(0);} \n }\n \n @keyframes tada { \n 0% {transform: scale(1);} \n 10%, 20% {transform: scale(0.9) rotate(-3deg);} \n 30%, 50%, 70%, 90% {transform: scale(1.1) rotate(3deg);} \n 40%, 60%, 80% {transform: scale(1.1) rotate(-3deg);} \n 100% {transform: scale(1) rotate(0);}\n }\n \n .tada { \n -webkit-animation-name: tada; \n animation-name: tada; \n }\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated tada\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4829,
"s": 4790,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5476,
"s": 4829,
"text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n"
},
{
"code": null,
"e": 5496,
"s": 5476,
"text": " Academic Tutorials"
},
{
"code": null,
"e": 5519,
"s": 5496,
"text": " Big Data & Analytics "
},
{
"code": null,
"e": 5542,
"s": 5519,
"text": " Computer Programming "
},
{
"code": null,
"e": 5561,
"s": 5542,
"text": " Computer Science "
},
{
"code": null,
"e": 5573,
"s": 5561,
"text": " Databases "
},
{
"code": null,
"e": 5582,
"s": 5573,
"text": " DevOps "
},
{
"code": null,
"e": 5602,
"s": 5582,
"text": " Digital Marketing "
},
{
"code": null,
"e": 5626,
"s": 5602,
"text": " Engineering Tutorials "
},
{
"code": null,
"e": 5643,
"s": 5626,
"text": " Exams Syllabus "
},
{
"code": null,
"e": 5662,
"s": 5643,
"text": " Famous Monuments "
},
{
"code": null,
"e": 5684,
"s": 5662,
"text": " GATE Exams Tutorials"
},
{
"code": null,
"e": 5706,
"s": 5684,
"text": " Latest Technologies "
},
{
"code": null,
"e": 5725,
"s": 5706,
"text": " Machine Learning "
},
{
"code": null,
"e": 5749,
"s": 5725,
"text": " Mainframe Development "
},
{
"code": null,
"e": 5772,
"s": 5749,
"text": " Management Tutorials "
},
{
"code": null,
"e": 5795,
"s": 5772,
"text": " Mathematics Tutorials"
},
{
"code": null,
"e": 5820,
"s": 5795,
"text": " Microsoft Technologies "
},
{
"code": null,
"e": 5837,
"s": 5820,
"text": " Misc tutorials "
},
{
"code": null,
"e": 5858,
"s": 5837,
"text": " Mobile Development "
},
{
"code": null,
"e": 5878,
"s": 5858,
"text": " Java Technologies "
},
{
"code": null,
"e": 5900,
"s": 5878,
"text": " Python Technologies "
},
{
"code": null,
"e": 5916,
"s": 5900,
"text": " SAP Tutorials "
},
{
"code": null,
"e": 5937,
"s": 5916,
"text": "Programming Scripts "
},
{
"code": null,
"e": 5956,
"s": 5937,
"text": " Selected Reading "
},
{
"code": null,
"e": 5975,
"s": 5956,
"text": " Software Quality "
},
{
"code": null,
"e": 5989,
"s": 5975,
"text": " Soft Skills "
},
{
"code": null,
"e": 6009,
"s": 5989,
"text": " Telecom Tutorials "
},
{
"code": null,
"e": 6026,
"s": 6009,
"text": " UPSC IAS Exams "
},
{
"code": null,
"e": 6044,
"s": 6026,
"text": " Web Development "
},
{
"code": null,
"e": 6063,
"s": 6044,
"text": " Sports Tutorials "
},
{
"code": null,
"e": 6082,
"s": 6063,
"text": " XML Technologies "
},
{
"code": null,
"e": 6098,
"s": 6082,
"text": " Multi-Language"
},
{
"code": null,
"e": 6119,
"s": 6098,
"text": " Interview Questions"
},
{
"code": null,
"e": 6136,
"s": 6119,
"text": "Selected Reading"
},
{
"code": null,
"e": 6157,
"s": 6136,
"text": "UPSC IAS Exams Notes"
},
{
"code": null,
"e": 6184,
"s": 6157,
"text": "Developer's Best Practices"
},
{
"code": null,
"e": 6206,
"s": 6184,
"text": "Questions and Answers"
},
{
"code": null,
"e": 6231,
"s": 6206,
"text": "Effective Resume Writing"
},
{
"code": null,
"e": 6254,
"s": 6231,
"text": "HR Interview Questions"
},
{
"code": null,
"e": 6272,
"s": 6254,
"text": "Computer Glossary"
},
{
"code": null,
"e": 6283,
"s": 6272,
"text": "Who is Who"
},
{
"code": null,
"e": 6290,
"s": 6283,
"text": " Print"
},
{
"code": null,
"e": 6301,
"s": 6290,
"text": " Add Notes"
}
] |
How to Display the List of Sensors Present in an Android Device Programmatically? - GeeksforGeeks
|
23 Feb, 2021
All Android devices produced worldwide come with built-in sensors that measure motion, orientation, and various environmental conditions. These sensors generally facilitate Android architecture by providing the data from the sensor for various applications. For example, a temperature sensor provides the device’s temperature, information from which could be used for shutting down a few unrequired services. Such a sensor is a general type, but broadly, sensors are divided into three types:
Motion Sensors: Motion sensors measure the acceleration and rotational forces along the three axes x-y-z. Motion Sensors include accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.Environment Sensors: Environment sensors measure a variety of environmental parameters, such as pressure, ambient temperature (room temperature), illumination (light falling on the device), and humidity. They include barometers, photometers, and thermometers.Position Sensors: Position Sensors measure the physical position of a device in the space. They include orientation sensors and magnetometers.
Motion Sensors: Motion sensors measure the acceleration and rotational forces along the three axes x-y-z. Motion Sensors include accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
Environment Sensors: Environment sensors measure a variety of environmental parameters, such as pressure, ambient temperature (room temperature), illumination (light falling on the device), and humidity. They include barometers, photometers, and thermometers.
Position Sensors: Position Sensors measure the physical position of a device in the space. They include orientation sensors and magnetometers.
In general, any Android Device on or above Android Version 4.4 (Kitkat) have these sensors present in them:
Accelerometer – Hardware Sensor – Motion SensorGravity Sensor – Program Based (Software) – Raw data derived from the Motion Sensors for Gravity calculation.Ambient Temperature – Hardware Sensor – Environment SensorGyroscope – Hardware Sensor – Motion SensorLight Sensor – Hardware Sensor – Environment SensorOrientation Sensor – Program Based (Software) – Raw data derived from the Position and Motion SensorsProximity Sensor – Hardware Sensor – Position Sensor
Accelerometer – Hardware Sensor – Motion Sensor
Gravity Sensor – Program Based (Software) – Raw data derived from the Motion Sensors for Gravity calculation.
Ambient Temperature – Hardware Sensor – Environment Sensor
Gyroscope – Hardware Sensor – Motion Sensor
Light Sensor – Hardware Sensor – Environment Sensor
Orientation Sensor – Program Based (Software) – Raw data derived from the Position and Motion Sensors
Proximity Sensor – Hardware Sensor – Position Sensor
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 Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file which represents the UI of the application, and create a TextView inside a ScrollView that shall list the sensors present in the device. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><ScrollView 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"> <!--Text View that shall display the sensor information list--> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> </ScrollView>
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.content.Contextimport android.hardware.Sensorimport android.hardware.SensorManagerimport android.os.Bundleimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // Information about Sensors present in the // device is supplied by Sensor Manager of the device private lateinit var sensorManager: SensorManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initialize the variable sensorManager sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager // getSensorList(Sensor.TYPE_ALL) lists all the sensors present in the device val deviceSensors: List<Sensor> = sensorManager.getSensorList(Sensor.TYPE_ALL) // Text View that shall display this list val textView = findViewById<TextView>(R.id.tv) // Converting List to String and displaying // every sensor and its information on a new line for (sensors in deviceSensors) { textView.append(sensors.toString() + "\n\n") } }}
Android-Misc
Android
Kotlin
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
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Android UI Layouts
Android RecyclerView in Kotlin
|
[
{
"code": null,
"e": 25406,
"s": 25378,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 25899,
"s": 25406,
"text": "All Android devices produced worldwide come with built-in sensors that measure motion, orientation, and various environmental conditions. These sensors generally facilitate Android architecture by providing the data from the sensor for various applications. For example, a temperature sensor provides the device’s temperature, information from which could be used for shutting down a few unrequired services. Such a sensor is a general type, but broadly, sensors are divided into three types:"
},
{
"code": null,
"e": 26505,
"s": 25899,
"text": "Motion Sensors: Motion sensors measure the acceleration and rotational forces along the three axes x-y-z. Motion Sensors include accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.Environment Sensors: Environment sensors measure a variety of environmental parameters, such as pressure, ambient temperature (room temperature), illumination (light falling on the device), and humidity. They include barometers, photometers, and thermometers.Position Sensors: Position Sensors measure the physical position of a device in the space. They include orientation sensors and magnetometers."
},
{
"code": null,
"e": 26710,
"s": 26505,
"text": "Motion Sensors: Motion sensors measure the acceleration and rotational forces along the three axes x-y-z. Motion Sensors include accelerometers, gravity sensors, gyroscopes, and rotational vector sensors."
},
{
"code": null,
"e": 26970,
"s": 26710,
"text": "Environment Sensors: Environment sensors measure a variety of environmental parameters, such as pressure, ambient temperature (room temperature), illumination (light falling on the device), and humidity. They include barometers, photometers, and thermometers."
},
{
"code": null,
"e": 27113,
"s": 26970,
"text": "Position Sensors: Position Sensors measure the physical position of a device in the space. They include orientation sensors and magnetometers."
},
{
"code": null,
"e": 27221,
"s": 27113,
"text": "In general, any Android Device on or above Android Version 4.4 (Kitkat) have these sensors present in them:"
},
{
"code": null,
"e": 27683,
"s": 27221,
"text": "Accelerometer – Hardware Sensor – Motion SensorGravity Sensor – Program Based (Software) – Raw data derived from the Motion Sensors for Gravity calculation.Ambient Temperature – Hardware Sensor – Environment SensorGyroscope – Hardware Sensor – Motion SensorLight Sensor – Hardware Sensor – Environment SensorOrientation Sensor – Program Based (Software) – Raw data derived from the Position and Motion SensorsProximity Sensor – Hardware Sensor – Position Sensor"
},
{
"code": null,
"e": 27731,
"s": 27683,
"text": "Accelerometer – Hardware Sensor – Motion Sensor"
},
{
"code": null,
"e": 27841,
"s": 27731,
"text": "Gravity Sensor – Program Based (Software) – Raw data derived from the Motion Sensors for Gravity calculation."
},
{
"code": null,
"e": 27900,
"s": 27841,
"text": "Ambient Temperature – Hardware Sensor – Environment Sensor"
},
{
"code": null,
"e": 27944,
"s": 27900,
"text": "Gyroscope – Hardware Sensor – Motion Sensor"
},
{
"code": null,
"e": 27996,
"s": 27944,
"text": "Light Sensor – Hardware Sensor – Environment Sensor"
},
{
"code": null,
"e": 28098,
"s": 27996,
"text": "Orientation Sensor – Program Based (Software) – Raw data derived from the Position and Motion Sensors"
},
{
"code": null,
"e": 28151,
"s": 28098,
"text": "Proximity Sensor – Hardware Sensor – Position Sensor"
},
{
"code": null,
"e": 28180,
"s": 28151,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 28344,
"s": 28180,
"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 Kotlin as the programming language."
},
{
"code": null,
"e": 28392,
"s": 28344,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 28613,
"s": 28392,
"text": "Go to the activity_main.xml file which represents the UI of the application, and create a TextView inside a ScrollView that shall list the sensors present in the device. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 28617,
"s": 28613,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScrollView 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\"> <!--Text View that shall display the sensor information list--> <TextView android:id=\"@+id/tv\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" /> </ScrollView>",
"e": 29151,
"s": 28617,
"text": null
},
{
"code": null,
"e": 29197,
"s": 29151,
"text": "Step 4: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 29384,
"s": 29197,
"text": "Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 29391,
"s": 29384,
"text": "Kotlin"
},
{
"code": "import android.content.Contextimport android.hardware.Sensorimport android.hardware.SensorManagerimport android.os.Bundleimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // Information about Sensors present in the // device is supplied by Sensor Manager of the device private lateinit var sensorManager: SensorManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initialize the variable sensorManager sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager // getSensorList(Sensor.TYPE_ALL) lists all the sensors present in the device val deviceSensors: List<Sensor> = sensorManager.getSensorList(Sensor.TYPE_ALL) // Text View that shall display this list val textView = findViewById<TextView>(R.id.tv) // Converting List to String and displaying // every sensor and its information on a new line for (sensors in deviceSensors) { textView.append(sensors.toString() + \"\\n\\n\") } }}",
"e": 30571,
"s": 29391,
"text": null
},
{
"code": null,
"e": 30584,
"s": 30571,
"text": "Android-Misc"
},
{
"code": null,
"e": 30592,
"s": 30584,
"text": "Android"
},
{
"code": null,
"e": 30599,
"s": 30592,
"text": "Kotlin"
},
{
"code": null,
"e": 30607,
"s": 30599,
"text": "Android"
},
{
"code": null,
"e": 30705,
"s": 30607,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30714,
"s": 30705,
"text": "Comments"
},
{
"code": null,
"e": 30727,
"s": 30714,
"text": "Old Comments"
},
{
"code": null,
"e": 30785,
"s": 30727,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 30828,
"s": 30785,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 30870,
"s": 30828,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 30901,
"s": 30870,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 30930,
"s": 30901,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 30973,
"s": 30930,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 31015,
"s": 30973,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 31034,
"s": 31015,
"text": "Android UI Layouts"
}
] |
DataPrep.Clean: Accelerate Your Data Cleaning | by Brandon Lockhart | Towards Data Science
|
Authors: Brandon Lockhart and Alice Lin
DataPrep is a library that aims to provide the easiest way to prepare data in Python. To address the onerous data cleaning step of data preparation, DataPrep has developed a new component: DataPrep.Clean.
DataPrep.Clean contains simple and efficient functions for cleaning, standardizing, and validating data in a DataFrame. The functions use a unified interface to perform common data cleaning operations required for various types of data.
This article demonstrates how to use DataPrep.Clean to simplify and speed-up data cleaning tasks.
Incorrect or inconsistent data can lead to false conclusions. Therefore, it is imperative for data scientists to clean their data to ensure the results are accurate. However, data cleaning consumes a significant portion of a data scientist’s working time — 26% according to a recent survey — and is normally considered to be tedious and mundane work.
Data cleaning tasks usually involve writing regular expressions to ensure values follow an allowed pattern and writing scripts to transform and standardize values, which can be difficult and error-prone. Furthermore, these tasks are often data or domain-specific, and need to be performed anew for each dataset.
There are three reasons DataPrep.Clean is the ideal tool for data cleaning in Python:
A Unified API: each function follows a simple naming convention, clean_type() and validate_type(), where type is the semantic data type of interest.Efficiency: the data is processed with the parallel computing library Dask to achieve fast performance.Transparency: after executing a cleaning function, a report is generated that describes the alterations that were made to the data.
A Unified API: each function follows a simple naming convention, clean_type() and validate_type(), where type is the semantic data type of interest.
Efficiency: the data is processed with the parallel computing library Dask to achieve fast performance.
Transparency: after executing a cleaning function, a report is generated that describes the alterations that were made to the data.
Let’s get started with DataPrep.Clean.
You can install DataPrep with pip using the command:
pip install -U dataprep==0.3.0a0
This is an alpha version, and DataPrep version 0.3 will be released soon.
We will use the dataset waste_hauler from DataPrep’s internal dataset repository. Let’s start by loading the DataPrep.Clean functions and the dataset into a pandas DataFrame:
from dataprep.clean import *from dataprep.datasets import load_datasetdf = load_dataset('waste_hauler')
Let’s take a look at the dataset:
df.head()
Notice the words in the column headers are uppercase and separated by spaces. However, it is easier to work with headers in snake case style since you don’t need to hold down the shift key when typing a header and you can access each column directly as an attribute of the DataFrame (e.g, df.local_address). To transform the headers, we can use the function clean_headers()which takes a DataFrame as input and returns the DataFrame with the headers in a desired style:
df = clean_headers(df)df.columns
clean_headers() by default converts the headers into snake case, however, many other styles are supported. Check out the user guide for more information.
DataPrep.Clean provides simple functions that parse, reformat and standardize values in a column. These functions follow the naming convention clean_type(), where type is the data type (such as phone numbers or email addresses) of the column that is to be cleaned. A DataFrame and column name are passed as input, and the DataFrame is returned with a new column containing the cleaned values of the specified column. The data can also be cleaned in place by specifying the parameter inplace=True.
Let’s see how to standardize phone numbers and street addresses using DataPrep.Clean.
Let’s take a look at the column phone:
df.phone.head()
As we can see, the phone numbers have different formats. To standardize their formats, we can use the function clean_phone(), which will by default convert all phone numbers into the format NPA-NXX-XXXX. clean_phone() takes a DataFrame and the name of the column that is to be cleaned as input, and it returns the original DataFrame augmented with a new column phone_clean containing the standardized phone numbers.
df = clean_phone(df, 'phone')df[['phone', 'phone_clean']].head()
Also, after calling clean_phone() a summary report is printed that describes the alterations made to the data to clean the column and the quality of the data in the resulting column:
To output the phone numbers in the format (NPA) NXX-XXXX, we can set the output_format parameter to national:
df = clean_phone(df, 'phone', output_format='national')df[['phone', 'phone_clean']].head()
For more information about clean_phone(), check out the user guide.
Next, let’s take a look at the local_address column:
df.local_address.head()
There are several inconsistencies in these address representations. For example, using “AVE.” (index 0) and “AVENUE” (index 1) to represent “avenue”, or “EAST” (index 3) and “E” (index 4) to represent “east”. To standardize these inconsistencies, we can use the function clean_address():
df = clean_address(df, 'local_address')df[['local_address', 'local_address_clean']].head()
Now each address in the column local_address_clean has the same, consistent format.
We may additionally like to extract components from the address, such as city and state. We can accomplish this by setting the parameter split to True which will create a new column in the DataFrame for each address component. Let’s call clean_address() with split=True and take a look at the new columns:
df = clean_address(df, 'local_address', split=True)
These individual components make it easy for the user to format an address as desired or perform aggregate analysis on cities and states.
For more information about clean_address(), check out the user guide.
Data validation refers to the process of ensuring that data is correct and correctly represented. DataPrep.Clean provides functions for validating various data types. The data validation functions follow the naming convention validate_type(), where type is the name of the semantic data type that is to be validated.
Each validation function takes a data Series as input and returns a boolean Series that indicates whether each value is of the specified data type or not. For example, let’s use the function validate_email() on the Series df['email']:
df['valid_email'] = validate_email(df['email'])df[['email', 'valid_email']].head()
As we can see, some values in the email column are valid email addresses, others are not, and validate_email() returns True and False appropriately. Moreover, we can filter the dataset to identify records that have incorrect email addresses:
df[~validate_email(df['email'])].dropna()
As we can see, these rows of the email column erroneously contain text and dates. Thus, validate_email() enables quick identification of these values so the data scientist can remove or correct the invalid email addresses as needed.
Next, we will see how DataPrep.Clean can be used for semantic data type detection. Although frequently a dataset is accompanied by informative column names that denote the type of data in their respective column, sometimes it is not, and it would be useful to identify the data type of each column. Alternatively, you may have a large number of columns or multiple datasets and would like to identify columns having specific data types, which could be difficult and time-consuming to do.
Below is a function that identifies the data type of each column, specifically checking for phone numbers, email addresses, street addresses, and dates.
def detect_data_types(df, thresh): ls = [] for col in df.columns: n = len(df[col].dropna()) if validate_phone(df[col].dropna()).sum() / n > thresh: ls.append((col, "phone")) elif validate_email(df[col].dropna()).sum() / n > thresh: ls.append((col, "email")) elif validate_address(df[col].dropna()).sum() / n > thresh: ls.append((col, "address")) elif validate_date(df[col].dropna()).sum() / n > thresh: ls.append((col, "date")) return pd.DataFrame(ls, columns=["Column Name", "Data Type"])
detect_data_types() takes a DataFrame df and threshold thresh as input. For each column in df, the validate_type() functions are used to determine how many values in the column satisfy each data type. If the proportion of values that satisfy the type is greater than thresh, the column is determined to be of that type.
Let’s call detect_data_types() with a threshold of 0.8:
df_types = detect_data_types(df, thresh=0.8)df_types
As we can see, the address, phone and email data types are correctly identified. Moreover, the column created is identified as containing dates, which is non-trivial to infer from the column name.
With the exponential increase in data collection across many fields, users of various skill levels need to derive insights from data. To avoid the garbage in, garbage out truism, data cleaning needs to be performed which can be difficult, time-consuming and tedious.
DataPrep.Clean through its simple APIs has the potential to turn data cleaning from the bane of each data scientist’s existence into a fast and easy process.
DataPrep.Clean currently contains functions for:
Column Headers
Country Names
Dates and Times
Email Addresses
Geographic Coordinates
IP Addresses
Phone Numbers
URLs
US Street Addresses
and more functions are currently being developed.
To learn more about DataPrep.Clean, check out the user guides and API references.
|
[
{
"code": null,
"e": 212,
"s": 172,
"text": "Authors: Brandon Lockhart and Alice Lin"
},
{
"code": null,
"e": 417,
"s": 212,
"text": "DataPrep is a library that aims to provide the easiest way to prepare data in Python. To address the onerous data cleaning step of data preparation, DataPrep has developed a new component: DataPrep.Clean."
},
{
"code": null,
"e": 654,
"s": 417,
"text": "DataPrep.Clean contains simple and efficient functions for cleaning, standardizing, and validating data in a DataFrame. The functions use a unified interface to perform common data cleaning operations required for various types of data."
},
{
"code": null,
"e": 752,
"s": 654,
"text": "This article demonstrates how to use DataPrep.Clean to simplify and speed-up data cleaning tasks."
},
{
"code": null,
"e": 1103,
"s": 752,
"text": "Incorrect or inconsistent data can lead to false conclusions. Therefore, it is imperative for data scientists to clean their data to ensure the results are accurate. However, data cleaning consumes a significant portion of a data scientist’s working time — 26% according to a recent survey — and is normally considered to be tedious and mundane work."
},
{
"code": null,
"e": 1415,
"s": 1103,
"text": "Data cleaning tasks usually involve writing regular expressions to ensure values follow an allowed pattern and writing scripts to transform and standardize values, which can be difficult and error-prone. Furthermore, these tasks are often data or domain-specific, and need to be performed anew for each dataset."
},
{
"code": null,
"e": 1501,
"s": 1415,
"text": "There are three reasons DataPrep.Clean is the ideal tool for data cleaning in Python:"
},
{
"code": null,
"e": 1884,
"s": 1501,
"text": "A Unified API: each function follows a simple naming convention, clean_type() and validate_type(), where type is the semantic data type of interest.Efficiency: the data is processed with the parallel computing library Dask to achieve fast performance.Transparency: after executing a cleaning function, a report is generated that describes the alterations that were made to the data."
},
{
"code": null,
"e": 2033,
"s": 1884,
"text": "A Unified API: each function follows a simple naming convention, clean_type() and validate_type(), where type is the semantic data type of interest."
},
{
"code": null,
"e": 2137,
"s": 2033,
"text": "Efficiency: the data is processed with the parallel computing library Dask to achieve fast performance."
},
{
"code": null,
"e": 2269,
"s": 2137,
"text": "Transparency: after executing a cleaning function, a report is generated that describes the alterations that were made to the data."
},
{
"code": null,
"e": 2308,
"s": 2269,
"text": "Let’s get started with DataPrep.Clean."
},
{
"code": null,
"e": 2361,
"s": 2308,
"text": "You can install DataPrep with pip using the command:"
},
{
"code": null,
"e": 2394,
"s": 2361,
"text": "pip install -U dataprep==0.3.0a0"
},
{
"code": null,
"e": 2468,
"s": 2394,
"text": "This is an alpha version, and DataPrep version 0.3 will be released soon."
},
{
"code": null,
"e": 2643,
"s": 2468,
"text": "We will use the dataset waste_hauler from DataPrep’s internal dataset repository. Let’s start by loading the DataPrep.Clean functions and the dataset into a pandas DataFrame:"
},
{
"code": null,
"e": 2747,
"s": 2643,
"text": "from dataprep.clean import *from dataprep.datasets import load_datasetdf = load_dataset('waste_hauler')"
},
{
"code": null,
"e": 2781,
"s": 2747,
"text": "Let’s take a look at the dataset:"
},
{
"code": null,
"e": 2791,
"s": 2781,
"text": "df.head()"
},
{
"code": null,
"e": 3260,
"s": 2791,
"text": "Notice the words in the column headers are uppercase and separated by spaces. However, it is easier to work with headers in snake case style since you don’t need to hold down the shift key when typing a header and you can access each column directly as an attribute of the DataFrame (e.g, df.local_address). To transform the headers, we can use the function clean_headers()which takes a DataFrame as input and returns the DataFrame with the headers in a desired style:"
},
{
"code": null,
"e": 3293,
"s": 3260,
"text": "df = clean_headers(df)df.columns"
},
{
"code": null,
"e": 3447,
"s": 3293,
"text": "clean_headers() by default converts the headers into snake case, however, many other styles are supported. Check out the user guide for more information."
},
{
"code": null,
"e": 3944,
"s": 3447,
"text": "DataPrep.Clean provides simple functions that parse, reformat and standardize values in a column. These functions follow the naming convention clean_type(), where type is the data type (such as phone numbers or email addresses) of the column that is to be cleaned. A DataFrame and column name are passed as input, and the DataFrame is returned with a new column containing the cleaned values of the specified column. The data can also be cleaned in place by specifying the parameter inplace=True."
},
{
"code": null,
"e": 4030,
"s": 3944,
"text": "Let’s see how to standardize phone numbers and street addresses using DataPrep.Clean."
},
{
"code": null,
"e": 4069,
"s": 4030,
"text": "Let’s take a look at the column phone:"
},
{
"code": null,
"e": 4085,
"s": 4069,
"text": "df.phone.head()"
},
{
"code": null,
"e": 4501,
"s": 4085,
"text": "As we can see, the phone numbers have different formats. To standardize their formats, we can use the function clean_phone(), which will by default convert all phone numbers into the format NPA-NXX-XXXX. clean_phone() takes a DataFrame and the name of the column that is to be cleaned as input, and it returns the original DataFrame augmented with a new column phone_clean containing the standardized phone numbers."
},
{
"code": null,
"e": 4566,
"s": 4501,
"text": "df = clean_phone(df, 'phone')df[['phone', 'phone_clean']].head()"
},
{
"code": null,
"e": 4749,
"s": 4566,
"text": "Also, after calling clean_phone() a summary report is printed that describes the alterations made to the data to clean the column and the quality of the data in the resulting column:"
},
{
"code": null,
"e": 4859,
"s": 4749,
"text": "To output the phone numbers in the format (NPA) NXX-XXXX, we can set the output_format parameter to national:"
},
{
"code": null,
"e": 4950,
"s": 4859,
"text": "df = clean_phone(df, 'phone', output_format='national')df[['phone', 'phone_clean']].head()"
},
{
"code": null,
"e": 5018,
"s": 4950,
"text": "For more information about clean_phone(), check out the user guide."
},
{
"code": null,
"e": 5071,
"s": 5018,
"text": "Next, let’s take a look at the local_address column:"
},
{
"code": null,
"e": 5095,
"s": 5071,
"text": "df.local_address.head()"
},
{
"code": null,
"e": 5383,
"s": 5095,
"text": "There are several inconsistencies in these address representations. For example, using “AVE.” (index 0) and “AVENUE” (index 1) to represent “avenue”, or “EAST” (index 3) and “E” (index 4) to represent “east”. To standardize these inconsistencies, we can use the function clean_address():"
},
{
"code": null,
"e": 5474,
"s": 5383,
"text": "df = clean_address(df, 'local_address')df[['local_address', 'local_address_clean']].head()"
},
{
"code": null,
"e": 5558,
"s": 5474,
"text": "Now each address in the column local_address_clean has the same, consistent format."
},
{
"code": null,
"e": 5864,
"s": 5558,
"text": "We may additionally like to extract components from the address, such as city and state. We can accomplish this by setting the parameter split to True which will create a new column in the DataFrame for each address component. Let’s call clean_address() with split=True and take a look at the new columns:"
},
{
"code": null,
"e": 5916,
"s": 5864,
"text": "df = clean_address(df, 'local_address', split=True)"
},
{
"code": null,
"e": 6054,
"s": 5916,
"text": "These individual components make it easy for the user to format an address as desired or perform aggregate analysis on cities and states."
},
{
"code": null,
"e": 6124,
"s": 6054,
"text": "For more information about clean_address(), check out the user guide."
},
{
"code": null,
"e": 6441,
"s": 6124,
"text": "Data validation refers to the process of ensuring that data is correct and correctly represented. DataPrep.Clean provides functions for validating various data types. The data validation functions follow the naming convention validate_type(), where type is the name of the semantic data type that is to be validated."
},
{
"code": null,
"e": 6676,
"s": 6441,
"text": "Each validation function takes a data Series as input and returns a boolean Series that indicates whether each value is of the specified data type or not. For example, let’s use the function validate_email() on the Series df['email']:"
},
{
"code": null,
"e": 6759,
"s": 6676,
"text": "df['valid_email'] = validate_email(df['email'])df[['email', 'valid_email']].head()"
},
{
"code": null,
"e": 7001,
"s": 6759,
"text": "As we can see, some values in the email column are valid email addresses, others are not, and validate_email() returns True and False appropriately. Moreover, we can filter the dataset to identify records that have incorrect email addresses:"
},
{
"code": null,
"e": 7043,
"s": 7001,
"text": "df[~validate_email(df['email'])].dropna()"
},
{
"code": null,
"e": 7276,
"s": 7043,
"text": "As we can see, these rows of the email column erroneously contain text and dates. Thus, validate_email() enables quick identification of these values so the data scientist can remove or correct the invalid email addresses as needed."
},
{
"code": null,
"e": 7764,
"s": 7276,
"text": "Next, we will see how DataPrep.Clean can be used for semantic data type detection. Although frequently a dataset is accompanied by informative column names that denote the type of data in their respective column, sometimes it is not, and it would be useful to identify the data type of each column. Alternatively, you may have a large number of columns or multiple datasets and would like to identify columns having specific data types, which could be difficult and time-consuming to do."
},
{
"code": null,
"e": 7917,
"s": 7764,
"text": "Below is a function that identifies the data type of each column, specifically checking for phone numbers, email addresses, street addresses, and dates."
},
{
"code": null,
"e": 8495,
"s": 7917,
"text": "def detect_data_types(df, thresh): ls = [] for col in df.columns: n = len(df[col].dropna()) if validate_phone(df[col].dropna()).sum() / n > thresh: ls.append((col, \"phone\")) elif validate_email(df[col].dropna()).sum() / n > thresh: ls.append((col, \"email\")) elif validate_address(df[col].dropna()).sum() / n > thresh: ls.append((col, \"address\")) elif validate_date(df[col].dropna()).sum() / n > thresh: ls.append((col, \"date\")) return pd.DataFrame(ls, columns=[\"Column Name\", \"Data Type\"])"
},
{
"code": null,
"e": 8815,
"s": 8495,
"text": "detect_data_types() takes a DataFrame df and threshold thresh as input. For each column in df, the validate_type() functions are used to determine how many values in the column satisfy each data type. If the proportion of values that satisfy the type is greater than thresh, the column is determined to be of that type."
},
{
"code": null,
"e": 8871,
"s": 8815,
"text": "Let’s call detect_data_types() with a threshold of 0.8:"
},
{
"code": null,
"e": 8924,
"s": 8871,
"text": "df_types = detect_data_types(df, thresh=0.8)df_types"
},
{
"code": null,
"e": 9121,
"s": 8924,
"text": "As we can see, the address, phone and email data types are correctly identified. Moreover, the column created is identified as containing dates, which is non-trivial to infer from the column name."
},
{
"code": null,
"e": 9388,
"s": 9121,
"text": "With the exponential increase in data collection across many fields, users of various skill levels need to derive insights from data. To avoid the garbage in, garbage out truism, data cleaning needs to be performed which can be difficult, time-consuming and tedious."
},
{
"code": null,
"e": 9546,
"s": 9388,
"text": "DataPrep.Clean through its simple APIs has the potential to turn data cleaning from the bane of each data scientist’s existence into a fast and easy process."
},
{
"code": null,
"e": 9595,
"s": 9546,
"text": "DataPrep.Clean currently contains functions for:"
},
{
"code": null,
"e": 9610,
"s": 9595,
"text": "Column Headers"
},
{
"code": null,
"e": 9624,
"s": 9610,
"text": "Country Names"
},
{
"code": null,
"e": 9640,
"s": 9624,
"text": "Dates and Times"
},
{
"code": null,
"e": 9656,
"s": 9640,
"text": "Email Addresses"
},
{
"code": null,
"e": 9679,
"s": 9656,
"text": "Geographic Coordinates"
},
{
"code": null,
"e": 9692,
"s": 9679,
"text": "IP Addresses"
},
{
"code": null,
"e": 9706,
"s": 9692,
"text": "Phone Numbers"
},
{
"code": null,
"e": 9711,
"s": 9706,
"text": "URLs"
},
{
"code": null,
"e": 9731,
"s": 9711,
"text": "US Street Addresses"
},
{
"code": null,
"e": 9781,
"s": 9731,
"text": "and more functions are currently being developed."
}
] |
BeautifulSoup CSS selector - Selecting nth child - GeeksforGeeks
|
26 Mar, 2021
In this article, we will see how beautifulsoup can be employed to select nth-child. For this, select() methods of the module are used. The select() method uses the SoupSieve package to use the CSS selector against the parsed document.
Syntax: select(“css_selector”)
CSS SELECTOR:
nth-of-type(n): Selects the nth paragraph child of the parent.
nth-child(n): Selects paragraph which is the nth child of the parent
Approach:
Import moduleScrap data from a webpage.Parse the string scraped to HTML.Use find() function to get tag with the given class name or id or tag_name.Use select(“css_selector”) to find the nth childPrint the child.
Import module
Scrap data from a webpage.
Parse the string scraped to HTML.
Use find() function to get tag with the given class name or id or tag_name.
Use select(“css_selector”) to find the nth child
Print the child.
Example 1:
Python3
# importing modulefrom bs4 import BeautifulSoup markup = """<html> <head> <title>GEEKS FOR GEEKS EXAMPLE</title> </head> <body> <p class="1"><b>Geeks for Geeks</b></p> <p class="coding">A Computer Science portal for geeks. <h1>Heading</h1> <b class="gfg">Programming Articles</b>, <b class="gfg">Programming Languages</b>, <b class="gfg">Quizzes</b>; </p> <p class="coding">practice</p> </body></html> """ # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') parent = soup.find(class_="coding") # assign nn = 2 # print the 2nd <b> of parentprint(parent.select("b:nth-of-type("+str(n)+")"))print() # print the <b> which is the 2nd child of the parentprint(parent.select("b:nth-child("+str(n)+")"))
Output:
Explanation:
select(“p:nth-of-type(n)”) means select the nth paragraph child of the parent.
select(“p:nth-child(n)”) means select paragraph which is the nth child of the parent.
Both functions will return [] if a parent doesn’t have nth-child.
Example 2:
Python3
# importing modulefrom bs4 import BeautifulSoupimport requests # assign websitesample_website='https://www.geeksforgeeks.org/python-programming-language/'page=requests.get(sample_website) # parsering string to HTMLsoup = BeautifulSoup(page.content, 'html.parser')parent = soup.find(class_="wrapper") # assign nn = 1 # print the 2nd <b> of parentprint(parent.select("b:nth-of-type("+str(n)+")"))print() # print the <b> which is the 2nd child of the parentprint(parent.select("b:nth-child("+str(n)+")"))
Output:
Picked
Python BeautifulSoup
Python bs4-Exercises
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 24527,
"s": 24292,
"text": "In this article, we will see how beautifulsoup can be employed to select nth-child. For this, select() methods of the module are used. The select() method uses the SoupSieve package to use the CSS selector against the parsed document."
},
{
"code": null,
"e": 24558,
"s": 24527,
"text": "Syntax: select(“css_selector”)"
},
{
"code": null,
"e": 24572,
"s": 24558,
"text": "CSS SELECTOR:"
},
{
"code": null,
"e": 24635,
"s": 24572,
"text": "nth-of-type(n): Selects the nth paragraph child of the parent."
},
{
"code": null,
"e": 24704,
"s": 24635,
"text": "nth-child(n): Selects paragraph which is the nth child of the parent"
},
{
"code": null,
"e": 24714,
"s": 24704,
"text": "Approach:"
},
{
"code": null,
"e": 24927,
"s": 24714,
"text": "Import moduleScrap data from a webpage.Parse the string scraped to HTML.Use find() function to get tag with the given class name or id or tag_name.Use select(“css_selector”) to find the nth childPrint the child."
},
{
"code": null,
"e": 24941,
"s": 24927,
"text": "Import module"
},
{
"code": null,
"e": 24968,
"s": 24941,
"text": "Scrap data from a webpage."
},
{
"code": null,
"e": 25002,
"s": 24968,
"text": "Parse the string scraped to HTML."
},
{
"code": null,
"e": 25078,
"s": 25002,
"text": "Use find() function to get tag with the given class name or id or tag_name."
},
{
"code": null,
"e": 25128,
"s": 25078,
"text": "Use select(“css_selector”) to find the nth child"
},
{
"code": null,
"e": 25145,
"s": 25128,
"text": "Print the child."
},
{
"code": null,
"e": 25156,
"s": 25145,
"text": "Example 1:"
},
{
"code": null,
"e": 25164,
"s": 25156,
"text": "Python3"
},
{
"code": "# importing modulefrom bs4 import BeautifulSoup markup = \"\"\"<html> <head> <title>GEEKS FOR GEEKS EXAMPLE</title> </head> <body> <p class=\"1\"><b>Geeks for Geeks</b></p> <p class=\"coding\">A Computer Science portal for geeks. <h1>Heading</h1> <b class=\"gfg\">Programming Articles</b>, <b class=\"gfg\">Programming Languages</b>, <b class=\"gfg\">Quizzes</b>; </p> <p class=\"coding\">practice</p> </body></html> \"\"\" # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') parent = soup.find(class_=\"coding\") # assign nn = 2 # print the 2nd <b> of parentprint(parent.select(\"b:nth-of-type(\"+str(n)+\")\"))print() # print the <b> which is the 2nd child of the parentprint(parent.select(\"b:nth-child(\"+str(n)+\")\"))",
"e": 25984,
"s": 25164,
"text": null
},
{
"code": null,
"e": 25992,
"s": 25984,
"text": "Output:"
},
{
"code": null,
"e": 26005,
"s": 25992,
"text": "Explanation:"
},
{
"code": null,
"e": 26084,
"s": 26005,
"text": "select(“p:nth-of-type(n)”) means select the nth paragraph child of the parent."
},
{
"code": null,
"e": 26170,
"s": 26084,
"text": "select(“p:nth-child(n)”) means select paragraph which is the nth child of the parent."
},
{
"code": null,
"e": 26236,
"s": 26170,
"text": "Both functions will return [] if a parent doesn’t have nth-child."
},
{
"code": null,
"e": 26247,
"s": 26236,
"text": "Example 2:"
},
{
"code": null,
"e": 26255,
"s": 26247,
"text": "Python3"
},
{
"code": "# importing modulefrom bs4 import BeautifulSoupimport requests # assign websitesample_website='https://www.geeksforgeeks.org/python-programming-language/'page=requests.get(sample_website) # parsering string to HTMLsoup = BeautifulSoup(page.content, 'html.parser')parent = soup.find(class_=\"wrapper\") # assign nn = 1 # print the 2nd <b> of parentprint(parent.select(\"b:nth-of-type(\"+str(n)+\")\"))print() # print the <b> which is the 2nd child of the parentprint(parent.select(\"b:nth-child(\"+str(n)+\")\"))",
"e": 26762,
"s": 26255,
"text": null
},
{
"code": null,
"e": 26770,
"s": 26762,
"text": "Output:"
},
{
"code": null,
"e": 26777,
"s": 26770,
"text": "Picked"
},
{
"code": null,
"e": 26798,
"s": 26777,
"text": "Python BeautifulSoup"
},
{
"code": null,
"e": 26819,
"s": 26798,
"text": "Python bs4-Exercises"
},
{
"code": null,
"e": 26826,
"s": 26819,
"text": "Python"
},
{
"code": null,
"e": 26924,
"s": 26826,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26956,
"s": 26924,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26998,
"s": 26956,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27054,
"s": 26998,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27096,
"s": 27054,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27127,
"s": 27096,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27149,
"s": 27127,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27204,
"s": 27149,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27243,
"s": 27204,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27272,
"s": 27243,
"text": "Create a directory in Python"
}
] |
Dynamically change TableView Cell height in Swift
|
To change the height of tableView cell in ios dynamically, i.e resizing the cell according to the content available, we’ll need to make use of automatic dimension property. We’ll see this with the help of an sample project.
Create an empty project and go to it’s viewController class, conform it to UITableViewDataSource and UITableViewDelegate.
Now, In the below code, we will first create a table, then register a cell for that table, and add some table properties.
We’ll set the table view delegate and table view datasource.
Finally we’ll add the table view to view. Then we’ll call this function inside the viewDidLoad method of our view controller.
Note: We have set a property called estimatedRowHeight
func initTableView() {
let tableView = UITableView()
tableView.frame = self.view.frame
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.estimatedRowHeight = UITableView.automaticDimension
self.view.addSubview(tableView)
}
Now, this code will add a table to our view, we also need to tell the table how many sections and rows we want in our code.
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
This code will create some big line of text at the second row in our table view so that it gets the height according to content size.
Note: The UITableViewCell has a label property by default, and a label has 1 line of length by default, so we need to change that to see automatic dimension work.
Now we need to tell the table what height its cell should have.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
When we run the above code we get the following result.
|
[
{
"code": null,
"e": 1286,
"s": 1062,
"text": "To change the height of tableView cell in ios dynamically, i.e resizing the cell according to the content available, we’ll need to make use of automatic dimension property. We’ll see this with the help of an sample project."
},
{
"code": null,
"e": 1408,
"s": 1286,
"text": "Create an empty project and go to it’s viewController class, conform it to UITableViewDataSource and UITableViewDelegate."
},
{
"code": null,
"e": 1530,
"s": 1408,
"text": "Now, In the below code, we will first create a table, then register a cell for that table, and add some table properties."
},
{
"code": null,
"e": 1591,
"s": 1530,
"text": "We’ll set the table view delegate and table view datasource."
},
{
"code": null,
"e": 1717,
"s": 1591,
"text": "Finally we’ll add the table view to view. Then we’ll call this function inside the viewDidLoad method of our view controller."
},
{
"code": null,
"e": 1773,
"s": 1717,
"text": "Note: We have set a property called estimatedRowHeight "
},
{
"code": null,
"e": 2218,
"s": 1773,
"text": "func initTableView() {\n let tableView = UITableView()\n tableView.frame = self.view.frame\n tableView.dataSource = self\n tableView.delegate = self\n tableView.backgroundColor = colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)\n tableView.register(UITableViewCell.self, forCellReuseIdentifier: \"cell\")\n tableView.estimatedRowHeight = UITableView.automaticDimension\n self.view.addSubview(tableView)\n}"
},
{
"code": null,
"e": 2342,
"s": 2218,
"text": "Now, this code will add a table to our view, we also need to tell the table how many sections and rows we want in our code."
},
{
"code": null,
"e": 2686,
"s": 2342,
"text": "func numberOfSections(in tableView: UITableView) -> Int {\n return 1\n}\nfunc tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return 5\n}\nfunc numberOfSections(in tableView: UITableView) -> Int {\n return 1\n}\nfunc tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return 5\n}"
},
{
"code": null,
"e": 2820,
"s": 2686,
"text": "This code will create some big line of text at the second row in our table view so that it gets the height according to content size."
},
{
"code": null,
"e": 2983,
"s": 2820,
"text": "Note: The UITableViewCell has a label property by default, and a label has 1 line of length by default, so we need to change that to see automatic dimension work."
},
{
"code": null,
"e": 3047,
"s": 2983,
"text": "Now we need to tell the table what height its cell should have."
},
{
"code": null,
"e": 3182,
"s": 3047,
"text": "func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {\n return UITableView.automaticDimension\n}\n"
},
{
"code": null,
"e": 3238,
"s": 3182,
"text": "When we run the above code we get the following result."
}
] |
How to delete all the file contents using PowerShell?
|
If you want to delete the entire text file content using PowerShell, then we can use the Clear-Content command. For example, we have the below text file called Locations.txt on the C:\Temp path. You can check the content using the below file.
Get-Content C:\temp\locations.txt
To clear the file content, we can use the below command.
Clear-Content C:\Temp\locations.txt -Force
-Force switch is used to clear the contents without user confirmation.
When you use this command with the pipeline in the Get-Content command, it will generate an IO Exception error that the file is in use because we are already retrieving the contents using Get-Content and then trying to delete the existing content.
Clear-Content : The process cannot access the file 'C:\Temp\locations.txt' because it is being used by another process.
At line:1 char:37
+ Get-Content C:\Temp\locations.txt | Clear-Content
+ ~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (C:\Temp\locations.txt:String) [Clear-Content], IOException
+ FullyQualifiedErrorId : ClearContentIOError,Microsoft.PowerShell.Commands.ClearContentCommand
To clear the file contents for the CSV, we can first import that CSV file and then use the Clear() method to clear the file content. For example,
PS C:\> $csvfile = Import-Csv C:\Temp\Services.csv
PS C:\> $csvfile.Clear()
In the above example, the CSV file stored at C:\temp will be cleared. You can also directly use the Clear-Content command for the CSV file or other files to clear the entire content of the file.
|
[
{
"code": null,
"e": 1305,
"s": 1062,
"text": "If you want to delete the entire text file content using PowerShell, then we can use the Clear-Content command. For example, we have the below text file called Locations.txt on the C:\\Temp path. You can check the content using the below file."
},
{
"code": null,
"e": 1339,
"s": 1305,
"text": "Get-Content C:\\temp\\locations.txt"
},
{
"code": null,
"e": 1396,
"s": 1339,
"text": "To clear the file content, we can use the below command."
},
{
"code": null,
"e": 1439,
"s": 1396,
"text": "Clear-Content C:\\Temp\\locations.txt -Force"
},
{
"code": null,
"e": 1510,
"s": 1439,
"text": "-Force switch is used to clear the contents without user confirmation."
},
{
"code": null,
"e": 1758,
"s": 1510,
"text": "When you use this command with the pipeline in the Get-Content command, it will generate an IO Exception error that the file is in use because we are already retrieving the contents using Get-Content and then trying to delete the existing content."
},
{
"code": null,
"e": 2149,
"s": 1758,
"text": "Clear-Content : The process cannot access the file 'C:\\Temp\\locations.txt' because it is being used by another process.\nAt line:1 char:37\n+ Get-Content C:\\Temp\\locations.txt | Clear-Content\n+ ~~~~~~~~~~~~~\n+ CategoryInfo : WriteError: (C:\\Temp\\locations.txt:String) [Clear-Content], IOException\n+ FullyQualifiedErrorId : ClearContentIOError,Microsoft.PowerShell.Commands.ClearContentCommand"
},
{
"code": null,
"e": 2295,
"s": 2149,
"text": "To clear the file contents for the CSV, we can first import that CSV file and then use the Clear() method to clear the file content. For example,"
},
{
"code": null,
"e": 2371,
"s": 2295,
"text": "PS C:\\> $csvfile = Import-Csv C:\\Temp\\Services.csv\nPS C:\\> $csvfile.Clear()"
},
{
"code": null,
"e": 2566,
"s": 2371,
"text": "In the above example, the CSV file stored at C:\\temp will be cleared. You can also directly use the Clear-Content command for the CSV file or other files to clear the entire content of the file."
}
] |
How to create a dashed horizontal line in a ggplot2 graph in R?
|
To create a dashed horizontal line in a ggplot2 graph in R, we can follow the below steps −
First of all, create a data frame.
Then, create a plot using ggplot2.
After that, create the same plot with geom_hline function having horizontal line defined with y intercept and its type defined with line type argument.
Let's create a data frame as shown below −
Live Demo
> x<-rnorm(20)
> y<-rnorm(20)
> df<-data.frame(x,y)
> df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y
1 -0.2622735 0.050784727
2 -0.9453493 0.005828098
3 -0.5544653 -0.569278949
4 0.4988631 0.978485828
5 0.5389510 -2.328920035
6 0.4434926 1.099015564
7 0.2681379 0.760637085
8 1.5537351 0.172285069
9 0.9497421 -1.823161011
10 0.3323686 -1.394199992
11 0.2146744 0.538098034
12 0.8275667 -0.361978640
13 -0.4820211 0.477345035
14 0.4364038 -0.341711304
15 -0.4499373 0.854135140
16 1.6604468 -1.333167314
17 -0.4244539 0.989662861
18 1.3667020 -0.358490011
19 -1.5132316 2.234713443
20 0.8474354 1.162478362
Let’s create a scatterplot between x and y −
> x<-rnorm(20)
> y<-rnorm(20)
> df<-data.frame(x,y)
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()
Using geom_hline to create the dashed horizontal line in the above plot with yintercept = 0.5 and linetype = 2 −
Live Demo
> x<-rnorm(20)
> y<-rnorm(20)
> df<-data.frame(x,y)
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=0.5,linetype=2)
|
[
{
"code": null,
"e": 1154,
"s": 1062,
"text": "To create a dashed horizontal line in a ggplot2 graph in R, we can follow the below steps −"
},
{
"code": null,
"e": 1189,
"s": 1154,
"text": "First of all, create a data frame."
},
{
"code": null,
"e": 1224,
"s": 1189,
"text": "Then, create a plot using ggplot2."
},
{
"code": null,
"e": 1376,
"s": 1224,
"text": "After that, create the same plot with geom_hline function having horizontal line defined with y intercept and its type defined with line type argument."
},
{
"code": null,
"e": 1419,
"s": 1376,
"text": "Let's create a data frame as shown below −"
},
{
"code": null,
"e": 1430,
"s": 1419,
"text": " Live Demo"
},
{
"code": null,
"e": 1487,
"s": 1430,
"text": "> x<-rnorm(20)\n> y<-rnorm(20)\n> df<-data.frame(x,y)\n> df"
},
{
"code": null,
"e": 1606,
"s": 1487,
"text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −"
},
{
"code": null,
"e": 2144,
"s": 1606,
"text": " x y\n1 -0.2622735 0.050784727\n2 -0.9453493 0.005828098\n3 -0.5544653 -0.569278949\n4 0.4988631 0.978485828\n5 0.5389510 -2.328920035\n6 0.4434926 1.099015564\n7 0.2681379 0.760637085\n8 1.5537351 0.172285069\n9 0.9497421 -1.823161011\n10 0.3323686 -1.394199992\n11 0.2146744 0.538098034\n12 0.8275667 -0.361978640\n13 -0.4820211 0.477345035\n14 0.4364038 -0.341711304\n15 -0.4499373 0.854135140\n16 1.6604468 -1.333167314\n17 -0.4244539 0.989662861\n18 1.3667020 -0.358490011\n19 -1.5132316 2.234713443\n20 0.8474354 1.162478362"
},
{
"code": null,
"e": 2189,
"s": 2144,
"text": "Let’s create a scatterplot between x and y −"
},
{
"code": null,
"e": 2295,
"s": 2189,
"text": "> x<-rnorm(20)\n> y<-rnorm(20)\n> df<-data.frame(x,y)\n> library(ggplot2)\n> ggplot(df,aes(x,y))+geom_point()"
},
{
"code": null,
"e": 2408,
"s": 2295,
"text": "Using geom_hline to create the dashed horizontal line in the above plot with yintercept = 0.5 and linetype = 2 −"
},
{
"code": null,
"e": 2419,
"s": 2408,
"text": " Live Demo"
},
{
"code": null,
"e": 2563,
"s": 2419,
"text": "> x<-rnorm(20)\n> y<-rnorm(20)\n> df<-data.frame(x,y)\n> library(ggplot2)\n> ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=0.5,linetype=2)"
}
] |
Build Your Own Convolution Neural Network in 5 mins | by Rohith Gandhi | Towards Data Science
|
Before answering what a convolutional neural network is, I believe you guys are aware of what neural networks are. If you are shaky on the basics, check out this link. Moving on. A convolution neural network is similar to a multi-layer perceptron network. The major differences are what the network learns, how they are structured and what purpose they are mostly used for. Convolutional neural networks were also inspired from biological processes, their structure has a semblance of the visual cortex present in an animal. CNNs are largely applied in the domain of computer vision and has been highly successful in achieving state of the art performance on various test cases.
The hidden layers in a CNN are generally convolution and pooling(downsampling) layers. In each convolution layer, we take a filter of a small size and move that filter across the image and perform convolution operations. Convolution operations are nothing but element-wise matrix multiplication between the filter values and the pixels in the image and the resultant values are summed.
The filter’s values are tuned through the iterative process of training and after a neural net has trained for certain number of epochs, these filters start to look out for various features in the image. Take the example of face detection using a convolutional neural network. The earlier layers of the network looks for simple features such as edges at different orientations etc. As we progress through the network, the layers start detecting more complex features and when you look at the features detected by the final layers, they almost look like a face.
Now, let’s move on to pooling layers. Pooling layers are used to downsample the image. The image would contain a lot of pixel values and it is typically easy for the network to learn the features if the image size is progressively reduced. Pooling layers help in reducing the number of parameters required and hence, this reduces the computation required. Pooling also helps in avoiding overfitting. There are two types of pooling operation that could be done:
Max Pooling — Selecting the maximum value
Average Pooling — Sum all of the values and dividing it by the total number of values
Average pooling is rarely used, you could find max pooling used in most of the examples.
Before we start coding, I would like to let you know that the dataset we are going to be using is the MNIST digits dataset and we are going to be using the Keras library with a Tensorflow backend for building the model. Ok, enough. Let’s do some coding.
First, let us do some necessary imports. The keras library helps us build our convolutional neural network. We download the mnist dataset through keras. We import a sequential model which is a pre-built keras model where you can just add the layers. We import the convolution and pooling layers. We also import dense layers as they are used to predict the labels. The dropout layer reduces overfitting and the flatten layer expands a three-dimensional vector into a one-dimensional vector. Finally, we import numpy for matrix operations.
Most of the statements in the above code would be trivial, I would just explain some lines of the code. We reshape x_train and x_test because our CNN accepts only a four-dimensional vector. The value 60000 represents the number of images in the training data, 28 represents the image size and 1 represents the number of channels. The number of channels is set to 1 if the image is in grayscale and if the image is in RGB format, the number of channels is set to 3. We also convert our target values into binary class matrices. To know what binary class matrices look like take a look at the example below.
Y = 2 # the value 2 represents that the image has digit 2 Y = [0,0,1,0,0,0,0,0,0,0] # The 2nd position in the vector is made 1# Here, the class value is converted into a binary class matrix
We build a sequential model and add convolutional layers and max pooling layers to it. We also add dropout layers in between, dropout randomly switches off some neurons in the network which forces the data to find new paths. Therefore, this reduces overfitting. We add dense layers at the end which are used for class prediction(0–9).
We now compile the model with a categorical cross entropy loss function, Adadelta optimizer and an accuracy metric. We then fit the dataset to the model, i.e we train the model for 12 epochs. After training the model, we evaluate the loss and accuracy of the model on the test data and print it.
Convolutional neural networks do have some shortcomings pointed out by Geoffrey Hinton. He posited that his capsule networks are the way to go if we are looking to achieve human-level accuracy in the domain of computer vision. But, as of now, CNNs seem to be doing really well. Please let me know if you found this article to be useful, thank you :)
|
[
{
"code": null,
"e": 851,
"s": 172,
"text": "Before answering what a convolutional neural network is, I believe you guys are aware of what neural networks are. If you are shaky on the basics, check out this link. Moving on. A convolution neural network is similar to a multi-layer perceptron network. The major differences are what the network learns, how they are structured and what purpose they are mostly used for. Convolutional neural networks were also inspired from biological processes, their structure has a semblance of the visual cortex present in an animal. CNNs are largely applied in the domain of computer vision and has been highly successful in achieving state of the art performance on various test cases."
},
{
"code": null,
"e": 1237,
"s": 851,
"text": "The hidden layers in a CNN are generally convolution and pooling(downsampling) layers. In each convolution layer, we take a filter of a small size and move that filter across the image and perform convolution operations. Convolution operations are nothing but element-wise matrix multiplication between the filter values and the pixels in the image and the resultant values are summed."
},
{
"code": null,
"e": 1798,
"s": 1237,
"text": "The filter’s values are tuned through the iterative process of training and after a neural net has trained for certain number of epochs, these filters start to look out for various features in the image. Take the example of face detection using a convolutional neural network. The earlier layers of the network looks for simple features such as edges at different orientations etc. As we progress through the network, the layers start detecting more complex features and when you look at the features detected by the final layers, they almost look like a face."
},
{
"code": null,
"e": 2259,
"s": 1798,
"text": "Now, let’s move on to pooling layers. Pooling layers are used to downsample the image. The image would contain a lot of pixel values and it is typically easy for the network to learn the features if the image size is progressively reduced. Pooling layers help in reducing the number of parameters required and hence, this reduces the computation required. Pooling also helps in avoiding overfitting. There are two types of pooling operation that could be done:"
},
{
"code": null,
"e": 2301,
"s": 2259,
"text": "Max Pooling — Selecting the maximum value"
},
{
"code": null,
"e": 2387,
"s": 2301,
"text": "Average Pooling — Sum all of the values and dividing it by the total number of values"
},
{
"code": null,
"e": 2476,
"s": 2387,
"text": "Average pooling is rarely used, you could find max pooling used in most of the examples."
},
{
"code": null,
"e": 2730,
"s": 2476,
"text": "Before we start coding, I would like to let you know that the dataset we are going to be using is the MNIST digits dataset and we are going to be using the Keras library with a Tensorflow backend for building the model. Ok, enough. Let’s do some coding."
},
{
"code": null,
"e": 3268,
"s": 2730,
"text": "First, let us do some necessary imports. The keras library helps us build our convolutional neural network. We download the mnist dataset through keras. We import a sequential model which is a pre-built keras model where you can just add the layers. We import the convolution and pooling layers. We also import dense layers as they are used to predict the labels. The dropout layer reduces overfitting and the flatten layer expands a three-dimensional vector into a one-dimensional vector. Finally, we import numpy for matrix operations."
},
{
"code": null,
"e": 3874,
"s": 3268,
"text": "Most of the statements in the above code would be trivial, I would just explain some lines of the code. We reshape x_train and x_test because our CNN accepts only a four-dimensional vector. The value 60000 represents the number of images in the training data, 28 represents the image size and 1 represents the number of channels. The number of channels is set to 1 if the image is in grayscale and if the image is in RGB format, the number of channels is set to 3. We also convert our target values into binary class matrices. To know what binary class matrices look like take a look at the example below."
},
{
"code": null,
"e": 4064,
"s": 3874,
"text": "Y = 2 # the value 2 represents that the image has digit 2 Y = [0,0,1,0,0,0,0,0,0,0] # The 2nd position in the vector is made 1# Here, the class value is converted into a binary class matrix"
},
{
"code": null,
"e": 4399,
"s": 4064,
"text": "We build a sequential model and add convolutional layers and max pooling layers to it. We also add dropout layers in between, dropout randomly switches off some neurons in the network which forces the data to find new paths. Therefore, this reduces overfitting. We add dense layers at the end which are used for class prediction(0–9)."
},
{
"code": null,
"e": 4695,
"s": 4399,
"text": "We now compile the model with a categorical cross entropy loss function, Adadelta optimizer and an accuracy metric. We then fit the dataset to the model, i.e we train the model for 12 epochs. After training the model, we evaluate the loss and accuracy of the model on the test data and print it."
}
] |
Change grid line thickness in 3D surface plot in Python - Matplotlib - GeeksforGeeks
|
14 Sep, 2021
Prerequisites: Matplotlib
Using Matplotlib library we can plot the three-dimensional plot by importing the mplot3d toolkit. In this plot, we are going the change the thickness of the gridline in a three-dimensional surface plot. Surface Plot is the diagram of 3D data it shows the functional relationship between the dependent variable (Y), and two independent variables (X and Y) rather than showing the individual data points.
Gridlines are the lines that cross the plot to show the axis divisions. Gridlines of the plot help the viewer of the chart to see what value is represented by the particular unlabeled data point of the plot. It helps especially when the plot is too complicated to analyze, so according to the need, we can adjust or change the thickness of the grid lines or the styles of the grid lines.
Import the necessary libraries.
Create the 3D data for plotting.
Create the three-dimensional co-ordinate system using ax = matplotlib.pyplot.gca(‘projection=3d’) here gca stands for get current grid and in that pass the parameter projection=3d it will generate three-dimensional co-ordinate system.
Now for changing the gridline thickness we have to update the axes info of respective axes by using ax.xaxis.update({‘linewidth’:3}) or whatever grid width you want to set this is for x-axis in the same way you can set for Y axis and Z axis just writing yaxis, zaxis in place of xaxis respectively.
If want to change the color of the respective axis just pass ‘color’:’red’ in the dictionary ax.xaxis.update({‘linewidth’:3,’color’:’red’}) or whatever color you want to set.
Now after making changes plot the surface plot using ax.plot_surface(x,y,z) in that pass 3d data.
Set X, Y and Z label using ax.set_xlabel(), ax.set_ylabel(), ax.set_zlabel() in parameter pass the string.
Now visualize the plot using matplotlib.pyplot.show() function.
Example 1: Changing X-axis grid lines thickness in the 3D surface plot using Matplotlib.
Python
# importing necessary librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # function to create data for plottingdef data_creation(): # creating 3d data x = np.outer(np.linspace(-3, 3, 30), np.ones(30)) y = x.copy().T # transpose z = np.cos(x ** 2 + y ** 2) return (x,y,z) # main functionif __name__ == '__main__': # creating three dimensional co-ordinate system ax = plt.gca(projection='3d') # calling data creation function and storing in # the variables data_x,data_y,data_z = data_creation() # changing grid lines thickness of x axis to 3 ax.xaxis._axinfo["grid"].update({"linewidth":3}) # plotting surface plot ax.plot_surface(data_x,data_y,data_z) # giving label name to x,y and z axis ax.set_xlabel("X axis") ax.set_ylabel("Y axis") ax.set_zlabel("Z axis") # visualizing the plot plt.show()
Output:
In the above example, we had changed the gridline thickness of X-axis, as you can see in the above figure X-axis gridlines has a thicker line with gray color. It can be done by updating the _axinfo dictionary of the respective axis in the above example code our respective axis is X axis.
Example 2: Changing X-axis grid lines thickness in the 3D surface plot using Matplotlib.
Python
# importing necessary librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # function to create data for plottingdef data_creation(): # creating 3d data x = np.outer(np.linspace(-3, 3, 30), np.ones(30)) y = x.copy().T # transpose z = np.cos(x ** 2 + y ** 2) return (x,y,z) # main functionif __name__ == '__main__': # creating three dimensional co-ordinate system ax = plt.gca(projection='3d') # calling data creation function and storing in the variables data_x,data_y,data_z = data_creation() # changing grid lines thickness of Y axis to 3 ax.yaxis._axinfo["grid"].update({"linewidth":3}) # plotting surface plot ax.plot_surface(data_x,data_y,data_z) # giving label name to x,y and z axis ax.set_xlabel("X axis") ax.set_ylabel("Y axis") ax.set_zlabel("Z axis") # visualizing the plot plt.show()
Output:
In the above example, we had changed the gridline thickness of Y axis, as you can see in the above figure Y-axis gridlines has a thicker line with gray color. We had set the gridline thickness of Y-axis to 3.
Example 3: Changing Z axis grid lines thickness in 3D surface plot using Matplotlib.
Python
# importing necessary librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # function to create data for plottingdef data_creation(): # creating 3d data x = np.outer(np.linspace(-3, 3, 30), np.ones(30)) y = x.copy().T # transpose z = np.cos(x ** 2 + y ** 2) return (x,y,z) # main functionif __name__ == '__main__': # creating three dimensional co-ordinate system ax = plt.gca(projection='3d') # calling data creation function and storing in the variables data_x,data_y,data_z = data_creation() # changing grid lines thickness of Z axis to 3 ax.zaxis._axinfo["grid"].update({"linewidth":3}) # plotting surface plot ax.plot_surface(data_x,data_y,data_z) # giving label name to x,y and z axis ax.set_xlabel("X axis") ax.set_ylabel("Y axis") ax.set_zlabel("Z axis") # visualizing the plot plt.show()
Output:
In the above example, we had changed the gridline thickness of the Z-axis, as you can see in the above figure Z-axis gridlines have a thicker line with gray color. We had set the gridline thickness of the Z-axis to 3.
Example 4: Changing gridline thickness and color of all three axis using Matplotlib.
Python
# importing necessary librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # function to create data for plottingdef data_creation(): # creating 3d data x = np.outer(np.linspace(-3, 3, 30), np.ones(30)) y = x.copy().T # transpose z = np.cos(x ** 2 + y ** 2) return (x,y,z) # main functionif __name__ == '__main__': # creating three dimensional co-ordinate system ax = plt.gca(projection='3d') # calling data creation function and storing in the variables data_x,data_y,data_z = data_creation() # changing grid lines thickness of x axis to 1 ax.xaxis._axinfo["grid"].update({"linewidth":1}) # changing grid lines thickness of Y axis to 1 and giving color to red ax.yaxis._axinfo["grid"].update({"linewidth":1,'color':'red'}) # changing grid lines thickness of Z axis to 1 and giving color to green ax.zaxis._axinfo["grid"].update({"linewidth":1,'color':'green'}) # plotting surface plot ax.plot_surface(data_x,data_y,data_z) # giving label name to x,y and z axis ax.set_xlabel("X axis") ax.set_ylabel("Y axis") ax.set_zlabel("Z axis") # visualizing the plot plt.show()
Output:
In the above example, we had set the gridline thickness of X, Y, and Z axis to 1 and change the color of the Y-axis to red and Z-axis to green, by updating the _axinfo and updating the dictionary we had set line width and color of the 3D plot.
rs1686740
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 24318,
"s": 24292,
"text": "Prerequisites: Matplotlib"
},
{
"code": null,
"e": 24721,
"s": 24318,
"text": "Using Matplotlib library we can plot the three-dimensional plot by importing the mplot3d toolkit. In this plot, we are going the change the thickness of the gridline in a three-dimensional surface plot. Surface Plot is the diagram of 3D data it shows the functional relationship between the dependent variable (Y), and two independent variables (X and Y) rather than showing the individual data points."
},
{
"code": null,
"e": 25109,
"s": 24721,
"text": "Gridlines are the lines that cross the plot to show the axis divisions. Gridlines of the plot help the viewer of the chart to see what value is represented by the particular unlabeled data point of the plot. It helps especially when the plot is too complicated to analyze, so according to the need, we can adjust or change the thickness of the grid lines or the styles of the grid lines."
},
{
"code": null,
"e": 25141,
"s": 25109,
"text": "Import the necessary libraries."
},
{
"code": null,
"e": 25174,
"s": 25141,
"text": "Create the 3D data for plotting."
},
{
"code": null,
"e": 25409,
"s": 25174,
"text": "Create the three-dimensional co-ordinate system using ax = matplotlib.pyplot.gca(‘projection=3d’) here gca stands for get current grid and in that pass the parameter projection=3d it will generate three-dimensional co-ordinate system."
},
{
"code": null,
"e": 25708,
"s": 25409,
"text": "Now for changing the gridline thickness we have to update the axes info of respective axes by using ax.xaxis.update({‘linewidth’:3}) or whatever grid width you want to set this is for x-axis in the same way you can set for Y axis and Z axis just writing yaxis, zaxis in place of xaxis respectively."
},
{
"code": null,
"e": 25883,
"s": 25708,
"text": "If want to change the color of the respective axis just pass ‘color’:’red’ in the dictionary ax.xaxis.update({‘linewidth’:3,’color’:’red’}) or whatever color you want to set."
},
{
"code": null,
"e": 25981,
"s": 25883,
"text": "Now after making changes plot the surface plot using ax.plot_surface(x,y,z) in that pass 3d data."
},
{
"code": null,
"e": 26088,
"s": 25981,
"text": "Set X, Y and Z label using ax.set_xlabel(), ax.set_ylabel(), ax.set_zlabel() in parameter pass the string."
},
{
"code": null,
"e": 26152,
"s": 26088,
"text": "Now visualize the plot using matplotlib.pyplot.show() function."
},
{
"code": null,
"e": 26241,
"s": 26152,
"text": "Example 1: Changing X-axis grid lines thickness in the 3D surface plot using Matplotlib."
},
{
"code": null,
"e": 26248,
"s": 26241,
"text": "Python"
},
{
"code": "# importing necessary librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # function to create data for plottingdef data_creation(): # creating 3d data x = np.outer(np.linspace(-3, 3, 30), np.ones(30)) y = x.copy().T # transpose z = np.cos(x ** 2 + y ** 2) return (x,y,z) # main functionif __name__ == '__main__': # creating three dimensional co-ordinate system ax = plt.gca(projection='3d') # calling data creation function and storing in # the variables data_x,data_y,data_z = data_creation() # changing grid lines thickness of x axis to 3 ax.xaxis._axinfo[\"grid\"].update({\"linewidth\":3}) # plotting surface plot ax.plot_surface(data_x,data_y,data_z) # giving label name to x,y and z axis ax.set_xlabel(\"X axis\") ax.set_ylabel(\"Y axis\") ax.set_zlabel(\"Z axis\") # visualizing the plot plt.show()",
"e": 27166,
"s": 26248,
"text": null
},
{
"code": null,
"e": 27178,
"s": 27170,
"text": "Output:"
},
{
"code": null,
"e": 27471,
"s": 27182,
"text": "In the above example, we had changed the gridline thickness of X-axis, as you can see in the above figure X-axis gridlines has a thicker line with gray color. It can be done by updating the _axinfo dictionary of the respective axis in the above example code our respective axis is X axis."
},
{
"code": null,
"e": 27562,
"s": 27473,
"text": "Example 2: Changing X-axis grid lines thickness in the 3D surface plot using Matplotlib."
},
{
"code": null,
"e": 27571,
"s": 27564,
"text": "Python"
},
{
"code": "# importing necessary librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # function to create data for plottingdef data_creation(): # creating 3d data x = np.outer(np.linspace(-3, 3, 30), np.ones(30)) y = x.copy().T # transpose z = np.cos(x ** 2 + y ** 2) return (x,y,z) # main functionif __name__ == '__main__': # creating three dimensional co-ordinate system ax = plt.gca(projection='3d') # calling data creation function and storing in the variables data_x,data_y,data_z = data_creation() # changing grid lines thickness of Y axis to 3 ax.yaxis._axinfo[\"grid\"].update({\"linewidth\":3}) # plotting surface plot ax.plot_surface(data_x,data_y,data_z) # giving label name to x,y and z axis ax.set_xlabel(\"X axis\") ax.set_ylabel(\"Y axis\") ax.set_zlabel(\"Z axis\") # visualizing the plot plt.show()",
"e": 28481,
"s": 27571,
"text": null
},
{
"code": null,
"e": 28493,
"s": 28485,
"text": "Output:"
},
{
"code": null,
"e": 28706,
"s": 28497,
"text": "In the above example, we had changed the gridline thickness of Y axis, as you can see in the above figure Y-axis gridlines has a thicker line with gray color. We had set the gridline thickness of Y-axis to 3."
},
{
"code": null,
"e": 28793,
"s": 28708,
"text": "Example 3: Changing Z axis grid lines thickness in 3D surface plot using Matplotlib."
},
{
"code": null,
"e": 28802,
"s": 28795,
"text": "Python"
},
{
"code": "# importing necessary librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # function to create data for plottingdef data_creation(): # creating 3d data x = np.outer(np.linspace(-3, 3, 30), np.ones(30)) y = x.copy().T # transpose z = np.cos(x ** 2 + y ** 2) return (x,y,z) # main functionif __name__ == '__main__': # creating three dimensional co-ordinate system ax = plt.gca(projection='3d') # calling data creation function and storing in the variables data_x,data_y,data_z = data_creation() # changing grid lines thickness of Z axis to 3 ax.zaxis._axinfo[\"grid\"].update({\"linewidth\":3}) # plotting surface plot ax.plot_surface(data_x,data_y,data_z) # giving label name to x,y and z axis ax.set_xlabel(\"X axis\") ax.set_ylabel(\"Y axis\") ax.set_zlabel(\"Z axis\") # visualizing the plot plt.show()",
"e": 29709,
"s": 28802,
"text": null
},
{
"code": null,
"e": 29721,
"s": 29713,
"text": "Output:"
},
{
"code": null,
"e": 29943,
"s": 29725,
"text": "In the above example, we had changed the gridline thickness of the Z-axis, as you can see in the above figure Z-axis gridlines have a thicker line with gray color. We had set the gridline thickness of the Z-axis to 3."
},
{
"code": null,
"e": 30030,
"s": 29945,
"text": "Example 4: Changing gridline thickness and color of all three axis using Matplotlib."
},
{
"code": null,
"e": 30039,
"s": 30032,
"text": "Python"
},
{
"code": "# importing necessary librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # function to create data for plottingdef data_creation(): # creating 3d data x = np.outer(np.linspace(-3, 3, 30), np.ones(30)) y = x.copy().T # transpose z = np.cos(x ** 2 + y ** 2) return (x,y,z) # main functionif __name__ == '__main__': # creating three dimensional co-ordinate system ax = plt.gca(projection='3d') # calling data creation function and storing in the variables data_x,data_y,data_z = data_creation() # changing grid lines thickness of x axis to 1 ax.xaxis._axinfo[\"grid\"].update({\"linewidth\":1}) # changing grid lines thickness of Y axis to 1 and giving color to red ax.yaxis._axinfo[\"grid\"].update({\"linewidth\":1,'color':'red'}) # changing grid lines thickness of Z axis to 1 and giving color to green ax.zaxis._axinfo[\"grid\"].update({\"linewidth\":1,'color':'green'}) # plotting surface plot ax.plot_surface(data_x,data_y,data_z) # giving label name to x,y and z axis ax.set_xlabel(\"X axis\") ax.set_ylabel(\"Y axis\") ax.set_zlabel(\"Z axis\") # visualizing the plot plt.show()",
"e": 31235,
"s": 30039,
"text": null
},
{
"code": null,
"e": 31247,
"s": 31239,
"text": "Output:"
},
{
"code": null,
"e": 31495,
"s": 31251,
"text": "In the above example, we had set the gridline thickness of X, Y, and Z axis to 1 and change the color of the Y-axis to red and Z-axis to green, by updating the _axinfo and updating the dictionary we had set line width and color of the 3D plot."
},
{
"code": null,
"e": 31507,
"s": 31497,
"text": "rs1686740"
},
{
"code": null,
"e": 31514,
"s": 31507,
"text": "Picked"
},
{
"code": null,
"e": 31532,
"s": 31514,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 31539,
"s": 31532,
"text": "Python"
},
{
"code": null,
"e": 31637,
"s": 31539,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31669,
"s": 31637,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31711,
"s": 31669,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 31767,
"s": 31711,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 31809,
"s": 31767,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 31840,
"s": 31809,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 31862,
"s": 31840,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 31917,
"s": 31862,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 31956,
"s": 31917,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 31985,
"s": 31956,
"text": "Create a directory in Python"
}
] |
Double.ToString Method in C#
|
The Double.ToString() method in C# is used to convert the numeric value of this instance to its equivalent string representation.
Following is the syntax −
public override string ToString ();
Let us now see an example to implement the Double.ToString() method −
using System;
public class Demo{
public static void Main(){
double d = 45.7878d;
string str = d.ToString();
Console.WriteLine("String = "+str);
}
}
This will produce the following output −
String = 45.7878
Let us now see another example −
using System;
public class Demo{
public static void Main(){
double d = -68.89d;
string str = d.ToString();
Console.WriteLine("String = "+str);
}
}
This will produce the following output −
String = -68.89
|
[
{
"code": null,
"e": 1192,
"s": 1062,
"text": "The Double.ToString() method in C# is used to convert the numeric value of this instance to its equivalent string representation."
},
{
"code": null,
"e": 1218,
"s": 1192,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1254,
"s": 1218,
"text": "public override string ToString ();"
},
{
"code": null,
"e": 1324,
"s": 1254,
"text": "Let us now see an example to implement the Double.ToString() method −"
},
{
"code": null,
"e": 1496,
"s": 1324,
"text": "using System;\npublic class Demo{\n public static void Main(){\n double d = 45.7878d;\n string str = d.ToString();\n Console.WriteLine(\"String = \"+str);\n }\n}"
},
{
"code": null,
"e": 1537,
"s": 1496,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1554,
"s": 1537,
"text": "String = 45.7878"
},
{
"code": null,
"e": 1587,
"s": 1554,
"text": "Let us now see another example −"
},
{
"code": null,
"e": 1758,
"s": 1587,
"text": "using System;\npublic class Demo{\n public static void Main(){\n double d = -68.89d;\n string str = d.ToString();\n Console.WriteLine(\"String = \"+str);\n }\n}"
},
{
"code": null,
"e": 1799,
"s": 1758,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1815,
"s": 1799,
"text": "String = -68.89"
}
] |
How to add a new column in an R data frame by combining two columns with a special character?
|
A data frame can have multiple types of column and some of them could be combined to make a single column based on their characteristics. For example, if a column has characters and the other has numbers then we might want to join them by separating with a special character to showcase them as an identity.
Consider the below data frame −
Live Demo
> ID<-LETTERS[1:20]
> Frequency<-sample(1:100,20)
> set.seed(111)
> ID<-LETTERS[1:20]
> Frequency<-sample(1:100,20)
> df<-data.frame(ID,Frequency)
> df
ID Frequency
1 A 78
2 B 84
3 C 83
4 D 47
5 E 25
6 F 59
7 G 69
8 H 35
9 I 72
10 J 26
11 K 49
12 L 45
13 M 74
14 N 8
15 O 100
16 P 96
17 Q 24
18 R 48
19 S 95
20 T 7
Creating new columns with different separators −
> df$Combined_with_hash<-paste(df$ID,df$Frequency,sep="#")
> df
ID Frequency Combined_with_hash
1 A 78 A#78
2 B 84 B#84
3 C 83 C#83
4 D 47 D#47
5 E 25 E#25
6 F 59 F#59
7 G 69 G#69
8 H 35 H#35
9 I 72 I#72
10 J 26 J#26
11 K 49 K#49
12 L 45 L#45
13 M 74 M#74
14 N 8 N#8
15 O 100 O#100
16 P 96 P#96
17 Q 24 Q#24
18 R 48 R#48
19 S 95 S#95
20 T 7 T#7
> df$Combined_with_hyphen<-paste(df$ID,df$Frequency,sep="-")
> df
ID Frequency Combined_with_hash Combined_with_hyphen
1 A 78 A#78 A-78
2 B 84 B#84 B-84
3 C 83 C#83 C-83
4 D 47 D#47 D-47
5 E 25 E#25 E-25
6 F 59 F#59 F-59
7 G 69 G#69 G-69
8 H 35 H#35 H-35
9 I 72 I#72 I-72
10 J 26 J#26 J-26
11 K 49 K#49 K-49
12 L 45 L#45 L-45
13 M 74 M#74 M-74
14 N 8 N#8 N-8
15 O 100 O#100 O-100
16 P 96 P#96 P-96
17 Q 24 Q#24 Q-24
18 R 48 R#48 R-48
19 S 95 S#95 S-95
20 T 7 T#7 T-7
> df$Combined_with_slash<-paste(df$ID,df$Frequency,sep="/")
> df
ID Frequency Combined_with_hash Combined_with_hyphen Combined_with_slash
1 A 78 A#78 A-78 A/78
2 B 84 B#84 B-84 B/84
3 C 83 C#83 C-83 C/83
4 D 47 D#47 D-47 D/47
5 E 25 E#25 E-25 E/25
6 F 59 F#59 F-59 F/59
7 G 69 G#69 G-69 G/69
8 H 35 H#35 H-35 H/35
9 I 72 I#72 I-72 I/72
10 J 26 J#26 J-26 J/26
11 K 49 K#49 K-49 K/49
12 L 45 L#45 L-45 L/45
13 M 74 M#74 M-74 M/74
14 N 8 N#8 N-8 N/8
15 O 100 O#100 O-100 O/100
16 P 96 P#96 P-96 P/96
17 Q 24 Q#24 Q-24 Q/24
18 R 48 R#48 R-48 R/48
19 S 95 S#95 S-95 S/95
20 T 7 T#7 T-7 T/7
|
[
{
"code": null,
"e": 1370,
"s": 1062,
"text": "A data frame can have multiple types of column and some of them could be combined to make a single column based on their characteristics. For example, if a column has characters and the other has numbers then we might want to join them by separating with a special character to showcase them as an identity."
},
{
"code": null,
"e": 1402,
"s": 1370,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1413,
"s": 1402,
"text": " Live Demo"
},
{
"code": null,
"e": 1565,
"s": 1413,
"text": "> ID<-LETTERS[1:20]\n> Frequency<-sample(1:100,20)\n> set.seed(111)\n> ID<-LETTERS[1:20]\n> Frequency<-sample(1:100,20)\n> df<-data.frame(ID,Frequency)\n> df"
},
{
"code": null,
"e": 1789,
"s": 1565,
"text": " ID Frequency\n1 A 78\n2 B 84\n3 C 83\n4 D 47\n5 E 25\n6 F 59\n7 G 69\n8 H 35\n9 I 72\n10 J 26\n11 K 49\n12 L 45\n13 M 74\n14 N 8\n15 O 100\n16 P 96\n17 Q 24\n18 R 48\n19 S 95\n20 T 7"
},
{
"code": null,
"e": 1838,
"s": 1789,
"text": "Creating new columns with different separators −"
},
{
"code": null,
"e": 1902,
"s": 1838,
"text": "> df$Combined_with_hash<-paste(df$ID,df$Frequency,sep=\"#\")\n> df"
},
{
"code": null,
"e": 2343,
"s": 1902,
"text": " ID Frequency Combined_with_hash\n1 A 78 A#78\n2 B 84 B#84\n3 C 83 C#83\n4 D 47 D#47\n5 E 25 E#25\n6 F 59 F#59\n7 G 69 G#69\n8 H 35 H#35\n9 I 72 I#72\n10 J 26 J#26\n11 K 49 K#49\n12 L 45 L#45\n13 M 74 M#74\n14 N 8 N#8\n15 O 100 O#100\n16 P 96 P#96\n17 Q 24 Q#24\n18 R 48 R#48\n19 S 95 S#95\n20 T 7 T#7"
},
{
"code": null,
"e": 2409,
"s": 2343,
"text": "> df$Combined_with_hyphen<-paste(df$ID,df$Frequency,sep=\"-\")\n> df"
},
{
"code": null,
"e": 3355,
"s": 2409,
"text": " ID Frequency Combined_with_hash Combined_with_hyphen\n1 A 78 A#78 A-78\n2 B 84 B#84 B-84\n3 C 83 C#83 C-83\n4 D 47 D#47 D-47\n5 E 25 E#25 E-25\n6 F 59 F#59 F-59\n7 G 69 G#69 G-69\n8 H 35 H#35 H-35\n9 I 72 I#72 I-72\n10 J 26 J#26 J-26\n11 K 49 K#49 K-49\n12 L 45 L#45 L-45\n13 M 74 M#74 M-74\n14 N 8 N#8 N-8\n15 O 100 O#100 O-100\n16 P 96 P#96 P-96\n17 Q 24 Q#24 Q-24\n18 R 48 R#48 R-48\n19 S 95 S#95 S-95\n20 T 7 T#7 T-7"
},
{
"code": null,
"e": 3420,
"s": 3355,
"text": "> df$Combined_with_slash<-paste(df$ID,df$Frequency,sep=\"/\")\n> df"
},
{
"code": null,
"e": 4779,
"s": 3420,
"text": " ID Frequency Combined_with_hash Combined_with_hyphen Combined_with_slash\n1 A 78 A#78 A-78 A/78\n2 B 84 B#84 B-84 B/84\n3 C 83 C#83 C-83 C/83\n4 D 47 D#47 D-47 D/47\n5 E 25 E#25 E-25 E/25\n6 F 59 F#59 F-59 F/59\n7 G 69 G#69 G-69 G/69\n8 H 35 H#35 H-35 H/35\n9 I 72 I#72 I-72 I/72\n10 J 26 J#26 J-26 J/26\n11 K 49 K#49 K-49 K/49\n12 L 45 L#45 L-45 L/45\n13 M 74 M#74 M-74 M/74 \n14 N 8 N#8 N-8 N/8\n15 O 100 O#100 O-100 O/100\n16 P 96 P#96 P-96 P/96\n17 Q 24 Q#24 Q-24 Q/24\n18 R 48 R#48 R-48 R/48\n19 S 95 S#95 S-95 S/95\n20 T 7 T#7 T-7 T/7"
}
] |
jQuery replaceWith() with Examples
|
The replaceWith() method in jQuery is used to replace selected elements with new content.
The syntax is as follows −
$(selector).replaceWith(content,function(index))
Above, the content parameter is the content to insert, whereas function is to return the content to replace.
Let us now see an example to implement the jQuery replaceWith() method −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h2").replaceWith("<h2>This is it!</h2>");
});
});
</script>
</head>
<style>
div {
margin: 10px;
width: 60%;
border: 2px dashed orange;
padding: 5px;
text-align:justify;
}
</style>
<body>
<div>
<h2>Demo Heading</h2>
<h2>Demo Heading</h2>
<h2>Demo Heading</h2>
<h2>Demo Heading</h2>
</div>
<p>Click the below button to update headings</p>
<button>Click</button>
</body>
</html>
This will produce the following output −
Now, click the button to update headings −
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "The replaceWith() method in jQuery is used to replace selected elements with new content."
},
{
"code": null,
"e": 1179,
"s": 1152,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1228,
"s": 1179,
"text": "$(selector).replaceWith(content,function(index))"
},
{
"code": null,
"e": 1337,
"s": 1228,
"text": "Above, the content parameter is the content to insert, whereas function is to return the content to replace."
},
{
"code": null,
"e": 1410,
"s": 1337,
"text": "Let us now see an example to implement the jQuery replaceWith() method −"
},
{
"code": null,
"e": 1421,
"s": 1410,
"text": " Live Demo"
},
{
"code": null,
"e": 2030,
"s": 1421,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>\n<script>\n $(document).ready(function(){\n $(\"button\").click(function(){\n $(\"h2\").replaceWith(\"<h2>This is it!</h2>\");\n });\n });\n</script>\n</head>\n<style>\ndiv {\n margin: 10px;\n width: 60%;\n border: 2px dashed orange;\n padding: 5px;\n text-align:justify;\n}\n</style>\n<body>\n<div>\n<h2>Demo Heading</h2>\n<h2>Demo Heading</h2>\n<h2>Demo Heading</h2>\n<h2>Demo Heading</h2>\n</div>\n<p>Click the below button to update headings</p>\n<button>Click</button>\n</body>\n</html>"
},
{
"code": null,
"e": 2071,
"s": 2030,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2114,
"s": 2071,
"text": "Now, click the button to update headings −"
}
] |
Cycle Sort - GeeksforGeeks
|
25 Mar, 2021
Cycle sort is an in-place sorting Algorithm, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array.
It is optimal in terms of number of memory writes. It minimizes the number of memory writes to sort (Each value is either written zero times, if it’s already in its correct position, or written one time to its correct position.)
It is based on the idea that array to be sorted can be divided into cycles. Cycles can be visualized as a graph. We have n nodes and an edge directed from node i to node j if the element at i-th index must be present at j-th index in the sorted array. Cycle in arr[] = {2, 4, 5, 1, 3}
Cycle in arr[] = {4, 3, 2, 1}
We one by one consider all cycles. We first consider the cycle that includes first element. We find correct position of first element, place it at its correct position, say j. We consider old value of arr[j] and find its correct position, we keep doing this till all elements of current cycle are placed at correct position, i.e., we don’t come back to cycle starting point.
Explanation :
arr[] = {10, 5, 2, 3}
index = 0 1 2 3
cycle_start = 0
item = 10 = arr[0]
Find position where we put the item
pos = cycle_start
i=pos+1
while(i<n)
if (arr[i] < item)
pos++;
We put 10 at arr[3] and change item to
old value of arr[3].
arr[] = {10, 5, 2, 10}
item = 3
Again rotate rest cycle that start with index '0'
Find position where we put the item = 3
we swap item with element at arr[1] now
arr[] = {10, 3, 2, 10}
item = 5
Again rotate rest cycle that start with index '0' and item = 5
we swap item with element at arr[2].
arr[] = {10, 3, 5, 10 }
item = 2
Again rotate rest cycle that start with index '0' and item = 2
arr[] = {2, 3, 5, 10}
Above is one iteration for cycle_stat = 0.
Repeat above steps for cycle_start = 1, 2, ..n-2
CPP
Java
Python3
C#
Javascript
// C++ program to implement cycle sort#include <iostream>using namespace std; // Function sort the array using Cycle sortvoid cycleSort(int arr[], int n){ // count number of memory writes int writes = 0; // traverse array elements and put it to on // the right place for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { // initialize item as starting point int item = arr[cycle_start]; // Find position where we put the item. We basically // count all smaller elements on right side of item. int pos = cycle_start; for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (pos != cycle_start) { swap(item, arr[pos]); writes++; } // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (item != arr[pos]) { swap(item, arr[pos]); writes++; } } } // Number of memory writes or swaps // cout << writes << endl ;} // Driver program to test above functionint main(){ int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cycleSort(arr, n); cout << "After sort : " << endl; for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;}
// Java program to implement cycle sort import java.util.*;import java.lang.*; class GFG { // Function sort the array using Cycle sort public static void cycleSort(int arr[], int n) { // count number of memory writes int writes = 0; // traverse array elements and put it to on // the right place for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { // initialize item as starting point int item = arr[cycle_start]; // Find position where we put the item. We basically // count all smaller elements on right side of item. int pos = cycle_start; for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (pos != cycle_start) { int temp = item; item = arr[pos]; arr[pos] = temp; writes++; } // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (item != arr[pos]) { int temp = item; item = arr[pos]; arr[pos] = temp; writes++; } } } } // Driver program to test above function public static void main(String[] args) { int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; int n = arr.length; cycleSort(arr, n); System.out.println("After sort : "); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }} // Code Contributed by Mohit Gupta_OMG <(0_o)>
# Python program to implement cycle sort def cycleSort(array): writes = 0 # Loop through the array to find cycles to rotate. for cycleStart in range(0, len(array) - 1): item = array[cycleStart] # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # If the item is already there, this is not a cycle. if pos == cycleStart: continue # Otherwise, put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] writes += 1 # Rotate the rest of the cycle. while pos != cycleStart: # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # Put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] writes += 1 return writes # driver codearr = [1, 8, 3, 9, 10, 10, 2, 4 ]n = len(arr)cycleSort(arr) print("After sort : ")for i in range(0, n) : print(arr[i], end = ' ') # Code Contributed by Mohit Gupta_OMG <(0_o)>
// C# program to implement cycle sortusing System; class GFG { // Function sort the array using Cycle sort public static void cycleSort(int[] arr, int n) { // count number of memory writes int writes = 0; // traverse array elements and // put it to on the right place for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { // initialize item as starting point int item = arr[cycle_start]; // Find position where we put the item. // We basically count all smaller elements // on right side of item. int pos = cycle_start; for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (pos != cycle_start) { int temp = item; item = arr[pos]; arr[pos] = temp; writes++; } // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (item != arr[pos]) { int temp = item; item = arr[pos]; arr[pos] = temp; writes++; } } } } // Driver program to test above function public static void Main() { int[] arr = { 1, 8, 3, 9, 10, 10, 2, 4 }; int n = arr.Length; // Function calling cycleSort(arr, n); Console.Write("After sort : "); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This code is contributed by Nitin Mittal
<script>// Javascript program to implement cycle sort // Function sort the array using Cycle sort function cycleSort(arr, n) { // count number of memory writes let writes = 0; // traverse array elements and put it to on // the right place for (let cycle_start = 0; cycle_start <= n - 2; cycle_start++) { // initialize item as starting point let item = arr[cycle_start]; // Find position where we put the item. We basically // count all smaller elements on right side of item. let pos = cycle_start; for (let i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (pos != cycle_start) { let temp = item; item = arr[pos]; arr[pos] = temp; writes++; } // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (let i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (item != arr[pos]) { let temp = item; item = arr[pos]; arr[pos] = temp; writes++; } } } } // Driver code let arr = [ 1, 8, 3, 9, 10, 10, 2, 4 ]; let n = arr.length; cycleSort(arr, n); document.write("After sort : " + "<br/>"); for (let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by susmitakundugoaldanga.</script>
Output:
After sort :
1 2 3 4 8 9 10 10
Time Complexity : O(n2) Worst Case : O(n2) Average Case: O(n2) Best Case : O(n2)This sorting algorithm is best suited for situations where memory write or swap operations are costly.
YouTubeGeeksforGeeks500K subscribersCycle Sort | 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 / 2:27•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=gZNOM_yMdSQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Reference: https://en.wikipedia.org/wiki/Cycle_sortThis article is contributed by Nishant Singh. 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.
nitin mittal
rahul sholapurkar
pedastrian
susmitakundugoaldanga
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Time Complexities of all Sorting Algorithms
Radix Sort
Merge two sorted arrays
Sort an array of 0s, 1s and 2s
Count Inversions in an array | Set 1 (Using Merge Sort)
k largest(or smallest) elements in an array
sort() in Python
Merge Sort for Linked Lists
Python List sort() method
Python Program for QuickSort
|
[
{
"code": null,
"e": 23465,
"s": 23437,
"text": "\n25 Mar, 2021"
},
{
"code": null,
"e": 23650,
"s": 23465,
"text": "Cycle sort is an in-place sorting Algorithm, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array. "
},
{
"code": null,
"e": 23879,
"s": 23650,
"text": "It is optimal in terms of number of memory writes. It minimizes the number of memory writes to sort (Each value is either written zero times, if it’s already in its correct position, or written one time to its correct position.)"
},
{
"code": null,
"e": 24166,
"s": 23879,
"text": "It is based on the idea that array to be sorted can be divided into cycles. Cycles can be visualized as a graph. We have n nodes and an edge directed from node i to node j if the element at i-th index must be present at j-th index in the sorted array. Cycle in arr[] = {2, 4, 5, 1, 3} "
},
{
"code": null,
"e": 24198,
"s": 24166,
"text": "Cycle in arr[] = {4, 3, 2, 1} "
},
{
"code": null,
"e": 24576,
"s": 24200,
"text": "We one by one consider all cycles. We first consider the cycle that includes first element. We find correct position of first element, place it at its correct position, say j. We consider old value of arr[j] and find its correct position, we keep doing this till all elements of current cycle are placed at correct position, i.e., we don’t come back to cycle starting point. "
},
{
"code": null,
"e": 24592,
"s": 24576,
"text": "Explanation : "
},
{
"code": null,
"e": 25364,
"s": 24592,
"text": " arr[] = {10, 5, 2, 3}\n index = 0 1 2 3\ncycle_start = 0 \nitem = 10 = arr[0]\n\nFind position where we put the item \npos = cycle_start\ni=pos+1\nwhile(i<n)\nif (arr[i] < item) \n pos++;\n\nWe put 10 at arr[3] and change item to \nold value of arr[3].\narr[] = {10, 5, 2, 10} \nitem = 3 \n\nAgain rotate rest cycle that start with index '0' \nFind position where we put the item = 3 \nwe swap item with element at arr[1] now \narr[] = {10, 3, 2, 10} \nitem = 5\n\nAgain rotate rest cycle that start with index '0' and item = 5 \nwe swap item with element at arr[2].\narr[] = {10, 3, 5, 10 } \nitem = 2\n\nAgain rotate rest cycle that start with index '0' and item = 2\narr[] = {2, 3, 5, 10} \n\nAbove is one iteration for cycle_stat = 0.\nRepeat above steps for cycle_start = 1, 2, ..n-2"
},
{
"code": null,
"e": 25370,
"s": 25366,
"text": "CPP"
},
{
"code": null,
"e": 25375,
"s": 25370,
"text": "Java"
},
{
"code": null,
"e": 25383,
"s": 25375,
"text": "Python3"
},
{
"code": null,
"e": 25386,
"s": 25383,
"text": "C#"
},
{
"code": null,
"e": 25397,
"s": 25386,
"text": "Javascript"
},
{
"code": "// C++ program to implement cycle sort#include <iostream>using namespace std; // Function sort the array using Cycle sortvoid cycleSort(int arr[], int n){ // count number of memory writes int writes = 0; // traverse array elements and put it to on // the right place for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { // initialize item as starting point int item = arr[cycle_start]; // Find position where we put the item. We basically // count all smaller elements on right side of item. int pos = cycle_start; for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (pos != cycle_start) { swap(item, arr[pos]); writes++; } // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (item != arr[pos]) { swap(item, arr[pos]); writes++; } } } // Number of memory writes or swaps // cout << writes << endl ;} // Driver program to test above functionint main(){ int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cycleSort(arr, n); cout << \"After sort : \" << endl; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}",
"e": 27315,
"s": 25397,
"text": null
},
{
"code": "// Java program to implement cycle sort import java.util.*;import java.lang.*; class GFG { // Function sort the array using Cycle sort public static void cycleSort(int arr[], int n) { // count number of memory writes int writes = 0; // traverse array elements and put it to on // the right place for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { // initialize item as starting point int item = arr[cycle_start]; // Find position where we put the item. We basically // count all smaller elements on right side of item. int pos = cycle_start; for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (pos != cycle_start) { int temp = item; item = arr[pos]; arr[pos] = temp; writes++; } // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (item != arr[pos]) { int temp = item; item = arr[pos]; arr[pos] = temp; writes++; } } } } // Driver program to test above function public static void main(String[] args) { int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; int n = arr.length; cycleSort(arr, n); System.out.println(\"After sort : \"); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }} // Code Contributed by Mohit Gupta_OMG <(0_o)>",
"e": 29590,
"s": 27315,
"text": null
},
{
"code": "# Python program to implement cycle sort def cycleSort(array): writes = 0 # Loop through the array to find cycles to rotate. for cycleStart in range(0, len(array) - 1): item = array[cycleStart] # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # If the item is already there, this is not a cycle. if pos == cycleStart: continue # Otherwise, put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] writes += 1 # Rotate the rest of the cycle. while pos != cycleStart: # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # Put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] writes += 1 return writes # driver codearr = [1, 8, 3, 9, 10, 10, 2, 4 ]n = len(arr)cycleSort(arr) print(\"After sort : \")for i in range(0, n) : print(arr[i], end = ' ') # Code Contributed by Mohit Gupta_OMG <(0_o)>",
"e": 30814,
"s": 29590,
"text": null
},
{
"code": "// C# program to implement cycle sortusing System; class GFG { // Function sort the array using Cycle sort public static void cycleSort(int[] arr, int n) { // count number of memory writes int writes = 0; // traverse array elements and // put it to on the right place for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { // initialize item as starting point int item = arr[cycle_start]; // Find position where we put the item. // We basically count all smaller elements // on right side of item. int pos = cycle_start; for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (pos != cycle_start) { int temp = item; item = arr[pos]; arr[pos] = temp; writes++; } // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (int i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (item != arr[pos]) { int temp = item; item = arr[pos]; arr[pos] = temp; writes++; } } } } // Driver program to test above function public static void Main() { int[] arr = { 1, 8, 3, 9, 10, 10, 2, 4 }; int n = arr.Length; // Function calling cycleSort(arr, n); Console.Write(\"After sort : \"); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by Nitin Mittal",
"e": 33099,
"s": 30814,
"text": null
},
{
"code": "<script>// Javascript program to implement cycle sort // Function sort the array using Cycle sort function cycleSort(arr, n) { // count number of memory writes let writes = 0; // traverse array elements and put it to on // the right place for (let cycle_start = 0; cycle_start <= n - 2; cycle_start++) { // initialize item as starting point let item = arr[cycle_start]; // Find position where we put the item. We basically // count all smaller elements on right side of item. let pos = cycle_start; for (let i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (pos != cycle_start) { let temp = item; item = arr[pos]; arr[pos] = temp; writes++; } // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (let i = cycle_start + 1; i < n; i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it's right position if (item != arr[pos]) { let temp = item; item = arr[pos]; arr[pos] = temp; writes++; } } } } // Driver code let arr = [ 1, 8, 3, 9, 10, 10, 2, 4 ]; let n = arr.length; cycleSort(arr, n); document.write(\"After sort : \" + \"<br/>\"); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by susmitakundugoaldanga.</script>",
"e": 35318,
"s": 33099,
"text": null
},
{
"code": null,
"e": 35328,
"s": 35318,
"text": "Output: "
},
{
"code": null,
"e": 35361,
"s": 35328,
"text": "After sort : \n1 2 3 4 8 9 10 10 "
},
{
"code": null,
"e": 35546,
"s": 35361,
"text": "Time Complexity : O(n2) Worst Case : O(n2) Average Case: O(n2) Best Case : O(n2)This sorting algorithm is best suited for situations where memory write or swap operations are costly. "
},
{
"code": null,
"e": 36355,
"s": 35546,
"text": "YouTubeGeeksforGeeks500K subscribersCycle Sort | 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 / 2:27•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=gZNOM_yMdSQ\" 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": 36832,
"s": 36355,
"text": "Reference: https://en.wikipedia.org/wiki/Cycle_sortThis article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36845,
"s": 36832,
"text": "nitin mittal"
},
{
"code": null,
"e": 36863,
"s": 36845,
"text": "rahul sholapurkar"
},
{
"code": null,
"e": 36874,
"s": 36863,
"text": "pedastrian"
},
{
"code": null,
"e": 36896,
"s": 36874,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 36904,
"s": 36896,
"text": "Sorting"
},
{
"code": null,
"e": 36912,
"s": 36904,
"text": "Sorting"
},
{
"code": null,
"e": 37010,
"s": 36912,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37019,
"s": 37010,
"text": "Comments"
},
{
"code": null,
"e": 37032,
"s": 37019,
"text": "Old Comments"
},
{
"code": null,
"e": 37076,
"s": 37032,
"text": "Time Complexities of all Sorting Algorithms"
},
{
"code": null,
"e": 37087,
"s": 37076,
"text": "Radix Sort"
},
{
"code": null,
"e": 37111,
"s": 37087,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 37142,
"s": 37111,
"text": "Sort an array of 0s, 1s and 2s"
},
{
"code": null,
"e": 37198,
"s": 37142,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 37242,
"s": 37198,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 37259,
"s": 37242,
"text": "sort() in Python"
},
{
"code": null,
"e": 37287,
"s": 37259,
"text": "Merge Sort for Linked Lists"
},
{
"code": null,
"e": 37313,
"s": 37287,
"text": "Python List sort() method"
}
] |
Count maximum possible pairs from an array having sum K - GeeksforGeeks
|
17 Nov, 2021
Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum number of pairs having a sum K possible from the given array.
Note: Every array element can be part of a single pair.
Examples:
Input: arr[] = {1, 2, 3, 4}, K = 5Output: 2Explanation: Pairs with sum K from the array are (1, 4), and (2, 3).
Input: arr[] = {3, 1, 3, 4, 3}, K = 6Output: 1Explanation: Pair with sum K from the array is (3, 3).
Two-Pointer Approach: The idea is to use the Two Pointer Technique. Follow the steps below to solve the problem:
Initialize the variable ans as 0 to store the maximum number of pairs with the sum K.
Sort the array arr[] in increasing order.
Initialize two index variables L as 0 and R as (N – 1) to find the candidate elements in the sorted array.
Iterate until L is less than R and do the following:Check if the sum of arr[L] and arr[R] is K or not. If found to be true, then increment ans and L by 1 and decrement R by 1.If the sum of arr[L] and arr[R] is less than K, then increment L by 1.Otherwise, decrement R by 1.
Check if the sum of arr[L] and arr[R] is K or not. If found to be true, then increment ans and L by 1 and decrement R by 1.
If the sum of arr[L] and arr[R] is less than K, then increment L by 1.
Otherwise, decrement R by 1.
After the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the maximum number// of pairs from given array with sum Kvoid maxPairs(int nums[], int n, int k){ // Sort array in increasing order sort(nums, nums + n); // Stores the final result int result = 0; // Initialize the left and right pointers int start = 0, end = n - 1; // Traverse array until start < end while (start < end) { if (nums[start] + nums[end] > k) // Decrement right by 1 end--; else if (nums[start] + nums[end] < k) // Increment left by 1 start++; // Increment result and left // pointer by 1 and decrement // right pointer by 1 else { start++; end--; result++; } } // Print the result cout << result << endl;;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr)/sizeof(arr[0]); int K = 5; // Function Call maxPairs(arr, n, K); return 0;} // This code is contributed by AnkThon
// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to count the maximum number // of pairs from given array with sum K public static void maxPairs(int[] nums, int k) { // Sort array in increasing order Arrays.sort(nums); // Stores the final result int result = 0; // Initialize the left and right pointers int start = 0, end = nums.length - 1; // Traverse array until start < end while (start < end) { if (nums[start] + nums[end] > k) // Decrement right by 1 end--; else if (nums[start] + nums[end] < k) // Increment left by 1 start++; // Increment result and left // pointer by 1 and decrement // right pointer by 1 else { start++; end--; result++; } } // Print the result System.out.println(result); } // Driver Code public static void main(String[] args) { int[] arr = { 1, 2, 3, 4 }; int K = 5; // Function Call maxPairs(arr, K); }}
# Python3 program for the above approach # Function to count the maximum number# of pairs from given array with sum Kdef maxPairs(nums, k): # Sort array in increasing order nums = sorted(nums) # Stores the final result result = 0 # Initialize the left and right pointers start, end = 0, len(nums) - 1 # Traverse array until start < end while (start < end): if (nums[start] + nums[end] > k): # Decrement right by 1 end -= 1 elif (nums[start] + nums[end] < k): # Increment left by 1 start += 1 # Increment result and left # pointer by 1 and decrement # right pointer by 1 else: start += 1 end -= 1 result += 1 # Print the result print(result) # Driver Codeif __name__ == '__main__': arr = [ 1, 2, 3, 4 ] K = 5 # Function Call maxPairs(arr, K) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System; class GFG{ // Function to count the maximum number // of pairs from given array with sum K public static void maxPairs(int[] nums, int k) { // Sort array in increasing order Array.Sort(nums); // Stores the final result int result = 0; // Initialize the left and right pointers int start = 0, end = nums.Length - 1; // Traverse array until start < end while (start < end) { if (nums[start] + nums[end] > k) // Decrement right by 1 end--; else if (nums[start] + nums[end] < k) // Increment left by 1 start++; // Increment result and left // pointer by 1 and decrement // right pointer by 1 else { start++; end--; result++; } } // Print the result Console.Write(result); } // Driver Code public static void Main(){ int[] arr = { 1, 2, 3, 4 }; int K = 5; // Function Call maxPairs(arr, K);}} // This code is contributed by susmitakundugoaldanga
<script> // JavaScript program for above approach // Function to count the maximum number // of pairs from given array with sum K function maxPairs(nums, k) { // Sort array in increasing order nums.sort(); // Stores the final result let result = 0; // Initialize the left and right pointers let start = 0, end = nums.length - 1; // Traverse array until start < end while (start < end) { if (nums[start] + nums[end] > k) // Decrement right by 1 end--; else if (nums[start] + nums[end] < k) // Increment left by 1 start++; // Increment result and left // pointer by 1 and decrement // right pointer by 1 else { start++; end--; result++; } } // Print the result document.write(result); } // Driver Code let arr = [ 1, 2, 3, 4 ]; let K = 5; // Function Call maxPairs(arr, K); </script>
Output:
2
Time Complexity: O(N*log N)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use hashing. Follow the steps below to solve the problem:
Initialize a variable, say ans, to store the maximum number of pairs with the sum K.
Initialize a hash table, say S, to store the frequency of elements in arr[].
Traverse the array arr[] using a variable, say i, and perform the following steps:If the frequency of (K – arr[i]) is positive, then increment ans by 1 and decrement the frequency of (K – arr[i]) by 1.Otherwise, insert arr[i] with frequency 1 in the Hash Table.
If the frequency of (K – arr[i]) is positive, then increment ans by 1 and decrement the frequency of (K – arr[i]) by 1.
Otherwise, insert arr[i] with frequency 1 in the Hash Table.
After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>#include <string.h>using namespace std; // Function to find the maximum number// of pairs with a sum K such that// same element can't be used twicevoid maxPairs(vector<int> nums, int k){ // Initialize a hashm map<int, int> m; // Store the final result int result = 0; // Iterate over the array nums[] for(auto i : nums) { // Decrement its frequency // in m and increment // the result by 1 if (m.find(i) != m.end() && m[i] > 0) { m[i] = m[i] - 1; result++; } // Increment its frequency by 1 // if it is already present in m. // Otherwise, set its frequency to 1 else { m[k - i] = m[k - i] + 1; } } // Print the result cout << result;} // Driver Codeint main(){ vector<int> arr = { 1, 2, 3, 4 }; int K = 5; // Function Call maxPairs(arr, K);} // This code is contributed by grand_master
// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to find the maximum number // of pairs with a sum K such that // same element can't be used twice public static void maxPairs( int[] nums, int k) { // Initialize a hashmap Map<Integer, Integer> map = new HashMap<>(); // Store the final result int result = 0; // Iterate over the array nums[] for (int i : nums) { // Decrement its frequency // in map and increment // the result by 1 if (map.containsKey(i) && map.get(i) > 0) { map.put(i, map.get(i) - 1); result++; } // Increment its frequency by 1 // if it is already present in map. // Otherwise, set its frequency to 1 else { map.put(k - i, map.getOrDefault(k - i, 0) + 1); } } // Print the result System.out.println(result); } // Driver Code public static void main(String[] args) { int[] arr = { 1, 2, 3, 4 }; int K = 5; // Function Call maxPairs(arr, K); }}
# Python3 program for the above approach # Function to find the maximum number# of pairs with a sum K such that# same element can't be used twicedef maxPairs(nums, k) : # Initialize a hashm m = {} # Store the final result result = 0 # Iterate over the array nums[] for i in nums : # Decrement its frequency # in m and increment # the result by 1 if ((i in m) and m[i] > 0) : m[i] = m[i] - 1 result += 1 # Increment its frequency by 1 # if it is already present in m. # Otherwise, set its frequency to 1 else : if k - i in m : m[k - i] += 1 else : m[k - i] = 1 # Print the result print(result) # Driver code arr = [ 1, 2, 3, 4 ]K = 5 # Function CallmaxPairs(arr, K) # This code is contributed by divyesh072019
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the maximum number // of pairs with a sum K such that // same element can't be used twice public static void maxPairs( int[] nums, int k) { // Initialize a hashmap Dictionary<int, int> map = new Dictionary<int, int>(); // Store the readonly result int result = 0; // Iterate over the array nums[] foreach (int i in nums) { // Decrement its frequency // in map and increment // the result by 1 if (map.ContainsKey(i) && map[i] > 0) { map[i] = map[i] - 1; result++; } // Increment its frequency by 1 // if it is already present in map. // Otherwise, set its frequency to 1 else { if (!map.ContainsKey(k - i)) map.Add(k - i, 1); else map[i] = map[i] + 1; } } // Print the result Console.WriteLine(result); } // Driver Code public static void Main(String[] args) { int[] arr = {1, 2, 3, 4}; int K = 5; // Function Call maxPairs(arr, K); }} // This code is contributed by 29AjayKumar
<script> // Javascript program for the above approach // Function to find the maximum number// of pairs with a sum K such that// same element can't be used twicefunction maxPairs(nums, k){ // Initialize a hashm var m = new Map(); // Store the final result var result = 0; // Iterate over the array nums[] nums.forEach(i => { // Decrement its frequency // in m and increment // the result by 1 if (m.has(i) && m.get(i) > 0) { m.set(i, m.get(i)-1); result++; } // Increment its frequency by 1 // if it is already present in m. // Otherwise, set its frequency to 1 else { if(m.has(k-i)) m.set(k-i, m.get(k-i)+1) else m.set(k-i, 1) } }); // Print the result document.write( result);} // Driver Codevar arr = [1, 2, 3, 4];var K = 5;// Function CallmaxPairs(arr, K); </script>
2
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
susmitakundugoaldanga
ankthon
29AjayKumar
grand_master
divyesh072019
chinmoy1997pal
importantly
surinderdawra388
HashTable
two-pointer-algorithm
Arrays
Hash
Searching
Sorting
two-pointer-algorithm
Arrays
Searching
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Building Heap from Array
Reversal algorithm for array rotation
Program to find sum of elements in a given array
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
Hashing | Set 2 (Separate Chaining)
|
[
{
"code": null,
"e": 24796,
"s": 24768,
"text": "\n17 Nov, 2021"
},
{
"code": null,
"e": 24955,
"s": 24796,
"text": "Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum number of pairs having a sum K possible from the given array. "
},
{
"code": null,
"e": 25011,
"s": 24955,
"text": "Note: Every array element can be part of a single pair."
},
{
"code": null,
"e": 25021,
"s": 25011,
"text": "Examples:"
},
{
"code": null,
"e": 25133,
"s": 25021,
"text": "Input: arr[] = {1, 2, 3, 4}, K = 5Output: 2Explanation: Pairs with sum K from the array are (1, 4), and (2, 3)."
},
{
"code": null,
"e": 25234,
"s": 25133,
"text": "Input: arr[] = {3, 1, 3, 4, 3}, K = 6Output: 1Explanation: Pair with sum K from the array is (3, 3)."
},
{
"code": null,
"e": 25347,
"s": 25234,
"text": "Two-Pointer Approach: The idea is to use the Two Pointer Technique. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25433,
"s": 25347,
"text": "Initialize the variable ans as 0 to store the maximum number of pairs with the sum K."
},
{
"code": null,
"e": 25475,
"s": 25433,
"text": "Sort the array arr[] in increasing order."
},
{
"code": null,
"e": 25582,
"s": 25475,
"text": "Initialize two index variables L as 0 and R as (N – 1) to find the candidate elements in the sorted array."
},
{
"code": null,
"e": 25856,
"s": 25582,
"text": "Iterate until L is less than R and do the following:Check if the sum of arr[L] and arr[R] is K or not. If found to be true, then increment ans and L by 1 and decrement R by 1.If the sum of arr[L] and arr[R] is less than K, then increment L by 1.Otherwise, decrement R by 1."
},
{
"code": null,
"e": 25980,
"s": 25856,
"text": "Check if the sum of arr[L] and arr[R] is K or not. If found to be true, then increment ans and L by 1 and decrement R by 1."
},
{
"code": null,
"e": 26051,
"s": 25980,
"text": "If the sum of arr[L] and arr[R] is less than K, then increment L by 1."
},
{
"code": null,
"e": 26080,
"s": 26051,
"text": "Otherwise, decrement R by 1."
},
{
"code": null,
"e": 26141,
"s": 26080,
"text": "After the above steps, print the value of ans as the result."
},
{
"code": null,
"e": 26192,
"s": 26141,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26196,
"s": 26192,
"text": "C++"
},
{
"code": null,
"e": 26201,
"s": 26196,
"text": "Java"
},
{
"code": null,
"e": 26209,
"s": 26201,
"text": "Python3"
},
{
"code": null,
"e": 26212,
"s": 26209,
"text": "C#"
},
{
"code": null,
"e": 26223,
"s": 26212,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the maximum number// of pairs from given array with sum Kvoid maxPairs(int nums[], int n, int k){ // Sort array in increasing order sort(nums, nums + n); // Stores the final result int result = 0; // Initialize the left and right pointers int start = 0, end = n - 1; // Traverse array until start < end while (start < end) { if (nums[start] + nums[end] > k) // Decrement right by 1 end--; else if (nums[start] + nums[end] < k) // Increment left by 1 start++; // Increment result and left // pointer by 1 and decrement // right pointer by 1 else { start++; end--; result++; } } // Print the result cout << result << endl;;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr)/sizeof(arr[0]); int K = 5; // Function Call maxPairs(arr, n, K); return 0;} // This code is contributed by AnkThon",
"e": 27226,
"s": 26223,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to count the maximum number // of pairs from given array with sum K public static void maxPairs(int[] nums, int k) { // Sort array in increasing order Arrays.sort(nums); // Stores the final result int result = 0; // Initialize the left and right pointers int start = 0, end = nums.length - 1; // Traverse array until start < end while (start < end) { if (nums[start] + nums[end] > k) // Decrement right by 1 end--; else if (nums[start] + nums[end] < k) // Increment left by 1 start++; // Increment result and left // pointer by 1 and decrement // right pointer by 1 else { start++; end--; result++; } } // Print the result System.out.println(result); } // Driver Code public static void main(String[] args) { int[] arr = { 1, 2, 3, 4 }; int K = 5; // Function Call maxPairs(arr, K); }}",
"e": 28437,
"s": 27226,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to count the maximum number# of pairs from given array with sum Kdef maxPairs(nums, k): # Sort array in increasing order nums = sorted(nums) # Stores the final result result = 0 # Initialize the left and right pointers start, end = 0, len(nums) - 1 # Traverse array until start < end while (start < end): if (nums[start] + nums[end] > k): # Decrement right by 1 end -= 1 elif (nums[start] + nums[end] < k): # Increment left by 1 start += 1 # Increment result and left # pointer by 1 and decrement # right pointer by 1 else: start += 1 end -= 1 result += 1 # Print the result print(result) # Driver Codeif __name__ == '__main__': arr = [ 1, 2, 3, 4 ] K = 5 # Function Call maxPairs(arr, K) # This code is contributed by mohit kumar 29",
"e": 29423,
"s": 28437,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to count the maximum number // of pairs from given array with sum K public static void maxPairs(int[] nums, int k) { // Sort array in increasing order Array.Sort(nums); // Stores the final result int result = 0; // Initialize the left and right pointers int start = 0, end = nums.Length - 1; // Traverse array until start < end while (start < end) { if (nums[start] + nums[end] > k) // Decrement right by 1 end--; else if (nums[start] + nums[end] < k) // Increment left by 1 start++; // Increment result and left // pointer by 1 and decrement // right pointer by 1 else { start++; end--; result++; } } // Print the result Console.Write(result); } // Driver Code public static void Main(){ int[] arr = { 1, 2, 3, 4 }; int K = 5; // Function Call maxPairs(arr, K);}} // This code is contributed by susmitakundugoaldanga",
"e": 30641,
"s": 29423,
"text": null
},
{
"code": "<script> // JavaScript program for above approach // Function to count the maximum number // of pairs from given array with sum K function maxPairs(nums, k) { // Sort array in increasing order nums.sort(); // Stores the final result let result = 0; // Initialize the left and right pointers let start = 0, end = nums.length - 1; // Traverse array until start < end while (start < end) { if (nums[start] + nums[end] > k) // Decrement right by 1 end--; else if (nums[start] + nums[end] < k) // Increment left by 1 start++; // Increment result and left // pointer by 1 and decrement // right pointer by 1 else { start++; end--; result++; } } // Print the result document.write(result); } // Driver Code let arr = [ 1, 2, 3, 4 ]; let K = 5; // Function Call maxPairs(arr, K); </script>",
"e": 31754,
"s": 30641,
"text": null
},
{
"code": null,
"e": 31762,
"s": 31754,
"text": "Output:"
},
{
"code": null,
"e": 31764,
"s": 31762,
"text": "2"
},
{
"code": null,
"e": 31813,
"s": 31764,
"text": "Time Complexity: O(N*log N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31938,
"s": 31813,
"text": "Efficient Approach: To optimize the above approach, the idea is to use hashing. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 32023,
"s": 31938,
"text": "Initialize a variable, say ans, to store the maximum number of pairs with the sum K."
},
{
"code": null,
"e": 32100,
"s": 32023,
"text": "Initialize a hash table, say S, to store the frequency of elements in arr[]."
},
{
"code": null,
"e": 32362,
"s": 32100,
"text": "Traverse the array arr[] using a variable, say i, and perform the following steps:If the frequency of (K – arr[i]) is positive, then increment ans by 1 and decrement the frequency of (K – arr[i]) by 1.Otherwise, insert arr[i] with frequency 1 in the Hash Table."
},
{
"code": null,
"e": 32482,
"s": 32362,
"text": "If the frequency of (K – arr[i]) is positive, then increment ans by 1 and decrement the frequency of (K – arr[i]) by 1."
},
{
"code": null,
"e": 32543,
"s": 32482,
"text": "Otherwise, insert arr[i] with frequency 1 in the Hash Table."
},
{
"code": null,
"e": 32615,
"s": 32543,
"text": "After completing the above steps, print the value of ans as the result."
},
{
"code": null,
"e": 32666,
"s": 32615,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 32670,
"s": 32666,
"text": "C++"
},
{
"code": null,
"e": 32675,
"s": 32670,
"text": "Java"
},
{
"code": null,
"e": 32683,
"s": 32675,
"text": "Python3"
},
{
"code": null,
"e": 32686,
"s": 32683,
"text": "C#"
},
{
"code": null,
"e": 32697,
"s": 32686,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>#include <string.h>using namespace std; // Function to find the maximum number// of pairs with a sum K such that// same element can't be used twicevoid maxPairs(vector<int> nums, int k){ // Initialize a hashm map<int, int> m; // Store the final result int result = 0; // Iterate over the array nums[] for(auto i : nums) { // Decrement its frequency // in m and increment // the result by 1 if (m.find(i) != m.end() && m[i] > 0) { m[i] = m[i] - 1; result++; } // Increment its frequency by 1 // if it is already present in m. // Otherwise, set its frequency to 1 else { m[k - i] = m[k - i] + 1; } } // Print the result cout << result;} // Driver Codeint main(){ vector<int> arr = { 1, 2, 3, 4 }; int K = 5; // Function Call maxPairs(arr, K);} // This code is contributed by grand_master",
"e": 33730,
"s": 32697,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to find the maximum number // of pairs with a sum K such that // same element can't be used twice public static void maxPairs( int[] nums, int k) { // Initialize a hashmap Map<Integer, Integer> map = new HashMap<>(); // Store the final result int result = 0; // Iterate over the array nums[] for (int i : nums) { // Decrement its frequency // in map and increment // the result by 1 if (map.containsKey(i) && map.get(i) > 0) { map.put(i, map.get(i) - 1); result++; } // Increment its frequency by 1 // if it is already present in map. // Otherwise, set its frequency to 1 else { map.put(k - i, map.getOrDefault(k - i, 0) + 1); } } // Print the result System.out.println(result); } // Driver Code public static void main(String[] args) { int[] arr = { 1, 2, 3, 4 }; int K = 5; // Function Call maxPairs(arr, K); }}",
"e": 35007,
"s": 33730,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the maximum number# of pairs with a sum K such that# same element can't be used twicedef maxPairs(nums, k) : # Initialize a hashm m = {} # Store the final result result = 0 # Iterate over the array nums[] for i in nums : # Decrement its frequency # in m and increment # the result by 1 if ((i in m) and m[i] > 0) : m[i] = m[i] - 1 result += 1 # Increment its frequency by 1 # if it is already present in m. # Otherwise, set its frequency to 1 else : if k - i in m : m[k - i] += 1 else : m[k - i] = 1 # Print the result print(result) # Driver code arr = [ 1, 2, 3, 4 ]K = 5 # Function CallmaxPairs(arr, K) # This code is contributed by divyesh072019",
"e": 35914,
"s": 35007,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the maximum number // of pairs with a sum K such that // same element can't be used twice public static void maxPairs( int[] nums, int k) { // Initialize a hashmap Dictionary<int, int> map = new Dictionary<int, int>(); // Store the readonly result int result = 0; // Iterate over the array nums[] foreach (int i in nums) { // Decrement its frequency // in map and increment // the result by 1 if (map.ContainsKey(i) && map[i] > 0) { map[i] = map[i] - 1; result++; } // Increment its frequency by 1 // if it is already present in map. // Otherwise, set its frequency to 1 else { if (!map.ContainsKey(k - i)) map.Add(k - i, 1); else map[i] = map[i] + 1; } } // Print the result Console.WriteLine(result); } // Driver Code public static void Main(String[] args) { int[] arr = {1, 2, 3, 4}; int K = 5; // Function Call maxPairs(arr, K); }} // This code is contributed by 29AjayKumar",
"e": 37299,
"s": 35914,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the maximum number// of pairs with a sum K such that// same element can't be used twicefunction maxPairs(nums, k){ // Initialize a hashm var m = new Map(); // Store the final result var result = 0; // Iterate over the array nums[] nums.forEach(i => { // Decrement its frequency // in m and increment // the result by 1 if (m.has(i) && m.get(i) > 0) { m.set(i, m.get(i)-1); result++; } // Increment its frequency by 1 // if it is already present in m. // Otherwise, set its frequency to 1 else { if(m.has(k-i)) m.set(k-i, m.get(k-i)+1) else m.set(k-i, 1) } }); // Print the result document.write( result);} // Driver Codevar arr = [1, 2, 3, 4];var K = 5;// Function CallmaxPairs(arr, K); </script>",
"e": 38290,
"s": 37299,
"text": null
},
{
"code": null,
"e": 38292,
"s": 38290,
"text": "2"
},
{
"code": null,
"e": 38337,
"s": 38294,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 38352,
"s": 38337,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 38374,
"s": 38352,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 38382,
"s": 38374,
"text": "ankthon"
},
{
"code": null,
"e": 38394,
"s": 38382,
"text": "29AjayKumar"
},
{
"code": null,
"e": 38407,
"s": 38394,
"text": "grand_master"
},
{
"code": null,
"e": 38421,
"s": 38407,
"text": "divyesh072019"
},
{
"code": null,
"e": 38436,
"s": 38421,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 38448,
"s": 38436,
"text": "importantly"
},
{
"code": null,
"e": 38465,
"s": 38448,
"text": "surinderdawra388"
},
{
"code": null,
"e": 38475,
"s": 38465,
"text": "HashTable"
},
{
"code": null,
"e": 38497,
"s": 38475,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 38504,
"s": 38497,
"text": "Arrays"
},
{
"code": null,
"e": 38509,
"s": 38504,
"text": "Hash"
},
{
"code": null,
"e": 38519,
"s": 38509,
"text": "Searching"
},
{
"code": null,
"e": 38527,
"s": 38519,
"text": "Sorting"
},
{
"code": null,
"e": 38549,
"s": 38527,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 38556,
"s": 38549,
"text": "Arrays"
},
{
"code": null,
"e": 38566,
"s": 38556,
"text": "Searching"
},
{
"code": null,
"e": 38571,
"s": 38566,
"text": "Hash"
},
{
"code": null,
"e": 38579,
"s": 38571,
"text": "Sorting"
},
{
"code": null,
"e": 38677,
"s": 38579,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38702,
"s": 38677,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 38722,
"s": 38702,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 38747,
"s": 38722,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 38785,
"s": 38747,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 38834,
"s": 38785,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 38870,
"s": 38834,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 38901,
"s": 38870,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 38935,
"s": 38901,
"text": "Hashing | Set 3 (Open Addressing)"
},
{
"code": null,
"e": 38962,
"s": 38935,
"text": "Count pairs with given sum"
}
] |
Transfer Learning using VGG Pre-trained model with Keras | Towards Data Science
|
Transfer learning is one of the state-of-the-art techniques in machine learning that has been widely used in image classification. In this article, I will discuss transfer learning, the VGG model, and feature extraction. In the last section, I will demonstrate an interesting example of transfer learning where the transfer learning technique displays unexpectedly poor performance in classifying the MNist digit dataset.
VGG is a convolutional neural network with a specific architecture that was proposed in the paper — Very Deep Convolutional Networks for Large-Scale Image Recognition by a group of researchers (visual geometry group) from the University of Oxford. The VGG group participated in an annual computer vision competition — ImageNet Large Scale Visual Recognition Challenge (ILSVRC) and submitted the famous VGG model for competing in object localization (detecting objects within an image coming from 200 classes)and image classification tasks (1000-class classification). The ImageNet dataset, a major computer vision benchmark dataset that was used in the competition, includes more than 14 million images belonging to 1000 classes. The VGG model outperformed other models with 92.7% top-5 test accuracy and won 1st and 2nd place in the 2014 ILSVRC competition.
VGG Architecture
The VGG has two different architectures: VGG-16 contains 16 layers and VGG-19 contains 19 layers. In this article, we focus on VGG-16 which mainly contains three different parts: convolution, pooling, and fully connected layers — it starts with two convolution layers followed by pooling, then another two convolutions followed by pooling, after that repetition of three convolutions followed by pooling, and then finally three fully connected layers. The following figure shows the architecture of the VGG-16 model. The most interesting part of the VGG model is that the model weights are available on different platforms (i.e. Keras) and can be used for further analysis — developing models and applications. The idea of utilizing models’ weights for further tasks initiates the idea of transfer learning.
We can run the following three lines of code to plot the VGG-16 model architecture in python:
from keras.applications.vgg16 import VGG16from keras.utils import plot_modelmodel = VGG16()plot_model(model)
Transfer Learning
We know that the training time increases exponentially with the neural network architecture increasing/deepening. In general, it could take hours/days to train a 3–5 layers neural network with a large-scale dataset. Consequently, deploying VGG from scratch on a large-scale dataset is a tiresome and computationally expensive task due to the depth and number of fully connected layers/nodes in the models’ architecture. Another challenge is that building VGG from scratch requires considerably large memory space and bandwidth since the size of ImageNet trained VGG-16 weights is 528 MB. However, instead of building a VGG from scratch, we can perform transfer learning i.e. — utilizing the knowledge like weights, and features of the previously trained (e.g. pre-trained VGG) models’ to solve a similar kind of problem. For instance, if we want to develop a binary image classifier, then we can use a pre-trained model that is trained on a large benchmark image dataset like VGG. Therefore, transfer learning is a machine learning method where a model developed for a task is reused as the starting point for a model on a second task. Transfer learning is generally used for speeding up the training time and eventually improving the performance of the models’. While leveraging transfer learning, we must consider that the benefits of using transfer learning are not obvious.
When to Use Transfer Learning?
You can read the article Significance Of Transfer Learning In The World Of Deep Learning that explains when to use transfer learning.
Machine learning algorithms especially deep neural networks may not able to learn properly when the training data is not enough. Transfer learning can play a significant role to solve this issue and adjust the model to suit the new task. There are a few factors we can look for while applying transfer learning [1]:
Higher start: The initial stage of the model with transfer learning should outperform the model without transfer learning.Higher slope: The performance slope or rate of improvement during the training phase of the source model is steeper than it otherwise would be.Higher asymptote: The pre-trained should be converged more smoothly.
Higher start: The initial stage of the model with transfer learning should outperform the model without transfer learning.
Higher slope: The performance slope or rate of improvement during the training phase of the source model is steeper than it otherwise would be.
Higher asymptote: The pre-trained should be converged more smoothly.
Why the VGG model for transfer learning?
Assuming the given number of training samples (images) are not sufficient enough for building a classifier, in that case, VGG can be easily leveraged for feature extraction as it is trained on millions of images. VGG was introduced in 2014 and still, it mysteriously produces better accuracy for some specific tasks compared to other classifiers through many state-of-the-art Image classifiers that came after 2014.
In this article, we will show one demonstration of transfer learning with the VGG model that shows that the transfer learning approach does not perform up to the mark. In the future post, we will demonstrate another example where models’ performance improved as expected for leveraging the transfer learning method.
In this demonstration, we use the famous MNIST digit dataset. We use a portion of the MNIST dataset that contains only digits 8 and 6. Altogether there are 8200 samples and 784 features for each of the samples. We extract features for the MNIST dataset using the VGG pre-trained weights.
Step 1 — Data Preparation
We upload the dataset into the Google Colab from the local hard drive and convert the labels to 1 and 0 from 8 and 6.
from google.colab import filesuploaded = files.upload()
Now, we read the dataset. The following figure shows that the labels are 8 & 6. As in the later section, we will apply logistic regression, we convert the labels into 1 and 0.
Running the one line of code will convert the labels:
data['label'] = np.where(data['label'] == 8, 1, 0)
Step 2 — Extracting Features from the VGG-16 Model
Before extracting features, just observe the summary of the VGG-16 model:
In the summary, the VGG-16 contains 16 layers where the number of features is 25,088 after flatten of the last convolutional layer (the 1st highlighted) and in the final layer (prediction or final dense layer), the number of nodes is 1000 as VGG-16 mainly trained for 1000-class classification problem (the 2nd highlighted).
For transfer learning purposes, we can extract 25088 features from the MNIST dataset using the VGG model. The red vertical line shows the cut for feature extraction.
The following code section will cut the VGG model after the final convolutional layer:
from keras import modelsbase_model = VGG16(weights='imagenet')model_VGG16 = models.Model(inputs=base_model.input, outputs=base_model.get_layer('flatten').output)
output:
After extracting features from the digit data using the VGG model, we trained a logistic regression binary classifier with the features and perform a 10-fold cross-validation. Simultaneously, we also apply logistic regression on the raw mnist digit data with 10-fold cross-validation to compare results with the performance of transfer learning.
The following two tables show the results of applying logistic regression to the raw data and extracted features from the raw data. Without transfer learning i.e. applying LR to the raw digit data achieves approximately 98% accuracy, while the model that leverages the transfer learning features achieves only 50% accuracy which is similar to a random guess for a binary classification problem. In general, we expect that with the transfer learning the model performance should be increased. However, in this demonstration, we experience that with transfer learning the model performance dramatically dropped.
The possible reasons that VGG16 does not perform well:
VGG-16 is trained for 3-channel RGB images while Mnist digit data is 1-channel grayscale
VGG-16 is trained for 3-channel RGB images while Mnist digit data is 1-channel grayscale
2. Background noises in the ImageNet data that were learned by the VGG-16 higher representational features
3. VGG-16 trained for 1000-class classification while for this task we used it for binary classification
Though the model with the transfer learning does not provide rewarding results in this experiment, utilizing other layers of the VGG for the feature extraction process or fine-tuning the parameters may produce better accuracy. To sum up, transfer learning is a state-of-the-art machine learning technique that can boost models’ performance. However, smartly utilizing the transfer learning technique is a requirement to gain the proper advantages.
Your membership fee will directly support and inspire Mohammad Masum and thousands of other writers you read. You’ll also get full access to every story on Medium — https://masum-math8065.medium.com/membership
|
[
{
"code": null,
"e": 593,
"s": 171,
"text": "Transfer learning is one of the state-of-the-art techniques in machine learning that has been widely used in image classification. In this article, I will discuss transfer learning, the VGG model, and feature extraction. In the last section, I will demonstrate an interesting example of transfer learning where the transfer learning technique displays unexpectedly poor performance in classifying the MNist digit dataset."
},
{
"code": null,
"e": 1452,
"s": 593,
"text": "VGG is a convolutional neural network with a specific architecture that was proposed in the paper — Very Deep Convolutional Networks for Large-Scale Image Recognition by a group of researchers (visual geometry group) from the University of Oxford. The VGG group participated in an annual computer vision competition — ImageNet Large Scale Visual Recognition Challenge (ILSVRC) and submitted the famous VGG model for competing in object localization (detecting objects within an image coming from 200 classes)and image classification tasks (1000-class classification). The ImageNet dataset, a major computer vision benchmark dataset that was used in the competition, includes more than 14 million images belonging to 1000 classes. The VGG model outperformed other models with 92.7% top-5 test accuracy and won 1st and 2nd place in the 2014 ILSVRC competition."
},
{
"code": null,
"e": 1469,
"s": 1452,
"text": "VGG Architecture"
},
{
"code": null,
"e": 2277,
"s": 1469,
"text": "The VGG has two different architectures: VGG-16 contains 16 layers and VGG-19 contains 19 layers. In this article, we focus on VGG-16 which mainly contains three different parts: convolution, pooling, and fully connected layers — it starts with two convolution layers followed by pooling, then another two convolutions followed by pooling, after that repetition of three convolutions followed by pooling, and then finally three fully connected layers. The following figure shows the architecture of the VGG-16 model. The most interesting part of the VGG model is that the model weights are available on different platforms (i.e. Keras) and can be used for further analysis — developing models and applications. The idea of utilizing models’ weights for further tasks initiates the idea of transfer learning."
},
{
"code": null,
"e": 2371,
"s": 2277,
"text": "We can run the following three lines of code to plot the VGG-16 model architecture in python:"
},
{
"code": null,
"e": 2481,
"s": 2371,
"text": "from keras.applications.vgg16 import VGG16from keras.utils import plot_modelmodel = VGG16()plot_model(model)"
},
{
"code": null,
"e": 2499,
"s": 2481,
"text": "Transfer Learning"
},
{
"code": null,
"e": 3877,
"s": 2499,
"text": "We know that the training time increases exponentially with the neural network architecture increasing/deepening. In general, it could take hours/days to train a 3–5 layers neural network with a large-scale dataset. Consequently, deploying VGG from scratch on a large-scale dataset is a tiresome and computationally expensive task due to the depth and number of fully connected layers/nodes in the models’ architecture. Another challenge is that building VGG from scratch requires considerably large memory space and bandwidth since the size of ImageNet trained VGG-16 weights is 528 MB. However, instead of building a VGG from scratch, we can perform transfer learning i.e. — utilizing the knowledge like weights, and features of the previously trained (e.g. pre-trained VGG) models’ to solve a similar kind of problem. For instance, if we want to develop a binary image classifier, then we can use a pre-trained model that is trained on a large benchmark image dataset like VGG. Therefore, transfer learning is a machine learning method where a model developed for a task is reused as the starting point for a model on a second task. Transfer learning is generally used for speeding up the training time and eventually improving the performance of the models’. While leveraging transfer learning, we must consider that the benefits of using transfer learning are not obvious."
},
{
"code": null,
"e": 3908,
"s": 3877,
"text": "When to Use Transfer Learning?"
},
{
"code": null,
"e": 4042,
"s": 3908,
"text": "You can read the article Significance Of Transfer Learning In The World Of Deep Learning that explains when to use transfer learning."
},
{
"code": null,
"e": 4358,
"s": 4042,
"text": "Machine learning algorithms especially deep neural networks may not able to learn properly when the training data is not enough. Transfer learning can play a significant role to solve this issue and adjust the model to suit the new task. There are a few factors we can look for while applying transfer learning [1]:"
},
{
"code": null,
"e": 4692,
"s": 4358,
"text": "Higher start: The initial stage of the model with transfer learning should outperform the model without transfer learning.Higher slope: The performance slope or rate of improvement during the training phase of the source model is steeper than it otherwise would be.Higher asymptote: The pre-trained should be converged more smoothly."
},
{
"code": null,
"e": 4815,
"s": 4692,
"text": "Higher start: The initial stage of the model with transfer learning should outperform the model without transfer learning."
},
{
"code": null,
"e": 4959,
"s": 4815,
"text": "Higher slope: The performance slope or rate of improvement during the training phase of the source model is steeper than it otherwise would be."
},
{
"code": null,
"e": 5028,
"s": 4959,
"text": "Higher asymptote: The pre-trained should be converged more smoothly."
},
{
"code": null,
"e": 5069,
"s": 5028,
"text": "Why the VGG model for transfer learning?"
},
{
"code": null,
"e": 5485,
"s": 5069,
"text": "Assuming the given number of training samples (images) are not sufficient enough for building a classifier, in that case, VGG can be easily leveraged for feature extraction as it is trained on millions of images. VGG was introduced in 2014 and still, it mysteriously produces better accuracy for some specific tasks compared to other classifiers through many state-of-the-art Image classifiers that came after 2014."
},
{
"code": null,
"e": 5801,
"s": 5485,
"text": "In this article, we will show one demonstration of transfer learning with the VGG model that shows that the transfer learning approach does not perform up to the mark. In the future post, we will demonstrate another example where models’ performance improved as expected for leveraging the transfer learning method."
},
{
"code": null,
"e": 6089,
"s": 5801,
"text": "In this demonstration, we use the famous MNIST digit dataset. We use a portion of the MNIST dataset that contains only digits 8 and 6. Altogether there are 8200 samples and 784 features for each of the samples. We extract features for the MNIST dataset using the VGG pre-trained weights."
},
{
"code": null,
"e": 6115,
"s": 6089,
"text": "Step 1 — Data Preparation"
},
{
"code": null,
"e": 6233,
"s": 6115,
"text": "We upload the dataset into the Google Colab from the local hard drive and convert the labels to 1 and 0 from 8 and 6."
},
{
"code": null,
"e": 6289,
"s": 6233,
"text": "from google.colab import filesuploaded = files.upload()"
},
{
"code": null,
"e": 6465,
"s": 6289,
"text": "Now, we read the dataset. The following figure shows that the labels are 8 & 6. As in the later section, we will apply logistic regression, we convert the labels into 1 and 0."
},
{
"code": null,
"e": 6519,
"s": 6465,
"text": "Running the one line of code will convert the labels:"
},
{
"code": null,
"e": 6570,
"s": 6519,
"text": "data['label'] = np.where(data['label'] == 8, 1, 0)"
},
{
"code": null,
"e": 6621,
"s": 6570,
"text": "Step 2 — Extracting Features from the VGG-16 Model"
},
{
"code": null,
"e": 6695,
"s": 6621,
"text": "Before extracting features, just observe the summary of the VGG-16 model:"
},
{
"code": null,
"e": 7020,
"s": 6695,
"text": "In the summary, the VGG-16 contains 16 layers where the number of features is 25,088 after flatten of the last convolutional layer (the 1st highlighted) and in the final layer (prediction or final dense layer), the number of nodes is 1000 as VGG-16 mainly trained for 1000-class classification problem (the 2nd highlighted)."
},
{
"code": null,
"e": 7186,
"s": 7020,
"text": "For transfer learning purposes, we can extract 25088 features from the MNIST dataset using the VGG model. The red vertical line shows the cut for feature extraction."
},
{
"code": null,
"e": 7273,
"s": 7186,
"text": "The following code section will cut the VGG model after the final convolutional layer:"
},
{
"code": null,
"e": 7436,
"s": 7273,
"text": "from keras import modelsbase_model = VGG16(weights='imagenet')model_VGG16 = models.Model(inputs=base_model.input, outputs=base_model.get_layer('flatten').output)"
},
{
"code": null,
"e": 7444,
"s": 7436,
"text": "output:"
},
{
"code": null,
"e": 7790,
"s": 7444,
"text": "After extracting features from the digit data using the VGG model, we trained a logistic regression binary classifier with the features and perform a 10-fold cross-validation. Simultaneously, we also apply logistic regression on the raw mnist digit data with 10-fold cross-validation to compare results with the performance of transfer learning."
},
{
"code": null,
"e": 8400,
"s": 7790,
"text": "The following two tables show the results of applying logistic regression to the raw data and extracted features from the raw data. Without transfer learning i.e. applying LR to the raw digit data achieves approximately 98% accuracy, while the model that leverages the transfer learning features achieves only 50% accuracy which is similar to a random guess for a binary classification problem. In general, we expect that with the transfer learning the model performance should be increased. However, in this demonstration, we experience that with transfer learning the model performance dramatically dropped."
},
{
"code": null,
"e": 8455,
"s": 8400,
"text": "The possible reasons that VGG16 does not perform well:"
},
{
"code": null,
"e": 8544,
"s": 8455,
"text": "VGG-16 is trained for 3-channel RGB images while Mnist digit data is 1-channel grayscale"
},
{
"code": null,
"e": 8633,
"s": 8544,
"text": "VGG-16 is trained for 3-channel RGB images while Mnist digit data is 1-channel grayscale"
},
{
"code": null,
"e": 8740,
"s": 8633,
"text": "2. Background noises in the ImageNet data that were learned by the VGG-16 higher representational features"
},
{
"code": null,
"e": 8845,
"s": 8740,
"text": "3. VGG-16 trained for 1000-class classification while for this task we used it for binary classification"
},
{
"code": null,
"e": 9293,
"s": 8845,
"text": "Though the model with the transfer learning does not provide rewarding results in this experiment, utilizing other layers of the VGG for the feature extraction process or fine-tuning the parameters may produce better accuracy. To sum up, transfer learning is a state-of-the-art machine learning technique that can boost models’ performance. However, smartly utilizing the transfer learning technique is a requirement to gain the proper advantages."
}
] |
Mastering catplot() in Seaborn with categorical plots | Towards Data Science
|
The goal of this article is to introduce you to the most common categorical plots using Seaborn’s catplot() function.
While doing Exploratory or Explanatory data analysis, you will have to choose from a wide range of plot types. Choosing one which depicts the relationships in your data accurately can be tricky.
If you are working with data that involves any categorical variables like survey responses, your best tools to visualize and compare different features of your data would be categorical plots. Fortunately, a data visualization library Seaborn encompasses several types of categorical plots into a single function: catplot().
Seaborn library offers many advantages over other plotting libraries:
1. It is very easy to use and requires less code syntax2. Works really well with `pandas` data structures, which is just what you need as a data scientist.3. It is built on top of Matplotlib, another vast and deep data visualization library.
BTW, my golden rule for Data Visualization is “Do it in Seabron if you can do it in Seaborn”.
In SB’s (I will be abbreviating from now on) documentation, it states that catplot() function includes 8 different types of categorical plots. But in this guide, I will cover the three most common plots: count plots, bar plots, and box plots.
I. Introduction II. SetupIII. Seaborn Count Plot 1. Changing the order of categories IV. Seaborn Bar Plot 1. Confidence intervals in a bar plot 2. Changing the orientation in bar plots V. Seaborn Box Plot 1. Overall understanding 2. Working with outliers 3. Working with whiskers VI. Conclusion
You can get the sample data and the notebook of the article on this GitHub repo.
If you have not SB already installed, you can install it using pip along with other libraries we will be using:
pip install numpy pandas seaborn matplotlib
If you are wondering why we don’t alias Seaborn as sb like a normal person, that's because the initials sns were named after a fictional character Samuel Norman Seaborn from the TV show "The West Wing". What can you say? (shrugs).
For the dataset, we will be using the classic diamonds dataset. It contains the price and quality data of 54000 diamonds. It is a great dataset for Data Visualization. One version of the data comes pre-loaded in Seaborn. You can get other loaded datasets with sns.get_dataset_names() function (there are many). But in this guide, we will be using the full version which I downloaded from Kaggle.
# Load sample datadiamonds = pd.read_csv('data/diamonds.csv', index_col=0)
diamonds.head()diamonds.info()diamonds.describe()
<class 'pandas.core.frame.DataFrame'>Int64Index: 53940 entries, 1 to 53940Data columns (total 10 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 carat 53940 non-null float64 1 cut 53940 non-null object 2 color 53940 non-null object 3 clarity 53940 non-null object 4 depth 53940 non-null float64 5 table 53940 non-null float64 6 price 53940 non-null int64 7 x 53940 non-null float64 8 y 53940 non-null float64 9 z 53940 non-null float64dtypes: float64(6), int64(1), object(3)memory usage: 4.5+ MB
diamonds.shape(53940, 10)
As the name suggests, a count plot displays the number of observations in each category of your variable. Throughout this article, we will be using catplot() function changing its kind parameter to create different plots. For the count plot, we set kind parameter to count and feed in the data using data parameter. Let's start by exploring the diamond cut quality.
sns.catplot(x='cut', data=diamonds, kind='count');
We start off with catplot() function and use x argument to specify the axis we want to show the categories. You can use y to make the chart horizontal. The count plot automatically counts the number of values in each category and displays them on YAxis.
In our plot, the quality of the cut is from best to worst. But let’s reverse the order:
category_order = ['Fair', 'Good', 'Very Good', 'Premium', 'Ideal']sns.catplot(x='cut', data=diamonds, kind='count', order=category_order);
It is best to create a list of categories in the order you want and then passing it to order. This improves code readability.
Another popular choice for plotting categorical data is a bar plot. In the count plot example, our plot only needed a single variable. In the bar plot, we often use one categorical variable and one quantitative. Let’s see how the prices of different diamond cuts compare to each other.
To create a bar plot, we feed the values for XAxis, YAxis separately and set kind parameter to bar:
sns.catplot(x='cut', y='price', data=diamonds, kind='bar', order=category_order);
The height of each bar represents the mean value in each category. In our plot, each bar is showing the mean price of diamonds in each category. I think you are also surprised to see that low-quality cuts also have significantly high prices. Lowest quality diamonds are, on average, even more expensive than ideal diamonds. This surprising trend is worth exploring but it would be beyond the scope of this article.
Black lines at the top of each bar represent 95% confidence intervals for the mean which can be thought of as the uncertainty in our sample data. Simply put, the tips of each line are the interval where you would expect the real mean price of all the diamonds (nut just 54000) in each category. If you don’t know statistics, best to skip this part. You can turn off confidence intervals setting the ci parameter to None:
sns.catplot(x='cut', y='price', data=diamonds, kind='bar', order=category_order, ci=None);
When you have lots of categories/bars, or long category names, it is a good idea to change the orientation. Just swap the x and y-axis values:
sns.catplot(x='price', y='cut', data=diamonds, kind='bar', order=category_order, ci=None);
Box plots are visuals that can be a little difficult to understand but depict the distribution of data very beautifully. It is best to start the explanation with an example of a box plot. I am going to use one of the common built-in datasets in Seaborn:
tips = sns.load_dataset('tips')sns.catplot(x='day', y='total_bill', data=tips, kind='box');
This box plot shows the distribution of bill amounts in a sample restaurant per day. Let’s start by interpreting Thursday’s.
The edges of the blue box are the 25th and 75th percentiles of the distribution of all bills. This means that 75% of all the bills on Thursday were lower than 20 dollars, while another 75% (from the bottom to the top) was higher than almost 13 dollars. The horizontal line in the box shows the median value of the distribution.
The dots above the whisker are called outliers. Outliers are calculated in three steps:
Find Inter Quartile Range (IQR) by subtracting the 25th percentile from the 75th: 75% — 25%The lower outlier limit is calculated by subtracting 1.5 times of IQR from the 25th: 25% — 1.5*IQRThe upper outlier limit is calculated by adding 1.5 times of IQR to the 75th: 75% + 1.5*IQR
Find Inter Quartile Range (IQR) by subtracting the 25th percentile from the 75th: 75% — 25%
The lower outlier limit is calculated by subtracting 1.5 times of IQR from the 25th: 25% — 1.5*IQR
The upper outlier limit is calculated by adding 1.5 times of IQR to the 75th: 75% + 1.5*IQR
Any values above and below the outlier limits become dots in a box plot.
Now that you understand box plots a little better, let’s get back to shiny diamonds:
sns.catplot(x='cut', y='price', data=diamonds, kind='box', order=category_order);
We create a box plot in the same way as any other plot. The key difference is that we set kind parameter to box. This box plot shows the distribution of prices of different quality cut diamonds. As you see, there are a lot of outliers for each category. And the distributions are highly skewed.
Box plots are very useful because they:
Show outliers, skewness, spread, and distribution in a single plotGreat for comparing different groups
Show outliers, skewness, spread, and distribution in a single plot
Great for comparing different groups
It is also possible to turn off the outliers in a box plot by setting the sym parameter to an empty string:
sns.catplot(x='cut', y='price', data=diamonds, kind='box', order=category_order, sym='');
The outliers in a box plot is by default calculated using the method I introduced earlier. However, you can change it by passing different values for whis parameter:
sns.catplot(x='cut', y='price', data=diamonds, kind='box', order=category_order, whis=2); # Using 2 times of IQR to calculate outliers
Using different percentiles:
sns.catplot(x='cut', y='price', data=diamonds, kind='box', order=category_order, whis=[5, 95]); # Whiskers show 5th and 95th percentiles
Or make the whiskers show minimum and max values:
sns.catplot(x='cut', y='price', data=diamonds, kind='box', order=category_order, whis=[0, 100]); # Min and max values in distribution
We have covered the three most common categorical plots. I did not include how to create subplots using the catplot() function even though it is one of the advantages of catplot()'s flexibility. I recently wrote another article for a similar function relplot() which is used to plot relational variables. I have discussed how to create subplots in detail there and the same techniques can be applied here.
towardsdatascience.com
Check out this story about Matplotlib fig and ax objects:
|
[
{
"code": null,
"e": 290,
"s": 172,
"text": "The goal of this article is to introduce you to the most common categorical plots using Seaborn’s catplot() function."
},
{
"code": null,
"e": 485,
"s": 290,
"text": "While doing Exploratory or Explanatory data analysis, you will have to choose from a wide range of plot types. Choosing one which depicts the relationships in your data accurately can be tricky."
},
{
"code": null,
"e": 810,
"s": 485,
"text": "If you are working with data that involves any categorical variables like survey responses, your best tools to visualize and compare different features of your data would be categorical plots. Fortunately, a data visualization library Seaborn encompasses several types of categorical plots into a single function: catplot()."
},
{
"code": null,
"e": 880,
"s": 810,
"text": "Seaborn library offers many advantages over other plotting libraries:"
},
{
"code": null,
"e": 1122,
"s": 880,
"text": "1. It is very easy to use and requires less code syntax2. Works really well with `pandas` data structures, which is just what you need as a data scientist.3. It is built on top of Matplotlib, another vast and deep data visualization library."
},
{
"code": null,
"e": 1216,
"s": 1122,
"text": "BTW, my golden rule for Data Visualization is “Do it in Seabron if you can do it in Seaborn”."
},
{
"code": null,
"e": 1459,
"s": 1216,
"text": "In SB’s (I will be abbreviating from now on) documentation, it states that catplot() function includes 8 different types of categorical plots. But in this guide, I will cover the three most common plots: count plots, bar plots, and box plots."
},
{
"code": null,
"e": 1805,
"s": 1459,
"text": " I. Introduction II. SetupIII. Seaborn Count Plot 1. Changing the order of categories IV. Seaborn Bar Plot 1. Confidence intervals in a bar plot 2. Changing the orientation in bar plots V. Seaborn Box Plot 1. Overall understanding 2. Working with outliers 3. Working with whiskers VI. Conclusion"
},
{
"code": null,
"e": 1886,
"s": 1805,
"text": "You can get the sample data and the notebook of the article on this GitHub repo."
},
{
"code": null,
"e": 1998,
"s": 1886,
"text": "If you have not SB already installed, you can install it using pip along with other libraries we will be using:"
},
{
"code": null,
"e": 2042,
"s": 1998,
"text": "pip install numpy pandas seaborn matplotlib"
},
{
"code": null,
"e": 2273,
"s": 2042,
"text": "If you are wondering why we don’t alias Seaborn as sb like a normal person, that's because the initials sns were named after a fictional character Samuel Norman Seaborn from the TV show \"The West Wing\". What can you say? (shrugs)."
},
{
"code": null,
"e": 2669,
"s": 2273,
"text": "For the dataset, we will be using the classic diamonds dataset. It contains the price and quality data of 54000 diamonds. It is a great dataset for Data Visualization. One version of the data comes pre-loaded in Seaborn. You can get other loaded datasets with sns.get_dataset_names() function (there are many). But in this guide, we will be using the full version which I downloaded from Kaggle."
},
{
"code": null,
"e": 2744,
"s": 2669,
"text": "# Load sample datadiamonds = pd.read_csv('data/diamonds.csv', index_col=0)"
},
{
"code": null,
"e": 2794,
"s": 2744,
"text": "diamonds.head()diamonds.info()diamonds.describe()"
},
{
"code": null,
"e": 3405,
"s": 2794,
"text": "<class 'pandas.core.frame.DataFrame'>Int64Index: 53940 entries, 1 to 53940Data columns (total 10 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 carat 53940 non-null float64 1 cut 53940 non-null object 2 color 53940 non-null object 3 clarity 53940 non-null object 4 depth 53940 non-null float64 5 table 53940 non-null float64 6 price 53940 non-null int64 7 x 53940 non-null float64 8 y 53940 non-null float64 9 z 53940 non-null float64dtypes: float64(6), int64(1), object(3)memory usage: 4.5+ MB"
},
{
"code": null,
"e": 3431,
"s": 3405,
"text": "diamonds.shape(53940, 10)"
},
{
"code": null,
"e": 3797,
"s": 3431,
"text": "As the name suggests, a count plot displays the number of observations in each category of your variable. Throughout this article, we will be using catplot() function changing its kind parameter to create different plots. For the count plot, we set kind parameter to count and feed in the data using data parameter. Let's start by exploring the diamond cut quality."
},
{
"code": null,
"e": 3848,
"s": 3797,
"text": "sns.catplot(x='cut', data=diamonds, kind='count');"
},
{
"code": null,
"e": 4102,
"s": 3848,
"text": "We start off with catplot() function and use x argument to specify the axis we want to show the categories. You can use y to make the chart horizontal. The count plot automatically counts the number of values in each category and displays them on YAxis."
},
{
"code": null,
"e": 4190,
"s": 4102,
"text": "In our plot, the quality of the cut is from best to worst. But let’s reverse the order:"
},
{
"code": null,
"e": 4329,
"s": 4190,
"text": "category_order = ['Fair', 'Good', 'Very Good', 'Premium', 'Ideal']sns.catplot(x='cut', data=diamonds, kind='count', order=category_order);"
},
{
"code": null,
"e": 4455,
"s": 4329,
"text": "It is best to create a list of categories in the order you want and then passing it to order. This improves code readability."
},
{
"code": null,
"e": 4741,
"s": 4455,
"text": "Another popular choice for plotting categorical data is a bar plot. In the count plot example, our plot only needed a single variable. In the bar plot, we often use one categorical variable and one quantitative. Let’s see how the prices of different diamond cuts compare to each other."
},
{
"code": null,
"e": 4841,
"s": 4741,
"text": "To create a bar plot, we feed the values for XAxis, YAxis separately and set kind parameter to bar:"
},
{
"code": null,
"e": 4967,
"s": 4841,
"text": "sns.catplot(x='cut', y='price', data=diamonds, kind='bar', order=category_order);"
},
{
"code": null,
"e": 5382,
"s": 4967,
"text": "The height of each bar represents the mean value in each category. In our plot, each bar is showing the mean price of diamonds in each category. I think you are also surprised to see that low-quality cuts also have significantly high prices. Lowest quality diamonds are, on average, even more expensive than ideal diamonds. This surprising trend is worth exploring but it would be beyond the scope of this article."
},
{
"code": null,
"e": 5803,
"s": 5382,
"text": "Black lines at the top of each bar represent 95% confidence intervals for the mean which can be thought of as the uncertainty in our sample data. Simply put, the tips of each line are the interval where you would expect the real mean price of all the diamonds (nut just 54000) in each category. If you don’t know statistics, best to skip this part. You can turn off confidence intervals setting the ci parameter to None:"
},
{
"code": null,
"e": 5949,
"s": 5803,
"text": "sns.catplot(x='cut', y='price', data=diamonds, kind='bar', order=category_order, ci=None);"
},
{
"code": null,
"e": 6092,
"s": 5949,
"text": "When you have lots of categories/bars, or long category names, it is a good idea to change the orientation. Just swap the x and y-axis values:"
},
{
"code": null,
"e": 6238,
"s": 6092,
"text": "sns.catplot(x='price', y='cut', data=diamonds, kind='bar', order=category_order, ci=None);"
},
{
"code": null,
"e": 6492,
"s": 6238,
"text": "Box plots are visuals that can be a little difficult to understand but depict the distribution of data very beautifully. It is best to start the explanation with an example of a box plot. I am going to use one of the common built-in datasets in Seaborn:"
},
{
"code": null,
"e": 6584,
"s": 6492,
"text": "tips = sns.load_dataset('tips')sns.catplot(x='day', y='total_bill', data=tips, kind='box');"
},
{
"code": null,
"e": 6709,
"s": 6584,
"text": "This box plot shows the distribution of bill amounts in a sample restaurant per day. Let’s start by interpreting Thursday’s."
},
{
"code": null,
"e": 7037,
"s": 6709,
"text": "The edges of the blue box are the 25th and 75th percentiles of the distribution of all bills. This means that 75% of all the bills on Thursday were lower than 20 dollars, while another 75% (from the bottom to the top) was higher than almost 13 dollars. The horizontal line in the box shows the median value of the distribution."
},
{
"code": null,
"e": 7125,
"s": 7037,
"text": "The dots above the whisker are called outliers. Outliers are calculated in three steps:"
},
{
"code": null,
"e": 7406,
"s": 7125,
"text": "Find Inter Quartile Range (IQR) by subtracting the 25th percentile from the 75th: 75% — 25%The lower outlier limit is calculated by subtracting 1.5 times of IQR from the 25th: 25% — 1.5*IQRThe upper outlier limit is calculated by adding 1.5 times of IQR to the 75th: 75% + 1.5*IQR"
},
{
"code": null,
"e": 7498,
"s": 7406,
"text": "Find Inter Quartile Range (IQR) by subtracting the 25th percentile from the 75th: 75% — 25%"
},
{
"code": null,
"e": 7597,
"s": 7498,
"text": "The lower outlier limit is calculated by subtracting 1.5 times of IQR from the 25th: 25% — 1.5*IQR"
},
{
"code": null,
"e": 7689,
"s": 7597,
"text": "The upper outlier limit is calculated by adding 1.5 times of IQR to the 75th: 75% + 1.5*IQR"
},
{
"code": null,
"e": 7762,
"s": 7689,
"text": "Any values above and below the outlier limits become dots in a box plot."
},
{
"code": null,
"e": 7847,
"s": 7762,
"text": "Now that you understand box plots a little better, let’s get back to shiny diamonds:"
},
{
"code": null,
"e": 7973,
"s": 7847,
"text": "sns.catplot(x='cut', y='price', data=diamonds, kind='box', order=category_order);"
},
{
"code": null,
"e": 8268,
"s": 7973,
"text": "We create a box plot in the same way as any other plot. The key difference is that we set kind parameter to box. This box plot shows the distribution of prices of different quality cut diamonds. As you see, there are a lot of outliers for each category. And the distributions are highly skewed."
},
{
"code": null,
"e": 8308,
"s": 8268,
"text": "Box plots are very useful because they:"
},
{
"code": null,
"e": 8411,
"s": 8308,
"text": "Show outliers, skewness, spread, and distribution in a single plotGreat for comparing different groups"
},
{
"code": null,
"e": 8478,
"s": 8411,
"text": "Show outliers, skewness, spread, and distribution in a single plot"
},
{
"code": null,
"e": 8515,
"s": 8478,
"text": "Great for comparing different groups"
},
{
"code": null,
"e": 8623,
"s": 8515,
"text": "It is also possible to turn off the outliers in a box plot by setting the sym parameter to an empty string:"
},
{
"code": null,
"e": 8768,
"s": 8623,
"text": "sns.catplot(x='cut', y='price', data=diamonds, kind='box', order=category_order, sym='');"
},
{
"code": null,
"e": 8934,
"s": 8768,
"text": "The outliers in a box plot is by default calculated using the method I introduced earlier. However, you can change it by passing different values for whis parameter:"
},
{
"code": null,
"e": 9126,
"s": 8934,
"text": "sns.catplot(x='cut', y='price', data=diamonds, kind='box', order=category_order, whis=2); # Using 2 times of IQR to calculate outliers"
},
{
"code": null,
"e": 9155,
"s": 9126,
"text": "Using different percentiles:"
},
{
"code": null,
"e": 9347,
"s": 9155,
"text": "sns.catplot(x='cut', y='price', data=diamonds, kind='box', order=category_order, whis=[5, 95]); # Whiskers show 5th and 95th percentiles"
},
{
"code": null,
"e": 9397,
"s": 9347,
"text": "Or make the whiskers show minimum and max values:"
},
{
"code": null,
"e": 9588,
"s": 9397,
"text": "sns.catplot(x='cut', y='price', data=diamonds, kind='box', order=category_order, whis=[0, 100]); # Min and max values in distribution"
},
{
"code": null,
"e": 9994,
"s": 9588,
"text": "We have covered the three most common categorical plots. I did not include how to create subplots using the catplot() function even though it is one of the advantages of catplot()'s flexibility. I recently wrote another article for a similar function relplot() which is used to plot relational variables. I have discussed how to create subplots in detail there and the same techniques can be applied here."
},
{
"code": null,
"e": 10017,
"s": 9994,
"text": "towardsdatascience.com"
}
] |
NLP with CNNs. Convolutional neural networks (CNNs)... | by Taha Binhuraib | Towards Data Science
|
Convolutional neural networks (CNNs) are the most widely used deep learning architectures in image processing and image recognition. Given their supremacy in the field of vision, it’s only natural that implementations on different fields of machine learning would be tried. In this article, I will try to explain the important terminology regarding CNNs from a natural language processing perspective, a short Keras implementation with code explanations will also be provided.
The concept of sliding or convolving a pre-determined window of data is the central idea behind why CNNs are named the way they are. An illustration of this concept is as below.
The first thing to notice here is the method by which each word(token) is represented as 3-dimensional word vectors. A weight matrix of 3x3 is then slid horizontally across the sentence by one step(also known as stride) capturing three words at a time. This weight matrix is called a filter; each filter is also composed of an activation function, similar to those used in feed-forward neural networks. Due to some mathematical properties, the activation function ReLU (rectified linear unit) is mostly used in CNNs and deep neural nets. Going back to image classification, the general intuition behind these filters is that, each filter can detect different features of an image, the deeper the filter, the more likely it will capture more complex details, as an example, the very first filters in your Convnet will detect simple features such as edges and lines, but the features at the very back might be able to detect certain animal types. All this is done without hardcoding any of the filters. Backpropagation will ensure that the weights of these filters are learned from the data.The next important step is to calculate the output(convolved feature). For the example, below we will consider a 5*5 image and a 3*3 filter (when dealing with CNNs you will mostly work with square matrices) the output layer is calculated by summing over the element-wise multiplication as each filter slides over the window of data one stride at a time each pixel is multiplied by its corresponding weight in the filter. The example below illustrates how the first cell in the output layer is calculated; the red numbers in the image represent the weights in the filter.
The calculation is as follows: (1∗2)+(1∗1)+(1∗0)+(0∗1)+(2∗0)+(0∗1)+(0∗0)+(2∗1)+(0∗4)=5
The python code with the activation function would be:
z_0 = max(sum(x*w), 0 )
In the case of a 2D filter The size of the output layer can be calculated using the following formula:
(N-F)/S +1
N = size of image , F = size of filter S = stride(1 in our case)
When applied to text you will be using a filter that slides by 3 strides horizontally across the window in 1-Dimension:
The last two examples resulted in an output size that is smaller than that of the input’s. It also isn’t too hard to imagine cases in which the filter doesn’t exactly fit the matrix with a given number of slides. To counter these complications, padding can be used in two ways:
Pad the outer edges with zero vectors (zero-padding)ignore the part of the matrix that does not fit the filter (valid padding)
Pad the outer edges with zero vectors (zero-padding)
ignore the part of the matrix that does not fit the filter (valid padding)
Pooling is the equivalent of dimension reduction in CNNs. The central idea is that we have to divide the output layers into subsections and calculate a value that best represents the output. The reason why this is so effective is that it helps the algorithm learn higher-order representations of the data while reducing the number of parameters. Types of pooling:
Sum poolingMax poolingAverage pooling
Sum pooling
Max pooling
Average pooling
Here is an example of max pooling:
The fully connected layer at the end receives the input from the previous pooling and convolutional layers, it then performs a classification task. In our example, we will be classifying a 300 token window of words into 1-Positive sentiment. 0-negative sentiment. The last neuron in the fully connected layer will take the weighted average of 250 neurons as a sigmoid function(returns a value between (0,1))
In this section, we will try to keep the code as general as possible for use cases in NLP. To keep things simple, we will not be going into the details of data pre-processing, but the general procedure is to tokenize and vectorize the data. In our example, a word2vec embedding was used, with each token being represented as a 300-Dimension word vector. Our data was also padded so that each sentence contained 400 tokens, long sentences were cut off after 400 tokens, and shorter sentences were zero-padded. The resulting dimension for each sentence is 300*400. We then divide the data into x_train and x_test; we will not be using a validation data set for this project. Now that we have our data ready, we can define some hyperparameters.
##hyper parametersbatch_size = 32embedding_dims = 300 #Length of the token vectorsfilters = 250 #number of filters in your Convnetkernel_size = 3 # a window size of 3 tokenshidden_dims = 250 #number of neurons at the normal feedforward NNepochs = 2
Now we can start building the model using the Keras library.
model = Sequential()model.add(Conv1D(filters,kernel_size,padding = 'valid' , activation = 'relu',strides = 1 , input_shape = (maxlen,embedding_dims)))
Here we that the padding is valid, which means that we will not maintain the input size, the resultant convolved matrix will be of size 100*1. Max pooling layer that takes the maximum value in a window of two.
model.add(GlobalMaxPooling1D())#GlobalMaxPooling1D(n) default = 2.
We then add the fully connected layer with a dropout rate of 0.2(we use this to counter over-fitting). Lastly, the output neuron will fire based on the sigmoid activation function. Keras will classify anything below 0.5 as 0, and anything above 0.5 as 1
model.add(Dense(hidden_dims))model.add(Dropout(0.2))model.add(Activation('relu'))model.add(Dense(1))model.add(Activation('sigmoid'))
The final step is to compile and fit the model.
model.compile(loss = 'binary_crossentropy',optimizer = 'adam', metrics = ['accuracy'])model.fit(x_train,y_train,batch_size = batch_size,epochs = epochs , validation_data = (x_test,y_test))
Now you can sit back and watch as your model trains. We were able to achieve a 90% accuracy using 60% of Stanford’s training data. you can find more details in the 7th chapter of the book: Natural Language Processing in Action.
CNNs can be used for different classification tasks in NLP.A convolution is a window that slides over a larger input data with an emphasis on a subset of the input matrix.Getting your data in the right dimensions is extremely important for any learning algorithm.
CNNs can be used for different classification tasks in NLP.
A convolution is a window that slides over a larger input data with an emphasis on a subset of the input matrix.
Getting your data in the right dimensions is extremely important for any learning algorithm.
|
[
{
"code": null,
"e": 649,
"s": 172,
"text": "Convolutional neural networks (CNNs) are the most widely used deep learning architectures in image processing and image recognition. Given their supremacy in the field of vision, it’s only natural that implementations on different fields of machine learning would be tried. In this article, I will try to explain the important terminology regarding CNNs from a natural language processing perspective, a short Keras implementation with code explanations will also be provided."
},
{
"code": null,
"e": 827,
"s": 649,
"text": "The concept of sliding or convolving a pre-determined window of data is the central idea behind why CNNs are named the way they are. An illustration of this concept is as below."
},
{
"code": null,
"e": 2487,
"s": 827,
"text": "The first thing to notice here is the method by which each word(token) is represented as 3-dimensional word vectors. A weight matrix of 3x3 is then slid horizontally across the sentence by one step(also known as stride) capturing three words at a time. This weight matrix is called a filter; each filter is also composed of an activation function, similar to those used in feed-forward neural networks. Due to some mathematical properties, the activation function ReLU (rectified linear unit) is mostly used in CNNs and deep neural nets. Going back to image classification, the general intuition behind these filters is that, each filter can detect different features of an image, the deeper the filter, the more likely it will capture more complex details, as an example, the very first filters in your Convnet will detect simple features such as edges and lines, but the features at the very back might be able to detect certain animal types. All this is done without hardcoding any of the filters. Backpropagation will ensure that the weights of these filters are learned from the data.The next important step is to calculate the output(convolved feature). For the example, below we will consider a 5*5 image and a 3*3 filter (when dealing with CNNs you will mostly work with square matrices) the output layer is calculated by summing over the element-wise multiplication as each filter slides over the window of data one stride at a time each pixel is multiplied by its corresponding weight in the filter. The example below illustrates how the first cell in the output layer is calculated; the red numbers in the image represent the weights in the filter."
},
{
"code": null,
"e": 2574,
"s": 2487,
"text": "The calculation is as follows: (1∗2)+(1∗1)+(1∗0)+(0∗1)+(2∗0)+(0∗1)+(0∗0)+(2∗1)+(0∗4)=5"
},
{
"code": null,
"e": 2629,
"s": 2574,
"text": "The python code with the activation function would be:"
},
{
"code": null,
"e": 2653,
"s": 2629,
"text": "z_0 = max(sum(x*w), 0 )"
},
{
"code": null,
"e": 2756,
"s": 2653,
"text": "In the case of a 2D filter The size of the output layer can be calculated using the following formula:"
},
{
"code": null,
"e": 2767,
"s": 2756,
"text": "(N-F)/S +1"
},
{
"code": null,
"e": 2832,
"s": 2767,
"text": "N = size of image , F = size of filter S = stride(1 in our case)"
},
{
"code": null,
"e": 2952,
"s": 2832,
"text": "When applied to text you will be using a filter that slides by 3 strides horizontally across the window in 1-Dimension:"
},
{
"code": null,
"e": 3230,
"s": 2952,
"text": "The last two examples resulted in an output size that is smaller than that of the input’s. It also isn’t too hard to imagine cases in which the filter doesn’t exactly fit the matrix with a given number of slides. To counter these complications, padding can be used in two ways:"
},
{
"code": null,
"e": 3357,
"s": 3230,
"text": "Pad the outer edges with zero vectors (zero-padding)ignore the part of the matrix that does not fit the filter (valid padding)"
},
{
"code": null,
"e": 3410,
"s": 3357,
"text": "Pad the outer edges with zero vectors (zero-padding)"
},
{
"code": null,
"e": 3485,
"s": 3410,
"text": "ignore the part of the matrix that does not fit the filter (valid padding)"
},
{
"code": null,
"e": 3849,
"s": 3485,
"text": "Pooling is the equivalent of dimension reduction in CNNs. The central idea is that we have to divide the output layers into subsections and calculate a value that best represents the output. The reason why this is so effective is that it helps the algorithm learn higher-order representations of the data while reducing the number of parameters. Types of pooling:"
},
{
"code": null,
"e": 3887,
"s": 3849,
"text": "Sum poolingMax poolingAverage pooling"
},
{
"code": null,
"e": 3899,
"s": 3887,
"text": "Sum pooling"
},
{
"code": null,
"e": 3911,
"s": 3899,
"text": "Max pooling"
},
{
"code": null,
"e": 3927,
"s": 3911,
"text": "Average pooling"
},
{
"code": null,
"e": 3962,
"s": 3927,
"text": "Here is an example of max pooling:"
},
{
"code": null,
"e": 4370,
"s": 3962,
"text": "The fully connected layer at the end receives the input from the previous pooling and convolutional layers, it then performs a classification task. In our example, we will be classifying a 300 token window of words into 1-Positive sentiment. 0-negative sentiment. The last neuron in the fully connected layer will take the weighted average of 250 neurons as a sigmoid function(returns a value between (0,1))"
},
{
"code": null,
"e": 5112,
"s": 4370,
"text": "In this section, we will try to keep the code as general as possible for use cases in NLP. To keep things simple, we will not be going into the details of data pre-processing, but the general procedure is to tokenize and vectorize the data. In our example, a word2vec embedding was used, with each token being represented as a 300-Dimension word vector. Our data was also padded so that each sentence contained 400 tokens, long sentences were cut off after 400 tokens, and shorter sentences were zero-padded. The resulting dimension for each sentence is 300*400. We then divide the data into x_train and x_test; we will not be using a validation data set for this project. Now that we have our data ready, we can define some hyperparameters."
},
{
"code": null,
"e": 5361,
"s": 5112,
"text": "##hyper parametersbatch_size = 32embedding_dims = 300 #Length of the token vectorsfilters = 250 #number of filters in your Convnetkernel_size = 3 # a window size of 3 tokenshidden_dims = 250 #number of neurons at the normal feedforward NNepochs = 2"
},
{
"code": null,
"e": 5422,
"s": 5361,
"text": "Now we can start building the model using the Keras library."
},
{
"code": null,
"e": 5573,
"s": 5422,
"text": "model = Sequential()model.add(Conv1D(filters,kernel_size,padding = 'valid' , activation = 'relu',strides = 1 , input_shape = (maxlen,embedding_dims)))"
},
{
"code": null,
"e": 5783,
"s": 5573,
"text": "Here we that the padding is valid, which means that we will not maintain the input size, the resultant convolved matrix will be of size 100*1. Max pooling layer that takes the maximum value in a window of two."
},
{
"code": null,
"e": 5850,
"s": 5783,
"text": "model.add(GlobalMaxPooling1D())#GlobalMaxPooling1D(n) default = 2."
},
{
"code": null,
"e": 6104,
"s": 5850,
"text": "We then add the fully connected layer with a dropout rate of 0.2(we use this to counter over-fitting). Lastly, the output neuron will fire based on the sigmoid activation function. Keras will classify anything below 0.5 as 0, and anything above 0.5 as 1"
},
{
"code": null,
"e": 6237,
"s": 6104,
"text": "model.add(Dense(hidden_dims))model.add(Dropout(0.2))model.add(Activation('relu'))model.add(Dense(1))model.add(Activation('sigmoid'))"
},
{
"code": null,
"e": 6285,
"s": 6237,
"text": "The final step is to compile and fit the model."
},
{
"code": null,
"e": 6474,
"s": 6285,
"text": "model.compile(loss = 'binary_crossentropy',optimizer = 'adam', metrics = ['accuracy'])model.fit(x_train,y_train,batch_size = batch_size,epochs = epochs , validation_data = (x_test,y_test))"
},
{
"code": null,
"e": 6702,
"s": 6474,
"text": "Now you can sit back and watch as your model trains. We were able to achieve a 90% accuracy using 60% of Stanford’s training data. you can find more details in the 7th chapter of the book: Natural Language Processing in Action."
},
{
"code": null,
"e": 6966,
"s": 6702,
"text": "CNNs can be used for different classification tasks in NLP.A convolution is a window that slides over a larger input data with an emphasis on a subset of the input matrix.Getting your data in the right dimensions is extremely important for any learning algorithm."
},
{
"code": null,
"e": 7026,
"s": 6966,
"text": "CNNs can be used for different classification tasks in NLP."
},
{
"code": null,
"e": 7139,
"s": 7026,
"text": "A convolution is a window that slides over a larger input data with an emphasis on a subset of the input matrix."
}
] |
Python Program for Extended Euclidean algorithms
|
In this article, we will learn about the solution to the problem statement given below.
Problem statement − Given two numbers we need to calculate gcd of those two numbers and display them.
GCD Greatest Common Divisor of two numbers is the largest number that can divide both of them. Here we follow the euclidean approach to compute the gcd i.e. to repeatedly divide the numbers and stop when the remainder becomes zero. Here we extend the algorithm based on previous values obtained in recursion.
Now let’s observe the solution in the implementation below −
Live Demo
# extended Euclidean Algorithm
def gcdExtended(a, b, x, y):
# Base Case
if a == 0 :
x = 0
y = 1
return b
x1 = 1
y1 = 1 # storing the result
gcd = gcdExtended(b%a, a, x1, y1)
# Update x and y with previous calculated values
x = y1 - (b/a) * x1
y = x1
return gcd
x = 1
y = 1
a = 11
b = 15
g = gcdExtended(a, b, x, y)
print("gcd of ", a , "&" , b, " is = ", g)
gcd of 11 & 15 is = 1
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can make a Python Program for Extended Euclidean algorithms
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In this article, we will learn about the solution to the problem statement given below."
},
{
"code": null,
"e": 1252,
"s": 1150,
"text": "Problem statement − Given two numbers we need to calculate gcd of those two numbers and display them."
},
{
"code": null,
"e": 1561,
"s": 1252,
"text": "GCD Greatest Common Divisor of two numbers is the largest number that can divide both of them. Here we follow the euclidean approach to compute the gcd i.e. to repeatedly divide the numbers and stop when the remainder becomes zero. Here we extend the algorithm based on previous values obtained in recursion."
},
{
"code": null,
"e": 1622,
"s": 1561,
"text": "Now let’s observe the solution in the implementation below −"
},
{
"code": null,
"e": 1633,
"s": 1622,
"text": " Live Demo"
},
{
"code": null,
"e": 2036,
"s": 1633,
"text": "# extended Euclidean Algorithm\ndef gcdExtended(a, b, x, y):\n # Base Case\n if a == 0 :\n x = 0\n y = 1\n return b\n x1 = 1\n y1 = 1 # storing the result\n gcd = gcdExtended(b%a, a, x1, y1)\n # Update x and y with previous calculated values\n x = y1 - (b/a) * x1\n y = x1\n return gcd\nx = 1\ny = 1\na = 11\nb = 15\ng = gcdExtended(a, b, x, y)\nprint(\"gcd of \", a , \"&\" , b, \" is = \", g)"
},
{
"code": null,
"e": 2058,
"s": 2036,
"text": "gcd of 11 & 15 is = 1"
},
{
"code": null,
"e": 2159,
"s": 2058,
"text": "All the variables are declared in the local scope and their references are seen in the figure above."
},
{
"code": null,
"e": 2265,
"s": 2159,
"text": "In this article, we have learned about how we can make a Python Program for Extended Euclidean algorithms"
}
] |
Checking the Given File Exists or Not in Golang - GeeksforGeeks
|
23 Mar, 2020
In Go language, you are allowed to check whether the given file exists or not with the help of the IsNotExist() function. If this function returns true, then it indicates that the error is known to report that the specified file or directory already does not exist and if it returns false, then it indicates that the given file or directory exists. This method also satisfied by ErrNotExist as well as some syscall errors. It is defined under the os package so, you have to import os package in your program for accessing IsNotExist() function.
Syntax:
func IsNotExist(e error) bool
Example 1:
// Golang program to illustrate how to check the// given file exists or not in the default directorypackage main import ( "log" "os") var ( myfile *os.FileInfo e error) func main() { // Here Stat() function returns file info and //if there is no file, then it will return an error myfile, e := os.Stat("gfg.txt") if e != nil { // Checking if the given file exists or not // Using IsNotExist() function if os.IsNotExist(e) { log.Fatal("File not Found !!") } } log.Println("File Exist!!") log.Println("Detail of file is:") log.Println("Name: ", myfile.Name()) log.Println("Size: ", myfile.Size()) }
Output:
Example 2:
// Golang program to illustrate how to check// the given file exists or not in given // directorypackage main import ( "log" "os") var ( myfile *os.FileInfo e error) func main() { // Here Stat() function // returns file info and // if there is no file, // then it will return an error myfile, e := os.Stat("/Users/anki/Documents/new_folder/myfolder/hello.txt") if e != nil { // Checking if the given file exists or not // Using IsNotExist() function if os.IsNotExist(e) { log.Fatal("File not Found !!") } } log.Println("File Exist!!") log.Println("Detail of file is:") log.Println("Name: ", myfile.Name()) log.Println("Size: ", myfile.Size()) }
Output:
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Defer Keyword in Golang
Time Durations in Golang
Anonymous function in Go Language
Loops in Go Language
How to iterate over an Array using for loop in Golang?
time.Parse() Function in Golang With Examples
Strings in Golang
Structures in Golang
Rune in Golang
|
[
{
"code": null,
"e": 24460,
"s": 24432,
"text": "\n23 Mar, 2020"
},
{
"code": null,
"e": 25005,
"s": 24460,
"text": "In Go language, you are allowed to check whether the given file exists or not with the help of the IsNotExist() function. If this function returns true, then it indicates that the error is known to report that the specified file or directory already does not exist and if it returns false, then it indicates that the given file or directory exists. This method also satisfied by ErrNotExist as well as some syscall errors. It is defined under the os package so, you have to import os package in your program for accessing IsNotExist() function."
},
{
"code": null,
"e": 25013,
"s": 25005,
"text": "Syntax:"
},
{
"code": null,
"e": 25043,
"s": 25013,
"text": "func IsNotExist(e error) bool"
},
{
"code": null,
"e": 25054,
"s": 25043,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate how to check the// given file exists or not in the default directorypackage main import ( \"log\" \"os\") var ( myfile *os.FileInfo e error) func main() { // Here Stat() function returns file info and //if there is no file, then it will return an error myfile, e := os.Stat(\"gfg.txt\") if e != nil { // Checking if the given file exists or not // Using IsNotExist() function if os.IsNotExist(e) { log.Fatal(\"File not Found !!\") } } log.Println(\"File Exist!!\") log.Println(\"Detail of file is:\") log.Println(\"Name: \", myfile.Name()) log.Println(\"Size: \", myfile.Size()) }",
"e": 25756,
"s": 25054,
"text": null
},
{
"code": null,
"e": 25764,
"s": 25756,
"text": "Output:"
},
{
"code": null,
"e": 25775,
"s": 25764,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate how to check// the given file exists or not in given // directorypackage main import ( \"log\" \"os\") var ( myfile *os.FileInfo e error) func main() { // Here Stat() function // returns file info and // if there is no file, // then it will return an error myfile, e := os.Stat(\"/Users/anki/Documents/new_folder/myfolder/hello.txt\") if e != nil { // Checking if the given file exists or not // Using IsNotExist() function if os.IsNotExist(e) { log.Fatal(\"File not Found !!\") } } log.Println(\"File Exist!!\") log.Println(\"Detail of file is:\") log.Println(\"Name: \", myfile.Name()) log.Println(\"Size: \", myfile.Size()) }",
"e": 26533,
"s": 25775,
"text": null
},
{
"code": null,
"e": 26541,
"s": 26533,
"text": "Output:"
},
{
"code": null,
"e": 26553,
"s": 26541,
"text": "Go Language"
},
{
"code": null,
"e": 26651,
"s": 26553,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26680,
"s": 26651,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 26704,
"s": 26680,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 26729,
"s": 26704,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 26763,
"s": 26729,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 26784,
"s": 26763,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 26839,
"s": 26784,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 26885,
"s": 26839,
"text": "time.Parse() Function in Golang With Examples"
},
{
"code": null,
"e": 26903,
"s": 26885,
"text": "Strings in Golang"
},
{
"code": null,
"e": 26924,
"s": 26903,
"text": "Structures in Golang"
}
] |
Python Program for Print Number series without using any loop
|
04 May, 2022
Problem – Givens Two number N and K, our task is to subtract a number K from N until number(N) is greater than zero, once the N becomes negative or zero then we start adding K until that number become the original number(N). Note : Not allow to use any loop. Examples :
Input : N = 15 K = 5
Output : 15 10 5 0 1 5 10 15
Input : N = 20 K = 6
Output : 20 14 8 2 -4 2 8 14 20
Explanation – We can do it using recursion idea is that we call the function again and again until N is greater than zero (in every function call we subtract N by K). Once the number becomes negative or zero we start adding K in every function call until the number becomes the original number. Here we use a single function for both addition and subtraction but to switch between addition or subtraction function we used a Boolean flag.
Python3
# Python program to Print Number# series without using loop def PrintNumber(N, Original, K, flag): #print the number print(N, end = " ") # change flag if number # become negative if (N <= 0): if(flag==0): flag = 1 else: flag = 0 # base condition for # second_case (Adding K) if (N == Original and (not(flag))): return # if flag is true # we subtract value until # number is greater than zero if (flag == True): PrintNumber(N - K, Original, K, flag) return # second case (Addition ) if (not(flag)): PrintNumber(N + K, Original, K, flag); return N = 20K = 6PrintNumber(N, N, K, True) # This code is contributed by Mohit Gupta_OMG
Output :
20 14 8 2 -4 2 8 14 20
Please refer complete article on Print Number series without using any loop for more details!
surinderdawra388
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 May, 2022"
},
{
"code": null,
"e": 298,
"s": 28,
"text": "Problem – Givens Two number N and K, our task is to subtract a number K from N until number(N) is greater than zero, once the N becomes negative or zero then we start adding K until that number become the original number(N). Note : Not allow to use any loop. Examples :"
},
{
"code": null,
"e": 405,
"s": 298,
"text": "Input : N = 15 K = 5 \nOutput : 15 10 5 0 1 5 10 15\n\nInput : N = 20 K = 6\nOutput : 20 14 8 2 -4 2 8 14 20 "
},
{
"code": null,
"e": 844,
"s": 405,
"text": "Explanation – We can do it using recursion idea is that we call the function again and again until N is greater than zero (in every function call we subtract N by K). Once the number becomes negative or zero we start adding K in every function call until the number becomes the original number. Here we use a single function for both addition and subtraction but to switch between addition or subtraction function we used a Boolean flag. "
},
{
"code": null,
"e": 852,
"s": 844,
"text": "Python3"
},
{
"code": "# Python program to Print Number# series without using loop def PrintNumber(N, Original, K, flag): #print the number print(N, end = \" \") # change flag if number # become negative if (N <= 0): if(flag==0): flag = 1 else: flag = 0 # base condition for # second_case (Adding K) if (N == Original and (not(flag))): return # if flag is true # we subtract value until # number is greater than zero if (flag == True): PrintNumber(N - K, Original, K, flag) return # second case (Addition ) if (not(flag)): PrintNumber(N + K, Original, K, flag); return N = 20K = 6PrintNumber(N, N, K, True) # This code is contributed by Mohit Gupta_OMG",
"e": 1636,
"s": 852,
"text": null
},
{
"code": null,
"e": 1645,
"s": 1636,
"text": "Output :"
},
{
"code": null,
"e": 1669,
"s": 1645,
"text": "20 14 8 2 -4 2 8 14 20 "
},
{
"code": null,
"e": 1763,
"s": 1669,
"text": "Please refer complete article on Print Number series without using any loop for more details!"
},
{
"code": null,
"e": 1780,
"s": 1763,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1796,
"s": 1780,
"text": "Python Programs"
}
] |
Fall Through Condition in Java
|
11 Feb, 2021
The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be a byte, short, char, and int primitive data types. Beginning with JDK7, it also works with enumerated types ( Enums in java), the String class, and Wrapper classes.
Flow Diagram of Switch-case :
Fall through condition: This condition occurs in the switch control statement when there is no break keyword mention for the particular case in the switch statement and cause execution of the cases till no break statement occurs or exit from the switch statement. This condition has its own advantage and disadvantage and it totally depends upon the type of operation we want in our program.
Fall through condition in below program:
Java
// Java program to showcase the fall through condition import java.util.*;import java.io.*;class GFG{ public static void main(String[] args) { int gfg = 1; switch ( gfg ){ case 1:{ System.out.println("GeeksforGeeks number 1"); } // Since break statement is missing // it will lead to fall through condition case 2:{ System.out.println("GeeksforGeeks number 2"); } case 3:{ System.out.println("GeeksforGeeks number 3"); } default :{ System.out.println("This is default case"); } } }}
GeeksforGeeks number 1
GeeksforGeeks number 2
GeeksforGeeks number 3
This is default case
Disadvantage: In the above program, we forgot to mention the break statement in the switch statement that leads to executing all the cases even they didn’t match with the matched value. This situation creates a major problem in the programs. So we have to use the break keyword for every case in the switch statement in order to overcome this situation this is the disadvantage of the fall through condition.
Advantage of fall through condition:
We know very well that the switch statement works for a single variable or expression and in many cases when there are same output many values and here fall through condition plays an important role in this case and makes the program efficient by reducing comparisons
Example: Java total number of days in a month, Java Program to check whether the character is a vowel or not, etc.
Java
// Java Program to check whether the character is a vowel or not import java.util.*;import java.io.*;class GFG{ public static void main(String[] args) { char ch='f'; switch ( ch ){ case 'a': case 'e': case 'i': case 'o': case 'u':System.out.println("Vowel"); break; default :{ System.out.println("Consonant"); } }}}
Consonant
Java-Control-Flow
Picked
Technical Scripter 2020
Java
Technical Scripter
Java-Control-Flow
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
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Feb, 2021"
},
{
"code": null,
"e": 391,
"s": 28,
"text": "The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be a byte, short, char, and int primitive data types. Beginning with JDK7, it also works with enumerated types ( Enums in java), the String class, and Wrapper classes."
},
{
"code": null,
"e": 422,
"s": 391,
"text": "Flow Diagram of Switch-case : "
},
{
"code": null,
"e": 815,
"s": 422,
"text": "Fall through condition: This condition occurs in the switch control statement when there is no break keyword mention for the particular case in the switch statement and cause execution of the cases till no break statement occurs or exit from the switch statement. This condition has its own advantage and disadvantage and it totally depends upon the type of operation we want in our program. "
},
{
"code": null,
"e": 856,
"s": 815,
"text": "Fall through condition in below program:"
},
{
"code": null,
"e": 861,
"s": 856,
"text": "Java"
},
{
"code": "// Java program to showcase the fall through condition import java.util.*;import java.io.*;class GFG{ public static void main(String[] args) { int gfg = 1; switch ( gfg ){ case 1:{ System.out.println(\"GeeksforGeeks number 1\"); } // Since break statement is missing // it will lead to fall through condition case 2:{ System.out.println(\"GeeksforGeeks number 2\"); } case 3:{ System.out.println(\"GeeksforGeeks number 3\"); } default :{ System.out.println(\"This is default case\"); } } }}",
"e": 1522,
"s": 861,
"text": null
},
{
"code": null,
"e": 1612,
"s": 1522,
"text": "GeeksforGeeks number 1\nGeeksforGeeks number 2\nGeeksforGeeks number 3\nThis is default case"
},
{
"code": null,
"e": 2022,
"s": 1612,
"text": "Disadvantage: In the above program, we forgot to mention the break statement in the switch statement that leads to executing all the cases even they didn’t match with the matched value. This situation creates a major problem in the programs. So we have to use the break keyword for every case in the switch statement in order to overcome this situation this is the disadvantage of the fall through condition. "
},
{
"code": null,
"e": 2059,
"s": 2022,
"text": "Advantage of fall through condition:"
},
{
"code": null,
"e": 2327,
"s": 2059,
"text": "We know very well that the switch statement works for a single variable or expression and in many cases when there are same output many values and here fall through condition plays an important role in this case and makes the program efficient by reducing comparisons"
},
{
"code": null,
"e": 2442,
"s": 2327,
"text": "Example: Java total number of days in a month, Java Program to check whether the character is a vowel or not, etc."
},
{
"code": null,
"e": 2447,
"s": 2442,
"text": "Java"
},
{
"code": "// Java Program to check whether the character is a vowel or not import java.util.*;import java.io.*;class GFG{ public static void main(String[] args) { char ch='f'; switch ( ch ){ case 'a': case 'e': case 'i': case 'o': case 'u':System.out.println(\"Vowel\"); break; default :{ System.out.println(\"Consonant\"); } }}}",
"e": 2879,
"s": 2447,
"text": null
},
{
"code": null,
"e": 2889,
"s": 2879,
"text": "Consonant"
},
{
"code": null,
"e": 2907,
"s": 2889,
"text": "Java-Control-Flow"
},
{
"code": null,
"e": 2914,
"s": 2907,
"text": "Picked"
},
{
"code": null,
"e": 2938,
"s": 2914,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2943,
"s": 2938,
"text": "Java"
},
{
"code": null,
"e": 2962,
"s": 2943,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2980,
"s": 2962,
"text": "Java-Control-Flow"
},
{
"code": null,
"e": 2985,
"s": 2980,
"text": "Java"
},
{
"code": null,
"e": 3083,
"s": 2985,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3098,
"s": 3083,
"text": "Stream In Java"
},
{
"code": null,
"e": 3119,
"s": 3098,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3140,
"s": 3119,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3159,
"s": 3140,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3176,
"s": 3159,
"text": "Generics in Java"
},
{
"code": null,
"e": 3206,
"s": 3176,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 3232,
"s": 3206,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3248,
"s": 3232,
"text": "Strings in Java"
},
{
"code": null,
"e": 3285,
"s": 3248,
"text": "Differences between JDK, JRE and JVM"
}
] |
Goldman Sachs Interview Experience (1.8 Years of Experience )
|
21 Jun, 2021
I was contacted by HR on LinkedIn
Round 1(Online Coding Round): Hackerrank platform 1 hour 30 min
Given an input string, write a function that returns the Run Length Encoded string for the input string.For example,
if the input string is “wwwwaaadexxxxxx”,
then the function should
return “w4a3d1e1x6”
Expected Time Complexity: O(n) Let 1 represent ‘A’, 2 represents ‘B’, etc. Given a digit sequence, count the number of possible decoding’s of the given digit sequence.Input:
digits[] = "121"
Output: 3
The possible decoding's are
"ABA", "AU", "LA"
Input:
digits[] = "1234"
Output: 3
The possible decoding's are
"ABCD", "LCD", "AWD"
Expected Time Complexity: O(n)
Given an input string, write a function that returns the Run Length Encoded string for the input string.For example,
if the input string is “wwwwaaadexxxxxx”,
then the function should
return “w4a3d1e1x6”
Expected Time Complexity: O(n)
For example,
if the input string is “wwwwaaadexxxxxx”,
then the function should
return “w4a3d1e1x6”
Expected Time Complexity: O(n)
Let 1 represent ‘A’, 2 represents ‘B’, etc. Given a digit sequence, count the number of possible decoding’s of the given digit sequence.Input:
digits[] = "121"
Output: 3
The possible decoding's are
"ABA", "AU", "LA"
Input:
digits[] = "1234"
Output: 3
The possible decoding's are
"ABCD", "LCD", "AWD"
Expected Time Complexity: O(n)
Input:
digits[] = "121"
Output: 3
The possible decoding's are
"ABA", "AU", "LA"
Input:
digits[] = "1234"
Output: 3
The possible decoding's are
"ABCD", "LCD", "AWD"
Expected Time Complexity: O(n)
Round 2(F2F Coding Round): CoderPad with Goldman Sachs Developer
Given an array of strings strings, group the anagrams together. You can return the answer in any order.An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.Input:
strs = ["eat","tea","tan","ate",
"nat","bat"]
Output:
[["bat"],["nat","tan"],
["ate","eat","tea"]]
Expected Time Complexity: O(n) Given a file containing data of student name and marks scored by him/her in 3 subjects. The task is to find the list of students having the maximum average score.If more than one student has the maximum average score, print them as per the order in the file.Input:
file[] = {“Shrikanth”, “20”, “30”,
“10”, “Ram”, “100”, “50”, “10”}
Output:
Ram 53 Average scores of Shrikanth, Ram are 20 and 53 respectively. So Ram has the maximum average score of 53.Expected Time Complexity: O(n)
Given an array of strings strings, group the anagrams together. You can return the answer in any order.An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.Input:
strs = ["eat","tea","tan","ate",
"nat","bat"]
Output:
[["bat"],["nat","tan"],
["ate","eat","tea"]]
Expected Time Complexity: O(n)
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Input:
strs = ["eat","tea","tan","ate",
"nat","bat"]
Output:
[["bat"],["nat","tan"],
["ate","eat","tea"]]
Expected Time Complexity: O(n)
Given a file containing data of student name and marks scored by him/her in 3 subjects. The task is to find the list of students having the maximum average score.If more than one student has the maximum average score, print them as per the order in the file.Input:
file[] = {“Shrikanth”, “20”, “30”,
“10”, “Ram”, “100”, “50”, “10”}
Output:
Ram 53 Average scores of Shrikanth, Ram are 20 and 53 respectively. So Ram has the maximum average score of 53.Expected Time Complexity: O(n)
If more than one student has the maximum average score, print them as per the order in the file.
Input:
file[] = {“Shrikanth”, “20”, “30”,
“10”, “Ram”, “100”, “50”, “10”}
Output:
Ram 53
Average scores of Shrikanth, Ram are 20 and 53 respectively. So Ram has the maximum average score of 53.
Expected Time Complexity: O(n)
Round 3(F2F Coding Round on Zoom): CoderPad with two Goldman Sachs Developers
Given a linked list, write a function to reverse every k nodes (where k is an input to the function).Input:
1->2->3->4->5->6->7->8->NULL, K = 3
Output:
3->2->1->6->5->4->8->7->NULL
Expected Time Complexity: O(n)
Auxiliary Space: O(n/k). Given a Binary Search Tree (BST) and a positive integer k, find the k’th largest element in the Binary Search Tree.Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure and no other data structure like arrays, list, .. etc.Example:
Consider the following
SpecialStack
16 --> TOP
15
29
19
18
When getMin() is called it
should return 15,
Given a linked list, write a function to reverse every k nodes (where k is an input to the function).Input:
1->2->3->4->5->6->7->8->NULL, K = 3
Output:
3->2->1->6->5->4->8->7->NULL
Expected Time Complexity: O(n)
Auxiliary Space: O(n/k).
Input:
1->2->3->4->5->6->7->8->NULL, K = 3
Output:
3->2->1->6->5->4->8->7->NULL
Expected Time Complexity: O(n)
Auxiliary Space: O(n/k).
Given a Binary Search Tree (BST) and a positive integer k, find the k’th largest element in the Binary Search Tree.
Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure and no other data structure like arrays, list, .. etc.Example:
Consider the following
SpecialStack
16 --> TOP
15
29
19
18
When getMin() is called it
should return 15,
Example:
Consider the following
SpecialStack
16 --> TOP
15
29
19
18
When getMin() is called it
should return 15,
Round 4(F2F Coding Round on Zoom): CoderPad with two Goldman Sachs Developers
Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that sorting this subarray makes the whole array sorted.Example: If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the subarray lies between indexes 3 and 8.Given a binary array, in which, moving an element from index i to index j requires abs(i – j) cost. The task is to find the cost to move all 1s to each index of the given array.Input:
arr[] = {0, 1, 0, 1}
Output:
4 2 2 2Explanation:Moving elements from index 1, index 3 to index 0 requires abs(0 – 1) + abs(0 – 3) = 4.Moving elements from index 1, index 3 to index 1 requires abs(1 – 1) + abs(1 – 3) = 2.Moving elements from index 1, index 2 to index 2 requires abs(2 – 1) + abs(2 – 3) = 2.Moving elements from index 1, index 2 to index 3 requires abs(3 – 1) + abs(3 – 3) = 2.Therefore, the required output is 4 2 2 2.
Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that sorting this subarray makes the whole array sorted.Example: If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the subarray lies between indexes 3 and 8.
Example: If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the subarray lies between indexes 3 and 8.
Given a binary array, in which, moving an element from index i to index j requires abs(i – j) cost. The task is to find the cost to move all 1s to each index of the given array.Input:
arr[] = {0, 1, 0, 1}
Output:
4 2 2 2Explanation:Moving elements from index 1, index 3 to index 0 requires abs(0 – 1) + abs(0 – 3) = 4.Moving elements from index 1, index 3 to index 1 requires abs(1 – 1) + abs(1 – 3) = 2.Moving elements from index 1, index 2 to index 2 requires abs(2 – 1) + abs(2 – 3) = 2.Moving elements from index 1, index 2 to index 3 requires abs(3 – 1) + abs(3 – 3) = 2.Therefore, the required output is 4 2 2 2.
Input:
arr[] = {0, 1, 0, 1}
Output:
4 2 2 2
Explanation:
Moving elements from index 1, index 3 to index 0 requires abs(0 – 1) + abs(0 – 3) = 4.
Moving elements from index 1, index 3 to index 1 requires abs(1 – 1) + abs(1 – 3) = 2.
Moving elements from index 1, index 2 to index 2 requires abs(2 – 1) + abs(2 – 3) = 2.
Moving elements from index 1, index 2 to index 3 requires abs(3 – 1) + abs(3 – 3) = 2.
Therefore, the required output is 4 2 2 2.
Round 5(F2F Coding Round on Zoom): CoderPad with two Goldman Sachs Developers
Problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.The expected output is a binary matrix which has 1s for the blocks where queens are placed.For example, following is the output matrix for above 4 queen solution.{ 0, 1, 0, 0}
{ 0, 0, 0, 1}
{ 1, 0, 0, 0}
{ 0, 0, 1, 0}Solution: Use Recursion and BacktrackingImplement a SnapshotArray that supports the following interface:SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0.void set(index, val) sets the element at the given index to be equal to val.int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_idSolution: Use the 2D Array of class Node , the 1D is used to store the indices and 2D is used to store the snap shots. For each index to get the value at particular snap id , we can use binary search as the snap array in each index will be sorted and Complexity of get Operation reduces to log(N)
Problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.The expected output is a binary matrix which has 1s for the blocks where queens are placed.For example, following is the output matrix for above 4 queen solution.{ 0, 1, 0, 0}
{ 0, 0, 0, 1}
{ 1, 0, 0, 0}
{ 0, 0, 1, 0}Solution: Use Recursion and Backtracking
The expected output is a binary matrix which has 1s for the blocks where queens are placed.
For example, following is the output matrix for above 4 queen solution.
{ 0, 1, 0, 0}
{ 0, 0, 0, 1}
{ 1, 0, 0, 0}
{ 0, 0, 1, 0}
Solution: Use Recursion and Backtracking
Implement a SnapshotArray that supports the following interface:SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0.void set(index, val) sets the element at the given index to be equal to val.int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_idSolution: Use the 2D Array of class Node , the 1D is used to store the indices and 2D is used to store the snap shots. For each index to get the value at particular snap id , we can use binary search as the snap array in each index will be sorted and Complexity of get Operation reduces to log(N)
SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0.
void set(index, val) sets the element at the given index to be equal to val.
int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.
int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id
Solution: Use the 2D Array of class Node , the 1D is used to store the indices and 2D is used to store the snap shots. For each index to get the value at particular snap id , we can use binary search as the snap array in each index will be sorted and Complexity of get Operation reduces to log(N)
Round 6(F2F Coding Round on Zoom): CoderPad with two Goldman Sachs Developers
https://www.hackerrank.com/challenges/connected-cell-in-a-grid/problem
https://www.hackerrank.com/challenges/connected-cell-in-a-grid/problem
Round 7(F2F Coding Round on Zoom): CoderPad with two Goldman Sachs Developers
Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same.Expected time complexity is O(n) and extra space is O(1).Some string-related basics and Strings in java and Python.
Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same.Expected time complexity is O(n) and extra space is O(1).
Expected time complexity is O(n) and extra space is O(1).
Some string-related basics and Strings in java and Python.
Round 8(F2F Round on Zoom): CoderPad with two Goldman Sachs Developers
Few Questions on my recent projects, technologies I have worked on, and Cache Evacuation policies.Introduction to Customer wealth Management (CWM Goldman Sachs) Team, the products, and the Tech stacks Goldman’s uses.
Few Questions on my recent projects, technologies I have worked on, and Cache Evacuation policies.
Introduction to Customer wealth Management (CWM Goldman Sachs) Team, the products, and the Tech stacks Goldman’s uses.
After these rounds Finally I got a mail from HR for compensation discussion.
Goldman Sachs
Marketing
Experienced
Interview Experiences
Goldman Sachs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience SDE-2 (3 Years Experienced)
Google Interview Experience for Software Engineer L3 Bangalore (6 Years Experienced)
SAMSUNG R&D Interview Experience for Team Lead
Adobe Interview Experience for MTS-1 (Off-Campus) 1 Year Experienced
Nagarro Interview Experience | Set 7 (For 2 Years Experienced)
Amazon Interview Questions
Amazon Interview Experience for SDE 1
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Commonly Asked Java Programming Interview Questions | Set 2
Google SWE Interview Experience (Google Online Coding Challenge) 2022
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 86,
"s": 52,
"text": "I was contacted by HR on LinkedIn"
},
{
"code": null,
"e": 150,
"s": 86,
"text": "Round 1(Online Coding Round): Hackerrank platform 1 hour 30 min"
},
{
"code": null,
"e": 732,
"s": 150,
"text": "Given an input string, write a function that returns the Run Length Encoded string for the input string.For example, \nif the input string is “wwwwaaadexxxxxx”, \nthen the function should\nreturn “w4a3d1e1x6”\nExpected Time Complexity: O(n) Let 1 represent ‘A’, 2 represents ‘B’, etc. Given a digit sequence, count the number of possible decoding’s of the given digit sequence.Input: \ndigits[] = \"121\" \nOutput: 3 \nThe possible decoding's are\n \"ABA\", \"AU\", \"LA\"\nInput: \ndigits[] = \"1234\" \nOutput: 3 \nThe possible decoding's are\n \"ABCD\", \"LCD\", \"AWD\"\nExpected Time Complexity: O(n) "
},
{
"code": null,
"e": 970,
"s": 732,
"text": "Given an input string, write a function that returns the Run Length Encoded string for the input string.For example, \nif the input string is “wwwwaaadexxxxxx”, \nthen the function should\nreturn “w4a3d1e1x6”\nExpected Time Complexity: O(n) "
},
{
"code": null,
"e": 1104,
"s": 970,
"text": "For example, \nif the input string is “wwwwaaadexxxxxx”, \nthen the function should\nreturn “w4a3d1e1x6”\nExpected Time Complexity: O(n) "
},
{
"code": null,
"e": 1449,
"s": 1104,
"text": "Let 1 represent ‘A’, 2 represents ‘B’, etc. Given a digit sequence, count the number of possible decoding’s of the given digit sequence.Input: \ndigits[] = \"121\" \nOutput: 3 \nThe possible decoding's are\n \"ABA\", \"AU\", \"LA\"\nInput: \ndigits[] = \"1234\" \nOutput: 3 \nThe possible decoding's are\n \"ABCD\", \"LCD\", \"AWD\"\nExpected Time Complexity: O(n) "
},
{
"code": null,
"e": 1658,
"s": 1449,
"text": "Input: \ndigits[] = \"121\" \nOutput: 3 \nThe possible decoding's are\n \"ABA\", \"AU\", \"LA\"\nInput: \ndigits[] = \"1234\" \nOutput: 3 \nThe possible decoding's are\n \"ABCD\", \"LCD\", \"AWD\"\nExpected Time Complexity: O(n) "
},
{
"code": null,
"e": 1723,
"s": 1658,
"text": "Round 2(F2F Coding Round): CoderPad with Goldman Sachs Developer"
},
{
"code": null,
"e": 2603,
"s": 1723,
"text": "Given an array of strings strings, group the anagrams together. You can return the answer in any order.An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.Input: \nstrs = [\"eat\",\"tea\",\"tan\",\"ate\",\n\"nat\",\"bat\"]\nOutput: \n[[\"bat\"],[\"nat\",\"tan\"],\n[\"ate\",\"eat\",\"tea\"]]\nExpected Time Complexity: O(n) Given a file containing data of student name and marks scored by him/her in 3 subjects. The task is to find the list of students having the maximum average score.If more than one student has the maximum average score, print them as per the order in the file.Input: \nfile[] = {“Shrikanth”, “20”, “30”, \n“10”, “Ram”, “100”, “50”, “10”} \nOutput: \nRam 53 Average scores of Shrikanth, Ram are 20 and 53 respectively. So Ram has the maximum average score of 53.Expected Time Complexity: O(n)"
},
{
"code": null,
"e": 2996,
"s": 2603,
"text": "Given an array of strings strings, group the anagrams together. You can return the answer in any order.An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.Input: \nstrs = [\"eat\",\"tea\",\"tan\",\"ate\",\n\"nat\",\"bat\"]\nOutput: \n[[\"bat\"],[\"nat\",\"tan\"],\n[\"ate\",\"eat\",\"tea\"]]\nExpected Time Complexity: O(n) "
},
{
"code": null,
"e": 3147,
"s": 2996,
"text": "An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once."
},
{
"code": null,
"e": 3287,
"s": 3147,
"text": "Input: \nstrs = [\"eat\",\"tea\",\"tan\",\"ate\",\n\"nat\",\"bat\"]\nOutput: \n[[\"bat\"],[\"nat\",\"tan\"],\n[\"ate\",\"eat\",\"tea\"]]\nExpected Time Complexity: O(n) "
},
{
"code": null,
"e": 3775,
"s": 3287,
"text": "Given a file containing data of student name and marks scored by him/her in 3 subjects. The task is to find the list of students having the maximum average score.If more than one student has the maximum average score, print them as per the order in the file.Input: \nfile[] = {“Shrikanth”, “20”, “30”, \n“10”, “Ram”, “100”, “50”, “10”} \nOutput: \nRam 53 Average scores of Shrikanth, Ram are 20 and 53 respectively. So Ram has the maximum average score of 53.Expected Time Complexity: O(n)"
},
{
"code": null,
"e": 3872,
"s": 3775,
"text": "If more than one student has the maximum average score, print them as per the order in the file."
},
{
"code": null,
"e": 3968,
"s": 3872,
"text": "Input: \nfile[] = {“Shrikanth”, “20”, “30”, \n“10”, “Ram”, “100”, “50”, “10”} \nOutput: \nRam 53 "
},
{
"code": null,
"e": 4073,
"s": 3968,
"text": "Average scores of Shrikanth, Ram are 20 and 53 respectively. So Ram has the maximum average score of 53."
},
{
"code": null,
"e": 4104,
"s": 4073,
"text": "Expected Time Complexity: O(n)"
},
{
"code": null,
"e": 4182,
"s": 4104,
"text": "Round 3(F2F Coding Round on Zoom): CoderPad with two Goldman Sachs Developers"
},
{
"code": null,
"e": 5051,
"s": 4182,
"text": "Given a linked list, write a function to reverse every k nodes (where k is an input to the function).Input: \n1->2->3->4->5->6->7->8->NULL, K = 3 \nOutput: \n3->2->1->6->5->4->8->7->NULL \nExpected Time Complexity: O(n) \nAuxiliary Space: O(n/k). Given a Binary Search Tree (BST) and a positive integer k, find the k’th largest element in the Binary Search Tree.Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure and no other data structure like arrays, list, .. etc.Example: \nConsider the following\nSpecialStack\n16 --> TOP\n15\n29\n19\n18\nWhen getMin() is called it\nshould return 15, "
},
{
"code": null,
"e": 5295,
"s": 5051,
"text": "Given a linked list, write a function to reverse every k nodes (where k is an input to the function).Input: \n1->2->3->4->5->6->7->8->NULL, K = 3 \nOutput: \n3->2->1->6->5->4->8->7->NULL \nExpected Time Complexity: O(n) \nAuxiliary Space: O(n/k). "
},
{
"code": null,
"e": 5438,
"s": 5295,
"text": "Input: \n1->2->3->4->5->6->7->8->NULL, K = 3 \nOutput: \n3->2->1->6->5->4->8->7->NULL \nExpected Time Complexity: O(n) \nAuxiliary Space: O(n/k). "
},
{
"code": null,
"e": 5554,
"s": 5438,
"text": "Given a Binary Search Tree (BST) and a positive integer k, find the k’th largest element in the Binary Search Tree."
},
{
"code": null,
"e": 6065,
"s": 5554,
"text": "Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure and no other data structure like arrays, list, .. etc.Example: \nConsider the following\nSpecialStack\n16 --> TOP\n15\n29\n19\n18\nWhen getMin() is called it\nshould return 15, "
},
{
"code": null,
"e": 6182,
"s": 6065,
"text": "Example: \nConsider the following\nSpecialStack\n16 --> TOP\n15\n29\n19\n18\nWhen getMin() is called it\nshould return 15, "
},
{
"code": null,
"e": 6260,
"s": 6182,
"text": "Round 4(F2F Coding Round on Zoom): CoderPad with two Goldman Sachs Developers"
},
{
"code": null,
"e": 7192,
"s": 6260,
"text": "Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that sorting this subarray makes the whole array sorted.Example: If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the subarray lies between indexes 3 and 8.Given a binary array, in which, moving an element from index i to index j requires abs(i – j) cost. The task is to find the cost to move all 1s to each index of the given array.Input: \narr[] = {0, 1, 0, 1}\nOutput: \n4 2 2 2Explanation:Moving elements from index 1, index 3 to index 0 requires abs(0 – 1) + abs(0 – 3) = 4.Moving elements from index 1, index 3 to index 1 requires abs(1 – 1) + abs(1 – 3) = 2.Moving elements from index 1, index 2 to index 2 requires abs(2 – 1) + abs(2 – 3) = 2.Moving elements from index 1, index 2 to index 3 requires abs(3 – 1) + abs(3 – 3) = 2.Therefore, the required output is 4 2 2 2."
},
{
"code": null,
"e": 7504,
"s": 7192,
"text": "Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that sorting this subarray makes the whole array sorted.Example: If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the subarray lies between indexes 3 and 8."
},
{
"code": null,
"e": 7665,
"s": 7504,
"text": "Example: If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the subarray lies between indexes 3 and 8."
},
{
"code": null,
"e": 8286,
"s": 7665,
"text": "Given a binary array, in which, moving an element from index i to index j requires abs(i – j) cost. The task is to find the cost to move all 1s to each index of the given array.Input: \narr[] = {0, 1, 0, 1}\nOutput: \n4 2 2 2Explanation:Moving elements from index 1, index 3 to index 0 requires abs(0 – 1) + abs(0 – 3) = 4.Moving elements from index 1, index 3 to index 1 requires abs(1 – 1) + abs(1 – 3) = 2.Moving elements from index 1, index 2 to index 2 requires abs(2 – 1) + abs(2 – 3) = 2.Moving elements from index 1, index 2 to index 3 requires abs(3 – 1) + abs(3 – 3) = 2.Therefore, the required output is 4 2 2 2."
},
{
"code": null,
"e": 8332,
"s": 8286,
"text": "Input: \narr[] = {0, 1, 0, 1}\nOutput: \n4 2 2 2"
},
{
"code": null,
"e": 8345,
"s": 8332,
"text": "Explanation:"
},
{
"code": null,
"e": 8432,
"s": 8345,
"text": "Moving elements from index 1, index 3 to index 0 requires abs(0 – 1) + abs(0 – 3) = 4."
},
{
"code": null,
"e": 8519,
"s": 8432,
"text": "Moving elements from index 1, index 3 to index 1 requires abs(1 – 1) + abs(1 – 3) = 2."
},
{
"code": null,
"e": 8606,
"s": 8519,
"text": "Moving elements from index 1, index 2 to index 2 requires abs(2 – 1) + abs(2 – 3) = 2."
},
{
"code": null,
"e": 8693,
"s": 8606,
"text": "Moving elements from index 1, index 2 to index 3 requires abs(3 – 1) + abs(3 – 3) = 2."
},
{
"code": null,
"e": 8736,
"s": 8693,
"text": "Therefore, the required output is 4 2 2 2."
},
{
"code": null,
"e": 8814,
"s": 8736,
"text": "Round 5(F2F Coding Round on Zoom): CoderPad with two Goldman Sachs Developers"
},
{
"code": null,
"e": 9972,
"s": 8814,
"text": "Problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.The expected output is a binary matrix which has 1s for the blocks where queens are placed.For example, following is the output matrix for above 4 queen solution.{ 0, 1, 0, 0}\n{ 0, 0, 0, 1}\n{ 1, 0, 0, 0}\n{ 0, 0, 1, 0}Solution: Use Recursion and BacktrackingImplement a SnapshotArray that supports the following interface:SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0.void set(index, val) sets the element at the given index to be equal to val.int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_idSolution: Use the 2D Array of class Node , the 1D is used to store the indices and 2D is used to store the snap shots. For each index to get the value at particular snap id , we can use binary search as the snap array in each index will be sorted and Complexity of get Operation reduces to log(N)"
},
{
"code": null,
"e": 10337,
"s": 9972,
"text": "Problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.The expected output is a binary matrix which has 1s for the blocks where queens are placed.For example, following is the output matrix for above 4 queen solution.{ 0, 1, 0, 0}\n{ 0, 0, 0, 1}\n{ 1, 0, 0, 0}\n{ 0, 0, 1, 0}Solution: Use Recursion and Backtracking"
},
{
"code": null,
"e": 10429,
"s": 10337,
"text": "The expected output is a binary matrix which has 1s for the blocks where queens are placed."
},
{
"code": null,
"e": 10501,
"s": 10429,
"text": "For example, following is the output matrix for above 4 queen solution."
},
{
"code": null,
"e": 10569,
"s": 10501,
"text": "{ 0, 1, 0, 0}\n{ 0, 0, 0, 1}\n{ 1, 0, 0, 0}\n{ 0, 0, 1, 0}"
},
{
"code": null,
"e": 10610,
"s": 10569,
"text": "Solution: Use Recursion and Backtracking"
},
{
"code": null,
"e": 11404,
"s": 10610,
"text": "Implement a SnapshotArray that supports the following interface:SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0.void set(index, val) sets the element at the given index to be equal to val.int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_idSolution: Use the 2D Array of class Node , the 1D is used to store the indices and 2D is used to store the snap shots. For each index to get the value at particular snap id , we can use binary search as the snap array in each index will be sorted and Complexity of get Operation reduces to log(N)"
},
{
"code": null,
"e": 11528,
"s": 11404,
"text": "SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0."
},
{
"code": null,
"e": 11605,
"s": 11528,
"text": "void set(index, val) sets the element at the given index to be equal to val."
},
{
"code": null,
"e": 11723,
"s": 11605,
"text": "int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1."
},
{
"code": null,
"e": 11841,
"s": 11723,
"text": "int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id"
},
{
"code": null,
"e": 12138,
"s": 11841,
"text": "Solution: Use the 2D Array of class Node , the 1D is used to store the indices and 2D is used to store the snap shots. For each index to get the value at particular snap id , we can use binary search as the snap array in each index will be sorted and Complexity of get Operation reduces to log(N)"
},
{
"code": null,
"e": 12216,
"s": 12138,
"text": "Round 6(F2F Coding Round on Zoom): CoderPad with two Goldman Sachs Developers"
},
{
"code": null,
"e": 12287,
"s": 12216,
"text": "https://www.hackerrank.com/challenges/connected-cell-in-a-grid/problem"
},
{
"code": null,
"e": 12358,
"s": 12287,
"text": "https://www.hackerrank.com/challenges/connected-cell-in-a-grid/problem"
},
{
"code": null,
"e": 12436,
"s": 12358,
"text": "Round 7(F2F Coding Round on Zoom): CoderPad with two Goldman Sachs Developers"
},
{
"code": null,
"e": 12825,
"s": 12436,
"text": "Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same.Expected time complexity is O(n) and extra space is O(1).Some string-related basics and Strings in java and Python."
},
{
"code": null,
"e": 13156,
"s": 12825,
"text": "Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same.Expected time complexity is O(n) and extra space is O(1)."
},
{
"code": null,
"e": 13214,
"s": 13156,
"text": "Expected time complexity is O(n) and extra space is O(1)."
},
{
"code": null,
"e": 13273,
"s": 13214,
"text": "Some string-related basics and Strings in java and Python."
},
{
"code": null,
"e": 13344,
"s": 13273,
"text": "Round 8(F2F Round on Zoom): CoderPad with two Goldman Sachs Developers"
},
{
"code": null,
"e": 13561,
"s": 13344,
"text": "Few Questions on my recent projects, technologies I have worked on, and Cache Evacuation policies.Introduction to Customer wealth Management (CWM Goldman Sachs) Team, the products, and the Tech stacks Goldman’s uses."
},
{
"code": null,
"e": 13660,
"s": 13561,
"text": "Few Questions on my recent projects, technologies I have worked on, and Cache Evacuation policies."
},
{
"code": null,
"e": 13779,
"s": 13660,
"text": "Introduction to Customer wealth Management (CWM Goldman Sachs) Team, the products, and the Tech stacks Goldman’s uses."
},
{
"code": null,
"e": 13856,
"s": 13779,
"text": "After these rounds Finally I got a mail from HR for compensation discussion."
},
{
"code": null,
"e": 13870,
"s": 13856,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 13880,
"s": 13870,
"text": "Marketing"
},
{
"code": null,
"e": 13892,
"s": 13880,
"text": "Experienced"
},
{
"code": null,
"e": 13914,
"s": 13892,
"text": "Interview Experiences"
},
{
"code": null,
"e": 13928,
"s": 13914,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 14026,
"s": 13928,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14082,
"s": 14026,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 14167,
"s": 14082,
"text": "Google Interview Experience for Software Engineer L3 Bangalore (6 Years Experienced)"
},
{
"code": null,
"e": 14214,
"s": 14167,
"text": "SAMSUNG R&D Interview Experience for Team Lead"
},
{
"code": null,
"e": 14283,
"s": 14214,
"text": "Adobe Interview Experience for MTS-1 (Off-Campus) 1 Year Experienced"
},
{
"code": null,
"e": 14346,
"s": 14283,
"text": "Nagarro Interview Experience | Set 7 (For 2 Years Experienced)"
},
{
"code": null,
"e": 14373,
"s": 14346,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 14411,
"s": 14373,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 14484,
"s": 14411,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 14544,
"s": 14484,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
}
] |
How to use ToggleButtonGroup Component in ReactJS ?
|
08 Apr, 2021
Whenever the user wants to group a related option, the ToggleButtonGroup component is used. Material UI for ReactJS has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to use ToggleButtonGroup component.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui module using the following command:
npm install @material-ui/core
npm install @material-ui/icons
npm install @material-ui/labs
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import ToggleButton from '@material-ui/lab/ToggleButton';import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup';import FormatAlignLeftIcon from '@material-ui/icons/FormatAlignLeft';import FormatAlignJustifyIcon from '@material-ui/icons/FormatAlignJustify';import FormatAlignCenterIcon from '@material-ui/icons/FormatAlignCenter'; export default function App() { const [currentAlignment, setCurrentAlignment] = React.useState('center'); return ( <div style={{ display: 'block', padding: 30 }}> <h4>How to use ToggleGroup Component in ReactJS?</h4> <ToggleButtonGroup value={currentAlignment} onChange={(event, newAlignment) => { setCurrentAlignment(newAlignment); }} exclusive aria-label="Demo Text Alignment" > <ToggleButton value="justify" aria-label="justified" disabled> <FormatAlignJustifyIcon /> </ToggleButton> <ToggleButton value="left" aria-label="left aligned"> <FormatAlignLeftIcon /> </ToggleButton> <ToggleButton value="center" aria-label="centered"> <FormatAlignCenterIcon /> </ToggleButton> </ToggleButtonGroup> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://material-ui.com/components/toggle-button/#toggle-buttons
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to do crud operations in ReactJS ?
How to create a multi-page website using React.js ?
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?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 296,
"s": 28,
"text": "Whenever the user wants to group a related option, the ToggleButtonGroup component is used. Material UI for ReactJS has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to use ToggleButtonGroup component."
},
{
"code": null,
"e": 346,
"s": 296,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 410,
"s": 346,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 442,
"s": 410,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 542,
"s": 442,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 556,
"s": 542,
"text": "cd foldername"
},
{
"code": null,
"e": 664,
"s": 556,
"text": "Step 3: After creating the ReactJS application, Install the material-ui module using the following command:"
},
{
"code": null,
"e": 755,
"s": 664,
"text": "npm install @material-ui/core\nnpm install @material-ui/icons\nnpm install @material-ui/labs"
},
{
"code": null,
"e": 807,
"s": 755,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 825,
"s": 807,
"text": "Project Structure"
},
{
"code": null,
"e": 955,
"s": 825,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 962,
"s": 955,
"text": "App.js"
},
{
"code": "import React from 'react';import ToggleButton from '@material-ui/lab/ToggleButton';import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup';import FormatAlignLeftIcon from '@material-ui/icons/FormatAlignLeft';import FormatAlignJustifyIcon from '@material-ui/icons/FormatAlignJustify';import FormatAlignCenterIcon from '@material-ui/icons/FormatAlignCenter'; export default function App() { const [currentAlignment, setCurrentAlignment] = React.useState('center'); return ( <div style={{ display: 'block', padding: 30 }}> <h4>How to use ToggleGroup Component in ReactJS?</h4> <ToggleButtonGroup value={currentAlignment} onChange={(event, newAlignment) => { setCurrentAlignment(newAlignment); }} exclusive aria-label=\"Demo Text Alignment\" > <ToggleButton value=\"justify\" aria-label=\"justified\" disabled> <FormatAlignJustifyIcon /> </ToggleButton> <ToggleButton value=\"left\" aria-label=\"left aligned\"> <FormatAlignLeftIcon /> </ToggleButton> <ToggleButton value=\"center\" aria-label=\"centered\"> <FormatAlignCenterIcon /> </ToggleButton> </ToggleButtonGroup> </div> );}",
"e": 2211,
"s": 962,
"text": null
},
{
"code": null,
"e": 2324,
"s": 2211,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2334,
"s": 2324,
"text": "npm start"
},
{
"code": null,
"e": 2433,
"s": 2334,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2509,
"s": 2433,
"text": "Reference: https://material-ui.com/components/toggle-button/#toggle-buttons"
},
{
"code": null,
"e": 2521,
"s": 2509,
"text": "Material-UI"
},
{
"code": null,
"e": 2537,
"s": 2521,
"text": "React-Questions"
},
{
"code": null,
"e": 2545,
"s": 2537,
"text": "ReactJS"
},
{
"code": null,
"e": 2562,
"s": 2545,
"text": "Web Technologies"
},
{
"code": null,
"e": 2660,
"s": 2562,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2698,
"s": 2660,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 2725,
"s": 2698,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 2764,
"s": 2725,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 2803,
"s": 2764,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 2855,
"s": 2803,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 2888,
"s": 2855,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2950,
"s": 2888,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3011,
"s": 2950,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3061,
"s": 3011,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to set a click event once a page or view is loaded in vue.js?
|
22 Jan, 2021
In this article, we will discuss how to set a click event once a page or view is loaded in vue.js. Just like every other JavaScript framework Vue also supports the Mounting hooks. Mounting hooks are often the most used hooks. They allow us to access or modify the DOM of your component just before or after the first render.
So, here we will use the mounted hook to trigger a click event when the page is loaded.
Step to setup the Environment:
First, we should install vue.js by using the command below:sudo npm install -g @vue/cliAfter, installing the vue.js. you can create a new project by using the command below:vue create testNow, Go to your project folder by usingcd myappYou can run your project using the command below:npm run serve
First, we should install vue.js by using the command below:sudo npm install -g @vue/cli
First, we should install vue.js by using the command below:
sudo npm install -g @vue/cli
After, installing the vue.js. you can create a new project by using the command below:vue create test
After, installing the vue.js. you can create a new project by using the command below:
vue create test
Now, Go to your project folder by usingcd myapp
Now, Go to your project folder by using
cd myapp
You can run your project using the command below:npm run serve
You can run your project using the command below:
npm run serve
The file structure of your project will look like this:
Syntax
Step-1: Give a reference to the button you want to click.<button ref="Btn" @click="logClicked">Click</button>
<button ref="Btn" @click="logClicked">Click</button>
Step-2: In the mounted hook trigger the button click.mounted () {
this.$refs.Btn.click()
}
mounted () {
this.$refs.Btn.click()
}
Example: Open your App.vue file from the test project src folder and update the code.
Javascript
<script>export default({ methods: { logClicked () { console.log('Clicked') } }, mounted () { this.$refs.Btn.click() }})</script><template><div id="app" class="container"> <button ref="Btn" @click="logClicked">Click</button></div></template>
OutputFor can see the output in chrome by typing localhost:8080 also open the console in your Chrome browser by using the command below
ctrl+shift+j
Picked
Technical Scripter 2020
Vue.JS
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jan, 2021"
},
{
"code": null,
"e": 354,
"s": 28,
"text": "In this article, we will discuss how to set a click event once a page or view is loaded in vue.js. Just like every other JavaScript framework Vue also supports the Mounting hooks. Mounting hooks are often the most used hooks. They allow us to access or modify the DOM of your component just before or after the first render. "
},
{
"code": null,
"e": 442,
"s": 354,
"text": "So, here we will use the mounted hook to trigger a click event when the page is loaded."
},
{
"code": null,
"e": 473,
"s": 442,
"text": "Step to setup the Environment:"
},
{
"code": null,
"e": 771,
"s": 473,
"text": "First, we should install vue.js by using the command below:sudo npm install -g @vue/cliAfter, installing the vue.js. you can create a new project by using the command below:vue create testNow, Go to your project folder by usingcd myappYou can run your project using the command below:npm run serve"
},
{
"code": null,
"e": 859,
"s": 771,
"text": "First, we should install vue.js by using the command below:sudo npm install -g @vue/cli"
},
{
"code": null,
"e": 919,
"s": 859,
"text": "First, we should install vue.js by using the command below:"
},
{
"code": null,
"e": 948,
"s": 919,
"text": "sudo npm install -g @vue/cli"
},
{
"code": null,
"e": 1050,
"s": 948,
"text": "After, installing the vue.js. you can create a new project by using the command below:vue create test"
},
{
"code": null,
"e": 1137,
"s": 1050,
"text": "After, installing the vue.js. you can create a new project by using the command below:"
},
{
"code": null,
"e": 1153,
"s": 1137,
"text": "vue create test"
},
{
"code": null,
"e": 1201,
"s": 1153,
"text": "Now, Go to your project folder by usingcd myapp"
},
{
"code": null,
"e": 1241,
"s": 1201,
"text": "Now, Go to your project folder by using"
},
{
"code": null,
"e": 1250,
"s": 1241,
"text": "cd myapp"
},
{
"code": null,
"e": 1313,
"s": 1250,
"text": "You can run your project using the command below:npm run serve"
},
{
"code": null,
"e": 1363,
"s": 1313,
"text": "You can run your project using the command below:"
},
{
"code": null,
"e": 1377,
"s": 1363,
"text": "npm run serve"
},
{
"code": null,
"e": 1433,
"s": 1377,
"text": "The file structure of your project will look like this:"
},
{
"code": null,
"e": 1440,
"s": 1433,
"text": "Syntax"
},
{
"code": null,
"e": 1550,
"s": 1440,
"text": "Step-1: Give a reference to the button you want to click.<button ref=\"Btn\" @click=\"logClicked\">Click</button>"
},
{
"code": null,
"e": 1603,
"s": 1550,
"text": "<button ref=\"Btn\" @click=\"logClicked\">Click</button>"
},
{
"code": null,
"e": 1696,
"s": 1603,
"text": "Step-2: In the mounted hook trigger the button click.mounted () {\n this.$refs.Btn.click()\n}"
},
{
"code": null,
"e": 1736,
"s": 1696,
"text": "mounted () {\n this.$refs.Btn.click()\n}"
},
{
"code": null,
"e": 1822,
"s": 1736,
"text": "Example: Open your App.vue file from the test project src folder and update the code."
},
{
"code": null,
"e": 1833,
"s": 1822,
"text": "Javascript"
},
{
"code": "<script>export default({ methods: { logClicked () { console.log('Clicked') } }, mounted () { this.$refs.Btn.click() }})</script><template><div id=\"app\" class=\"container\"> <button ref=\"Btn\" @click=\"logClicked\">Click</button></div></template>",
"e": 2095,
"s": 1833,
"text": null
},
{
"code": null,
"e": 2231,
"s": 2095,
"text": "OutputFor can see the output in chrome by typing localhost:8080 also open the console in your Chrome browser by using the command below"
},
{
"code": null,
"e": 2245,
"s": 2231,
"text": " ctrl+shift+j"
},
{
"code": null,
"e": 2252,
"s": 2245,
"text": "Picked"
},
{
"code": null,
"e": 2276,
"s": 2252,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2283,
"s": 2276,
"text": "Vue.JS"
},
{
"code": null,
"e": 2294,
"s": 2283,
"text": "JavaScript"
},
{
"code": null,
"e": 2313,
"s": 2294,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2330,
"s": 2313,
"text": "Web Technologies"
}
] |
How to Implement Stack in Java Using Array and Generics?
|
13 Oct, 2021
Stack is a linear Data Structure that is based on the LIFO concept (last in first out). Instead of only an Integer Stack, Stack can be of String, Character, or even Float type. There are 4 primary operations in the stack as follows:
push() Method adds element x to the stack.pop() Method removes the last element of the stack.top() Method returns the last element of the stack.empty() Method returns whether the stack is empty or not.
push() Method adds element x to the stack.
pop() Method removes the last element of the stack.
top() Method returns the last element of the stack.
empty() Method returns whether the stack is empty or not.
Note: Time Complexity is of order 1 for all operations of the stack
Illustration:
Stack 1
let s = empty stack of Integer type with size 4
Stack 2
push (100) : top = top + 1 and s[top] = 100
Stack 3
push (200) : top = top + 1 and s[top] = 200
Stack 4
push (300) : top = top + 1 and s[top] = 300
Stack 5
pop ( ) : top = top - 1
Stack 6
push (500) : top = top + 1 and s[top] = 500
Stack 7
push (600) : top = top + 1 and s[top] = 600
Note:
push (700) : top +1 == size of stack : Stack Overflow !
// Since top = 3 and size of stack = 4, no more elements can be pushed
Implementation:
Example
Java
// Java Program to Implement Stack in Java Using Array and// Generics // Importing input output classesimport java.io.*;// Importing all utility classesimport java.util.*; // user defined class for generic stackclass stack<T> { // Empty array list ArrayList<T> A; // Default value of top variable when stack is empty int top = -1; // Variable to store size of array int size; // Constructor of this class // To initialize stack stack(int size) { // Storing the value of size into global variable this.size = size; // Creating array of Size = size this.A = new ArrayList<T>(size); } // Method 1 // To push generic element into stack void push(T X) { // Checking if array is full if (top + 1 == size) { // Display message when array is full System.out.println("Stack Overflow"); } else { // Increment top to go to next position top = top + 1; // Over-writing existing element if (A.size() > top) A.set(top, X); else // Creating new element A.add(X); } } // Method 2 // To return topmost element of stack T top() { // If stack is empty if (top == -1) { // Display message when there are no elements in // the stack System.out.println("Stack Underflow"); return null; } // else elements are present so // return the topmost element else return A.get(top); } // Method 3 // To delete last element of stack void pop() { // If stack is empty if (top == -1) { // Display message when there are no elements in // the stack System.out.println("Stack Underflow"); } else // Delete the last element // by decrementing the top top--; } // Method 4 // To check if stack is empty or not boolean empty() { return top == -1; } // Method 5 // To print the stack // @Override public String toString() { String Ans = ""; for (int i = 0; i < top; i++) { Ans += String.valueOf(A.get(i)) + "->"; } Ans += String.valueOf(A.get(top)); return Ans; }}// Main Classpublic class GFG { // main driver method public static void main(String[] args) { // Integer Stack // Creating an object of Stack class // Declaring objects of Integer type stack<Integer> s1 = new stack<>(3); // Pushing elements to integer stack - s1 // Element 1 - 10 s1.push(10); // Element 2 - 20 s1.push(20); // Element 3 - 30 s1.push(30); // Print the stack elements after pushing the // elements System.out.println( "s1 after pushing 10, 20 and 30 :\n" + s1); // Now, pop from stack s1 s1.pop(); // Print the stack elements after poping few // element/s System.out.println("s1 after pop :\n" + s1); // String Stack // Creating an object of Stack class // Declaring objects of Integer type stack<String> s2 = new stack<>(3); // Pushing elements to string stack - s2 // Element 1 - hello s2.push("hello"); // Element 2 - world s2.push("world"); // Element 3 - java s2.push("java"); // Print string stack after pushing above string // elements System.out.println( "\ns2 after pushing 3 elements :\n" + s2); System.out.println( "s2 after pushing 4th element :"); // Pushing another element to above stack // Element 4 - GFG s2.push("GFG"); // Float stack // Creating an object of Stack class // Declaring objects of Integer type stack<Float> s3 = new stack<>(2); // Pushing elements to float stack - s3 // Element 1 - 100.0 s3.push(100.0f); // Element 2 - 200.0 s3.push(200.0f); // Print string stack after pushing above float // elements System.out.println( "\ns3 after pushing 2 elements :\n" + s3); // Print and display top element of stack s3 System.out.println("top element of s3:\n" + s3.top()); }}
s1 after pushing 10, 20 and 30 :
10->20->30
s1 after pop :
10->20
s2 after pushing 3 elements :
hello->world->java
s2 after pushing 4th element :
Stack Overflow
s3 after pushing 2 elements :
100.0->200.0
top element of s3:
200.0
gabaa406
syedmuazzamsiddiqhi
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 285,
"s": 52,
"text": "Stack is a linear Data Structure that is based on the LIFO concept (last in first out). Instead of only an Integer Stack, Stack can be of String, Character, or even Float type. There are 4 primary operations in the stack as follows:"
},
{
"code": null,
"e": 487,
"s": 285,
"text": "push() Method adds element x to the stack.pop() Method removes the last element of the stack.top() Method returns the last element of the stack.empty() Method returns whether the stack is empty or not."
},
{
"code": null,
"e": 530,
"s": 487,
"text": "push() Method adds element x to the stack."
},
{
"code": null,
"e": 582,
"s": 530,
"text": "pop() Method removes the last element of the stack."
},
{
"code": null,
"e": 634,
"s": 582,
"text": "top() Method returns the last element of the stack."
},
{
"code": null,
"e": 692,
"s": 634,
"text": "empty() Method returns whether the stack is empty or not."
},
{
"code": null,
"e": 761,
"s": 692,
"text": "Note: Time Complexity is of order 1 for all operations of the stack "
},
{
"code": null,
"e": 775,
"s": 761,
"text": "Illustration:"
},
{
"code": null,
"e": 783,
"s": 775,
"text": "Stack 1"
},
{
"code": null,
"e": 831,
"s": 783,
"text": "let s = empty stack of Integer type with size 4"
},
{
"code": null,
"e": 839,
"s": 831,
"text": "Stack 2"
},
{
"code": null,
"e": 884,
"s": 839,
"text": "push (100) : top = top + 1 and s[top] = 100 "
},
{
"code": null,
"e": 892,
"s": 884,
"text": "Stack 3"
},
{
"code": null,
"e": 936,
"s": 892,
"text": "push (200) : top = top + 1 and s[top] = 200"
},
{
"code": null,
"e": 944,
"s": 936,
"text": "Stack 4"
},
{
"code": null,
"e": 989,
"s": 944,
"text": " push (300) : top = top + 1 and s[top] = 300"
},
{
"code": null,
"e": 997,
"s": 989,
"text": "Stack 5"
},
{
"code": null,
"e": 1022,
"s": 997,
"text": "pop ( ) : top = top - 1"
},
{
"code": null,
"e": 1030,
"s": 1022,
"text": "Stack 6"
},
{
"code": null,
"e": 1074,
"s": 1030,
"text": "push (500) : top = top + 1 and s[top] = 500"
},
{
"code": null,
"e": 1082,
"s": 1074,
"text": "Stack 7"
},
{
"code": null,
"e": 1126,
"s": 1082,
"text": "push (600) : top = top + 1 and s[top] = 600"
},
{
"code": null,
"e": 1132,
"s": 1126,
"text": "Note:"
},
{
"code": null,
"e": 1261,
"s": 1132,
"text": "push (700) : top +1 == size of stack : Stack Overflow ! \n// Since top = 3 and size of stack = 4, no more elements can be pushed"
},
{
"code": null,
"e": 1277,
"s": 1261,
"text": "Implementation:"
},
{
"code": null,
"e": 1285,
"s": 1277,
"text": "Example"
},
{
"code": null,
"e": 1290,
"s": 1285,
"text": "Java"
},
{
"code": "// Java Program to Implement Stack in Java Using Array and// Generics // Importing input output classesimport java.io.*;// Importing all utility classesimport java.util.*; // user defined class for generic stackclass stack<T> { // Empty array list ArrayList<T> A; // Default value of top variable when stack is empty int top = -1; // Variable to store size of array int size; // Constructor of this class // To initialize stack stack(int size) { // Storing the value of size into global variable this.size = size; // Creating array of Size = size this.A = new ArrayList<T>(size); } // Method 1 // To push generic element into stack void push(T X) { // Checking if array is full if (top + 1 == size) { // Display message when array is full System.out.println(\"Stack Overflow\"); } else { // Increment top to go to next position top = top + 1; // Over-writing existing element if (A.size() > top) A.set(top, X); else // Creating new element A.add(X); } } // Method 2 // To return topmost element of stack T top() { // If stack is empty if (top == -1) { // Display message when there are no elements in // the stack System.out.println(\"Stack Underflow\"); return null; } // else elements are present so // return the topmost element else return A.get(top); } // Method 3 // To delete last element of stack void pop() { // If stack is empty if (top == -1) { // Display message when there are no elements in // the stack System.out.println(\"Stack Underflow\"); } else // Delete the last element // by decrementing the top top--; } // Method 4 // To check if stack is empty or not boolean empty() { return top == -1; } // Method 5 // To print the stack // @Override public String toString() { String Ans = \"\"; for (int i = 0; i < top; i++) { Ans += String.valueOf(A.get(i)) + \"->\"; } Ans += String.valueOf(A.get(top)); return Ans; }}// Main Classpublic class GFG { // main driver method public static void main(String[] args) { // Integer Stack // Creating an object of Stack class // Declaring objects of Integer type stack<Integer> s1 = new stack<>(3); // Pushing elements to integer stack - s1 // Element 1 - 10 s1.push(10); // Element 2 - 20 s1.push(20); // Element 3 - 30 s1.push(30); // Print the stack elements after pushing the // elements System.out.println( \"s1 after pushing 10, 20 and 30 :\\n\" + s1); // Now, pop from stack s1 s1.pop(); // Print the stack elements after poping few // element/s System.out.println(\"s1 after pop :\\n\" + s1); // String Stack // Creating an object of Stack class // Declaring objects of Integer type stack<String> s2 = new stack<>(3); // Pushing elements to string stack - s2 // Element 1 - hello s2.push(\"hello\"); // Element 2 - world s2.push(\"world\"); // Element 3 - java s2.push(\"java\"); // Print string stack after pushing above string // elements System.out.println( \"\\ns2 after pushing 3 elements :\\n\" + s2); System.out.println( \"s2 after pushing 4th element :\"); // Pushing another element to above stack // Element 4 - GFG s2.push(\"GFG\"); // Float stack // Creating an object of Stack class // Declaring objects of Integer type stack<Float> s3 = new stack<>(2); // Pushing elements to float stack - s3 // Element 1 - 100.0 s3.push(100.0f); // Element 2 - 200.0 s3.push(200.0f); // Print string stack after pushing above float // elements System.out.println( \"\\ns3 after pushing 2 elements :\\n\" + s3); // Print and display top element of stack s3 System.out.println(\"top element of s3:\\n\" + s3.top()); }}",
"e": 5746,
"s": 1290,
"text": null
},
{
"code": null,
"e": 5980,
"s": 5749,
"text": "s1 after pushing 10, 20 and 30 :\n10->20->30\ns1 after pop :\n10->20\n\ns2 after pushing 3 elements :\nhello->world->java\ns2 after pushing 4th element :\nStack Overflow\n\ns3 after pushing 2 elements :\n100.0->200.0\ntop element of s3:\n200.0"
},
{
"code": null,
"e": 5991,
"s": 5982,
"text": "gabaa406"
},
{
"code": null,
"e": 6011,
"s": 5991,
"text": "syedmuazzamsiddiqhi"
},
{
"code": null,
"e": 6018,
"s": 6011,
"text": "Picked"
},
{
"code": null,
"e": 6023,
"s": 6018,
"text": "Java"
},
{
"code": null,
"e": 6037,
"s": 6023,
"text": "Java Programs"
},
{
"code": null,
"e": 6042,
"s": 6037,
"text": "Java"
},
{
"code": null,
"e": 6140,
"s": 6042,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6155,
"s": 6140,
"text": "Stream In Java"
},
{
"code": null,
"e": 6176,
"s": 6155,
"text": "Introduction to Java"
},
{
"code": null,
"e": 6197,
"s": 6176,
"text": "Constructors in Java"
},
{
"code": null,
"e": 6216,
"s": 6197,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 6233,
"s": 6216,
"text": "Generics in Java"
},
{
"code": null,
"e": 6259,
"s": 6233,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 6293,
"s": 6259,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 6340,
"s": 6293,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 6378,
"s": 6340,
"text": "Factory method design pattern in Java"
}
] |
implicitly_wait driver method – Selenium Python
|
15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around implicitly_wait driver method in Selenium. implicitly_wait method sets a sticky timeout to implicitly wait for an element to be found, or a command to complete. This method only needs to be called one time per session. To set the timeout for calls to execute_async_script, see set_script_timeout.
Syntax –
driver.implicitly_wait(time_to_wait)
Example –Now one can use implicitly_wait method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.implicitly_wait(30)
To demonstrate, implicitly_wait method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s set wait time to 30.
Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # set wait timedriver.implicitly_wait(30)
Output –Screenshot added –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 767,
"s": 28,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc."
},
{
"code": null,
"e": 1093,
"s": 767,
"text": "This article revolves around implicitly_wait driver method in Selenium. implicitly_wait method sets a sticky timeout to implicitly wait for an element to be found, or a command to complete. This method only needs to be called one time per session. To set the timeout for calls to execute_async_script, see set_script_timeout."
},
{
"code": null,
"e": 1102,
"s": 1093,
"text": "Syntax –"
},
{
"code": null,
"e": 1139,
"s": 1102,
"text": "driver.implicitly_wait(time_to_wait)"
},
{
"code": null,
"e": 1217,
"s": 1139,
"text": "Example –Now one can use implicitly_wait method as a driver method as below –"
},
{
"code": null,
"e": 1289,
"s": 1217,
"text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.implicitly_wait(30)\n"
},
{
"code": null,
"e": 1462,
"s": 1289,
"text": "To demonstrate, implicitly_wait method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s set wait time to 30."
},
{
"code": null,
"e": 1472,
"s": 1462,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # set wait timedriver.implicitly_wait(30)",
"e": 1690,
"s": 1472,
"text": null
},
{
"code": null,
"e": 1717,
"s": 1690,
"text": "Output –Screenshot added –"
},
{
"code": null,
"e": 1733,
"s": 1717,
"text": "Python-selenium"
},
{
"code": null,
"e": 1742,
"s": 1733,
"text": "selenium"
},
{
"code": null,
"e": 1749,
"s": 1742,
"text": "Python"
},
{
"code": null,
"e": 1847,
"s": 1749,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1879,
"s": 1847,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1906,
"s": 1879,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1927,
"s": 1906,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1950,
"s": 1927,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1981,
"s": 1950,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2037,
"s": 1981,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2079,
"s": 2037,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2121,
"s": 2079,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2160,
"s": 2121,
"text": "Python | Get unique values from a list"
}
] |
WTF is Sensor Fusion? The good old Kalman filter | by Marko Cotra | Towards Data Science
|
In my previous post in this series I talked about the two equations that are used for essentially all sensor fusion algorithms: the predict and update equations. I did not however showcase any practical algorithm that makes the equations analytically tractable. So, in this post I’ll explain perhaps the most famous and well-known algorithm — the Kalman filter.
Even though it’s in many ways a simple algorithm it can still take some time to build up intuition around how it actually works. Having good intuition is important, since correctly tuning a Kalman filter isn’t all that easy sometimes.
Let’s quickly summarize what sensor fusion is all about, including the predict and update equations. In order to do this we’ll revisit the airplane example first presented in part 1 of this series. If you feel lost then I strongly recommend that you read through it.
Okay. We’re using a radar sensor to track an airplane over time. We’re interested in learning about the state x_k of the plane, where k denotes the time-step. The state contains the dynamic properties of the airplane that we’re interested in estimating. This could for example be position, velocity, roll, yaw and so on.
We have some knowledge of the dynamics of the airplane between time-steps, which we represent as a motion model. However, there is uncertainty in the model, which is why we view it as a probability distribution
Expressed in words, the model says that the state x_k is drawn from a distribution over possible values of x_k, and that this distribution depends on the previous state x_{k-1}. We can also choose to express the motion model as
This equation says the same thing, but in this formulation we a deterministic function f() and a random variable q_{k-1}. So, expressed in words we have that the state x_k is a function of the previous state x_{k-1} and some random motion noise q_{k-1} which is stochastic (i.e. drawn from some distribution).
In addition to the dynamics of the airplane we also know the dynamics of the radar, which we can express as a measurement model. The sensor isn’t perfect, so we’re going to have noise in the measurements y_k that we receive. Because of this we can view the measurement model as a probability distribution as well
Expressed in words, the model says that the measurement y_k is drawn from a distribution over possible values of measurements y_k, and that this distribution depends on the state x_k. We can also choose to express the measurement model as
In this formulation we have a deterministic measurement model h() which receives the current state x_k as well as a random variable r_k. This says that the measurement y_k is a function of the state x_k as well as some stochastic (i.e. drawn from some distribution) measurement noise r_k.
We’re looking for a way to combine these two models, so that when we observe measurements from the radar we can formulate the following density
which is called the posterior distribution over the state, and can be seen as describing a region of plausible values for x_k, given all of the values that we have observed so far.
We can express this density by computing two equations, the predict and update equations
The predict equation uses the posterior from the previous time-step k-1 together with the motion model to predict what the current state x_k will be. This belief is then updated via the update equation by using Bayes’ theorem to combine the observed measurement y_k with the measurement model and the predicted state. We then end up with the posterior distribution! For the next measurement we just repeat these steps, and the current posterior becomes the previous posterior instead.
The predict and update equations provide a recursive way to compute the posterior of the state for every measurement that we receive. However, if we look at the equations, they aren’t all that easy to compute in practice.
For starters, we need to express densities in such a way that we can actually solve the equations (i.e. we want numerically stable equations). Secondly, it would be nice if we could find analytical solutions, since then we wouldn’t have to numerically solve the equations (which might require a lot of compute). Both of these are important, especially when you consider that a lot of sensors give you measurements at a rate of hundreds or thousands hertz. Since we don’t want to discard measurements, we need to find a way to compute both equations really fast.
This is where the Kalman filter comes in. The Kalman filter is built around one key concept
This reason for this is that Gaussian densities have a lot of nice properties:
If we draw values from a Gaussian and perform a linear operation (i.e. multiplication and/or addition), these values will still be distributed according to a Gaussian.Another nice property with Gaussian densities is that they are self-conjugate. This means that if we have a Gaussian likelihood and a Gaussian prior then the posterior is guaranteed to be a Gaussian as well.Finally, Gaussian densities can be described entirely by their first two moments: the mean and the variance.
If we draw values from a Gaussian and perform a linear operation (i.e. multiplication and/or addition), these values will still be distributed according to a Gaussian.
Another nice property with Gaussian densities is that they are self-conjugate. This means that if we have a Gaussian likelihood and a Gaussian prior then the posterior is guaranteed to be a Gaussian as well.
Finally, Gaussian densities can be described entirely by their first two moments: the mean and the variance.
If we look at the predict and update equations you can hopefully see how all of these properties might come in handy. By making every density a Gaussian each equation boils down to finding expressions for the corresponding mean and variance!
The linear and Gaussian motion and measurement models can be expressed as
Just as before we can choose to express both of these models as functions instead of densities
With these in place we can rewrite the predict and update equations where all the densities are Gaussians
What we’re looking for is to find equations for how to compute the moments marked in orange and magenta above: the predicted mean and covariance, as well as the updated mean and covariance. I’m going to skip the derivations, but what we end up with is the following
There we have it, we now have an analytical solution for computing the posterior distribution of the state x_k for every time-step! Since we end up with a Gaussian computing the MMSE or MAP is trivial, since the mean of the posterior serves as both. Another way to view it all is as the following
“The posterior (magenta colored) mean is the optimal estimate of the state, and the posterior (magenta colored) covariance is the uncertainty of the estimate”.
Before we move on to a practical example let’s take a brief look at each line and break down what’s happening.
We get the predicted mean by taking the past posterior mean and multiplying it with the matrix A_{k-1}, which makes sense since A_{k-1} describes how the state evolves over time.The predicted covariance is computed in a similar manner, where we multiply the past posterior covariance with A_{k-1} twice and add Q_{k-1}. We add the covariance Q_{k-1} since we have uncertainty in our motion model, so that’s added to the transformed covariance.v_k is called the innovation, and can be seen as a representation of the new information that’s gained when comparing the real measurement with the predicted measurement that we get from the measurement model.S_k represents the predicted measurement covariance. R_k represents the measurement uncertainty in the measurement model, and with S_k we combine the uncertainty of the predicted state with the uncertainty of the measurement model.K_k is called the Kalman gain and represents how much the predicted state and covariance should be adjusted with the new information gained from the measurement.The posterior mean is computed by taking the predicted mean and adjusting it with the new information that has been gained. As noted in above, K_k is a scaling factor that determines how much of v_k should be added.The posterior covariance is computed by taking the predicted covariance and adjusting it with information gained from the measurement. The new information allows us to decrease the uncertainty regarding the state, that’s why there’s a minus sign.
We get the predicted mean by taking the past posterior mean and multiplying it with the matrix A_{k-1}, which makes sense since A_{k-1} describes how the state evolves over time.
The predicted covariance is computed in a similar manner, where we multiply the past posterior covariance with A_{k-1} twice and add Q_{k-1}. We add the covariance Q_{k-1} since we have uncertainty in our motion model, so that’s added to the transformed covariance.
v_k is called the innovation, and can be seen as a representation of the new information that’s gained when comparing the real measurement with the predicted measurement that we get from the measurement model.
S_k represents the predicted measurement covariance. R_k represents the measurement uncertainty in the measurement model, and with S_k we combine the uncertainty of the predicted state with the uncertainty of the measurement model.
K_k is called the Kalman gain and represents how much the predicted state and covariance should be adjusted with the new information gained from the measurement.
The posterior mean is computed by taking the predicted mean and adjusting it with the new information that has been gained. As noted in above, K_k is a scaling factor that determines how much of v_k should be added.
The posterior covariance is computed by taking the predicted covariance and adjusting it with information gained from the measurement. The new information allows us to decrease the uncertainty regarding the state, that’s why there’s a minus sign.
In order to understand a bit better what those 7 lines of equations represent it’s helpful to visualize on a conceptual level what’s going in a Kalman filter.
To start, we can image that we have two different planes (or dimensions): the measurement plane (red, denoted with Y) and the state plane (blue, denoted with X). The state x_k evolves over time in the state plane. The issue is that we can’t access or explicitly observe the state plane in any way, we only have access to the measurement plane. The measurement plane is where we observe measurements, which are caused by the state.
We can’t know for sure what’s going on in the state plane (i.e. we can’t observe an exact value of the state), but with the Kalman filter we can describe the state’s behavior in the state plane as a Gaussian density.
In the Kalman filter we start with an initial Gaussian, describing the state at time-step k-1. This initial Gaussian is illustrated with a black point and circle (the point represents the mean and the circle is a contour line of the covariance matrix). We use the motion model to predict where the state will be at time-step k, illustrated by the Gaussian in blue. We then use the measurement model to project the predicted state (blue Gaussian) from the state plane into the measurement plane. What we end up with is the red Gaussian, which essentially describes where we can expect the measurement to occur. Once the measurement is observed (indicated in green), we use the red Gaussian to decide how much of the measurement should be used to update the predicted state in the state plane. After we’ve updated the predicted state, we end up with a new black Gaussian, describing the posterior of the state at time k. This process is then repeated for all future time-steps.
Alright, let’s put all of this into practice by showing what a Kalman filter looks like in code and apply it to a toy example.
In the toy example we’ll use the airplane example that I mentioned before. To make things easy, let’s assume that the airplane is flying at a constant altitude. So, in this case we can choose to include xy-position as well as xy-velocity in the state
The motion of the airplane can be described by a constant velocity (CV) model. The CV model is nice since it’s a linear and simple model to implement and at the same time it manages to give quite a good representation of how an airplane behaves. Simply put, it assumes that the airplane’s next position is a function of its current position and current velocity. The velocity is assumed to be stochastic (subject to additive gaussian noise), which makes sense since we don’t know what actions the pilot is taking. In 1D this model is formulated as
The parameter T denotes the sampling-time that’s used in the system and σ2 is used as a scaling factor for the covariance matrix (i.e. indicating how much uncertainty we have in the model). Now, the reason why the covariance model looks so funky is because we’re using a discretized CV model (read this for more info). This is important since our choice of sampling-time T will affect filter performance (I’ll go more in depth on this topic in a later post).
In our case where we have motion in both x and y directions, the motion model becomes
The 1D covariance components Σ for each direction are subscripted with x and y respectively. This is since both directions don’t necessarily suffer from the same amount of noise.
Okay so now we know how to formulate A and Q. Let’s go on to the measurement model. Now, this model is fairly simple. We assume that we measure the position of the airplane at every time-step and the measurements are stochastic (subject to additive gaussian noise). This can be expressed as
Similar to before we use λ2 as a scaling factor for the measurement covariance matrix R_k.
Before we move on to implementing a Kalman Filter for this system we’ll use these two models to generate motion and measurement data. We’ll use this data later on to test out the Kalman Filter and see how well it works. For this we’ll need a script that can simulate the system and create all of the model parameters (Note that the @ operator is the same as np.matmul in numpy, so A @ B is the same as np.matmul(A, B)).
After running simulate_model.py we get the following plot, illustrating how the positional components (x and y) of the state evolved over 20 time-steps (with sampling time T=1), as well as the measurements that were observed. Now keep in mind that we’re simulating the system, that’s how we know what the true state is.
Now let’s implement the Kalman filter, which is a straightforward process since the filter equations translate from math into code really easy.
With the Kalman filter in place we can now run it and see how it performs on our simulated data. In order to do this we’ll write a script that combines the functionality found in kalman_filter.py and simulate_model.py.
After running the script we get the following plot, which is the same as the one before but with the addition of the Kalman filter’s estimate of the x and y positions.
Just by looking at the plot it’s clear that the Kalman filter gives better estimates of the x- and y-position than if one were to just use the raw measurements. The superior performance of the Kalman filter to that of just using measurements can also be analyzed numerically. By using euclidean distance as error metric for the x- and y-position we can compute the Root Mean Square Error (RMSE) for both the Kalman filer and the measurements. For this 20 time-step long scenario the RMSE for each method is
(20 time-step simulation)RMSE Kalman Filter: 0.2917RMSE Measurements: 0.4441
The Kalman filter has a lower RMSE value than the measurements by quite a large margin. Since 20 time-steps is pretty short so let’s investigate if the RMSE results hold for a longer simulation less prone to statistical uncertainty.
(100,000 time-step simulation)RMSE Kalman Filter: 0.3162RMSE Measurements: 0.4241
Just like before the kalman filter a better option than just using measurements.
(The comparison has only focused on the positional states, since these are easier to plot. But don’t forget that with our chosen motion model we’re also getting estimates of the x- and y-velocities as well from the Kalman filter!)
It’s important to stress that the purpose of the toy example is to illustrate how the Kalman filter works. In real world applications we don’t know the model parameters beforehand (Q and R) and we might not even know what motion model to use. In such cases a lot of time is spent tuning the filter parameters and trying out different motion models. To make matters worse, most of the time we end up dealing with systems that are nonlinear and where the Gaussian assumption doesn’t hold.
But at the same time, it’s these types of problems that are actually the most fun to solve! This is where the more complex variants or extensions of the kalman filter come in — they provide different methods and strategies to address either all or some of these issues, depending on the need.
In the next post of this series I’ll explore the family of sigma-point filters, which consist of several different filters capable of tackling nonlinear and non Gaussian models to varying degrees.
Thanks for reading!
|
[
{
"code": null,
"e": 534,
"s": 172,
"text": "In my previous post in this series I talked about the two equations that are used for essentially all sensor fusion algorithms: the predict and update equations. I did not however showcase any practical algorithm that makes the equations analytically tractable. So, in this post I’ll explain perhaps the most famous and well-known algorithm — the Kalman filter."
},
{
"code": null,
"e": 769,
"s": 534,
"text": "Even though it’s in many ways a simple algorithm it can still take some time to build up intuition around how it actually works. Having good intuition is important, since correctly tuning a Kalman filter isn’t all that easy sometimes."
},
{
"code": null,
"e": 1036,
"s": 769,
"text": "Let’s quickly summarize what sensor fusion is all about, including the predict and update equations. In order to do this we’ll revisit the airplane example first presented in part 1 of this series. If you feel lost then I strongly recommend that you read through it."
},
{
"code": null,
"e": 1357,
"s": 1036,
"text": "Okay. We’re using a radar sensor to track an airplane over time. We’re interested in learning about the state x_k of the plane, where k denotes the time-step. The state contains the dynamic properties of the airplane that we’re interested in estimating. This could for example be position, velocity, roll, yaw and so on."
},
{
"code": null,
"e": 1568,
"s": 1357,
"text": "We have some knowledge of the dynamics of the airplane between time-steps, which we represent as a motion model. However, there is uncertainty in the model, which is why we view it as a probability distribution"
},
{
"code": null,
"e": 1796,
"s": 1568,
"text": "Expressed in words, the model says that the state x_k is drawn from a distribution over possible values of x_k, and that this distribution depends on the previous state x_{k-1}. We can also choose to express the motion model as"
},
{
"code": null,
"e": 2106,
"s": 1796,
"text": "This equation says the same thing, but in this formulation we a deterministic function f() and a random variable q_{k-1}. So, expressed in words we have that the state x_k is a function of the previous state x_{k-1} and some random motion noise q_{k-1} which is stochastic (i.e. drawn from some distribution)."
},
{
"code": null,
"e": 2419,
"s": 2106,
"text": "In addition to the dynamics of the airplane we also know the dynamics of the radar, which we can express as a measurement model. The sensor isn’t perfect, so we’re going to have noise in the measurements y_k that we receive. Because of this we can view the measurement model as a probability distribution as well"
},
{
"code": null,
"e": 2658,
"s": 2419,
"text": "Expressed in words, the model says that the measurement y_k is drawn from a distribution over possible values of measurements y_k, and that this distribution depends on the state x_k. We can also choose to express the measurement model as"
},
{
"code": null,
"e": 2947,
"s": 2658,
"text": "In this formulation we have a deterministic measurement model h() which receives the current state x_k as well as a random variable r_k. This says that the measurement y_k is a function of the state x_k as well as some stochastic (i.e. drawn from some distribution) measurement noise r_k."
},
{
"code": null,
"e": 3091,
"s": 2947,
"text": "We’re looking for a way to combine these two models, so that when we observe measurements from the radar we can formulate the following density"
},
{
"code": null,
"e": 3272,
"s": 3091,
"text": "which is called the posterior distribution over the state, and can be seen as describing a region of plausible values for x_k, given all of the values that we have observed so far."
},
{
"code": null,
"e": 3361,
"s": 3272,
"text": "We can express this density by computing two equations, the predict and update equations"
},
{
"code": null,
"e": 3846,
"s": 3361,
"text": "The predict equation uses the posterior from the previous time-step k-1 together with the motion model to predict what the current state x_k will be. This belief is then updated via the update equation by using Bayes’ theorem to combine the observed measurement y_k with the measurement model and the predicted state. We then end up with the posterior distribution! For the next measurement we just repeat these steps, and the current posterior becomes the previous posterior instead."
},
{
"code": null,
"e": 4068,
"s": 3846,
"text": "The predict and update equations provide a recursive way to compute the posterior of the state for every measurement that we receive. However, if we look at the equations, they aren’t all that easy to compute in practice."
},
{
"code": null,
"e": 4630,
"s": 4068,
"text": "For starters, we need to express densities in such a way that we can actually solve the equations (i.e. we want numerically stable equations). Secondly, it would be nice if we could find analytical solutions, since then we wouldn’t have to numerically solve the equations (which might require a lot of compute). Both of these are important, especially when you consider that a lot of sensors give you measurements at a rate of hundreds or thousands hertz. Since we don’t want to discard measurements, we need to find a way to compute both equations really fast."
},
{
"code": null,
"e": 4722,
"s": 4630,
"text": "This is where the Kalman filter comes in. The Kalman filter is built around one key concept"
},
{
"code": null,
"e": 4801,
"s": 4722,
"text": "This reason for this is that Gaussian densities have a lot of nice properties:"
},
{
"code": null,
"e": 5284,
"s": 4801,
"text": "If we draw values from a Gaussian and perform a linear operation (i.e. multiplication and/or addition), these values will still be distributed according to a Gaussian.Another nice property with Gaussian densities is that they are self-conjugate. This means that if we have a Gaussian likelihood and a Gaussian prior then the posterior is guaranteed to be a Gaussian as well.Finally, Gaussian densities can be described entirely by their first two moments: the mean and the variance."
},
{
"code": null,
"e": 5452,
"s": 5284,
"text": "If we draw values from a Gaussian and perform a linear operation (i.e. multiplication and/or addition), these values will still be distributed according to a Gaussian."
},
{
"code": null,
"e": 5660,
"s": 5452,
"text": "Another nice property with Gaussian densities is that they are self-conjugate. This means that if we have a Gaussian likelihood and a Gaussian prior then the posterior is guaranteed to be a Gaussian as well."
},
{
"code": null,
"e": 5769,
"s": 5660,
"text": "Finally, Gaussian densities can be described entirely by their first two moments: the mean and the variance."
},
{
"code": null,
"e": 6011,
"s": 5769,
"text": "If we look at the predict and update equations you can hopefully see how all of these properties might come in handy. By making every density a Gaussian each equation boils down to finding expressions for the corresponding mean and variance!"
},
{
"code": null,
"e": 6085,
"s": 6011,
"text": "The linear and Gaussian motion and measurement models can be expressed as"
},
{
"code": null,
"e": 6180,
"s": 6085,
"text": "Just as before we can choose to express both of these models as functions instead of densities"
},
{
"code": null,
"e": 6286,
"s": 6180,
"text": "With these in place we can rewrite the predict and update equations where all the densities are Gaussians"
},
{
"code": null,
"e": 6552,
"s": 6286,
"text": "What we’re looking for is to find equations for how to compute the moments marked in orange and magenta above: the predicted mean and covariance, as well as the updated mean and covariance. I’m going to skip the derivations, but what we end up with is the following"
},
{
"code": null,
"e": 6849,
"s": 6552,
"text": "There we have it, we now have an analytical solution for computing the posterior distribution of the state x_k for every time-step! Since we end up with a Gaussian computing the MMSE or MAP is trivial, since the mean of the posterior serves as both. Another way to view it all is as the following"
},
{
"code": null,
"e": 7009,
"s": 6849,
"text": "“The posterior (magenta colored) mean is the optimal estimate of the state, and the posterior (magenta colored) covariance is the uncertainty of the estimate”."
},
{
"code": null,
"e": 7120,
"s": 7009,
"text": "Before we move on to a practical example let’s take a brief look at each line and break down what’s happening."
},
{
"code": null,
"e": 8626,
"s": 7120,
"text": "We get the predicted mean by taking the past posterior mean and multiplying it with the matrix A_{k-1}, which makes sense since A_{k-1} describes how the state evolves over time.The predicted covariance is computed in a similar manner, where we multiply the past posterior covariance with A_{k-1} twice and add Q_{k-1}. We add the covariance Q_{k-1} since we have uncertainty in our motion model, so that’s added to the transformed covariance.v_k is called the innovation, and can be seen as a representation of the new information that’s gained when comparing the real measurement with the predicted measurement that we get from the measurement model.S_k represents the predicted measurement covariance. R_k represents the measurement uncertainty in the measurement model, and with S_k we combine the uncertainty of the predicted state with the uncertainty of the measurement model.K_k is called the Kalman gain and represents how much the predicted state and covariance should be adjusted with the new information gained from the measurement.The posterior mean is computed by taking the predicted mean and adjusting it with the new information that has been gained. As noted in above, K_k is a scaling factor that determines how much of v_k should be added.The posterior covariance is computed by taking the predicted covariance and adjusting it with information gained from the measurement. The new information allows us to decrease the uncertainty regarding the state, that’s why there’s a minus sign."
},
{
"code": null,
"e": 8805,
"s": 8626,
"text": "We get the predicted mean by taking the past posterior mean and multiplying it with the matrix A_{k-1}, which makes sense since A_{k-1} describes how the state evolves over time."
},
{
"code": null,
"e": 9071,
"s": 8805,
"text": "The predicted covariance is computed in a similar manner, where we multiply the past posterior covariance with A_{k-1} twice and add Q_{k-1}. We add the covariance Q_{k-1} since we have uncertainty in our motion model, so that’s added to the transformed covariance."
},
{
"code": null,
"e": 9281,
"s": 9071,
"text": "v_k is called the innovation, and can be seen as a representation of the new information that’s gained when comparing the real measurement with the predicted measurement that we get from the measurement model."
},
{
"code": null,
"e": 9513,
"s": 9281,
"text": "S_k represents the predicted measurement covariance. R_k represents the measurement uncertainty in the measurement model, and with S_k we combine the uncertainty of the predicted state with the uncertainty of the measurement model."
},
{
"code": null,
"e": 9675,
"s": 9513,
"text": "K_k is called the Kalman gain and represents how much the predicted state and covariance should be adjusted with the new information gained from the measurement."
},
{
"code": null,
"e": 9891,
"s": 9675,
"text": "The posterior mean is computed by taking the predicted mean and adjusting it with the new information that has been gained. As noted in above, K_k is a scaling factor that determines how much of v_k should be added."
},
{
"code": null,
"e": 10138,
"s": 9891,
"text": "The posterior covariance is computed by taking the predicted covariance and adjusting it with information gained from the measurement. The new information allows us to decrease the uncertainty regarding the state, that’s why there’s a minus sign."
},
{
"code": null,
"e": 10297,
"s": 10138,
"text": "In order to understand a bit better what those 7 lines of equations represent it’s helpful to visualize on a conceptual level what’s going in a Kalman filter."
},
{
"code": null,
"e": 10728,
"s": 10297,
"text": "To start, we can image that we have two different planes (or dimensions): the measurement plane (red, denoted with Y) and the state plane (blue, denoted with X). The state x_k evolves over time in the state plane. The issue is that we can’t access or explicitly observe the state plane in any way, we only have access to the measurement plane. The measurement plane is where we observe measurements, which are caused by the state."
},
{
"code": null,
"e": 10945,
"s": 10728,
"text": "We can’t know for sure what’s going on in the state plane (i.e. we can’t observe an exact value of the state), but with the Kalman filter we can describe the state’s behavior in the state plane as a Gaussian density."
},
{
"code": null,
"e": 11921,
"s": 10945,
"text": "In the Kalman filter we start with an initial Gaussian, describing the state at time-step k-1. This initial Gaussian is illustrated with a black point and circle (the point represents the mean and the circle is a contour line of the covariance matrix). We use the motion model to predict where the state will be at time-step k, illustrated by the Gaussian in blue. We then use the measurement model to project the predicted state (blue Gaussian) from the state plane into the measurement plane. What we end up with is the red Gaussian, which essentially describes where we can expect the measurement to occur. Once the measurement is observed (indicated in green), we use the red Gaussian to decide how much of the measurement should be used to update the predicted state in the state plane. After we’ve updated the predicted state, we end up with a new black Gaussian, describing the posterior of the state at time k. This process is then repeated for all future time-steps."
},
{
"code": null,
"e": 12048,
"s": 11921,
"text": "Alright, let’s put all of this into practice by showing what a Kalman filter looks like in code and apply it to a toy example."
},
{
"code": null,
"e": 12299,
"s": 12048,
"text": "In the toy example we’ll use the airplane example that I mentioned before. To make things easy, let’s assume that the airplane is flying at a constant altitude. So, in this case we can choose to include xy-position as well as xy-velocity in the state"
},
{
"code": null,
"e": 12847,
"s": 12299,
"text": "The motion of the airplane can be described by a constant velocity (CV) model. The CV model is nice since it’s a linear and simple model to implement and at the same time it manages to give quite a good representation of how an airplane behaves. Simply put, it assumes that the airplane’s next position is a function of its current position and current velocity. The velocity is assumed to be stochastic (subject to additive gaussian noise), which makes sense since we don’t know what actions the pilot is taking. In 1D this model is formulated as"
},
{
"code": null,
"e": 13306,
"s": 12847,
"text": "The parameter T denotes the sampling-time that’s used in the system and σ2 is used as a scaling factor for the covariance matrix (i.e. indicating how much uncertainty we have in the model). Now, the reason why the covariance model looks so funky is because we’re using a discretized CV model (read this for more info). This is important since our choice of sampling-time T will affect filter performance (I’ll go more in depth on this topic in a later post)."
},
{
"code": null,
"e": 13392,
"s": 13306,
"text": "In our case where we have motion in both x and y directions, the motion model becomes"
},
{
"code": null,
"e": 13571,
"s": 13392,
"text": "The 1D covariance components Σ for each direction are subscripted with x and y respectively. This is since both directions don’t necessarily suffer from the same amount of noise."
},
{
"code": null,
"e": 13862,
"s": 13571,
"text": "Okay so now we know how to formulate A and Q. Let’s go on to the measurement model. Now, this model is fairly simple. We assume that we measure the position of the airplane at every time-step and the measurements are stochastic (subject to additive gaussian noise). This can be expressed as"
},
{
"code": null,
"e": 13953,
"s": 13862,
"text": "Similar to before we use λ2 as a scaling factor for the measurement covariance matrix R_k."
},
{
"code": null,
"e": 14373,
"s": 13953,
"text": "Before we move on to implementing a Kalman Filter for this system we’ll use these two models to generate motion and measurement data. We’ll use this data later on to test out the Kalman Filter and see how well it works. For this we’ll need a script that can simulate the system and create all of the model parameters (Note that the @ operator is the same as np.matmul in numpy, so A @ B is the same as np.matmul(A, B))."
},
{
"code": null,
"e": 14693,
"s": 14373,
"text": "After running simulate_model.py we get the following plot, illustrating how the positional components (x and y) of the state evolved over 20 time-steps (with sampling time T=1), as well as the measurements that were observed. Now keep in mind that we’re simulating the system, that’s how we know what the true state is."
},
{
"code": null,
"e": 14837,
"s": 14693,
"text": "Now let’s implement the Kalman filter, which is a straightforward process since the filter equations translate from math into code really easy."
},
{
"code": null,
"e": 15056,
"s": 14837,
"text": "With the Kalman filter in place we can now run it and see how it performs on our simulated data. In order to do this we’ll write a script that combines the functionality found in kalman_filter.py and simulate_model.py."
},
{
"code": null,
"e": 15224,
"s": 15056,
"text": "After running the script we get the following plot, which is the same as the one before but with the addition of the Kalman filter’s estimate of the x and y positions."
},
{
"code": null,
"e": 15731,
"s": 15224,
"text": "Just by looking at the plot it’s clear that the Kalman filter gives better estimates of the x- and y-position than if one were to just use the raw measurements. The superior performance of the Kalman filter to that of just using measurements can also be analyzed numerically. By using euclidean distance as error metric for the x- and y-position we can compute the Root Mean Square Error (RMSE) for both the Kalman filer and the measurements. For this 20 time-step long scenario the RMSE for each method is"
},
{
"code": null,
"e": 15809,
"s": 15731,
"text": "(20 time-step simulation)RMSE Kalman Filter: 0.2917RMSE Measurements: 0.4441"
},
{
"code": null,
"e": 16042,
"s": 15809,
"text": "The Kalman filter has a lower RMSE value than the measurements by quite a large margin. Since 20 time-steps is pretty short so let’s investigate if the RMSE results hold for a longer simulation less prone to statistical uncertainty."
},
{
"code": null,
"e": 16125,
"s": 16042,
"text": "(100,000 time-step simulation)RMSE Kalman Filter: 0.3162RMSE Measurements: 0.4241"
},
{
"code": null,
"e": 16206,
"s": 16125,
"text": "Just like before the kalman filter a better option than just using measurements."
},
{
"code": null,
"e": 16437,
"s": 16206,
"text": "(The comparison has only focused on the positional states, since these are easier to plot. But don’t forget that with our chosen motion model we’re also getting estimates of the x- and y-velocities as well from the Kalman filter!)"
},
{
"code": null,
"e": 16924,
"s": 16437,
"text": "It’s important to stress that the purpose of the toy example is to illustrate how the Kalman filter works. In real world applications we don’t know the model parameters beforehand (Q and R) and we might not even know what motion model to use. In such cases a lot of time is spent tuning the filter parameters and trying out different motion models. To make matters worse, most of the time we end up dealing with systems that are nonlinear and where the Gaussian assumption doesn’t hold."
},
{
"code": null,
"e": 17217,
"s": 16924,
"text": "But at the same time, it’s these types of problems that are actually the most fun to solve! This is where the more complex variants or extensions of the kalman filter come in — they provide different methods and strategies to address either all or some of these issues, depending on the need."
},
{
"code": null,
"e": 17414,
"s": 17217,
"text": "In the next post of this series I’ll explore the family of sigma-point filters, which consist of several different filters capable of tackling nonlinear and non Gaussian models to varying degrees."
}
] |
How to convert list to string in Python?
|
There may be some situations, where we need to convert a list into a string. We will discuss different methods to do the same.
Iterate through the list and append the elements to the string to convert list into a string. We will use for-in loop to iterate through the list elements.
Live Demo
list1=["Welcome","To","Tutorials","Point"]
string1=""
for i in list1:
string1=string1+i
string2=""
for i in list1:
string2=string2+i+" "
print(string1)
print(string2)
WelcomeToTutorialsPoint
Welcome To Tutorials Point
The list will be passed as a parameter inside the join method.
Live Demo
list1=["Welcome","To","Tutorials","Point"]
string1=""
print(string1.join(list1))
string2=" "
print(string2.join(list1))
WelcomeToTutorialsPoint
Welcome To Tutorials Point
We can use map() method for mapping str with the list and then use join() to convert list into string.
Live Demo
list1=["Welcome","To","Tutorials","Point"]
string1="".join(map(str,list1))
string2=" ".join(map(str,list1))
print(string1)
print(string2)
WelcomeToTutorialsPoint
Welcome To Tutorials Point
Comprehensions in Python provide a short way to construct new sequences using already provided sequences. We will access each element of the list as a string and then use join().
Live Demo
list1=["Welcome","To","Tutorials","Point"]
string1="".join(str(elem) for elem in list1)
string2=" ".join(str(elem) for elem in list1)
print(string1)
print(string2)
WelcomeToTutorialsPoint
Welcome To Tutorials Point
|
[
{
"code": null,
"e": 1189,
"s": 1062,
"text": "There may be some situations, where we need to convert a list into a string. We will discuss different methods to do the same."
},
{
"code": null,
"e": 1345,
"s": 1189,
"text": "Iterate through the list and append the elements to the string to convert list into a string. We will use for-in loop to iterate through the list elements."
},
{
"code": null,
"e": 1356,
"s": 1345,
"text": " Live Demo"
},
{
"code": null,
"e": 1529,
"s": 1356,
"text": "list1=[\"Welcome\",\"To\",\"Tutorials\",\"Point\"]\nstring1=\"\"\nfor i in list1:\n string1=string1+i\nstring2=\"\"\nfor i in list1:\n string2=string2+i+\" \"\nprint(string1)\nprint(string2)"
},
{
"code": null,
"e": 1580,
"s": 1529,
"text": "WelcomeToTutorialsPoint\nWelcome To Tutorials Point"
},
{
"code": null,
"e": 1643,
"s": 1580,
"text": "The list will be passed as a parameter inside the join method."
},
{
"code": null,
"e": 1654,
"s": 1643,
"text": " Live Demo"
},
{
"code": null,
"e": 1774,
"s": 1654,
"text": "list1=[\"Welcome\",\"To\",\"Tutorials\",\"Point\"]\nstring1=\"\"\nprint(string1.join(list1))\nstring2=\" \"\nprint(string2.join(list1))"
},
{
"code": null,
"e": 1825,
"s": 1774,
"text": "WelcomeToTutorialsPoint\nWelcome To Tutorials Point"
},
{
"code": null,
"e": 1928,
"s": 1825,
"text": "We can use map() method for mapping str with the list and then use join() to convert list into string."
},
{
"code": null,
"e": 1939,
"s": 1928,
"text": " Live Demo"
},
{
"code": null,
"e": 2077,
"s": 1939,
"text": "list1=[\"Welcome\",\"To\",\"Tutorials\",\"Point\"]\nstring1=\"\".join(map(str,list1))\nstring2=\" \".join(map(str,list1))\nprint(string1)\nprint(string2)"
},
{
"code": null,
"e": 2128,
"s": 2077,
"text": "WelcomeToTutorialsPoint\nWelcome To Tutorials Point"
},
{
"code": null,
"e": 2307,
"s": 2128,
"text": "Comprehensions in Python provide a short way to construct new sequences using already provided sequences. We will access each element of the list as a string and then use join()."
},
{
"code": null,
"e": 2318,
"s": 2307,
"text": " Live Demo"
},
{
"code": null,
"e": 2482,
"s": 2318,
"text": "list1=[\"Welcome\",\"To\",\"Tutorials\",\"Point\"]\nstring1=\"\".join(str(elem) for elem in list1)\nstring2=\" \".join(str(elem) for elem in list1)\nprint(string1)\nprint(string2)"
},
{
"code": null,
"e": 2533,
"s": 2482,
"text": "WelcomeToTutorialsPoint\nWelcome To Tutorials Point"
}
] |
BFS using STL for competitive coding in C++?
|
The Breadth First Search (BFS) traversal is an algorithm, which is used to visit all of the nodes of a given graph. In this traversal algorithm one node is selected and then all of the adjacent nodes are visited one by one. After completing all of the adjacent vertices, it moves further to check another vertices and checks its adjacent vertices again.
In The competitive coding, we have to solve problems very quickly. We will use the STL (Standard Library of C++) to implement this algorithm, we need to use the Queue data structure. All the adjacent vertices are added into the queue, when all adjacent vertices are completed, one item is removed from the queue and start traversing through that vertex again.
In Graph sometimes, we may get some cycles, so we will use an array to mark when a node is visited already or not.
Input : The Adjacency matrix of the graph.
A B C D E F
A 0 1 1 1 0 0
B 1 0 0 1 1 0
C 1 0 0 1 0 1
D 1 1 1 0 1 1
E 0 1 0 1 0 1
F 0 0 1 1 1 0
Output : BFS Traversal: B A D E C F
Input − The list of vertices, and the start vertex.
Output − Traverse all of the nodes, if the graph is connected.
Begin
define an empty queue que
at first mark all nodes status as unvisited
add the start vertex into the que
while que is not empty, do
delete item from que and set to u
display the vertex u
for all vertices 1 adjacent with u, do
if vertices[i] is unvisited, then
mark vertices[i] as temporarily visited
add v into the queue
mark
done
mark u as completely visited
done
End
Live Demo
#include<iostream>
#include<queue>
#define NODE 6
using namespace std;
class node {
public:
int val;
int state; //status
};
int graph[NODE][NODE] = {
{0, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 1, 0},
{1, 0, 0, 1, 0, 1},
{1, 1, 1, 0, 1, 1},
{0, 1, 0, 1, 0, 1},
{0, 0, 1, 1, 1, 0}
};
void bfs(node *vert, node s) {
node u;
int i, j;
queue<node> que;
for(i = 0; i<NODE; i++) {
vert[i].state = 0; //not visited
}
vert[s.val].state = 1;//visited
que.push(s); //insert starting node
while(!que.empty()) {
u = que.front(); //delete from queue and print
que.pop();
cout << char(u.val+'A') << " ";
for(i = 0; i<NODE; i++) {
if(graph[i][u.val]) {
//when the node is non-visited
if(vert[i].state == 0) {
vert[i].state = 1;
que.push(vert[i]);
}
}
}
u.state = 2;//completed for node u
}
}
int main() {
node vertices[NODE];
node start;
char s;
for(int i = 0; i<NODE; i++) {
vertices[i].val = i;
}
s = 'B';//starting vertex B
start.val = s-'A';
cout << "BFS Traversal: ";
bfs(vertices, start);
cout << endl;
}
BFS Traversal: B A D E C F
|
[
{
"code": null,
"e": 1416,
"s": 1062,
"text": "The Breadth First Search (BFS) traversal is an algorithm, which is used to visit all of the nodes of a given graph. In this traversal algorithm one node is selected and then all of the adjacent nodes are visited one by one. After completing all of the adjacent vertices, it moves further to check another vertices and checks its adjacent vertices again."
},
{
"code": null,
"e": 1776,
"s": 1416,
"text": "In The competitive coding, we have to solve problems very quickly. We will use the STL (Standard Library of C++) to implement this algorithm, we need to use the Queue data structure. All the adjacent vertices are added into the queue, when all adjacent vertices are completed, one item is removed from the queue and start traversing through that vertex again."
},
{
"code": null,
"e": 1891,
"s": 1776,
"text": "In Graph sometimes, we may get some cycles, so we will use an array to mark when a node is visited already or not."
},
{
"code": null,
"e": 2066,
"s": 1891,
"text": "Input : The Adjacency matrix of the graph.\nA B C D E F\nA 0 1 1 1 0 0\nB 1 0 0 1 1 0\nC 1 0 0 1 0 1\nD 1 1 1 0 1 1\nE 0 1 0 1 0 1\nF 0 0 1 1 1 0\nOutput : BFS Traversal: B A D E C F"
},
{
"code": null,
"e": 2118,
"s": 2066,
"text": "Input − The list of vertices, and the start vertex."
},
{
"code": null,
"e": 2181,
"s": 2118,
"text": "Output − Traverse all of the nodes, if the graph is connected."
},
{
"code": null,
"e": 2642,
"s": 2181,
"text": "Begin\n define an empty queue que\n at first mark all nodes status as unvisited\n add the start vertex into the que\n while que is not empty, do\n delete item from que and set to u\n display the vertex u\n for all vertices 1 adjacent with u, do\n if vertices[i] is unvisited, then\n mark vertices[i] as temporarily visited\n add v into the queue\n mark\n done\n mark u as completely visited\n done\nEnd"
},
{
"code": null,
"e": 2653,
"s": 2642,
"text": " Live Demo"
},
{
"code": null,
"e": 3860,
"s": 2653,
"text": "#include<iostream>\n#include<queue>\n#define NODE 6\nusing namespace std;\nclass node {\n public:\n int val;\n int state; //status\n};\nint graph[NODE][NODE] = {\n {0, 1, 1, 1, 0, 0},\n {1, 0, 0, 1, 1, 0},\n {1, 0, 0, 1, 0, 1},\n {1, 1, 1, 0, 1, 1},\n {0, 1, 0, 1, 0, 1},\n {0, 0, 1, 1, 1, 0}\n};\nvoid bfs(node *vert, node s) {\n node u;\n int i, j;\n queue<node> que;\n for(i = 0; i<NODE; i++) {\n vert[i].state = 0; //not visited\n }\n vert[s.val].state = 1;//visited\n que.push(s); //insert starting node\n while(!que.empty()) {\n u = que.front(); //delete from queue and print\n que.pop();\n cout << char(u.val+'A') << \" \";\n for(i = 0; i<NODE; i++) {\n if(graph[i][u.val]) {\n //when the node is non-visited\n if(vert[i].state == 0) {\n vert[i].state = 1;\n que.push(vert[i]);\n }\n }\n }\n u.state = 2;//completed for node u\n }\n}\nint main() {\n node vertices[NODE];\n node start;\n char s;\n for(int i = 0; i<NODE; i++) {\n vertices[i].val = i;\n }\n s = 'B';//starting vertex B\n start.val = s-'A';\n cout << \"BFS Traversal: \";\n bfs(vertices, start);\n cout << endl;\n}"
},
{
"code": null,
"e": 3887,
"s": 3860,
"text": "BFS Traversal: B A D E C F"
}
] |
Check whether a given graph is Bipartite or not - GeeksforGeeks
|
23 Feb, 2022
A Bipartite Graph is a graph whose vertices can be divided into two independent sets, U and V such that every edge (u, v) either connects a vertex from U to V or a vertex from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, or u belongs to V and v to U. We can also say that there is no edge that connects vertices of same set.
A bipartite graph is possible if the graph coloring is possible using two colors such that vertices in a set are colored with the same color. Note that it is possible to color a cycle graph with even cycle using two colors. For example, see the following graph.
It is not possible to color a cycle graph with odd cycle using two colors.
Algorithm to check if a graph is Bipartite: One approach is to check whether the graph is 2-colorable or not using backtracking algorithm m coloring problem. Following is a simple algorithm to find out whether a given graph is Bipartite or not using Breadth First Search (BFS). 1. Assign RED color to the source vertex (putting into set U). 2. Color all the neighbors with BLUE color (putting into set V). 3. Color all neighbor’s neighbor with RED color (putting into set U). 4. This way, assign color to all vertices such that it satisfies all the constraints of m way coloring problem where m = 2. 5. While assigning colors, if we find a neighbor which is colored with same color as current vertex, then the graph cannot be colored with 2 vertices (or graph is not Bipartite)
C++
Java
Python3
C#
Javascript
// C++ program to find out whether a// given graph is Bipartite or not#include <iostream>#include <queue>#define V 4 using namespace std; // This function returns true if graph// G[V][V] is Bipartite, else falsebool isBipartite(int G[][V], int src){ // Create a color array to store colors // assigned to all vertices. Vertex // number is used as index in this array. // The value '-1' of colorArr[i] // is used to indicate that no color // is assigned to vertex 'i'. The value 1 // is used to indicate first color // is assigned and value 0 indicates // second color is assigned. int colorArr[V]; for (int i = 0; i < V; ++i) colorArr[i] = -1; // Assign first color to source colorArr[src] = 1; // Create a queue (FIFO) of vertex // numbers and enqueue source vertex // for BFS traversal queue <int> q; q.push(src); // Run while there are vertices // in queue (Similar to BFS) while (!q.empty()) { // Dequeue a vertex from queue ( Refer http://goo.gl/35oz8 ) int u = q.front(); q.pop(); // Return false if there is a self-loop if (G[u][u] == 1) return false; // Find all non-colored adjacent vertices for (int v = 0; v < V; ++v) { // An edge from u to v exists and // destination v is not colored if (G[u][v] && colorArr[v] == -1) { // Assign alternate color to this adjacent v of u colorArr[v] = 1 - colorArr[u]; q.push(v); } // An edge from u to v exists and destination // v is colored with same color as u else if (G[u][v] && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all adjacent // vertices can be colored with alternate color return true;} // Driver program to test above functionint main(){ int G[][V] = {{0, 1, 0, 1}, {1, 0, 1, 0}, {0, 1, 0, 1}, {1, 0, 1, 0} }; isBipartite(G, 0) ? cout << "Yes" : cout << "No"; return 0;}
// Java program to find out whether// a given graph is Bipartite or notimport java.util.*;import java.lang.*;import java.io.*; class Bipartite{ final static int V = 4; // No. of Vertices // This function returns true if // graph G[V][V] is Bipartite, else false boolean isBipartite(int G[][],int src) { // Create a color array to store // colors assigned to all vertices. // Vertex number is used as index // in this array. The value '-1' // of colorArr[i] is used to indicate // that no color is assigned // to vertex 'i'. The value 1 is // used to indicate first color // is assigned and value 0 indicates // second color is assigned. int colorArr[] = new int[V]; for (int i=0; i<V; ++i) colorArr[i] = -1; // Assign first color to source colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers // and enqueue source vertex for BFS traversal LinkedList<Integer>q = new LinkedList<Integer>(); q.add(src); // Run while there are vertices in queue (Similar to BFS) while (q.size() != 0) { // Dequeue a vertex from queue int u = q.poll(); // Return false if there is a self-loop if (G[u][u] == 1) return false; // Find all non-colored adjacent vertices for (int v=0; v<V; ++v) { // An edge from u to v exists // and destination v is not colored if (G[u][v]==1 && colorArr[v]==-1) { // Assign alternate color to this adjacent v of u colorArr[v] = 1-colorArr[u]; q.add(v); } // An edge from u to v exists and destination // v is colored with same color as u else if (G[u][v]==1 && colorArr[v]==colorArr[u]) return false; } } // If we reach here, then all adjacent vertices can // be colored with alternate color return true; } // Driver program to test above function public static void main (String[] args) { int G[][] = {{0, 1, 0, 1}, {1, 0, 1, 0}, {0, 1, 0, 1}, {1, 0, 1, 0} }; Bipartite b = new Bipartite(); if (b.isBipartite(G, 0)) System.out.println("Yes"); else System.out.println("No"); }} // Contributed by Aakash Hasija
# Python program to find out whether a# given graph is Bipartite or not class Graph(): def __init__(self, V): self.V = V self.graph = [[0 for column in range(V)] \ for row in range(V)] # This function returns true if graph G[V][V] # is Bipartite, else false def isBipartite(self, src): # Create a color array to store colors # assigned to all vertices. Vertex # number is used as index in this array. # The value '-1' of colorArr[i] is used to # indicate that no color is assigned to # vertex 'i'. The value 1 is used to indicate # first color is assigned and value 0 # indicates second color is assigned. colorArr = [-1] * self.V # Assign first color to source colorArr[src] = 1 # Create a queue (FIFO) of vertex numbers and # enqueue source vertex for BFS traversal queue = [] queue.append(src) # Run while there are vertices in queue # (Similar to BFS) while queue: u = queue.pop() # Return false if there is a self-loop if self.graph[u][u] == 1: return False; for v in range(self.V): # An edge from u to v exists and destination # v is not colored if self.graph[u][v] == 1 and colorArr[v] == -1: # Assign alternate color to this # adjacent v of u colorArr[v] = 1 - colorArr[u] queue.append(v) # An edge from u to v exists and destination # v is colored with same color as u elif self.graph[u][v] == 1 and colorArr[v] == colorArr[u]: return False # If we reach here, then all adjacent # vertices can be colored with alternate # color return True # Driver program to test above functiong = Graph(4)g.graph = [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0] ] print ("Yes" if g.isBipartite(0) else "No") # This code is contributed by Divyanshu Mehta
// C# program to find out whether// a given graph is Bipartite or notusing System;using System.Collections.Generic; class GFG{ readonly static int V = 4; // No. of Vertices // This function returns true if // graph G[V,V] is Bipartite, else false bool isBipartite(int [,]G, int src) { // Create a color array to store // colors assigned to all vertices. // Vertex number is used as index // in this array. The value '-1' // of colorArr[i] is used to indicate // that no color is assigned // to vertex 'i'. The value 1 is // used to indicate first color // is assigned and value 0 indicates // second color is assigned. int []colorArr = new int[V]; for (int i = 0; i < V; ++i) colorArr[i] = -1; // Assign first color to source colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers // and enqueue source vertex for BFS traversal List<int>q = new List<int>(); q.Add(src); // Run while there are vertices // in queue (Similar to BFS) while (q.Count != 0) { // Dequeue a vertex from queue int u = q[0]; q.RemoveAt(0); // Return false if there is a self-loop if (G[u, u] == 1) return false; // Find all non-colored adjacent vertices for (int v = 0; v < V; ++v) { // An edge from u to v exists // and destination v is not colored if (G[u, v] == 1 && colorArr[v] == -1) { // Assign alternate color // to this adjacent v of u colorArr[v] = 1 - colorArr[u]; q.Add(v); } // An edge from u to v exists and // destination v is colored with // same color as u else if (G[u, v] == 1 && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all adjacent vertices // can be colored with alternate color return true; } // Driver Code public static void Main(String[] args) { int [,]G = {{0, 1, 0, 1}, {1, 0, 1, 0}, {0, 1, 0, 1}, {1, 0, 1, 0}}; GFG b = new GFG(); if (b.isBipartite(G, 0)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Rajput-Ji
<script>// Javascript program to find out whether// a given graph is Bipartite or not let V = 4; // No. of Vertices // This function returns true if // graph G[V][V] is Bipartite, else falsefunction isBipartite(G,src){ // Create a color array to store // colors assigned to all vertices. // Vertex number is used as index // in this array. The value '-1' // of colorArr[i] is used to indicate // that no color is assigned // to vertex 'i'. The value 1 is // used to indicate first color // is assigned and value 0 indicates // second color is assigned. let colorArr = new Array(V); for (let i=0; i<V; ++i) colorArr[i] = -1; // Assign first color to source colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers // and enqueue source vertex for BFS traversal let q = []; q.push(src); // Run while there are vertices in queue (Similar to BFS) while (q.length != 0) { // Dequeue a vertex from queue let u = q.shift(); // Return false if there is a self-loop if (G[u][u] == 1) return false; // Find all non-colored adjacent vertices for (let v=0; v<V; ++v) { // An edge from u to v exists // and destination v is not colored if (G[u][v]==1 && colorArr[v]==-1) { // Assign alternate color to this adjacent v of u colorArr[v] = 1-colorArr[u]; q.push(v); } // An edge from u to v exists and destination // v is colored with same color as u else if (G[u][v]==1 && colorArr[v]==colorArr[u]) return false; } } // If we reach here, then all adjacent vertices can // be colored with alternate color return true;} // Driver program to test above functionlet G=[[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]; if (isBipartite(G, 0)) document.write("Yes");else document.write("No"); // This code is contributed by avanitrachhadiya2155</script>
Output:
Yes
The above algorithm works only if the graph is connected. In above code, we always start with source 0 and assume that vertices are visited from it. One important observation is a graph with no edges is also Bipartite. Note that the Bipartite condition says all edges should be from one set to another.
We can extend the above code to handle cases when a graph is not connected. The idea is repeatedly called above method for all not yet visited vertices.
C++
Java
Python3
C#
Javascript
// C++ program to find out whether// a given graph is Bipartite or not.// It works for disconnected graph also.#include <bits/stdc++.h> using namespace std; const int V = 4; // This function returns true if// graph G[V][V] is Bipartite, else falsebool isBipartiteUtil(int G[][V], int src, int colorArr[]){ colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers a // nd enqueue source vertex for BFS traversal queue<int> q; q.push(src); // Run while there are vertices in queue (Similar to // BFS) while (!q.empty()) { // Dequeue a vertex from queue ( Refer // http://goo.gl/35oz8 ) int u = q.front(); q.pop(); // Return false if there is a self-loop if (G[u][u] == 1) return false; // Find all non-colored adjacent vertices for (int v = 0; v < V; ++v) { // An edge from u to v exists and // destination v is not colored if (G[u][v] && colorArr[v] == -1) { // Assign alternate color to this // adjacent v of u colorArr[v] = 1 - colorArr[u]; q.push(v); } // An edge from u to v exists and destination // v is colored with same color as u else if (G[u][v] && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all adjacent vertices can // be colored with alternate color return true;} // Returns true if G[][] is Bipartite, else falsebool isBipartite(int G[][V]){ // Create a color array to store colors assigned to all // vertices. Vertex/ number is used as index in this // array. The value '-1' of colorArr[i] is used to // indicate that no color is assigned to vertex 'i'. // The value 1 is used to indicate first color is // assigned and value 0 indicates second color is // assigned. int colorArr[V]; for (int i = 0; i < V; ++i) colorArr[i] = -1; // This code is to handle disconnected graph for (int i = 0; i < V; i++) if (colorArr[i] == -1) if (isBipartiteUtil(G, i, colorArr) == false) return false; return true;} // Driver codeint main(){ int G[][V] = { { 0, 1, 0, 1 }, { 1, 0, 1, 0 }, { 0, 1, 0, 1 }, { 1, 0, 1, 0 } }; isBipartite(G) ? cout << "Yes" : cout << "No"; return 0;}
// JAVA Code to check whether a given// graph is Bipartite or notimport java.util.*; class Bipartite { public static int V = 4; // This function returns true if graph // G[V][V] is Bipartite, else false public static boolean isBipartiteUtil(int G[][], int src, int colorArr[]) { colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers and // enqueue source vertex for BFS traversal LinkedList<Integer> q = new LinkedList<Integer>(); q.add(src); // Run while there are vertices in queue // (Similar to BFS) while (!q.isEmpty()) { // Dequeue a vertex from queue // ( Refer http://goo.gl/35oz8 ) int u = q.getFirst(); q.pop(); // Return false if there is a self-loop if (G[u][u] == 1) return false; // Find all non-colored adjacent vertices for (int v = 0; v < V; ++v) { // An edge from u to v exists and // destination v is not colored if (G[u][v] == 1 && colorArr[v] == -1) { // Assign alternate color to this // adjacent v of u colorArr[v] = 1 - colorArr[u]; q.push(v); } // An edge from u to v exists and // destination v is colored with same // color as u else if (G[u][v] == 1 && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all adjacent vertices // can be colored with alternate color return true; } // Returns true if G[][] is Bipartite, else false public static boolean isBipartite(int G[][]) { // Create a color array to store colors assigned // to all vertices. Vertex/ number is used as // index in this array. The value '-1' of // colorArr[i] is used to indicate that no color // is assigned to vertex 'i'. The value 1 is used // to indicate first color is assigned and value // 0 indicates second color is assigned. int colorArr[] = new int[V]; for (int i = 0; i < V; ++i) colorArr[i] = -1; // This code is to handle disconnected graph for (int i = 0; i < V; i++) if (colorArr[i] == -1) if (isBipartiteUtil(G, i, colorArr) == false) return false; return true; } /* Driver code*/ public static void main(String[] args) { int G[][] = { { 0, 1, 0, 1 }, { 1, 0, 1, 0 }, { 0, 1, 0, 1 }, { 1, 0, 1, 0 } }; if (isBipartite(G)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Arnav Kr. Mandal.
# Python3 program to find out whether a# given graph is Bipartite or not class Graph(): def __init__(self, V): self.V = V self.graph = [[0 for column in range(V)] for row in range(V)] self.colorArr = [-1 for i in range(self.V)] # This function returns true if graph G[V][V] # is Bipartite, else false def isBipartiteUtil(self, src): # Create a color array to store colors # assigned to all vertices. Vertex # number is used as index in this array. # The value '-1' of self.colorArr[i] is used # to indicate that no color is assigned to # vertex 'i'. The value 1 is used to indicate # first color is assigned and value 0 # indicates second color is assigned. # Assign first color to source # Create a queue (FIFO) of vertex numbers and # enqueue source vertex for BFS traversal queue = [] queue.append(src) # Run while there are vertices in queue # (Similar to BFS) while queue: u = queue.pop() # Return false if there is a self-loop if self.graph[u][u] == 1: return False for v in range(self.V): # An edge from u to v exists and # destination v is not colored if (self.graph[u][v] == 1 and self.colorArr[v] == -1): # Assign alternate color to # this adjacent v of u self.colorArr[v] = 1 - self.colorArr[u] queue.append(v) # An edge from u to v exists and destination # v is colored with same color as u elif (self.graph[u][v] == 1 and self.colorArr[v] == self.colorArr[u]): return False # If we reach here, then all adjacent # vertices can be colored with alternate # color return True def isBipartite(self): self.colorArr = [-1 for i in range(self.V)] for i in range(self.V): if self.colorArr[i] == -1: if not self.isBipartiteUtil(i): return False return True # Driver Codeg = Graph(4)g.graph = [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]] print ("Yes" if g.isBipartite() else "No") # This code is contributed by Anshuman Sharma
// C# Code to check whether a given// graph is Bipartite or notusing System;using System.Collections.Generic; class GFG { public static int V = 4; // This function returns true if graph // G[V,V] is Bipartite, else false public static bool isBipartiteUtil(int[, ] G, int src, int[] colorArr) { colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers and // enqueue source vertex for BFS traversal Queue<int> q = new Queue<int>(); q.Enqueue(src); // Run while there are vertices in queue // (Similar to BFS) while (q.Count != 0) { // Dequeue a vertex from queue // ( Refer http://goo.gl/35oz8 ) int u = q.Peek(); q.Dequeue(); // Return false if there is a self-loop if (G[u, u] == 1) return false; // Find all non-colored adjacent vertices for (int v = 0; v < V; ++v) { // An edge from u to v exists and // destination v is not colored if (G[u, v] == 1 && colorArr[v] == -1) { // Assign alternate color to this // adjacent v of u colorArr[v] = 1 - colorArr[u]; q.Enqueue(v); } // An edge from u to v exists and // destination v is colored with same // color as u else if (G[u, v] == 1 && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all // adjacent vertices can be colored // with alternate color return true; } // Returns true if G[,] is Bipartite, // else false public static bool isBipartite(int[, ] G) { // Create a color array to store // colors assigned to all vertices. // Vertex/ number is used as // index in this array. The value '-1' // of colorArr[i] is used to indicate // that no color is assigned to vertex 'i'. // The value 1 is used to indicate // first color is assigned and value // 0 indicates second color is assigned. int[] colorArr = new int[V]; for (int i = 0; i < V; ++i) colorArr[i] = -1; // This code is to handle disconnected graph for (int i = 0; i < V; i++) if (colorArr[i] == -1) if (isBipartiteUtil(G, i, colorArr) == false) return false; return true; } // Driver Code public static void Main(String[] args) { int[, ] G = { { 0, 1, 0, 1 }, { 1, 0, 1, 0 }, { 0, 1, 0, 1 }, { 1, 0, 1, 0 } }; if (isBipartite(G)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Rajput-Ji
<script>// Javascript Code to check whether a given// graph is Bipartite or notvar V = 4; // This function returns true if graph// G[V,V] is Bipartite, else falsefunction isBipartiteUtil(G, src, colorArr){ colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers and // enqueue source vertex for BFS traversal var q = []; q.push(src); // Run while there are vertices in queue // (Similar to BFS) while (q.length != 0) { // Dequeue a vertex from queue // ( Refer http://goo.gl/35oz8 ) var u = q[0]; q.shift(); // Return false if there is a self-loop if (G[u, u] == 1) return false; // Find all non-colored adjacent vertices for (var v = 0; v < V; ++v) { // An edge from u to v exists and // destination v is not colored if (G[u][v] == 1 && colorArr[v] == -1) { // Assign alternate color to this // adjacent v of u colorArr[v] = 1 - colorArr[u]; q.push(v); } // An edge from u to v exists and // destination v is colored with same // color as u else if (G[u, v] == 1 && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all // adjacent vertices can be colored // with alternate color return true;} // Returns true if G[,] is Bipartite,// else falsefunction isBipartite(G){ // Create a color array to store // colors assigned to all vertices. // Vertex/ number is used as // index in this array. The value '-1' // of colorArr[i] is used to indicate // that no color is assigned to vertex 'i'. // The value 1 is used to indicate // first color is assigned and value // 0 indicates second color is assigned. var colorArr = Array(V); for (var i = 0; i < V; ++i) colorArr[i] = -1; // This code is to handle disconnected graph for (var i = 0; i < V; i++) if (colorArr[i] == -1) if (isBipartiteUtil(G, i, colorArr) == false) return false; return true;} // Driver Codevar G = [ [ 0, 1, 0, 1 ], [ 1, 0, 1, 0 ], [ 0, 1, 0, 1 ], [ 1, 0, 1, 0 ] ];if (isBipartite(G)) document.write("Yes");else document.write("No"); // This code is contributed by rrrtnx.</script>
Output:
Yes
Time Complexity of the above approach is same as that Breadth First Search. In above implementation is O(V^2) where V is number of vertices. If graph is represented using adjacency list, then the complexity becomes O(V+E).
If Graph is represented using Adjacency List .Time Complexity will be O(V+E).
Works for connected as well as disconnected graph.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; bool isBipartite(int V, vector<int> adj[]){ // vector to store colour of vertex // assigning all to -1 i.e. uncoloured // colours are either 0 or 1 // for understanding take 0 as red and 1 as blue vector<int> col(V, -1); // queue for BFS storing {vertex , colour} queue<pair<int, int> > q; //loop incase graph is not connected for (int i = 0; i < V; i++) { //if not coloured if (col[i] == -1) { //colouring with 0 i.e. red q.push({ i, 0 }); col[i] = 0; while (!q.empty()) { pair<int, int> p = q.front(); q.pop(); //current vertex int v = p.first; //colour of current vertex int c = p.second; //traversing vertexes connected to current vertex for (int j : adj[v]) { //if already coloured with parent vertex color //then bipartite graph is not possible if (col[j] == c) return 0; //if uncoloured if (col[j] == -1) { //colouring with opposite color to that of parent col[j] = (c) ? 0 : 1; q.push({ j, col[j] }); } } } } } //if all vertexes are coloured such that //no two connected vertex have same colours return 1;} // { Driver Code Starts.int main(){ int V, E; V = 4 , E = 8; //adjacency list for storing graph vector<int> adj[V]; adj[0] = {1,3}; adj[1] = {0,2}; adj[2] = {1,3}; adj[3] = {0,2}; bool ans = isBipartite(V, adj); //returns 1 if bipartite graph is possible if (ans) cout << "Yes\n"; //returns 0 if bipartite graph is not possible else cout << "No\n"; return 0;} // code Contributed By Devendra Kolhe
import java.util.*; public class GFG{ static class Pair{ int first, second; Pair(int f, int s){ first = f; second = s; } } static boolean isBipartite(int V, ArrayList<ArrayList<Integer>> adj) { // vector to store colour of vertex // assigning all to -1 i.e. uncoloured // colours are either 0 or 1 // for understanding take 0 as red and 1 as blue int col[] = new int[V]; Arrays.fill(col, -1); // queue for BFS storing {vertex , colour} Queue<Pair> q = new LinkedList<Pair>(); //loop incase graph is not connected for (int i = 0; i < V; i++) { // if not coloured if (col[i] == -1) { // colouring with 0 i.e. red q.add(new Pair(i, 0)); col[i] = 0; while (!q.isEmpty()) { Pair p = q.peek(); q.poll(); //current vertex int v = p.first; // colour of current vertex int c = p.second; // traversing vertexes connected to current vertex for (int j : adj.get(v)) { // if already coloured with parent vertex color // then bipartite graph is not possible if (col[j] == c) return false; // if uncoloured if (col[j] == -1) { // colouring with opposite color to that of parent col[j] = (c==1) ? 0 : 1; q.add(new Pair(j, col[j])); } } } } } // if all vertexes are coloured such that // no two connected vertex have same colours return true; } // Driver Code Starts. public static void main(String args[]) { int V, E; V = 4 ; E = 8; // adjacency list for storing graph ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < V; i++){ adj.add(new ArrayList<Integer>()); } adj.get(0).add(1); adj.get(0).add(3); adj.get(1).add(0); adj.get(1).add(2); adj.get(2).add(1); adj.get(2).add(3); adj.get(3).add(0); adj.get(3).add(2); boolean ans = isBipartite(V, adj); // returns 1 if bipartite graph is possible if (ans) System.out.println("Yes"); // returns 0 if bipartite graph is not possible else System.out.println("No"); }} // This code is contributed by adityapande88.
def isBipartite(V, adj): # vector to store colour of vertex # assigning all to -1 i.e. uncoloured # colours are either 0 or 1 # for understanding take 0 as red and 1 as blue col = [-1]*(V) # queue for BFS storing {vertex , colour} q = [] #loop incase graph is not connected for i in range(V): # if not coloured if (col[i] == -1): # colouring with 0 i.e. red q.append([i, 0]) col[i] = 0 while len(q) != 0: p = q[0] q.pop(0) # current vertex v = p[0] # colour of current vertex c = p[1] # traversing vertexes connected to current vertex for j in adj[v]: # if already coloured with parent vertex color # then bipartite graph is not possible if (col[j] == c): return False # if uncoloured if (col[j] == -1): # colouring with opposite color to that of parent if c == 1: col[j] = 0 else: col[j] = 1 q.append([j, col[j]]) # if all vertexes are coloured such that # no two connected vertex have same colours return True V, E = 4, 8 # adjacency list for storing graphadj = []adj.append([1,3])adj.append([0,2])adj.append([1,3])adj.append([0,2]) ans = isBipartite(V, adj) # returns 1 if bipartite graph is possibleif (ans): print("Yes") # returns 0 if bipartite graph is not possibleelse: print("No") # This code is contributed by divyesh072019.
using System;using System.Collections.Generic;class GFG { static bool isBipartite(int V, List<List<int>> adj) { // vector to store colour of vertex // assigning all to -1 i.e. uncoloured // colours are either 0 or 1 // for understanding take 0 as red and 1 as blue int[] col = new int[V]; Array.Fill(col, -1); // queue for BFS storing {vertex , colour} List<Tuple<int,int>> q = new List<Tuple<int,int>>(); //loop incase graph is not connected for (int i = 0; i < V; i++) { // if not coloured if (col[i] == -1) { // colouring with 0 i.e. red q.Add(new Tuple<int,int>(i, 0)); col[i] = 0; while (q.Count > 0) { Tuple<int,int> p = q[0]; q.RemoveAt(0); //current vertex int v = p.Item1; // colour of current vertex int c = p.Item2; // traversing vertexes connected to current vertex foreach(int j in adj[v]) { // if already coloured with parent vertex color // then bipartite graph is not possible if (col[j] == c) return false; // if uncoloured if (col[j] == -1) { // colouring with opposite color to that of parent col[j] = (c==1) ? 0 : 1; q.Add(new Tuple<int,int>(j, col[j])); } } } } } // if all vertexes are coloured such that // no two connected vertex have same colours return true; } static void Main() { int V; V = 4 ; // adjacency list for storing graph List<List<int>> adj = new List<List<int>>(); for(int i = 0; i < V; i++){ adj.Add(new List<int>()); } adj[0].Add(1); adj[0].Add(3); adj[1].Add(0); adj[1].Add(2); adj[2].Add(1); adj[2].Add(3); adj[3].Add(0); adj[3].Add(2); bool ans = isBipartite(V, adj); // returns 1 if bipartite graph is possible if (ans) Console.WriteLine("Yes"); // returns 0 if bipartite graph is not possible else Console.WriteLine("No"); }} // This code is contributed by decode2207.
<script>class Pair{ constructor(f,s) { this.first = f; this.second = s; }} function isBipartite(V, adj){ // vector to store colour of vertex // assigning all to -1 i.e. uncoloured // colours are either 0 or 1 // for understanding take 0 as red and 1 as blue let col = new Array(V); for(let i = 0; i < V; i++) col[i] = -1; // queue for BFS storing {vertex , colour} let q = []; //loop incase graph is not connected for (let i = 0; i < V; i++) { // if not coloured if (col[i] == -1) { // colouring with 0 i.e. red q.push(new Pair(i, 0)); col[i] = 0; while (q.length!=0) { let p = q[0]; q.shift(); //current vertex let v = p.first; // colour of current vertex let c = p.second; // traversing vertexes connected to current vertex for (let j of adj[v]) { // if already coloured with parent vertex color // then bipartite graph is not possible if (col[j] == c) return false; // if uncoloured if (col[j] == -1) { // colouring with opposite color to that of parent col[j] = (c==1) ? 0 : 1; q.push(new Pair(j, col[j])); } } } } } // if all vertexes are coloured such that // no two connected vertex have same colours return true;} // Driver Code Starts.let V, E; V = 4 ; E = 8; // adjacency list for storing graph let adj = []; for(let i = 0; i < V; i++){ adj.push([]); } adj[0].push(1); adj[0].push(3); adj[1].push(0); adj[1].push(2); adj[2].push(1); adj[2].push(3); adj[3].push(0); adj[3].push(2); let ans = isBipartite(V, adj); // returns 1 if bipartite graph is possible if (ans) document.write("Yes"); // returns 0 if bipartite graph is not possible else document.write("No"); // This code is contributed by patel2127</script>
Yes
Exercise: 1. Can DFS algorithm be used to check the bipartite-ness of a graph? If yes, how? Solution :
C++
Java
Python3
C#
Javascript
// C++ program to find out whether a given graph is Bipartite or not.// Using recursion.#include <iostream> using namespace std;#define V 4 bool colorGraph(int G[][V],int color[],int pos, int c){ if(color[pos] != -1 && color[pos] !=c) return false; // color this pos as c and all its neighbours and 1-c color[pos] = c; bool ans = true; for(int i=0;i<V;i++){ if(G[pos][i]){ if(color[i] == -1) ans &= colorGraph(G,color,i,1-c); if(color[i] !=-1 && color[i] != 1-c) return false; } if (!ans) return false; } return true;} bool isBipartite(int G[][V]){ int color[V]; for(int i=0;i<V;i++) color[i] = -1; //start is vertex 0; int pos = 0; // two colors 1 and 0 return colorGraph(G,color,pos,1); } int main(){ int G[][V] = {{0, 1, 0, 1}, {1, 0, 1, 0}, {0, 1, 0, 1}, {1, 0, 1, 0} }; isBipartite(G) ? cout<< "Yes" : cout << "No"; return 0;}// This code is contributed By Mudit Verma
// Java program to find out whether// a given graph is Bipartite or not.// Using recursion.class GFG{ static final int V = 4; static boolean colorGraph(int G[][], int color[], int pos, int c) { if (color[pos] != -1 && color[pos] != c) return false; // color this pos as c and // all its neighbours as 1-c color[pos] = c; boolean ans = true; for (int i = 0; i < V; i++) { if (G[pos][i] == 1) { if (color[i] == -1) ans &= colorGraph(G, color, i, 1 - c); if (color[i] != -1 && color[i] != 1 - c) return false; } if (!ans) return false; } return true; } static boolean isBipartite(int G[][]) { int[] color = new int[V]; for (int i = 0; i < V; i++) color[i] = -1; // start is vertex 0; int pos = 0; // two colors 1 and 0 return colorGraph(G, color, pos, 1); } // Driver Code public static void main(String[] args) { int G[][] = { { 0, 1, 0, 1 }, { 1, 0, 1, 0 }, { 0, 1, 0, 1 }, { 1, 0, 1, 0 } }; if (isBipartite(G)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by Rajput-Ji
# Python3 program to find out whether a given# graph is Bipartite or not using recursion.V = 4 def colorGraph(G, color, pos, c): if color[pos] != -1 and color[pos] != c: return False # color this pos as c and all its neighbours and 1-c color[pos] = c ans = True for i in range(0, V): if G[pos][i]: if color[i] == -1: ans &= colorGraph(G, color, i, 1-c) if color[i] !=-1 and color[i] != 1-c: return False if not ans: return False return True def isBipartite(G): color = [-1] * V #start is vertex 0 pos = 0 # two colors 1 and 0 return colorGraph(G, color, pos, 1) if __name__ == "__main__": G = [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]] if isBipartite(G): print("Yes") else: print("No") # This code is contributed by Rituraj Jain
// C# program to find out whether// a given graph is Bipartite or not.// Using recursion.using System; class GFG{ static readonly int V = 4; static bool colorGraph(int [,]G, int []color, int pos, int c) { if (color[pos] != -1 && color[pos] != c) return false; // color this pos as c and // all its neighbours as 1-c color[pos] = c; bool ans = true; for (int i = 0; i < V; i++) { if (G[pos, i] == 1) { if (color[i] == -1) ans &= colorGraph(G, color, i, 1 - c); if (color[i] != -1 && color[i] != 1 - c) return false; } if (!ans) return false; } return true; } static bool isBipartite(int [,]G) { int[] color = new int[V]; for (int i = 0; i < V; i++) color[i] = -1; // start is vertex 0; int pos = 0; // two colors 1 and 0 return colorGraph(G, color, pos, 1); } // Driver Code public static void Main(String[] args) { int [,]G = {{ 0, 1, 0, 1 }, { 1, 0, 1, 0 }, { 0, 1, 0, 1 }, { 1, 0, 1, 0 }}; if (isBipartite(G)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by 29AjayKumar
<script> // JavaScript program to find out whether // a given graph is Bipartite or not. // Using recursion. var V = 4; function colorGraph(G, color, pos, c) { if (color[pos] != -1 && color[pos] != c) return false; // color this pos as c and // all its neighbours as 1-c color[pos] = c; var ans = true; for (var i = 0; i < V; i++) { if (G[pos][i] == 1) { if (color[i] == -1) ans &= colorGraph(G, color, i, 1 - c); if (color[i] != -1 && color[i] != 1 - c) return false; } if (!ans) return false; } return true; } function isBipartite(G) { var color = new Array(V).fill(0); for (var i = 0; i < V; i++) color[i] = -1; // start is vertex 0; var pos = 0; // two colors 1 and 0 return colorGraph(G, color, pos, 1); } // Driver Code var G = [ [0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0], ]; if (isBipartite(G)) document.write("Yes"); else document.write("No"); // This code is contributed by rdtank. </script>
Yes
References: http://en.wikipedia.org/wiki/Graph_coloring http://en.wikipedia.org/wiki/Bipartite_graphThis article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Mudit Verma
anshumansharma
rituraj_jain
danielagfavero
Rajput-Ji
29AjayKumar
aanchaltiwari
dhawangupta08
devendrakolhe5
adityapande88
rrrtnx
rdtank
avanitrachhadiya2155
patel2127
kalrap615
surindertarika1234
anikakapoor
divyesh072019
decode2207
rs1686740
amartyaghoshgfg
simmytarika5
BFS
DFS
Graph Coloring
Samsung
Graph
Samsung
DFS
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Traveling Salesman Problem (TSP) Implementation
Ford-Fulkerson Algorithm for Maximum Flow Problem
Strongly Connected Components
Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)
Shortest path in an unweighted graph
Best First Search (Informed Search)
Find the number of islands | Set 1 (Using DFS)
|
[
{
"code": null,
"e": 34596,
"s": 34568,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 34957,
"s": 34596,
"text": "A Bipartite Graph is a graph whose vertices can be divided into two independent sets, U and V such that every edge (u, v) either connects a vertex from U to V or a vertex from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, or u belongs to V and v to U. We can also say that there is no edge that connects vertices of same set."
},
{
"code": null,
"e": 35220,
"s": 34957,
"text": "A bipartite graph is possible if the graph coloring is possible using two colors such that vertices in a set are colored with the same color. Note that it is possible to color a cycle graph with even cycle using two colors. For example, see the following graph. "
},
{
"code": null,
"e": 35296,
"s": 35220,
"text": "It is not possible to color a cycle graph with odd cycle using two colors. "
},
{
"code": null,
"e": 36075,
"s": 35296,
"text": "Algorithm to check if a graph is Bipartite: One approach is to check whether the graph is 2-colorable or not using backtracking algorithm m coloring problem. Following is a simple algorithm to find out whether a given graph is Bipartite or not using Breadth First Search (BFS). 1. Assign RED color to the source vertex (putting into set U). 2. Color all the neighbors with BLUE color (putting into set V). 3. Color all neighbor’s neighbor with RED color (putting into set U). 4. This way, assign color to all vertices such that it satisfies all the constraints of m way coloring problem where m = 2. 5. While assigning colors, if we find a neighbor which is colored with same color as current vertex, then the graph cannot be colored with 2 vertices (or graph is not Bipartite) "
},
{
"code": null,
"e": 36079,
"s": 36075,
"text": "C++"
},
{
"code": null,
"e": 36084,
"s": 36079,
"text": "Java"
},
{
"code": null,
"e": 36092,
"s": 36084,
"text": "Python3"
},
{
"code": null,
"e": 36095,
"s": 36092,
"text": "C#"
},
{
"code": null,
"e": 36106,
"s": 36095,
"text": "Javascript"
},
{
"code": "// C++ program to find out whether a// given graph is Bipartite or not#include <iostream>#include <queue>#define V 4 using namespace std; // This function returns true if graph// G[V][V] is Bipartite, else falsebool isBipartite(int G[][V], int src){ // Create a color array to store colors // assigned to all vertices. Vertex // number is used as index in this array. // The value '-1' of colorArr[i] // is used to indicate that no color // is assigned to vertex 'i'. The value 1 // is used to indicate first color // is assigned and value 0 indicates // second color is assigned. int colorArr[V]; for (int i = 0; i < V; ++i) colorArr[i] = -1; // Assign first color to source colorArr[src] = 1; // Create a queue (FIFO) of vertex // numbers and enqueue source vertex // for BFS traversal queue <int> q; q.push(src); // Run while there are vertices // in queue (Similar to BFS) while (!q.empty()) { // Dequeue a vertex from queue ( Refer http://goo.gl/35oz8 ) int u = q.front(); q.pop(); // Return false if there is a self-loop if (G[u][u] == 1) return false; // Find all non-colored adjacent vertices for (int v = 0; v < V; ++v) { // An edge from u to v exists and // destination v is not colored if (G[u][v] && colorArr[v] == -1) { // Assign alternate color to this adjacent v of u colorArr[v] = 1 - colorArr[u]; q.push(v); } // An edge from u to v exists and destination // v is colored with same color as u else if (G[u][v] && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all adjacent // vertices can be colored with alternate color return true;} // Driver program to test above functionint main(){ int G[][V] = {{0, 1, 0, 1}, {1, 0, 1, 0}, {0, 1, 0, 1}, {1, 0, 1, 0} }; isBipartite(G, 0) ? cout << \"Yes\" : cout << \"No\"; return 0;}",
"e": 38213,
"s": 36106,
"text": null
},
{
"code": "// Java program to find out whether// a given graph is Bipartite or notimport java.util.*;import java.lang.*;import java.io.*; class Bipartite{ final static int V = 4; // No. of Vertices // This function returns true if // graph G[V][V] is Bipartite, else false boolean isBipartite(int G[][],int src) { // Create a color array to store // colors assigned to all vertices. // Vertex number is used as index // in this array. The value '-1' // of colorArr[i] is used to indicate // that no color is assigned // to vertex 'i'. The value 1 is // used to indicate first color // is assigned and value 0 indicates // second color is assigned. int colorArr[] = new int[V]; for (int i=0; i<V; ++i) colorArr[i] = -1; // Assign first color to source colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers // and enqueue source vertex for BFS traversal LinkedList<Integer>q = new LinkedList<Integer>(); q.add(src); // Run while there are vertices in queue (Similar to BFS) while (q.size() != 0) { // Dequeue a vertex from queue int u = q.poll(); // Return false if there is a self-loop if (G[u][u] == 1) return false; // Find all non-colored adjacent vertices for (int v=0; v<V; ++v) { // An edge from u to v exists // and destination v is not colored if (G[u][v]==1 && colorArr[v]==-1) { // Assign alternate color to this adjacent v of u colorArr[v] = 1-colorArr[u]; q.add(v); } // An edge from u to v exists and destination // v is colored with same color as u else if (G[u][v]==1 && colorArr[v]==colorArr[u]) return false; } } // If we reach here, then all adjacent vertices can // be colored with alternate color return true; } // Driver program to test above function public static void main (String[] args) { int G[][] = {{0, 1, 0, 1}, {1, 0, 1, 0}, {0, 1, 0, 1}, {1, 0, 1, 0} }; Bipartite b = new Bipartite(); if (b.isBipartite(G, 0)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // Contributed by Aakash Hasija",
"e": 40750,
"s": 38213,
"text": null
},
{
"code": "# Python program to find out whether a# given graph is Bipartite or not class Graph(): def __init__(self, V): self.V = V self.graph = [[0 for column in range(V)] \\ for row in range(V)] # This function returns true if graph G[V][V] # is Bipartite, else false def isBipartite(self, src): # Create a color array to store colors # assigned to all vertices. Vertex # number is used as index in this array. # The value '-1' of colorArr[i] is used to # indicate that no color is assigned to # vertex 'i'. The value 1 is used to indicate # first color is assigned and value 0 # indicates second color is assigned. colorArr = [-1] * self.V # Assign first color to source colorArr[src] = 1 # Create a queue (FIFO) of vertex numbers and # enqueue source vertex for BFS traversal queue = [] queue.append(src) # Run while there are vertices in queue # (Similar to BFS) while queue: u = queue.pop() # Return false if there is a self-loop if self.graph[u][u] == 1: return False; for v in range(self.V): # An edge from u to v exists and destination # v is not colored if self.graph[u][v] == 1 and colorArr[v] == -1: # Assign alternate color to this # adjacent v of u colorArr[v] = 1 - colorArr[u] queue.append(v) # An edge from u to v exists and destination # v is colored with same color as u elif self.graph[u][v] == 1 and colorArr[v] == colorArr[u]: return False # If we reach here, then all adjacent # vertices can be colored with alternate # color return True # Driver program to test above functiong = Graph(4)g.graph = [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0] ] print (\"Yes\" if g.isBipartite(0) else \"No\") # This code is contributed by Divyanshu Mehta",
"e": 42933,
"s": 40750,
"text": null
},
{
"code": "// C# program to find out whether// a given graph is Bipartite or notusing System;using System.Collections.Generic; class GFG{ readonly static int V = 4; // No. of Vertices // This function returns true if // graph G[V,V] is Bipartite, else false bool isBipartite(int [,]G, int src) { // Create a color array to store // colors assigned to all vertices. // Vertex number is used as index // in this array. The value '-1' // of colorArr[i] is used to indicate // that no color is assigned // to vertex 'i'. The value 1 is // used to indicate first color // is assigned and value 0 indicates // second color is assigned. int []colorArr = new int[V]; for (int i = 0; i < V; ++i) colorArr[i] = -1; // Assign first color to source colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers // and enqueue source vertex for BFS traversal List<int>q = new List<int>(); q.Add(src); // Run while there are vertices // in queue (Similar to BFS) while (q.Count != 0) { // Dequeue a vertex from queue int u = q[0]; q.RemoveAt(0); // Return false if there is a self-loop if (G[u, u] == 1) return false; // Find all non-colored adjacent vertices for (int v = 0; v < V; ++v) { // An edge from u to v exists // and destination v is not colored if (G[u, v] == 1 && colorArr[v] == -1) { // Assign alternate color // to this adjacent v of u colorArr[v] = 1 - colorArr[u]; q.Add(v); } // An edge from u to v exists and // destination v is colored with // same color as u else if (G[u, v] == 1 && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all adjacent vertices // can be colored with alternate color return true; } // Driver Code public static void Main(String[] args) { int [,]G = {{0, 1, 0, 1}, {1, 0, 1, 0}, {0, 1, 0, 1}, {1, 0, 1, 0}}; GFG b = new GFG(); if (b.isBipartite(G, 0)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Rajput-Ji",
"e": 45544,
"s": 42933,
"text": null
},
{
"code": "<script>// Javascript program to find out whether// a given graph is Bipartite or not let V = 4; // No. of Vertices // This function returns true if // graph G[V][V] is Bipartite, else falsefunction isBipartite(G,src){ // Create a color array to store // colors assigned to all vertices. // Vertex number is used as index // in this array. The value '-1' // of colorArr[i] is used to indicate // that no color is assigned // to vertex 'i'. The value 1 is // used to indicate first color // is assigned and value 0 indicates // second color is assigned. let colorArr = new Array(V); for (let i=0; i<V; ++i) colorArr[i] = -1; // Assign first color to source colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers // and enqueue source vertex for BFS traversal let q = []; q.push(src); // Run while there are vertices in queue (Similar to BFS) while (q.length != 0) { // Dequeue a vertex from queue let u = q.shift(); // Return false if there is a self-loop if (G[u][u] == 1) return false; // Find all non-colored adjacent vertices for (let v=0; v<V; ++v) { // An edge from u to v exists // and destination v is not colored if (G[u][v]==1 && colorArr[v]==-1) { // Assign alternate color to this adjacent v of u colorArr[v] = 1-colorArr[u]; q.push(v); } // An edge from u to v exists and destination // v is colored with same color as u else if (G[u][v]==1 && colorArr[v]==colorArr[u]) return false; } } // If we reach here, then all adjacent vertices can // be colored with alternate color return true;} // Driver program to test above functionlet G=[[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]; if (isBipartite(G, 0)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by avanitrachhadiya2155</script>",
"e": 47826,
"s": 45544,
"text": null
},
{
"code": null,
"e": 47835,
"s": 47826,
"text": "Output: "
},
{
"code": null,
"e": 47839,
"s": 47835,
"text": "Yes"
},
{
"code": null,
"e": 48142,
"s": 47839,
"text": "The above algorithm works only if the graph is connected. In above code, we always start with source 0 and assume that vertices are visited from it. One important observation is a graph with no edges is also Bipartite. Note that the Bipartite condition says all edges should be from one set to another."
},
{
"code": null,
"e": 48296,
"s": 48142,
"text": "We can extend the above code to handle cases when a graph is not connected. The idea is repeatedly called above method for all not yet visited vertices. "
},
{
"code": null,
"e": 48300,
"s": 48296,
"text": "C++"
},
{
"code": null,
"e": 48305,
"s": 48300,
"text": "Java"
},
{
"code": null,
"e": 48313,
"s": 48305,
"text": "Python3"
},
{
"code": null,
"e": 48316,
"s": 48313,
"text": "C#"
},
{
"code": null,
"e": 48327,
"s": 48316,
"text": "Javascript"
},
{
"code": "// C++ program to find out whether// a given graph is Bipartite or not.// It works for disconnected graph also.#include <bits/stdc++.h> using namespace std; const int V = 4; // This function returns true if// graph G[V][V] is Bipartite, else falsebool isBipartiteUtil(int G[][V], int src, int colorArr[]){ colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers a // nd enqueue source vertex for BFS traversal queue<int> q; q.push(src); // Run while there are vertices in queue (Similar to // BFS) while (!q.empty()) { // Dequeue a vertex from queue ( Refer // http://goo.gl/35oz8 ) int u = q.front(); q.pop(); // Return false if there is a self-loop if (G[u][u] == 1) return false; // Find all non-colored adjacent vertices for (int v = 0; v < V; ++v) { // An edge from u to v exists and // destination v is not colored if (G[u][v] && colorArr[v] == -1) { // Assign alternate color to this // adjacent v of u colorArr[v] = 1 - colorArr[u]; q.push(v); } // An edge from u to v exists and destination // v is colored with same color as u else if (G[u][v] && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all adjacent vertices can // be colored with alternate color return true;} // Returns true if G[][] is Bipartite, else falsebool isBipartite(int G[][V]){ // Create a color array to store colors assigned to all // vertices. Vertex/ number is used as index in this // array. The value '-1' of colorArr[i] is used to // indicate that no color is assigned to vertex 'i'. // The value 1 is used to indicate first color is // assigned and value 0 indicates second color is // assigned. int colorArr[V]; for (int i = 0; i < V; ++i) colorArr[i] = -1; // This code is to handle disconnected graph for (int i = 0; i < V; i++) if (colorArr[i] == -1) if (isBipartiteUtil(G, i, colorArr) == false) return false; return true;} // Driver codeint main(){ int G[][V] = { { 0, 1, 0, 1 }, { 1, 0, 1, 0 }, { 0, 1, 0, 1 }, { 1, 0, 1, 0 } }; isBipartite(G) ? cout << \"Yes\" : cout << \"No\"; return 0;}",
"e": 50750,
"s": 48327,
"text": null
},
{
"code": "// JAVA Code to check whether a given// graph is Bipartite or notimport java.util.*; class Bipartite { public static int V = 4; // This function returns true if graph // G[V][V] is Bipartite, else false public static boolean isBipartiteUtil(int G[][], int src, int colorArr[]) { colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers and // enqueue source vertex for BFS traversal LinkedList<Integer> q = new LinkedList<Integer>(); q.add(src); // Run while there are vertices in queue // (Similar to BFS) while (!q.isEmpty()) { // Dequeue a vertex from queue // ( Refer http://goo.gl/35oz8 ) int u = q.getFirst(); q.pop(); // Return false if there is a self-loop if (G[u][u] == 1) return false; // Find all non-colored adjacent vertices for (int v = 0; v < V; ++v) { // An edge from u to v exists and // destination v is not colored if (G[u][v] == 1 && colorArr[v] == -1) { // Assign alternate color to this // adjacent v of u colorArr[v] = 1 - colorArr[u]; q.push(v); } // An edge from u to v exists and // destination v is colored with same // color as u else if (G[u][v] == 1 && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all adjacent vertices // can be colored with alternate color return true; } // Returns true if G[][] is Bipartite, else false public static boolean isBipartite(int G[][]) { // Create a color array to store colors assigned // to all vertices. Vertex/ number is used as // index in this array. The value '-1' of // colorArr[i] is used to indicate that no color // is assigned to vertex 'i'. The value 1 is used // to indicate first color is assigned and value // 0 indicates second color is assigned. int colorArr[] = new int[V]; for (int i = 0; i < V; ++i) colorArr[i] = -1; // This code is to handle disconnected graph for (int i = 0; i < V; i++) if (colorArr[i] == -1) if (isBipartiteUtil(G, i, colorArr) == false) return false; return true; } /* Driver code*/ public static void main(String[] args) { int G[][] = { { 0, 1, 0, 1 }, { 1, 0, 1, 0 }, { 0, 1, 0, 1 }, { 1, 0, 1, 0 } }; if (isBipartite(G)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 53684,
"s": 50750,
"text": null
},
{
"code": "# Python3 program to find out whether a# given graph is Bipartite or not class Graph(): def __init__(self, V): self.V = V self.graph = [[0 for column in range(V)] for row in range(V)] self.colorArr = [-1 for i in range(self.V)] # This function returns true if graph G[V][V] # is Bipartite, else false def isBipartiteUtil(self, src): # Create a color array to store colors # assigned to all vertices. Vertex # number is used as index in this array. # The value '-1' of self.colorArr[i] is used # to indicate that no color is assigned to # vertex 'i'. The value 1 is used to indicate # first color is assigned and value 0 # indicates second color is assigned. # Assign first color to source # Create a queue (FIFO) of vertex numbers and # enqueue source vertex for BFS traversal queue = [] queue.append(src) # Run while there are vertices in queue # (Similar to BFS) while queue: u = queue.pop() # Return false if there is a self-loop if self.graph[u][u] == 1: return False for v in range(self.V): # An edge from u to v exists and # destination v is not colored if (self.graph[u][v] == 1 and self.colorArr[v] == -1): # Assign alternate color to # this adjacent v of u self.colorArr[v] = 1 - self.colorArr[u] queue.append(v) # An edge from u to v exists and destination # v is colored with same color as u elif (self.graph[u][v] == 1 and self.colorArr[v] == self.colorArr[u]): return False # If we reach here, then all adjacent # vertices can be colored with alternate # color return True def isBipartite(self): self.colorArr = [-1 for i in range(self.V)] for i in range(self.V): if self.colorArr[i] == -1: if not self.isBipartiteUtil(i): return False return True # Driver Codeg = Graph(4)g.graph = [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]] print (\"Yes\" if g.isBipartite() else \"No\") # This code is contributed by Anshuman Sharma",
"e": 56124,
"s": 53684,
"text": null
},
{
"code": "// C# Code to check whether a given// graph is Bipartite or notusing System;using System.Collections.Generic; class GFG { public static int V = 4; // This function returns true if graph // G[V,V] is Bipartite, else false public static bool isBipartiteUtil(int[, ] G, int src, int[] colorArr) { colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers and // enqueue source vertex for BFS traversal Queue<int> q = new Queue<int>(); q.Enqueue(src); // Run while there are vertices in queue // (Similar to BFS) while (q.Count != 0) { // Dequeue a vertex from queue // ( Refer http://goo.gl/35oz8 ) int u = q.Peek(); q.Dequeue(); // Return false if there is a self-loop if (G[u, u] == 1) return false; // Find all non-colored adjacent vertices for (int v = 0; v < V; ++v) { // An edge from u to v exists and // destination v is not colored if (G[u, v] == 1 && colorArr[v] == -1) { // Assign alternate color to this // adjacent v of u colorArr[v] = 1 - colorArr[u]; q.Enqueue(v); } // An edge from u to v exists and // destination v is colored with same // color as u else if (G[u, v] == 1 && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all // adjacent vertices can be colored // with alternate color return true; } // Returns true if G[,] is Bipartite, // else false public static bool isBipartite(int[, ] G) { // Create a color array to store // colors assigned to all vertices. // Vertex/ number is used as // index in this array. The value '-1' // of colorArr[i] is used to indicate // that no color is assigned to vertex 'i'. // The value 1 is used to indicate // first color is assigned and value // 0 indicates second color is assigned. int[] colorArr = new int[V]; for (int i = 0; i < V; ++i) colorArr[i] = -1; // This code is to handle disconnected graph for (int i = 0; i < V; i++) if (colorArr[i] == -1) if (isBipartiteUtil(G, i, colorArr) == false) return false; return true; } // Driver Code public static void Main(String[] args) { int[, ] G = { { 0, 1, 0, 1 }, { 1, 0, 1, 0 }, { 0, 1, 0, 1 }, { 1, 0, 1, 0 } }; if (isBipartite(G)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Rajput-Ji",
"e": 59118,
"s": 56124,
"text": null
},
{
"code": "<script>// Javascript Code to check whether a given// graph is Bipartite or notvar V = 4; // This function returns true if graph// G[V,V] is Bipartite, else falsefunction isBipartiteUtil(G, src, colorArr){ colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers and // enqueue source vertex for BFS traversal var q = []; q.push(src); // Run while there are vertices in queue // (Similar to BFS) while (q.length != 0) { // Dequeue a vertex from queue // ( Refer http://goo.gl/35oz8 ) var u = q[0]; q.shift(); // Return false if there is a self-loop if (G[u, u] == 1) return false; // Find all non-colored adjacent vertices for (var v = 0; v < V; ++v) { // An edge from u to v exists and // destination v is not colored if (G[u][v] == 1 && colorArr[v] == -1) { // Assign alternate color to this // adjacent v of u colorArr[v] = 1 - colorArr[u]; q.push(v); } // An edge from u to v exists and // destination v is colored with same // color as u else if (G[u, v] == 1 && colorArr[v] == colorArr[u]) return false; } } // If we reach here, then all // adjacent vertices can be colored // with alternate color return true;} // Returns true if G[,] is Bipartite,// else falsefunction isBipartite(G){ // Create a color array to store // colors assigned to all vertices. // Vertex/ number is used as // index in this array. The value '-1' // of colorArr[i] is used to indicate // that no color is assigned to vertex 'i'. // The value 1 is used to indicate // first color is assigned and value // 0 indicates second color is assigned. var colorArr = Array(V); for (var i = 0; i < V; ++i) colorArr[i] = -1; // This code is to handle disconnected graph for (var i = 0; i < V; i++) if (colorArr[i] == -1) if (isBipartiteUtil(G, i, colorArr) == false) return false; return true;} // Driver Codevar G = [ [ 0, 1, 0, 1 ], [ 1, 0, 1, 0 ], [ 0, 1, 0, 1 ], [ 1, 0, 1, 0 ] ];if (isBipartite(G)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by rrrtnx.</script>",
"e": 61631,
"s": 59118,
"text": null
},
{
"code": null,
"e": 61640,
"s": 61631,
"text": "Output: "
},
{
"code": null,
"e": 61644,
"s": 61640,
"text": "Yes"
},
{
"code": null,
"e": 61867,
"s": 61644,
"text": "Time Complexity of the above approach is same as that Breadth First Search. In above implementation is O(V^2) where V is number of vertices. If graph is represented using adjacency list, then the complexity becomes O(V+E)."
},
{
"code": null,
"e": 61945,
"s": 61867,
"text": "If Graph is represented using Adjacency List .Time Complexity will be O(V+E)."
},
{
"code": null,
"e": 61996,
"s": 61945,
"text": "Works for connected as well as disconnected graph."
},
{
"code": null,
"e": 62000,
"s": 61996,
"text": "C++"
},
{
"code": null,
"e": 62005,
"s": 62000,
"text": "Java"
},
{
"code": null,
"e": 62013,
"s": 62005,
"text": "Python3"
},
{
"code": null,
"e": 62016,
"s": 62013,
"text": "C#"
},
{
"code": null,
"e": 62027,
"s": 62016,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; bool isBipartite(int V, vector<int> adj[]){ // vector to store colour of vertex // assigning all to -1 i.e. uncoloured // colours are either 0 or 1 // for understanding take 0 as red and 1 as blue vector<int> col(V, -1); // queue for BFS storing {vertex , colour} queue<pair<int, int> > q; //loop incase graph is not connected for (int i = 0; i < V; i++) { //if not coloured if (col[i] == -1) { //colouring with 0 i.e. red q.push({ i, 0 }); col[i] = 0; while (!q.empty()) { pair<int, int> p = q.front(); q.pop(); //current vertex int v = p.first; //colour of current vertex int c = p.second; //traversing vertexes connected to current vertex for (int j : adj[v]) { //if already coloured with parent vertex color //then bipartite graph is not possible if (col[j] == c) return 0; //if uncoloured if (col[j] == -1) { //colouring with opposite color to that of parent col[j] = (c) ? 0 : 1; q.push({ j, col[j] }); } } } } } //if all vertexes are coloured such that //no two connected vertex have same colours return 1;} // { Driver Code Starts.int main(){ int V, E; V = 4 , E = 8; //adjacency list for storing graph vector<int> adj[V]; adj[0] = {1,3}; adj[1] = {0,2}; adj[2] = {1,3}; adj[3] = {0,2}; bool ans = isBipartite(V, adj); //returns 1 if bipartite graph is possible if (ans) cout << \"Yes\\n\"; //returns 0 if bipartite graph is not possible else cout << \"No\\n\"; return 0;} // code Contributed By Devendra Kolhe",
"e": 64137,
"s": 62027,
"text": null
},
{
"code": "import java.util.*; public class GFG{ static class Pair{ int first, second; Pair(int f, int s){ first = f; second = s; } } static boolean isBipartite(int V, ArrayList<ArrayList<Integer>> adj) { // vector to store colour of vertex // assigning all to -1 i.e. uncoloured // colours are either 0 or 1 // for understanding take 0 as red and 1 as blue int col[] = new int[V]; Arrays.fill(col, -1); // queue for BFS storing {vertex , colour} Queue<Pair> q = new LinkedList<Pair>(); //loop incase graph is not connected for (int i = 0; i < V; i++) { // if not coloured if (col[i] == -1) { // colouring with 0 i.e. red q.add(new Pair(i, 0)); col[i] = 0; while (!q.isEmpty()) { Pair p = q.peek(); q.poll(); //current vertex int v = p.first; // colour of current vertex int c = p.second; // traversing vertexes connected to current vertex for (int j : adj.get(v)) { // if already coloured with parent vertex color // then bipartite graph is not possible if (col[j] == c) return false; // if uncoloured if (col[j] == -1) { // colouring with opposite color to that of parent col[j] = (c==1) ? 0 : 1; q.add(new Pair(j, col[j])); } } } } } // if all vertexes are coloured such that // no two connected vertex have same colours return true; } // Driver Code Starts. public static void main(String args[]) { int V, E; V = 4 ; E = 8; // adjacency list for storing graph ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < V; i++){ adj.add(new ArrayList<Integer>()); } adj.get(0).add(1); adj.get(0).add(3); adj.get(1).add(0); adj.get(1).add(2); adj.get(2).add(1); adj.get(2).add(3); adj.get(3).add(0); adj.get(3).add(2); boolean ans = isBipartite(V, adj); // returns 1 if bipartite graph is possible if (ans) System.out.println(\"Yes\"); // returns 0 if bipartite graph is not possible else System.out.println(\"No\"); }} // This code is contributed by adityapande88.",
"e": 67217,
"s": 64137,
"text": null
},
{
"code": "def isBipartite(V, adj): # vector to store colour of vertex # assigning all to -1 i.e. uncoloured # colours are either 0 or 1 # for understanding take 0 as red and 1 as blue col = [-1]*(V) # queue for BFS storing {vertex , colour} q = [] #loop incase graph is not connected for i in range(V): # if not coloured if (col[i] == -1): # colouring with 0 i.e. red q.append([i, 0]) col[i] = 0 while len(q) != 0: p = q[0] q.pop(0) # current vertex v = p[0] # colour of current vertex c = p[1] # traversing vertexes connected to current vertex for j in adj[v]: # if already coloured with parent vertex color # then bipartite graph is not possible if (col[j] == c): return False # if uncoloured if (col[j] == -1): # colouring with opposite color to that of parent if c == 1: col[j] = 0 else: col[j] = 1 q.append([j, col[j]]) # if all vertexes are coloured such that # no two connected vertex have same colours return True V, E = 4, 8 # adjacency list for storing graphadj = []adj.append([1,3])adj.append([0,2])adj.append([1,3])adj.append([0,2]) ans = isBipartite(V, adj) # returns 1 if bipartite graph is possibleif (ans): print(\"Yes\") # returns 0 if bipartite graph is not possibleelse: print(\"No\") # This code is contributed by divyesh072019.",
"e": 69101,
"s": 67217,
"text": null
},
{
"code": "using System;using System.Collections.Generic;class GFG { static bool isBipartite(int V, List<List<int>> adj) { // vector to store colour of vertex // assigning all to -1 i.e. uncoloured // colours are either 0 or 1 // for understanding take 0 as red and 1 as blue int[] col = new int[V]; Array.Fill(col, -1); // queue for BFS storing {vertex , colour} List<Tuple<int,int>> q = new List<Tuple<int,int>>(); //loop incase graph is not connected for (int i = 0; i < V; i++) { // if not coloured if (col[i] == -1) { // colouring with 0 i.e. red q.Add(new Tuple<int,int>(i, 0)); col[i] = 0; while (q.Count > 0) { Tuple<int,int> p = q[0]; q.RemoveAt(0); //current vertex int v = p.Item1; // colour of current vertex int c = p.Item2; // traversing vertexes connected to current vertex foreach(int j in adj[v]) { // if already coloured with parent vertex color // then bipartite graph is not possible if (col[j] == c) return false; // if uncoloured if (col[j] == -1) { // colouring with opposite color to that of parent col[j] = (c==1) ? 0 : 1; q.Add(new Tuple<int,int>(j, col[j])); } } } } } // if all vertexes are coloured such that // no two connected vertex have same colours return true; } static void Main() { int V; V = 4 ; // adjacency list for storing graph List<List<int>> adj = new List<List<int>>(); for(int i = 0; i < V; i++){ adj.Add(new List<int>()); } adj[0].Add(1); adj[0].Add(3); adj[1].Add(0); adj[1].Add(2); adj[2].Add(1); adj[2].Add(3); adj[3].Add(0); adj[3].Add(2); bool ans = isBipartite(V, adj); // returns 1 if bipartite graph is possible if (ans) Console.WriteLine(\"Yes\"); // returns 0 if bipartite graph is not possible else Console.WriteLine(\"No\"); }} // This code is contributed by decode2207.",
"e": 71818,
"s": 69101,
"text": null
},
{
"code": "<script>class Pair{ constructor(f,s) { this.first = f; this.second = s; }} function isBipartite(V, adj){ // vector to store colour of vertex // assigning all to -1 i.e. uncoloured // colours are either 0 or 1 // for understanding take 0 as red and 1 as blue let col = new Array(V); for(let i = 0; i < V; i++) col[i] = -1; // queue for BFS storing {vertex , colour} let q = []; //loop incase graph is not connected for (let i = 0; i < V; i++) { // if not coloured if (col[i] == -1) { // colouring with 0 i.e. red q.push(new Pair(i, 0)); col[i] = 0; while (q.length!=0) { let p = q[0]; q.shift(); //current vertex let v = p.first; // colour of current vertex let c = p.second; // traversing vertexes connected to current vertex for (let j of adj[v]) { // if already coloured with parent vertex color // then bipartite graph is not possible if (col[j] == c) return false; // if uncoloured if (col[j] == -1) { // colouring with opposite color to that of parent col[j] = (c==1) ? 0 : 1; q.push(new Pair(j, col[j])); } } } } } // if all vertexes are coloured such that // no two connected vertex have same colours return true;} // Driver Code Starts.let V, E; V = 4 ; E = 8; // adjacency list for storing graph let adj = []; for(let i = 0; i < V; i++){ adj.push([]); } adj[0].push(1); adj[0].push(3); adj[1].push(0); adj[1].push(2); adj[2].push(1); adj[2].push(3); adj[3].push(0); adj[3].push(2); let ans = isBipartite(V, adj); // returns 1 if bipartite graph is possible if (ans) document.write(\"Yes\"); // returns 0 if bipartite graph is not possible else document.write(\"No\"); // This code is contributed by patel2127</script>",
"e": 74569,
"s": 71818,
"text": null
},
{
"code": null,
"e": 74573,
"s": 74569,
"text": "Yes"
},
{
"code": null,
"e": 74676,
"s": 74573,
"text": "Exercise: 1. Can DFS algorithm be used to check the bipartite-ness of a graph? If yes, how? Solution :"
},
{
"code": null,
"e": 74680,
"s": 74676,
"text": "C++"
},
{
"code": null,
"e": 74685,
"s": 74680,
"text": "Java"
},
{
"code": null,
"e": 74693,
"s": 74685,
"text": "Python3"
},
{
"code": null,
"e": 74696,
"s": 74693,
"text": "C#"
},
{
"code": null,
"e": 74707,
"s": 74696,
"text": "Javascript"
},
{
"code": "// C++ program to find out whether a given graph is Bipartite or not.// Using recursion.#include <iostream> using namespace std;#define V 4 bool colorGraph(int G[][V],int color[],int pos, int c){ if(color[pos] != -1 && color[pos] !=c) return false; // color this pos as c and all its neighbours and 1-c color[pos] = c; bool ans = true; for(int i=0;i<V;i++){ if(G[pos][i]){ if(color[i] == -1) ans &= colorGraph(G,color,i,1-c); if(color[i] !=-1 && color[i] != 1-c) return false; } if (!ans) return false; } return true;} bool isBipartite(int G[][V]){ int color[V]; for(int i=0;i<V;i++) color[i] = -1; //start is vertex 0; int pos = 0; // two colors 1 and 0 return colorGraph(G,color,pos,1); } int main(){ int G[][V] = {{0, 1, 0, 1}, {1, 0, 1, 0}, {0, 1, 0, 1}, {1, 0, 1, 0} }; isBipartite(G) ? cout<< \"Yes\" : cout << \"No\"; return 0;}// This code is contributed By Mudit Verma",
"e": 75802,
"s": 74707,
"text": null
},
{
"code": "// Java program to find out whether// a given graph is Bipartite or not.// Using recursion.class GFG{ static final int V = 4; static boolean colorGraph(int G[][], int color[], int pos, int c) { if (color[pos] != -1 && color[pos] != c) return false; // color this pos as c and // all its neighbours as 1-c color[pos] = c; boolean ans = true; for (int i = 0; i < V; i++) { if (G[pos][i] == 1) { if (color[i] == -1) ans &= colorGraph(G, color, i, 1 - c); if (color[i] != -1 && color[i] != 1 - c) return false; } if (!ans) return false; } return true; } static boolean isBipartite(int G[][]) { int[] color = new int[V]; for (int i = 0; i < V; i++) color[i] = -1; // start is vertex 0; int pos = 0; // two colors 1 and 0 return colorGraph(G, color, pos, 1); } // Driver Code public static void main(String[] args) { int G[][] = { { 0, 1, 0, 1 }, { 1, 0, 1, 0 }, { 0, 1, 0, 1 }, { 1, 0, 1, 0 } }; if (isBipartite(G)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by Rajput-Ji",
"e": 77285,
"s": 75802,
"text": null
},
{
"code": "# Python3 program to find out whether a given# graph is Bipartite or not using recursion.V = 4 def colorGraph(G, color, pos, c): if color[pos] != -1 and color[pos] != c: return False # color this pos as c and all its neighbours and 1-c color[pos] = c ans = True for i in range(0, V): if G[pos][i]: if color[i] == -1: ans &= colorGraph(G, color, i, 1-c) if color[i] !=-1 and color[i] != 1-c: return False if not ans: return False return True def isBipartite(G): color = [-1] * V #start is vertex 0 pos = 0 # two colors 1 and 0 return colorGraph(G, color, pos, 1) if __name__ == \"__main__\": G = [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]] if isBipartite(G): print(\"Yes\") else: print(\"No\") # This code is contributed by Rituraj Jain",
"e": 78248,
"s": 77285,
"text": null
},
{
"code": "// C# program to find out whether// a given graph is Bipartite or not.// Using recursion.using System; class GFG{ static readonly int V = 4; static bool colorGraph(int [,]G, int []color, int pos, int c) { if (color[pos] != -1 && color[pos] != c) return false; // color this pos as c and // all its neighbours as 1-c color[pos] = c; bool ans = true; for (int i = 0; i < V; i++) { if (G[pos, i] == 1) { if (color[i] == -1) ans &= colorGraph(G, color, i, 1 - c); if (color[i] != -1 && color[i] != 1 - c) return false; } if (!ans) return false; } return true; } static bool isBipartite(int [,]G) { int[] color = new int[V]; for (int i = 0; i < V; i++) color[i] = -1; // start is vertex 0; int pos = 0; // two colors 1 and 0 return colorGraph(G, color, pos, 1); } // Driver Code public static void Main(String[] args) { int [,]G = {{ 0, 1, 0, 1 }, { 1, 0, 1, 0 }, { 0, 1, 0, 1 }, { 1, 0, 1, 0 }}; if (isBipartite(G)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by 29AjayKumar",
"e": 79716,
"s": 78248,
"text": null
},
{
"code": "<script> // JavaScript program to find out whether // a given graph is Bipartite or not. // Using recursion. var V = 4; function colorGraph(G, color, pos, c) { if (color[pos] != -1 && color[pos] != c) return false; // color this pos as c and // all its neighbours as 1-c color[pos] = c; var ans = true; for (var i = 0; i < V; i++) { if (G[pos][i] == 1) { if (color[i] == -1) ans &= colorGraph(G, color, i, 1 - c); if (color[i] != -1 && color[i] != 1 - c) return false; } if (!ans) return false; } return true; } function isBipartite(G) { var color = new Array(V).fill(0); for (var i = 0; i < V; i++) color[i] = -1; // start is vertex 0; var pos = 0; // two colors 1 and 0 return colorGraph(G, color, pos, 1); } // Driver Code var G = [ [0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0], ]; if (isBipartite(G)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by rdtank. </script>",
"e": 80893,
"s": 79716,
"text": null
},
{
"code": null,
"e": 80897,
"s": 80893,
"text": "Yes"
},
{
"code": null,
"e": 81167,
"s": 80897,
"text": "References: http://en.wikipedia.org/wiki/Graph_coloring http://en.wikipedia.org/wiki/Bipartite_graphThis article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 81179,
"s": 81167,
"text": "Mudit Verma"
},
{
"code": null,
"e": 81194,
"s": 81179,
"text": "anshumansharma"
},
{
"code": null,
"e": 81207,
"s": 81194,
"text": "rituraj_jain"
},
{
"code": null,
"e": 81222,
"s": 81207,
"text": "danielagfavero"
},
{
"code": null,
"e": 81232,
"s": 81222,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 81244,
"s": 81232,
"text": "29AjayKumar"
},
{
"code": null,
"e": 81258,
"s": 81244,
"text": "aanchaltiwari"
},
{
"code": null,
"e": 81272,
"s": 81258,
"text": "dhawangupta08"
},
{
"code": null,
"e": 81287,
"s": 81272,
"text": "devendrakolhe5"
},
{
"code": null,
"e": 81301,
"s": 81287,
"text": "adityapande88"
},
{
"code": null,
"e": 81308,
"s": 81301,
"text": "rrrtnx"
},
{
"code": null,
"e": 81315,
"s": 81308,
"text": "rdtank"
},
{
"code": null,
"e": 81336,
"s": 81315,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 81346,
"s": 81336,
"text": "patel2127"
},
{
"code": null,
"e": 81356,
"s": 81346,
"text": "kalrap615"
},
{
"code": null,
"e": 81375,
"s": 81356,
"text": "surindertarika1234"
},
{
"code": null,
"e": 81387,
"s": 81375,
"text": "anikakapoor"
},
{
"code": null,
"e": 81401,
"s": 81387,
"text": "divyesh072019"
},
{
"code": null,
"e": 81412,
"s": 81401,
"text": "decode2207"
},
{
"code": null,
"e": 81422,
"s": 81412,
"text": "rs1686740"
},
{
"code": null,
"e": 81438,
"s": 81422,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 81451,
"s": 81438,
"text": "simmytarika5"
},
{
"code": null,
"e": 81455,
"s": 81451,
"text": "BFS"
},
{
"code": null,
"e": 81459,
"s": 81455,
"text": "DFS"
},
{
"code": null,
"e": 81474,
"s": 81459,
"text": "Graph Coloring"
},
{
"code": null,
"e": 81482,
"s": 81474,
"text": "Samsung"
},
{
"code": null,
"e": 81488,
"s": 81482,
"text": "Graph"
},
{
"code": null,
"e": 81496,
"s": 81488,
"text": "Samsung"
},
{
"code": null,
"e": 81500,
"s": 81496,
"text": "DFS"
},
{
"code": null,
"e": 81506,
"s": 81500,
"text": "Graph"
},
{
"code": null,
"e": 81510,
"s": 81506,
"text": "BFS"
},
{
"code": null,
"e": 81608,
"s": 81510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 81617,
"s": 81608,
"text": "Comments"
},
{
"code": null,
"e": 81630,
"s": 81617,
"text": "Old Comments"
},
{
"code": null,
"e": 81661,
"s": 81630,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 81694,
"s": 81661,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 81762,
"s": 81694,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 81810,
"s": 81762,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 81860,
"s": 81810,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 81890,
"s": 81860,
"text": "Strongly Connected Components"
},
{
"code": null,
"e": 81956,
"s": 81890,
"text": "Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)"
},
{
"code": null,
"e": 81993,
"s": 81956,
"text": "Shortest path in an unweighted graph"
},
{
"code": null,
"e": 82029,
"s": 81993,
"text": "Best First Search (Informed Search)"
}
] |
Neural Network for Satellite Data Classification Using Tensorflow in Python | by Pratyush Tripathy | Towards Data Science
|
Deep Learning has taken over the majority of fields in solving complex problems, and the geospatial field is no exception. The title of the article interests you and hence, I hope that you are familiar with satellite datasets; for now, Landsat 5 TM. Little knowledge of how Machine Learning (ML) algorithms work, will help you grasp this hands-on tutorial quickly. For those who are unfamiliar with ML concept, in a nutshell, it is establishing the relationship between a few characteristics (features or Xs) of an entity with its other property (value or label or Y) — we provide plenty of examples (labelled data) to the model so that it learns from it and then predicts values/ labels for the new data (unlabelled data). That is enough of theory brush-up for machine learning!
The general problem with satellite data:
Two or more feature classes (e.g. built-up/ barren/ quarry) in the satellite data can have similar spectral values, which has made the classification a challenging task in the past couple of decades. The conventional supervised and unsupervised methods fail to be the perfect classifier due to the aforementioned issue, although they robustly perform the classification. But, there are always related issues. Let us understand this with the example below:
In the above figure, if you were to use a vertical line as a classifier and move it only along the x-axis in such a way that it classifies all the images to its right as houses, the answer might not be straight forward. This is because the distribution of data is in such a way that it is impossible to separate them with just one vertical line. However, this doesn’t mean that the houses can’t be classified at all!
Let us say you use the red line, as shown in the figure above, to separate the two features. In this instance, the majority of the houses were identified by the classifier but, a house was still left out, and a tree got misclassified as a house. To make sure that not even a single house is left behind, you might use the blue line. In that case, the classifier will cover all the house; this is called a high recall. However, not all the classified images are truly houses, this is called a low precision. Similarly, if we use the green line, all the images classified as houses are houses; therefore, the classifier possesses high precision. The recall will be lesser in this case because three houses were still left out. In the majority of cases, this trade-off between precision and recall holds.
The house and tree problem demonstrated above is analogous to the built-up, quarry and barren land case. The classification priorities for satellite data can vary with the purpose. For example, if you want to make sure that all the built-up cells are classified as built-up, leaving none behind, and you care less about pixels of other classes with similar signatures being classified as built-up, then a model with a high recall is required. On the contrary, if the priority is to classify pure built-up pixels only without including any of the other class pixels, and you are okay to let go of mixed built-up pixels, then a high precision classifier is required. A generic model will use the red line in the case of the house and the tree to maintain the balance between precision and recall.
Data used in the current scope
Here, we will treat six bands (band 2 — band 7) of Landsat 5 TM as features and try to predict the binary built-up class. A multispectral Landsat 5 data acquired in the year 2011 for Bangalore and its corresponding binary built-up layer will be used for training and testing. Finally, another multispectral Landsat 5 data acquired in the year 2011 for Hyderabad will be used for new predictions. To know more about how to create training data for the model, you can check out this video.
Since we are using labelled data to train the model, this is a supervised ML approach.
We will be using Google’s Tensorflow library in Python to build a Neural Network (NN). The following other libraries will be required, please make sure you install them in advance (check out this video for installation instructions):
pyrsgis — to read and write GeoTIFFscikit-learn — for data pre-processing and accuracy checksnumpy — for basic array operationsTensorflow — to build the neural network model
pyrsgis — to read and write GeoTIFF
scikit-learn — for data pre-processing and accuracy checks
numpy — for basic array operations
Tensorflow — to build the neural network model
Without further delay, let us get started with coding.
Place all the three files in a directory — assign the path and input file names in the script, and read the GeoTIFF files.
The raster module of the pyrsgis package reads the GeoTIFF’s geolocation information and the digital number (DN) values as a NumPy array separately. For details on this, please refer to the pyrsgis page.
Let us print the size of the data that we have read.
Output:
Bangalore multispectral image shape: 6, 2054, 2044Bangalore binary built-up image shape: 2054, 2044Hyderabad multispectral image shape: 6, 1318, 1056
As evident from the output, the number of rows and columns in the Bangalore images is the same, and the number of layers in the multispectral images are the same. The model will learn to decide whether a pixel is built-up or not based on the respective DN values across all the bands, and therefore, both the multispectral images should have the same number of features (bands) stacked in the same order.
We will now change the shape of the arrays to a two-dimensional array, which is expected by the majority of ML algorithms, where each row represents a pixel. The convert module of the pyrsgis package will do that for us.
Output:
Bangalore multispectral image shape: 4198376, 6Bangalore binary built-up image shape: 4198376Hyderabad multispectral image shape: 1391808, 6
In the seventh line of the code snippet above, we extract all the pixels with the value one. This is a fail-safe to avoid issues due to NoData pixels that often has extreme high and low values.
Now, we will split the data for training and validation. This is done to make sure that the model has not seen the test data and it performs equally well on new data. Otherwise, the model will overfit and perform well only on training data.
Output:
(2519025, 6)(2519025,)(1679351, 6)(1679351,)
The test_size (0.4) in the code snippet above signifies that the training-testing proportion is 60/40.
Many ML algorithms including NNs expect normalised data. This means that the histogram is stretched and scaled between a certain range (here, 0 to 1). We will normalise our features to suffice this requirement. Normalisation can be achieved by subtracting the minimum value and dividing by range. Since the Landsat data is an 8-bit data, the minimum and maximum values are 0 and 255 (28 = 256 values).
Note that it is always a good practice to calculate the minimum and maximum values from the data for normalisation. To avoid complexity, we will stick to the default rage of the 8-bit data here.
Another additional pre-processing step is to reshape the features from two-dimensions to three-dimensions, such that each row represents an individual pixel.
Output:
(2519025, 1, 6) (1679351, 1, 6) (1391808, 1, 6)
Now that everything is in place, let us build the model using keras. To start with, we will use the sequential model, to add the layers one after the other. There is one input layer with the number of nodes equal to nBands. One hidden layer with 14 nodes and ‘relu’ as the activation function is used. The final layer contains two nodes for the binary built-up class with ‘softmax’ activation function, which is suitable for categorical output. You can find more activation functions here.
As mentioned in line 10, we compile the model with ‘adam’ optimiser. (There are several others that you can check.) The loss type that we will be using, for now, is the categorical-sparse-crossentropy. You can check details here. The metric for model performance evaluation is ‘accuracy’.
Finally, we run the model on xTrain and yTrain with two epochs (or iterations). Fitting the model will take some time depending on your data size and computational power. The following can be seen after the model compilation:
Let us predict the values for the test data that we have kept separately, and perform various accuracy checks.
The softmax function generates separate columns for each class type probability values. We extract only for class one (built-up), as mentioned in the sixth line in the code snippet above. The models for geospatial-related analysis become tricky to evaluate because unlike other general ML problems, it would not be fair to rely on a generalised summed up error; the spatial location is the key to the winning model. Therefore, the confusion matrix, precision and recall can reflect a clearer picture of how well the model performs.
As seen in the confusion matrix above, there are thousands of built-up pixels classified as non-built-up and vice versa, but the proportion to the total data size is less. The precision and recall as obtained on the test data are more than 0.8.
You can always spend some time and perform a few iterations to find the optimum number of hidden layers, the number of nodes in each hidden layer, and the number of epochs to get accuracy. Some commonly used remote sensing indices such as the NDBI or NDWI can also be used as features, as and when required. Once the desired accuracy is reached, use the model to predict for the new data and export the GeoTIFF. A similar model with minor tweaks can be applied for similar applications.
Note that we are exporting the GeoTIFF with the predicted probability values, and not its thresholded binary version. We can always threshold the float type layer in a GIS environment later, as shown in the image below.
The accuracy of the model has been evaluated already with precision and recall — you can also do the traditional checks (e.g. kappa coefficient) on the new predicted raster. Apart from the aforementioned challenges of satellite data classification, other intuitive limitations include the inability of the model to predict on data acquired in different seasons and over different regions, due to variation in the spectral signatures.
The model that we used in the present article is a very basic architecture of the NN, some of the complex models including Convolution Neural Networks (CNN) have been proven by researchers to produce better results. To get started with CNN for satellite data classification, you can check out this post “Is CNN equally shiny on mid-resolution satellite data?”. The major advantage of these methods is the scalability once the model is trained.
Please find the data used and the full script here.
|
[
{
"code": null,
"e": 952,
"s": 172,
"text": "Deep Learning has taken over the majority of fields in solving complex problems, and the geospatial field is no exception. The title of the article interests you and hence, I hope that you are familiar with satellite datasets; for now, Landsat 5 TM. Little knowledge of how Machine Learning (ML) algorithms work, will help you grasp this hands-on tutorial quickly. For those who are unfamiliar with ML concept, in a nutshell, it is establishing the relationship between a few characteristics (features or Xs) of an entity with its other property (value or label or Y) — we provide plenty of examples (labelled data) to the model so that it learns from it and then predicts values/ labels for the new data (unlabelled data). That is enough of theory brush-up for machine learning!"
},
{
"code": null,
"e": 993,
"s": 952,
"text": "The general problem with satellite data:"
},
{
"code": null,
"e": 1449,
"s": 993,
"text": "Two or more feature classes (e.g. built-up/ barren/ quarry) in the satellite data can have similar spectral values, which has made the classification a challenging task in the past couple of decades. The conventional supervised and unsupervised methods fail to be the perfect classifier due to the aforementioned issue, although they robustly perform the classification. But, there are always related issues. Let us understand this with the example below:"
},
{
"code": null,
"e": 1866,
"s": 1449,
"text": "In the above figure, if you were to use a vertical line as a classifier and move it only along the x-axis in such a way that it classifies all the images to its right as houses, the answer might not be straight forward. This is because the distribution of data is in such a way that it is impossible to separate them with just one vertical line. However, this doesn’t mean that the houses can’t be classified at all!"
},
{
"code": null,
"e": 2668,
"s": 1866,
"text": "Let us say you use the red line, as shown in the figure above, to separate the two features. In this instance, the majority of the houses were identified by the classifier but, a house was still left out, and a tree got misclassified as a house. To make sure that not even a single house is left behind, you might use the blue line. In that case, the classifier will cover all the house; this is called a high recall. However, not all the classified images are truly houses, this is called a low precision. Similarly, if we use the green line, all the images classified as houses are houses; therefore, the classifier possesses high precision. The recall will be lesser in this case because three houses were still left out. In the majority of cases, this trade-off between precision and recall holds."
},
{
"code": null,
"e": 3463,
"s": 2668,
"text": "The house and tree problem demonstrated above is analogous to the built-up, quarry and barren land case. The classification priorities for satellite data can vary with the purpose. For example, if you want to make sure that all the built-up cells are classified as built-up, leaving none behind, and you care less about pixels of other classes with similar signatures being classified as built-up, then a model with a high recall is required. On the contrary, if the priority is to classify pure built-up pixels only without including any of the other class pixels, and you are okay to let go of mixed built-up pixels, then a high precision classifier is required. A generic model will use the red line in the case of the house and the tree to maintain the balance between precision and recall."
},
{
"code": null,
"e": 3494,
"s": 3463,
"text": "Data used in the current scope"
},
{
"code": null,
"e": 3982,
"s": 3494,
"text": "Here, we will treat six bands (band 2 — band 7) of Landsat 5 TM as features and try to predict the binary built-up class. A multispectral Landsat 5 data acquired in the year 2011 for Bangalore and its corresponding binary built-up layer will be used for training and testing. Finally, another multispectral Landsat 5 data acquired in the year 2011 for Hyderabad will be used for new predictions. To know more about how to create training data for the model, you can check out this video."
},
{
"code": null,
"e": 4069,
"s": 3982,
"text": "Since we are using labelled data to train the model, this is a supervised ML approach."
},
{
"code": null,
"e": 4303,
"s": 4069,
"text": "We will be using Google’s Tensorflow library in Python to build a Neural Network (NN). The following other libraries will be required, please make sure you install them in advance (check out this video for installation instructions):"
},
{
"code": null,
"e": 4477,
"s": 4303,
"text": "pyrsgis — to read and write GeoTIFFscikit-learn — for data pre-processing and accuracy checksnumpy — for basic array operationsTensorflow — to build the neural network model"
},
{
"code": null,
"e": 4513,
"s": 4477,
"text": "pyrsgis — to read and write GeoTIFF"
},
{
"code": null,
"e": 4572,
"s": 4513,
"text": "scikit-learn — for data pre-processing and accuracy checks"
},
{
"code": null,
"e": 4607,
"s": 4572,
"text": "numpy — for basic array operations"
},
{
"code": null,
"e": 4654,
"s": 4607,
"text": "Tensorflow — to build the neural network model"
},
{
"code": null,
"e": 4709,
"s": 4654,
"text": "Without further delay, let us get started with coding."
},
{
"code": null,
"e": 4832,
"s": 4709,
"text": "Place all the three files in a directory — assign the path and input file names in the script, and read the GeoTIFF files."
},
{
"code": null,
"e": 5036,
"s": 4832,
"text": "The raster module of the pyrsgis package reads the GeoTIFF’s geolocation information and the digital number (DN) values as a NumPy array separately. For details on this, please refer to the pyrsgis page."
},
{
"code": null,
"e": 5089,
"s": 5036,
"text": "Let us print the size of the data that we have read."
},
{
"code": null,
"e": 5097,
"s": 5089,
"text": "Output:"
},
{
"code": null,
"e": 5247,
"s": 5097,
"text": "Bangalore multispectral image shape: 6, 2054, 2044Bangalore binary built-up image shape: 2054, 2044Hyderabad multispectral image shape: 6, 1318, 1056"
},
{
"code": null,
"e": 5652,
"s": 5247,
"text": "As evident from the output, the number of rows and columns in the Bangalore images is the same, and the number of layers in the multispectral images are the same. The model will learn to decide whether a pixel is built-up or not based on the respective DN values across all the bands, and therefore, both the multispectral images should have the same number of features (bands) stacked in the same order."
},
{
"code": null,
"e": 5873,
"s": 5652,
"text": "We will now change the shape of the arrays to a two-dimensional array, which is expected by the majority of ML algorithms, where each row represents a pixel. The convert module of the pyrsgis package will do that for us."
},
{
"code": null,
"e": 5881,
"s": 5873,
"text": "Output:"
},
{
"code": null,
"e": 6022,
"s": 5881,
"text": "Bangalore multispectral image shape: 4198376, 6Bangalore binary built-up image shape: 4198376Hyderabad multispectral image shape: 1391808, 6"
},
{
"code": null,
"e": 6216,
"s": 6022,
"text": "In the seventh line of the code snippet above, we extract all the pixels with the value one. This is a fail-safe to avoid issues due to NoData pixels that often has extreme high and low values."
},
{
"code": null,
"e": 6457,
"s": 6216,
"text": "Now, we will split the data for training and validation. This is done to make sure that the model has not seen the test data and it performs equally well on new data. Otherwise, the model will overfit and perform well only on training data."
},
{
"code": null,
"e": 6465,
"s": 6457,
"text": "Output:"
},
{
"code": null,
"e": 6510,
"s": 6465,
"text": "(2519025, 6)(2519025,)(1679351, 6)(1679351,)"
},
{
"code": null,
"e": 6613,
"s": 6510,
"text": "The test_size (0.4) in the code snippet above signifies that the training-testing proportion is 60/40."
},
{
"code": null,
"e": 7015,
"s": 6613,
"text": "Many ML algorithms including NNs expect normalised data. This means that the histogram is stretched and scaled between a certain range (here, 0 to 1). We will normalise our features to suffice this requirement. Normalisation can be achieved by subtracting the minimum value and dividing by range. Since the Landsat data is an 8-bit data, the minimum and maximum values are 0 and 255 (28 = 256 values)."
},
{
"code": null,
"e": 7210,
"s": 7015,
"text": "Note that it is always a good practice to calculate the minimum and maximum values from the data for normalisation. To avoid complexity, we will stick to the default rage of the 8-bit data here."
},
{
"code": null,
"e": 7368,
"s": 7210,
"text": "Another additional pre-processing step is to reshape the features from two-dimensions to three-dimensions, such that each row represents an individual pixel."
},
{
"code": null,
"e": 7376,
"s": 7368,
"text": "Output:"
},
{
"code": null,
"e": 7424,
"s": 7376,
"text": "(2519025, 1, 6) (1679351, 1, 6) (1391808, 1, 6)"
},
{
"code": null,
"e": 7914,
"s": 7424,
"text": "Now that everything is in place, let us build the model using keras. To start with, we will use the sequential model, to add the layers one after the other. There is one input layer with the number of nodes equal to nBands. One hidden layer with 14 nodes and ‘relu’ as the activation function is used. The final layer contains two nodes for the binary built-up class with ‘softmax’ activation function, which is suitable for categorical output. You can find more activation functions here."
},
{
"code": null,
"e": 8203,
"s": 7914,
"text": "As mentioned in line 10, we compile the model with ‘adam’ optimiser. (There are several others that you can check.) The loss type that we will be using, for now, is the categorical-sparse-crossentropy. You can check details here. The metric for model performance evaluation is ‘accuracy’."
},
{
"code": null,
"e": 8429,
"s": 8203,
"text": "Finally, we run the model on xTrain and yTrain with two epochs (or iterations). Fitting the model will take some time depending on your data size and computational power. The following can be seen after the model compilation:"
},
{
"code": null,
"e": 8540,
"s": 8429,
"text": "Let us predict the values for the test data that we have kept separately, and perform various accuracy checks."
},
{
"code": null,
"e": 9072,
"s": 8540,
"text": "The softmax function generates separate columns for each class type probability values. We extract only for class one (built-up), as mentioned in the sixth line in the code snippet above. The models for geospatial-related analysis become tricky to evaluate because unlike other general ML problems, it would not be fair to rely on a generalised summed up error; the spatial location is the key to the winning model. Therefore, the confusion matrix, precision and recall can reflect a clearer picture of how well the model performs."
},
{
"code": null,
"e": 9317,
"s": 9072,
"text": "As seen in the confusion matrix above, there are thousands of built-up pixels classified as non-built-up and vice versa, but the proportion to the total data size is less. The precision and recall as obtained on the test data are more than 0.8."
},
{
"code": null,
"e": 9804,
"s": 9317,
"text": "You can always spend some time and perform a few iterations to find the optimum number of hidden layers, the number of nodes in each hidden layer, and the number of epochs to get accuracy. Some commonly used remote sensing indices such as the NDBI or NDWI can also be used as features, as and when required. Once the desired accuracy is reached, use the model to predict for the new data and export the GeoTIFF. A similar model with minor tweaks can be applied for similar applications."
},
{
"code": null,
"e": 10024,
"s": 9804,
"text": "Note that we are exporting the GeoTIFF with the predicted probability values, and not its thresholded binary version. We can always threshold the float type layer in a GIS environment later, as shown in the image below."
},
{
"code": null,
"e": 10458,
"s": 10024,
"text": "The accuracy of the model has been evaluated already with precision and recall — you can also do the traditional checks (e.g. kappa coefficient) on the new predicted raster. Apart from the aforementioned challenges of satellite data classification, other intuitive limitations include the inability of the model to predict on data acquired in different seasons and over different regions, due to variation in the spectral signatures."
},
{
"code": null,
"e": 10902,
"s": 10458,
"text": "The model that we used in the present article is a very basic architecture of the NN, some of the complex models including Convolution Neural Networks (CNN) have been proven by researchers to produce better results. To get started with CNN for satellite data classification, you can check out this post “Is CNN equally shiny on mid-resolution satellite data?”. The major advantage of these methods is the scalability once the model is trained."
}
] |
ArrayDeque remove() Method in Java - GeeksforGeeks
|
10 Dec, 2018
The Java.util.ArrayDeque.remove() method is used to remove the element present at the head of the Deque.Syntax:Array_Deque.remove()Parameters: The method does not take any parameters.Return Value: This method returns the element present at the head of the Deque.Exceptions: The method throws NoSuchElementException is thrown if the deque is empty.Below programs illustrate the Java.util.ArrayDeque.remove() method:Program 1:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("For"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using remove() method de_que.remove(); de_que.remove(); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}Output:Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]
ArrayDeque after removing elements: [Geeks, For, Geeks]
Program 2:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using remove() method de_que.remove(); de_que.remove(); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}Output:Initial ArrayDeque: [10, 15, 30, 20, 5]
ArrayDeque after removing elements: [30, 20, 5]
The Java.util.ArrayDeque.remove(Object) method is used to remove a particular element from an ArrayDeque.Syntax:Priority_Queue.remove(Object O)Parameters: The parameter O is of the type of ArrayDeque and specifies the element to be removed from the ArrayDeque.Return Value: This method returns True if the specified element is present in the Deque else it returns False.Below programs illustrate the Java.util.ArrayDeque.remove() method:Program 1:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("For"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using remove() method de_que.remove("Geeks"); de_que.remove("For"); de_que.remove("Welcome"); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}Output:Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]
ArrayDeque after removing elements: [To, Geeks]
Program 2:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using remove() method de_que.remove(30); de_que.remove(5); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}Output:Initial ArrayDeque: [10, 15, 30, 20, 5]
ArrayDeque after removing elements: [10, 15, 20]
The Java.util.ArrayDeque.remove() method is used to remove the element present at the head of the Deque.Syntax:Array_Deque.remove()Parameters: The method does not take any parameters.Return Value: This method returns the element present at the head of the Deque.Exceptions: The method throws NoSuchElementException is thrown if the deque is empty.Below programs illustrate the Java.util.ArrayDeque.remove() method:Program 1:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("For"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using remove() method de_que.remove(); de_que.remove(); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}Output:Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]
ArrayDeque after removing elements: [Geeks, For, Geeks]
Program 2:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using remove() method de_que.remove(); de_que.remove(); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}Output:Initial ArrayDeque: [10, 15, 30, 20, 5]
ArrayDeque after removing elements: [30, 20, 5]
Syntax:
Array_Deque.remove()
Parameters: The method does not take any parameters.
Return Value: This method returns the element present at the head of the Deque.
Exceptions: The method throws NoSuchElementException is thrown if the deque is empty.
Below programs illustrate the Java.util.ArrayDeque.remove() method:
Program 1:
// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("For"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using remove() method de_que.remove(); de_que.remove(); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}
Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]
ArrayDeque after removing elements: [Geeks, For, Geeks]
Program 2:
// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using remove() method de_que.remove(); de_que.remove(); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}
Initial ArrayDeque: [10, 15, 30, 20, 5]
ArrayDeque after removing elements: [30, 20, 5]
The Java.util.ArrayDeque.remove(Object) method is used to remove a particular element from an ArrayDeque.Syntax:Priority_Queue.remove(Object O)Parameters: The parameter O is of the type of ArrayDeque and specifies the element to be removed from the ArrayDeque.Return Value: This method returns True if the specified element is present in the Deque else it returns False.Below programs illustrate the Java.util.ArrayDeque.remove() method:Program 1:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("For"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using remove() method de_que.remove("Geeks"); de_que.remove("For"); de_que.remove("Welcome"); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}Output:Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]
ArrayDeque after removing elements: [To, Geeks]
Program 2:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using remove() method de_que.remove(30); de_que.remove(5); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}Output:Initial ArrayDeque: [10, 15, 30, 20, 5]
ArrayDeque after removing elements: [10, 15, 20]
Syntax:
Priority_Queue.remove(Object O)
Parameters: The parameter O is of the type of ArrayDeque and specifies the element to be removed from the ArrayDeque.
Return Value: This method returns True if the specified element is present in the Deque else it returns False.
Below programs illustrate the Java.util.ArrayDeque.remove() method:
Program 1:
// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("For"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using remove() method de_que.remove("Geeks"); de_que.remove("For"); de_que.remove("Welcome"); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}
Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]
ArrayDeque after removing elements: [To, Geeks]
Program 2:
// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Removing elements using remove() method de_que.remove(30); de_que.remove(5); // Displaying the ArrayDeque after removal System.out.println("ArrayDeque after removing " + "elements: " + de_que); }}
Initial ArrayDeque: [10, 15, 30, 20, 5]
ArrayDeque after removing elements: [10, 15, 20]
Java - util package
Java-ArrayDeque
Java-Collections
Java-Functions
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
HashMap in Java with Examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
|
[
{
"code": null,
"e": 23649,
"s": 23621,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 28110,
"s": 23649,
"text": "The Java.util.ArrayDeque.remove() method is used to remove the element present at the head of the Deque.Syntax:Array_Deque.remove()Parameters: The method does not take any parameters.Return Value: This method returns the element present at the head of the Deque.Exceptions: The method throws NoSuchElementException is thrown if the deque is empty.Below programs illustrate the Java.util.ArrayDeque.remove() method:Program 1:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"For\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using remove() method de_que.remove(); de_que.remove(); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}Output:Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]\nArrayDeque after removing elements: [Geeks, For, Geeks]\nProgram 2:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using remove() method de_que.remove(); de_que.remove(); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}Output:Initial ArrayDeque: [10, 15, 30, 20, 5]\nArrayDeque after removing elements: [30, 20, 5]\nThe Java.util.ArrayDeque.remove(Object) method is used to remove a particular element from an ArrayDeque.Syntax:Priority_Queue.remove(Object O)Parameters: The parameter O is of the type of ArrayDeque and specifies the element to be removed from the ArrayDeque.Return Value: This method returns True if the specified element is present in the Deque else it returns False.Below programs illustrate the Java.util.ArrayDeque.remove() method:Program 1:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"For\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using remove() method de_que.remove(\"Geeks\"); de_que.remove(\"For\"); de_que.remove(\"Welcome\"); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}Output:Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]\nArrayDeque after removing elements: [To, Geeks]\nProgram 2:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using remove() method de_que.remove(30); de_que.remove(5); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}Output:Initial ArrayDeque: [10, 15, 30, 20, 5]\nArrayDeque after removing elements: [10, 15, 20]\n"
},
{
"code": null,
"e": 30309,
"s": 28110,
"text": "The Java.util.ArrayDeque.remove() method is used to remove the element present at the head of the Deque.Syntax:Array_Deque.remove()Parameters: The method does not take any parameters.Return Value: This method returns the element present at the head of the Deque.Exceptions: The method throws NoSuchElementException is thrown if the deque is empty.Below programs illustrate the Java.util.ArrayDeque.remove() method:Program 1:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"For\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using remove() method de_que.remove(); de_que.remove(); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}Output:Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]\nArrayDeque after removing elements: [Geeks, For, Geeks]\nProgram 2:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using remove() method de_que.remove(); de_que.remove(); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}Output:Initial ArrayDeque: [10, 15, 30, 20, 5]\nArrayDeque after removing elements: [30, 20, 5]\n"
},
{
"code": null,
"e": 30317,
"s": 30309,
"text": "Syntax:"
},
{
"code": null,
"e": 30338,
"s": 30317,
"text": "Array_Deque.remove()"
},
{
"code": null,
"e": 30391,
"s": 30338,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 30471,
"s": 30391,
"text": "Return Value: This method returns the element present at the head of the Deque."
},
{
"code": null,
"e": 30557,
"s": 30471,
"text": "Exceptions: The method throws NoSuchElementException is thrown if the deque is empty."
},
{
"code": null,
"e": 30625,
"s": 30557,
"text": "Below programs illustrate the Java.util.ArrayDeque.remove() method:"
},
{
"code": null,
"e": 30636,
"s": 30625,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"For\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using remove() method de_que.remove(); de_que.remove(); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}",
"e": 31424,
"s": 30636,
"text": null
},
{
"code": null,
"e": 31534,
"s": 31424,
"text": "Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]\nArrayDeque after removing elements: [Geeks, For, Geeks]\n"
},
{
"code": null,
"e": 31545,
"s": 31534,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using remove() method de_que.remove(); de_que.remove(); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}",
"e": 32312,
"s": 31545,
"text": null
},
{
"code": null,
"e": 32401,
"s": 32312,
"text": "Initial ArrayDeque: [10, 15, 30, 20, 5]\nArrayDeque after removing elements: [30, 20, 5]\n"
},
{
"code": null,
"e": 34664,
"s": 32401,
"text": "The Java.util.ArrayDeque.remove(Object) method is used to remove a particular element from an ArrayDeque.Syntax:Priority_Queue.remove(Object O)Parameters: The parameter O is of the type of ArrayDeque and specifies the element to be removed from the ArrayDeque.Return Value: This method returns True if the specified element is present in the Deque else it returns False.Below programs illustrate the Java.util.ArrayDeque.remove() method:Program 1:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"For\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using remove() method de_que.remove(\"Geeks\"); de_que.remove(\"For\"); de_que.remove(\"Welcome\"); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}Output:Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]\nArrayDeque after removing elements: [To, Geeks]\nProgram 2:// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using remove() method de_que.remove(30); de_que.remove(5); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}Output:Initial ArrayDeque: [10, 15, 30, 20, 5]\nArrayDeque after removing elements: [10, 15, 20]\n"
},
{
"code": null,
"e": 34672,
"s": 34664,
"text": "Syntax:"
},
{
"code": null,
"e": 34704,
"s": 34672,
"text": "Priority_Queue.remove(Object O)"
},
{
"code": null,
"e": 34822,
"s": 34704,
"text": "Parameters: The parameter O is of the type of ArrayDeque and specifies the element to be removed from the ArrayDeque."
},
{
"code": null,
"e": 34933,
"s": 34822,
"text": "Return Value: This method returns True if the specified element is present in the Deque else it returns False."
},
{
"code": null,
"e": 35001,
"s": 34933,
"text": "Below programs illustrate the Java.util.ArrayDeque.remove() method:"
},
{
"code": null,
"e": 35012,
"s": 35001,
"text": "Program 1:"
},
{
"code": "// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"For\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using remove() method de_que.remove(\"Geeks\"); de_que.remove(\"For\"); de_que.remove(\"Welcome\"); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}",
"e": 35845,
"s": 35012,
"text": null
},
{
"code": null,
"e": 35947,
"s": 35845,
"text": "Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]\nArrayDeque after removing elements: [To, Geeks]\n"
},
{
"code": null,
"e": 35958,
"s": 35947,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate remove()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Removing elements using remove() method de_que.remove(30); de_que.remove(5); // Displaying the ArrayDeque after removal System.out.println(\"ArrayDeque after removing \" + \"elements: \" + de_que); }}",
"e": 36728,
"s": 35958,
"text": null
},
{
"code": null,
"e": 36818,
"s": 36728,
"text": "Initial ArrayDeque: [10, 15, 30, 20, 5]\nArrayDeque after removing elements: [10, 15, 20]\n"
},
{
"code": null,
"e": 36838,
"s": 36818,
"text": "Java - util package"
},
{
"code": null,
"e": 36854,
"s": 36838,
"text": "Java-ArrayDeque"
},
{
"code": null,
"e": 36871,
"s": 36854,
"text": "Java-Collections"
},
{
"code": null,
"e": 36886,
"s": 36871,
"text": "Java-Functions"
},
{
"code": null,
"e": 36891,
"s": 36886,
"text": "Java"
},
{
"code": null,
"e": 36896,
"s": 36891,
"text": "Java"
},
{
"code": null,
"e": 36913,
"s": 36896,
"text": "Java-Collections"
},
{
"code": null,
"e": 37011,
"s": 36913,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37020,
"s": 37011,
"text": "Comments"
},
{
"code": null,
"e": 37033,
"s": 37020,
"text": "Old Comments"
},
{
"code": null,
"e": 37048,
"s": 37033,
"text": "Arrays in Java"
},
{
"code": null,
"e": 37092,
"s": 37048,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 37114,
"s": 37092,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 37150,
"s": 37114,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 37175,
"s": 37150,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 37205,
"s": 37175,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 37237,
"s": 37205,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 37288,
"s": 37237,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 37307,
"s": 37288,
"text": "Interfaces in Java"
}
] |
Compute n! under modulo p - GeeksforGeeks
|
26 Apr, 2022
Given a large number n and a prime p, how to efficiently compute n! % p?Examples :
Input: n = 5, p = 13
Output: 3
5! = 120 and 120 % 13 = 3
Input: n = 6, p = 11
Output: 5
6! = 720 and 720 % 11 = 5
A Naive Solution is to first compute n!, then compute n! % p. This solution works fine when the value of n! is small. The value of n! % p is generally needed for large values of n when n! cannot fit in a variable, and causes overflow. So computing n! and then using modular operator is not a good idea as there will be overflow even for slightly larger values of n and r. Following are different methods.Method 1 (Simple) A Simple Solution is to one by one multiply result with i under modulo p. So the value of result doesn’t go beyond p before next iteration.
C++
Java
Python3
C#
PHP
Javascript
// Simple method to compute n! % p#include <bits/stdc++.h>using namespace std; // Returns value of n! % pint modFact(int n, int p){ if (n >= p) return 0; int result = 1; for (int i = 1; i <= n; i++) result = (result * i) % p; return result;} // Driver programint main(){ int n = 25, p = 29; cout << modFact(n, p); return 0;}
// Simple method to compute n! % pimport java.io.*; class GFG{ // Returns value of n! % p static int modFact(int n, int p) { if (n >= p) return 0; int result = 1; for (int i = 1; i <= n; i++) result = (result * i) % p; return result; } // Driver Code public static void main (String[] args) { int n = 25, p = 29; System.out.print(modFact(n, p)); }} // This code is contributed// by aj_36
# Simple method to compute n ! % p # Returns value of n ! % pdef modFact(n, p): if n >= p: return 0 result = 1 for i in range(1, n + 1): result = (result * i) % p return result # Driver Coden = 25; p = 29print (modFact(n, p)) # This code is contributed by Shreyanshi Arun.
// Simple method to compute n! % pusing System; class GFG { // Returns value of n! % p static int modFact(int n, int p) { if (n >= p) return 0; int result = 1; for (int i = 1; i <= n; i++) result = (result * i) % p; return result; } // Driver program static void Main() { int n = 25, p = 29; Console.Write(modFact(n, p)); }} // This code is contributed by Anuj_67
<?php// PHP Simple method to compute n! % p // Returns value of n! % pfunction modFact($n, $p){ if ($n >= $p) return 0; $result = 1; for ($i = 1; $i <= $n; $i++) $result = ($result * $i) % $p; return $result;} // Driver Code$n = 25; $p = 29;echo modFact($n, $p); // This code is contributed by Ajit.?>
<script> // Simple method to compute n! % p // Returns value of n! % p function modFact(n,p) { if (n >= p) return 0; let result = 1; for (let i = 1; i <= n; i++) result = (result * i) % p; return result; } // Driver Code let n = 25, p = 29; document.write(modFact(n, p)); // This code is contributed by Rajput-Ji </script>
Output :
5
Time Complexity of this solution is O(n).Method 2 (Using Sieve) The idea is based on below formula discussed here.
The largest possible power of a prime pi that divides n is,
⌊n/pi⌋ + ⌊n/(pi2)⌋ + ⌊n/(pi3)⌋ + .....+ 0
Every integer can be written as multiplication of powers of primes. So,
n! = p1k1 * p2k2 * p3k3 * ....
Where p1, p2, p3, .. are primes and
k1, k2, k3, .. are integers greater than or equal to 1.
The idea is to find all primes smaller than n using Sieve of Eratosthenes. For every prime ‘pi‘, find the largest power of it that divides n!. Let the largest power be ki. Compute piki % p using modular exponentiation. Multiply this with final result under modulo p.Below is implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to Returns n % p// using Sieve of Eratosthenes#include <bits/stdc++.h>using namespace std; // Returns largest power of p that divides n!int largestPower(int n, int p){ // Initialize result int x = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n) { n /= p; x += n; } return x;} // Utility function to do modular exponentiation.// It returns (x^y) % pint power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Returns n! % pint modFact(int n, int p){ if (n >= p) return 0; int res = 1; // Use Sieve of Eratosthenes to find all primes // smaller than n bool isPrime[n + 1]; memset(isPrime, 1, sizeof(isPrime)); for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = 2 * i; j <= n; j += i) isPrime[j] = 0; } } // Consider all primes found by Sieve for (int i = 2; i <= n; i++) { if (isPrime[i]) { // Find the largest power of prime 'i' that divides n int k = largestPower(n, i); // Multiply result with (i^k) % p res = (res * power(i, k, p)) % p; } } return res;} // Driver methodint main(){ int n = 25, p = 29; cout << modFact(n, p); return 0;}
import java.util.Arrays; // Java program Returns n % p using Sieve of Eratosthenespublic class GFG { // Returns largest power of p that divides n! static int largestPower(int n, int p) { // Initialize result int x = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n > 0) { n /= p; x += n; } return x; } // Utility function to do modular exponentiation.// It returns (x^y) % p static int power(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res * x) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n! % p static int modFact(int n, int p) { if (n >= p) { return 0; } int res = 1; // Use Sieve of Eratosthenes to find all primes // smaller than n boolean isPrime[] = new boolean[n + 1]; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = 2 * i; j <= n; j += i) { isPrime[j] = false; } } } // Consider all primes found by Sieve for (int i = 2; i <= n; i++) { if (isPrime[i]) { // Find the largest power of prime 'i' that divides n int k = largestPower(n, i); // Multiply result with (i^k) % p res = (res * power(i, k, p)) % p; } } return res; } // Driver method static public void main(String[] args) { int n = 25, p = 29; System.out.println(modFact(n, p)); }}// This code is contributed by Rajput-Ji
# Python3 program to Returns n % p# using Sieve of Eratosthenes # Returns largest power of p that divides n!def largestPower(n, p): # Initialize result x = 0 # Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n): n //= p x += n return x # Utility function to do modular exponentiation.# It returns (x^y) % pdef power( x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more than # or equal to p while (y > 0) : # If y is odd, multiply x with result if (y & 1) : res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # Returns n! % pdef modFact( n, p) : if (n >= p) : return 0 res = 1 # Use Sieve of Eratosthenes to find # all primes smaller than n isPrime = [1] * (n + 1) i = 2 while(i * i <= n): if (isPrime[i]): for j in range(2 * i, n, i) : isPrime[j] = 0 i += 1 # Consider all primes found by Sieve for i in range(2, n): if (isPrime[i]) : # Find the largest power of prime 'i' # that divides n k = largestPower(n, i) # Multiply result with (i^k) % p res = (res * power(i, k, p)) % p return res # Driver codeif __name__ =="__main__": n = 25 p = 29 print(modFact(n, p)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# program Returns n % p using Sieve of Eratosthenesusing System; public class GFG { // Returns largest power of p that divides n! static int largestPower(int n, int p) { // Initialize result int x = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n > 0) { n /= p; x += n; } return x; } // Utility function to do modular exponentiation.// It returns (x^y) % p static int power(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res * x) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n! % p static int modFact(int n, int p) { if (n >= p) { return 0; } int res = 1; // Use Sieve of Eratosthenes to find all primes // smaller than n bool []isPrime = new bool[n + 1]; for(int i = 0;i<n+1;i++) isPrime[i] = true; for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = 2 * i; j <= n; j += i) { isPrime[j] = false; } } } // Consider all primes found by Sieve for (int i = 2; i <= n; i++) { if (isPrime[i]) { // Find the largest power of prime 'i' that divides n int k = largestPower(n, i); // Multiply result with (i^k) % p res = (res * power(i, k, p)) % p; } } return res; } // Driver method static public void Main() { int n = 25, p = 29; Console.WriteLine(modFact(n, p)); }}// This code is contributed by PrinciRaj19992
<?php// PHP program to Returns n % p// using Sieve of Eratosthenes // Returns largest power of p that// divides n!function largestPower($n, $p){ // Initialize result $x = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while ($n) { $n = (int)($n / $p); $x += $n; } return $x;} // Utility function to do modular exponentiation.// It returns (x^y) % pfunction power($x, $y, $p){ $res = 1; // Initialize result $x = $x % $p; // Update x if it is more // than or equal to p while ($y > 0) { // If y is odd, multiply x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // Returns n! % pfunction modFact($n, $p){ if ($n >= $p) return 0; $res = 1; // Use Sieve of Eratosthenes to find // all primes smaller than n $isPrime = array_fill(0, $n + 1, true); for ($i = 2; $i * $i <= $n; $i++) { if ($isPrime[$i]) { for ($j = 2 * $i; $j <= $n; $j += $i) $isPrime[$j] = 0; } } // Consider all primes found by Sieve for ($i = 2; $i <= $n; $i++) { if ($isPrime[$i]) { // Find the largest power of // prime 'i' that divides n $k = largestPower($n, $i); // Multiply result with (i^k) % p $res = ($res * power($i, $k, $p)) % $p; } } return $res;} // Driver Code$n = 25;$p = 29;echo modFact($n, $p); // This code is contributed by mits?>
<script> // Javascript program Returns n % p // using Sieve of Eratosthenes // Returns largest power of p // that divides n! function largestPower(n, p) { // Initialize result let x = 0; // Calculate x = n/p + n/(p^2) + // n/(p^3) + .... while (n > 0) { n = parseInt(n / p, 10); x += n; } return x; } // Utility function to do // modular exponentiation. // It returns (x^y) % p function power(x, y, p) { // Initialize result let res = 1; // Update x if it is more than or x = x % p; // equal to p while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res * x) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n! % p function modFact(n, p) { if (n >= p) { return 0; } let res = 1; // Use Sieve of Eratosthenes // to find all primes // smaller than n let isPrime = new Array(n + 1); for(let i = 0;i<n+1;i++) isPrime[i] = true; for (let i = 2; i * i <= n; i++) { if (isPrime[i]) { for (let j = 2 * i; j <= n; j += i) { isPrime[j] = false; } } } // Consider all primes found by Sieve for (let i = 2; i <= n; i++) { if (isPrime[i]) { // Find the largest power of // prime 'i' that divides n let k = largestPower(n, i); // Multiply result with (i^k) % p res = (res * power(i, k, p)) % p; } } return res; } let n = 25, p = 29; document.write(modFact(n, p)); </script>
Output:
5
This is an interesting method, but time complexity of this is more than Simple Method as time complexity of Sieve itself is O(n log log n). This method can be useful if we have list of prime numbers smaller than or equal to n available to us.Method 3 (Using Wilson’s Theorem) Wilson’s theorem states that a natural number p > 1 is a prime number if and only if
(p - 1) ! ≡ -1 mod p
OR (p - 1) ! ≡ (p-1) mod p
Note that n! % p is 0 if n >= p. This method is mainly useful when p is close to input number n. For example (25! % 29). From Wilson’s theorem, we know that 28! is -1. So we basically need to find [ (-1) * inverse(28, 29) * inverse(27, 29) * inverse(26) ] % 29. The inverse function inverse(x, p) returns inverse of x under modulo p (See this for details).
C++
Java
Python3
C#
PHP
Javascript
// C++ program to compute n! % p using Wilson's Theorem#include <bits/stdc++.h>using namespace std; // Utility function to do modular exponentiation.// It returns (x^y) % pint power(int x, unsigned int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Function to find modular inverse of a under modulo p// using Fermat's method. Assumption: p is primeint modInverse(int a, int p){ return power(a, p - 2, p);} // Returns n! % p using Wilson's Theoremint modFact(int n, int p){ // n! % p is 0 if n >= p if (p <= n) return 0; // Initialize result as (p-1)! which is -1 or (p-1) int res = (p - 1); // Multiply modulo inverse of all numbers from (n+1) // to p for (int i = n + 1; i < p; i++) res = (res * modInverse(i, p)) % p; return res;} // Driver methodint main(){ int n = 25, p = 29; cout << modFact(n, p); return 0;}
// Java program to compute n! % p// using Wilson's Theoremclass GFG{ // Utility function to do// modular exponentiation.// It returns (x^y) % pstatic int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0) { // If y is odd, multiply // x with result if ((y & 1) > 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Function to find modular// inverse of a under modulo p// using Fermat's method.// Assumption: p is primestatic int modInverse(int a, int p){ return power(a, p - 2, p);} // Returns n! % p using// Wilson's Theoremstatic int modFact(int n, int p){ // n! % p is 0 if n >= p if (p <= n) return 0; // Initialize result as (p-1)! // which is -1 or (p-1) int res = (p - 1); // Multiply modulo inverse of // all numbers from (n+1) to p for (int i = n + 1; i < p; i++) res = (res * modInverse(i, p)) % p; return res;} // Driver Codepublic static void main(String[] args){ int n = 25, p = 29; System.out.println(modFact(n, p));}} // This code is contributed by mits
def gcdExtended(a,b): if(b==0): return a,1,0 g,x1,y1=gcdExtended(b,a%b) x1,y1 = y1,x1-(a//b)*y1 return g,x1,y1# Driver codefor _ in range(int(input())): n,m=map(int,input().split()) # if n>m, then there is a m in (1*2*3..n) % m such that # m % m=0 then whole ans is 0 if(n>=m): print(0) else: s=1 # Using Wilson's Theorem, (m-1)! % m = m - 1 # Since we need (1*2*3..n) % m # it can be divided into two parts # ( ((1*2*3...n) % m) * ((n+1)*(n+2)*...*(m-1)) )%m=m-1 # We only need to calculate 2nd part i.e. let s=((n+1)*(n+2)*...*(m-1)) ) % m for i in range(n+1,m): s=(s*i)%m # Then we divide (m-1) by s under modulo m means modulo inverse of s under m # It can be done by taking gcd extended g,a,b=gcdExtended(s,m) a=a%m # ans is (m-1)*(modulo inverse of s under m) print(((m-1)*a)%m) # This code is contributed by Himanshu Kaithal
// C# program to compute n! % p// using Wilson's Theoremusing System; // Utility function to do modular// exponentiation. It returns (x^y) % pclass GFG{public int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0) { // If y is odd, multiply // x with result if((y & 1) > 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Function to find modular inverse// of a under modulo p using Fermat's// method. Assumption: p is primepublic int modInverse(int a, int p){ return power(a, p - 2, p);} // Returns n! % p using// Wilson's Theorempublic int modFact(int n, int p){ // n! % p is 0 if n >= p if (p <= n) return 0; // Initialize result as (p-1)! // which is -1 or (p-1) int res = (p - 1); // Multiply modulo inverse of all // numbers from (n+1) to p for (int i = n + 1; i < p; i++) res = (res * modInverse(i, p)) % p; return res;} // Driver methodpublic static void Main(){ GFG g = new GFG(); int n = 25, p = 29; Console.WriteLine(g.modFact(n, p));}} // This code is contributed by Soumik
<?php// PHP program to compute// n!% p using Wilson's Theorem // Utility function to do// modular exponentiation.// It returns (x^y) % pfunction power($x, $y, $p){ $res = 1; // Initialize result $x = $x % $p; // Update x if it is // more than or equal to p while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // Function to find modular// inverse of a under modulo// p using Fermat's method.// Assumption: p is primefunction modInverse($a, $p){ return power($a, $p - 2, $p);} // Returns n! % p// using Wilson's Theoremfunction modFact( $n, $p){ // n! % p is 0 // if n >= p if ($p <= $n) return 0; // Initialize result as // (p-1)! which is -1 or (p-1) $res = ($p - 1); // Multiply modulo inverse // of all numbers from (n+1) // to p for ($i = $n + 1; $i < $p; $i++) $res = ($res * modInverse($i, $p)) % $p; return $res;} // Driver Code$n = 25; $p = 29;echo modFact($n, $p); // This code is contributed by ajit?>
<script> // Javascript program to compute n! % p // using Wilson's Theorem // Utility function to do modular // exponentiation. It returns (x^y) % p function power(x, y, p) { let res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0) { // If y is odd, multiply // x with result if((y & 1) > 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Function to find modular inverse // of a under modulo p using Fermat's // method. Assumption: p is prime function modInverse(a, p) { return power(a, p - 2, p); } // Returns n! % p using // Wilson's Theorem function modFact(n, p) { // n! % p is 0 if n >= p if (p <= n) return 0; // Initialize result as (p-1)! // which is -1 or (p-1) let res = (p - 1); // Multiply modulo inverse of all // numbers from (n+1) to p for (let i = n + 1; i < p; i++) res = (res * modInverse(i, p)) % p; return res; } let n = 25, p = 29; document.write(modFact(n, p)); // This code is contributed by divyeshrabadiya07.</script>
Output:
5
Time complexity of this method is O((p-n)*Logn)Method 4 (Using Primality Test Algorithm)
1) Initialize: result = 1
2) While n is not prime
result = (result * n) % p
3) result = (result * (n-1)) % p // Using Wilson's Theorem
4) Return result.
Note that time complexity step 2 of above algorithm depends on the primality test algorithm being used and value of the largest prime smaller than n. The AKS algorithm for example takes O(Log 10.5 n) time. This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
vt_m
Mithun Kumar
SoumikMondal
ihritik
Rajput-Ji
princiraj1992
SHUBHAMSINGH10
divyeshrabadiya07
suresh07
himanshu2286200116
rkbhola5
factorial
large-numbers
Modular Arithmetic
number-theory
sieve
Mathematical
number-theory
Mathematical
sieve
Modular Arithmetic
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find sum of elements in a given array
Operators in C / C++
Euclidean algorithms (Basic and Extended)
Algorithm to solve Rubik's Cube
The Knight's tour problem | Backtracking-1
Write a program to calculate pow(x,n)
Find minimum number of coins that make a given value
Print all possible combinations of r elements in a given array of size n
Write a program to reverse digits of a number
Fizz Buzz Implementation
|
[
{
"code": null,
"e": 24568,
"s": 24540,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 24653,
"s": 24568,
"text": "Given a large number n and a prime p, how to efficiently compute n! % p?Examples : "
},
{
"code": null,
"e": 24770,
"s": 24653,
"text": "Input: n = 5, p = 13\nOutput: 3\n5! = 120 and 120 % 13 = 3\n\nInput: n = 6, p = 11\nOutput: 5\n6! = 720 and 720 % 11 = 5"
},
{
"code": null,
"e": 25333,
"s": 24770,
"text": "A Naive Solution is to first compute n!, then compute n! % p. This solution works fine when the value of n! is small. The value of n! % p is generally needed for large values of n when n! cannot fit in a variable, and causes overflow. So computing n! and then using modular operator is not a good idea as there will be overflow even for slightly larger values of n and r. Following are different methods.Method 1 (Simple) A Simple Solution is to one by one multiply result with i under modulo p. So the value of result doesn’t go beyond p before next iteration. "
},
{
"code": null,
"e": 25337,
"s": 25333,
"text": "C++"
},
{
"code": null,
"e": 25342,
"s": 25337,
"text": "Java"
},
{
"code": null,
"e": 25350,
"s": 25342,
"text": "Python3"
},
{
"code": null,
"e": 25353,
"s": 25350,
"text": "C#"
},
{
"code": null,
"e": 25357,
"s": 25353,
"text": "PHP"
},
{
"code": null,
"e": 25368,
"s": 25357,
"text": "Javascript"
},
{
"code": "// Simple method to compute n! % p#include <bits/stdc++.h>using namespace std; // Returns value of n! % pint modFact(int n, int p){ if (n >= p) return 0; int result = 1; for (int i = 1; i <= n; i++) result = (result * i) % p; return result;} // Driver programint main(){ int n = 25, p = 29; cout << modFact(n, p); return 0;}",
"e": 25730,
"s": 25368,
"text": null
},
{
"code": "// Simple method to compute n! % pimport java.io.*; class GFG{ // Returns value of n! % p static int modFact(int n, int p) { if (n >= p) return 0; int result = 1; for (int i = 1; i <= n; i++) result = (result * i) % p; return result; } // Driver Code public static void main (String[] args) { int n = 25, p = 29; System.out.print(modFact(n, p)); }} // This code is contributed// by aj_36",
"e": 26243,
"s": 25730,
"text": null
},
{
"code": "# Simple method to compute n ! % p # Returns value of n ! % pdef modFact(n, p): if n >= p: return 0 result = 1 for i in range(1, n + 1): result = (result * i) % p return result # Driver Coden = 25; p = 29print (modFact(n, p)) # This code is contributed by Shreyanshi Arun.",
"e": 26547,
"s": 26243,
"text": null
},
{
"code": "// Simple method to compute n! % pusing System; class GFG { // Returns value of n! % p static int modFact(int n, int p) { if (n >= p) return 0; int result = 1; for (int i = 1; i <= n; i++) result = (result * i) % p; return result; } // Driver program static void Main() { int n = 25, p = 29; Console.Write(modFact(n, p)); }} // This code is contributed by Anuj_67",
"e": 27021,
"s": 26547,
"text": null
},
{
"code": "<?php// PHP Simple method to compute n! % p // Returns value of n! % pfunction modFact($n, $p){ if ($n >= $p) return 0; $result = 1; for ($i = 1; $i <= $n; $i++) $result = ($result * $i) % $p; return $result;} // Driver Code$n = 25; $p = 29;echo modFact($n, $p); // This code is contributed by Ajit.?>",
"e": 27347,
"s": 27021,
"text": null
},
{
"code": "<script> // Simple method to compute n! % p // Returns value of n! % p function modFact(n,p) { if (n >= p) return 0; let result = 1; for (let i = 1; i <= n; i++) result = (result * i) % p; return result; } // Driver Code let n = 25, p = 29; document.write(modFact(n, p)); // This code is contributed by Rajput-Ji </script>",
"e": 27771,
"s": 27347,
"text": null
},
{
"code": null,
"e": 27781,
"s": 27771,
"text": "Output : "
},
{
"code": null,
"e": 27783,
"s": 27781,
"text": "5"
},
{
"code": null,
"e": 27899,
"s": 27783,
"text": "Time Complexity of this solution is O(n).Method 2 (Using Sieve) The idea is based on below formula discussed here. "
},
{
"code": null,
"e": 28217,
"s": 27899,
"text": "The largest possible power of a prime pi that divides n is,\n ⌊n/pi⌋ + ⌊n/(pi2)⌋ + ⌊n/(pi3)⌋ + .....+ 0 \n\nEvery integer can be written as multiplication of powers of primes. So,\n n! = p1k1 * p2k2 * p3k3 * ....\n Where p1, p2, p3, .. are primes and \n k1, k2, k3, .. are integers greater than or equal to 1."
},
{
"code": null,
"e": 28523,
"s": 28217,
"text": "The idea is to find all primes smaller than n using Sieve of Eratosthenes. For every prime ‘pi‘, find the largest power of it that divides n!. Let the largest power be ki. Compute piki % p using modular exponentiation. Multiply this with final result under modulo p.Below is implementation of above idea. "
},
{
"code": null,
"e": 28527,
"s": 28523,
"text": "C++"
},
{
"code": null,
"e": 28532,
"s": 28527,
"text": "Java"
},
{
"code": null,
"e": 28540,
"s": 28532,
"text": "Python3"
},
{
"code": null,
"e": 28543,
"s": 28540,
"text": "C#"
},
{
"code": null,
"e": 28547,
"s": 28543,
"text": "PHP"
},
{
"code": null,
"e": 28558,
"s": 28547,
"text": "Javascript"
},
{
"code": "// C++ program to Returns n % p// using Sieve of Eratosthenes#include <bits/stdc++.h>using namespace std; // Returns largest power of p that divides n!int largestPower(int n, int p){ // Initialize result int x = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n) { n /= p; x += n; } return x;} // Utility function to do modular exponentiation.// It returns (x^y) % pint power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Returns n! % pint modFact(int n, int p){ if (n >= p) return 0; int res = 1; // Use Sieve of Eratosthenes to find all primes // smaller than n bool isPrime[n + 1]; memset(isPrime, 1, sizeof(isPrime)); for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = 2 * i; j <= n; j += i) isPrime[j] = 0; } } // Consider all primes found by Sieve for (int i = 2; i <= n; i++) { if (isPrime[i]) { // Find the largest power of prime 'i' that divides n int k = largestPower(n, i); // Multiply result with (i^k) % p res = (res * power(i, k, p)) % p; } } return res;} // Driver methodint main(){ int n = 25, p = 29; cout << modFact(n, p); return 0;}",
"e": 30123,
"s": 28558,
"text": null
},
{
"code": "import java.util.Arrays; // Java program Returns n % p using Sieve of Eratosthenespublic class GFG { // Returns largest power of p that divides n! static int largestPower(int n, int p) { // Initialize result int x = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n > 0) { n /= p; x += n; } return x; } // Utility function to do modular exponentiation.// It returns (x^y) % p static int power(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res * x) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n! % p static int modFact(int n, int p) { if (n >= p) { return 0; } int res = 1; // Use Sieve of Eratosthenes to find all primes // smaller than n boolean isPrime[] = new boolean[n + 1]; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = 2 * i; j <= n; j += i) { isPrime[j] = false; } } } // Consider all primes found by Sieve for (int i = 2; i <= n; i++) { if (isPrime[i]) { // Find the largest power of prime 'i' that divides n int k = largestPower(n, i); // Multiply result with (i^k) % p res = (res * power(i, k, p)) % p; } } return res; } // Driver method static public void main(String[] args) { int n = 25, p = 29; System.out.println(modFact(n, p)); }}// This code is contributed by Rajput-Ji",
"e": 32057,
"s": 30123,
"text": null
},
{
"code": "# Python3 program to Returns n % p# using Sieve of Eratosthenes # Returns largest power of p that divides n!def largestPower(n, p): # Initialize result x = 0 # Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n): n //= p x += n return x # Utility function to do modular exponentiation.# It returns (x^y) % pdef power( x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more than # or equal to p while (y > 0) : # If y is odd, multiply x with result if (y & 1) : res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # Returns n! % pdef modFact( n, p) : if (n >= p) : return 0 res = 1 # Use Sieve of Eratosthenes to find # all primes smaller than n isPrime = [1] * (n + 1) i = 2 while(i * i <= n): if (isPrime[i]): for j in range(2 * i, n, i) : isPrime[j] = 0 i += 1 # Consider all primes found by Sieve for i in range(2, n): if (isPrime[i]) : # Find the largest power of prime 'i' # that divides n k = largestPower(n, i) # Multiply result with (i^k) % p res = (res * power(i, k, p)) % p return res # Driver codeif __name__ ==\"__main__\": n = 25 p = 29 print(modFact(n, p)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 33541,
"s": 32057,
"text": null
},
{
"code": "// C# program Returns n % p using Sieve of Eratosthenesusing System; public class GFG { // Returns largest power of p that divides n! static int largestPower(int n, int p) { // Initialize result int x = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while (n > 0) { n /= p; x += n; } return x; } // Utility function to do modular exponentiation.// It returns (x^y) % p static int power(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res * x) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n! % p static int modFact(int n, int p) { if (n >= p) { return 0; } int res = 1; // Use Sieve of Eratosthenes to find all primes // smaller than n bool []isPrime = new bool[n + 1]; for(int i = 0;i<n+1;i++) isPrime[i] = true; for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = 2 * i; j <= n; j += i) { isPrime[j] = false; } } } // Consider all primes found by Sieve for (int i = 2; i <= n; i++) { if (isPrime[i]) { // Find the largest power of prime 'i' that divides n int k = largestPower(n, i); // Multiply result with (i^k) % p res = (res * power(i, k, p)) % p; } } return res; } // Driver method static public void Main() { int n = 25, p = 29; Console.WriteLine(modFact(n, p)); }}// This code is contributed by PrinciRaj19992",
"e": 35475,
"s": 33541,
"text": null
},
{
"code": "<?php// PHP program to Returns n % p// using Sieve of Eratosthenes // Returns largest power of p that// divides n!function largestPower($n, $p){ // Initialize result $x = 0; // Calculate x = n/p + n/(p^2) + n/(p^3) + .... while ($n) { $n = (int)($n / $p); $x += $n; } return $x;} // Utility function to do modular exponentiation.// It returns (x^y) % pfunction power($x, $y, $p){ $res = 1; // Initialize result $x = $x % $p; // Update x if it is more // than or equal to p while ($y > 0) { // If y is odd, multiply x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // Returns n! % pfunction modFact($n, $p){ if ($n >= $p) return 0; $res = 1; // Use Sieve of Eratosthenes to find // all primes smaller than n $isPrime = array_fill(0, $n + 1, true); for ($i = 2; $i * $i <= $n; $i++) { if ($isPrime[$i]) { for ($j = 2 * $i; $j <= $n; $j += $i) $isPrime[$j] = 0; } } // Consider all primes found by Sieve for ($i = 2; $i <= $n; $i++) { if ($isPrime[$i]) { // Find the largest power of // prime 'i' that divides n $k = largestPower($n, $i); // Multiply result with (i^k) % p $res = ($res * power($i, $k, $p)) % $p; } } return $res;} // Driver Code$n = 25;$p = 29;echo modFact($n, $p); // This code is contributed by mits?>",
"e": 37070,
"s": 35475,
"text": null
},
{
"code": "<script> // Javascript program Returns n % p // using Sieve of Eratosthenes // Returns largest power of p // that divides n! function largestPower(n, p) { // Initialize result let x = 0; // Calculate x = n/p + n/(p^2) + // n/(p^3) + .... while (n > 0) { n = parseInt(n / p, 10); x += n; } return x; } // Utility function to do // modular exponentiation. // It returns (x^y) % p function power(x, y, p) { // Initialize result let res = 1; // Update x if it is more than or x = x % p; // equal to p while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) { res = (res * x) % p; } // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n! % p function modFact(n, p) { if (n >= p) { return 0; } let res = 1; // Use Sieve of Eratosthenes // to find all primes // smaller than n let isPrime = new Array(n + 1); for(let i = 0;i<n+1;i++) isPrime[i] = true; for (let i = 2; i * i <= n; i++) { if (isPrime[i]) { for (let j = 2 * i; j <= n; j += i) { isPrime[j] = false; } } } // Consider all primes found by Sieve for (let i = 2; i <= n; i++) { if (isPrime[i]) { // Find the largest power of // prime 'i' that divides n let k = largestPower(n, i); // Multiply result with (i^k) % p res = (res * power(i, k, p)) % p; } } return res; } let n = 25, p = 29; document.write(modFact(n, p)); </script>",
"e": 38984,
"s": 37070,
"text": null
},
{
"code": null,
"e": 38993,
"s": 38984,
"text": "Output: "
},
{
"code": null,
"e": 38995,
"s": 38993,
"text": "5"
},
{
"code": null,
"e": 39357,
"s": 38995,
"text": "This is an interesting method, but time complexity of this is more than Simple Method as time complexity of Sieve itself is O(n log log n). This method can be useful if we have list of prime numbers smaller than or equal to n available to us.Method 3 (Using Wilson’s Theorem) Wilson’s theorem states that a natural number p > 1 is a prime number if and only if "
},
{
"code": null,
"e": 39415,
"s": 39357,
"text": " (p - 1) ! ≡ -1 mod p \nOR (p - 1) ! ≡ (p-1) mod p "
},
{
"code": null,
"e": 39774,
"s": 39415,
"text": "Note that n! % p is 0 if n >= p. This method is mainly useful when p is close to input number n. For example (25! % 29). From Wilson’s theorem, we know that 28! is -1. So we basically need to find [ (-1) * inverse(28, 29) * inverse(27, 29) * inverse(26) ] % 29. The inverse function inverse(x, p) returns inverse of x under modulo p (See this for details). "
},
{
"code": null,
"e": 39778,
"s": 39774,
"text": "C++"
},
{
"code": null,
"e": 39783,
"s": 39778,
"text": "Java"
},
{
"code": null,
"e": 39791,
"s": 39783,
"text": "Python3"
},
{
"code": null,
"e": 39794,
"s": 39791,
"text": "C#"
},
{
"code": null,
"e": 39798,
"s": 39794,
"text": "PHP"
},
{
"code": null,
"e": 39809,
"s": 39798,
"text": "Javascript"
},
{
"code": "// C++ program to compute n! % p using Wilson's Theorem#include <bits/stdc++.h>using namespace std; // Utility function to do modular exponentiation.// It returns (x^y) % pint power(int x, unsigned int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Function to find modular inverse of a under modulo p// using Fermat's method. Assumption: p is primeint modInverse(int a, int p){ return power(a, p - 2, p);} // Returns n! % p using Wilson's Theoremint modFact(int n, int p){ // n! % p is 0 if n >= p if (p <= n) return 0; // Initialize result as (p-1)! which is -1 or (p-1) int res = (p - 1); // Multiply modulo inverse of all numbers from (n+1) // to p for (int i = n + 1; i < p; i++) res = (res * modInverse(i, p)) % p; return res;} // Driver methodint main(){ int n = 25, p = 29; cout << modFact(n, p); return 0;}",
"e": 40966,
"s": 39809,
"text": null
},
{
"code": "// Java program to compute n! % p// using Wilson's Theoremclass GFG{ // Utility function to do// modular exponentiation.// It returns (x^y) % pstatic int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0) { // If y is odd, multiply // x with result if ((y & 1) > 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Function to find modular// inverse of a under modulo p// using Fermat's method.// Assumption: p is primestatic int modInverse(int a, int p){ return power(a, p - 2, p);} // Returns n! % p using// Wilson's Theoremstatic int modFact(int n, int p){ // n! % p is 0 if n >= p if (p <= n) return 0; // Initialize result as (p-1)! // which is -1 or (p-1) int res = (p - 1); // Multiply modulo inverse of // all numbers from (n+1) to p for (int i = n + 1; i < p; i++) res = (res * modInverse(i, p)) % p; return res;} // Driver Codepublic static void main(String[] args){ int n = 25, p = 29; System.out.println(modFact(n, p));}} // This code is contributed by mits",
"e": 42218,
"s": 40966,
"text": null
},
{
"code": "def gcdExtended(a,b): if(b==0): return a,1,0 g,x1,y1=gcdExtended(b,a%b) x1,y1 = y1,x1-(a//b)*y1 return g,x1,y1# Driver codefor _ in range(int(input())): n,m=map(int,input().split()) # if n>m, then there is a m in (1*2*3..n) % m such that # m % m=0 then whole ans is 0 if(n>=m): print(0) else: s=1 # Using Wilson's Theorem, (m-1)! % m = m - 1 # Since we need (1*2*3..n) % m # it can be divided into two parts # ( ((1*2*3...n) % m) * ((n+1)*(n+2)*...*(m-1)) )%m=m-1 # We only need to calculate 2nd part i.e. let s=((n+1)*(n+2)*...*(m-1)) ) % m for i in range(n+1,m): s=(s*i)%m # Then we divide (m-1) by s under modulo m means modulo inverse of s under m # It can be done by taking gcd extended g,a,b=gcdExtended(s,m) a=a%m # ans is (m-1)*(modulo inverse of s under m) print(((m-1)*a)%m) # This code is contributed by Himanshu Kaithal",
"e": 43202,
"s": 42218,
"text": null
},
{
"code": "// C# program to compute n! % p// using Wilson's Theoremusing System; // Utility function to do modular// exponentiation. It returns (x^y) % pclass GFG{public int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0) { // If y is odd, multiply // x with result if((y & 1) > 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Function to find modular inverse// of a under modulo p using Fermat's// method. Assumption: p is primepublic int modInverse(int a, int p){ return power(a, p - 2, p);} // Returns n! % p using// Wilson's Theorempublic int modFact(int n, int p){ // n! % p is 0 if n >= p if (p <= n) return 0; // Initialize result as (p-1)! // which is -1 or (p-1) int res = (p - 1); // Multiply modulo inverse of all // numbers from (n+1) to p for (int i = n + 1; i < p; i++) res = (res * modInverse(i, p)) % p; return res;} // Driver methodpublic static void Main(){ GFG g = new GFG(); int n = 25, p = 29; Console.WriteLine(g.modFact(n, p));}} // This code is contributed by Soumik",
"e": 44466,
"s": 43202,
"text": null
},
{
"code": "<?php// PHP program to compute// n!% p using Wilson's Theorem // Utility function to do// modular exponentiation.// It returns (x^y) % pfunction power($x, $y, $p){ $res = 1; // Initialize result $x = $x % $p; // Update x if it is // more than or equal to p while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // Function to find modular// inverse of a under modulo// p using Fermat's method.// Assumption: p is primefunction modInverse($a, $p){ return power($a, $p - 2, $p);} // Returns n! % p// using Wilson's Theoremfunction modFact( $n, $p){ // n! % p is 0 // if n >= p if ($p <= $n) return 0; // Initialize result as // (p-1)! which is -1 or (p-1) $res = ($p - 1); // Multiply modulo inverse // of all numbers from (n+1) // to p for ($i = $n + 1; $i < $p; $i++) $res = ($res * modInverse($i, $p)) % $p; return $res;} // Driver Code$n = 25; $p = 29;echo modFact($n, $p); // This code is contributed by ajit?>",
"e": 45662,
"s": 44466,
"text": null
},
{
"code": "<script> // Javascript program to compute n! % p // using Wilson's Theorem // Utility function to do modular // exponentiation. It returns (x^y) % p function power(x, y, p) { let res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0) { // If y is odd, multiply // x with result if((y & 1) > 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Function to find modular inverse // of a under modulo p using Fermat's // method. Assumption: p is prime function modInverse(a, p) { return power(a, p - 2, p); } // Returns n! % p using // Wilson's Theorem function modFact(n, p) { // n! % p is 0 if n >= p if (p <= n) return 0; // Initialize result as (p-1)! // which is -1 or (p-1) let res = (p - 1); // Multiply modulo inverse of all // numbers from (n+1) to p for (let i = n + 1; i < p; i++) res = (res * modInverse(i, p)) % p; return res; } let n = 25, p = 29; document.write(modFact(n, p)); // This code is contributed by divyeshrabadiya07.</script>",
"e": 47049,
"s": 45662,
"text": null
},
{
"code": null,
"e": 47058,
"s": 47049,
"text": "Output: "
},
{
"code": null,
"e": 47060,
"s": 47058,
"text": "5"
},
{
"code": null,
"e": 47150,
"s": 47060,
"text": "Time complexity of this method is O((p-n)*Logn)Method 4 (Using Primality Test Algorithm) "
},
{
"code": null,
"e": 47309,
"s": 47150,
"text": "1) Initialize: result = 1\n2) While n is not prime\n result = (result * n) % p\n3) result = (result * (n-1)) % p // Using Wilson's Theorem \n4) Return result."
},
{
"code": null,
"e": 47684,
"s": 47309,
"text": "Note that time complexity step 2 of above algorithm depends on the primality test algorithm being used and value of the largest prime smaller than n. The AKS algorithm for example takes O(Log 10.5 n) time. This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 47690,
"s": 47684,
"text": "jit_t"
},
{
"code": null,
"e": 47695,
"s": 47690,
"text": "vt_m"
},
{
"code": null,
"e": 47708,
"s": 47695,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 47721,
"s": 47708,
"text": "SoumikMondal"
},
{
"code": null,
"e": 47729,
"s": 47721,
"text": "ihritik"
},
{
"code": null,
"e": 47739,
"s": 47729,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 47753,
"s": 47739,
"text": "princiraj1992"
},
{
"code": null,
"e": 47768,
"s": 47753,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 47786,
"s": 47768,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 47795,
"s": 47786,
"text": "suresh07"
},
{
"code": null,
"e": 47814,
"s": 47795,
"text": "himanshu2286200116"
},
{
"code": null,
"e": 47823,
"s": 47814,
"text": "rkbhola5"
},
{
"code": null,
"e": 47833,
"s": 47823,
"text": "factorial"
},
{
"code": null,
"e": 47847,
"s": 47833,
"text": "large-numbers"
},
{
"code": null,
"e": 47866,
"s": 47847,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 47880,
"s": 47866,
"text": "number-theory"
},
{
"code": null,
"e": 47886,
"s": 47880,
"text": "sieve"
},
{
"code": null,
"e": 47899,
"s": 47886,
"text": "Mathematical"
},
{
"code": null,
"e": 47913,
"s": 47899,
"text": "number-theory"
},
{
"code": null,
"e": 47926,
"s": 47913,
"text": "Mathematical"
},
{
"code": null,
"e": 47932,
"s": 47926,
"text": "sieve"
},
{
"code": null,
"e": 47951,
"s": 47932,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 47961,
"s": 47951,
"text": "factorial"
},
{
"code": null,
"e": 48059,
"s": 47961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48068,
"s": 48059,
"text": "Comments"
},
{
"code": null,
"e": 48081,
"s": 48068,
"text": "Old Comments"
},
{
"code": null,
"e": 48130,
"s": 48081,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 48151,
"s": 48130,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 48193,
"s": 48151,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 48225,
"s": 48193,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 48268,
"s": 48225,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 48306,
"s": 48268,
"text": "Write a program to calculate pow(x,n)"
},
{
"code": null,
"e": 48359,
"s": 48306,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 48432,
"s": 48359,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 48478,
"s": 48432,
"text": "Write a program to reverse digits of a number"
}
] |
Mean of range in array in C++
|
In this problem, we are given an array of n integers and some m querries. Our task is to create a program that calculates the integral value(round down) of the mean of the ranges given by the querries.
Let’s take an example to understand the problem,
Input −
array = {5, 7, 8, 9, 10}
m = 2; [0, 3], [2, 4]
Output −
7
9
To solve this problem, we have two methods one is direct and the other is using prefix sum.
In the direct approach, for each query, we will loop from the start index to the end index of the range. And add all integers of the array and divide by count. This approach works fine and prints the result but is not an effective one.
In this approach, we will calculate the prefix sum array which will store the sum of all elements of the array till the ith index i.e. prefixSum(4) is the sum of all elements till index 4.
Now, using this prefixSum array we will calculate the mean for each query using the formula,
Mean = prefixSum[upper] - prefixSum(lower-1) / upper-lower+1
Upper and lower are the indexes given in the query. If lower = 0, prefixSum(lower-1) = 0.
Program to illustrate the working of our solution,
Live Demo
#include <iostream>
#define MAX 100
using namespace std;
int prefixSum[MAX];
void initialisePrefixSum(int arr[], int n) {
prefixSum[0] = arr[0];
for (int i = 1; i < n; i++)
prefixSum[i] = prefixSum[i - 1] + arr[i];
}
int queryMean(int l, int r) {
int mean;
if (l == 0)
mean =(prefixSum[r]/(r+1));
else
mean =((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1));
return mean;
}
int main() {
int arr[] = {5, 7, 8, 9, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
initialisePrefixSum(arr, n);
cout<<"Mean in 1st query: "<<queryMean(1, 4)<<endl;
cout<<"Mean in 2st query: "<<queryMean(2, 4)<<endl;
return 0;
}
Mean in 1st query: 8
Mean in 2st query: 9
|
[
{
"code": null,
"e": 1264,
"s": 1062,
"text": "In this problem, we are given an array of n integers and some m querries. Our task is to create a program that calculates the integral value(round down) of the mean of the ranges given by the querries."
},
{
"code": null,
"e": 1313,
"s": 1264,
"text": "Let’s take an example to understand the problem,"
},
{
"code": null,
"e": 1321,
"s": 1313,
"text": "Input −"
},
{
"code": null,
"e": 1368,
"s": 1321,
"text": "array = {5, 7, 8, 9, 10}\nm = 2; [0, 3], [2, 4]"
},
{
"code": null,
"e": 1377,
"s": 1368,
"text": "Output −"
},
{
"code": null,
"e": 1381,
"s": 1377,
"text": "7\n9"
},
{
"code": null,
"e": 1473,
"s": 1381,
"text": "To solve this problem, we have two methods one is direct and the other is using prefix sum."
},
{
"code": null,
"e": 1709,
"s": 1473,
"text": "In the direct approach, for each query, we will loop from the start index to the end index of the range. And add all integers of the array and divide by count. This approach works fine and prints the result but is not an effective one."
},
{
"code": null,
"e": 1898,
"s": 1709,
"text": "In this approach, we will calculate the prefix sum array which will store the sum of all elements of the array till the ith index i.e. prefixSum(4) is the sum of all elements till index 4."
},
{
"code": null,
"e": 1991,
"s": 1898,
"text": "Now, using this prefixSum array we will calculate the mean for each query using the formula,"
},
{
"code": null,
"e": 2052,
"s": 1991,
"text": "Mean = prefixSum[upper] - prefixSum(lower-1) / upper-lower+1"
},
{
"code": null,
"e": 2142,
"s": 2052,
"text": "Upper and lower are the indexes given in the query. If lower = 0, prefixSum(lower-1) = 0."
},
{
"code": null,
"e": 2193,
"s": 2142,
"text": "Program to illustrate the working of our solution,"
},
{
"code": null,
"e": 2204,
"s": 2193,
"text": " Live Demo"
},
{
"code": null,
"e": 2859,
"s": 2204,
"text": "#include <iostream>\n#define MAX 100\nusing namespace std;\nint prefixSum[MAX];\nvoid initialisePrefixSum(int arr[], int n) {\n prefixSum[0] = arr[0];\n for (int i = 1; i < n; i++)\n prefixSum[i] = prefixSum[i - 1] + arr[i];\n}\nint queryMean(int l, int r) {\n int mean;\n if (l == 0)\n mean =(prefixSum[r]/(r+1));\n else\n mean =((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1));\n return mean;\n}\nint main() {\n int arr[] = {5, 7, 8, 9, 10 };\n int n = sizeof(arr) / sizeof(arr[0]);\n initialisePrefixSum(arr, n);\n cout<<\"Mean in 1st query: \"<<queryMean(1, 4)<<endl;\n cout<<\"Mean in 2st query: \"<<queryMean(2, 4)<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 2901,
"s": 2859,
"text": "Mean in 1st query: 8\nMean in 2st query: 9"
}
] |
C++ Program to Implement a Binary Search Tree using Linked Lists
|
Here is a C++ program to Implement a Binary Search Tree using Linked Lists.
Begin
Take the nodes of the tree as input.
Create a structure nod to take the data d, a left pointer l and a right r as input.
Create a function create() to insert nodes into the tree:
Initialize c = 0 as number of nodes.
Perform while loop till c < 6:
Enter the root.
Enter the value of the node, if it is greater than root then entered as right otherwise left.
Create a function inorder() to traverse the node as inorder as:
Left – Root – Right.
Create a function preorder() to traverse the node as preorder as:
Root – Left – Right.
Create a function postorder() to traverse the node as preorder as:
Left – Right – Root
From main(), call the functions and print the result.
End
Live Demo
#include <iostream>
using namespace std;
struct nod {
nod *l, *r;
int d;
}*r = NULL, *p = NULL, *np = NULL, *q;
void create() {
int v,c = 0;
while (c < 6) {
if (r == NULL) {
r = new nod;
cout<<"enter value of root node\n";
cin>>r->d;
r->r = NULL;
r->l = NULL;
} else {
p = r;
cout<<"enter value of node\n";
cin>>v;
while(true) {
if (v< p->d) {
if (p->l == NULL) {
p->l = new nod;
p = p->l;
p->d = v;
p->l = NULL;
p->r = NULL;
cout<<"value entered in left\n";
break;
} else if (p->l != NULL) {
p = p->l;
}
} else if (v >p->d) {
if (p->r == NULL) {
p->r = new nod;
p = p->r;
p->d = v;
p->l = NULL;
p->r = NULL;
cout<<"value entered in right\n";
break;
} else if (p->r != NULL) {
p = p->r;
}
}
}
}
c++;
}
}
void inorder(nod *p) {
if (p != NULL) {
inorder(p->l);
cout<<p->d<<endl;
inorder(p->r);
}
}
void preorder(nod *p) {
if (p != NULL) {
cout<<p->d<<endl;
preorder(p->l);
preorder(p->r);
}
}
void postorder(nod *p) {
if (p != NULL) {
postorder(p->l);
postorder(p->r);
cout<<p->d<<endl;
}
}
int main() {
create();
cout<<" traversal in inorder\n";
inorder(r);
cout<<" traversal in preorder\n";
preorder(r);
cout<<" traversal in postorder\n";
postorder(r);
}
enter value of root node
7
enter value of node
6
value entered in left
enter value of node
4
value entered in left
enter value of node
3
value entered in left
enter value of node
2
value entered in left
enter value of node
1
value entered in left
traversal in inorder
1
2
3
4
6
7
traversal in preorder
7
6
4
3
2
1
traversal in postorder
1
2
3
4
6
7
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "Here is a C++ program to Implement a Binary Search Tree using Linked Lists."
},
{
"code": null,
"e": 1887,
"s": 1138,
"text": "Begin\n Take the nodes of the tree as input.\n Create a structure nod to take the data d, a left pointer l and a right r as input.\n Create a function create() to insert nodes into the tree:\n Initialize c = 0 as number of nodes.\n Perform while loop till c < 6:\n Enter the root.\n Enter the value of the node, if it is greater than root then entered as right otherwise left.\n Create a function inorder() to traverse the node as inorder as:\n Left – Root – Right.\n Create a function preorder() to traverse the node as preorder as:\n Root – Left – Right.\n Create a function postorder() to traverse the node as preorder as:\n Left – Right – Root\n From main(), call the functions and print the result.\nEnd"
},
{
"code": null,
"e": 1898,
"s": 1887,
"text": " Live Demo"
},
{
"code": null,
"e": 3695,
"s": 1898,
"text": "#include <iostream>\nusing namespace std;\n\nstruct nod {\n nod *l, *r;\n int d;\n}*r = NULL, *p = NULL, *np = NULL, *q;\n\nvoid create() {\n int v,c = 0;\n while (c < 6) {\n if (r == NULL) {\n r = new nod;\n cout<<\"enter value of root node\\n\";\n cin>>r->d;\n r->r = NULL;\n r->l = NULL;\n } else {\n p = r;\n cout<<\"enter value of node\\n\";\n cin>>v;\n while(true) {\n if (v< p->d) {\n if (p->l == NULL) {\n p->l = new nod;\n p = p->l;\n p->d = v;\n p->l = NULL;\n p->r = NULL;\n cout<<\"value entered in left\\n\";\n break;\n } else if (p->l != NULL) {\n p = p->l;\n }\n } else if (v >p->d) {\n if (p->r == NULL) {\n p->r = new nod;\n p = p->r;\n p->d = v;\n p->l = NULL;\n p->r = NULL;\n cout<<\"value entered in right\\n\";\n break;\n } else if (p->r != NULL) {\n p = p->r;\n }\n }\n }\n }\n c++;\n }\n}\n\nvoid inorder(nod *p) {\n if (p != NULL) {\n inorder(p->l);\n cout<<p->d<<endl;\n inorder(p->r);\n }\n}\n\nvoid preorder(nod *p) {\n if (p != NULL) {\n cout<<p->d<<endl;\n preorder(p->l);\n preorder(p->r);\n }\n}\n\nvoid postorder(nod *p) {\n if (p != NULL) {\n postorder(p->l);\n postorder(p->r);\n cout<<p->d<<endl;\n }\n}\n\nint main() {\n create();\n cout<<\" traversal in inorder\\n\";\n inorder(r);\n cout<<\" traversal in preorder\\n\";\n preorder(r);\n cout<<\" traversal in postorder\\n\";\n postorder(r);\n}"
},
{
"code": null,
"e": 4044,
"s": 3695,
"text": "enter value of root node\n7\nenter value of node\n6\nvalue entered in left\nenter value of node\n4\nvalue entered in left\nenter value of node\n3\nvalue entered in left\nenter value of node\n2\nvalue entered in left\nenter value of node\n1\nvalue entered in left\ntraversal in inorder\n1\n2\n3\n4\n6\n7\ntraversal in preorder\n7\n6\n4\n3\n2\n1\ntraversal in postorder\n1\n2\n3\n4\n6\n7"
}
] |
Bootstrap 4 | Cards - GeeksforGeeks
|
28 Jul, 2021
A Bootstrap card is a flexible box containing some padding around the content. It includes the options for headers and footers, color, content, and powerful display options. It replaces the use of panels, wells, and thumbnails. It can be used in a single container called card.
Basic Card: The .card and .card-body classes are used to create basic card. The .card-body class is used inside the .card class.Example:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <div class="card"> <div class="card-body">card-body</div> </div> </div></body> </html>
Output:
Header and Footer: The .card-header class provides header to the cards and .card-footer class provides footer to the cards.Example:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <div class="card"> <div class="card-header">Card Header</div> <div class="card-body">Card Body</div> <div class="card-footer">Card Footer</div> </div> </div></body> </html>
Output:
Card Title and Links: The .card-title class is used to set a title to the card and .card-link class is used to set a link to the card if required in it.Example:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <div class="card"> <div class="card-title">Card Title</div> <p class="card-text">Card Text.</p> <a href="#" class="card-link">Click Me!</div> </div> </div></body> </html>
Output:
Card Styles: Card styles can be set by using a color of the card so that it may be easy for the user to understand what does the particular card stands for. It consists of the colors used in the alerts.Example:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <div class="card text-white bg-primary"> <div class="card-header">Primary</div> <h4 class="card-title">Title.</h4> </div> <br> <div class="card text-white bg-danger"> <div class="card-header">Danger</div> <h4 class="card-title">Title.</h4> </div> <br> <div class="card text-white bg-warning"> <div class="card-header">Warning</div> <h4 class="card-title">Title.</h4> </div> <br> <div class="card text-white bg-info"> <div class="card-header">Info</div> <h4 class="card-title">Title.</h4> </div> </div></body> </html>
Output:
Card Images: The .card-img-top or .card-img-bottom class is used to place the image at top or bottom inside the card.Example 1:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Author Name</h5> <p class="card-text">Passionate about programming.</p> <a href="#" class="btn btn-primary">See Profile</a> </div> </div></div></body> </html>
Output:
Example 2:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Author Name</h5> <p class="card-text">Passionate about programming.</p> <a href="#" class="btn btn-primary">See Profile</a> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png" alt="Card image cap"> </div> </div> </div></body> </html>
Output:
Card Image Overlays: The .card-img-overlay class is used to add text on the top of the image.Example:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <div class="card" style="width: 18rem;"> <img class="card-img-bottom" src="https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png" alt="Card image cap"> <div class="card-img-overlay"> <div class="card-body"> <h5 class="card-title">Author Name</h5> <p class="card-text">Passionate about programming.</p> <a href="#" class="btn btn-primary">See Profile</a> </div> </div> </div> </div></body> </html>
Output:
Card Deck: The .card-deck class is used to create an equal height and width card grid. Example:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <div class="card-deck"> <div class="card text-white bg-primary"> <div class="card-body"> <h4 class="card-title">Primary</h4> </div> </div> <div class="card text-white bg-danger"> <div class="card-body"> <h4 class="card-title">Danger</h4> </div> </div> <div class="card text-white bg-warning"> <div class="card-body"> <h4 class="card-title">Warning</h4> </div> </div> <div class="card text-white bg-info"> <div class="card-body"> <h4 class="card-title">Info</h4> </div> </div> </div> </div></body> </html>
Output:
Card Group: The .card-group class is used to create equal height and width card grid and removing the left and right margins between the cards.Example:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <div class="card-group"> <div class="card text-white bg-primary"> <div class="card-body"> <h4 class="card-title">Primary</h4> </div> </div> <div class="card text-white bg-danger"> <div class="card-body"> <h4 class="card-title">Danger</h4> </div> </div> <div class="card text-white bg-warning"> <div class="card-body"> <h4 class="card-title">Warning</h4> </div> </div> <div class="card text-white bg-info"> <div class="card-body"> <h4 class="card-title">Info</h4> </div> </div> </div> </div></body> </html>
Output:
List groups: The .list-group and .list-group-flush classes are used to create a list of contents in a card.Example:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <div class="card"> <ul class="list-group list-group-flush"> <li class="list-group-item">List Item 1</li> <li class="list-group-item">List Item 2</li> <li class="list-group-item">List Item 3</li> </ul> </div> </div></body> </html>
Output:
Kitchen sink: It is a name given to the type of card which consists of everything in it. It mixes and matches multiple contents to make the desired card.Example:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="container"> <div class="card" style="width:12rem;"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png"> <div class="card-block"> <h4 class="card-title">Languages</h4> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">C</li> <li class="list-group-item">C++</li> <li class="list-group-item">JavaScript</li> </ul> <div class="card-body"> <a href="#" class="card-link">Add New</a> <a href="#" class="card-link">More..</a> </div> </div> </div></body> </html>
Output:
Navigation: It adds the navigation menu to the card header.Example:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="card text-center"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs"> <li class="nav-item"> <a class="nav-link active" href="#">JavaStript</a> </li> <li class="nav-item"> <a class="nav-link" href="#">BootStrap</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Python</a> </li> </ul> </div> <div class="card-body"> <h5 class="card-title">Card Title</h5> <p class="card-text">Add more language tutorials.</p> <a href="#" class="btn btn-primary">Add Language</a> </div> </div></body> </html>
Output:
Navigation menu in pills form: It adds the navigation menu in pills form to the card header.Example:
html
<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <h1 style="color:green;text-align:center;"> GeeksforGeeks </h1> <div class="card text-center"> <div class="card-header"> <ul class="nav nav-pills card-header-pills"> <li class="nav-item"> <a class="nav-link active" href="#">JavaStript</a> </li> <li class="nav-item"> <a class="nav-link" href="#">BootStrap</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Python</a> </li> </ul> </div> <div class="card-body"> <h5 class="card-title">Card Title</h5> <p class="card-text">Add more language tutorials.</p> <a href="#" class="btn btn-primary">Add Language</a> </div> </div></body> </html>
Output:
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
ysachin2314
Bootstrap-4
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to align navbar items to the right in Bootstrap 4 ?
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 28049,
"s": 28021,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 28329,
"s": 28049,
"text": "A Bootstrap card is a flexible box containing some padding around the content. It includes the options for headers and footers, color, content, and powerful display options. It replaces the use of panels, wells, and thumbnails. It can be used in a single container called card. "
},
{
"code": null,
"e": 28468,
"s": 28329,
"text": "Basic Card: The .card and .card-body classes are used to create basic card. The .card-body class is used inside the .card class.Example: "
},
{
"code": null,
"e": 28473,
"s": 28468,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"card\"> <div class=\"card-body\">card-body</div> </div> </div></body> </html> ",
"e": 29329,
"s": 28473,
"text": null
},
{
"code": null,
"e": 29339,
"s": 29329,
"text": "Output: "
},
{
"code": null,
"e": 29473,
"s": 29339,
"text": "Header and Footer: The .card-header class provides header to the cards and .card-footer class provides footer to the cards.Example: "
},
{
"code": null,
"e": 29478,
"s": 29473,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"card\"> <div class=\"card-header\">Card Header</div> <div class=\"card-body\">Card Body</div> <div class=\"card-footer\">Card Footer</div> </div> </div></body> </html> ",
"e": 30442,
"s": 29478,
"text": null
},
{
"code": null,
"e": 30452,
"s": 30442,
"text": "Output: "
},
{
"code": null,
"e": 30615,
"s": 30452,
"text": "Card Title and Links: The .card-title class is used to set a title to the card and .card-link class is used to set a link to the card if required in it.Example: "
},
{
"code": null,
"e": 30620,
"s": 30615,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"card\"> <div class=\"card-title\">Card Title</div> <p class=\"card-text\">Card Text.</p> <a href=\"#\" class=\"card-link\">Click Me!</div> </div> </div></body> </html> ",
"e": 31583,
"s": 30620,
"text": null
},
{
"code": null,
"e": 31593,
"s": 31583,
"text": "Output: "
},
{
"code": null,
"e": 31806,
"s": 31593,
"text": "Card Styles: Card styles can be set by using a color of the card so that it may be easy for the user to understand what does the particular card stands for. It consists of the colors used in the alerts.Example: "
},
{
"code": null,
"e": 31811,
"s": 31806,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"card text-white bg-primary\"> <div class=\"card-header\">Primary</div> <h4 class=\"card-title\">Title.</h4> </div> <br> <div class=\"card text-white bg-danger\"> <div class=\"card-header\">Danger</div> <h4 class=\"card-title\">Title.</h4> </div> <br> <div class=\"card text-white bg-warning\"> <div class=\"card-header\">Warning</div> <h4 class=\"card-title\">Title.</h4> </div> <br> <div class=\"card text-white bg-info\"> <div class=\"card-header\">Info</div> <h4 class=\"card-title\">Title.</h4> </div> </div></body> </html> ",
"e": 33237,
"s": 31811,
"text": null
},
{
"code": null,
"e": 33247,
"s": 33237,
"text": "Output: "
},
{
"code": null,
"e": 33377,
"s": 33247,
"text": "Card Images: The .card-img-top or .card-img-bottom class is used to place the image at top or bottom inside the card.Example 1: "
},
{
"code": null,
"e": 33382,
"s": 33377,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"card\" style=\"width: 18rem;\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png\" alt=\"Card image cap\"> <div class=\"card-body\"> <h5 class=\"card-title\">Author Name</h5> <p class=\"card-text\">Passionate about programming.</p> <a href=\"#\" class=\"btn btn-primary\">See Profile</a> </div> </div></div></body> </html> ",
"e": 34586,
"s": 33382,
"text": null
},
{
"code": null,
"e": 34596,
"s": 34586,
"text": "Output: "
},
{
"code": null,
"e": 34609,
"s": 34596,
"text": "Example 2: "
},
{
"code": null,
"e": 34614,
"s": 34609,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"card\" style=\"width: 18rem;\"> <div class=\"card-body\"> <h5 class=\"card-title\">Author Name</h5> <p class=\"card-text\">Passionate about programming.</p> <a href=\"#\" class=\"btn btn-primary\">See Profile</a> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png\" alt=\"Card image cap\"> </div> </div> </div></body> </html> ",
"e": 35850,
"s": 34614,
"text": null
},
{
"code": null,
"e": 35860,
"s": 35850,
"text": "Output: "
},
{
"code": null,
"e": 35964,
"s": 35860,
"text": "Card Image Overlays: The .card-img-overlay class is used to add text on the top of the image.Example: "
},
{
"code": null,
"e": 35969,
"s": 35964,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"card\" style=\"width: 18rem;\"> <img class=\"card-img-bottom\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png\" alt=\"Card image cap\"> <div class=\"card-img-overlay\"> <div class=\"card-body\"> <h5 class=\"card-title\">Author Name</h5> <p class=\"card-text\">Passionate about programming.</p> <a href=\"#\" class=\"btn btn-primary\">See Profile</a> </div> </div> </div> </div></body> </html> ",
"e": 37293,
"s": 35969,
"text": null
},
{
"code": null,
"e": 37303,
"s": 37293,
"text": "Output: "
},
{
"code": null,
"e": 37401,
"s": 37303,
"text": "Card Deck: The .card-deck class is used to create an equal height and width card grid. Example: "
},
{
"code": null,
"e": 37406,
"s": 37401,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"card-deck\"> <div class=\"card text-white bg-primary\"> <div class=\"card-body\"> <h4 class=\"card-title\">Primary</h4> </div> </div> <div class=\"card text-white bg-danger\"> <div class=\"card-body\"> <h4 class=\"card-title\">Danger</h4> </div> </div> <div class=\"card text-white bg-warning\"> <div class=\"card-body\"> <h4 class=\"card-title\">Warning</h4> </div> </div> <div class=\"card text-white bg-info\"> <div class=\"card-body\"> <h4 class=\"card-title\">Info</h4> </div> </div> </div> </div></body> </html> ",
"e": 38956,
"s": 37406,
"text": null
},
{
"code": null,
"e": 38966,
"s": 38956,
"text": "Output: "
},
{
"code": null,
"e": 39120,
"s": 38966,
"text": "Card Group: The .card-group class is used to create equal height and width card grid and removing the left and right margins between the cards.Example: "
},
{
"code": null,
"e": 39125,
"s": 39120,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"card-group\"> <div class=\"card text-white bg-primary\"> <div class=\"card-body\"> <h4 class=\"card-title\">Primary</h4> </div> </div> <div class=\"card text-white bg-danger\"> <div class=\"card-body\"> <h4 class=\"card-title\">Danger</h4> </div> </div> <div class=\"card text-white bg-warning\"> <div class=\"card-body\"> <h4 class=\"card-title\">Warning</h4> </div> </div> <div class=\"card text-white bg-info\"> <div class=\"card-body\"> <h4 class=\"card-title\">Info</h4> </div> </div> </div> </div></body> </html> ",
"e": 40707,
"s": 39125,
"text": null
},
{
"code": null,
"e": 40717,
"s": 40707,
"text": "Output: "
},
{
"code": null,
"e": 40835,
"s": 40717,
"text": "List groups: The .list-group and .list-group-flush classes are used to create a list of contents in a card.Example: "
},
{
"code": null,
"e": 40840,
"s": 40835,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"card\"> <ul class=\"list-group list-group-flush\"> <li class=\"list-group-item\">List Item 1</li> <li class=\"list-group-item\">List Item 2</li> <li class=\"list-group-item\">List Item 3</li> </ul> </div> </div></body> </html> ",
"e": 41905,
"s": 40840,
"text": null
},
{
"code": null,
"e": 41915,
"s": 41905,
"text": "Output: "
},
{
"code": null,
"e": 42079,
"s": 41915,
"text": "Kitchen sink: It is a name given to the type of card which consists of everything in it. It mixes and matches multiple contents to make the desired card.Example: "
},
{
"code": null,
"e": 42084,
"s": 42079,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"card\" style=\"width:12rem;\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png\"> <div class=\"card-block\"> <h4 class=\"card-title\">Languages</h4> </div> <ul class=\"list-group list-group-flush\"> <li class=\"list-group-item\">C</li> <li class=\"list-group-item\">C++</li> <li class=\"list-group-item\">JavaScript</li> </ul> <div class=\"card-body\"> <a href=\"#\" class=\"card-link\">Add New</a> <a href=\"#\" class=\"card-link\">More..</a> </div> </div> </div></body> </html> ",
"e": 43575,
"s": 42084,
"text": null
},
{
"code": null,
"e": 43585,
"s": 43575,
"text": "Output: "
},
{
"code": null,
"e": 43655,
"s": 43585,
"text": "Navigation: It adds the navigation menu to the card header.Example: "
},
{
"code": null,
"e": 43660,
"s": 43655,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"card text-center\"> <div class=\"card-header\"> <ul class=\"nav nav-tabs card-header-tabs\"> <li class=\"nav-item\"> <a class=\"nav-link active\" href=\"#\">JavaStript</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">BootStrap</a> </li> <li class=\"nav-item\"> <a class=\"nav-link disabled\" href=\"#\">Python</a> </li> </ul> </div> <div class=\"card-body\"> <h5 class=\"card-title\">Card Title</h5> <p class=\"card-text\">Add more language tutorials.</p> <a href=\"#\" class=\"btn btn-primary\">Add Language</a> </div> </div></body> </html> ",
"e": 45174,
"s": 43660,
"text": null
},
{
"code": null,
"e": 45184,
"s": 45174,
"text": "Output: "
},
{
"code": null,
"e": 45287,
"s": 45184,
"text": "Navigation menu in pills form: It adds the navigation menu in pills form to the card header.Example: "
},
{
"code": null,
"e": 45292,
"s": 45287,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Cards</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.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <h1 style=\"color:green;text-align:center;\"> GeeksforGeeks </h1> <div class=\"card text-center\"> <div class=\"card-header\"> <ul class=\"nav nav-pills card-header-pills\"> <li class=\"nav-item\"> <a class=\"nav-link active\" href=\"#\">JavaStript</a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\">BootStrap</a> </li> <li class=\"nav-item\"> <a class=\"nav-link disabled\" href=\"#\">Python</a> </li> </ul> </div> <div class=\"card-body\"> <h5 class=\"card-title\">Card Title</h5> <p class=\"card-text\">Add more language tutorials.</p> <a href=\"#\" class=\"btn btn-primary\">Add Language</a> </div> </div></body> </html> ",
"e": 46801,
"s": 45292,
"text": null
},
{
"code": null,
"e": 46811,
"s": 46801,
"text": "Output: "
},
{
"code": null,
"e": 46830,
"s": 46811,
"text": "Supported Browser:"
},
{
"code": null,
"e": 46844,
"s": 46830,
"text": "Google Chrome"
},
{
"code": null,
"e": 46862,
"s": 46844,
"text": "Internet Explorer"
},
{
"code": null,
"e": 46870,
"s": 46862,
"text": "Firefox"
},
{
"code": null,
"e": 46876,
"s": 46870,
"text": "Opera"
},
{
"code": null,
"e": 46883,
"s": 46876,
"text": "Safari"
},
{
"code": null,
"e": 46895,
"s": 46883,
"text": "ysachin2314"
},
{
"code": null,
"e": 46907,
"s": 46895,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 46917,
"s": 46907,
"text": "Bootstrap"
},
{
"code": null,
"e": 46934,
"s": 46917,
"text": "Web Technologies"
},
{
"code": null,
"e": 47032,
"s": 46934,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47041,
"s": 47032,
"text": "Comments"
},
{
"code": null,
"e": 47054,
"s": 47041,
"text": "Old Comments"
},
{
"code": null,
"e": 47104,
"s": 47054,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 47133,
"s": 47104,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 47189,
"s": 47133,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 47230,
"s": 47189,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 47271,
"s": 47230,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 47327,
"s": 47271,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 47360,
"s": 47327,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 47422,
"s": 47360,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 47465,
"s": 47422,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python Design Patterns - Factory
|
The factory pattern comes under the creational patterns list category. It provides one of the best ways to create an object. In factory pattern, objects are created without exposing the logic to client and referring to the newly created object using a common interface.
Factory patterns are implemented in Python using factory method. When a user calls a method such that we pass in a string and the return value as a new object is implemented through factory method. The type of object used in factory method is determined by string which is passed through method.
In the example below, every method includes object as a parameter, which is implemented through factory method.
Let us now see how to implement a factory pattern.
class Button(object):
html = ""
def get_html(self):
return self.html
class Image(Button):
html = "<img></img>"
class Input(Button):
html = "<input></input>"
class Flash(Button):
html = "<obj></obj>"
class ButtonFactory():
def create_button(self, typ):
targetclass = typ.capitalize()
return globals()[targetclass]()
button_obj = ButtonFactory()
button = ['image', 'input', 'flash']
for b in button:
print button_obj.create_button(b).get_html()
The button class helps to create the html tags and the associated html page. The client will not have access to the logic of code and the output represents the creation of html page.
The python code includes the logic of html tags, which specified value. The end user can have a look on the HTML file created by the Python code.
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": 2749,
"s": 2479,
"text": "The factory pattern comes under the creational patterns list category. It provides one of the best ways to create an object. In factory pattern, objects are created without exposing the logic to client and referring to the newly created object using a common interface."
},
{
"code": null,
"e": 3045,
"s": 2749,
"text": "Factory patterns are implemented in Python using factory method. When a user calls a method such that we pass in a string and the return value as a new object is implemented through factory method. The type of object used in factory method is determined by string which is passed through method."
},
{
"code": null,
"e": 3157,
"s": 3045,
"text": "In the example below, every method includes object as a parameter, which is implemented through factory method."
},
{
"code": null,
"e": 3208,
"s": 3157,
"text": "Let us now see how to implement a factory pattern."
},
{
"code": null,
"e": 3695,
"s": 3208,
"text": "class Button(object):\n html = \"\"\n def get_html(self):\n return self.html\n\nclass Image(Button):\n html = \"<img></img>\"\n\nclass Input(Button):\n html = \"<input></input>\"\n\nclass Flash(Button):\n html = \"<obj></obj>\"\n\nclass ButtonFactory():\n def create_button(self, typ):\n targetclass = typ.capitalize()\n return globals()[targetclass]()\n\nbutton_obj = ButtonFactory()\nbutton = ['image', 'input', 'flash']\nfor b in button:\n print button_obj.create_button(b).get_html()"
},
{
"code": null,
"e": 3878,
"s": 3695,
"text": "The button class helps to create the html tags and the associated html page. The client will not have access to the logic of code and the output represents the creation of html page."
},
{
"code": null,
"e": 4024,
"s": 3878,
"text": "The python code includes the logic of html tags, which specified value. The end user can have a look on the HTML file created by the Python code."
},
{
"code": null,
"e": 4061,
"s": 4024,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4077,
"s": 4061,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4110,
"s": 4077,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4129,
"s": 4110,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4164,
"s": 4129,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4186,
"s": 4164,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4220,
"s": 4186,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4248,
"s": 4220,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4283,
"s": 4248,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4297,
"s": 4283,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4330,
"s": 4297,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4347,
"s": 4330,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4354,
"s": 4347,
"text": " Print"
},
{
"code": null,
"e": 4365,
"s": 4354,
"text": " Add Notes"
}
] |
Hibernate One To Many Annotations | Hibernate Annotations | @OnetoMany
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorials, we are going to implement hibernate one to many relationship using annotations. In the previous tutorial, we did the same example using xml configuration one to many relationship with xml.
A one to many relationship can occur, if an entity is related to multiple occurrences in another entity. In simple terms, if one row in database table can be mapped to multiple rows in another table, then we can call that relationship as one to many relationship. Here is the example for Hibernate one to many relationship using annotations.
To implement the one to many relationship, we are taking Vendor and Customer. Here the relationship between the Vendor to Customer is one to many. That is one Vendor can have multiple Customers. The same relationship is developed using hibernate one to many annotations.
Database Tables :
CREATE TABLE `vendor` (
`vendid` INT(11) NOT NULL,
`venName` VARCHAR(10) NULL DEFAULT NULL,
PRIMARY KEY (`vendid`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;
CREATE TABLE `customer` (
`custid` INT(11) NOT NULL,
`custaddress` VARCHAR(10) NULL DEFAULT NULL,
`custname` VARCHAR(10) NULL DEFAULT NULL,
`venid` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`custid`),
INDEX (`venid`),
CONSTRAINT FOREIGN KEY (`venid`) REFERENCES `vendor` (`vendid`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;
Project Structure :
Required Dependencies :
<dependencies>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.0.Final</version>
</dependency>
<!-- MySQL Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5</version>
</dependency>
</dependencies>
Hibernate POJO Classes :
Vendor.java
package com.onlinetutorialspoint.hibernate.pojo;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "vendor")
public class Vendor {
@Id
@Column(name = "vendid")
private int vendorId;
@Column(name = "venName", length = 10)
private String vendorName;
@OneToMany(targetEntity = Customer.class, cascade = CascadeType.ALL)
@JoinColumn(name = "venid", referencedColumnName = "vendid")
private Set customers;
public int getVendorId() {
return vendorId;
}
public void setVendorId(int vendorId) {
this.vendorId = vendorId;
}
public String getVendorName() {
return vendorName;
}
public void setVendorName(String vendorName) {
this.vendorName = vendorName;
}
public Set getCustomers() {
return customers;
}
public void setCustomers(Set customers) {
this.customers = customers;
}
}
Customer.java
package com.onlinetutorialspoint.hibernate.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "customer")
public class Customer {
@Id
@Column(name = "custid")
private int customerId;
@Column(name = "custname", length = 10)
private String customerName;
@Column(name = "custaddress", length = 10)
private String customerAddress;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
}
Hibernate Utility Class :
HibernateUtil.java
package com.onlinetutorialspoint.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private HibernateUtil() {
}
private static SessionFactory sessionFactory;
public static synchronized SessionFactory getInstnce() {
if (sessionFactory == null) {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
return sessionFactory;
}
}
Well ! Its completed, Now we can Run our application:
Main.java
import java.util.HashSet;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.onlinetutorialspoint.hibernate.pojo.Customer;
import com.onlinetutorialspoint.hibernate.pojo.Vendor;
import com.onlinetutorialspoint.util.HibernateUtil;
public class Main {
public static void main(String a[])
{
SessionFactory sessionFactory = HibernateUtil.getInstnce();
Session session = sessionFactory.openSession();
Vendor vendor=new Vendor();
vendor.setVendorId(101);
vendor.setVendorName("IBM");
Customer customer=new Customer();
customer.setCustomerId(102);
customer.setCustomerName("NIFY");
customer.setCustomerAddress("BANG");
Customer customer2=new Customer();
customer2.setCustomerId(104);
customer2.setCustomerName("TCS");
customer2.setCustomerAddress("HYD");
Customer customer3=new Customer();
customer3.setCustomerId(105);
customer3.setCustomerName("VERIZON");
customer3.setCustomerAddress("US");
Set customers = new HashSet();
customers.add(customer);
customers.add(customer2);
customers.add(customer3);
vendor.setCustomers(customers);
Transaction transaction=session.beginTransaction();
session.save(vendor);
transaction.commit();
session.close();
sessionFactory.close();
}
}
Output :
Hibernate: select customer_.custid, customer_.custaddress as custaddr2_0_, customer_.custname as custname3_0_ from customer customer_ where customer_.custid=?
Hibernate: select customer_.custid, customer_.custaddress as custaddr2_0_, customer_.custname as custname3_0_ from customer customer_ where customer_.custid=?
Hibernate: select customer_.custid, customer_.custaddress as custaddr2_0_, customer_.custname as custname3_0_ from customer customer_ where customer_.custid=?
Hibernate: insert into vendor (venName, vendid) values (?, ?)
Hibernate: insert into customer (custaddress, custname, custid) values (?, ?, ?)
Hibernate: insert into customer (custaddress, custname, custid) values (?, ?, ?)
Hibernate: insert into customer (custaddress, custname, custid) values (?, ?, ?)
Hibernate: update customer set venid=? where custid=?
Hibernate: update customer set venid=? where custid=?
Hibernate: update customer set venid=? where custid=?
Database Output :
Happy Learning:)
Hibernate One To Many Annotations Example
File size: 18 KB
Downloads: 1062
Many to One Mapping in Hibernate Example
Hibernate Table per Class strategy Annotations Example
Hibernate One To Many Example (XML Mapping)
Hibernate Right Join Example
Hibernate Left Join Example
Hibernate 4 Example with Annotations Mysql
Custom Generator Class in Hibernate
Hibernate Filters Example Annotation
Hibernate Named Query with Example
@Formula Annotation in Hibernate Example
One to One Mapping in Hibernate using foreign key (XML)
Basic Hibernate Example with XML Configuration
Hibernate One to One Mapping using primary key (XML)
Singleton Hibernate SessionFactory Example
Calling Stored Procedures in Hibernate
Many to One Mapping in Hibernate Example
Hibernate Table per Class strategy Annotations Example
Hibernate One To Many Example (XML Mapping)
Hibernate Right Join Example
Hibernate Left Join Example
Hibernate 4 Example with Annotations Mysql
Custom Generator Class in Hibernate
Hibernate Filters Example Annotation
Hibernate Named Query with Example
@Formula Annotation in Hibernate Example
One to One Mapping in Hibernate using foreign key (XML)
Basic Hibernate Example with XML Configuration
Hibernate One to One Mapping using primary key (XML)
Singleton Hibernate SessionFactory Example
Calling Stored Procedures in Hibernate
Δ
Hibernate – Introduction
Hibernate – Advantages
Hibernate – Download and Setup
Hibernate – Sql Dialect list
Hibernate – Helloworld – XML
Hibernate – Install Tools in Eclipse
Hibernate – Object States
Hibernate – Helloworld – Annotations
Hibernate – One to One Mapping – XML
Hibernate – One to One Mapping foreign key – XML
Hibernate – One To Many -XML
Hibernate – One To Many – Annotations
Hibernate – Many to Many Mapping – XML
Hibernate – Many to One – XML
Hibernate – Composite Key Mapping
Hibernate – Named Query
Hibernate – Native SQL Query
Hibernate – load() vs get()
Hibernate Criteria API with Example
Hibernate – Restrictions
Hibernate – Projection
Hibernate – Query Language (HQL)
Hibernate – Groupby Criteria HQL
Hibernate – Orderby Criteria
Hibernate – HQLSelect Operation
Hibernate – HQL Update, Delete
Hibernate – Update Query
Hibernate – Update vs Merge
Hibernate – Right Join
Hibernate – Left Join
Hibernate – Pagination
Hibernate – Generator Classes
Hibernate – Custom Generator
Hibernate – Inheritance Mappings
Hibernate – Table per Class
Hibernate – Table per Sub Class
Hibernate – Table per Concrete Class
Hibernate – Table per Class Annotations
Hibernate – Stored Procedures
Hibernate – @Formula Annotation
Hibernate – Singleton SessionFactory
Hibernate – Interceptor
hbm2ddl.auto Example in Hibernate XML Config
Hibernate – First Level Cache
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 606,
"s": 398,
"text": "In this tutorials, we are going to implement hibernate one to many relationship using annotations. In the previous tutorial, we did the same example using xml configuration one to many relationship with xml."
},
{
"code": null,
"e": 948,
"s": 606,
"text": "A one to many relationship can occur, if an entity is related to multiple occurrences in another entity. In simple terms, if one row in database table can be mapped to multiple rows in another table, then we can call that relationship as one to many relationship. Here is the example for Hibernate one to many relationship using annotations."
},
{
"code": null,
"e": 1219,
"s": 948,
"text": "To implement the one to many relationship, we are taking Vendor and Customer. Here the relationship between the Vendor to Customer is one to many. That is one Vendor can have multiple Customers. The same relationship is developed using hibernate one to many annotations."
},
{
"code": null,
"e": 1237,
"s": 1219,
"text": "Database Tables :"
},
{
"code": null,
"e": 1723,
"s": 1237,
"text": "CREATE TABLE `vendor` (\n`vendid` INT(11) NOT NULL,\n`venName` VARCHAR(10) NULL DEFAULT NULL,\nPRIMARY KEY (`vendid`)\n)\nCOLLATE='latin1_swedish_ci'\nENGINE=InnoDB;\n\nCREATE TABLE `customer` (\n`custid` INT(11) NOT NULL,\n`custaddress` VARCHAR(10) NULL DEFAULT NULL,\n`custname` VARCHAR(10) NULL DEFAULT NULL,\n`venid` INT(11) NULL DEFAULT NULL,\nPRIMARY KEY (`custid`),\nINDEX (`venid`),\nCONSTRAINT FOREIGN KEY (`venid`) REFERENCES `vendor` (`vendid`)\n)\nCOLLATE='latin1_swedish_ci'\nENGINE=InnoDB;"
},
{
"code": null,
"e": 1743,
"s": 1723,
"text": "Project Structure :"
},
{
"code": null,
"e": 1767,
"s": 1743,
"text": "Required Dependencies :"
},
{
"code": null,
"e": 2213,
"s": 1767,
"text": "<dependencies>\n <!-- Hibernate -->\n <dependency>\n <groupId>org.hibernate</groupId>\n <artifactId>hibernate-core</artifactId>\n <version>4.3.0.Final</version>\n </dependency>\n <!-- MySQL Driver -->\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <version>5.0.5</version>\n </dependency>\n</dependencies>"
},
{
"code": null,
"e": 2238,
"s": 2213,
"text": "Hibernate POJO Classes :"
},
{
"code": null,
"e": 2250,
"s": 2238,
"text": "Vendor.java"
},
{
"code": null,
"e": 3391,
"s": 2250,
"text": "package com.onlinetutorialspoint.hibernate.pojo;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"vendor\")\npublic class Vendor {\n @Id\n @Column(name = \"vendid\")\n private int vendorId;\n\n @Column(name = \"venName\", length = 10)\n private String vendorName;\n\n @OneToMany(targetEntity = Customer.class, cascade = CascadeType.ALL)\n @JoinColumn(name = \"venid\", referencedColumnName = \"vendid\")\n private Set customers;\n\n public int getVendorId() {\n return vendorId;\n }\n\n public void setVendorId(int vendorId) {\n this.vendorId = vendorId;\n }\n\n public String getVendorName() {\n return vendorName;\n }\n\n public void setVendorName(String vendorName) {\n this.vendorName = vendorName;\n }\n\n public Set getCustomers() {\n return customers;\n }\n\n public void setCustomers(Set customers) {\n this.customers = customers;\n }\n\n}"
},
{
"code": null,
"e": 3405,
"s": 3391,
"text": "Customer.java"
},
{
"code": null,
"e": 4405,
"s": 3405,
"text": "package com.onlinetutorialspoint.hibernate.pojo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"customer\")\npublic class Customer {\n @Id\n @Column(name = \"custid\")\n private int customerId;\n\n @Column(name = \"custname\", length = 10)\n private String customerName;\n\n @Column(name = \"custaddress\", length = 10)\n private String customerAddress;\n\n public int getCustomerId() {\n return customerId;\n }\n\n public void setCustomerId(int customerId) {\n this.customerId = customerId;\n }\n\n public String getCustomerName() {\n return customerName;\n }\n\n public void setCustomerName(String customerName) {\n this.customerName = customerName;\n }\n\n public String getCustomerAddress() {\n return customerAddress;\n }\n\n public void setCustomerAddress(String customerAddress) {\n this.customerAddress = customerAddress;\n }\n\n}"
},
{
"code": null,
"e": 4431,
"s": 4405,
"text": "Hibernate Utility Class :"
},
{
"code": null,
"e": 4450,
"s": 4431,
"text": "HibernateUtil.java"
},
{
"code": null,
"e": 5235,
"s": 4450,
"text": "package com.onlinetutorialspoint.util;\n\nimport org.hibernate.SessionFactory;\nimport org.hibernate.boot.registry.StandardServiceRegistryBuilder;\nimport org.hibernate.cfg.Configuration;\n\npublic class HibernateUtil {\n private HibernateUtil() {\n\n }\n\n private static SessionFactory sessionFactory;\n\n public static synchronized SessionFactory getInstnce() {\n\n if (sessionFactory == null) {\n Configuration configuration = new Configuration().configure(\"hibernate.cfg.xml\");\n StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()\n .applySettings(configuration.getProperties());\n sessionFactory = configuration.buildSessionFactory(builder.build());\n }\n return sessionFactory;\n\n }\n}"
},
{
"code": null,
"e": 5289,
"s": 5235,
"text": "Well ! Its completed, Now we can Run our application:"
},
{
"code": null,
"e": 5299,
"s": 5289,
"text": "Main.java"
},
{
"code": null,
"e": 6823,
"s": 5299,
"text": "import java.util.HashSet;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.Transaction;\n\nimport com.onlinetutorialspoint.hibernate.pojo.Customer;\nimport com.onlinetutorialspoint.hibernate.pojo.Vendor;\nimport com.onlinetutorialspoint.util.HibernateUtil;\n\npublic class Main {\n\n public static void main(String a[])\n {\n SessionFactory sessionFactory = HibernateUtil.getInstnce();\n Session session = sessionFactory.openSession(); \n\n Vendor vendor=new Vendor();\n vendor.setVendorId(101);\n vendor.setVendorName(\"IBM\");\n\n Customer customer=new Customer();\n customer.setCustomerId(102);\n customer.setCustomerName(\"NIFY\");\n customer.setCustomerAddress(\"BANG\");\n\n Customer customer2=new Customer();\n customer2.setCustomerId(104);\n customer2.setCustomerName(\"TCS\");\n customer2.setCustomerAddress(\"HYD\");\n\n Customer customer3=new Customer();\n customer3.setCustomerId(105);\n customer3.setCustomerName(\"VERIZON\");\n customer3.setCustomerAddress(\"US\");\n\n Set customers = new HashSet();\n customers.add(customer);\n customers.add(customer2);\n customers.add(customer3);\n\n vendor.setCustomers(customers);\n\n Transaction transaction=session.beginTransaction();\n\n session.save(vendor);\n\n transaction.commit();\n\n session.close();\n sessionFactory.close();\n }\n\n}"
},
{
"code": null,
"e": 6832,
"s": 6823,
"text": "Output :"
},
{
"code": null,
"e": 7776,
"s": 6832,
"text": "Hibernate: select customer_.custid, customer_.custaddress as custaddr2_0_, customer_.custname as custname3_0_ from customer customer_ where customer_.custid=?\nHibernate: select customer_.custid, customer_.custaddress as custaddr2_0_, customer_.custname as custname3_0_ from customer customer_ where customer_.custid=?\nHibernate: select customer_.custid, customer_.custaddress as custaddr2_0_, customer_.custname as custname3_0_ from customer customer_ where customer_.custid=?\nHibernate: insert into vendor (venName, vendid) values (?, ?)\nHibernate: insert into customer (custaddress, custname, custid) values (?, ?, ?)\nHibernate: insert into customer (custaddress, custname, custid) values (?, ?, ?)\nHibernate: insert into customer (custaddress, custname, custid) values (?, ?, ?)\nHibernate: update customer set venid=? where custid=?\nHibernate: update customer set venid=? where custid=?\nHibernate: update customer set venid=? where custid=?"
},
{
"code": null,
"e": 7794,
"s": 7776,
"text": "Database Output :"
},
{
"code": null,
"e": 7811,
"s": 7794,
"text": "Happy Learning:)"
},
{
"code": null,
"e": 7890,
"s": 7811,
"text": "\n\nHibernate One To Many Annotations Example\n\nFile size: 18 KB\nDownloads: 1062\n"
},
{
"code": null,
"e": 8519,
"s": 7890,
"text": "\nMany to One Mapping in Hibernate Example\nHibernate Table per Class strategy Annotations Example\nHibernate One To Many Example (XML Mapping)\nHibernate Right Join Example\nHibernate Left Join Example\nHibernate 4 Example with Annotations Mysql\nCustom Generator Class in Hibernate\nHibernate Filters Example Annotation\nHibernate Named Query with Example\n@Formula Annotation in Hibernate Example\nOne to One Mapping in Hibernate using foreign key (XML)\nBasic Hibernate Example with XML Configuration\nHibernate One to One Mapping using primary key (XML)\nSingleton Hibernate SessionFactory Example\nCalling Stored Procedures in Hibernate\n"
},
{
"code": null,
"e": 8560,
"s": 8519,
"text": "Many to One Mapping in Hibernate Example"
},
{
"code": null,
"e": 8615,
"s": 8560,
"text": "Hibernate Table per Class strategy Annotations Example"
},
{
"code": null,
"e": 8659,
"s": 8615,
"text": "Hibernate One To Many Example (XML Mapping)"
},
{
"code": null,
"e": 8688,
"s": 8659,
"text": "Hibernate Right Join Example"
},
{
"code": null,
"e": 8716,
"s": 8688,
"text": "Hibernate Left Join Example"
},
{
"code": null,
"e": 8759,
"s": 8716,
"text": "Hibernate 4 Example with Annotations Mysql"
},
{
"code": null,
"e": 8795,
"s": 8759,
"text": "Custom Generator Class in Hibernate"
},
{
"code": null,
"e": 8832,
"s": 8795,
"text": "Hibernate Filters Example Annotation"
},
{
"code": null,
"e": 8867,
"s": 8832,
"text": "Hibernate Named Query with Example"
},
{
"code": null,
"e": 8908,
"s": 8867,
"text": "@Formula Annotation in Hibernate Example"
},
{
"code": null,
"e": 8964,
"s": 8908,
"text": "One to One Mapping in Hibernate using foreign key (XML)"
},
{
"code": null,
"e": 9011,
"s": 8964,
"text": "Basic Hibernate Example with XML Configuration"
},
{
"code": null,
"e": 9064,
"s": 9011,
"text": "Hibernate One to One Mapping using primary key (XML)"
},
{
"code": null,
"e": 9107,
"s": 9064,
"text": "Singleton Hibernate SessionFactory Example"
},
{
"code": null,
"e": 9146,
"s": 9107,
"text": "Calling Stored Procedures in Hibernate"
},
{
"code": null,
"e": 9152,
"s": 9150,
"text": "Δ"
},
{
"code": null,
"e": 9178,
"s": 9152,
"text": " Hibernate – Introduction"
},
{
"code": null,
"e": 9202,
"s": 9178,
"text": " Hibernate – Advantages"
},
{
"code": null,
"e": 9234,
"s": 9202,
"text": " Hibernate – Download and Setup"
},
{
"code": null,
"e": 9264,
"s": 9234,
"text": " Hibernate – Sql Dialect list"
},
{
"code": null,
"e": 9294,
"s": 9264,
"text": " Hibernate – Helloworld – XML"
},
{
"code": null,
"e": 9332,
"s": 9294,
"text": " Hibernate – Install Tools in Eclipse"
},
{
"code": null,
"e": 9359,
"s": 9332,
"text": " Hibernate – Object States"
},
{
"code": null,
"e": 9397,
"s": 9359,
"text": " Hibernate – Helloworld – Annotations"
},
{
"code": null,
"e": 9435,
"s": 9397,
"text": " Hibernate – One to One Mapping – XML"
},
{
"code": null,
"e": 9485,
"s": 9435,
"text": " Hibernate – One to One Mapping foreign key – XML"
},
{
"code": null,
"e": 9515,
"s": 9485,
"text": " Hibernate – One To Many -XML"
},
{
"code": null,
"e": 9554,
"s": 9515,
"text": " Hibernate – One To Many – Annotations"
},
{
"code": null,
"e": 9594,
"s": 9554,
"text": " Hibernate – Many to Many Mapping – XML"
},
{
"code": null,
"e": 9625,
"s": 9594,
"text": " Hibernate – Many to One – XML"
},
{
"code": null,
"e": 9660,
"s": 9625,
"text": " Hibernate – Composite Key Mapping"
},
{
"code": null,
"e": 9685,
"s": 9660,
"text": " Hibernate – Named Query"
},
{
"code": null,
"e": 9715,
"s": 9685,
"text": " Hibernate – Native SQL Query"
},
{
"code": null,
"e": 9744,
"s": 9715,
"text": " Hibernate – load() vs get()"
},
{
"code": null,
"e": 9781,
"s": 9744,
"text": " Hibernate Criteria API with Example"
},
{
"code": null,
"e": 9807,
"s": 9781,
"text": " Hibernate – Restrictions"
},
{
"code": null,
"e": 9831,
"s": 9807,
"text": " Hibernate – Projection"
},
{
"code": null,
"e": 9865,
"s": 9831,
"text": " Hibernate – Query Language (HQL)"
},
{
"code": null,
"e": 9899,
"s": 9865,
"text": " Hibernate – Groupby Criteria HQL"
},
{
"code": null,
"e": 9929,
"s": 9899,
"text": " Hibernate – Orderby Criteria"
},
{
"code": null,
"e": 9962,
"s": 9929,
"text": " Hibernate – HQLSelect Operation"
},
{
"code": null,
"e": 9994,
"s": 9962,
"text": " Hibernate – HQL Update, Delete"
},
{
"code": null,
"e": 10020,
"s": 9994,
"text": " Hibernate – Update Query"
},
{
"code": null,
"e": 10049,
"s": 10020,
"text": " Hibernate – Update vs Merge"
},
{
"code": null,
"e": 10073,
"s": 10049,
"text": " Hibernate – Right Join"
},
{
"code": null,
"e": 10096,
"s": 10073,
"text": " Hibernate – Left Join"
},
{
"code": null,
"e": 10120,
"s": 10096,
"text": " Hibernate – Pagination"
},
{
"code": null,
"e": 10151,
"s": 10120,
"text": " Hibernate – Generator Classes"
},
{
"code": null,
"e": 10181,
"s": 10151,
"text": " Hibernate – Custom Generator"
},
{
"code": null,
"e": 10215,
"s": 10181,
"text": " Hibernate – Inheritance Mappings"
},
{
"code": null,
"e": 10244,
"s": 10215,
"text": " Hibernate – Table per Class"
},
{
"code": null,
"e": 10277,
"s": 10244,
"text": " Hibernate – Table per Sub Class"
},
{
"code": null,
"e": 10315,
"s": 10277,
"text": " Hibernate – Table per Concrete Class"
},
{
"code": null,
"e": 10357,
"s": 10315,
"text": " Hibernate – Table per Class Annotations"
},
{
"code": null,
"e": 10388,
"s": 10357,
"text": " Hibernate – Stored Procedures"
},
{
"code": null,
"e": 10421,
"s": 10388,
"text": " Hibernate – @Formula Annotation"
},
{
"code": null,
"e": 10459,
"s": 10421,
"text": " Hibernate – Singleton SessionFactory"
},
{
"code": null,
"e": 10484,
"s": 10459,
"text": " Hibernate – Interceptor"
},
{
"code": null,
"e": 10530,
"s": 10484,
"text": " hbm2ddl.auto Example in Hibernate XML Config"
}
] |
How to combine two lists of same size to make a data frame in R?
|
If we have two lists of same size then we can create a data frame using those lists and this can be easily done with the help of expand.grid function. The expand.grid function create a data frame from all combinations of the provided lists or vectors or factors. For example, if we have two lists defined as List1 and List2 then we can create a data frame using the code expand.grid(List1,List2).
Live Demo
Consider the below lists −
List1<-as.list(sample(LETTERS[1:5],5,replace=TRUE))
List1
[[1]]
[1] "C"
[[2]]
[1] "D"
[[3]]
[1] "E"
[[4]]
[1] "D"
[[5]]
[1] "D"
Live Demo
List2<-as.list(sample(LETTERS[6:10],5,replace=TRUE))
List2
[[1]]
[1] "I"
[[2]]
[1] "J"
[[3]]
[1] "F"
[[4]]
[1] "I"
[[5]]
[1] "F"
Creating a data frame using List1 and List2 −
df1<-expand.grid(List1,List2)
df1
Var1 Var2
1 C I
2 D I
3 E I
4 D I
5 D I
6 C J
7 D J
8 E J
9 D J
10 D J
11 C F
12 D F
13 E F
14 D F
15 D F
16 C I
17 D I
18 E I
19 D I
20 D I
21 C F
22 D F
23 E F
24 D F
25 D F
Let’s have a look at another example −
Live Demo
List3<-as.list(c("India","China","USA","France","Germany"))
List3
[[1]]
[1] "India"
[[2]]
[1] "China"
[[3]]
[1] "USA"
[[4]]
[1] "France"
[[5]]
[1] "Germany"
Live Demo
List4<-as.list(1:4)
List4
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] 4
Creating a data frame using List3 and List4 −
df2<-expand.grid(List3,List4)
df2
Var1 Var2
1 India 1
2 China 1
3 USA 1
4 France 1
5 Germany 1
6 India 2
7 China 2
8 USA 2
9 France 2
10 Germany 2
11 India 3
12 China 3
13 USA 3
14 France 3
15 Germany 3
16 India 4
17 China 4
18 USA 4
19 France 4
20 Germany 4
|
[
{
"code": null,
"e": 1459,
"s": 1062,
"text": "If we have two lists of same size then we can create a data frame using those lists and this can be easily done with the help of expand.grid function. The expand.grid function create a data frame from all combinations of the provided lists or vectors or factors. For example, if we have two lists defined as List1 and List2 then we can create a data frame using the code expand.grid(List1,List2)."
},
{
"code": null,
"e": 1470,
"s": 1459,
"text": " Live Demo"
},
{
"code": null,
"e": 1497,
"s": 1470,
"text": "Consider the below lists −"
},
{
"code": null,
"e": 1555,
"s": 1497,
"text": "List1<-as.list(sample(LETTERS[1:5],5,replace=TRUE))\nList1"
},
{
"code": null,
"e": 1625,
"s": 1555,
"text": "[[1]]\n[1] \"C\"\n[[2]]\n[1] \"D\"\n[[3]]\n[1] \"E\"\n[[4]]\n[1] \"D\"\n[[5]]\n[1] \"D\""
},
{
"code": null,
"e": 1636,
"s": 1625,
"text": " Live Demo"
},
{
"code": null,
"e": 1695,
"s": 1636,
"text": "List2<-as.list(sample(LETTERS[6:10],5,replace=TRUE))\nList2"
},
{
"code": null,
"e": 1765,
"s": 1695,
"text": "[[1]]\n[1] \"I\"\n[[2]]\n[1] \"J\"\n[[3]]\n[1] \"F\"\n[[4]]\n[1] \"I\"\n[[5]]\n[1] \"F\""
},
{
"code": null,
"e": 1811,
"s": 1765,
"text": "Creating a data frame using List1 and List2 −"
},
{
"code": null,
"e": 1845,
"s": 1811,
"text": "df1<-expand.grid(List1,List2)\ndf1"
},
{
"code": null,
"e": 2032,
"s": 1845,
"text": " Var1 Var2\n1 C I\n2 D I\n3 E I\n4 D I\n5 D I\n6 C J\n7 D J\n8 E J\n9 D J\n10 D J\n11 C F\n12 D F\n13 E F\n14 D F\n15 D F\n16 C I\n17 D I\n18 E I\n19 D I\n20 D I\n21 C F\n22 D F\n23 E F\n24 D F\n25 D F"
},
{
"code": null,
"e": 2071,
"s": 2032,
"text": "Let’s have a look at another example −"
},
{
"code": null,
"e": 2082,
"s": 2071,
"text": " Live Demo"
},
{
"code": null,
"e": 2148,
"s": 2082,
"text": "List3<-as.list(c(\"India\",\"China\",\"USA\",\"France\",\"Germany\"))\nList3"
},
{
"code": null,
"e": 2239,
"s": 2148,
"text": "[[1]]\n[1] \"India\"\n[[2]]\n[1] \"China\"\n[[3]]\n[1] \"USA\"\n[[4]]\n[1] \"France\"\n[[5]]\n[1] \"Germany\""
},
{
"code": null,
"e": 2250,
"s": 2239,
"text": " Live Demo"
},
{
"code": null,
"e": 2276,
"s": 2250,
"text": "List4<-as.list(1:4)\nList4"
},
{
"code": null,
"e": 2324,
"s": 2276,
"text": "[[1]]\n[1] 1\n[[2]]\n[1] 2\n[[3]]\n[1] 3\n[[4]]\n[1] 4"
},
{
"code": null,
"e": 2370,
"s": 2324,
"text": "Creating a data frame using List3 and List4 −"
},
{
"code": null,
"e": 2404,
"s": 2370,
"text": "df2<-expand.grid(List3,List4)\ndf2"
},
{
"code": null,
"e": 2629,
"s": 2404,
"text": "Var1 Var2\n1 India 1\n2 China 1\n3 USA 1\n4 France 1\n5 Germany 1\n6 India 2\n7 China 2\n8 USA 2\n9 France 2\n10 Germany 2\n11 India 3\n12 China 3\n13 USA 3\n14 France 3\n15 Germany 3\n16 India 4\n17 China 4\n18 USA 4\n19 France 4\n20 Germany 4"
}
] |
C++ Program to Display Factors of a Number
|
Factors are those numbers that are multiplied to get a number.
For example: 5 and 3 are factors of 15 as 5*3=15. Similarly other factors of 15 are 1 and 15 as 15*1=15.
The program to display the factors of a number are given as follows.
Live Demo
#include<iostream>
using namespace std;
int main() {
int num = 20, i;
cout << "The factors of " << num << " are : ";
for(i=1; i <= num; i++) {
if (num % i == 0)
cout << i << " ";
}
return 0;
}
The factors of 20 are : 1 2 4 5 10 20
In the above program, the for loop runs from 1 to num. The number is divided by i and if the remainder is 0, then i is a factor of num and is printed.
for(i=1; i <= num; i++) {
if (num % i == 0)
cout << i << " ";
}
The same program given above can be created using a function that calculates all the factors of the number. This is given as follows −
Live Demo
#include<iostream>
using namespace std;
void factors(int num) {
int i;
for(i=1; i <= num; i++) {
if (num % i == 0)
cout << i << " ";
}
}
int main() {
int num = 25;
cout << "The factors of " << num << " are : ";
factors(num);
return 0;
}
The factors of 25 are : 1 5 25
In the above program, the function factors() finds all the factors of “num”. It is called from the main() function with one parameter i.e. “num”.
factors(num);
The for loop in the function factors() runs from 1 to num. The number is divided by i and if the remainder is 0, then i is a factor of “num” and is printed.
for(i=1; i <= num; i++) {
if (num % i == 0)
cout << i << " ";
}
|
[
{
"code": null,
"e": 1125,
"s": 1062,
"text": "Factors are those numbers that are multiplied to get a number."
},
{
"code": null,
"e": 1230,
"s": 1125,
"text": "For example: 5 and 3 are factors of 15 as 5*3=15. Similarly other factors of 15 are 1 and 15 as 15*1=15."
},
{
"code": null,
"e": 1299,
"s": 1230,
"text": "The program to display the factors of a number are given as follows."
},
{
"code": null,
"e": 1310,
"s": 1299,
"text": " Live Demo"
},
{
"code": null,
"e": 1530,
"s": 1310,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int num = 20, i;\n cout << \"The factors of \" << num << \" are : \";\n for(i=1; i <= num; i++) {\n if (num % i == 0)\n cout << i << \" \";\n }\n return 0;\n}"
},
{
"code": null,
"e": 1568,
"s": 1530,
"text": "The factors of 20 are : 1 2 4 5 10 20"
},
{
"code": null,
"e": 1719,
"s": 1568,
"text": "In the above program, the for loop runs from 1 to num. The number is divided by i and if the remainder is 0, then i is a factor of num and is printed."
},
{
"code": null,
"e": 1789,
"s": 1719,
"text": "for(i=1; i <= num; i++) {\n if (num % i == 0)\n cout << i << \" \";\n}"
},
{
"code": null,
"e": 1924,
"s": 1789,
"text": "The same program given above can be created using a function that calculates all the factors of the number. This is given as follows −"
},
{
"code": null,
"e": 1935,
"s": 1924,
"text": " Live Demo"
},
{
"code": null,
"e": 2205,
"s": 1935,
"text": "#include<iostream>\nusing namespace std;\nvoid factors(int num) {\n int i;\n for(i=1; i <= num; i++) {\n if (num % i == 0)\n cout << i << \" \";\n }\n}\nint main() {\n int num = 25;\n cout << \"The factors of \" << num << \" are : \";\n factors(num);\n return 0;\n}"
},
{
"code": null,
"e": 2236,
"s": 2205,
"text": "The factors of 25 are : 1 5 25"
},
{
"code": null,
"e": 2382,
"s": 2236,
"text": "In the above program, the function factors() finds all the factors of “num”. It is called from the main() function with one parameter i.e. “num”."
},
{
"code": null,
"e": 2396,
"s": 2382,
"text": "factors(num);"
},
{
"code": null,
"e": 2553,
"s": 2396,
"text": "The for loop in the function factors() runs from 1 to num. The number is divided by i and if the remainder is 0, then i is a factor of “num” and is printed."
},
{
"code": null,
"e": 2623,
"s": 2553,
"text": "for(i=1; i <= num; i++) {\n if (num % i == 0)\n cout << i << \" \";\n}"
}
] |
Data Analysis and Visualization with Python | Set 2 - GeeksforGeeks
|
09 Sep, 2018
Prerequisites : NumPy in Python, Data Analysis Visualization with Python | Set 1
1. Storing DataFrame in CSV Format :
Pandas provide to.csv('filename', index = "False|True") function to write DataFrame into a CSV file. Here filename is the name of the CSV file that you want to create and index tells that index (if Default) of DataFrame should be overwritten or not. If we set index = False then the index is not overwritten. By Default value of index is TRUE then index is overwritten.
Example :
import pandas as pd # assigning three series to s1, s2, s3s1 = pd.Series([0, 4, 8])s2 = pd.Series([1, 5, 9])s3 = pd.Series([2, 6, 10]) # taking index and column valuesdframe = pd.DataFrame([s1, s2, s3]) # assign column namedframe.columns =['Geeks', 'For', 'Geeks'] # write data to csv filedframe.to_csv('geeksforgeeks.csv', index = False) dframe.to_csv('geeksforgeeks1.csv', index = True)
Output :
geeksforgeeks1.csv
geeksforgeeks2.csv
2. Handling Missing Data
The Data Analysis Phase also comprises of the ability to handle the missing data from our dataset, and not so surprisingly Pandas live up to that expectation as well. This is where dropna and/or fillna methods comes into the play. While dealing with the missing data, you as a Data Analyst are either supposed to drop the column containing the NaN values (dropna method) or fill in the missing data with mean or mode of the whole column entry (fillna method), this decision is of great significance and depends upon the data and the affect would create in our results.
Drop the missing Data :Consider this is the DataFrame generated by below code :import pandas as pd # Create a DataFramedframe = pd.DataFrame({'Geeks': [23, 24, 22], 'For': [10, 12, np.nan], 'geeks': [0, np.nan, np.nan]}, columns =['Geeks', 'For', 'geeks']) # This will remove all the# rows with NAN values # If axis is not defined then# it is along rows i.e. axis = 0dframe.dropna(inplace = True)print(dframe) # if axis is equal to 1dframe.dropna(axis = 1, inplace = True) print(dframe)Output :axis=0
axis=1
import pandas as pd # Create a DataFramedframe = pd.DataFrame({'Geeks': [23, 24, 22], 'For': [10, 12, np.nan], 'geeks': [0, np.nan, np.nan]}, columns =['Geeks', 'For', 'geeks']) # This will remove all the# rows with NAN values # If axis is not defined then# it is along rows i.e. axis = 0dframe.dropna(inplace = True)print(dframe) # if axis is equal to 1dframe.dropna(axis = 1, inplace = True) print(dframe)
Output :
axis=0
axis=1
Fill the missing values :Now, to replace any NaN value with mean or mode of the data, fillna is used, which could replace all the NaN values from a particular column or even in whole DataFrame as per the requirement.import numpy as npimport pandas as pd # Create a DataFramedframe = pd.DataFrame({'Geeks': [23, 24, 22], 'For': [10, 12, np.nan], 'geeks': [0, np.nan, np.nan]}, columns = ['Geeks', 'For', 'geeks']) # Use fillna of complete Dataframe # value function will be applied on every columndframe.fillna(value = dframe.mean(), inplace = True)print(dframe) # filling value of one columndframe['For'].fillna(value = dframe['For'].mean(), inplace = True)print(dframe)Output :
import numpy as npimport pandas as pd # Create a DataFramedframe = pd.DataFrame({'Geeks': [23, 24, 22], 'For': [10, 12, np.nan], 'geeks': [0, np.nan, np.nan]}, columns = ['Geeks', 'For', 'geeks']) # Use fillna of complete Dataframe # value function will be applied on every columndframe.fillna(value = dframe.mean(), inplace = True)print(dframe) # filling value of one columndframe['For'].fillna(value = dframe['For'].mean(), inplace = True)print(dframe)
Output :
3. Groupby Method (Aggregation) :
The groupby method allows us to group together the data based off any row or column, thus we can further apply the aggregate functions to analyze our data. Group series using mapper (dict or key function, apply given function to group, return result as series) or by a series of columns.
Consider this is the DataFrame generated by below code :
import pandas as pdimport numpy as np # create DataFramedframe = pd.DataFrame({'Geeks': [23, 24, 22, 22, 23, 24], 'For': [10, 12, 13, 14, 15, 16], 'geeks': [122, 142, 112, 122, 114, 112]}, columns = ['Geeks', 'For', 'geeks']) # Apply groupby and aggregate function# max to find max value of column # "For" and column "geeks" for every# different value of column "Geeks". print(dframe.groupby(['Geeks']).max())
Output :
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 24601,
"s": 24573,
"text": "\n09 Sep, 2018"
},
{
"code": null,
"e": 24682,
"s": 24601,
"text": "Prerequisites : NumPy in Python, Data Analysis Visualization with Python | Set 1"
},
{
"code": null,
"e": 24719,
"s": 24682,
"text": "1. Storing DataFrame in CSV Format :"
},
{
"code": null,
"e": 25089,
"s": 24719,
"text": "Pandas provide to.csv('filename', index = \"False|True\") function to write DataFrame into a CSV file. Here filename is the name of the CSV file that you want to create and index tells that index (if Default) of DataFrame should be overwritten or not. If we set index = False then the index is not overwritten. By Default value of index is TRUE then index is overwritten."
},
{
"code": null,
"e": 25099,
"s": 25089,
"text": "Example :"
},
{
"code": "import pandas as pd # assigning three series to s1, s2, s3s1 = pd.Series([0, 4, 8])s2 = pd.Series([1, 5, 9])s3 = pd.Series([2, 6, 10]) # taking index and column valuesdframe = pd.DataFrame([s1, s2, s3]) # assign column namedframe.columns =['Geeks', 'For', 'Geeks'] # write data to csv filedframe.to_csv('geeksforgeeks.csv', index = False) dframe.to_csv('geeksforgeeks1.csv', index = True)",
"e": 25493,
"s": 25099,
"text": null
},
{
"code": null,
"e": 25502,
"s": 25493,
"text": "Output :"
},
{
"code": null,
"e": 25544,
"s": 25502,
"text": "geeksforgeeks1.csv\n\n\ngeeksforgeeks2.csv\n\n"
},
{
"code": null,
"e": 25571,
"s": 25546,
"text": "2. Handling Missing Data"
},
{
"code": null,
"e": 26140,
"s": 25571,
"text": "The Data Analysis Phase also comprises of the ability to handle the missing data from our dataset, and not so surprisingly Pandas live up to that expectation as well. This is where dropna and/or fillna methods comes into the play. While dealing with the missing data, you as a Data Analyst are either supposed to drop the column containing the NaN values (dropna method) or fill in the missing data with mean or mode of the whole column entry (fillna method), this decision is of great significance and depends upon the data and the affect would create in our results."
},
{
"code": null,
"e": 26725,
"s": 26140,
"text": "Drop the missing Data :Consider this is the DataFrame generated by below code :import pandas as pd # Create a DataFramedframe = pd.DataFrame({'Geeks': [23, 24, 22], 'For': [10, 12, np.nan], 'geeks': [0, np.nan, np.nan]}, columns =['Geeks', 'For', 'geeks']) # This will remove all the# rows with NAN values # If axis is not defined then# it is along rows i.e. axis = 0dframe.dropna(inplace = True)print(dframe) # if axis is equal to 1dframe.dropna(axis = 1, inplace = True) print(dframe)Output :axis=0\n \n\naxis=1\n "
},
{
"code": "import pandas as pd # Create a DataFramedframe = pd.DataFrame({'Geeks': [23, 24, 22], 'For': [10, 12, np.nan], 'geeks': [0, np.nan, np.nan]}, columns =['Geeks', 'For', 'geeks']) # This will remove all the# rows with NAN values # If axis is not defined then# it is along rows i.e. axis = 0dframe.dropna(inplace = True)print(dframe) # if axis is equal to 1dframe.dropna(axis = 1, inplace = True) print(dframe)",
"e": 27205,
"s": 26725,
"text": null
},
{
"code": null,
"e": 27214,
"s": 27205,
"text": "Output :"
},
{
"code": null,
"e": 27232,
"s": 27214,
"text": "axis=0\n \n\naxis=1\n"
},
{
"code": null,
"e": 28023,
"s": 27234,
"text": "Fill the missing values :Now, to replace any NaN value with mean or mode of the data, fillna is used, which could replace all the NaN values from a particular column or even in whole DataFrame as per the requirement.import numpy as npimport pandas as pd # Create a DataFramedframe = pd.DataFrame({'Geeks': [23, 24, 22], 'For': [10, 12, np.nan], 'geeks': [0, np.nan, np.nan]}, columns = ['Geeks', 'For', 'geeks']) # Use fillna of complete Dataframe # value function will be applied on every columndframe.fillna(value = dframe.mean(), inplace = True)print(dframe) # filling value of one columndframe['For'].fillna(value = dframe['For'].mean(), inplace = True)print(dframe)Output :"
},
{
"code": "import numpy as npimport pandas as pd # Create a DataFramedframe = pd.DataFrame({'Geeks': [23, 24, 22], 'For': [10, 12, np.nan], 'geeks': [0, np.nan, np.nan]}, columns = ['Geeks', 'For', 'geeks']) # Use fillna of complete Dataframe # value function will be applied on every columndframe.fillna(value = dframe.mean(), inplace = True)print(dframe) # filling value of one columndframe['For'].fillna(value = dframe['For'].mean(), inplace = True)print(dframe)",
"e": 28588,
"s": 28023,
"text": null
},
{
"code": null,
"e": 28597,
"s": 28588,
"text": "Output :"
},
{
"code": null,
"e": 28633,
"s": 28599,
"text": "3. Groupby Method (Aggregation) :"
},
{
"code": null,
"e": 28921,
"s": 28633,
"text": "The groupby method allows us to group together the data based off any row or column, thus we can further apply the aggregate functions to analyze our data. Group series using mapper (dict or key function, apply given function to group, return result as series) or by a series of columns."
},
{
"code": null,
"e": 28978,
"s": 28921,
"text": "Consider this is the DataFrame generated by below code :"
},
{
"code": "import pandas as pdimport numpy as np # create DataFramedframe = pd.DataFrame({'Geeks': [23, 24, 22, 22, 23, 24], 'For': [10, 12, 13, 14, 15, 16], 'geeks': [122, 142, 112, 122, 114, 112]}, columns = ['Geeks', 'For', 'geeks']) # Apply groupby and aggregate function# max to find max value of column # \"For\" and column \"geeks\" for every# different value of column \"Geeks\". print(dframe.groupby(['Geeks']).max())",
"e": 29464,
"s": 28978,
"text": null
},
{
"code": null,
"e": 29473,
"s": 29464,
"text": "Output :"
},
{
"code": null,
"e": 29482,
"s": 29475,
"text": "Python"
},
{
"code": null,
"e": 29580,
"s": 29482,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29589,
"s": 29580,
"text": "Comments"
},
{
"code": null,
"e": 29602,
"s": 29589,
"text": "Old Comments"
},
{
"code": null,
"e": 29620,
"s": 29602,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29655,
"s": 29620,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29677,
"s": 29655,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29709,
"s": 29677,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29739,
"s": 29709,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29781,
"s": 29739,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29824,
"s": 29781,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29850,
"s": 29824,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29894,
"s": 29850,
"text": "Reading and Writing to text files in Python"
}
] |
A Hello World App using Flutter - GeeksforGeeks
|
24 Nov, 2020
Flutter is an app SDK for building high-performance, high-fidelity apps for iOS, Android, Web(beta), and desktop(technical preview) from a single codebase written in Dart Language. In this article, I will provide line by line explanation on how to build a simple Hello World App using Flutter.
In Flutter everything is a Widget and using predefined widgets one can create user-defined widgets just like using int, float, double we can create user-defined data type. In Flutter there are three types of widgets
Stateless Widget
Stateful Widget
Inherited Widget
In this article, we will use Stateless Widget, Material App, Center and Text Widget
In Flutter Stateless Widget are the widgets that can not change their state, that is in Stateless Widget there is a method(function) called as build which is responsible for drawing components on the screen is called only once. To redraw a stateless widget one has to create a new instance of the stateless widget.
It is also a widget provided by Flutter Team, which follows Google Material Design Scheme, MaterialApp is a class which has various named arguments like home: in which we pass the widget that has to be displayed on Home Screen of an App. To read more about MaterialApp check out Flutter Documentation
Center is also a predefined widget by Flutter Team, which takes another widget in its child argument. Using Center Widget as the name suggest it will display Widget in its child argument in Center
Dart
Center( child: Widget( ),),
The text widget is also predefined by Flutter Team, which is used to display text. Let us now build a Hello World App using Flutter
Dart
import 'package:flutter/material.dart'; void main() { runApp(GeeksForGeeks());} class GeeksForGeeks extends StatelessWidget{ Widget build(BuildContext context){ return MaterialApp( home: Center( child: Text('Hello World') ), ); }}
import 'package:flutter/material.dart';
Here we are importing the package which has a definition for Stateless Widget, Center, Text, Material App, and many more. It is like #include<iostream> in C++ program
GeeksForGeeks: It is a user Defined class which inherits Stateless Widget, that is all the property of Stateless Widget is in GeeksForGeeks
Build: It is a method which is responsible for drawing components on the Screen it takes a BuildContext as an argument which has information about which widget has to be displayed and in which order it has to be painted on the screen.
Output:
It does not look like a Modern App, Let us add material design!
Dart
import 'package:flutter/material.dart'; void main() { runApp(GeeksForGeeks());} class GeeksForGeeks extends StatelessWidget{ Widget build(BuildContext context){ // Material App return MaterialApp( // Scaffold Widget home: Scaffold( appBar: AppBar( // AppBar takes a Text Widget // in it's title parameter title: Text('GFG'), ), body: Center( child: Text('Hello World') ), ) ); }}
Output:
Explanation: In the first line we have imported the material design library which will be used in this app. Then we have our main function. This is the point where the code execution will start. Then we have the class ‘GeeksForGeeks’ which is extending the StatelessWidget. This is basically the main widget tree of our ‘hello world’ app. All this is followed by the build method, which is returning a MaterialApp widget. Then we have employed home property of the MaterialApp, which in turn is holding the Scaffold widget. The Scaffold widget is containing the whole screen of the app. We have used the appBar property which is taking the AppBar widget as the object. And in turn the AppBar widget is holding ‘GFG’ as the title. Then we have the body, which is again the property of the MaterialApp. Center is the object of the body and it’s child is Text widget which reads ‘Hello World’.
ankit_kumar_
Flutter
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Listview.builder in Flutter
Flutter - DropDownButton Widget
Flutter - Asset Image
Splash Screen in Flutter
Flutter - Custom Bottom Navigation Bar
Dart - Standard Input Output
Getter and Setter Methods in Dart
Flutter - Checkbox Widget
Flutter - Row and Column Widgets
How to Append or Concatenate Strings in Dart?
|
[
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n24 Nov, 2020"
},
{
"code": null,
"e": 25842,
"s": 25547,
"text": "Flutter is an app SDK for building high-performance, high-fidelity apps for iOS, Android, Web(beta), and desktop(technical preview) from a single codebase written in Dart Language. In this article, I will provide line by line explanation on how to build a simple Hello World App using Flutter. "
},
{
"code": null,
"e": 26058,
"s": 25842,
"text": "In Flutter everything is a Widget and using predefined widgets one can create user-defined widgets just like using int, float, double we can create user-defined data type. In Flutter there are three types of widgets"
},
{
"code": null,
"e": 26075,
"s": 26058,
"text": "Stateless Widget"
},
{
"code": null,
"e": 26091,
"s": 26075,
"text": "Stateful Widget"
},
{
"code": null,
"e": 26108,
"s": 26091,
"text": "Inherited Widget"
},
{
"code": null,
"e": 26192,
"s": 26108,
"text": "In this article, we will use Stateless Widget, Material App, Center and Text Widget"
},
{
"code": null,
"e": 26508,
"s": 26192,
"text": "In Flutter Stateless Widget are the widgets that can not change their state, that is in Stateless Widget there is a method(function) called as build which is responsible for drawing components on the screen is called only once. To redraw a stateless widget one has to create a new instance of the stateless widget. "
},
{
"code": null,
"e": 26811,
"s": 26508,
"text": "It is also a widget provided by Flutter Team, which follows Google Material Design Scheme, MaterialApp is a class which has various named arguments like home: in which we pass the widget that has to be displayed on Home Screen of an App. To read more about MaterialApp check out Flutter Documentation "
},
{
"code": null,
"e": 27009,
"s": 26811,
"text": "Center is also a predefined widget by Flutter Team, which takes another widget in its child argument. Using Center Widget as the name suggest it will display Widget in its child argument in Center "
},
{
"code": null,
"e": 27014,
"s": 27009,
"text": "Dart"
},
{
"code": "Center( child: Widget( ),),",
"e": 27048,
"s": 27014,
"text": null
},
{
"code": null,
"e": 27180,
"s": 27048,
"text": "The text widget is also predefined by Flutter Team, which is used to display text. Let us now build a Hello World App using Flutter"
},
{
"code": null,
"e": 27185,
"s": 27180,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(GeeksForGeeks());} class GeeksForGeeks extends StatelessWidget{ Widget build(BuildContext context){ return MaterialApp( home: Center( child: Text('Hello World') ), ); }}",
"e": 27442,
"s": 27185,
"text": null
},
{
"code": null,
"e": 27486,
"s": 27442,
"text": "import 'package:flutter/material.dart';\n\n\n\n"
},
{
"code": null,
"e": 27653,
"s": 27486,
"text": "Here we are importing the package which has a definition for Stateless Widget, Center, Text, Material App, and many more. It is like #include<iostream> in C++ program"
},
{
"code": null,
"e": 27793,
"s": 27653,
"text": "GeeksForGeeks: It is a user Defined class which inherits Stateless Widget, that is all the property of Stateless Widget is in GeeksForGeeks"
},
{
"code": null,
"e": 28029,
"s": 27793,
"text": "Build: It is a method which is responsible for drawing components on the Screen it takes a BuildContext as an argument which has information about which widget has to be displayed and in which order it has to be painted on the screen. "
},
{
"code": null,
"e": 28037,
"s": 28029,
"text": "Output:"
},
{
"code": null,
"e": 28101,
"s": 28037,
"text": "It does not look like a Modern App, Let us add material design!"
},
{
"code": null,
"e": 28106,
"s": 28101,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(GeeksForGeeks());} class GeeksForGeeks extends StatelessWidget{ Widget build(BuildContext context){ // Material App return MaterialApp( // Scaffold Widget home: Scaffold( appBar: AppBar( // AppBar takes a Text Widget // in it's title parameter title: Text('GFG'), ), body: Center( child: Text('Hello World') ), ) ); }}",
"e": 28601,
"s": 28106,
"text": null
},
{
"code": null,
"e": 28609,
"s": 28601,
"text": "Output:"
},
{
"code": null,
"e": 29502,
"s": 28609,
"text": "Explanation: In the first line we have imported the material design library which will be used in this app. Then we have our main function. This is the point where the code execution will start. Then we have the class ‘GeeksForGeeks’ which is extending the StatelessWidget. This is basically the main widget tree of our ‘hello world’ app. All this is followed by the build method, which is returning a MaterialApp widget. Then we have employed home property of the MaterialApp, which in turn is holding the Scaffold widget. The Scaffold widget is containing the whole screen of the app. We have used the appBar property which is taking the AppBar widget as the object. And in turn the AppBar widget is holding ‘GFG’ as the title. Then we have the body, which is again the property of the MaterialApp. Center is the object of the body and it’s child is Text widget which reads ‘Hello World’."
},
{
"code": null,
"e": 29515,
"s": 29502,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 29523,
"s": 29515,
"text": "Flutter"
},
{
"code": null,
"e": 29528,
"s": 29523,
"text": "Dart"
},
{
"code": null,
"e": 29626,
"s": 29528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29635,
"s": 29626,
"text": "Comments"
},
{
"code": null,
"e": 29648,
"s": 29635,
"text": "Old Comments"
},
{
"code": null,
"e": 29676,
"s": 29648,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 29708,
"s": 29676,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 29730,
"s": 29708,
"text": "Flutter - Asset Image"
},
{
"code": null,
"e": 29755,
"s": 29730,
"text": "Splash Screen in Flutter"
},
{
"code": null,
"e": 29794,
"s": 29755,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29823,
"s": 29794,
"text": "Dart - Standard Input Output"
},
{
"code": null,
"e": 29857,
"s": 29823,
"text": "Getter and Setter Methods in Dart"
},
{
"code": null,
"e": 29883,
"s": 29857,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 29916,
"s": 29883,
"text": "Flutter - Row and Column Widgets"
}
] |
Optimizing Hyperparameters the right Way | by Richard Michael | Towards Data Science
|
In this post, we will build a machine learning pipeline using multiple optimizers and use the power of Bayesian Optimization to arrive at the most optimal configuration for all our parameters. All we need is the sklearn Pipeline and Skopt.You can use your favorite ML models, as long as they have a sklearn wrapper (looking at you XGBoost or NGBoost).
The critical point for finding the best models that can solve a problem are not just the models. We need to find the optimal parameters to make our model work optimally, given the dataset. This is called finding or searching hyperparameters.For example, we would like to implement a Random Forest in practice and its documentation states:
class sklearn.ensemble.RandomForestClassifier(n_estimators=100, *, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, ...
All of those parameters can be explored. This can include all possible number of estimators ( n_estimators ) in the forest from 1 to 10.000, you may try to split using {“gini”, “entropy”}, or the maximum depth of your trees is another integer and there are many, many more options. Each of those parameters can influence your model‘s performance and worst of all most of the time you do not know the right configuration when you’re starting out with a new problem-set.
The brute-force way to find the optimal configuration is to perform a grid-search for example using sklearn’s GridSearchCV. This means that you try out all possible combinations of parameters on your model.On the bright side, you might find the desired values. The problem is that the runtime is horrible and over all grid-searching does not scale well. For every new parameter you want to try out, you will test all of the other previously specified parameters also.This approach is very uninformative and feels like being blind in our problem-space and testing out all the possible buttons and configurations. In contrast to this is our understanding of hyperparameters:
We have the intuition that some picks of parameters are more informative than others.
Some parameters just make more sense and once we know that some ranges of parameters work better than others. Further once we know what direction works, we don’t have to explore all values in the wrong domain.
We don’t need to test for all parameters — especially not those of which we know that they are far off.One step in the right direction is randomized search like RandomizedSearchCV, where we pick the parameters randomly while moving in the right direction.
Our tool of choice is BayesSearchCV. This approach uses stepwise Bayesian Optimization to explore the most promising hyperparameters in the problem-space.Very briefly, Bayesian Optimization finds the minimum to an objective function in large problem-spaces and is very applicable to continuous values. To do this it uses Gaussian Process regression on the objective function under the hood. A thorough mathematical introduction can be found in [2]. In our case the objective function is to arrive at the best model output given the model-parameters that we specify.The Bayesian Optimization approach gives the benefit that we can give a much larger range of possible values, since over time we automatically explore the most promising regions and discard the not so promising ones.Plain grid-search would need ages to stupidly explore all possible values.Since we move much more effectively, we can allow for a much larger playing field. Let’s look at an example.
Today we use the diabetes dataset from sklearn for ease of use.This saves us the trouble of loading and cleaning our data and the features are already neatly encoded.
We have a set of encoded columns from age, sex, bmi, blood-pressure and serum values, numerically encoded. Our target value is a measure of the disease progression.We can see some interactions on the s-columns (blood-serum values), indicating some level of correlation.
To build our pipeline we first split our dataset into training and testing respectively in an 80:20 split.
X_train, X_test, y_train, y_test = train_test_split(diabetes_df.drop(columns="target"), diabetes_df.target, test_size=0.2, random_state=21)
We need three elements to build a pipeline: (1) the models to be optimized, (2) the sklearn Pipeline object, and (3) the skopt optimization procedure.
First, we choose two boosting models: AdaBoost and GradientBoosted regressors and for each we define a search space over crucial hyperparameters. Any other regressor from the depth of the sklearn library would do, but boosting might win you the next hackathon (...its 2015 isn’t it?)The search-space is a dictionary with the key-value pair := { ‘model__parameter‘ : skopt.space.Object}. For each parameter we set a space from the skopt library in the range that we want. Categorical values are also included by passing them as a list of strings (see Categorical below):
ada_search = { 'model': [AdaBoostRegressor()], 'model__learning_rate': Real(0.005, 0.9, prior="log-uniform"), 'model__n_estimators': Integer(1, 1000), 'model__loss': Categorical(['linear', 'square', 'exponential'])}gb_search = { 'model': [GradientBoostingRegressor()], 'model__learning_rate': Real(0.005, 0.9, prior="log-uniform"), 'model__n_estimators': Integer(1, 1000), 'model__loss': Categorical(['ls', 'lad', 'quantile'])}
Second, we select over which regression model to pick through another model, this is our pipeline element, where both optimizers (adaboost and gradientboost) come together for selection:
pipe = Pipeline([('model', GradientBoostingRegressor())])
Third, we optimize over our search-space. For this we invoke the BayesSearchCV. We also specify how the optimizer should call our search-space. In our case that is 100 invocations. Then we fit the pipeline with a simple skopt .fit() command:
opt = BayesSearchCV( pipe, [(ada_search, 100), (gb_search, 100)], cv=5)opt.fit(X_train, y_train)
After the fitting is done, we can then ask for the optimal found parameters. This includes using the score function on the unseen test-data.
We can see the validation and test-score as well as the parameters of the best fit. The model with the best results is the AdaBoost model with a linear loss and 259 estimators at a learning-rate of 0.064. Neat.From the output we can also see that the optimizer uses a GP for optimization under the hood:
For illustrative purposes we can also call GP minimization specifically — we’ll use the AdaBoost regressor for that — only focusing on a numerical hyperparameter space.
ada = AdaBoostRegressor(random_state=21)# numerical spacespace = [Real(0.005, 0.9, "log-uniform", name='learning_rate'), Integer(1, 1000, name="n_estimators")]
The major change here is that we have to define an objective function over which we have to optimize. In order to see how the model performs over the parameter-space we use the named_args decorator.
@use_named_args(space)def objective(**params): ada.set_params(**params) return -np.mean(cross_val_score(ada, X_train, y_train, cv=5, n_jobs=-1, scoring="neg_mean_absolute_error"))
Therefore our optimization is the negative mean score that we get from the cross-validated fit while using the negative mean absolute error. Other scoring functions might suit you better.We then use GP minimization to fit the most optimal parameters for our regressor.gp_minimize(objective, space, n_calls=100, random_state=21)
Using GP optimization directly allows us to plot convergence over the minimization process.
We can see that the min in the function value has already been reached after around 40 iterations.The last excellent feature is visualizing the explored problem space. Since we used only numerical input at this point, we can then evaluate the problem space by plotting it using skopt, like so:
From the figure above we can see that a lot of exploration was done on the lower end of our learning-rate spectrum, and the peaks of the tried and tested estimator number was 200 and over 800.The scatterplot paints a picture of how difficult the problem space is that we are trying to optimize — with the minimum marked with a red star. Each GP-minimize run uncovers a function value, given the parameter that it has as input. Though we have reached convergence not a lot of values are evident in the region around the minimum and increasing the number of evaluations can be considered.
Now that we have the best model given our parameter space we can implement that model accordingly and go into its specific analysis.
We have shown that we can explore a vast space of possible model-parameters in an efficient way, saving both time and computational resources. We do this by formulating the search for hyperparameters as an objective function for which we find the optimal values using Bayesian Optimization. There is no need to test useless parameters anymore by trying out every single one of them.As you have seen skopt is a library that offers a lot in the realm of optimizations and I encourage you to use them in your daily ML engineering.
Happy Exploring!
The complete code can be found in a Notebook here:
github.com
Marc Claesen, Bart De Moor. Hyperparameter Search in Machine Learning. 2015 on arXiv.Peter I. Frazier. A Tutorial on Bayesian Optimization. 2018 on arXiv.scikit-optimize contributors (BSD License). Scikit-learn hyperparameter search wrapper.
Marc Claesen, Bart De Moor. Hyperparameter Search in Machine Learning. 2015 on arXiv.
Peter I. Frazier. A Tutorial on Bayesian Optimization. 2018 on arXiv.
scikit-optimize contributors (BSD License). Scikit-learn hyperparameter search wrapper.
|
[
{
"code": null,
"e": 524,
"s": 172,
"text": "In this post, we will build a machine learning pipeline using multiple optimizers and use the power of Bayesian Optimization to arrive at the most optimal configuration for all our parameters. All we need is the sklearn Pipeline and Skopt.You can use your favorite ML models, as long as they have a sklearn wrapper (looking at you XGBoost or NGBoost)."
},
{
"code": null,
"e": 863,
"s": 524,
"text": "The critical point for finding the best models that can solve a problem are not just the models. We need to find the optimal parameters to make our model work optimally, given the dataset. This is called finding or searching hyperparameters.For example, we would like to implement a Random Forest in practice and its documentation states:"
},
{
"code": null,
"e": 1081,
"s": 863,
"text": "class sklearn.ensemble.RandomForestClassifier(n_estimators=100, *, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, ..."
},
{
"code": null,
"e": 1550,
"s": 1081,
"text": "All of those parameters can be explored. This can include all possible number of estimators ( n_estimators ) in the forest from 1 to 10.000, you may try to split using {“gini”, “entropy”}, or the maximum depth of your trees is another integer and there are many, many more options. Each of those parameters can influence your model‘s performance and worst of all most of the time you do not know the right configuration when you’re starting out with a new problem-set."
},
{
"code": null,
"e": 2223,
"s": 1550,
"text": "The brute-force way to find the optimal configuration is to perform a grid-search for example using sklearn’s GridSearchCV. This means that you try out all possible combinations of parameters on your model.On the bright side, you might find the desired values. The problem is that the runtime is horrible and over all grid-searching does not scale well. For every new parameter you want to try out, you will test all of the other previously specified parameters also.This approach is very uninformative and feels like being blind in our problem-space and testing out all the possible buttons and configurations. In contrast to this is our understanding of hyperparameters:"
},
{
"code": null,
"e": 2309,
"s": 2223,
"text": "We have the intuition that some picks of parameters are more informative than others."
},
{
"code": null,
"e": 2519,
"s": 2309,
"text": "Some parameters just make more sense and once we know that some ranges of parameters work better than others. Further once we know what direction works, we don’t have to explore all values in the wrong domain."
},
{
"code": null,
"e": 2775,
"s": 2519,
"text": "We don’t need to test for all parameters — especially not those of which we know that they are far off.One step in the right direction is randomized search like RandomizedSearchCV, where we pick the parameters randomly while moving in the right direction."
},
{
"code": null,
"e": 3739,
"s": 2775,
"text": "Our tool of choice is BayesSearchCV. This approach uses stepwise Bayesian Optimization to explore the most promising hyperparameters in the problem-space.Very briefly, Bayesian Optimization finds the minimum to an objective function in large problem-spaces and is very applicable to continuous values. To do this it uses Gaussian Process regression on the objective function under the hood. A thorough mathematical introduction can be found in [2]. In our case the objective function is to arrive at the best model output given the model-parameters that we specify.The Bayesian Optimization approach gives the benefit that we can give a much larger range of possible values, since over time we automatically explore the most promising regions and discard the not so promising ones.Plain grid-search would need ages to stupidly explore all possible values.Since we move much more effectively, we can allow for a much larger playing field. Let’s look at an example."
},
{
"code": null,
"e": 3906,
"s": 3739,
"text": "Today we use the diabetes dataset from sklearn for ease of use.This saves us the trouble of loading and cleaning our data and the features are already neatly encoded."
},
{
"code": null,
"e": 4176,
"s": 3906,
"text": "We have a set of encoded columns from age, sex, bmi, blood-pressure and serum values, numerically encoded. Our target value is a measure of the disease progression.We can see some interactions on the s-columns (blood-serum values), indicating some level of correlation."
},
{
"code": null,
"e": 4283,
"s": 4176,
"text": "To build our pipeline we first split our dataset into training and testing respectively in an 80:20 split."
},
{
"code": null,
"e": 4423,
"s": 4283,
"text": "X_train, X_test, y_train, y_test = train_test_split(diabetes_df.drop(columns=\"target\"), diabetes_df.target, test_size=0.2, random_state=21)"
},
{
"code": null,
"e": 4574,
"s": 4423,
"text": "We need three elements to build a pipeline: (1) the models to be optimized, (2) the sklearn Pipeline object, and (3) the skopt optimization procedure."
},
{
"code": null,
"e": 5144,
"s": 4574,
"text": "First, we choose two boosting models: AdaBoost and GradientBoosted regressors and for each we define a search space over crucial hyperparameters. Any other regressor from the depth of the sklearn library would do, but boosting might win you the next hackathon (...its 2015 isn’t it?)The search-space is a dictionary with the key-value pair := { ‘model__parameter‘ : skopt.space.Object}. For each parameter we set a space from the skopt library in the range that we want. Categorical values are also included by passing them as a list of strings (see Categorical below):"
},
{
"code": null,
"e": 5596,
"s": 5144,
"text": "ada_search = { 'model': [AdaBoostRegressor()], 'model__learning_rate': Real(0.005, 0.9, prior=\"log-uniform\"), 'model__n_estimators': Integer(1, 1000), 'model__loss': Categorical(['linear', 'square', 'exponential'])}gb_search = { 'model': [GradientBoostingRegressor()], 'model__learning_rate': Real(0.005, 0.9, prior=\"log-uniform\"), 'model__n_estimators': Integer(1, 1000), 'model__loss': Categorical(['ls', 'lad', 'quantile'])}"
},
{
"code": null,
"e": 5783,
"s": 5596,
"text": "Second, we select over which regression model to pick through another model, this is our pipeline element, where both optimizers (adaboost and gradientboost) come together for selection:"
},
{
"code": null,
"e": 5841,
"s": 5783,
"text": "pipe = Pipeline([('model', GradientBoostingRegressor())])"
},
{
"code": null,
"e": 6083,
"s": 5841,
"text": "Third, we optimize over our search-space. For this we invoke the BayesSearchCV. We also specify how the optimizer should call our search-space. In our case that is 100 invocations. Then we fit the pipeline with a simple skopt .fit() command:"
},
{
"code": null,
"e": 6189,
"s": 6083,
"text": "opt = BayesSearchCV( pipe, [(ada_search, 100), (gb_search, 100)], cv=5)opt.fit(X_train, y_train)"
},
{
"code": null,
"e": 6330,
"s": 6189,
"text": "After the fitting is done, we can then ask for the optimal found parameters. This includes using the score function on the unseen test-data."
},
{
"code": null,
"e": 6634,
"s": 6330,
"text": "We can see the validation and test-score as well as the parameters of the best fit. The model with the best results is the AdaBoost model with a linear loss and 259 estimators at a learning-rate of 0.064. Neat.From the output we can also see that the optimizer uses a GP for optimization under the hood:"
},
{
"code": null,
"e": 6803,
"s": 6634,
"text": "For illustrative purposes we can also call GP minimization specifically — we’ll use the AdaBoost regressor for that — only focusing on a numerical hyperparameter space."
},
{
"code": null,
"e": 6973,
"s": 6803,
"text": "ada = AdaBoostRegressor(random_state=21)# numerical spacespace = [Real(0.005, 0.9, \"log-uniform\", name='learning_rate'), Integer(1, 1000, name=\"n_estimators\")]"
},
{
"code": null,
"e": 7172,
"s": 6973,
"text": "The major change here is that we have to define an objective function over which we have to optimize. In order to see how the model performs over the parameter-space we use the named_args decorator."
},
{
"code": null,
"e": 7393,
"s": 7172,
"text": "@use_named_args(space)def objective(**params): ada.set_params(**params) return -np.mean(cross_val_score(ada, X_train, y_train, cv=5, n_jobs=-1, scoring=\"neg_mean_absolute_error\"))"
},
{
"code": null,
"e": 7721,
"s": 7393,
"text": "Therefore our optimization is the negative mean score that we get from the cross-validated fit while using the negative mean absolute error. Other scoring functions might suit you better.We then use GP minimization to fit the most optimal parameters for our regressor.gp_minimize(objective, space, n_calls=100, random_state=21)"
},
{
"code": null,
"e": 7813,
"s": 7721,
"text": "Using GP optimization directly allows us to plot convergence over the minimization process."
},
{
"code": null,
"e": 8107,
"s": 7813,
"text": "We can see that the min in the function value has already been reached after around 40 iterations.The last excellent feature is visualizing the explored problem space. Since we used only numerical input at this point, we can then evaluate the problem space by plotting it using skopt, like so:"
},
{
"code": null,
"e": 8694,
"s": 8107,
"text": "From the figure above we can see that a lot of exploration was done on the lower end of our learning-rate spectrum, and the peaks of the tried and tested estimator number was 200 and over 800.The scatterplot paints a picture of how difficult the problem space is that we are trying to optimize — with the minimum marked with a red star. Each GP-minimize run uncovers a function value, given the parameter that it has as input. Though we have reached convergence not a lot of values are evident in the region around the minimum and increasing the number of evaluations can be considered."
},
{
"code": null,
"e": 8827,
"s": 8694,
"text": "Now that we have the best model given our parameter space we can implement that model accordingly and go into its specific analysis."
},
{
"code": null,
"e": 9355,
"s": 8827,
"text": "We have shown that we can explore a vast space of possible model-parameters in an efficient way, saving both time and computational resources. We do this by formulating the search for hyperparameters as an objective function for which we find the optimal values using Bayesian Optimization. There is no need to test useless parameters anymore by trying out every single one of them.As you have seen skopt is a library that offers a lot in the realm of optimizations and I encourage you to use them in your daily ML engineering."
},
{
"code": null,
"e": 9372,
"s": 9355,
"text": "Happy Exploring!"
},
{
"code": null,
"e": 9423,
"s": 9372,
"text": "The complete code can be found in a Notebook here:"
},
{
"code": null,
"e": 9434,
"s": 9423,
"text": "github.com"
},
{
"code": null,
"e": 9676,
"s": 9434,
"text": "Marc Claesen, Bart De Moor. Hyperparameter Search in Machine Learning. 2015 on arXiv.Peter I. Frazier. A Tutorial on Bayesian Optimization. 2018 on arXiv.scikit-optimize contributors (BSD License). Scikit-learn hyperparameter search wrapper."
},
{
"code": null,
"e": 9762,
"s": 9676,
"text": "Marc Claesen, Bart De Moor. Hyperparameter Search in Machine Learning. 2015 on arXiv."
},
{
"code": null,
"e": 9832,
"s": 9762,
"text": "Peter I. Frazier. A Tutorial on Bayesian Optimization. 2018 on arXiv."
}
] |
Optimize your Investments using Math and Python | by Andrew Hershy | Towards Data Science
|
During the MBA, we learned all about predictive modeling techniques using Excel and University of Waikato’s free software, WEKA. We learned the foundational concepts but never ventured into the hard skills required for advanced calculation. After some time studying python, I thought it would be fun to rework one of my linear optimization projects I originally did in Excel’s solver. The goal of this article is to recreate the project in python’s PuLP, share what I learn along the way, and compare python’s results to Excel’s.
The real world benefits /applications of linear optimization are endless. I would highly recommend following along closely, at least on a conceptual level, and making an effort to learn this skill if you are not already familiar with it.
What is Linear Optimization?The Assignment / ReviewData Upload and CleanLinear Optimization using PuLP
What is Linear Optimization?
The Assignment / Review
Data Upload and Clean
Linear Optimization using PuLP
According to Wikipedia, linear programming is “a method to achieve the best outcome (such as maximum profit or lowest cost) in a mathematical model whose requirements are represented by linear relationships.” These lecture notes from Carnegie Mellon University were very helpful in my own understanding of the topic.
In my own words, I would describe it as being a way to solve minimum / maximum solutions for a particular variable (decision variable), intertwined with other linear variables, to an extent that it would be very difficult to solve the problem with a pen and paper.
This is a linear optimization problem with regard to risk and return of a portfolio. Our objective is to minimize portfolio risk while simultaneously satisfying 5 constraints:
The sum of the investments will be $100,000
The sum of the investments will be $100,000
2. The portfolio has an annual return of at least 7.5%
3. At least 50% of the investments are A-rated
4. At least 40% of the investments are immediately liquid
5. No more than $30,000 are in savings accounts and certificates of deposit
The detailed instructions are below:
To review the process in solving a linear optimization problem, there are 3 steps:
Decision Variables: Here, there are 8 decision variables. They are our investment options.Objective Function: We want to minimize the risk for the 8 investments. Below are the investments multiplied by their respective risk coefficients.
Decision Variables: Here, there are 8 decision variables. They are our investment options.
Objective Function: We want to minimize the risk for the 8 investments. Below are the investments multiplied by their respective risk coefficients.
3. Constraints: Lastly, we want to define exactly what our constraints are. These are algebraically expressed below in the same order as we listed the constraints previously:
In case you are confused about the “7,500” in constraint #2, that would be the 7.5% annual return we are looking for multiplied by our $100,000 investment.
Now that we have the problem set up, let’s upload the data into pandas and import pulp:
from pulp import *import pandas as pddf = pd.read_excel(r"C:\Users\Andrew\Desktop\Fin_optimization.xlsx")df
Looking good. There are a few formatting changes that must be made in order to move forward, however.
Turn the “Liquidity” and “Ratings” columns into binary values. This is in regard to constraints #3 and #4. The relevant string values in these columns are “Immediate” for Liquidity and “A” for Rating. Distinguishing these string values from the others is necessary for further calculation.Create a new binary column for Investment Type. Constraint #5 focuses on the savings and CD investment types, so distinguishing them from the other investment types will help later.Create a column of all 1’s for Amt_invested. This will be useful for constraint #1: the $100,000 total portfolio constraint.
Turn the “Liquidity” and “Ratings” columns into binary values. This is in regard to constraints #3 and #4. The relevant string values in these columns are “Immediate” for Liquidity and “A” for Rating. Distinguishing these string values from the others is necessary for further calculation.
Create a new binary column for Investment Type. Constraint #5 focuses on the savings and CD investment types, so distinguishing them from the other investment types will help later.
Create a column of all 1’s for Amt_invested. This will be useful for constraint #1: the $100,000 total portfolio constraint.
#1adf['Liquidity'] = (df['Liquidity']=='Immediate')df['Liquidity'] = df['Liquidity'].astype(int)#1bdf['Rating'] = (df['Rating']=='A')df['Rating']= df['Rating'].astype(int)#2savecd = [1,1,0,0,0,0,0,0]df['Saving&CD'] = savecd#3amt_invested = [1]*8df['Amt_Invested'] = amt_investeddf
Perfect. Let’s move on.
The first step using PuLP is to define the problem. The code below simply defines our problem as minimization (with regard to risk)and gives it the title, “Portfolio_Opt”. We will add more to this ‘prob’ variable later.
prob = LpProblem("Portfolio_Opt",LpMinimize)
Next we will create a list of our decision variables (investments options). Then we will use that list to create dictionaries for each feature:
#Create a list of the investment itemsinv_items = list(df['Potential Investment'])#Create a dictionary of risks for all inv itemsrisks = dict(zip(inv_items,df['Risk']))#Create a dictionary of returns for all inv itemsreturns = dict(zip(inv_items,df['Expected Return']))#Create dictionary for ratings of inv itemsratings = dict(zip(inv_items,df['Rating']))#Create a dictionary for liquidity for all inv itemsliquidity = dict(zip(inv_items,df['Liquidity']))#Create a dictionary for savecd for inve itemssavecd = dict(zip(inv_items,df['Saving&CD']))#Create a dictionary for amt as being all 1'samt = dict(zip(inv_items,df['Amt_Invested']))risks
Next, we are defining our decision variables as investments and are adding a few parameters to it,
Name: To label our decision variables
Lowbound = 0: To make sure there is no negative money in our solution
Continuous: Because we are dealing with cents to the dollar.
inv_vars = LpVariable.dicts("Potential Investment",inv_items,lowBound=0,cat='Continuous')
Finally, we add the modified decision variable to our problem variable we made earlier and additionally enter the constraints. We are iterating over dictionaries using “for loops” for each investment item.
#Setting the Decision Variablesprob += lpSum([risks[i]*inv_vars[i] for i in inv_items])#Constraint #1:prob += lpSum([amt[f] * inv_vars[f] for f in inv_items]) == 100000, "Investments"Constraint #2prob += lpSum([returns[f] * inv_vars[f] for f in inv_items]) >= 7500, "Returns"Constraint #3prob += lpSum([ratings[f] * inv_vars[f] for f in inv_items]) >= 50000, "Ratings"Constraint #4prob += lpSum([liquidity[f] * inv_vars[f] for f in inv_items]) >= 40000, "Liquidity"Constraint #5prob += lpSum([savecd[f] * inv_vars[f] for f in inv_items]) <= 30000, "Save and CD"prob
Below is the problem:
Result:
prob.writeLP("Portfolio_Opt.lp")print("The optimal portfolio consists of\n"+"-"*110)for v in prob.variables(): if v.varValue>0: print(v.name, "=", v.varValue)
This is exactly the same outcome Excel’s solver gave.
Refer to my Github to see the full notebook file.
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
Please subscribe if you found this helpful. If you enjoy my content, below are some projects I’ve worked on:
Uber Reviews Text Analysis
Excel vs SQL: A Conceptual Comparison
Simple Linear vs Polynomial Regression
Is Random Forest better than Logistic Regression? (a comparison)
Gini Index vs Information Entropy
Predicting Cancer with Logistic Regression in Python
Bivariate Logistic Regression Example (python)
Calculating R-squared from scratch (using python)
|
[
{
"code": null,
"e": 702,
"s": 172,
"text": "During the MBA, we learned all about predictive modeling techniques using Excel and University of Waikato’s free software, WEKA. We learned the foundational concepts but never ventured into the hard skills required for advanced calculation. After some time studying python, I thought it would be fun to rework one of my linear optimization projects I originally did in Excel’s solver. The goal of this article is to recreate the project in python’s PuLP, share what I learn along the way, and compare python’s results to Excel’s."
},
{
"code": null,
"e": 940,
"s": 702,
"text": "The real world benefits /applications of linear optimization are endless. I would highly recommend following along closely, at least on a conceptual level, and making an effort to learn this skill if you are not already familiar with it."
},
{
"code": null,
"e": 1043,
"s": 940,
"text": "What is Linear Optimization?The Assignment / ReviewData Upload and CleanLinear Optimization using PuLP"
},
{
"code": null,
"e": 1072,
"s": 1043,
"text": "What is Linear Optimization?"
},
{
"code": null,
"e": 1096,
"s": 1072,
"text": "The Assignment / Review"
},
{
"code": null,
"e": 1118,
"s": 1096,
"text": "Data Upload and Clean"
},
{
"code": null,
"e": 1149,
"s": 1118,
"text": "Linear Optimization using PuLP"
},
{
"code": null,
"e": 1466,
"s": 1149,
"text": "According to Wikipedia, linear programming is “a method to achieve the best outcome (such as maximum profit or lowest cost) in a mathematical model whose requirements are represented by linear relationships.” These lecture notes from Carnegie Mellon University were very helpful in my own understanding of the topic."
},
{
"code": null,
"e": 1731,
"s": 1466,
"text": "In my own words, I would describe it as being a way to solve minimum / maximum solutions for a particular variable (decision variable), intertwined with other linear variables, to an extent that it would be very difficult to solve the problem with a pen and paper."
},
{
"code": null,
"e": 1907,
"s": 1731,
"text": "This is a linear optimization problem with regard to risk and return of a portfolio. Our objective is to minimize portfolio risk while simultaneously satisfying 5 constraints:"
},
{
"code": null,
"e": 1951,
"s": 1907,
"text": "The sum of the investments will be $100,000"
},
{
"code": null,
"e": 1995,
"s": 1951,
"text": "The sum of the investments will be $100,000"
},
{
"code": null,
"e": 2050,
"s": 1995,
"text": "2. The portfolio has an annual return of at least 7.5%"
},
{
"code": null,
"e": 2097,
"s": 2050,
"text": "3. At least 50% of the investments are A-rated"
},
{
"code": null,
"e": 2155,
"s": 2097,
"text": "4. At least 40% of the investments are immediately liquid"
},
{
"code": null,
"e": 2231,
"s": 2155,
"text": "5. No more than $30,000 are in savings accounts and certificates of deposit"
},
{
"code": null,
"e": 2268,
"s": 2231,
"text": "The detailed instructions are below:"
},
{
"code": null,
"e": 2351,
"s": 2268,
"text": "To review the process in solving a linear optimization problem, there are 3 steps:"
},
{
"code": null,
"e": 2589,
"s": 2351,
"text": "Decision Variables: Here, there are 8 decision variables. They are our investment options.Objective Function: We want to minimize the risk for the 8 investments. Below are the investments multiplied by their respective risk coefficients."
},
{
"code": null,
"e": 2680,
"s": 2589,
"text": "Decision Variables: Here, there are 8 decision variables. They are our investment options."
},
{
"code": null,
"e": 2828,
"s": 2680,
"text": "Objective Function: We want to minimize the risk for the 8 investments. Below are the investments multiplied by their respective risk coefficients."
},
{
"code": null,
"e": 3003,
"s": 2828,
"text": "3. Constraints: Lastly, we want to define exactly what our constraints are. These are algebraically expressed below in the same order as we listed the constraints previously:"
},
{
"code": null,
"e": 3159,
"s": 3003,
"text": "In case you are confused about the “7,500” in constraint #2, that would be the 7.5% annual return we are looking for multiplied by our $100,000 investment."
},
{
"code": null,
"e": 3247,
"s": 3159,
"text": "Now that we have the problem set up, let’s upload the data into pandas and import pulp:"
},
{
"code": null,
"e": 3355,
"s": 3247,
"text": "from pulp import *import pandas as pddf = pd.read_excel(r\"C:\\Users\\Andrew\\Desktop\\Fin_optimization.xlsx\")df"
},
{
"code": null,
"e": 3457,
"s": 3355,
"text": "Looking good. There are a few formatting changes that must be made in order to move forward, however."
},
{
"code": null,
"e": 4052,
"s": 3457,
"text": "Turn the “Liquidity” and “Ratings” columns into binary values. This is in regard to constraints #3 and #4. The relevant string values in these columns are “Immediate” for Liquidity and “A” for Rating. Distinguishing these string values from the others is necessary for further calculation.Create a new binary column for Investment Type. Constraint #5 focuses on the savings and CD investment types, so distinguishing them from the other investment types will help later.Create a column of all 1’s for Amt_invested. This will be useful for constraint #1: the $100,000 total portfolio constraint."
},
{
"code": null,
"e": 4342,
"s": 4052,
"text": "Turn the “Liquidity” and “Ratings” columns into binary values. This is in regard to constraints #3 and #4. The relevant string values in these columns are “Immediate” for Liquidity and “A” for Rating. Distinguishing these string values from the others is necessary for further calculation."
},
{
"code": null,
"e": 4524,
"s": 4342,
"text": "Create a new binary column for Investment Type. Constraint #5 focuses on the savings and CD investment types, so distinguishing them from the other investment types will help later."
},
{
"code": null,
"e": 4649,
"s": 4524,
"text": "Create a column of all 1’s for Amt_invested. This will be useful for constraint #1: the $100,000 total portfolio constraint."
},
{
"code": null,
"e": 4930,
"s": 4649,
"text": "#1adf['Liquidity'] = (df['Liquidity']=='Immediate')df['Liquidity'] = df['Liquidity'].astype(int)#1bdf['Rating'] = (df['Rating']=='A')df['Rating']= df['Rating'].astype(int)#2savecd = [1,1,0,0,0,0,0,0]df['Saving&CD'] = savecd#3amt_invested = [1]*8df['Amt_Invested'] = amt_investeddf"
},
{
"code": null,
"e": 4954,
"s": 4930,
"text": "Perfect. Let’s move on."
},
{
"code": null,
"e": 5174,
"s": 4954,
"text": "The first step using PuLP is to define the problem. The code below simply defines our problem as minimization (with regard to risk)and gives it the title, “Portfolio_Opt”. We will add more to this ‘prob’ variable later."
},
{
"code": null,
"e": 5219,
"s": 5174,
"text": "prob = LpProblem(\"Portfolio_Opt\",LpMinimize)"
},
{
"code": null,
"e": 5363,
"s": 5219,
"text": "Next we will create a list of our decision variables (investments options). Then we will use that list to create dictionaries for each feature:"
},
{
"code": null,
"e": 6005,
"s": 5363,
"text": "#Create a list of the investment itemsinv_items = list(df['Potential Investment'])#Create a dictionary of risks for all inv itemsrisks = dict(zip(inv_items,df['Risk']))#Create a dictionary of returns for all inv itemsreturns = dict(zip(inv_items,df['Expected Return']))#Create dictionary for ratings of inv itemsratings = dict(zip(inv_items,df['Rating']))#Create a dictionary for liquidity for all inv itemsliquidity = dict(zip(inv_items,df['Liquidity']))#Create a dictionary for savecd for inve itemssavecd = dict(zip(inv_items,df['Saving&CD']))#Create a dictionary for amt as being all 1'samt = dict(zip(inv_items,df['Amt_Invested']))risks"
},
{
"code": null,
"e": 6104,
"s": 6005,
"text": "Next, we are defining our decision variables as investments and are adding a few parameters to it,"
},
{
"code": null,
"e": 6142,
"s": 6104,
"text": "Name: To label our decision variables"
},
{
"code": null,
"e": 6212,
"s": 6142,
"text": "Lowbound = 0: To make sure there is no negative money in our solution"
},
{
"code": null,
"e": 6273,
"s": 6212,
"text": "Continuous: Because we are dealing with cents to the dollar."
},
{
"code": null,
"e": 6363,
"s": 6273,
"text": "inv_vars = LpVariable.dicts(\"Potential Investment\",inv_items,lowBound=0,cat='Continuous')"
},
{
"code": null,
"e": 6569,
"s": 6363,
"text": "Finally, we add the modified decision variable to our problem variable we made earlier and additionally enter the constraints. We are iterating over dictionaries using “for loops” for each investment item."
},
{
"code": null,
"e": 7135,
"s": 6569,
"text": "#Setting the Decision Variablesprob += lpSum([risks[i]*inv_vars[i] for i in inv_items])#Constraint #1:prob += lpSum([amt[f] * inv_vars[f] for f in inv_items]) == 100000, \"Investments\"Constraint #2prob += lpSum([returns[f] * inv_vars[f] for f in inv_items]) >= 7500, \"Returns\"Constraint #3prob += lpSum([ratings[f] * inv_vars[f] for f in inv_items]) >= 50000, \"Ratings\"Constraint #4prob += lpSum([liquidity[f] * inv_vars[f] for f in inv_items]) >= 40000, \"Liquidity\"Constraint #5prob += lpSum([savecd[f] * inv_vars[f] for f in inv_items]) <= 30000, \"Save and CD\"prob"
},
{
"code": null,
"e": 7157,
"s": 7135,
"text": "Below is the problem:"
},
{
"code": null,
"e": 7165,
"s": 7157,
"text": "Result:"
},
{
"code": null,
"e": 7334,
"s": 7165,
"text": "prob.writeLP(\"Portfolio_Opt.lp\")print(\"The optimal portfolio consists of\\n\"+\"-\"*110)for v in prob.variables(): if v.varValue>0: print(v.name, \"=\", v.varValue)"
},
{
"code": null,
"e": 7388,
"s": 7334,
"text": "This is exactly the same outcome Excel’s solver gave."
},
{
"code": null,
"e": 7438,
"s": 7388,
"text": "Refer to my Github to see the full notebook file."
},
{
"code": null,
"e": 7738,
"s": 7438,
"text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details."
},
{
"code": null,
"e": 7847,
"s": 7738,
"text": "Please subscribe if you found this helpful. If you enjoy my content, below are some projects I’ve worked on:"
},
{
"code": null,
"e": 7874,
"s": 7847,
"text": "Uber Reviews Text Analysis"
},
{
"code": null,
"e": 7912,
"s": 7874,
"text": "Excel vs SQL: A Conceptual Comparison"
},
{
"code": null,
"e": 7951,
"s": 7912,
"text": "Simple Linear vs Polynomial Regression"
},
{
"code": null,
"e": 8016,
"s": 7951,
"text": "Is Random Forest better than Logistic Regression? (a comparison)"
},
{
"code": null,
"e": 8050,
"s": 8016,
"text": "Gini Index vs Information Entropy"
},
{
"code": null,
"e": 8103,
"s": 8050,
"text": "Predicting Cancer with Logistic Regression in Python"
},
{
"code": null,
"e": 8150,
"s": 8103,
"text": "Bivariate Logistic Regression Example (python)"
}
] |
What are obsolete attributes in C#?
|
If a method has an obsolete attribute, then the compiler issues a warning in the code after it is compiled.
When a new method is being used in a class and if you still want to retain the old method in the class, you may mark it as obsolete by displaying a message the new method should be used, instead of the old method.
The following is an example showing how obsolete attribute is used −
using System;
public class Demo {
[Obsolete("Old Method shouldn't be used! Use New Method instead", true)]
static void OldMethod() {
Console.WriteLine("This is the old method!");
}
static void NewMethod() {
Console.WriteLine("This is the new method!");
}
public static void Main() {
OldMethod();
}
}
As we have set the warning message above, it will show the following warning −
Compilation failed: 1 error(s), 0 warnings
error CS0619: `Demo.OldMethod()' is obsolete: `Old Method shouldn't be used! Use New Method instead'
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "If a method has an obsolete attribute, then the compiler issues a warning in the code after it is compiled."
},
{
"code": null,
"e": 1384,
"s": 1170,
"text": "When a new method is being used in a class and if you still want to retain the old method in the class, you may mark it as obsolete by displaying a message the new method should be used, instead of the old method."
},
{
"code": null,
"e": 1453,
"s": 1384,
"text": "The following is an example showing how obsolete attribute is used −"
},
{
"code": null,
"e": 1796,
"s": 1453,
"text": "using System;\n\npublic class Demo {\n [Obsolete(\"Old Method shouldn't be used! Use New Method instead\", true)]\n\n static void OldMethod() {\n Console.WriteLine(\"This is the old method!\");\n }\n\n static void NewMethod() {\n Console.WriteLine(\"This is the new method!\");\n }\n\n public static void Main() {\n OldMethod();\n }\n}"
},
{
"code": null,
"e": 1875,
"s": 1796,
"text": "As we have set the warning message above, it will show the following warning −"
},
{
"code": null,
"e": 2019,
"s": 1875,
"text": "Compilation failed: 1 error(s), 0 warnings\nerror CS0619: `Demo.OldMethod()' is obsolete: `Old Method shouldn't be used! Use New Method instead'"
}
] |
Data visualization using ggplot2: 5 features worth knowing | by Abhinav Malasi | Towards Data Science
|
Whether you are working on your school project, term paper, master’s thesis, or a business presentation, the quality of the data translates well to the audience if the data is presented in a meaningful and aesthetically pleasing way. Although making an impactful figure from the data is challenging and time-consuming, but some small tips if implemented properly can make the workflow simpler and save a lot of time over the long run.
In this post, I will be discussing 5 tips or features that I find useful and implement on a regular basis while working with the ggplot2 package. Maybe some of you will already know them and for some, it will be something new.
To give a little background about ggplot2, it is developed based on the grammar of graphics in short gg. The plot consists of three fundamental parts, namely:
1. Data: consisting of the data frame
2. Aesthetics: defining the x and y variable and detailing the color, size, and shape of the data points
3. Geometry: defines the type of plot e.g. bar plot, line plot, scatter, histogram, etc.
So, let's dive in to see the 5 features/tips that I want to share with you all that have been very handy to me. For demonstration purposes, I will be using the USArrests dataset from the in-built R data repository.
Tip #1: Using parentheses while assigning ggplot function to a variable
A cool thing in the ggplot2 package is the use of parentheses. In general, while plotting using ggplot function, if we assign it to a variable then in order to plot, the variable is executed in the next line. So, this is a two-step process. By putting the ggplot function in the parentheses when assigning helps plot the figure directly without executing the variable again.
# two step way to plotplot <- USArrests %>% ggplot(aes(States, Murder)) + geom_bar(stat = "identity")plot# one step way to plot using parentheses(plot <- USArrests %>% ggplot(aes(States, Murder)) + geom_bar(stat = "identity"))
Tip #2: Minimizing repetitive ggplot function by switching data
This command simply is very useful during the EDA stage when I try plotting different sets of variables to understand the relationships. Instead of writing ggplot commands, again and again, I prefer to use %+% from the tidyverse package. By using %+% we can override the current data with the new data.
# lets define a temporary variabletemp <- USArrests[,c(1,3)] %>% rename(Murder = Assault)# switching the current data with the temp variable using %+% operatorplot2 <- plot %+% temp# plotting the new graphplot2 + ylab("Assaults per 100,000")
Warning: For %+% to work, make sure the column names of the new data matches the column name of the dataset being replaced.
Tip #3: Freedom to use col/color/colour in aesthetics
The aesthetics of the ggplot2 package gives the freedom to choose between col/color/colour to assign the colors to the plot. So, it doesn’t matter if you use British English or American English, you are covered by ggplot.
# plotting the same data using col/color/colour in aesthetics using green/blue/red colors to distinguishplot3 <- USArrests %>% ggplot(aes(States, Murder)) + geom_bar(stat = "identity", col = "green") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + ylab("Murders per 100,000") + xlab("USA States") + #scale_y_discrete(limits=c(0:10)) + theme_bw()plot4 <- USArrests %>% ggplot(aes(States, Murder)) + geom_bar(stat = "identity", color = "blue") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + ylab("Murders per 100,000") + xlab("USA States") + #scale_y_discrete(limits=c(0:10)) + theme_bw()plot5 <- USArrests %>% ggplot(aes(States, Murder)) + geom_bar(stat = "identity", colour = "red") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + ylab("Murders per 100,000") + xlab("USA States") + #scale_y_discrete(limits=c(0:10)) + theme_bw()plot3 + plot4 + plot5 + plot_layout(ncol = 3)
Tip #4: Reordering data using fct_reorder()
To make aesthetically pleasing plots, generally, most of us use group_by(), summarize(), and arrange() functions to arrange the data. This being a lengthy step that could be replaced by a single function from the forcats package called fct_order().
plot6 <- USArrests %>% ggplot(aes(x = fct_reorder(States, Murder, .desc = FALSE), y = Murder)) + geom_bar(stat = "identity", colour = "red") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + ylab("Murders per 100,000") + xlab("USA States") + theme_bw() + coord_flip()
Tip #5: ggsave() for saving plots
ggsave() function provides flexibility to the users looking to save high-resolution images for publications, presentations, or printing. The ggsave function has features to adjust image size, define the resolution and adjusting the image background to be transparent or not, and flexibility to choose different file extensions.
ggsave( filename = "trial.png", device = png(), path = NULL, scale = 1, width = 5, height = 5, units = "in", dpi = 600, limitsize = TRUE, bg = "transparent")
These are the 5 features that I use quite often when plotting with the ggplot2 package.
Using parentheses while assigning ggplot function to a variableMinimizing repetitive ggplot function by switching dataFreedom to use col/color/colour in aestheticsReordering data using fct_reorder()ggsave() for saving plots
Using parentheses while assigning ggplot function to a variable
Minimizing repetitive ggplot function by switching data
Freedom to use col/color/colour in aesthetics
Reordering data using fct_reorder()
ggsave() for saving plots
The best way to implement the above 5 features is to keep on practicing, this is how I did. The more different scenarios you try using them the more potential you will see. Till then, happy coding.
Did you guys find these features/tips interesting? Were any of them new to you? Do share your thoughts in the comments and any tips/tricks that you use for plotting not covered here.
Link to the code.
You can connect with me on LinkedIn.
|
[
{
"code": null,
"e": 606,
"s": 171,
"text": "Whether you are working on your school project, term paper, master’s thesis, or a business presentation, the quality of the data translates well to the audience if the data is presented in a meaningful and aesthetically pleasing way. Although making an impactful figure from the data is challenging and time-consuming, but some small tips if implemented properly can make the workflow simpler and save a lot of time over the long run."
},
{
"code": null,
"e": 833,
"s": 606,
"text": "In this post, I will be discussing 5 tips or features that I find useful and implement on a regular basis while working with the ggplot2 package. Maybe some of you will already know them and for some, it will be something new."
},
{
"code": null,
"e": 992,
"s": 833,
"text": "To give a little background about ggplot2, it is developed based on the grammar of graphics in short gg. The plot consists of three fundamental parts, namely:"
},
{
"code": null,
"e": 1030,
"s": 992,
"text": "1. Data: consisting of the data frame"
},
{
"code": null,
"e": 1135,
"s": 1030,
"text": "2. Aesthetics: defining the x and y variable and detailing the color, size, and shape of the data points"
},
{
"code": null,
"e": 1224,
"s": 1135,
"text": "3. Geometry: defines the type of plot e.g. bar plot, line plot, scatter, histogram, etc."
},
{
"code": null,
"e": 1439,
"s": 1224,
"text": "So, let's dive in to see the 5 features/tips that I want to share with you all that have been very handy to me. For demonstration purposes, I will be using the USArrests dataset from the in-built R data repository."
},
{
"code": null,
"e": 1511,
"s": 1439,
"text": "Tip #1: Using parentheses while assigning ggplot function to a variable"
},
{
"code": null,
"e": 1886,
"s": 1511,
"text": "A cool thing in the ggplot2 package is the use of parentheses. In general, while plotting using ggplot function, if we assign it to a variable then in order to plot, the variable is executed in the next line. So, this is a two-step process. By putting the ggplot function in the parentheses when assigning helps plot the figure directly without executing the variable again."
},
{
"code": null,
"e": 2117,
"s": 1886,
"text": "# two step way to plotplot <- USArrests %>% ggplot(aes(States, Murder)) + geom_bar(stat = \"identity\")plot# one step way to plot using parentheses(plot <- USArrests %>% ggplot(aes(States, Murder)) + geom_bar(stat = \"identity\"))"
},
{
"code": null,
"e": 2181,
"s": 2117,
"text": "Tip #2: Minimizing repetitive ggplot function by switching data"
},
{
"code": null,
"e": 2484,
"s": 2181,
"text": "This command simply is very useful during the EDA stage when I try plotting different sets of variables to understand the relationships. Instead of writing ggplot commands, again and again, I prefer to use %+% from the tidyverse package. By using %+% we can override the current data with the new data."
},
{
"code": null,
"e": 2726,
"s": 2484,
"text": "# lets define a temporary variabletemp <- USArrests[,c(1,3)] %>% rename(Murder = Assault)# switching the current data with the temp variable using %+% operatorplot2 <- plot %+% temp# plotting the new graphplot2 + ylab(\"Assaults per 100,000\")"
},
{
"code": null,
"e": 2850,
"s": 2726,
"text": "Warning: For %+% to work, make sure the column names of the new data matches the column name of the dataset being replaced."
},
{
"code": null,
"e": 2904,
"s": 2850,
"text": "Tip #3: Freedom to use col/color/colour in aesthetics"
},
{
"code": null,
"e": 3126,
"s": 2904,
"text": "The aesthetics of the ggplot2 package gives the freedom to choose between col/color/colour to assign the colors to the plot. So, it doesn’t matter if you use British English or American English, you are covered by ggplot."
},
{
"code": null,
"e": 4095,
"s": 3126,
"text": "# plotting the same data using col/color/colour in aesthetics using green/blue/red colors to distinguishplot3 <- USArrests %>% ggplot(aes(States, Murder)) + geom_bar(stat = \"identity\", col = \"green\") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + ylab(\"Murders per 100,000\") + xlab(\"USA States\") + #scale_y_discrete(limits=c(0:10)) + theme_bw()plot4 <- USArrests %>% ggplot(aes(States, Murder)) + geom_bar(stat = \"identity\", color = \"blue\") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + ylab(\"Murders per 100,000\") + xlab(\"USA States\") + #scale_y_discrete(limits=c(0:10)) + theme_bw()plot5 <- USArrests %>% ggplot(aes(States, Murder)) + geom_bar(stat = \"identity\", colour = \"red\") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + ylab(\"Murders per 100,000\") + xlab(\"USA States\") + #scale_y_discrete(limits=c(0:10)) + theme_bw()plot3 + plot4 + plot5 + plot_layout(ncol = 3)"
},
{
"code": null,
"e": 4139,
"s": 4095,
"text": "Tip #4: Reordering data using fct_reorder()"
},
{
"code": null,
"e": 4388,
"s": 4139,
"text": "To make aesthetically pleasing plots, generally, most of us use group_by(), summarize(), and arrange() functions to arrange the data. This being a lengthy step that could be replaced by a single function from the forcats package called fct_order()."
},
{
"code": null,
"e": 4686,
"s": 4388,
"text": "plot6 <- USArrests %>% ggplot(aes(x = fct_reorder(States, Murder, .desc = FALSE), y = Murder)) + geom_bar(stat = \"identity\", colour = \"red\") + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + ylab(\"Murders per 100,000\") + xlab(\"USA States\") + theme_bw() + coord_flip()"
},
{
"code": null,
"e": 4720,
"s": 4686,
"text": "Tip #5: ggsave() for saving plots"
},
{
"code": null,
"e": 5048,
"s": 4720,
"text": "ggsave() function provides flexibility to the users looking to save high-resolution images for publications, presentations, or printing. The ggsave function has features to adjust image size, define the resolution and adjusting the image background to be transparent or not, and flexibility to choose different file extensions."
},
{
"code": null,
"e": 5216,
"s": 5048,
"text": "ggsave( filename = \"trial.png\", device = png(), path = NULL, scale = 1, width = 5, height = 5, units = \"in\", dpi = 600, limitsize = TRUE, bg = \"transparent\")"
},
{
"code": null,
"e": 5304,
"s": 5216,
"text": "These are the 5 features that I use quite often when plotting with the ggplot2 package."
},
{
"code": null,
"e": 5528,
"s": 5304,
"text": "Using parentheses while assigning ggplot function to a variableMinimizing repetitive ggplot function by switching dataFreedom to use col/color/colour in aestheticsReordering data using fct_reorder()ggsave() for saving plots"
},
{
"code": null,
"e": 5592,
"s": 5528,
"text": "Using parentheses while assigning ggplot function to a variable"
},
{
"code": null,
"e": 5648,
"s": 5592,
"text": "Minimizing repetitive ggplot function by switching data"
},
{
"code": null,
"e": 5694,
"s": 5648,
"text": "Freedom to use col/color/colour in aesthetics"
},
{
"code": null,
"e": 5730,
"s": 5694,
"text": "Reordering data using fct_reorder()"
},
{
"code": null,
"e": 5756,
"s": 5730,
"text": "ggsave() for saving plots"
},
{
"code": null,
"e": 5954,
"s": 5756,
"text": "The best way to implement the above 5 features is to keep on practicing, this is how I did. The more different scenarios you try using them the more potential you will see. Till then, happy coding."
},
{
"code": null,
"e": 6137,
"s": 5954,
"text": "Did you guys find these features/tips interesting? Were any of them new to you? Do share your thoughts in the comments and any tips/tricks that you use for plotting not covered here."
},
{
"code": null,
"e": 6155,
"s": 6137,
"text": "Link to the code."
}
] |
Puppet - Installing and Configuring r10K
|
In Puppet, we have a code management tool known as r10k that helps in managing environment configurations related to different kind of environments that we can configure in Puppet such as development, testing, and production. This helps in storing environment-related configuration in the source code repository. Using the source control repo branches, r10k creates environments on Puppet master machine installs and updates environment using modules present in the repo.
Gem file can be used to install r10k on any machine but for modularity and in order to get the latest version, we will use rpm and rpm package manager. Following is an example for the same.
$ urlgrabber -o /etc/yum.repos.d/timhughes-r10k-epel-6.repo
https://copr.fedoraproject.org/coprs/timhughes/yum -y install rubygem-r10k
Configure environment in /etc/puppet/puppet.conf
[main]
environmentpath = $confdir/environments
cat <<EOF >/etc/r10k.yaml
# The location to use for storing cached Git repos
:cachedir: '/var/cache/r10k'
# A list of git repositories to create
:sources:
# This will clone the git repository and instantiate an environment per
# branch in /etc/puppet/environments
:opstree:
#remote: 'https://github.com/fullstack-puppet/fullstackpuppet-environment.git'
remote: '/var/lib/git/fullstackpuppet-environment.git'
basedir: '/etc/puppet/environments'
EOF
r10k deploy environment -pv
As we need to continue updating the environment in every 15 minutes, we will create a cron job for the same.
cat << EOF > /etc/cron.d/r10k.conf
SHELL = /bin/bash
PATH = /sbin:/bin:/usr/sbin:/usr/bin
H/15 * * * * root r10k deploy environment -p
EOF
In order to test if everything works as accepted, one needs to compile the Puppet manifest for Puppet module. Run the following command and get a YAML output as the result.
curl --cert /etc/puppet/ssl/certs/puppet.corp.guest.pem \
--key /etc/puppet/ssl/private_keys/puppet.corp.guest.pem \
--cacert /etc/puppet/ssl/ca/ca_crt.pem \
-H 'Accept: yaml' \
https://puppet.corp.guest:8140/production/catalog/puppet.corp.guest
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2645,
"s": 2173,
"text": "In Puppet, we have a code management tool known as r10k that helps in managing environment configurations related to different kind of environments that we can configure in Puppet such as development, testing, and production. This helps in storing environment-related configuration in the source code repository. Using the source control repo branches, r10k creates environments on Puppet master machine installs and updates environment using modules present in the repo."
},
{
"code": null,
"e": 2835,
"s": 2645,
"text": "Gem file can be used to install r10k on any machine but for modularity and in order to get the latest version, we will use rpm and rpm package manager. Following is an example for the same."
},
{
"code": null,
"e": 2972,
"s": 2835,
"text": "$ urlgrabber -o /etc/yum.repos.d/timhughes-r10k-epel-6.repo\nhttps://copr.fedoraproject.org/coprs/timhughes/yum -y install rubygem-r10k \n"
},
{
"code": null,
"e": 3021,
"s": 2972,
"text": "Configure environment in /etc/puppet/puppet.conf"
},
{
"code": null,
"e": 3071,
"s": 3021,
"text": "[main] \nenvironmentpath = $confdir/environments \n"
},
{
"code": null,
"e": 3531,
"s": 3071,
"text": "cat <<EOF >/etc/r10k.yaml \n# The location to use for storing cached Git repos \n:cachedir: '/var/cache/r10k' \n# A list of git repositories to create \n:sources: \n# This will clone the git repository and instantiate an environment per \n# branch in /etc/puppet/environments \n:opstree: \n#remote: 'https://github.com/fullstack-puppet/fullstackpuppet-environment.git' \nremote: '/var/lib/git/fullstackpuppet-environment.git' \nbasedir: '/etc/puppet/environments' \nEOF\n"
},
{
"code": null,
"e": 3561,
"s": 3531,
"text": "r10k deploy environment -pv \n"
},
{
"code": null,
"e": 3670,
"s": 3561,
"text": "As we need to continue updating the environment in every 15 minutes, we will create a cron job for the same."
},
{
"code": null,
"e": 3814,
"s": 3670,
"text": "cat << EOF > /etc/cron.d/r10k.conf \nSHELL = /bin/bash \nPATH = /sbin:/bin:/usr/sbin:/usr/bin \nH/15 * * * * root r10k deploy environment -p \nEOF\n"
},
{
"code": null,
"e": 3987,
"s": 3814,
"text": "In order to test if everything works as accepted, one needs to compile the Puppet manifest for Puppet module. Run the following command and get a YAML output as the result."
},
{
"code": null,
"e": 4239,
"s": 3987,
"text": "curl --cert /etc/puppet/ssl/certs/puppet.corp.guest.pem \\ \n--key /etc/puppet/ssl/private_keys/puppet.corp.guest.pem \\ \n--cacert /etc/puppet/ssl/ca/ca_crt.pem \\ \n-H 'Accept: yaml' \\ \nhttps://puppet.corp.guest:8140/production/catalog/puppet.corp.guest \n"
},
{
"code": null,
"e": 4246,
"s": 4239,
"text": " Print"
},
{
"code": null,
"e": 4257,
"s": 4246,
"text": " Add Notes"
}
] |
JavaFX - Text
|
Just like various shapes, you can also create a text node in JavaFX. The text node is represented by the class named Text, which belongs to the package javafx.scene.text.
This class contains several properties to create text in JavaFX and modify its appearance. This class also inherits the Shape class which belongs to the package javafx.scene.shape.
Therefore, in addition to the properties of the text like font, alignment, line spacing, text, etc. It also inherits the basic shape node properties such as strokeFill, stroke, strokeWidth, strokeType, etc.
Since the class Text of the package javafx.scene.text represents the text node in JavaFX, you can create a text by instantiating this class as follows −
Text text = new Text();
The class Text contains a property named text of string type, which represents the text that is to be created.
After instantiating the Text class, you need to set value to this property using the setText() method as shown below.
String text = "Hello how are you"
Text.setText(text);
You can also set the position (origin) of the text by specifying the values to the properties x and y using their respective setter methods namely setX() and setY() as shown in the following code block −
text.setX(50);
text.setY(50);
The following program is an example demonstrating how to create a text node in JavaFX. Save this code in a file with name TextExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.text.Text;
public class TextExample extends Application {
@Override
public void start(Stage stage) {
//Creating a Text object
Text text = new Text();
//Setting the text to be added.
text.setText("Hello how are you");
//setting the position of the text
text.setX(50);
text.setY(50);
//Creating a Group object
Group root = new Group(text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Sample Application");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac TextExample.java
java TextExample
On executing, the above program generates a JavaFX window displaying the specified text as follows −
By default, the text created by text class is of the font..., size..., and black in color.
You can change the font size and color of the text using the setFont() method. This method accepts an object of the Font class.
The class named Font of the package javafx.scene.text is used to define the font for the text. This class contains a static method named font().
This method accepts four parameters namely −
family − This is of a String type and represents the family of the font that we want to apply to the text.
family − This is of a String type and represents the family of the font that we want to apply to the text.
weight − This property represents the weight of the font. It accepts 9 values, which are − FontWeight.BLACK, FontWeight.BOLD, FontWeight.EXTRA_BOLD, FontWeight.EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN.
weight − This property represents the weight of the font. It accepts 9 values, which are − FontWeight.BLACK, FontWeight.BOLD, FontWeight.EXTRA_BOLD, FontWeight.EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN.
posture − This property represents the font posture (regular or italic). It accepts two values FontPosture.REGULAR and FontPosture.ITALIC.
posture − This property represents the font posture (regular or italic). It accepts two values FontPosture.REGULAR and FontPosture.ITALIC.
size − This property is of type double and it represents the size of the font.
size − This property is of type double and it represents the size of the font.
You can set font to the text by using the following method −
text.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 20));
The following program is an example demonstrating how to set font of the text node in JavaFX. In here, we are setting the font to Verdana, weight to bold, posture to regular and size to 20.
Save this code in a file with the name TextFontExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class TextFontExample extends Application {
@Override
public void start(Stage stage) {
//Creating a Text object
Text text = new Text();
//Setting font to the text
text.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 20));
//setting the position of the text
text.setX(50);
text.setY(130);
//Setting the text to be added.
text.setText("Hi how are you");
//Creating a Group object
Group root = new Group(text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Setting Font to the text");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac TextFontExample.java
java TextFontExample
On executing, the above program generates a JavaFX window displaying the text with the specified font as follows −
The Text class also inherits the class Shape of the package. Therefore, you can use javafx.scene.shape with which you can set the stroke and color to the text node too.
You can set the color to the text using the setFill() method of the shape (inherited) class as follows −
text.setFill(Color.BEIGE);
Similarly, you can set the stroke color of the text using the method setStroke(). While the width of the stroke can be set using the method setStrokeWidth() as follows −
//Setting the color
text.setFill(Color.BROWN);
//Setting the Stroke
text.setStrokeWidth(2);
//Setting the stroke color
text.setStroke(Color.BLUE);
The following program is an example that demonstrates how to set the color, strokeWidth and strokeColor, of the text node. In this code, we are setting stroke color to – blue, text color to – brown and the stroke width to – 2.
Save this code in a file with the name StrokeExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class StrokeExample extends Application {
@Override
public void start(Stage stage) {
//Creating a Text object
Text text = new Text();
//Setting font to the text
text.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 50));
//setting the position of the text
text.setX(50);
text.setY(130);
//Setting the color
text.setFill(Color.BROWN);
//Setting the Stroke
text.setStrokeWidth(2);
// Setting the stroke color
text.setStroke(Color.BLUE);
//Setting the text to be added.
text.setText("Hi how are you");
//Creating a Group object
Group root = new Group(text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Setting font to the text");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac StrokeExample.java
java StrokeExample
On executing, the above program generates a JavaFX window displaying the text with the specified stroke and color attributes as follows −
You can also apply decorations such as strike through; in which case a line is passed through the text. You can underline a text using the methods of the Text class.
You can strike through the text using the method setStrikethrough(). This accepts a Boolean value, pass the value true to this method to strike through the text as shown in the following code box −
//Striking through the text
text1.setStrikethrough(true);
In the same way, you can underline a text by passing the value true to the method setUnderLine() as follows −
//underlining the text
text2.setUnderline(true);
The following program is an example demonstrating how to apply decorations such as underline or strike through to a text. Save this code in a file with the name DecorationsExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class DecorationsExample extends Application {
@Override
public void start(Stage stage) {
//Creating a Text_Example object
Text text1 = new Text("Hi how are you");
//Setting font to the text
text1.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 20));
//setting the position of the text
text1.setX(50);
text1.setY(75);
//Striking through the text
text1.setStrikethrough(true);
//Creating a Text_Example object
Text text2 = new Text("Welcome to Tutorialspoint");
//Setting font to the text
text2.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 20));
//setting the position of the text
text2.setX(50);
text2.setY(150);
//underlining the text
text2.setUnderline(true);
//Creating a Group object
Group root = new Group(text1, text2);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Decorations Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac DecorationsExample.java
java DecorationsExample
On executing, the above program generates a JavaFX window as shown below −
33 Lectures
7.5 hours
Syed Raza
64 Lectures
12.5 hours
Emenwa Global, Ejike IfeanyiChukwu
20 Lectures
4 hours
Emenwa Global, Ejike IfeanyiChukwu
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2071,
"s": 1900,
"text": "Just like various shapes, you can also create a text node in JavaFX. The text node is represented by the class named Text, which belongs to the package javafx.scene.text."
},
{
"code": null,
"e": 2252,
"s": 2071,
"text": "This class contains several properties to create text in JavaFX and modify its appearance. This class also inherits the Shape class which belongs to the package javafx.scene.shape."
},
{
"code": null,
"e": 2459,
"s": 2252,
"text": "Therefore, in addition to the properties of the text like font, alignment, line spacing, text, etc. It also inherits the basic shape node properties such as strokeFill, stroke, strokeWidth, strokeType, etc."
},
{
"code": null,
"e": 2612,
"s": 2459,
"text": "Since the class Text of the package javafx.scene.text represents the text node in JavaFX, you can create a text by instantiating this class as follows −"
},
{
"code": null,
"e": 2637,
"s": 2612,
"text": "Text text = new Text();\n"
},
{
"code": null,
"e": 2748,
"s": 2637,
"text": "The class Text contains a property named text of string type, which represents the text that is to be created."
},
{
"code": null,
"e": 2866,
"s": 2748,
"text": "After instantiating the Text class, you need to set value to this property using the setText() method as shown below."
},
{
"code": null,
"e": 2922,
"s": 2866,
"text": "String text = \"Hello how are you\" \nText.setText(text);\n"
},
{
"code": null,
"e": 3126,
"s": 2922,
"text": "You can also set the position (origin) of the text by specifying the values to the properties x and y using their respective setter methods namely setX() and setY() as shown in the following code block −"
},
{
"code": null,
"e": 3158,
"s": 3126,
"text": "text.setX(50); \ntext.setY(50);\n"
},
{
"code": null,
"e": 3298,
"s": 3158,
"text": "The following program is an example demonstrating how to create a text node in JavaFX. Save this code in a file with name TextExample.java."
},
{
"code": null,
"e": 4324,
"s": 3298,
"text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene;\nimport javafx.stage.Stage; \nimport javafx.scene.text.Text; \n \npublic class TextExample extends Application { \n @Override \n public void start(Stage stage) { \n //Creating a Text object \n Text text = new Text(); \n \n //Setting the text to be added. \n text.setText(\"Hello how are you\"); \n \n //setting the position of the text \n text.setX(50); \n text.setY(50); \n \n //Creating a Group object \n Group root = new Group(text); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Sample Application\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} "
},
{
"code": null,
"e": 4418,
"s": 4324,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 4460,
"s": 4418,
"text": "javac TextExample.java \njava TextExample\n"
},
{
"code": null,
"e": 4561,
"s": 4460,
"text": "On executing, the above program generates a JavaFX window displaying the specified text as follows −"
},
{
"code": null,
"e": 4652,
"s": 4561,
"text": "By default, the text created by text class is of the font..., size..., and black in color."
},
{
"code": null,
"e": 4780,
"s": 4652,
"text": "You can change the font size and color of the text using the setFont() method. This method accepts an object of the Font class."
},
{
"code": null,
"e": 4925,
"s": 4780,
"text": "The class named Font of the package javafx.scene.text is used to define the font for the text. This class contains a static method named font()."
},
{
"code": null,
"e": 4970,
"s": 4925,
"text": "This method accepts four parameters namely −"
},
{
"code": null,
"e": 5077,
"s": 4970,
"text": "family − This is of a String type and represents the family of the font that we want to apply to the text."
},
{
"code": null,
"e": 5184,
"s": 5077,
"text": "family − This is of a String type and represents the family of the font that we want to apply to the text."
},
{
"code": null,
"e": 5397,
"s": 5184,
"text": "weight − This property represents the weight of the font. It accepts 9 values, which are − FontWeight.BLACK, FontWeight.BOLD, FontWeight.EXTRA_BOLD, FontWeight.EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN."
},
{
"code": null,
"e": 5610,
"s": 5397,
"text": "weight − This property represents the weight of the font. It accepts 9 values, which are − FontWeight.BLACK, FontWeight.BOLD, FontWeight.EXTRA_BOLD, FontWeight.EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN."
},
{
"code": null,
"e": 5749,
"s": 5610,
"text": "posture − This property represents the font posture (regular or italic). It accepts two values FontPosture.REGULAR and FontPosture.ITALIC."
},
{
"code": null,
"e": 5888,
"s": 5749,
"text": "posture − This property represents the font posture (regular or italic). It accepts two values FontPosture.REGULAR and FontPosture.ITALIC."
},
{
"code": null,
"e": 5967,
"s": 5888,
"text": "size − This property is of type double and it represents the size of the font."
},
{
"code": null,
"e": 6046,
"s": 5967,
"text": "size − This property is of type double and it represents the size of the font."
},
{
"code": null,
"e": 6107,
"s": 6046,
"text": "You can set font to the text by using the following method −"
},
{
"code": null,
"e": 6186,
"s": 6107,
"text": "text.setFont(Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 20));\n"
},
{
"code": null,
"e": 6376,
"s": 6186,
"text": "The following program is an example demonstrating how to set font of the text node in JavaFX. In here, we are setting the font to Verdana, weight to bold, posture to regular and size to 20."
},
{
"code": null,
"e": 6437,
"s": 6376,
"text": "Save this code in a file with the name TextFontExample.java."
},
{
"code": null,
"e": 7717,
"s": 6437,
"text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.stage.Stage; \nimport javafx.scene.text.Font; \nimport javafx.scene.text.FontPosture; \nimport javafx.scene.text.FontWeight; \nimport javafx.scene.text.Text; \n \npublic class TextFontExample extends Application { \n @Override \n public void start(Stage stage) { \n //Creating a Text object \n Text text = new Text(); \n \n //Setting font to the text \n text.setFont(Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 20)); \n \n //setting the position of the text\n text.setX(50); \n text.setY(130); \n \n //Setting the text to be added. \n text.setText(\"Hi how are you\"); \n \n //Creating a Group object \n Group root = new Group(text); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Setting Font to the text\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} "
},
{
"code": null,
"e": 7811,
"s": 7717,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 7862,
"s": 7811,
"text": "javac TextFontExample.java \njava TextFontExample \n"
},
{
"code": null,
"e": 7977,
"s": 7862,
"text": "On executing, the above program generates a JavaFX window displaying the text with the specified font as follows −"
},
{
"code": null,
"e": 8146,
"s": 7977,
"text": "The Text class also inherits the class Shape of the package. Therefore, you can use javafx.scene.shape with which you can set the stroke and color to the text node too."
},
{
"code": null,
"e": 8251,
"s": 8146,
"text": "You can set the color to the text using the setFill() method of the shape (inherited) class as follows −"
},
{
"code": null,
"e": 8280,
"s": 8251,
"text": "text.setFill(Color.BEIGE); \n"
},
{
"code": null,
"e": 8450,
"s": 8280,
"text": "Similarly, you can set the stroke color of the text using the method setStroke(). While the width of the stroke can be set using the method setStrokeWidth() as follows −"
},
{
"code": null,
"e": 8622,
"s": 8450,
"text": "//Setting the color \ntext.setFill(Color.BROWN); \n \n//Setting the Stroke \ntext.setStrokeWidth(2); \n \n//Setting the stroke color \ntext.setStroke(Color.BLUE); \n"
},
{
"code": null,
"e": 8849,
"s": 8622,
"text": "The following program is an example that demonstrates how to set the color, strokeWidth and strokeColor, of the text node. In this code, we are setting stroke color to – blue, text color to – brown and the stroke width to – 2."
},
{
"code": null,
"e": 8908,
"s": 8849,
"text": "Save this code in a file with the name StrokeExample.java."
},
{
"code": null,
"e": 10436,
"s": 8908,
"text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.paint.Color; \nimport javafx.stage.Stage; \nimport javafx.scene.text.Font; \nimport javafx.scene.text.FontPosture; \nimport javafx.scene.text.FontWeight; \nimport javafx.scene.text.Text; \n \npublic class StrokeExample extends Application { \n @Override \n public void start(Stage stage) { \n //Creating a Text object \n Text text = new Text(); \n \n //Setting font to the text \n text.setFont(Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 50)); \n \n //setting the position of the text \n text.setX(50); \n text.setY(130); \n \n //Setting the color \n text.setFill(Color.BROWN); \n \n //Setting the Stroke \n text.setStrokeWidth(2); \n \n // Setting the stroke color\n text.setStroke(Color.BLUE); \n \n //Setting the text to be added. \n text.setText(\"Hi how are you\"); \n \n //Creating a Group object \n Group root = new Group(text); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Setting font to the text\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} "
},
{
"code": null,
"e": 10530,
"s": 10436,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 10577,
"s": 10530,
"text": "javac StrokeExample.java \njava StrokeExample \n"
},
{
"code": null,
"e": 10715,
"s": 10577,
"text": "On executing, the above program generates a JavaFX window displaying the text with the specified stroke and color attributes as follows −"
},
{
"code": null,
"e": 10881,
"s": 10715,
"text": "You can also apply decorations such as strike through; in which case a line is passed through the text. You can underline a text using the methods of the Text class."
},
{
"code": null,
"e": 11079,
"s": 10881,
"text": "You can strike through the text using the method setStrikethrough(). This accepts a Boolean value, pass the value true to this method to strike through the text as shown in the following code box −"
},
{
"code": null,
"e": 11140,
"s": 11079,
"text": "//Striking through the text \ntext1.setStrikethrough(true); \n"
},
{
"code": null,
"e": 11250,
"s": 11140,
"text": "In the same way, you can underline a text by passing the value true to the method setUnderLine() as follows −"
},
{
"code": null,
"e": 11305,
"s": 11250,
"text": "//underlining the text \ntext2.setUnderline(true);\n"
},
{
"code": null,
"e": 11491,
"s": 11305,
"text": "The following program is an example demonstrating how to apply decorations such as underline or strike through to a text. Save this code in a file with the name DecorationsExample.java."
},
{
"code": null,
"e": 13202,
"s": 11491,
"text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.stage.Stage; \nimport javafx.scene.text.Font; \nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight; \nimport javafx.scene.text.Text; \n \npublic class DecorationsExample extends Application { \n @Override \n public void start(Stage stage) { \n //Creating a Text_Example object \n Text text1 = new Text(\"Hi how are you\"); \n \n //Setting font to the text \n text1.setFont(Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 20));\n \n //setting the position of the text \n text1.setX(50); \n text1.setY(75); \n \n //Striking through the text \n text1.setStrikethrough(true); \n \n //Creating a Text_Example object \n Text text2 = new Text(\"Welcome to Tutorialspoint\"); \n \n //Setting font to the text \n text2.setFont(Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 20));\n \n //setting the position of the text \n text2.setX(50); \n text2.setY(150); \n \n //underlining the text \n text2.setUnderline(true); \n \n //Creating a Group object \n Group root = new Group(text1, text2); \n \n //Creating a scene object\n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Decorations Example\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}"
},
{
"code": null,
"e": 13296,
"s": 13202,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 13352,
"s": 13296,
"text": "javac DecorationsExample.java \njava DecorationsExample\n"
},
{
"code": null,
"e": 13427,
"s": 13352,
"text": "On executing, the above program generates a JavaFX window as shown below −"
},
{
"code": null,
"e": 13462,
"s": 13427,
"text": "\n 33 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 13473,
"s": 13462,
"text": " Syed Raza"
},
{
"code": null,
"e": 13509,
"s": 13473,
"text": "\n 64 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 13545,
"s": 13509,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 13578,
"s": 13545,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 13614,
"s": 13578,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 13621,
"s": 13614,
"text": " Print"
},
{
"code": null,
"e": 13632,
"s": 13621,
"text": " Add Notes"
}
] |
Bucket Sort
|
In the Bucket Sorting technique, the data items are distributed in a set of buckets. Each bucket can hold a similar type of data. After distributing, each bucket is sorted using another sorting algorithm. After that, all elements are gathered on the main list to get the sorted form.
Time Complexity: O(n + k) for best case and average case and O(n^2) for the worst case.
Time Complexity: O(n + k) for best case and average case and O(n^2) for the worst case.
Space Complexity: O(nk) for worst case
Space Complexity: O(nk) for worst case
Input:
A list of unsorted data: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
Array before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
Output:
Array after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79
bucketSort(array, size)
Input − An array of data, and the total number in the array
Output − The sorted Array
Begin
for i := 0 to size-1 do
insert array[i] into the bucket index (size * array[i])
done
for i := 0 to size-1 do
sort bucket[i]
done
for i := 0 to size -1 do
gather items of bucket[i] and put in array
done
End
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void display(float *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void bucketSort(float *array, int size) {
vector<float> bucket[size];
for(int i = 0; i<size; i++) { //put elements into different buckets
bucket[int(size*array[i])].push_back(array[i]);
}
for(int i = 0; i<size; i++) {
sort(bucket[i].begin(), bucket[i].end()); //sort individual vectors
}
int index = 0;
for(int i = 0; i<size; i++) {
while(!bucket[i].empty()) {
array[index++] = *(bucket[i].begin());
bucket[i].erase(bucket[i].begin());
}
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
float arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
bucketSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}
Enter the number of elements: 10
Enter elements:
0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
Array before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69
Array after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79
|
[
{
"code": null,
"e": 1346,
"s": 1062,
"text": "In the Bucket Sorting technique, the data items are distributed in a set of buckets. Each bucket can hold a similar type of data. After distributing, each bucket is sorted using another sorting algorithm. After that, all elements are gathered on the main list to get the sorted form."
},
{
"code": null,
"e": 1434,
"s": 1346,
"text": "Time Complexity: O(n + k) for best case and average case and O(n^2) for the worst case."
},
{
"code": null,
"e": 1522,
"s": 1434,
"text": "Time Complexity: O(n + k) for best case and average case and O(n^2) for the worst case."
},
{
"code": null,
"e": 1561,
"s": 1522,
"text": "Space Complexity: O(nk) for worst case"
},
{
"code": null,
"e": 1600,
"s": 1561,
"text": "Space Complexity: O(nk) for worst case"
},
{
"code": null,
"e": 1833,
"s": 1600,
"text": "Input:\nA list of unsorted data: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69\nArray before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69\nOutput:\nArray after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79"
},
{
"code": null,
"e": 1857,
"s": 1833,
"text": "bucketSort(array, size)"
},
{
"code": null,
"e": 1917,
"s": 1857,
"text": "Input − An array of data, and the total number in the array"
},
{
"code": null,
"e": 1943,
"s": 1917,
"text": "Output − The sorted Array"
},
{
"code": null,
"e": 2193,
"s": 1943,
"text": "Begin\n for i := 0 to size-1 do\n insert array[i] into the bucket index (size * array[i])\n done\n\n for i := 0 to size-1 do\n sort bucket[i]\n done\n\n for i := 0 to size -1 do\n gather items of bucket[i] and put in array\n done\nEnd"
},
{
"code": null,
"e": 3284,
"s": 2193,
"text": "#include<iostream>\n#include<vector>\n#include<algorithm>\nusing namespace std;\n\nvoid display(float *array, int size) {\n for(int i = 0; i<size; i++)\n cout << array[i] << \" \";\n cout << endl;\n}\n\nvoid bucketSort(float *array, int size) {\n vector<float> bucket[size];\n for(int i = 0; i<size; i++) { //put elements into different buckets\n bucket[int(size*array[i])].push_back(array[i]);\n }\n\n for(int i = 0; i<size; i++) {\n sort(bucket[i].begin(), bucket[i].end()); //sort individual vectors\n }\n\n int index = 0;\n for(int i = 0; i<size; i++) {\n while(!bucket[i].empty()) {\n array[index++] = *(bucket[i].begin());\n bucket[i].erase(bucket[i].begin());\n }\n }\n}\n\nint main() {\n int n;\n cout << \"Enter the number of elements: \";\n cin >> n;\n float arr[n]; //create an array with given number of elements\n cout << \"Enter elements:\" << endl;\n\n for(int i = 0; i<n; i++) {\n cin >> arr[i];\n }\n\n cout << \"Array before Sorting: \";\n display(arr, n);\n bucketSort(arr, n);\n\n cout << \"Array after Sorting: \";\n display(arr, n);\n}"
},
{
"code": null,
"e": 3526,
"s": 3284,
"text": "Enter the number of elements: 10\nEnter elements:\n0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69\nArray before Sorting: 0.25 0.36 0.58 0.41 0.29 0.22 0.45 0.79 0.01 0.69\nArray after Sorting: 0.01 0.22 0.25 0.29 0.36 0.41 0.45 0.58 0.69 0.79"
}
] |
How to count the number of characters (including spaces) in a text file using Java?
|
To count the number of lines in a file
Instantiate the FileInputStream class by passing an object of the required file as parameter to its constructor.
Instantiate the FileInputStream class by passing an object of the required file as parameter to its constructor.
Read the contents of the file to a byte array using the read() method of FileInputStream class.
Read the contents of the file to a byte array using the read() method of FileInputStream class.
Instantiate a String class by passing the byte array obtained, as a parameter its constructor.
Instantiate a String class by passing the byte array obtained, as a parameter its constructor.
Finally, find the length of the string.
Finally, find the length of the string.
import java.io.File;
import java.io.FileInputStream;
public class NumberOfCharacters {
public static void main(String args[]) throws Exception{
File file = new File("data");
FileInputStream fis = new FileInputStream(file);
byte[] byteArray = new byte[(int)file.length()];
fis.read(byteArray);
String data = new String(byteArray);
System.out.println("Number of characters in the String: "+data.length());
}
}
Number of characters in the String: 3
|
[
{
"code": null,
"e": 1101,
"s": 1062,
"text": "To count the number of lines in a file"
},
{
"code": null,
"e": 1214,
"s": 1101,
"text": "Instantiate the FileInputStream class by passing an object of the required file as parameter to its constructor."
},
{
"code": null,
"e": 1327,
"s": 1214,
"text": "Instantiate the FileInputStream class by passing an object of the required file as parameter to its constructor."
},
{
"code": null,
"e": 1423,
"s": 1327,
"text": "Read the contents of the file to a byte array using the read() method of FileInputStream class."
},
{
"code": null,
"e": 1519,
"s": 1423,
"text": "Read the contents of the file to a byte array using the read() method of FileInputStream class."
},
{
"code": null,
"e": 1614,
"s": 1519,
"text": "Instantiate a String class by passing the byte array obtained, as a parameter its constructor."
},
{
"code": null,
"e": 1709,
"s": 1614,
"text": "Instantiate a String class by passing the byte array obtained, as a parameter its constructor."
},
{
"code": null,
"e": 1749,
"s": 1709,
"text": "Finally, find the length of the string."
},
{
"code": null,
"e": 1789,
"s": 1749,
"text": "Finally, find the length of the string."
},
{
"code": null,
"e": 2241,
"s": 1789,
"text": "import java.io.File;\nimport java.io.FileInputStream;\n\npublic class NumberOfCharacters {\npublic static void main(String args[]) throws Exception{\n File file = new File(\"data\");\n FileInputStream fis = new FileInputStream(file);\n byte[] byteArray = new byte[(int)file.length()];\n \n fis.read(byteArray);\n String data = new String(byteArray);\n System.out.println(\"Number of characters in the String: \"+data.length());\n }\n}"
},
{
"code": null,
"e": 2280,
"s": 2241,
"text": "Number of characters in the String: 3\n"
}
] |
Regular Expression in Python with Examples?
|
Regular expressions is a kind of programming language which is used to identify whether a pattern exists in a given sequence of characters (string) or not.
Regular expression or Regex is a sequence of characters that is used to check if a string contains the specified search pattern.
To use RegEx module, python comes with built-in package called re, which we need to work with Regular expression. To use RegEx module, just import re module.
import re
import re
txt = "Use of python in Machine Learning"
x = re.search("^Use.*Learning$", txt)
if (x):
print("YES! We have a match!")
else:
print("No match")
YES! We have a match!
The re module offers couples of functions that allows us to search a string for a match.
Metacharacters in RegEx are characters with a special meaning.
Special sequences in RegEx is a \ followed by one of the characters listed below and has a special meaning -
A set in RegEx is a set of characters inside a pair of square brackets [] having some special meaning.
The findall() function returns a list containg all matches.
#Print a list of all matches (“in”) from a text
import re
txt = "Use of python in Machine Learning"
x = re.findall("in", txt)
print(x)
['in', 'in', 'in']
Above output display list contains all the matches in the order they are found. However, if no match found, an empty list is displayed.
Just change the below line in your above program, “pattern” which is not there in the text or string.
x = re.findall("Hello", txt)
[]
The search() function searches the string and returns a match object if match is found.
However, if there are more than one match, only the first occurrence of the match will be returned.
import re
txt = "Python is one of the most popular languages around the world"
searchObj = re.search("\s", txt)
print("The first white-space character is located in position: ", searchObj.start())
The first white-space character is located in position: 6
However, if no match found then None is returned.
The split() function in RegEx returns a list where the string has been split at each match -
# Split at each white-space character
import re
string = "Python is one of the most popular languages around the world"
searchObj = re.split("\s", string)
print(searchObj)
['Python', 'is', 'one', 'of', 'the', 'most', 'popular', 'languages', 'around', 'the', 'world']
The sub() function in RegEx is to replace the match with the text of your choice.
#Replace every white-space in the string with _:
import re
string = "Python is one of the most popular language around the world"
searchObj = re.sub("\s", "_", string)
print(searchObj)
Python_is_one_of_the_most_popular_language_around_the_world
A match object in RegEx is an object containing information about the search and the result. In no match found, None is returned.
Example - Search a string and returned match object.
import re
string = "Python is one of the most popular language around the world"
searchObj = re.search("on", string)
print(searchObj)
<_sre.SRE_Match object; span=(4, 6), match='on'>
The match object has properties and methods used to retrieve information about the search, and the Result.
.span() – returns a tuple containing the start and end position of the match found.
.span() – returns a tuple containing the start and end position of the match found.
.string – returns the string passed into the function.
.string – returns the string passed into the function.
.group() – returns the part of the string where there was a match.
.group() – returns the part of the string where there was a match.
Example - Print the part of the string where there was a match.
#Looks for any words that starts with the an upper case “P”:
import re
string = "Python is one of the most popular language around the world"
searchObj = re.search(r"\bP\w+", string)
print(searchObj)
<_sre.SRE_Match object; span=(0, 6), match='Python'>
|
[
{
"code": null,
"e": 1218,
"s": 1062,
"text": "Regular expressions is a kind of programming language which is used to identify whether a pattern exists in a given sequence of characters (string) or not."
},
{
"code": null,
"e": 1347,
"s": 1218,
"text": "Regular expression or Regex is a sequence of characters that is used to check if a string contains the specified search pattern."
},
{
"code": null,
"e": 1505,
"s": 1347,
"text": "To use RegEx module, python comes with built-in package called re, which we need to work with Regular expression. To use RegEx module, just import re module."
},
{
"code": null,
"e": 1515,
"s": 1505,
"text": "import re"
},
{
"code": null,
"e": 1674,
"s": 1515,
"text": "import re\ntxt = \"Use of python in Machine Learning\"\nx = re.search(\"^Use.*Learning$\", txt)\nif (x):\n print(\"YES! We have a match!\")\nelse:\n print(\"No match\")"
},
{
"code": null,
"e": 1696,
"s": 1674,
"text": "YES! We have a match!"
},
{
"code": null,
"e": 1785,
"s": 1696,
"text": "The re module offers couples of functions that allows us to search a string for a match."
},
{
"code": null,
"e": 1848,
"s": 1785,
"text": "Metacharacters in RegEx are characters with a special meaning."
},
{
"code": null,
"e": 1957,
"s": 1848,
"text": "Special sequences in RegEx is a \\ followed by one of the characters listed below and has a special meaning -"
},
{
"code": null,
"e": 2060,
"s": 1957,
"text": "A set in RegEx is a set of characters inside a pair of square brackets [] having some special meaning."
},
{
"code": null,
"e": 2122,
"s": 2062,
"text": "The findall() function returns a list containg all matches."
},
{
"code": null,
"e": 2257,
"s": 2122,
"text": "#Print a list of all matches (“in”) from a text\nimport re\ntxt = \"Use of python in Machine Learning\"\nx = re.findall(\"in\", txt)\nprint(x)"
},
{
"code": null,
"e": 2276,
"s": 2257,
"text": "['in', 'in', 'in']"
},
{
"code": null,
"e": 2412,
"s": 2276,
"text": "Above output display list contains all the matches in the order they are found. However, if no match found, an empty list is displayed."
},
{
"code": null,
"e": 2514,
"s": 2412,
"text": "Just change the below line in your above program, “pattern” which is not there in the text or string."
},
{
"code": null,
"e": 2543,
"s": 2514,
"text": "x = re.findall(\"Hello\", txt)"
},
{
"code": null,
"e": 2546,
"s": 2543,
"text": "[]"
},
{
"code": null,
"e": 2634,
"s": 2546,
"text": "The search() function searches the string and returns a match object if match is found."
},
{
"code": null,
"e": 2734,
"s": 2634,
"text": "However, if there are more than one match, only the first occurrence of the match will be returned."
},
{
"code": null,
"e": 2931,
"s": 2734,
"text": "import re\ntxt = \"Python is one of the most popular languages around the world\"\nsearchObj = re.search(\"\\s\", txt)\nprint(\"The first white-space character is located in position: \", searchObj.start())"
},
{
"code": null,
"e": 2989,
"s": 2931,
"text": "The first white-space character is located in position: 6"
},
{
"code": null,
"e": 3039,
"s": 2989,
"text": "However, if no match found then None is returned."
},
{
"code": null,
"e": 3132,
"s": 3039,
"text": "The split() function in RegEx returns a list where the string has been split at each match -"
},
{
"code": null,
"e": 3304,
"s": 3132,
"text": "# Split at each white-space character\nimport re\nstring = \"Python is one of the most popular languages around the world\"\nsearchObj = re.split(\"\\s\", string)\nprint(searchObj)"
},
{
"code": null,
"e": 3399,
"s": 3304,
"text": "['Python', 'is', 'one', 'of', 'the', 'most', 'popular', 'languages', 'around', 'the', 'world']"
},
{
"code": null,
"e": 3481,
"s": 3399,
"text": "The sub() function in RegEx is to replace the match with the text of your choice."
},
{
"code": null,
"e": 3666,
"s": 3481,
"text": "#Replace every white-space in the string with _:\nimport re\nstring = \"Python is one of the most popular language around the world\"\nsearchObj = re.sub(\"\\s\", \"_\", string)\nprint(searchObj)"
},
{
"code": null,
"e": 3726,
"s": 3666,
"text": "Python_is_one_of_the_most_popular_language_around_the_world"
},
{
"code": null,
"e": 3856,
"s": 3726,
"text": "A match object in RegEx is an object containing information about the search and the result. In no match found, None is returned."
},
{
"code": null,
"e": 3909,
"s": 3856,
"text": "Example - Search a string and returned match object."
},
{
"code": null,
"e": 4043,
"s": 3909,
"text": "import re\nstring = \"Python is one of the most popular language around the world\"\nsearchObj = re.search(\"on\", string)\nprint(searchObj)"
},
{
"code": null,
"e": 4092,
"s": 4043,
"text": "<_sre.SRE_Match object; span=(4, 6), match='on'>"
},
{
"code": null,
"e": 4199,
"s": 4092,
"text": "The match object has properties and methods used to retrieve information about the search, and the Result."
},
{
"code": null,
"e": 4283,
"s": 4199,
"text": ".span() – returns a tuple containing the start and end position of the match found."
},
{
"code": null,
"e": 4367,
"s": 4283,
"text": ".span() – returns a tuple containing the start and end position of the match found."
},
{
"code": null,
"e": 4422,
"s": 4367,
"text": ".string – returns the string passed into the function."
},
{
"code": null,
"e": 4477,
"s": 4422,
"text": ".string – returns the string passed into the function."
},
{
"code": null,
"e": 4544,
"s": 4477,
"text": ".group() – returns the part of the string where there was a match."
},
{
"code": null,
"e": 4611,
"s": 4544,
"text": ".group() – returns the part of the string where there was a match."
},
{
"code": null,
"e": 4675,
"s": 4611,
"text": "Example - Print the part of the string where there was a match."
},
{
"code": null,
"e": 4875,
"s": 4675,
"text": "#Looks for any words that starts with the an upper case “P”:\nimport re\nstring = \"Python is one of the most popular language around the world\"\nsearchObj = re.search(r\"\\bP\\w+\", string)\nprint(searchObj)"
},
{
"code": null,
"e": 4928,
"s": 4875,
"text": "<_sre.SRE_Match object; span=(0, 6), match='Python'>"
}
] |
Randomize string in C#
|
To randomize string, firstly use Random class −
Random r = new Random();
Now, use the Next() method with OrderBy() −
string random = new string(str.ToCharArray().OrderBy(s => (r.Next(2) % 2) == 0).ToArray());
Here is the compete code that displays randomize string −
Live Demo
using System;
using System.IO;
using System.Linq;
class Demo {
static void Main() {
const string str = "electronics";
Random r = new Random();
string random = new string(str.ToCharArray().OrderBy(s => (r.Next(2) % 2) == 0).ToArray());
Console.WriteLine("String = {0}", str);
Console.WriteLine("Random String = {0}",random);
Console.Read();
}
}
String = electronics
Random String = lericsecton
|
[
{
"code": null,
"e": 1110,
"s": 1062,
"text": "To randomize string, firstly use Random class −"
},
{
"code": null,
"e": 1135,
"s": 1110,
"text": "Random r = new Random();"
},
{
"code": null,
"e": 1179,
"s": 1135,
"text": "Now, use the Next() method with OrderBy() −"
},
{
"code": null,
"e": 1271,
"s": 1179,
"text": "string random = new string(str.ToCharArray().OrderBy(s => (r.Next(2) % 2) == 0).ToArray());"
},
{
"code": null,
"e": 1329,
"s": 1271,
"text": "Here is the compete code that displays randomize string −"
},
{
"code": null,
"e": 1340,
"s": 1329,
"text": " Live Demo"
},
{
"code": null,
"e": 1726,
"s": 1340,
"text": "using System;\nusing System.IO;\nusing System.Linq;\nclass Demo {\n static void Main() {\n const string str = \"electronics\";\n Random r = new Random();\n string random = new string(str.ToCharArray().OrderBy(s => (r.Next(2) % 2) == 0).ToArray());\n Console.WriteLine(\"String = {0}\", str);\n Console.WriteLine(\"Random String = {0}\",random);\n Console.Read();\n }\n}"
},
{
"code": null,
"e": 1775,
"s": 1726,
"text": "String = electronics\nRandom String = lericsecton"
}
] |
__init_subclass__ in Python - GeeksforGeeks
|
22 Jun, 2020
Prerequisites: Python Classes and Objects, Inheritance in Python
Regardless of any programming languages, Inheritance is one of the most important topics in Object-Oriented Programming Concepts. Inheritance is a concept of defining a class in terms of another class. As per inheritance, we know that a superclass reference can hold its subclass reference. We all know that the behavior of the superclass can be altered according to the implementation of its sub-class(es).
But now, we can alter the behavior of the sub-class(es) by using __init_subclass__
# defining a SuperClassclass SuperClass: # defining __init_subclass__ method def __init_subclass__(cls, **kwargs): cls.default_name ="Inherited Class" # defining a SubClassclass SubClass(SuperClass): # an attribute of SubClass default_name ="SubClass" print(default_name) subclass = SubClass()print(subclass.default_name)
Output :
SubClass
Inherited Class
Understanding the code
In the above example, there are 2 classes(i.e Super Class and SubClass) and SubClass is inherited from SuperClass. default_name is an attribute of SubClass.
The value of attribute default_name is altered by SuperClass by using __init_subclass__ method.
cls is referred to the subclass(es) which are inherited. Keyword arguments(**kwargs) which are given to a new class are passed to the parent’s class __init_subclass__.
For compatibility with other subclasses using __init_subclass__, one should take out the needed keyword arguments and pass the others over to the base class(Super Class).
This __init_subclass__ closely look alike Decorator class. But where class decorators only affect the specific class they are applied to, __init_subclass__ solely applies to future sub-classes of the class defining the method. It means we can alter/define the behavior of any new classes which are inherited from super-class.Example:
# defining a SuperClassclass SuperClass: def __init_subclass__(cls, default_name, **kwargs): cls.default_name = default_name # defining a subclassclass SubClass1(SuperClass, default_name ="SubClass1"): pass # defining another subclassclass SubClass2(SuperClass, default_name ="SubClass2"): default_name = "InheritedClass" # references for subclassessubClass1 = SubClass1()subClass2 = SubClass2() print(subClass1.default_name)print(subClass2.default_name)
Output :
SubClass1
SubClass2
By this we can conclude that __init_subclass__ method is used to alter the behavior of subclasses which may be created in future.
Python-OOP
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
|
[
{
"code": null,
"e": 23697,
"s": 23669,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 23762,
"s": 23697,
"text": "Prerequisites: Python Classes and Objects, Inheritance in Python"
},
{
"code": null,
"e": 24170,
"s": 23762,
"text": "Regardless of any programming languages, Inheritance is one of the most important topics in Object-Oriented Programming Concepts. Inheritance is a concept of defining a class in terms of another class. As per inheritance, we know that a superclass reference can hold its subclass reference. We all know that the behavior of the superclass can be altered according to the implementation of its sub-class(es)."
},
{
"code": null,
"e": 24253,
"s": 24170,
"text": "But now, we can alter the behavior of the sub-class(es) by using __init_subclass__"
},
{
"code": "# defining a SuperClassclass SuperClass: # defining __init_subclass__ method def __init_subclass__(cls, **kwargs): cls.default_name =\"Inherited Class\" # defining a SubClassclass SubClass(SuperClass): # an attribute of SubClass default_name =\"SubClass\" print(default_name) subclass = SubClass()print(subclass.default_name)",
"e": 24606,
"s": 24253,
"text": null
},
{
"code": null,
"e": 24615,
"s": 24606,
"text": "Output :"
},
{
"code": null,
"e": 24641,
"s": 24615,
"text": "SubClass\nInherited Class\n"
},
{
"code": null,
"e": 24664,
"s": 24641,
"text": "Understanding the code"
},
{
"code": null,
"e": 24821,
"s": 24664,
"text": "In the above example, there are 2 classes(i.e Super Class and SubClass) and SubClass is inherited from SuperClass. default_name is an attribute of SubClass."
},
{
"code": null,
"e": 24917,
"s": 24821,
"text": "The value of attribute default_name is altered by SuperClass by using __init_subclass__ method."
},
{
"code": null,
"e": 25085,
"s": 24917,
"text": "cls is referred to the subclass(es) which are inherited. Keyword arguments(**kwargs) which are given to a new class are passed to the parent’s class __init_subclass__."
},
{
"code": null,
"e": 25256,
"s": 25085,
"text": "For compatibility with other subclasses using __init_subclass__, one should take out the needed keyword arguments and pass the others over to the base class(Super Class)."
},
{
"code": null,
"e": 25590,
"s": 25256,
"text": "This __init_subclass__ closely look alike Decorator class. But where class decorators only affect the specific class they are applied to, __init_subclass__ solely applies to future sub-classes of the class defining the method. It means we can alter/define the behavior of any new classes which are inherited from super-class.Example:"
},
{
"code": "# defining a SuperClassclass SuperClass: def __init_subclass__(cls, default_name, **kwargs): cls.default_name = default_name # defining a subclassclass SubClass1(SuperClass, default_name =\"SubClass1\"): pass # defining another subclassclass SubClass2(SuperClass, default_name =\"SubClass2\"): default_name = \"InheritedClass\" # references for subclassessubClass1 = SubClass1()subClass2 = SubClass2() print(subClass1.default_name)print(subClass2.default_name)",
"e": 26067,
"s": 25590,
"text": null
},
{
"code": null,
"e": 26076,
"s": 26067,
"text": "Output :"
},
{
"code": null,
"e": 26097,
"s": 26076,
"text": "SubClass1\nSubClass2\n"
},
{
"code": null,
"e": 26227,
"s": 26097,
"text": "By this we can conclude that __init_subclass__ method is used to alter the behavior of subclasses which may be created in future."
},
{
"code": null,
"e": 26238,
"s": 26227,
"text": "Python-OOP"
},
{
"code": null,
"e": 26258,
"s": 26238,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 26265,
"s": 26258,
"text": "Python"
},
{
"code": null,
"e": 26363,
"s": 26265,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26372,
"s": 26363,
"text": "Comments"
},
{
"code": null,
"e": 26385,
"s": 26372,
"text": "Old Comments"
},
{
"code": null,
"e": 26403,
"s": 26385,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26438,
"s": 26403,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26460,
"s": 26438,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26492,
"s": 26460,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26522,
"s": 26492,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26564,
"s": 26522,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26590,
"s": 26564,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26633,
"s": 26590,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26677,
"s": 26633,
"text": "Reading and Writing to text files in Python"
}
] |
How to get first letter of each word using regular expression in Java?
|
The metacharacter “\b” matches for the word boundaries and [a-zA-Z] matches one character from the English alphabet (both cases). In short, the expression \\b[a-zA-Z] matches one single character from the English alphabet, both cases after every word boundary.
Therefore, to retrieve the first letter of each word −
Compile the above expression of the compile() method of the Pattern class.
Compile the above expression of the compile() method of the Pattern class.
Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class.
Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class.
Finally, for each match get the matched characters by invoking the group() method.
Finally, for each match get the matched characters by invoking the group() method.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FirstLetterExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter sample text: ");
String data = sc.nextLine();
String regex = "\\b[a-zA-Z]";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Creating a Matcher object
Matcher matcher = pattern.matcher(data);
System.out.println("First letter of each word from the given string: ");
while(matcher.find()) {
System.out.print(matcher.group()+" ");
}
}
}
Enter sample text:
National Intelligence Agency Research & Analysis Wing
First letter of each word from the given string:
N I A R A W
|
[
{
"code": null,
"e": 1323,
"s": 1062,
"text": "The metacharacter “\\b” matches for the word boundaries and [a-zA-Z] matches one character from the English alphabet (both cases). In short, the expression \\\\b[a-zA-Z] matches one single character from the English alphabet, both cases after every word boundary."
},
{
"code": null,
"e": 1378,
"s": 1323,
"text": "Therefore, to retrieve the first letter of each word −"
},
{
"code": null,
"e": 1453,
"s": 1378,
"text": "Compile the above expression of the compile() method of the Pattern class."
},
{
"code": null,
"e": 1528,
"s": 1453,
"text": "Compile the above expression of the compile() method of the Pattern class."
},
{
"code": null,
"e": 1648,
"s": 1528,
"text": "Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class."
},
{
"code": null,
"e": 1768,
"s": 1648,
"text": "Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class."
},
{
"code": null,
"e": 1851,
"s": 1768,
"text": "Finally, for each match get the matched characters by invoking the group() method."
},
{
"code": null,
"e": 1934,
"s": 1851,
"text": "Finally, for each match get the matched characters by invoking the group() method."
},
{
"code": null,
"e": 2600,
"s": 1934,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class FirstLetterExample {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter sample text: \");\n String data = sc.nextLine();\n String regex = \"\\\\b[a-zA-Z]\";\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n //Creating a Matcher object\n Matcher matcher = pattern.matcher(data);\n System.out.println(\"First letter of each word from the given string: \");\n while(matcher.find()) {\n System.out.print(matcher.group()+\" \");\n }\n }\n}"
},
{
"code": null,
"e": 2734,
"s": 2600,
"text": "Enter sample text:\nNational Intelligence Agency Research & Analysis Wing\nFirst letter of each word from the given string:\nN I A R A W"
}
] |
SWING - Event Handling
|
In this chapter, you will learn about Events, its types, and also learn how to handle an event. Example is provided at the end of the chapter for better understanding.
Change in the state of an object is known as Event, i.e., event describes the change in the state of the source. Events are generated as a result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from the list, and scrolling the page are the activities that causes an event to occur.
The events can be broadly classified into two categories −
Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc.
Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc.
Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events.
Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events.
Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an event handler, that is executed when an event occurs.
Java uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.
The Delegation Event Model has the following key participants.
Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide us with classes for the source object.
Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide us with classes for the source object.
Listener − It is also known as event handler. The listener is responsible for generating a response to an event. From the point of view of Java implementation, the listener is also an object. The listener waits till it receives an event. Once the event is received, the listener processes the event and then returns.
Listener − It is also known as event handler. The listener is responsible for generating a response to an event. From the point of view of Java implementation, the listener is also an object. The listener waits till it receives an event. Once the event is received, the listener processes the event and then returns.
The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to a separate piece of code.
In this model, the listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listeners who want to receive them.
Step 1 − The user clicks the button and the event is generated.
Step 2 − The object of concerned event class is created automatically and information about the source and the event get populated within the same object.
Step 3 − Event object is forwarded to the method of the registered listener class.
Step 4 − The method is gets executed and returns.
In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods, which must be implemented by the listener class.
In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods, which must be implemented by the listener class.
If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a source object.
If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a source object.
These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represent an event method. In response to an event, java jre will fire callback method. All such callback methods are provided in listener interfaces.
If a component wants some listener to listen ot its events, the source must register itself to the listener.
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingControlDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingControlDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");
JButton okButton = new JButton("OK");
JButton submitButton = new JButton("Submit");
JButton cancelButton = new JButton("Cancel");
okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if( command.equals( "OK" )) {
statusLabel.setText("Ok Button clicked.");
} else if( command.equals( "Submit" ) ) {
statusLabel.setText("Submit Button clicked.");
} else {
statusLabel.setText("Cancel Button clicked.");
}
}
}
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\AWT>javac com\tutorialspoint\gui\SwingControlDemo.java
If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\AWT>java com.tutorialspoint.gui.SwingControlDemo
Verify the following output.
30 Lectures
3.5 hours
Pranjal Srivastava
13 Lectures
1 hours
Pranjal Srivastava
25 Lectures
4.5 hours
Emenwa Global, Ejike IfeanyiChukwu
14 Lectures
1.5 hours
Travis Rose
14 Lectures
1 hours
Travis Rose
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1931,
"s": 1763,
"text": "In this chapter, you will learn about Events, its types, and also learn how to handle an event. Example is provided at the end of the chapter for better understanding."
},
{
"code": null,
"e": 2341,
"s": 1931,
"text": "Change in the state of an object is known as Event, i.e., event describes the change in the state of the source. Events are generated as a result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from the list, and scrolling the page are the activities that causes an event to occur."
},
{
"code": null,
"e": 2400,
"s": 2341,
"text": "The events can be broadly classified into two categories −"
},
{
"code": null,
"e": 2741,
"s": 2400,
"text": "Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc."
},
{
"code": null,
"e": 3082,
"s": 2741,
"text": "Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc."
},
{
"code": null,
"e": 3298,
"s": 3082,
"text": "Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events."
},
{
"code": null,
"e": 3514,
"s": 3298,
"text": "Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events."
},
{
"code": null,
"e": 3722,
"s": 3514,
"text": "Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an event handler, that is executed when an event occurs."
},
{
"code": null,
"e": 3858,
"s": 3722,
"text": "Java uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events."
},
{
"code": null,
"e": 3921,
"s": 3858,
"text": "The Delegation Event Model has the following key participants."
},
{
"code": null,
"e": 4120,
"s": 3921,
"text": "Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide us with classes for the source object."
},
{
"code": null,
"e": 4319,
"s": 4120,
"text": "Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide us with classes for the source object."
},
{
"code": null,
"e": 4636,
"s": 4319,
"text": "Listener − It is also known as event handler. The listener is responsible for generating a response to an event. From the point of view of Java implementation, the listener is also an object. The listener waits till it receives an event. Once the event is received, the listener processes the event and then returns."
},
{
"code": null,
"e": 4953,
"s": 4636,
"text": "Listener − It is also known as event handler. The listener is responsible for generating a response to an event. From the point of view of Java implementation, the listener is also an object. The listener waits till it receives an event. Once the event is received, the listener processes the event and then returns."
},
{
"code": null,
"e": 5183,
"s": 4953,
"text": "The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to a separate piece of code."
},
{
"code": null,
"e": 5452,
"s": 5183,
"text": "In this model, the listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listeners who want to receive them."
},
{
"code": null,
"e": 5516,
"s": 5452,
"text": "Step 1 − The user clicks the button and the event is generated."
},
{
"code": null,
"e": 5671,
"s": 5516,
"text": "Step 2 − The object of concerned event class is created automatically and information about the source and the event get populated within the same object."
},
{
"code": null,
"e": 5754,
"s": 5671,
"text": "Step 3 − Event object is forwarded to the method of the registered listener class."
},
{
"code": null,
"e": 5804,
"s": 5754,
"text": "Step 4 − The method is gets executed and returns."
},
{
"code": null,
"e": 6010,
"s": 5804,
"text": "In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods, which must be implemented by the listener class."
},
{
"code": null,
"e": 6216,
"s": 6010,
"text": "In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods, which must be implemented by the listener class."
},
{
"code": null,
"e": 6342,
"s": 6216,
"text": "If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a source object."
},
{
"code": null,
"e": 6468,
"s": 6342,
"text": "If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a source object."
},
{
"code": null,
"e": 6789,
"s": 6468,
"text": "These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represent an event method. In response to an event, java jre will fire callback method. All such callback methods are provided in listener interfaces."
},
{
"code": null,
"e": 6898,
"s": 6789,
"text": "If a component wants some listener to listen ot its events, the source must register itself to the listener."
},
{
"code": null,
"e": 7014,
"s": 6898,
"text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 7036,
"s": 7014,
"text": "SwingControlDemo.java"
},
{
"code": null,
"e": 9453,
"s": 7036,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class SwingControlDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n\n public SwingControlDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingControlDemo swingControlDemo = new SwingControlDemo(); \n swingControlDemo.showEventDemo(); \n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java SWING Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n\n headerLabel = new JLabel(\"\",JLabel.CENTER );\n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showEventDemo(){\n headerLabel.setText(\"Control in action: Button\"); \n\n JButton okButton = new JButton(\"OK\");\n JButton submitButton = new JButton(\"Submit\");\n JButton cancelButton = new JButton(\"Cancel\");\n\n okButton.setActionCommand(\"OK\");\n submitButton.setActionCommand(\"Submit\");\n cancelButton.setActionCommand(\"Cancel\");\n\n okButton.addActionListener(new ButtonClickListener()); \n submitButton.addActionListener(new ButtonClickListener()); \n cancelButton.addActionListener(new ButtonClickListener()); \n\n controlPanel.add(okButton);\n controlPanel.add(submitButton);\n controlPanel.add(cancelButton); \n\n mainFrame.setVisible(true); \n }\n private class ButtonClickListener implements ActionListener{\n public void actionPerformed(ActionEvent e) {\n String command = e.getActionCommand(); \n \n if( command.equals( \"OK\" )) {\n statusLabel.setText(\"Ok Button clicked.\");\n } else if( command.equals( \"Submit\" ) ) {\n statusLabel.setText(\"Submit Button clicked.\"); \n } else {\n statusLabel.setText(\"Cancel Button clicked.\");\n } \t\n }\t\t\n }\n}"
},
{
"code": null,
"e": 9549,
"s": 9453,
"text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command."
},
{
"code": null,
"e": 9608,
"s": 9549,
"text": "D:\\AWT>javac com\\tutorialspoint\\gui\\SwingControlDemo.java\n"
},
{
"code": null,
"e": 9713,
"s": 9608,
"text": "If no error occurs, it means the compilation is successful. Run the program using the following command."
},
{
"code": null,
"e": 9766,
"s": 9713,
"text": "D:\\AWT>java com.tutorialspoint.gui.SwingControlDemo\n"
},
{
"code": null,
"e": 9795,
"s": 9766,
"text": "Verify the following output."
},
{
"code": null,
"e": 9830,
"s": 9795,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9850,
"s": 9830,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 9883,
"s": 9850,
"text": "\n 13 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9903,
"s": 9883,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 9938,
"s": 9903,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9974,
"s": 9938,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 10009,
"s": 9974,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10022,
"s": 10009,
"text": " Travis Rose"
},
{
"code": null,
"e": 10055,
"s": 10022,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10068,
"s": 10055,
"text": " Travis Rose"
},
{
"code": null,
"e": 10075,
"s": 10068,
"text": " Print"
},
{
"code": null,
"e": 10086,
"s": 10075,
"text": " Add Notes"
}
] |
Fortran - Basic Syntax
|
A Fortran program is made of a collection of program units like a main program, modules, and external subprograms or procedures.
Each program contains one main program and may or may not contain other program units. The syntax of the main program is as follows −
program program_name
implicit none
! type declaration statements
! executable statements
end program program_name
Let’s write a program that adds two numbers and prints the result −
program addNumbers
! This simple program adds two numbers
implicit none
! Type declarations
real :: a, b, result
! Executable statements
a = 12.0
b = 15.0
result = a + b
print *, 'The total is ', result
end program addNumbers
When you compile and execute the above program, it produces the following result −
The total is 27.0000000
Please note that −
All Fortran programs start with the keyword program and end with the keyword end program, followed by the name of the program.
All Fortran programs start with the keyword program and end with the keyword end program, followed by the name of the program.
The implicit none statement allows the compiler to check that all your variable types are declared properly. You must always use implicit none at the start of every program.
The implicit none statement allows the compiler to check that all your variable types are declared properly. You must always use implicit none at the start of every program.
Comments in Fortran are started with the exclamation mark (!), as all characters after this (except in a character string) are ignored by the compiler.
Comments in Fortran are started with the exclamation mark (!), as all characters after this (except in a character string) are ignored by the compiler.
The print * command displays data on the screen.
The print * command displays data on the screen.
Indentation of code lines is a good practice for keeping a program readable.
Indentation of code lines is a good practice for keeping a program readable.
Fortran allows both uppercase and lowercase letters. Fortran is case-insensitive, except for string literals.
Fortran allows both uppercase and lowercase letters. Fortran is case-insensitive, except for string literals.
The basic character set of Fortran contains −
the letters A ... Z and a ... z
the digits 0 ... 9
the underscore (_) character
the special characters = : + blank - * / ( ) [ ] , . $ ' ! " % & ; < > ?
Tokens are made of characters in the basic character set. A token could be a keyword, an identifier, a constant, a string literal, or a symbol.
Program statements are made of tokens.
An identifier is a name used to identify a variable, procedure, or any other user-defined item. A name in Fortran must follow the following rules −
It cannot be longer than 31 characters.
It cannot be longer than 31 characters.
It must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores (_).
It must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores (_).
First character of a name must be a letter.
First character of a name must be a letter.
Names are case-insensitive
Names are case-insensitive
Keywords are special words, reserved for the language. These reserved words cannot be used as identifiers or names.
The following table, lists the Fortran keywords −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2275,
"s": 2146,
"text": "A Fortran program is made of a collection of program units like a main program, modules, and external subprograms or procedures."
},
{
"code": null,
"e": 2409,
"s": 2275,
"text": "Each program contains one main program and may or may not contain other program units. The syntax of the main program is as follows −"
},
{
"code": null,
"e": 2539,
"s": 2409,
"text": "program program_name\nimplicit none \n\n! type declaration statements \n! executable statements \n\nend program program_name"
},
{
"code": null,
"e": 2607,
"s": 2539,
"text": "Let’s write a program that adds two numbers and prints the result −"
},
{
"code": null,
"e": 2855,
"s": 2607,
"text": "program addNumbers\n\n! This simple program adds two numbers\n implicit none\n\n! Type declarations\n real :: a, b, result\n\n! Executable statements\n a = 12.0\n b = 15.0\n result = a + b\n print *, 'The total is ', result\n\nend program addNumbers"
},
{
"code": null,
"e": 2938,
"s": 2855,
"text": "When you compile and execute the above program, it produces the following result −"
},
{
"code": null,
"e": 2967,
"s": 2938,
"text": "The total is 27.0000000 \n"
},
{
"code": null,
"e": 2986,
"s": 2967,
"text": "Please note that −"
},
{
"code": null,
"e": 3113,
"s": 2986,
"text": "All Fortran programs start with the keyword program and end with the keyword end program, followed by the name of the program."
},
{
"code": null,
"e": 3240,
"s": 3113,
"text": "All Fortran programs start with the keyword program and end with the keyword end program, followed by the name of the program."
},
{
"code": null,
"e": 3414,
"s": 3240,
"text": "The implicit none statement allows the compiler to check that all your variable types are declared properly. You must always use implicit none at the start of every program."
},
{
"code": null,
"e": 3588,
"s": 3414,
"text": "The implicit none statement allows the compiler to check that all your variable types are declared properly. You must always use implicit none at the start of every program."
},
{
"code": null,
"e": 3740,
"s": 3588,
"text": "Comments in Fortran are started with the exclamation mark (!), as all characters after this (except in a character string) are ignored by the compiler."
},
{
"code": null,
"e": 3892,
"s": 3740,
"text": "Comments in Fortran are started with the exclamation mark (!), as all characters after this (except in a character string) are ignored by the compiler."
},
{
"code": null,
"e": 3941,
"s": 3892,
"text": "The print * command displays data on the screen."
},
{
"code": null,
"e": 3990,
"s": 3941,
"text": "The print * command displays data on the screen."
},
{
"code": null,
"e": 4067,
"s": 3990,
"text": "Indentation of code lines is a good practice for keeping a program readable."
},
{
"code": null,
"e": 4144,
"s": 4067,
"text": "Indentation of code lines is a good practice for keeping a program readable."
},
{
"code": null,
"e": 4254,
"s": 4144,
"text": "Fortran allows both uppercase and lowercase letters. Fortran is case-insensitive, except for string literals."
},
{
"code": null,
"e": 4364,
"s": 4254,
"text": "Fortran allows both uppercase and lowercase letters. Fortran is case-insensitive, except for string literals."
},
{
"code": null,
"e": 4410,
"s": 4364,
"text": "The basic character set of Fortran contains −"
},
{
"code": null,
"e": 4442,
"s": 4410,
"text": "the letters A ... Z and a ... z"
},
{
"code": null,
"e": 4461,
"s": 4442,
"text": "the digits 0 ... 9"
},
{
"code": null,
"e": 4490,
"s": 4461,
"text": "the underscore (_) character"
},
{
"code": null,
"e": 4567,
"s": 4490,
"text": "the special characters = : + blank - * / ( ) [ ] , . $ ' ! \" % & ; < > ?"
},
{
"code": null,
"e": 4711,
"s": 4567,
"text": "Tokens are made of characters in the basic character set. A token could be a keyword, an identifier, a constant, a string literal, or a symbol."
},
{
"code": null,
"e": 4750,
"s": 4711,
"text": "Program statements are made of tokens."
},
{
"code": null,
"e": 4898,
"s": 4750,
"text": "An identifier is a name used to identify a variable, procedure, or any other user-defined item. A name in Fortran must follow the following rules −"
},
{
"code": null,
"e": 4938,
"s": 4898,
"text": "It cannot be longer than 31 characters."
},
{
"code": null,
"e": 4978,
"s": 4938,
"text": "It cannot be longer than 31 characters."
},
{
"code": null,
"e": 5103,
"s": 4978,
"text": "It must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores (_)."
},
{
"code": null,
"e": 5228,
"s": 5103,
"text": "It must be composed of alphanumeric characters (all the letters of the alphabet, and the digits 0 to 9) and underscores (_)."
},
{
"code": null,
"e": 5272,
"s": 5228,
"text": "First character of a name must be a letter."
},
{
"code": null,
"e": 5316,
"s": 5272,
"text": "First character of a name must be a letter."
},
{
"code": null,
"e": 5343,
"s": 5316,
"text": "Names are case-insensitive"
},
{
"code": null,
"e": 5370,
"s": 5343,
"text": "Names are case-insensitive"
},
{
"code": null,
"e": 5486,
"s": 5370,
"text": "Keywords are special words, reserved for the language. These reserved words cannot be used as identifiers or names."
},
{
"code": null,
"e": 5536,
"s": 5486,
"text": "The following table, lists the Fortran keywords −"
},
{
"code": null,
"e": 5543,
"s": 5536,
"text": " Print"
},
{
"code": null,
"e": 5554,
"s": 5543,
"text": " Add Notes"
}
] |
Bootstrap 4 .float-right class
|
Use the float-right class in Bootstrap to place an element on the right.
The default text alignment is on the left and use the float-right class to align text on the right as in the following code snippet −
<div class="float-right">
This text is on the right.
</div>
It can be used on any other element as well, for example, <h1>, <p>, etc −
<p class="float-right">
On the right
</p>
You can try to run the following code to implement the float-right 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">
<h2>Example</h2>
<div class="clearfix">
<div class="float-right">This text is on the right.</div><br>
<div class="float-left">This text is on the left.</div><br>
<div class="float-none">Float Removed</div><br>
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1135,
"s": 1062,
"text": "Use the float-right class in Bootstrap to place an element on the right."
},
{
"code": null,
"e": 1269,
"s": 1135,
"text": "The default text alignment is on the left and use the float-right class to align text on the right as in the following code snippet −"
},
{
"code": null,
"e": 1331,
"s": 1269,
"text": "<div class=\"float-right\">\n This text is on the right.\n</div>"
},
{
"code": null,
"e": 1406,
"s": 1331,
"text": "It can be used on any other element as well, for example, <h1>, <p>, etc −"
},
{
"code": null,
"e": 1450,
"s": 1406,
"text": "<p class=\"float-right\">\n On the right\n</p>"
},
{
"code": null,
"e": 1525,
"s": 1450,
"text": "You can try to run the following code to implement the float-right class −"
},
{
"code": null,
"e": 1535,
"s": 1525,
"text": "Live Demo"
},
{
"code": null,
"e": 2323,
"s": 1535,
"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 <div class=\"container\">\n <h2>Example</h2>\n <div class=\"clearfix\">\n <div class=\"float-right\">This text is on the right.</div><br>\n <div class=\"float-left\">This text is on the left.</div><br>\n <div class=\"float-none\">Float Removed</div><br>\n </div>\n </div>\n\n</body>\n</html>"
}
] |
Multiply Large Numbers represented as Strings in C++
|
Given two numbers in the string formats. We need to multiply them. The idea to solve the problem is to maintain a previous digit multiplication answer and carry. We can use the previous digits multiplication answer and carry to get the next set digits multiplication.
Let's see an example.
Input
15
2
Output
30
Initialise the numbers in string.
Initialise the numbers in string.
Initialise a string of length number_one_length + number_two_length.
Initialise a string of length number_one_length + number_two_length.
Iterate over the first number from the end.Iterate over the second number from the end.Multiply two digits and add the corresponding previous row digit.Update the previous row digit.Store the carry in the previous index of the result string.
Iterate over the first number from the end.
Iterate over the second number from the end.Multiply two digits and add the corresponding previous row digit.Update the previous row digit.Store the carry in the previous index of the result string.
Iterate over the second number from the end.
Multiply two digits and add the corresponding previous row digit.
Multiply two digits and add the corresponding previous row digit.
Update the previous row digit.
Update the previous row digit.
Store the carry in the previous index of the result string.
Store the carry in the previous index of the result string.
Convert the char to digits by adding 0 character to every character in the result.
Convert the char to digits by adding 0 character to every character in the result.
Return the result by ignoring the leading zero.
Return the result by ignoring the leading zero.
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h>
using namespace std;
string multiplyTwoNumbers(string num1, string num2) {
if (num1 == "0" || num2 == "0") {
return "0";
}
string product(num1.size() + num2.size(), 0);
for (int i = num1.size() - 1; i >= 0; i--) {
for (int j = num2.size() - 1; j >= 0; j--) {
int n = (num1[i] - '0') * (num2[j] - '0') + product[i + j + 1];
product[i + j + 1] = n % 10;
product[i + j] += n / 10;
}
}
for (int i = 0; i < product.size(); i++) {
product[i] += '0';
}
if (product[0] == '0') {
return product.substr(1);
}
return product;
}
int main() {
string num1 = "34";
string num2 = "57";
if((num1.at(0) == '-' || num2.at(0) == '-') && (num1.at(0) != '-' || num2.at(0) != '-')) {
cout << "-";
}
if(num1.at(0) == '-') {
num1 = num1.substr(1);
}
if(num2.at(0) == '-') {
num2 = num2.substr(1);
}
cout << multiplyTwoNumbers(num1, num2) << endl;
return 0;
}
If you run the above code, then you will get the following result.
1938
|
[
{
"code": null,
"e": 1330,
"s": 1062,
"text": "Given two numbers in the string formats. We need to multiply them. The idea to solve the problem is to maintain a previous digit multiplication answer and carry. We can use the previous digits multiplication answer and carry to get the next set digits multiplication."
},
{
"code": null,
"e": 1352,
"s": 1330,
"text": "Let's see an example."
},
{
"code": null,
"e": 1358,
"s": 1352,
"text": "Input"
},
{
"code": null,
"e": 1363,
"s": 1358,
"text": "15\n2"
},
{
"code": null,
"e": 1370,
"s": 1363,
"text": "Output"
},
{
"code": null,
"e": 1373,
"s": 1370,
"text": "30"
},
{
"code": null,
"e": 1407,
"s": 1373,
"text": "Initialise the numbers in string."
},
{
"code": null,
"e": 1441,
"s": 1407,
"text": "Initialise the numbers in string."
},
{
"code": null,
"e": 1510,
"s": 1441,
"text": "Initialise a string of length number_one_length + number_two_length."
},
{
"code": null,
"e": 1579,
"s": 1510,
"text": "Initialise a string of length number_one_length + number_two_length."
},
{
"code": null,
"e": 1821,
"s": 1579,
"text": "Iterate over the first number from the end.Iterate over the second number from the end.Multiply two digits and add the corresponding previous row digit.Update the previous row digit.Store the carry in the previous index of the result string."
},
{
"code": null,
"e": 1865,
"s": 1821,
"text": "Iterate over the first number from the end."
},
{
"code": null,
"e": 2064,
"s": 1865,
"text": "Iterate over the second number from the end.Multiply two digits and add the corresponding previous row digit.Update the previous row digit.Store the carry in the previous index of the result string."
},
{
"code": null,
"e": 2109,
"s": 2064,
"text": "Iterate over the second number from the end."
},
{
"code": null,
"e": 2175,
"s": 2109,
"text": "Multiply two digits and add the corresponding previous row digit."
},
{
"code": null,
"e": 2241,
"s": 2175,
"text": "Multiply two digits and add the corresponding previous row digit."
},
{
"code": null,
"e": 2272,
"s": 2241,
"text": "Update the previous row digit."
},
{
"code": null,
"e": 2303,
"s": 2272,
"text": "Update the previous row digit."
},
{
"code": null,
"e": 2363,
"s": 2303,
"text": "Store the carry in the previous index of the result string."
},
{
"code": null,
"e": 2423,
"s": 2363,
"text": "Store the carry in the previous index of the result string."
},
{
"code": null,
"e": 2506,
"s": 2423,
"text": "Convert the char to digits by adding 0 character to every character in the result."
},
{
"code": null,
"e": 2589,
"s": 2506,
"text": "Convert the char to digits by adding 0 character to every character in the result."
},
{
"code": null,
"e": 2637,
"s": 2589,
"text": "Return the result by ignoring the leading zero."
},
{
"code": null,
"e": 2685,
"s": 2637,
"text": "Return the result by ignoring the leading zero."
},
{
"code": null,
"e": 2747,
"s": 2685,
"text": "Following is the implementation of the above algorithm in C++"
},
{
"code": null,
"e": 3750,
"s": 2747,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nstring multiplyTwoNumbers(string num1, string num2) {\n if (num1 == \"0\" || num2 == \"0\") {\n return \"0\";\n }\n string product(num1.size() + num2.size(), 0);\n for (int i = num1.size() - 1; i >= 0; i--) {\n for (int j = num2.size() - 1; j >= 0; j--) {\n int n = (num1[i] - '0') * (num2[j] - '0') + product[i + j + 1];\n product[i + j + 1] = n % 10;\n product[i + j] += n / 10;\n }\n }\n for (int i = 0; i < product.size(); i++) {\n product[i] += '0';\n }\n if (product[0] == '0') {\n return product.substr(1);\n }\n return product;\n}\nint main() {\n string num1 = \"34\";\n string num2 = \"57\";\n if((num1.at(0) == '-' || num2.at(0) == '-') && (num1.at(0) != '-' || num2.at(0) != '-')) {\n cout << \"-\";\n }\n if(num1.at(0) == '-') {\n num1 = num1.substr(1);\n }\n if(num2.at(0) == '-') {\n num2 = num2.substr(1);\n }\n cout << multiplyTwoNumbers(num1, num2) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 3817,
"s": 3750,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 3822,
"s": 3817,
"text": "1938"
}
] |
How to Structure Your Data Science Workflow | by Mikhail Klassen | Towards Data Science
|
From the outside, data science can appear to be a huge and nebulous discipline. Today’s data science experts did not attend university to get data science degrees (although many universities now offer these programs).
The first generation of professional data scientists are drawn from the disciplines of mathematics, statistics, computer science, and physics.
The “science” part of data science is the classic work of posing a question, generating hypotheses, examining the evidence, and formulating a model that explains the evidence.
These are skills that anyone can learn, and there are more resources than ever to get started.
One of the best resources is Kaggle. Their data science competitions are a chance for anyone to get their feet wet with a real project. The community that has formed around these challenges is also a great place to learn from others.
When I transitioned from physicist to data scientist, Kaggle was one of the resources I used when teaching myself new skills, especially the use of machine learning libraries like scikit-learn.
In this article, I’ll be using the classic challenge “Titanic: Machine Learning from Disaster” to explain how to approach any data science problem and find a winning solution.
The aim of this challenge is to build a model that can predict the survival of a passenger, based on information known about them from the passenger manifest. This is based on historical data, and we know things like the names, age, gender, ticket class, and family information for many of the passengers — and whether they survived the disaster or not.
Kaggle provides training data and test data. The training data has the “ground truth” label of survival (yes/no), but the test data does not include the ground truth label. Kaggle retains those labels and uses them to score your submission. The test-data predictions are up to you to predict, and the accuracy of your predictions are used to determine your place on the leaderboard.
A side note about the Titanic challenge: if you look at the leaderboard, you’ll see a lot of perfect scores. This naturally leads you to wonder, “how did they do that?”
The answer is disheartening — they cheated. If you google around for a while, you’ll discover that the full test data with ground truth labels is available on the internet. Those with perfect scores simply submit the true labels instead of the predictions of a machine learning model... and receive a perfect score.
But they have failed the true test — these challenges exist for mastering a craft, not stealing a high score.
Before starting your data science project, I recommend setting up your work environment thus:
New project folder, with a subfolder for storing dataSeparate virtual environment, with your standard data science libraries installed.
New project folder, with a subfolder for storing data
Separate virtual environment, with your standard data science libraries installed.
For the virtual environment, I recommend using conda to manage your Python environment. My preferred data science libraries are numpy, pandas, matplotlib, seaborn, and scikit-learn. Depending on the nature of the problem, other libraries (like scipy) may be relevant. Deep learning challenges will involve installing either Tensorflow or PyTorch.
For this data science exercise, we won’t need any deep learning tools, but if you’re curious, I wrote up a guide on setting up a deep learning data science environment in PyTorch.
towardsdatascience.com
Finally, let’s load the data. Assuming you have downloaded the data for the challenge from Kaggle onto your own machine into a subfolder called data and you are writing code inside a Jupyter notebook.
Alternatively, you can create a data science notebook directly on Kaggle’s platform.
It’s important not to skip this first step.
Whenever you work with new data, it’s important to understand what the data contains, what the variables mean, what units and data types are being used, and what the distributions look like.
This will help you develop an intuition for the data and make it easier to generate hypotheses, which hopefully also makes the solution easier to find.
The challenge website explains the data well, with a table explaining each variable:
Most of these are self-explanatory, but sibsp and parch warrant a bit more information:
sibsp: The dataset defines family relations in this way...Sibling = brother, sister, stepbrother, stepsisterSpouse = husband, wife (mistresses and fiancés were ignored)
parch: The dataset defines family relations in this way...Parent = mother, fatherChild = daughter, son, stepdaughter, stepsonSome children travelled only with a nanny, therefore parch=0 for them.
The seaborn Python library excels at visualizing distributions, so in this section, I’m going to inspect the data in a few different ways.
I’m interested to know whether our assumptions about the survival rate of women and children hold up, so I created the following plot.
Our assumptions hold up fairly well, but it’s notable that quite a few children did not survive, and quite a few men of all ages did indeed survive. Could their survival be related to something else?
Perhaps the passenger class is predictive of survival. Let’s take a look at the data again, but this time splitting out by class.
We see a few things here. Of the adult men that survived, a higher fraction of 1st-class passengers survived. There were adult male survivors among 2nd and 3rd class passengers as well, but not as many relative the number of the passengers in each group.
Of the women that did not survive, most of them were 3rd-class passengers.
This tells us that sex, age, and passenger class are all likely to be predictive of survival, but that there are outliers in each group. It’s not clear whether this is random, or due to more subtle factors.
Finally, let’s take a quick look at where these passengers boarded. Perhaps that might tell us something.
The letters S, C, and Q stand for Southampton, Cherbourg, and Queenstown. The majority of passengers embarked at Southampton. Passengers embarking at Cherbourg appear to have a slightly better chance of survival from among their cohort, but there does not appear to be a strong correlation between port and survival.
With these insights, we are already starting to formulate hypotheses about the data, which we’ll test later. Without visualizing the data, we wouldn’t have these same intuitions.
Even under the best of circumstances, data is rarely “clean”, meaning that there could be missing values or mistakes in the data. Other times, data will be recorded in units that need to be converted, filtered, or otherwise processed before any further work can be done.
There is no single way to do data cleaning. It will depend on your data:
Images may need to be rescaled, rotated, color-corrected, smoothed, sharpened.
Audio may need to be filtered, remastered, de-noised, or normalized.
Natural language data (text) may need to be case-corrected, have stop words removed, and punctuation stripped out.
etc.
If we look closely at our Titanic data, we can find a few problems:
This code produces the output:
Column "Age" is missing data.Column "Cabin" is missing data.Column "Embarked" is missing data.
Here I’m using pandas to check for null values with the .isna() method. Missing data or null values produce a “NA” code. If numerical data is expected, it produces a “NaN”, meaning “Not a Number”.
The Titanic data has a lot of missing values in it. Sometimes we don’t know a person’s age, or what cabin they occupied (if any), or what their port of embarkation was.
This leaves us with a few options:
Drop all rows with missing values
Find reasonable values to fill the holes
Each approach has its merits. In the first case, we make no assumptions about the data, and just choose to get rid of any incomplete rows in our table. The advantage is we’re not biasing our future model with our assumption, but at the cost of fewer training examples.
When training a machine learning model, more data is always better. If you have a lot of clean data, it may be fine to throw away any incomplete samples. But if every row in your table is precious, it’s better to find values to plug the holes.
The Titanic data set isn’t very large. We have less than 1000 passengers in our training set. And we may need to further subdivide our training data to validate our models, so that leaves us with even fewer training examples.
Machine learning models need numerical data, but a lot of the Titanic data is categorical. We need to convert this data somehow to numbers.
The Sex column has only two values, female and male. We can remap these to 0 and 1.
train_data.Sex = train_data.Sex.map({‘female’: 0, ‘male’: 1})
Dealing with categorical data that has more than 2 possibilities, e.g. the port of embarkation (which has 3 possible values), is covered below using a technique called “one-hot encoding”.
With a few reasonable assumptions, we can actually fill the holes in our data pretty well.
Age
There are several strategies we could employ here, such as simply imputing the average age of all passengers to the missing values.
But we can do better.
My strategy was to look at the average age of passengers in each ticket class.
This gave the result:
Class: 1 -- Median Age: 37.0Class: 2 -- Median Age: 29.0Class: 3 -- Median Age: 24.0
I was not surprised to discover that first-class passengers tended to be older, and that there was a downward gradient in age as you went into second and then third class.
For all the missing age values, I assigned them the median value based on their passenger class.
You could improve this technique even further by looking at the median age for women and men within each class, and then filling in missing data based on those two variables.
Port of embarkation
There aren’t many missing values here, which is encouraging. The most common port of embarkation was Southhampton, so all else being equal, it’s most likely that a passenger would have boarded there. This was true for passengers of all classes.
From cabin to deck
Many of the rows in our table contain a cabin number. It was initially unclear how to make use of this information, but we can determine the ship deck from the cabin number. For example, “C22” is on Deck C.
Passenger cabins are mostly on Decks B through F. Some information about ship layout can be found here. That same page also indicates where the 1st-, 2nd-, and 3rd-class cabins can be found.
For passengers with a known cabin number, I used it to infer the deck.
For passengers without a cabin number, I used their fare class to infer the most likely deck they occupied.
I created a new column in my data frame called “Deck” and wrote all the inferred deck information there. The “Cabin” column can now be deleted.
The output is:
Class: 1C 59B 47Unknown 40D 29E 25A 15T 1Name: Deck, dtype: int64 Class: 2Unknown 168F 8D 4E 4Name: Deck, dtype: int64 Class: 3Unknown 479F 5G 4E 3Name: Deck, dtype: int64
My strategy here was to look at the deck layout and see where most of the 1st, 2nd, and 3rd class cabins were. It appeared to be decks C, E, and F, respectively, though I may be wrong.
For all the passengers with an unknown deck, I assigned them to a deck based on their passenger class.
I spent a good amount of time investigating what information could be gleaned from the values in the ticket column.
You’ll notice that some tickets have a prefix, like “S.C./PARIS”, followed by a number. Both the prefix and number could tell us something. My guess is that the prefix indicates the ticket vendor. From the ticket number itself we can sometimes infer groups of people traveling together.
I did a bunch of deep cleaning and disambiguation on the prefix data, but in the end, I dropped it, since it didn’t seem to be leading to anywhere. Please comment if you found a way to use this information to improve your models.
There’s a good discussion about this topic on the Kaggle forum.
Now that we’ve cleaned our data, we could try out a few simple tests. Let’s split off some of our own test data that we can use to test our hypotheses. For this split-off test data, we know the ground truth labels, so we can measure the accuracy of our predictions.
We know that survivors of the Titanic fled on lifeboats, and these (we assume) would be filled preferentially with women and children. How accurately can we predict survival from just these two variables?
We’ll use logistic regression to test it:
Which gives an accuracy of
0.7847533632286996
78% accuracy is pretty good! Clearly these two variables are highly predictive, as expected.
Next, we may assume that first class passenger, because of their status or proximity of their cabins to the upper decks, could have more likely been among the survivors, so let’s see if class alone is a good predictor. Then we’ll see if combining it with age and sex improves the previous result.
I had to do some one-hot encoding of the Pclass variable. I explain what one-hot encoding is below and why it’s important. From these tests, I get the results:
Using Pclass as the sole predictor, our accuracy:0.6995515695067265Using Pclass, age, and sex as predictors, our accuracy:0.7937219730941704
So using the passenger class as the only predictor, our logistic classifier gets almost 70% accuracy. Combining with age and sex, we improve slightly on the previous result: 79% vs 78%. This difference isn’t great and could be noise.
What these first few experiments are telling us is that survival will depend in large part on age, sex, and socio-economic status. These three factors alone could probably get us a reasonably good prediction of survival.
But to eke out those last few percentage points of accuracy, it’s going to take some feature engineering.
Really good feature engineering is what often distinguishes the experts from the novice data scientists. Anyone can take an off-the-shelf software library, train a machine learning model in a few lines of Python, and use it make predictions. But data science is about more than just model selection. You need to give that model high-quality predictive features to work with.
Feature engineering typically means creating new features to help your machine learning model make better predictions. There are tools for automating this process, but it’s better to first think deeply about the data and what other factors may be responsible for the target outcome.
In our Titanic example, we have some information families traveling together. The columns “sibsp” and “parch” tell us about the numbers of siblings, spouses, parents, and children that a passenger has. We could create a new variable called “Family Size” that is the sum of “sibsp” and “parch”.
X['Family Size'] = X['SibSp'] + X['Parch']
Many Kagglers will also create a variable called “not_alone”, which is just a binary identifier describing whether a passenger is traveling by themselves.
This particular data set contains a lot of categorical data. Consider the port of embarkation. There are 3 possible values: Cherbourg, Queenstown, and Southampton. ML models need numerical data, so we could map the port to a number:
{'Cherbourg': 1, 'Queenstown': 2, 'Southampton': 3}
But think about how that looks to a machine learning model. Is Southampton 3x greater in value than Cherbourg? No, that’s absurd. Each port matters equally.
We instead perform a “one-hot encoding” of this categorical data, which will create three new columns, one for each port, and we will use the number 0 or 1 to indicate whether the passenger embarked at a particular port or not.
We can do the same for other categorical variables, such as deck. Sex is a categorical variable in our data set, but since the only values in our data set are “female” and “male”, we just use 0/1 to indicate. No need to create new columns.
One major disadvantage of one-hot encoding is that it can create many new columns. Each column is considered a separate feature. More features aren’t always a good thing. You want the number of examples in your data to greatly exceed the number of features. This can help to prevent overfitting.
Some Kagglers find that creating separate “bins” for age or fare ranges is helpful. Consider that when filling life boats, the crew are probably not asking for age, but considering age categories such as “infant”, “child”, “young”, “old”. You can create similar bins and see if this helps your model. I’m going to leave the age and fare variables as they are.
The above steps are actually the hardest part and represents about 80% to 90% of the work.
The next few steps are usually easier and more fun. We can play around with different machine learning models to see how well they perform, and pick a promising one for further optimization.
Since we are simply trying to predict a binary variable, “survival”, any binary classifier will work. If you’re using scikit-learn, you have many choices.
Some of the most popular classifiers are:
Logistic regression
Decision tree
Random forest
Adaptive boosting (AdaBoost)
XGBoost
That last one, XGBoost, isn’t part of scikit-learn, so you’ll have to install it separately.
Let’s take our training data, select a classifier, and test it using k-fold cross-validation.
Cross-validation is a technique whereby a small portion of the data is left out, while the model is trained on the remaining data. The accuracy of the model is then tested against the left-out data. This process is repeated k times, where the portion of left-out data is drawn randomly each time.
The point of this technique is to help avoid overfitting. In your zeal to engineer the perfect model with the highest accuracy, you may accidentally create a model that doesn’t generalize to data outside of your sample. So you always need to be testing your models against data outside of your sample.
Of the classifiers mentioned above, logistic regression and decision trees are the easiest to understand. Random forests are ensemble models constructed from many decision trees. They tend to do well out of the box. AdaBoost and XGBoost are newer, more advanced models. XGBoost is very popular with Kagglers.
I won’t cover the mechanics of each classifier in this article, but that information is pretty easy to find.
My assess_model function uses 5-fold cross-validation to test the accuracy of each classifier on both the training set and the test set. The true worth of a model is always how well it performs on the test set. The accuracy of each one:
# Logistic regressionAverage Train Accuracy: 0.802 ±0.01Average Test Accuracy: 0.780 ±0.02# Decision treeAverage Train Accuracy: 0.974 ±0.00Average Test Accuracy: 0.781 ±0.02# Random forestAverage Train Accuracy: 0.974 ±0.00Average Test Accuracy: 0.791 ±0.03# AdaBoostAverage Train Accuracy: 0.832 ±0.00Average Test Accuracy: 0.804 ±0.02# XGBoostAverage Train Accuracy: 0.964 ±0.00Average Test Accuracy: 0.820 ±0.03
It’s important to note that we’ve used the “out-of-the-box” version of each of these classifiers. These use default values for all of their internal tunable parameters.
Notice how a classifier sometimes gets ~97% accuracy on the training set. That looks amazing, but it’s overfitting. The test accuracy is lower and it’s the variable we care more about.
Of these classifiers, XGBoost has the highest test accuracy. This is one of the reasons why Kaggler’s love XGBoost — great performance with zero tuning.
Most machine learning models have tunable parameters that often influence model accuracy. The best-performing values for these parameters is different for every problem.
In ML, these parameters are often referred to as “hyperparameters” and tuning them is as much art as science.
There are tools out there to help with tuning. TPOT is one example. But keeping it simple, we’re going to perform a simple grid search and manually test a whole range of plausible hyperparameter values to see which one gives us the best results.
scikit-learn has a convenient tool for performing grid searches.
This code takes some time to run, as it tries all the different combinations of hyperparameters.
You can modify the parameter grid to change the search space. Remember, this technique won’t find the best possible hyperparameter values, only the best combination from within the search space.
With this approach we get:
{'bootstrap': True, 'max_depth': 6, 'max_features': 'auto', 'min_samples_leaf': 2, 'min_samples_split': 4, 'n_estimators': 100}RandomForestClassifier(max_depth=6, min_samples_leaf=2, min_samples_split=4)0.830804623499046
So there you have it. You’d be hard pressed to outperform 83% on the Kaggle Titanic challenge without cheating. I mentioned a few other possible ways of boosting performance, such as age or fare binning, and imputing missing age values based both class and gender. You can try these and see if they boost accuracy.
In conclusion, approaching a data science problem is stepwise process of starting from a clean slate, getting to know your data, cleaning it, and then iteratively testing different models and adding more features until you achieve good model performance. From there, you optimize your best model to squeeze a little more performance out of it.
What happens next? Well if you’re a researcher, you publish your results. If you’re an entrepreneur, you operationalize your model to do something useful that others will pay money for. If you’re a Kaggler, you submit your test predictions for a shot at glory (and sometimes money).
If I missed anything, or you find other techniques for doing even better, let me know in the comments. I hope this has helped you on your data science journey.
|
[
{
"code": null,
"e": 390,
"s": 172,
"text": "From the outside, data science can appear to be a huge and nebulous discipline. Today’s data science experts did not attend university to get data science degrees (although many universities now offer these programs)."
},
{
"code": null,
"e": 533,
"s": 390,
"text": "The first generation of professional data scientists are drawn from the disciplines of mathematics, statistics, computer science, and physics."
},
{
"code": null,
"e": 709,
"s": 533,
"text": "The “science” part of data science is the classic work of posing a question, generating hypotheses, examining the evidence, and formulating a model that explains the evidence."
},
{
"code": null,
"e": 804,
"s": 709,
"text": "These are skills that anyone can learn, and there are more resources than ever to get started."
},
{
"code": null,
"e": 1038,
"s": 804,
"text": "One of the best resources is Kaggle. Their data science competitions are a chance for anyone to get their feet wet with a real project. The community that has formed around these challenges is also a great place to learn from others."
},
{
"code": null,
"e": 1232,
"s": 1038,
"text": "When I transitioned from physicist to data scientist, Kaggle was one of the resources I used when teaching myself new skills, especially the use of machine learning libraries like scikit-learn."
},
{
"code": null,
"e": 1408,
"s": 1232,
"text": "In this article, I’ll be using the classic challenge “Titanic: Machine Learning from Disaster” to explain how to approach any data science problem and find a winning solution."
},
{
"code": null,
"e": 1762,
"s": 1408,
"text": "The aim of this challenge is to build a model that can predict the survival of a passenger, based on information known about them from the passenger manifest. This is based on historical data, and we know things like the names, age, gender, ticket class, and family information for many of the passengers — and whether they survived the disaster or not."
},
{
"code": null,
"e": 2145,
"s": 1762,
"text": "Kaggle provides training data and test data. The training data has the “ground truth” label of survival (yes/no), but the test data does not include the ground truth label. Kaggle retains those labels and uses them to score your submission. The test-data predictions are up to you to predict, and the accuracy of your predictions are used to determine your place on the leaderboard."
},
{
"code": null,
"e": 2314,
"s": 2145,
"text": "A side note about the Titanic challenge: if you look at the leaderboard, you’ll see a lot of perfect scores. This naturally leads you to wonder, “how did they do that?”"
},
{
"code": null,
"e": 2630,
"s": 2314,
"text": "The answer is disheartening — they cheated. If you google around for a while, you’ll discover that the full test data with ground truth labels is available on the internet. Those with perfect scores simply submit the true labels instead of the predictions of a machine learning model... and receive a perfect score."
},
{
"code": null,
"e": 2740,
"s": 2630,
"text": "But they have failed the true test — these challenges exist for mastering a craft, not stealing a high score."
},
{
"code": null,
"e": 2834,
"s": 2740,
"text": "Before starting your data science project, I recommend setting up your work environment thus:"
},
{
"code": null,
"e": 2970,
"s": 2834,
"text": "New project folder, with a subfolder for storing dataSeparate virtual environment, with your standard data science libraries installed."
},
{
"code": null,
"e": 3024,
"s": 2970,
"text": "New project folder, with a subfolder for storing data"
},
{
"code": null,
"e": 3107,
"s": 3024,
"text": "Separate virtual environment, with your standard data science libraries installed."
},
{
"code": null,
"e": 3454,
"s": 3107,
"text": "For the virtual environment, I recommend using conda to manage your Python environment. My preferred data science libraries are numpy, pandas, matplotlib, seaborn, and scikit-learn. Depending on the nature of the problem, other libraries (like scipy) may be relevant. Deep learning challenges will involve installing either Tensorflow or PyTorch."
},
{
"code": null,
"e": 3634,
"s": 3454,
"text": "For this data science exercise, we won’t need any deep learning tools, but if you’re curious, I wrote up a guide on setting up a deep learning data science environment in PyTorch."
},
{
"code": null,
"e": 3657,
"s": 3634,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3858,
"s": 3657,
"text": "Finally, let’s load the data. Assuming you have downloaded the data for the challenge from Kaggle onto your own machine into a subfolder called data and you are writing code inside a Jupyter notebook."
},
{
"code": null,
"e": 3943,
"s": 3858,
"text": "Alternatively, you can create a data science notebook directly on Kaggle’s platform."
},
{
"code": null,
"e": 3987,
"s": 3943,
"text": "It’s important not to skip this first step."
},
{
"code": null,
"e": 4178,
"s": 3987,
"text": "Whenever you work with new data, it’s important to understand what the data contains, what the variables mean, what units and data types are being used, and what the distributions look like."
},
{
"code": null,
"e": 4330,
"s": 4178,
"text": "This will help you develop an intuition for the data and make it easier to generate hypotheses, which hopefully also makes the solution easier to find."
},
{
"code": null,
"e": 4415,
"s": 4330,
"text": "The challenge website explains the data well, with a table explaining each variable:"
},
{
"code": null,
"e": 4503,
"s": 4415,
"text": "Most of these are self-explanatory, but sibsp and parch warrant a bit more information:"
},
{
"code": null,
"e": 4673,
"s": 4503,
"text": "sibsp: The dataset defines family relations in this way...Sibling = brother, sister, stepbrother, stepsisterSpouse = husband, wife (mistresses and fiancés were ignored)"
},
{
"code": null,
"e": 4869,
"s": 4673,
"text": "parch: The dataset defines family relations in this way...Parent = mother, fatherChild = daughter, son, stepdaughter, stepsonSome children travelled only with a nanny, therefore parch=0 for them."
},
{
"code": null,
"e": 5008,
"s": 4869,
"text": "The seaborn Python library excels at visualizing distributions, so in this section, I’m going to inspect the data in a few different ways."
},
{
"code": null,
"e": 5143,
"s": 5008,
"text": "I’m interested to know whether our assumptions about the survival rate of women and children hold up, so I created the following plot."
},
{
"code": null,
"e": 5343,
"s": 5143,
"text": "Our assumptions hold up fairly well, but it’s notable that quite a few children did not survive, and quite a few men of all ages did indeed survive. Could their survival be related to something else?"
},
{
"code": null,
"e": 5473,
"s": 5343,
"text": "Perhaps the passenger class is predictive of survival. Let’s take a look at the data again, but this time splitting out by class."
},
{
"code": null,
"e": 5728,
"s": 5473,
"text": "We see a few things here. Of the adult men that survived, a higher fraction of 1st-class passengers survived. There were adult male survivors among 2nd and 3rd class passengers as well, but not as many relative the number of the passengers in each group."
},
{
"code": null,
"e": 5803,
"s": 5728,
"text": "Of the women that did not survive, most of them were 3rd-class passengers."
},
{
"code": null,
"e": 6010,
"s": 5803,
"text": "This tells us that sex, age, and passenger class are all likely to be predictive of survival, but that there are outliers in each group. It’s not clear whether this is random, or due to more subtle factors."
},
{
"code": null,
"e": 6116,
"s": 6010,
"text": "Finally, let’s take a quick look at where these passengers boarded. Perhaps that might tell us something."
},
{
"code": null,
"e": 6433,
"s": 6116,
"text": "The letters S, C, and Q stand for Southampton, Cherbourg, and Queenstown. The majority of passengers embarked at Southampton. Passengers embarking at Cherbourg appear to have a slightly better chance of survival from among their cohort, but there does not appear to be a strong correlation between port and survival."
},
{
"code": null,
"e": 6612,
"s": 6433,
"text": "With these insights, we are already starting to formulate hypotheses about the data, which we’ll test later. Without visualizing the data, we wouldn’t have these same intuitions."
},
{
"code": null,
"e": 6883,
"s": 6612,
"text": "Even under the best of circumstances, data is rarely “clean”, meaning that there could be missing values or mistakes in the data. Other times, data will be recorded in units that need to be converted, filtered, or otherwise processed before any further work can be done."
},
{
"code": null,
"e": 6956,
"s": 6883,
"text": "There is no single way to do data cleaning. It will depend on your data:"
},
{
"code": null,
"e": 7035,
"s": 6956,
"text": "Images may need to be rescaled, rotated, color-corrected, smoothed, sharpened."
},
{
"code": null,
"e": 7104,
"s": 7035,
"text": "Audio may need to be filtered, remastered, de-noised, or normalized."
},
{
"code": null,
"e": 7219,
"s": 7104,
"text": "Natural language data (text) may need to be case-corrected, have stop words removed, and punctuation stripped out."
},
{
"code": null,
"e": 7224,
"s": 7219,
"text": "etc."
},
{
"code": null,
"e": 7292,
"s": 7224,
"text": "If we look closely at our Titanic data, we can find a few problems:"
},
{
"code": null,
"e": 7323,
"s": 7292,
"text": "This code produces the output:"
},
{
"code": null,
"e": 7418,
"s": 7323,
"text": "Column \"Age\" is missing data.Column \"Cabin\" is missing data.Column \"Embarked\" is missing data."
},
{
"code": null,
"e": 7615,
"s": 7418,
"text": "Here I’m using pandas to check for null values with the .isna() method. Missing data or null values produce a “NA” code. If numerical data is expected, it produces a “NaN”, meaning “Not a Number”."
},
{
"code": null,
"e": 7784,
"s": 7615,
"text": "The Titanic data has a lot of missing values in it. Sometimes we don’t know a person’s age, or what cabin they occupied (if any), or what their port of embarkation was."
},
{
"code": null,
"e": 7819,
"s": 7784,
"text": "This leaves us with a few options:"
},
{
"code": null,
"e": 7853,
"s": 7819,
"text": "Drop all rows with missing values"
},
{
"code": null,
"e": 7894,
"s": 7853,
"text": "Find reasonable values to fill the holes"
},
{
"code": null,
"e": 8163,
"s": 7894,
"text": "Each approach has its merits. In the first case, we make no assumptions about the data, and just choose to get rid of any incomplete rows in our table. The advantage is we’re not biasing our future model with our assumption, but at the cost of fewer training examples."
},
{
"code": null,
"e": 8407,
"s": 8163,
"text": "When training a machine learning model, more data is always better. If you have a lot of clean data, it may be fine to throw away any incomplete samples. But if every row in your table is precious, it’s better to find values to plug the holes."
},
{
"code": null,
"e": 8633,
"s": 8407,
"text": "The Titanic data set isn’t very large. We have less than 1000 passengers in our training set. And we may need to further subdivide our training data to validate our models, so that leaves us with even fewer training examples."
},
{
"code": null,
"e": 8773,
"s": 8633,
"text": "Machine learning models need numerical data, but a lot of the Titanic data is categorical. We need to convert this data somehow to numbers."
},
{
"code": null,
"e": 8857,
"s": 8773,
"text": "The Sex column has only two values, female and male. We can remap these to 0 and 1."
},
{
"code": null,
"e": 8919,
"s": 8857,
"text": "train_data.Sex = train_data.Sex.map({‘female’: 0, ‘male’: 1})"
},
{
"code": null,
"e": 9107,
"s": 8919,
"text": "Dealing with categorical data that has more than 2 possibilities, e.g. the port of embarkation (which has 3 possible values), is covered below using a technique called “one-hot encoding”."
},
{
"code": null,
"e": 9198,
"s": 9107,
"text": "With a few reasonable assumptions, we can actually fill the holes in our data pretty well."
},
{
"code": null,
"e": 9202,
"s": 9198,
"text": "Age"
},
{
"code": null,
"e": 9334,
"s": 9202,
"text": "There are several strategies we could employ here, such as simply imputing the average age of all passengers to the missing values."
},
{
"code": null,
"e": 9356,
"s": 9334,
"text": "But we can do better."
},
{
"code": null,
"e": 9435,
"s": 9356,
"text": "My strategy was to look at the average age of passengers in each ticket class."
},
{
"code": null,
"e": 9457,
"s": 9435,
"text": "This gave the result:"
},
{
"code": null,
"e": 9542,
"s": 9457,
"text": "Class: 1 -- Median Age: 37.0Class: 2 -- Median Age: 29.0Class: 3 -- Median Age: 24.0"
},
{
"code": null,
"e": 9714,
"s": 9542,
"text": "I was not surprised to discover that first-class passengers tended to be older, and that there was a downward gradient in age as you went into second and then third class."
},
{
"code": null,
"e": 9811,
"s": 9714,
"text": "For all the missing age values, I assigned them the median value based on their passenger class."
},
{
"code": null,
"e": 9986,
"s": 9811,
"text": "You could improve this technique even further by looking at the median age for women and men within each class, and then filling in missing data based on those two variables."
},
{
"code": null,
"e": 10006,
"s": 9986,
"text": "Port of embarkation"
},
{
"code": null,
"e": 10251,
"s": 10006,
"text": "There aren’t many missing values here, which is encouraging. The most common port of embarkation was Southhampton, so all else being equal, it’s most likely that a passenger would have boarded there. This was true for passengers of all classes."
},
{
"code": null,
"e": 10270,
"s": 10251,
"text": "From cabin to deck"
},
{
"code": null,
"e": 10477,
"s": 10270,
"text": "Many of the rows in our table contain a cabin number. It was initially unclear how to make use of this information, but we can determine the ship deck from the cabin number. For example, “C22” is on Deck C."
},
{
"code": null,
"e": 10668,
"s": 10477,
"text": "Passenger cabins are mostly on Decks B through F. Some information about ship layout can be found here. That same page also indicates where the 1st-, 2nd-, and 3rd-class cabins can be found."
},
{
"code": null,
"e": 10739,
"s": 10668,
"text": "For passengers with a known cabin number, I used it to infer the deck."
},
{
"code": null,
"e": 10847,
"s": 10739,
"text": "For passengers without a cabin number, I used their fare class to infer the most likely deck they occupied."
},
{
"code": null,
"e": 10991,
"s": 10847,
"text": "I created a new column in my data frame called “Deck” and wrote all the inferred deck information there. The “Cabin” column can now be deleted."
},
{
"code": null,
"e": 11006,
"s": 10991,
"text": "The output is:"
},
{
"code": null,
"e": 11309,
"s": 11006,
"text": " Class: 1C 59B 47Unknown 40D 29E 25A 15T 1Name: Deck, dtype: int64 Class: 2Unknown 168F 8D 4E 4Name: Deck, dtype: int64 Class: 3Unknown 479F 5G 4E 3Name: Deck, dtype: int64"
},
{
"code": null,
"e": 11494,
"s": 11309,
"text": "My strategy here was to look at the deck layout and see where most of the 1st, 2nd, and 3rd class cabins were. It appeared to be decks C, E, and F, respectively, though I may be wrong."
},
{
"code": null,
"e": 11597,
"s": 11494,
"text": "For all the passengers with an unknown deck, I assigned them to a deck based on their passenger class."
},
{
"code": null,
"e": 11713,
"s": 11597,
"text": "I spent a good amount of time investigating what information could be gleaned from the values in the ticket column."
},
{
"code": null,
"e": 12000,
"s": 11713,
"text": "You’ll notice that some tickets have a prefix, like “S.C./PARIS”, followed by a number. Both the prefix and number could tell us something. My guess is that the prefix indicates the ticket vendor. From the ticket number itself we can sometimes infer groups of people traveling together."
},
{
"code": null,
"e": 12230,
"s": 12000,
"text": "I did a bunch of deep cleaning and disambiguation on the prefix data, but in the end, I dropped it, since it didn’t seem to be leading to anywhere. Please comment if you found a way to use this information to improve your models."
},
{
"code": null,
"e": 12294,
"s": 12230,
"text": "There’s a good discussion about this topic on the Kaggle forum."
},
{
"code": null,
"e": 12560,
"s": 12294,
"text": "Now that we’ve cleaned our data, we could try out a few simple tests. Let’s split off some of our own test data that we can use to test our hypotheses. For this split-off test data, we know the ground truth labels, so we can measure the accuracy of our predictions."
},
{
"code": null,
"e": 12765,
"s": 12560,
"text": "We know that survivors of the Titanic fled on lifeboats, and these (we assume) would be filled preferentially with women and children. How accurately can we predict survival from just these two variables?"
},
{
"code": null,
"e": 12807,
"s": 12765,
"text": "We’ll use logistic regression to test it:"
},
{
"code": null,
"e": 12834,
"s": 12807,
"text": "Which gives an accuracy of"
},
{
"code": null,
"e": 12853,
"s": 12834,
"text": "0.7847533632286996"
},
{
"code": null,
"e": 12946,
"s": 12853,
"text": "78% accuracy is pretty good! Clearly these two variables are highly predictive, as expected."
},
{
"code": null,
"e": 13243,
"s": 12946,
"text": "Next, we may assume that first class passenger, because of their status or proximity of their cabins to the upper decks, could have more likely been among the survivors, so let’s see if class alone is a good predictor. Then we’ll see if combining it with age and sex improves the previous result."
},
{
"code": null,
"e": 13403,
"s": 13243,
"text": "I had to do some one-hot encoding of the Pclass variable. I explain what one-hot encoding is below and why it’s important. From these tests, I get the results:"
},
{
"code": null,
"e": 13544,
"s": 13403,
"text": "Using Pclass as the sole predictor, our accuracy:0.6995515695067265Using Pclass, age, and sex as predictors, our accuracy:0.7937219730941704"
},
{
"code": null,
"e": 13778,
"s": 13544,
"text": "So using the passenger class as the only predictor, our logistic classifier gets almost 70% accuracy. Combining with age and sex, we improve slightly on the previous result: 79% vs 78%. This difference isn’t great and could be noise."
},
{
"code": null,
"e": 13999,
"s": 13778,
"text": "What these first few experiments are telling us is that survival will depend in large part on age, sex, and socio-economic status. These three factors alone could probably get us a reasonably good prediction of survival."
},
{
"code": null,
"e": 14105,
"s": 13999,
"text": "But to eke out those last few percentage points of accuracy, it’s going to take some feature engineering."
},
{
"code": null,
"e": 14480,
"s": 14105,
"text": "Really good feature engineering is what often distinguishes the experts from the novice data scientists. Anyone can take an off-the-shelf software library, train a machine learning model in a few lines of Python, and use it make predictions. But data science is about more than just model selection. You need to give that model high-quality predictive features to work with."
},
{
"code": null,
"e": 14763,
"s": 14480,
"text": "Feature engineering typically means creating new features to help your machine learning model make better predictions. There are tools for automating this process, but it’s better to first think deeply about the data and what other factors may be responsible for the target outcome."
},
{
"code": null,
"e": 15057,
"s": 14763,
"text": "In our Titanic example, we have some information families traveling together. The columns “sibsp” and “parch” tell us about the numbers of siblings, spouses, parents, and children that a passenger has. We could create a new variable called “Family Size” that is the sum of “sibsp” and “parch”."
},
{
"code": null,
"e": 15100,
"s": 15057,
"text": "X['Family Size'] = X['SibSp'] + X['Parch']"
},
{
"code": null,
"e": 15255,
"s": 15100,
"text": "Many Kagglers will also create a variable called “not_alone”, which is just a binary identifier describing whether a passenger is traveling by themselves."
},
{
"code": null,
"e": 15488,
"s": 15255,
"text": "This particular data set contains a lot of categorical data. Consider the port of embarkation. There are 3 possible values: Cherbourg, Queenstown, and Southampton. ML models need numerical data, so we could map the port to a number:"
},
{
"code": null,
"e": 15540,
"s": 15488,
"text": "{'Cherbourg': 1, 'Queenstown': 2, 'Southampton': 3}"
},
{
"code": null,
"e": 15697,
"s": 15540,
"text": "But think about how that looks to a machine learning model. Is Southampton 3x greater in value than Cherbourg? No, that’s absurd. Each port matters equally."
},
{
"code": null,
"e": 15925,
"s": 15697,
"text": "We instead perform a “one-hot encoding” of this categorical data, which will create three new columns, one for each port, and we will use the number 0 or 1 to indicate whether the passenger embarked at a particular port or not."
},
{
"code": null,
"e": 16165,
"s": 15925,
"text": "We can do the same for other categorical variables, such as deck. Sex is a categorical variable in our data set, but since the only values in our data set are “female” and “male”, we just use 0/1 to indicate. No need to create new columns."
},
{
"code": null,
"e": 16461,
"s": 16165,
"text": "One major disadvantage of one-hot encoding is that it can create many new columns. Each column is considered a separate feature. More features aren’t always a good thing. You want the number of examples in your data to greatly exceed the number of features. This can help to prevent overfitting."
},
{
"code": null,
"e": 16821,
"s": 16461,
"text": "Some Kagglers find that creating separate “bins” for age or fare ranges is helpful. Consider that when filling life boats, the crew are probably not asking for age, but considering age categories such as “infant”, “child”, “young”, “old”. You can create similar bins and see if this helps your model. I’m going to leave the age and fare variables as they are."
},
{
"code": null,
"e": 16912,
"s": 16821,
"text": "The above steps are actually the hardest part and represents about 80% to 90% of the work."
},
{
"code": null,
"e": 17103,
"s": 16912,
"text": "The next few steps are usually easier and more fun. We can play around with different machine learning models to see how well they perform, and pick a promising one for further optimization."
},
{
"code": null,
"e": 17258,
"s": 17103,
"text": "Since we are simply trying to predict a binary variable, “survival”, any binary classifier will work. If you’re using scikit-learn, you have many choices."
},
{
"code": null,
"e": 17300,
"s": 17258,
"text": "Some of the most popular classifiers are:"
},
{
"code": null,
"e": 17320,
"s": 17300,
"text": "Logistic regression"
},
{
"code": null,
"e": 17334,
"s": 17320,
"text": "Decision tree"
},
{
"code": null,
"e": 17348,
"s": 17334,
"text": "Random forest"
},
{
"code": null,
"e": 17377,
"s": 17348,
"text": "Adaptive boosting (AdaBoost)"
},
{
"code": null,
"e": 17385,
"s": 17377,
"text": "XGBoost"
},
{
"code": null,
"e": 17478,
"s": 17385,
"text": "That last one, XGBoost, isn’t part of scikit-learn, so you’ll have to install it separately."
},
{
"code": null,
"e": 17572,
"s": 17478,
"text": "Let’s take our training data, select a classifier, and test it using k-fold cross-validation."
},
{
"code": null,
"e": 17869,
"s": 17572,
"text": "Cross-validation is a technique whereby a small portion of the data is left out, while the model is trained on the remaining data. The accuracy of the model is then tested against the left-out data. This process is repeated k times, where the portion of left-out data is drawn randomly each time."
},
{
"code": null,
"e": 18171,
"s": 17869,
"text": "The point of this technique is to help avoid overfitting. In your zeal to engineer the perfect model with the highest accuracy, you may accidentally create a model that doesn’t generalize to data outside of your sample. So you always need to be testing your models against data outside of your sample."
},
{
"code": null,
"e": 18480,
"s": 18171,
"text": "Of the classifiers mentioned above, logistic regression and decision trees are the easiest to understand. Random forests are ensemble models constructed from many decision trees. They tend to do well out of the box. AdaBoost and XGBoost are newer, more advanced models. XGBoost is very popular with Kagglers."
},
{
"code": null,
"e": 18589,
"s": 18480,
"text": "I won’t cover the mechanics of each classifier in this article, but that information is pretty easy to find."
},
{
"code": null,
"e": 18826,
"s": 18589,
"text": "My assess_model function uses 5-fold cross-validation to test the accuracy of each classifier on both the training set and the test set. The true worth of a model is always how well it performs on the test set. The accuracy of each one:"
},
{
"code": null,
"e": 19242,
"s": 18826,
"text": "# Logistic regressionAverage Train Accuracy: 0.802 ±0.01Average Test Accuracy: 0.780 ±0.02# Decision treeAverage Train Accuracy: 0.974 ±0.00Average Test Accuracy: 0.781 ±0.02# Random forestAverage Train Accuracy: 0.974 ±0.00Average Test Accuracy: 0.791 ±0.03# AdaBoostAverage Train Accuracy: 0.832 ±0.00Average Test Accuracy: 0.804 ±0.02# XGBoostAverage Train Accuracy: 0.964 ±0.00Average Test Accuracy: 0.820 ±0.03"
},
{
"code": null,
"e": 19411,
"s": 19242,
"text": "It’s important to note that we’ve used the “out-of-the-box” version of each of these classifiers. These use default values for all of their internal tunable parameters."
},
{
"code": null,
"e": 19596,
"s": 19411,
"text": "Notice how a classifier sometimes gets ~97% accuracy on the training set. That looks amazing, but it’s overfitting. The test accuracy is lower and it’s the variable we care more about."
},
{
"code": null,
"e": 19749,
"s": 19596,
"text": "Of these classifiers, XGBoost has the highest test accuracy. This is one of the reasons why Kaggler’s love XGBoost — great performance with zero tuning."
},
{
"code": null,
"e": 19919,
"s": 19749,
"text": "Most machine learning models have tunable parameters that often influence model accuracy. The best-performing values for these parameters is different for every problem."
},
{
"code": null,
"e": 20029,
"s": 19919,
"text": "In ML, these parameters are often referred to as “hyperparameters” and tuning them is as much art as science."
},
{
"code": null,
"e": 20275,
"s": 20029,
"text": "There are tools out there to help with tuning. TPOT is one example. But keeping it simple, we’re going to perform a simple grid search and manually test a whole range of plausible hyperparameter values to see which one gives us the best results."
},
{
"code": null,
"e": 20340,
"s": 20275,
"text": "scikit-learn has a convenient tool for performing grid searches."
},
{
"code": null,
"e": 20437,
"s": 20340,
"text": "This code takes some time to run, as it tries all the different combinations of hyperparameters."
},
{
"code": null,
"e": 20632,
"s": 20437,
"text": "You can modify the parameter grid to change the search space. Remember, this technique won’t find the best possible hyperparameter values, only the best combination from within the search space."
},
{
"code": null,
"e": 20659,
"s": 20632,
"text": "With this approach we get:"
},
{
"code": null,
"e": 20880,
"s": 20659,
"text": "{'bootstrap': True, 'max_depth': 6, 'max_features': 'auto', 'min_samples_leaf': 2, 'min_samples_split': 4, 'n_estimators': 100}RandomForestClassifier(max_depth=6, min_samples_leaf=2, min_samples_split=4)0.830804623499046"
},
{
"code": null,
"e": 21195,
"s": 20880,
"text": "So there you have it. You’d be hard pressed to outperform 83% on the Kaggle Titanic challenge without cheating. I mentioned a few other possible ways of boosting performance, such as age or fare binning, and imputing missing age values based both class and gender. You can try these and see if they boost accuracy."
},
{
"code": null,
"e": 21539,
"s": 21195,
"text": "In conclusion, approaching a data science problem is stepwise process of starting from a clean slate, getting to know your data, cleaning it, and then iteratively testing different models and adding more features until you achieve good model performance. From there, you optimize your best model to squeeze a little more performance out of it."
},
{
"code": null,
"e": 21822,
"s": 21539,
"text": "What happens next? Well if you’re a researcher, you publish your results. If you’re an entrepreneur, you operationalize your model to do something useful that others will pay money for. If you’re a Kaggler, you submit your test predictions for a shot at glory (and sometimes money)."
}
] |
QlikView - Fill Function
|
The Fill function in QlikView is used to fill values from existing fields into a new field.
Let us consider the following input data, which represents the actual and forecasted sales figures.
Month,Forecast,Actual
March,2145,2247
April,2458,
May,1245,
June,5124,3652
July,7421,7514
August,2584,
September,5314,4251
October,7846,6354
November,6532,7451
December,4625,1424
January,8547,7852
February,3265,
The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data.
After clicking Next in the above step, we choose the Enable Transformation Step button
to carry out the required data transformation.
As we are going to use the Fill function, let us choose the Fill tab, which displays th empty values under the Actual Field.
On clicking the Fill button, the option to choose target column and the cell condition appears. We choose column three, as we want to fill the empty values of this column with values from same row in column two. Also, choose the Cell Value as empty so that only the empty cells will be overwritten with new values.
On completing the above steps, we get the transformed data as shown below.
The load script for the transformed data can be seen using the script editor. The script shows the expression, which replaces the empty cell values.
The transformed data can be seen by creating a Table Box using the option in the menu Layout → New Sheet Object.
70 Lectures
5 hours
Arthur Fong
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3013,
"s": 2920,
"text": "The Fill function in QlikView is used to fill values from existing fields into a new field. "
},
{
"code": null,
"e": 3113,
"s": 3013,
"text": "Let us consider the following input data, which represents the actual and forecasted sales figures."
},
{
"code": null,
"e": 3326,
"s": 3113,
"text": "Month,Forecast,Actual\nMarch,2145,2247\nApril,2458,\nMay,1245,\nJune,5124,3652\nJuly,7421,7514\nAugust,2584,\nSeptember,5314,4251\nOctober,7846,6354\nNovember,6532,7451\nDecember,4625,1424\nJanuary,8547,7852\nFebruary,3265,\n"
},
{
"code": null,
"e": 3578,
"s": 3326,
"text": "The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the \"Table Files\" option from the \"Data from Files\" tab and browse for the file containing the above data."
},
{
"code": null,
"e": 3712,
"s": 3578,
"text": "After clicking Next in the above step, we choose the Enable Transformation Step button\nto carry out the required data transformation."
},
{
"code": null,
"e": 3837,
"s": 3712,
"text": "As we are going to use the Fill function, let us choose the Fill tab, which displays th empty values under the Actual Field."
},
{
"code": null,
"e": 4152,
"s": 3837,
"text": "On clicking the Fill button, the option to choose target column and the cell condition appears. We choose column three, as we want to fill the empty values of this column with values from same row in column two. Also, choose the Cell Value as empty so that only the empty cells will be overwritten with new values."
},
{
"code": null,
"e": 4227,
"s": 4152,
"text": "On completing the above steps, we get the transformed data as shown below."
},
{
"code": null,
"e": 4376,
"s": 4227,
"text": "The load script for the transformed data can be seen using the script editor. The script shows the expression, which replaces the empty cell values."
},
{
"code": null,
"e": 4489,
"s": 4376,
"text": "The transformed data can be seen by creating a Table Box using the option in the menu Layout → New Sheet Object."
},
{
"code": null,
"e": 4522,
"s": 4489,
"text": "\n 70 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4535,
"s": 4522,
"text": " Arthur Fong"
},
{
"code": null,
"e": 4542,
"s": 4535,
"text": " Print"
},
{
"code": null,
"e": 4553,
"s": 4542,
"text": " Add Notes"
}
] |
host - Unix, Linux Command
|
host - DNS lookup utility
host [-aCdlnrsTwv] [-c class] [-N ndots] [-R number] [-t type] [-W wait] [-m flag] [-4] [-6] {name} [server]
When no arguments or options are given, host prints a short summary of its command line arguments and options.
EXAMPLE-1:
Making simple query for any site say google.com using sitename
$ host google.comoutput:
google.com has address 172.217.26.174google.com has IPv6 address 2404:6800:4007:801::200egoogle.com mail is handled by 20 alt1.aspmx.l.google.com.google.com mail is handled by 30 alt2.aspmx.l.google.com.google.com mail is handled by 40 alt3.aspmx.l.google.com.google.com mail is handled by 10 aspmx.l.google.com.google.com mail is handled by 50 alt4.aspmx.l.google.com.
EXAMPLE-2:
Making host query using IP address:
$ host 172.217.26.174
output:174.26.217.172.in-addr.arpa domain name pointer maa03s22-in-f14.1e100.net.
EXAMPLE-3:
To display MX records for google.com domain
$ host -n -t mx google.com
output:# host -n -t mx google.comgoogle.com mail is handled by 10 aspmx.l.google.com.google.com mail is handled by 50 alt4.aspmx.l.google.com.google.com mail is handled by 40 alt3.aspmx.l.google.com.google.com mail is handled by 20 alt1.aspmx.l.google.com.google.com mail is handled by 30 alt2.aspmx.l.google.com.
EXAMPLE-4:
To find out the domain name servers
$ host -t ns google.comoutput:# host -t ns google.comgoogle.com name server ns3.google.com.google.com name server ns1.google.com.google.com name server ns2.google.com.google.com name server ns4.google.com.
EXAMPLE-5:
Find out the domain TXT record
$ host -t txt google.com
output:google.com descriptive text "v=spf1 include:_spf.google.com ~all"
EXAMPLE-6:
Find out the SOA record:
$ host -t soa google.com
output:google.com has SOA record ns4.google.com. dns-admin.google.com. 143179694 900 900 1800 60
EXAMPLE-7:
Query Particular Name Server
$ host google.com ns4.google.comoutput:
Using domain server:Name: ns4.google.comAddress: 216.239.38.10#53Aliases:google.com has address 216.58.196.110google.com has IPv6 address 2404:6800:4007:806::200egoogle.com mail is handled by 40 alt3.aspmx.l.google.com.google.com mail is handled by 50 alt4.aspmx.l.google.com.google.com mail is handled by 30 alt2.aspmx.l.google.com.google.com mail is handled by 10 aspmx.l.google.com.google.com mail is handled by 20 alt1.aspmx.l.google.com.
EXAMPLE-8:
Display all information regarding Domain Records and Zone:
$ host -a amazon.inoutput:Trying "amazon.in";; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 26969;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 7, ADDITIONAL: 12;; QUESTION SECTION:;amazon.in. IN ANY;; ANSWER SECTION:amazon.in. 5 IN A 178.236.7.18amazon.in. 5 IN A 54.239.32.8amazon.in. 5 IN A 54.239.34.40;; AUTHORITY SECTION:in. 5 IN NS c0.in.afilias-nst.info.in. 5 IN NS a2.in.afilias-nst.info.in. 5 IN NS b2.in.afilias-nst.org.in. 5 IN NS a0.in.afilias-nst.info.in. 5 IN NS b1.in.afilias-nst.in.in. 5 IN NS b0.in.afilias-nst.org.in. 5 IN NS a1.in.afilias-nst.in.;; ADDITIONAL SECTION:a0.in.afilias-nst.info. 5 IN A 199.7.87.1a0.in.afilias-nst.info. 5 IN AAAA 2001:500:29::1a1.in.afilias-nst.in. 5 IN A 115.249.164.142a2.in.afilias-nst.info. 5 IN A 199.249.117.1a2.in.afilias-nst.info. 5 IN AAAA 2001:500:45::1b0.in.afilias-nst.org. 5 IN A 199.253.56.1b0.in.afilias-nst.org. 5 IN AAAA 2001:500:50::1b1.in.afilias-nst.in. 5 IN A 180.179.215.70b1.in.afilias-nst.in. 5 IN AAAA 2401:8800:411:8::70b2.in.afilias-nst.org. 5 IN A 199.249.125.1b2.in.afilias-nst.org. 5 IN AAAA 2001:500:4d::1c0.in.afilias-nst.info. 5 IN A 199.253.57.1Received 498 bytes from 192.168.134.2#53 in 498 ms
EXAMPLE-9:
Get TTL Information
$ host -v -t a google.comoutput:Trying "google.com";; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 37908;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 4, ADDITIONAL: 4;; QUESTION SECTION:;google.com. IN A;; ANSWER SECTION:google.com. 5 IN A 172.217.26.174;; AUTHORITY SECTION:google.com. 5 IN NS ns2.google.com.google.com. 5 IN NS ns4.google.com.google.com. 5 IN NS ns1.google.com.google.com. 5 IN NS ns3.google.com.;; ADDITIONAL SECTION:ns1.google.com. 5 IN A 216.239.32.10ns2.google.com. 5 IN A 216.239.34.10ns3.google.com. 5 IN A 216.239.36.10ns4.google.com. 5 IN A 216.239.38.10Received 180 bytes from 192.168.134.2#53 in 54 ms
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 10603,
"s": 10577,
"text": "host - DNS lookup utility"
},
{
"code": null,
"e": 10712,
"s": 10603,
"text": "host [-aCdlnrsTwv] [-c class] [-N ndots] [-R number] [-t type] [-W wait] [-m flag] [-4] [-6] {name} [server]"
},
{
"code": null,
"e": 10825,
"s": 10712,
"text": "When no arguments or options are given, host prints a short summary of its command line arguments and options.\n "
},
{
"code": null,
"e": 10836,
"s": 10825,
"text": "EXAMPLE-1:"
},
{
"code": null,
"e": 10899,
"s": 10836,
"text": "Making simple query for any site say google.com using sitename"
},
{
"code": null,
"e": 10925,
"s": 10899,
"text": "$ host google.comoutput:\n"
},
{
"code": null,
"e": 11295,
"s": 10925,
"text": "google.com has address 172.217.26.174google.com has IPv6 address 2404:6800:4007:801::200egoogle.com mail is handled by 20 alt1.aspmx.l.google.com.google.com mail is handled by 30 alt2.aspmx.l.google.com.google.com mail is handled by 40 alt3.aspmx.l.google.com.google.com mail is handled by 10 aspmx.l.google.com.google.com mail is handled by 50 alt4.aspmx.l.google.com."
},
{
"code": null,
"e": 11306,
"s": 11295,
"text": "EXAMPLE-2:"
},
{
"code": null,
"e": 11342,
"s": 11306,
"text": "Making host query using IP address:"
},
{
"code": null,
"e": 11365,
"s": 11342,
"text": "$ host 172.217.26.174\n"
},
{
"code": null,
"e": 11447,
"s": 11365,
"text": "output:174.26.217.172.in-addr.arpa domain name pointer maa03s22-in-f14.1e100.net."
},
{
"code": null,
"e": 11458,
"s": 11447,
"text": "EXAMPLE-3:"
},
{
"code": null,
"e": 11502,
"s": 11458,
"text": "To display MX records for google.com domain"
},
{
"code": null,
"e": 11530,
"s": 11502,
"text": "$ host -n -t mx google.com\n"
},
{
"code": null,
"e": 11845,
"s": 11530,
"text": "output:# host -n -t mx google.comgoogle.com mail is handled by 10 aspmx.l.google.com.google.com mail is handled by 50 alt4.aspmx.l.google.com.google.com mail is handled by 40 alt3.aspmx.l.google.com.google.com mail is handled by 20 alt1.aspmx.l.google.com.google.com mail is handled by 30 alt2.aspmx.l.google.com."
},
{
"code": null,
"e": 11856,
"s": 11845,
"text": "EXAMPLE-4:"
},
{
"code": null,
"e": 11892,
"s": 11856,
"text": "To find out the domain name servers"
},
{
"code": null,
"e": 12099,
"s": 11892,
"text": "$ host -t ns google.comoutput:# host -t ns google.comgoogle.com name server ns3.google.com.google.com name server ns1.google.com.google.com name server ns2.google.com.google.com name server ns4.google.com.\n"
},
{
"code": null,
"e": 12110,
"s": 12099,
"text": "EXAMPLE-5:"
},
{
"code": null,
"e": 12141,
"s": 12110,
"text": "Find out the domain TXT record"
},
{
"code": null,
"e": 12167,
"s": 12141,
"text": "$ host -t txt google.com\n"
},
{
"code": null,
"e": 12240,
"s": 12167,
"text": "output:google.com descriptive text \"v=spf1 include:_spf.google.com ~all\""
},
{
"code": null,
"e": 12251,
"s": 12240,
"text": "EXAMPLE-6:"
},
{
"code": null,
"e": 12276,
"s": 12251,
"text": "Find out the SOA record:"
},
{
"code": null,
"e": 12302,
"s": 12276,
"text": "$ host -t soa google.com\n"
},
{
"code": null,
"e": 12399,
"s": 12302,
"text": "output:google.com has SOA record ns4.google.com. dns-admin.google.com. 143179694 900 900 1800 60"
},
{
"code": null,
"e": 12412,
"s": 12401,
"text": "EXAMPLE-7:"
},
{
"code": null,
"e": 12441,
"s": 12412,
"text": "Query Particular Name Server"
},
{
"code": null,
"e": 12482,
"s": 12441,
"text": "$ host google.com ns4.google.comoutput:\n"
},
{
"code": null,
"e": 12925,
"s": 12482,
"text": "Using domain server:Name: ns4.google.comAddress: 216.239.38.10#53Aliases:google.com has address 216.58.196.110google.com has IPv6 address 2404:6800:4007:806::200egoogle.com mail is handled by 40 alt3.aspmx.l.google.com.google.com mail is handled by 50 alt4.aspmx.l.google.com.google.com mail is handled by 30 alt2.aspmx.l.google.com.google.com mail is handled by 10 aspmx.l.google.com.google.com mail is handled by 20 alt1.aspmx.l.google.com."
},
{
"code": null,
"e": 12936,
"s": 12925,
"text": "EXAMPLE-8:"
},
{
"code": null,
"e": 12995,
"s": 12936,
"text": "Display all information regarding Domain Records and Zone:"
},
{
"code": null,
"e": 14751,
"s": 12995,
"text": "$ host -a amazon.inoutput:Trying \"amazon.in\";; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 26969;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 7, ADDITIONAL: 12;; QUESTION SECTION:;amazon.in. IN ANY;; ANSWER SECTION:amazon.in. 5 IN A 178.236.7.18amazon.in. 5 IN A 54.239.32.8amazon.in. 5 IN A 54.239.34.40;; AUTHORITY SECTION:in. 5 IN NS c0.in.afilias-nst.info.in. 5 IN NS a2.in.afilias-nst.info.in. 5 IN NS b2.in.afilias-nst.org.in. 5 IN NS a0.in.afilias-nst.info.in. 5 IN NS b1.in.afilias-nst.in.in. 5 IN NS b0.in.afilias-nst.org.in. 5 IN NS a1.in.afilias-nst.in.;; ADDITIONAL SECTION:a0.in.afilias-nst.info. 5 IN A 199.7.87.1a0.in.afilias-nst.info. 5 IN AAAA 2001:500:29::1a1.in.afilias-nst.in. 5 IN A 115.249.164.142a2.in.afilias-nst.info. 5 IN A 199.249.117.1a2.in.afilias-nst.info. 5 IN AAAA 2001:500:45::1b0.in.afilias-nst.org. 5 IN A 199.253.56.1b0.in.afilias-nst.org. 5 IN AAAA 2001:500:50::1b1.in.afilias-nst.in. 5 IN A 180.179.215.70b1.in.afilias-nst.in. 5 IN AAAA 2401:8800:411:8::70b2.in.afilias-nst.org. 5 IN A 199.249.125.1b2.in.afilias-nst.org. 5 IN AAAA 2001:500:4d::1c0.in.afilias-nst.info. 5 IN A 199.253.57.1Received 498 bytes from 192.168.134.2#53 in 498 ms\n"
},
{
"code": null,
"e": 14762,
"s": 14751,
"text": "EXAMPLE-9:"
},
{
"code": null,
"e": 14782,
"s": 14762,
"text": "Get TTL Information"
},
{
"code": null,
"e": 15689,
"s": 14782,
"text": "$ host -v -t a google.comoutput:Trying \"google.com\";; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 37908;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 4, ADDITIONAL: 4;; QUESTION SECTION:;google.com. IN A;; ANSWER SECTION:google.com. 5 IN A 172.217.26.174;; AUTHORITY SECTION:google.com. 5 IN NS ns2.google.com.google.com. 5 IN NS ns4.google.com.google.com. 5 IN NS ns1.google.com.google.com. 5 IN NS ns3.google.com.;; ADDITIONAL SECTION:ns1.google.com. 5 IN A 216.239.32.10ns2.google.com. 5 IN A 216.239.34.10ns3.google.com. 5 IN A 216.239.36.10ns4.google.com. 5 IN A 216.239.38.10Received 180 bytes from 192.168.134.2#53 in 54 ms\n"
},
{
"code": null,
"e": 15724,
"s": 15689,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 15752,
"s": 15724,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 15786,
"s": 15752,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 15803,
"s": 15786,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 15836,
"s": 15803,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 15847,
"s": 15836,
"text": " Pradeep D"
},
{
"code": null,
"e": 15882,
"s": 15847,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 15898,
"s": 15882,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 15931,
"s": 15898,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 15943,
"s": 15931,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 15975,
"s": 15943,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 15983,
"s": 15975,
"text": " Uplatz"
},
{
"code": null,
"e": 15990,
"s": 15983,
"text": " Print"
},
{
"code": null,
"e": 16001,
"s": 15990,
"text": " Add Notes"
}
] |
Swing Examples - Open file Dialog with multi-select option
|
Following example showcase how to show a Open File dialog to select multiple files in swing based application.
We are using the following APIs.
JFileChooser − To create a file chooser.
JFileChooser − To create a file chooser.
JFileChooser.showOpenDialog() − To show an open file dialog.
JFileChooser.showOpenDialog() − To show an open file dialog.
JFileChooser.setMultiSelectionEnabled(true) − To enable the multiple selection of file.
JFileChooser.setMultiSelectionEnabled(true) − To enable the multiple selection of file.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(final JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
JButton button = new JButton("Click Me!");
final JLabel label = new JLabel();
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(true);
int option = fileChooser.showOpenDialog(frame);
if(option == JFileChooser.APPROVE_OPTION){
File[] files = fileChooser.getSelectedFiles();
String fileNames = "";
for(File file: files){
fileNames += file.getName() + " ";
}
label.setText("File(s) Selected: " + fileNames);
}else{
label.setText("Open command canceled");
}
}
});
panel.add(button);
panel.add(label);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2150,
"s": 2039,
"text": "Following example showcase how to show a Open File dialog to select multiple files in swing based application."
},
{
"code": null,
"e": 2183,
"s": 2150,
"text": "We are using the following APIs."
},
{
"code": null,
"e": 2224,
"s": 2183,
"text": "JFileChooser − To create a file chooser."
},
{
"code": null,
"e": 2265,
"s": 2224,
"text": "JFileChooser − To create a file chooser."
},
{
"code": null,
"e": 2326,
"s": 2265,
"text": "JFileChooser.showOpenDialog() − To show an open file dialog."
},
{
"code": null,
"e": 2387,
"s": 2326,
"text": "JFileChooser.showOpenDialog() − To show an open file dialog."
},
{
"code": null,
"e": 2475,
"s": 2387,
"text": "JFileChooser.setMultiSelectionEnabled(true) − To enable the multiple selection of file."
},
{
"code": null,
"e": 2563,
"s": 2475,
"text": "JFileChooser.setMultiSelectionEnabled(true) − To enable the multiple selection of file."
},
{
"code": null,
"e": 4415,
"s": 2563,
"text": "import java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.awt.LayoutManager;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.io.File;\n\nimport javax.swing.JButton;\nimport javax.swing.JFileChooser;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\n\npublic class SwingTester {\n public static void main(String[] args) {\n createWindow();\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Swing Tester\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n createUI(frame);\n frame.setSize(560, 200); \n frame.setLocationRelativeTo(null); \n frame.setVisible(true);\n }\n\n private static void createUI(final JFrame frame){ \n JPanel panel = new JPanel();\n LayoutManager layout = new FlowLayout(); \n panel.setLayout(layout); \n\n JButton button = new JButton(\"Click Me!\");\n final JLabel label = new JLabel();\n\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n JFileChooser fileChooser = new JFileChooser();\n fileChooser.setMultiSelectionEnabled(true);\n\n int option = fileChooser.showOpenDialog(frame);\n if(option == JFileChooser.APPROVE_OPTION){\n File[] files = fileChooser.getSelectedFiles();\n String fileNames = \"\";\n for(File file: files){\n fileNames += file.getName() + \" \";\n }\n label.setText(\"File(s) Selected: \" + fileNames);\n }else{\n label.setText(\"Open command canceled\");\n }\n }\n });\n\n panel.add(button);\n panel.add(label);\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n } \n} "
},
{
"code": null,
"e": 4422,
"s": 4415,
"text": " Print"
},
{
"code": null,
"e": 4433,
"s": 4422,
"text": " Add Notes"
}
] |
Java - The Set Interface
|
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.
The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.
The methods declared by Set are summarized in the following table −
add( )
Adds an object to the collection.
clear( )
Removes all objects from the collection.
contains( )
Returns true if a specified object is an element within the collection.
isEmpty( )
Returns true if the collection has no elements.
iterator( )
Returns an Iterator object for the collection, which may be used to retrieve an object.
remove( )
Removes a specified object from the collection.
size( )
Returns the number of elements in the collection.
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality −
import java.util.*;
public class SetDemo {
public static void main(String args[]) {
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try {
for(int i = 0; i < 5; i++) {
set.add(count[i]);
}
System.out.println(set);
TreeSet sortedSet = new TreeSet<Integer>(set);
System.out.println("The sorted list is:");
System.out.println(sortedSet);
System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
}
catch(Exception e) {}
}
}
This will produce the following result −
[34, 22, 10, 60, 30]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60
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": 2483,
"s": 2377,
"text": "A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction."
},
{
"code": null,
"e": 2614,
"s": 2483,
"text": "The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited."
},
{
"code": null,
"e": 2797,
"s": 2614,
"text": "Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ."
},
{
"code": null,
"e": 2865,
"s": 2797,
"text": "The methods declared by Set are summarized in the following table −"
},
{
"code": null,
"e": 2872,
"s": 2865,
"text": "add( )"
},
{
"code": null,
"e": 2906,
"s": 2872,
"text": "Adds an object to the collection."
},
{
"code": null,
"e": 2915,
"s": 2906,
"text": "clear( )"
},
{
"code": null,
"e": 2956,
"s": 2915,
"text": "Removes all objects from the collection."
},
{
"code": null,
"e": 2968,
"s": 2956,
"text": "contains( )"
},
{
"code": null,
"e": 3040,
"s": 2968,
"text": "Returns true if a specified object is an element within the collection."
},
{
"code": null,
"e": 3051,
"s": 3040,
"text": "isEmpty( )"
},
{
"code": null,
"e": 3099,
"s": 3051,
"text": "Returns true if the collection has no elements."
},
{
"code": null,
"e": 3111,
"s": 3099,
"text": "iterator( )"
},
{
"code": null,
"e": 3199,
"s": 3111,
"text": "Returns an Iterator object for the collection, which may be used to retrieve an object."
},
{
"code": null,
"e": 3209,
"s": 3199,
"text": "remove( )"
},
{
"code": null,
"e": 3257,
"s": 3209,
"text": "Removes a specified object from the collection."
},
{
"code": null,
"e": 3266,
"s": 3257,
"text": " size( )"
},
{
"code": null,
"e": 3316,
"s": 3266,
"text": "Returns the number of elements in the collection."
},
{
"code": null,
"e": 3455,
"s": 3316,
"text": "Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality −"
},
{
"code": null,
"e": 4140,
"s": 3455,
"text": "import java.util.*;\npublic class SetDemo {\n\n public static void main(String args[]) { \n int count[] = {34, 22,10,60,30,22};\n Set<Integer> set = new HashSet<Integer>();\n try {\n for(int i = 0; i < 5; i++) {\n set.add(count[i]);\n }\n System.out.println(set);\n\n TreeSet sortedSet = new TreeSet<Integer>(set);\n System.out.println(\"The sorted list is:\");\n System.out.println(sortedSet);\n\n System.out.println(\"The First element of the set is: \"+ (Integer)sortedSet.first());\n System.out.println(\"The last element of the set is: \"+ (Integer)sortedSet.last());\n }\n catch(Exception e) {}\n }\n} "
},
{
"code": null,
"e": 4181,
"s": 4140,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4315,
"s": 4181,
"text": "[34, 22, 10, 60, 30]\nThe sorted list is:\n[10, 22, 30, 34, 60]\nThe First element of the set is: 10\nThe last element of the set is: 60\n"
},
{
"code": null,
"e": 4348,
"s": 4315,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4364,
"s": 4348,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4397,
"s": 4364,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4413,
"s": 4397,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4448,
"s": 4413,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4462,
"s": 4448,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4496,
"s": 4462,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4510,
"s": 4496,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4547,
"s": 4510,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4562,
"s": 4547,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4595,
"s": 4562,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4614,
"s": 4595,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4621,
"s": 4614,
"text": " Print"
},
{
"code": null,
"e": 4632,
"s": 4621,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.