title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to get MySQL query result in same order as given by IN clause? | For this, you can use IN() along with ORDER BY FIELD(). Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
FirstName varchar(100)
);
Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values('Sam');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(FirstName) values('Carol');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(FirstName) values('David');
Query OK, 1 row affected (0.42 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-----------+
| Id | FirstName |
+----+-----------+
| 1 | Chris |
| 2 | Robert |
| 3 | Mike |
| 4 | Sam |
| 5 | Carol |
| 6 | David |
+----+-----------+
6 rows in set (0.00 sec)
The following is how to get query results in the same order as given by the IN clause.
mysql> select FirstName from DemoTable where Id IN(4,5,6) order by field(Id,4,5,6);
This will produce the following output −
+-----------+
| FirstName |
+-----------+
| Sam |
| Carol |
| David |
+-----------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "For this, you can use IN() along with ORDER BY FIELD(). Let us first create a table −"
},
{
"code": null,
"e": 1293,
"s": 1148,
"text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n FirstName varchar(100)\n);\nQuery OK, 0 rows affected (0.64 sec)"
},
{
"code": null,
"e": 1349,
"s": 1293,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1905,
"s": 1349,
"text": "mysql> insert into DemoTable(FirstName) values('Chris');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable(FirstName) values('Robert');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable(FirstName) values('Mike');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(FirstName) values('Sam');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable(FirstName) values('Carol');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable(FirstName) values('David');\nQuery OK, 1 row affected (0.42 sec)"
},
{
"code": null,
"e": 1965,
"s": 1905,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1996,
"s": 1965,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2037,
"s": 1996,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2252,
"s": 2037,
"text": "+----+-----------+\n| Id | FirstName |\n+----+-----------+\n| 1 | Chris |\n| 2 | Robert |\n| 3 | Mike |\n| 4 | Sam |\n| 5 | Carol |\n| 6 | David |\n+----+-----------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2339,
"s": 2252,
"text": "The following is how to get query results in the same order as given by the IN clause."
},
{
"code": null,
"e": 2423,
"s": 2339,
"text": "mysql> select FirstName from DemoTable where Id IN(4,5,6) order by field(Id,4,5,6);"
},
{
"code": null,
"e": 2464,
"s": 2423,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2587,
"s": 2464,
"text": "+-----------+\n| FirstName |\n+-----------+\n| Sam |\n| Carol |\n| David |\n+-----------+\n3 rows in set (0.00 sec)"
}
]
|
Sort the numbers according to their sum of digits - GeeksforGeeks | 29 Apr, 2022
Given an array arr[] of N non-negative integers, the task is to sort these integers according to sum of their digits.Examples:
Input: arr[] = {12, 10, 102, 31, 15} Output: 10 12 102 31 15 10 => 1 + 0 = 1 12 => 1 + 2 = 3 102 => 1 + 0 + 2 = 3 31 => 3 + 1= 4 15 => 1 + 5 = 6Input: arr[] = {14, 1101, 10, 35, 0} Output: 0 10 1101 14 35
First Approach: The idea is to store each element with its sum of digits in a vector pair and then sort all the elements of the vector according to the digit sums stored. Finally, print the elements in order.Below is the implementation of the above approach:
C++
Python3
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum// of the digits of nint sumOfDigit(int n){ int sum = 0; while (n > 0) { sum += n % 10; n = n / 10; } return sum;} // Function to sort the array according to// the sum of the digits of elementsvoid sortArr(int arr[], int n){ // Vector to store digit sum with respective element vector<pair<int, int> > vp; // Inserting digit sum with element in the vector pair for (int i = 0; i < n; i++) { vp.push_back(make_pair(sumOfDigit(arr[i]), arr[i])); } // Quick sort the vector, this will sort the pair // according to sum of the digits of elements sort(vp.begin(), vp.end()); // Print the sorted vector content for (int i = 0; i < vp.size(); i++) cout << vp[i].second << " ";} // Driver codeint main(){ int arr[] = { 14, 1101, 10, 35, 0 }; int n = sizeof(arr) / sizeof(arr[0]); sortArr(arr, n); return 0;}
# Python3 implementation of the approach # Function to return the sum# of the digits of ndef sumOfDigit(n) : sum = 0; while (n > 0) : sum += n % 10; n = n // 10; return sum; # Function to sort the array according to# the sum of the digits of elementsdef sortArr(arr, n) : # Vector to store digit sum with # respective element vp = []; # Inserting digit sum with element # in the vector pair for i in range(n) : vp.append([sumOfDigit(arr[i]), arr[i]]); # Quick sort the vector, this will # sort the pair according to sum # of the digits of elements vp.sort() # Print the sorted vector content for i in range(len(vp)) : print(vp[i][1], end = " "); # Driver codeif __name__ == "__main__" : arr = [14, 1101, 10, 35, 0]; n = len(arr); sortArr(arr, n); # This code is contributed by Ryuga
<script> // JavaScript implementation of the approach // Function to return the sum// of the digits of nfunction sumOfDigit(n){ let sum = 0; while (n > 0) { sum += n % 10; n = Math.floor(n / 10); } return sum;} // Function to sort the array according to// the sum of the digits of elementsfunction sortArr(arr, n){ // Vector to store digit sum with respective element let vp = []; // Inserting digit sum with element in the vector pair for (let i = 0; i < n; i++) { vp.push([sumOfDigit(arr[i]), arr[i]]); } // Quick sort the vector, this will sort the pair // according to sum of the digits of elements vp.sort(); // Print the sorted vector content for (let i = 0; i < vp.length; i++) document.write(vp[i][1]," ");} // Driver codelet arr = [ 14, 1101, 10, 35, 0 ];let n = arr.length;sortArr(arr, n); // This code is contributed by shinjanpatra </script>
0 10 1101 14 35
Time Complexity: O(n log n) for merge sort and heap sort but O(n^2) for quick sort
Auxiliary Space: O(n)
Second Approach: The idea is to use built-in sort function with a comparator function that computes sum for each pair of comparing integers.
1. Pass the array arr into sort function with Sum_Compare comparator function.
2. Inside Sum_Compare function, calculate sum of digits of both numbers x and y as sumx and sumy by taking modulus by 10 and then dividing it by 10.
3. return whether sumx is less than sumy.
C++14
#include <bits/stdc++.h> using namespace std; bool Sum_Compare(int x,int y){ int tempx=x,tempy=y; int sumx=0,sumy=0; while(tempx) { sumx+=tempx%10; tempx/=10; } while(tempy) { sumy+=tempy%10; tempy/=10; } return sumx<sumy;} int main(){ int arr[]={12, 10, 102, 31, 15}; int n=sizeof(arr)/sizeof(arr[0]); sort(arr,arr+n,Sum_Compare); for(auto& x:arr) cout<<x<<" "; return 0;}
10 12 102 31 15
Time Complexity: O(n (log n)^2) for merge sort and heap sort but O(n^2 log n) for quick sort.
Auxiliary Space: O(1) for quick sort and heap sort but O(n) for merge sort.
ankthon
prophet1999
shinjanpatra
number-digits
Analysis
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Time Complexity of building a heap
Analysis of different sorting techniques
Bubble Sort
Insertion Sort
Selection Sort
std::sort() in C++ STL
Time Complexities of all Sorting Algorithms | [
{
"code": null,
"e": 25174,
"s": 25146,
"text": "\n29 Apr, 2022"
},
{
"code": null,
"e": 25303,
"s": 25174,
"text": "Given an array arr[] of N non-negative integers, the task is to sort these integers according to sum of their digits.Examples: "
},
{
"code": null,
"e": 25510,
"s": 25303,
"text": "Input: arr[] = {12, 10, 102, 31, 15} Output: 10 12 102 31 15 10 => 1 + 0 = 1 12 => 1 + 2 = 3 102 => 1 + 0 + 2 = 3 31 => 3 + 1= 4 15 => 1 + 5 = 6Input: arr[] = {14, 1101, 10, 35, 0} Output: 0 10 1101 14 35 "
},
{
"code": null,
"e": 25773,
"s": 25512,
"text": "First Approach: The idea is to store each element with its sum of digits in a vector pair and then sort all the elements of the vector according to the digit sums stored. Finally, print the elements in order.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25777,
"s": 25773,
"text": "C++"
},
{
"code": null,
"e": 25785,
"s": 25777,
"text": "Python3"
},
{
"code": null,
"e": 25796,
"s": 25785,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum// of the digits of nint sumOfDigit(int n){ int sum = 0; while (n > 0) { sum += n % 10; n = n / 10; } return sum;} // Function to sort the array according to// the sum of the digits of elementsvoid sortArr(int arr[], int n){ // Vector to store digit sum with respective element vector<pair<int, int> > vp; // Inserting digit sum with element in the vector pair for (int i = 0; i < n; i++) { vp.push_back(make_pair(sumOfDigit(arr[i]), arr[i])); } // Quick sort the vector, this will sort the pair // according to sum of the digits of elements sort(vp.begin(), vp.end()); // Print the sorted vector content for (int i = 0; i < vp.size(); i++) cout << vp[i].second << \" \";} // Driver codeint main(){ int arr[] = { 14, 1101, 10, 35, 0 }; int n = sizeof(arr) / sizeof(arr[0]); sortArr(arr, n); return 0;}",
"e": 26793,
"s": 25796,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the sum# of the digits of ndef sumOfDigit(n) : sum = 0; while (n > 0) : sum += n % 10; n = n // 10; return sum; # Function to sort the array according to# the sum of the digits of elementsdef sortArr(arr, n) : # Vector to store digit sum with # respective element vp = []; # Inserting digit sum with element # in the vector pair for i in range(n) : vp.append([sumOfDigit(arr[i]), arr[i]]); # Quick sort the vector, this will # sort the pair according to sum # of the digits of elements vp.sort() # Print the sorted vector content for i in range(len(vp)) : print(vp[i][1], end = \" \"); # Driver codeif __name__ == \"__main__\" : arr = [14, 1101, 10, 35, 0]; n = len(arr); sortArr(arr, n); # This code is contributed by Ryuga",
"e": 27690,
"s": 26793,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the sum// of the digits of nfunction sumOfDigit(n){ let sum = 0; while (n > 0) { sum += n % 10; n = Math.floor(n / 10); } return sum;} // Function to sort the array according to// the sum of the digits of elementsfunction sortArr(arr, n){ // Vector to store digit sum with respective element let vp = []; // Inserting digit sum with element in the vector pair for (let i = 0; i < n; i++) { vp.push([sumOfDigit(arr[i]), arr[i]]); } // Quick sort the vector, this will sort the pair // according to sum of the digits of elements vp.sort(); // Print the sorted vector content for (let i = 0; i < vp.length; i++) document.write(vp[i][1],\" \");} // Driver codelet arr = [ 14, 1101, 10, 35, 0 ];let n = arr.length;sortArr(arr, n); // This code is contributed by shinjanpatra </script>",
"e": 28618,
"s": 27690,
"text": null
},
{
"code": null,
"e": 28635,
"s": 28618,
"text": "0 10 1101 14 35 "
},
{
"code": null,
"e": 28718,
"s": 28635,
"text": "Time Complexity: O(n log n) for merge sort and heap sort but O(n^2) for quick sort"
},
{
"code": null,
"e": 28740,
"s": 28718,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 28881,
"s": 28740,
"text": "Second Approach: The idea is to use built-in sort function with a comparator function that computes sum for each pair of comparing integers."
},
{
"code": null,
"e": 28960,
"s": 28881,
"text": "1. Pass the array arr into sort function with Sum_Compare comparator function."
},
{
"code": null,
"e": 29109,
"s": 28960,
"text": "2. Inside Sum_Compare function, calculate sum of digits of both numbers x and y as sumx and sumy by taking modulus by 10 and then dividing it by 10."
},
{
"code": null,
"e": 29151,
"s": 29109,
"text": "3. return whether sumx is less than sumy."
},
{
"code": null,
"e": 29157,
"s": 29151,
"text": "C++14"
},
{
"code": "#include <bits/stdc++.h> using namespace std; bool Sum_Compare(int x,int y){ int tempx=x,tempy=y; int sumx=0,sumy=0; while(tempx) { sumx+=tempx%10; tempx/=10; } while(tempy) { sumy+=tempy%10; tempy/=10; } return sumx<sumy;} int main(){ int arr[]={12, 10, 102, 31, 15}; int n=sizeof(arr)/sizeof(arr[0]); sort(arr,arr+n,Sum_Compare); for(auto& x:arr) cout<<x<<\" \"; return 0;}",
"e": 29630,
"s": 29157,
"text": null
},
{
"code": null,
"e": 29647,
"s": 29630,
"text": "10 12 102 31 15 "
},
{
"code": null,
"e": 29741,
"s": 29647,
"text": "Time Complexity: O(n (log n)^2) for merge sort and heap sort but O(n^2 log n) for quick sort."
},
{
"code": null,
"e": 29817,
"s": 29741,
"text": "Auxiliary Space: O(1) for quick sort and heap sort but O(n) for merge sort."
},
{
"code": null,
"e": 29825,
"s": 29817,
"text": "ankthon"
},
{
"code": null,
"e": 29837,
"s": 29825,
"text": "prophet1999"
},
{
"code": null,
"e": 29850,
"s": 29837,
"text": "shinjanpatra"
},
{
"code": null,
"e": 29864,
"s": 29850,
"text": "number-digits"
},
{
"code": null,
"e": 29873,
"s": 29864,
"text": "Analysis"
},
{
"code": null,
"e": 29881,
"s": 29873,
"text": "Sorting"
},
{
"code": null,
"e": 29889,
"s": 29881,
"text": "Sorting"
},
{
"code": null,
"e": 29987,
"s": 29889,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30038,
"s": 29987,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 30075,
"s": 30038,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 30158,
"s": 30075,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 30193,
"s": 30158,
"text": "Time Complexity of building a heap"
},
{
"code": null,
"e": 30234,
"s": 30193,
"text": "Analysis of different sorting techniques"
},
{
"code": null,
"e": 30246,
"s": 30234,
"text": "Bubble Sort"
},
{
"code": null,
"e": 30261,
"s": 30246,
"text": "Insertion Sort"
},
{
"code": null,
"e": 30276,
"s": 30261,
"text": "Selection Sort"
},
{
"code": null,
"e": 30299,
"s": 30276,
"text": "std::sort() in C++ STL"
}
]
|
Practical Guide to DQN. Tensorflow.js implementation of DQN in... | by Ziad SALLOUM | Towards Data Science | “Practice what you know, and it will help to make clear what now you do not know”Rembrandt
The Deep Q-Network proposed by Mnih et al. [2015] is a jumpstart and building point for many deep reinforcement learning algorithms. However, despite its simplicity on the surface, nevertheless, it represents some challenges when implementing it, and when seeking solutions to problems.
This article will use Tensorflow.js as the implementing technology, for the obvious reasons:- The more you need to install stuff, the more unlikely you will make efforts to code the real algorithm.- Javascript is a nice and popular language and very intuitive for those who are familiar with C++, C#, Java, etc...- Sharing a demo on the web is easy and straightforward.
As said the algorithm by itself is quite easy, it can be summarized by the following image
The steps below describe how the algorithm really works:
1- Create Q-Network and Target-Network2- Fill the Experience Buffer with data using the Q-Network3- Repeat the following steps a sufficient number of times4- Get a random sample from the Experience Buffer5- Feed the sample as input to the Q-Network and Target Network 6- Use the output of the Target Network to train the Q-Network (i.e. the output of the Target Network will play the role of the labels for the Q-Network in a standard supervised learning scenario)7- Apply Exploration / Exploitation strategy (ex: Epsilon Greedy)8- If Exploration is selected then generate a random action, else If Exploitation is selected then feed the current state to the Q-Network and deduce action from the output.9- Apply action to the environment, get the reward, and the new state10- Store the old state, action, reward, and new state in the Experience buffer (also called Replay Memory)11- Every few episodes, copy the weights from Q-Network to the Target-Network
It is quite obvious to wonder, why do we need two networks?Actually, the Q learning formula is as follows:
We notice that in order for Q(S, A) to reach its final value, it must become almost equal to R’ + γ max Q(S’,a). So to make Q(S, A) move towards R’ + γ max Q(S’,a), we transform the problem into some kind of supervised learning where we estimate Q(S,A) and R’ + γ max Q(S’,a) become the ‘label’.The weights of the network used to estimate Q(S,A) will get updated via a combination of a Loss function and backpropagation.
But we don’t know the max Q(S’,a), we simply estimate it using the same neural network, however, the weights of this network are changing constantly which gives different values of max Q(S’,a) with each iteration.That makes the estimation of Q(S, A) chasing a moving target.
To solve this issue, we create an identical neural network we call it Target network, while the first network needed to compute Q(S,A) will be called Online network. The aim of the Target network is to have fixed weights for some time in order to stabilize the computation of max Q(S’,a). Then after some iterations, the Target network gets its weights updated by a simple copy of weights from the Online network that the latter had the occasion to learn.
Normalizing inputs. It might be obvious, but beginners might easily forget about this important feature. This would have big consequences on the output since some inputs might have a large range of values while others have a smaller range of values. That does not mean the latter ones are less important than the former. However computation-wise, the large values will crush the small ones. So if you see weird values for some obvious input, it is a good reflex to check if the input has been normalized.
Synchronizing the two Neural networks. DQN uses two neural networks, one that is “online” which means computing Q value at each iteration, the other network, “target”, computes the Q value but is based on a stable set of weights.The “target” network represents the expression R + γ max Q(St+1). The output of the “online” and “target” networks are used to compute the Mean Squared Error (MSE) and then update the weights of the “online” network via backpropagation.Every certain number of iterations the weights of the “online” network should be copied to the “target” network so that the “target” gets the experience learned by the “online” network.The important value here is to set the right value of iterations at which the weights are copied. Too small values, make the system unstable, too large value makes the system unable to learn. So when things are not going in the right direction, it is important to check this parameter.
Filling the experience buffer. At the beginning of the process, it is important to fill the experience buffer by letting the agent interact with the environment and store the current state, action, reward, next state, terminal state, in the experience buffer so that when the learning process generates random samples from this experience.
Sampling size. It is good practice to put the sampling size around half of the experience buffer size because having a small sampling size will make learning from experience inefficient while putting a large one (around the maximum) introduces bias in the learning that you don’t want. For example, if you have a self-driving car, and since most of the time the roads are straight, excessively sampling from straight road experience will make the AI tend to minimize the effect of turnings.
A classical implementation of the DQN is the CartPole game, where the AI agent should move the cart in a way to keep the pole near vertical.The pole must not fall beyond 30° from the vertical and the cart must not reach the edges. Winning is achieved whenever the AI agent collects 300 rewards.
You can check a real implementation of the game at https://rl-lab.com/cartpole/
The following are code snippets of the main part of the algorithm. It contains the main loop and the playStep and the training base on the batch sample.
The train() method contains the main loop of the training. It first initializes the agent and fills the replay memory buffer with experience, then it starts looping: training, then one step playing.
train(agent, maxIterations, batchSize, gamma, learningRate, syncEveryFrames) { // init the agent agent.reset(); // at first fill the replay memory with experience by playing // without any training for (let i = 0; i < agent.replayBufferSize; ++i) { agent.playStep(); } // create optimizer for the training const optimizer = tf.train.adam(learningRate); // loop until all iterations are done let counter = maxIterations; while (counter > 0) { // train the agent by extracting samples from replay memory and // use them as input for the DQN agent.trainOnReplayBatch(batchSize, gamma, optimizer); // after each training, play one step of the game agent.playStep(); if (agent.frameCount % syncEveryFrames === 0) { copyWeights(agent.targetNN, agent.onlineNN); } counter--; }}
The playStep() method, makes the agent play the game for only one step. It uses an epsilon greedy policy that makes it choose random action part of the time and the action that returns max Q value the rest of the time.
// play one step of the game and store result in replay memoryplayStep() {... let action; let actionIndex = 0; const state = this.game.getState(); if (Math.random() < this.epsilon) { // Pick an action at random. actionIndex = this.getRandomAction(); action = ALL_ACTIONS[actionIndex]; } else { // Greedily pick an action based on online DQN output. // use tf.tidy() to clean up after finishing tf.tidy(() => { const stateTensor = getStateTensor(state); actionIndex = this.onlineNN.predict(stateTensor) .argMax(-1).dataSync()[0]; action = ALL_ACTIONS[actionIndex]; }); } // play one step of the game and get the results const result = this.game.step(action); // store experience in replay Memory this.replayMemory.append([state, actionIndex, result.reward, result.state, result.status]); // if terminal state, reset the game if (r.status != 0) {this.reset();}}
The trainOnReplayBatch() extracts a sample from the replayMemory and uses it as input into the DQN, then uses Mean Squared Error as a loss function to update the weights.
// This method is used to train the online network by using batch// samples from the memory replaytrainOnReplayBatch(batchSize, gamma, optimizer){// Get a batch of examples from the replay buffer.const batch = this.replayMemory.sample(batchSize);//define the loss functionconst lossFunction = () => tf.tidy(() => { // example[0] is the state // example[1] is the action // example[2] is the reward // example[3] is the next state // example[4] indicates if this is a terminal state const stateTensor = getStateTensor(batch.map( example => example[0])); const actionTensor = tf.tensor1d(batch.map( example => example[1]), 'int32'); // compute Q value of the current state // note that we use apply() instead of predict // because apply() allow access to the gradient const online = this.onlineNN.apply(stateTensor, {training: true}); const oneHot = tf.oneHot(actionTensor, NUM_ACTIONS); const qs = online.mul(oneHot).sum(-1); // compute the Q value of the next state. // it is R if the next state is terminal // R + max Q(next_state) if the next state is not terminal const rewardTensor = tf.tensor1d(batch.map( example => example[2])); const nextStateTensor = getStateTensor(batch.map( example => example[3])); const nextMaxQTensor = this.targetNN.predict( nextStateTensor).max(-1); const status = tf.tensor1d(batch.map( example => example[4])).asType('float32'); // if terminal state then status = 1 => doneMask = 0 // if not terminal then status = 0 => doneMask = 1 // this will make nextMaxQTensor.mul(doneMask) either 0 or not const doneMask = tf.scalar(1).sub(status); const targetQs = rewardTensor.add( nextMaxQTensor.mul(doneMask).mul(gamma)); // define the mean square error between Q value of current state // and target Q value const mse = tf.losses.meanSquaredError(targetQs, qs); return mse;});// Calculate the gradients of the loss function with respect // to the weights of the online DQN.const grads = tf.variableGrads(lossFunction);// Use the gradients to update the online DQN's weights.optimizer.applyGradients(grads.grads);tf.dispose(grads);}
Finally here is a video in which the DQN agent plays and wins the CartPole game by reaching the reward of 300.
DQN is one of the most popular Deep Reinforcement Learning algorithms. It achieved for the first time superhuman level performance on an Atari game.As the years passed, it has been subject to many improvements, which makes it still among the best-performing DRL agents. | [
{
"code": null,
"e": 131,
"s": 40,
"text": "“Practice what you know, and it will help to make clear what now you do not know”Rembrandt"
},
{
"code": null,
"e": 418,
"s": 131,
"text": "The Deep Q-Network proposed by Mnih et al. [2015] is a jumpstart and building point for many deep reinforcement learning algorithms. However, despite its simplicity on the surface, nevertheless, it represents some challenges when implementing it, and when seeking solutions to problems."
},
{
"code": null,
"e": 788,
"s": 418,
"text": "This article will use Tensorflow.js as the implementing technology, for the obvious reasons:- The more you need to install stuff, the more unlikely you will make efforts to code the real algorithm.- Javascript is a nice and popular language and very intuitive for those who are familiar with C++, C#, Java, etc...- Sharing a demo on the web is easy and straightforward."
},
{
"code": null,
"e": 879,
"s": 788,
"text": "As said the algorithm by itself is quite easy, it can be summarized by the following image"
},
{
"code": null,
"e": 936,
"s": 879,
"text": "The steps below describe how the algorithm really works:"
},
{
"code": null,
"e": 1892,
"s": 936,
"text": "1- Create Q-Network and Target-Network2- Fill the Experience Buffer with data using the Q-Network3- Repeat the following steps a sufficient number of times4- Get a random sample from the Experience Buffer5- Feed the sample as input to the Q-Network and Target Network 6- Use the output of the Target Network to train the Q-Network (i.e. the output of the Target Network will play the role of the labels for the Q-Network in a standard supervised learning scenario)7- Apply Exploration / Exploitation strategy (ex: Epsilon Greedy)8- If Exploration is selected then generate a random action, else If Exploitation is selected then feed the current state to the Q-Network and deduce action from the output.9- Apply action to the environment, get the reward, and the new state10- Store the old state, action, reward, and new state in the Experience buffer (also called Replay Memory)11- Every few episodes, copy the weights from Q-Network to the Target-Network"
},
{
"code": null,
"e": 1999,
"s": 1892,
"text": "It is quite obvious to wonder, why do we need two networks?Actually, the Q learning formula is as follows:"
},
{
"code": null,
"e": 2420,
"s": 1999,
"text": "We notice that in order for Q(S, A) to reach its final value, it must become almost equal to R’ + γ max Q(S’,a). So to make Q(S, A) move towards R’ + γ max Q(S’,a), we transform the problem into some kind of supervised learning where we estimate Q(S,A) and R’ + γ max Q(S’,a) become the ‘label’.The weights of the network used to estimate Q(S,A) will get updated via a combination of a Loss function and backpropagation."
},
{
"code": null,
"e": 2695,
"s": 2420,
"text": "But we don’t know the max Q(S’,a), we simply estimate it using the same neural network, however, the weights of this network are changing constantly which gives different values of max Q(S’,a) with each iteration.That makes the estimation of Q(S, A) chasing a moving target."
},
{
"code": null,
"e": 3151,
"s": 2695,
"text": "To solve this issue, we create an identical neural network we call it Target network, while the first network needed to compute Q(S,A) will be called Online network. The aim of the Target network is to have fixed weights for some time in order to stabilize the computation of max Q(S’,a). Then after some iterations, the Target network gets its weights updated by a simple copy of weights from the Online network that the latter had the occasion to learn."
},
{
"code": null,
"e": 3656,
"s": 3151,
"text": "Normalizing inputs. It might be obvious, but beginners might easily forget about this important feature. This would have big consequences on the output since some inputs might have a large range of values while others have a smaller range of values. That does not mean the latter ones are less important than the former. However computation-wise, the large values will crush the small ones. So if you see weird values for some obvious input, it is a good reflex to check if the input has been normalized."
},
{
"code": null,
"e": 4592,
"s": 3656,
"text": "Synchronizing the two Neural networks. DQN uses two neural networks, one that is “online” which means computing Q value at each iteration, the other network, “target”, computes the Q value but is based on a stable set of weights.The “target” network represents the expression R + γ max Q(St+1). The output of the “online” and “target” networks are used to compute the Mean Squared Error (MSE) and then update the weights of the “online” network via backpropagation.Every certain number of iterations the weights of the “online” network should be copied to the “target” network so that the “target” gets the experience learned by the “online” network.The important value here is to set the right value of iterations at which the weights are copied. Too small values, make the system unstable, too large value makes the system unable to learn. So when things are not going in the right direction, it is important to check this parameter."
},
{
"code": null,
"e": 4932,
"s": 4592,
"text": "Filling the experience buffer. At the beginning of the process, it is important to fill the experience buffer by letting the agent interact with the environment and store the current state, action, reward, next state, terminal state, in the experience buffer so that when the learning process generates random samples from this experience."
},
{
"code": null,
"e": 5423,
"s": 4932,
"text": "Sampling size. It is good practice to put the sampling size around half of the experience buffer size because having a small sampling size will make learning from experience inefficient while putting a large one (around the maximum) introduces bias in the learning that you don’t want. For example, if you have a self-driving car, and since most of the time the roads are straight, excessively sampling from straight road experience will make the AI tend to minimize the effect of turnings."
},
{
"code": null,
"e": 5718,
"s": 5423,
"text": "A classical implementation of the DQN is the CartPole game, where the AI agent should move the cart in a way to keep the pole near vertical.The pole must not fall beyond 30° from the vertical and the cart must not reach the edges. Winning is achieved whenever the AI agent collects 300 rewards."
},
{
"code": null,
"e": 5798,
"s": 5718,
"text": "You can check a real implementation of the game at https://rl-lab.com/cartpole/"
},
{
"code": null,
"e": 5951,
"s": 5798,
"text": "The following are code snippets of the main part of the algorithm. It contains the main loop and the playStep and the training base on the batch sample."
},
{
"code": null,
"e": 6150,
"s": 5951,
"text": "The train() method contains the main loop of the training. It first initializes the agent and fills the replay memory buffer with experience, then it starts looping: training, then one step playing."
},
{
"code": null,
"e": 6976,
"s": 6150,
"text": "train(agent, maxIterations, batchSize, gamma, learningRate, syncEveryFrames) { // init the agent agent.reset(); // at first fill the replay memory with experience by playing // without any training for (let i = 0; i < agent.replayBufferSize; ++i) { agent.playStep(); } // create optimizer for the training const optimizer = tf.train.adam(learningRate); // loop until all iterations are done let counter = maxIterations; while (counter > 0) { // train the agent by extracting samples from replay memory and // use them as input for the DQN agent.trainOnReplayBatch(batchSize, gamma, optimizer); // after each training, play one step of the game agent.playStep(); if (agent.frameCount % syncEveryFrames === 0) { copyWeights(agent.targetNN, agent.onlineNN); } counter--; }}"
},
{
"code": null,
"e": 7195,
"s": 6976,
"text": "The playStep() method, makes the agent play the game for only one step. It uses an epsilon greedy policy that makes it choose random action part of the time and the action that returns max Q value the rest of the time."
},
{
"code": null,
"e": 8166,
"s": 7195,
"text": "// play one step of the game and store result in replay memoryplayStep() {... let action; let actionIndex = 0; const state = this.game.getState(); if (Math.random() < this.epsilon) { // Pick an action at random. actionIndex = this.getRandomAction(); action = ALL_ACTIONS[actionIndex]; } else { // Greedily pick an action based on online DQN output. // use tf.tidy() to clean up after finishing tf.tidy(() => { const stateTensor = getStateTensor(state); actionIndex = this.onlineNN.predict(stateTensor) .argMax(-1).dataSync()[0]; action = ALL_ACTIONS[actionIndex]; }); } // play one step of the game and get the results const result = this.game.step(action); // store experience in replay Memory this.replayMemory.append([state, actionIndex, result.reward, result.state, result.status]); // if terminal state, reset the game if (r.status != 0) {this.reset();}}"
},
{
"code": null,
"e": 8337,
"s": 8166,
"text": "The trainOnReplayBatch() extracts a sample from the replayMemory and uses it as input into the DQN, then uses Mean Squared Error as a loss function to update the weights."
},
{
"code": null,
"e": 10679,
"s": 8337,
"text": "// This method is used to train the online network by using batch// samples from the memory replaytrainOnReplayBatch(batchSize, gamma, optimizer){// Get a batch of examples from the replay buffer.const batch = this.replayMemory.sample(batchSize);//define the loss functionconst lossFunction = () => tf.tidy(() => { // example[0] is the state // example[1] is the action // example[2] is the reward // example[3] is the next state // example[4] indicates if this is a terminal state const stateTensor = getStateTensor(batch.map( example => example[0])); const actionTensor = tf.tensor1d(batch.map( example => example[1]), 'int32'); // compute Q value of the current state // note that we use apply() instead of predict // because apply() allow access to the gradient const online = this.onlineNN.apply(stateTensor, {training: true}); const oneHot = tf.oneHot(actionTensor, NUM_ACTIONS); const qs = online.mul(oneHot).sum(-1); // compute the Q value of the next state. // it is R if the next state is terminal // R + max Q(next_state) if the next state is not terminal const rewardTensor = tf.tensor1d(batch.map( example => example[2])); const nextStateTensor = getStateTensor(batch.map( example => example[3])); const nextMaxQTensor = this.targetNN.predict( nextStateTensor).max(-1); const status = tf.tensor1d(batch.map( example => example[4])).asType('float32'); // if terminal state then status = 1 => doneMask = 0 // if not terminal then status = 0 => doneMask = 1 // this will make nextMaxQTensor.mul(doneMask) either 0 or not const doneMask = tf.scalar(1).sub(status); const targetQs = rewardTensor.add( nextMaxQTensor.mul(doneMask).mul(gamma)); // define the mean square error between Q value of current state // and target Q value const mse = tf.losses.meanSquaredError(targetQs, qs); return mse;});// Calculate the gradients of the loss function with respect // to the weights of the online DQN.const grads = tf.variableGrads(lossFunction);// Use the gradients to update the online DQN's weights.optimizer.applyGradients(grads.grads);tf.dispose(grads);}"
},
{
"code": null,
"e": 10790,
"s": 10679,
"text": "Finally here is a video in which the DQN agent plays and wins the CartPole game by reaching the reward of 300."
}
]
|
IDE | GeeksforGeeks | A computer science portal for geeks | Please enter your email address or userHandle.
12345678910111213141516171819202122232425262728293031323334353637// C++ program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order#include<bits/stdc++.h>using namespace std;// To do two way sort. First sort even numbers in// ascending order, then odd numbers in descending// order.void twoWaySort(int arr[], int n){ int count_pos = 0; // Make all odd numbers negative for (int i=0 ; i<n ; i++) if (arr[i] & 1){ // Check for odd // counting only positive odd numbers if(arr[i] > 0){ count_pos++; } arr[i] *= -1; } // Sort positive odd and all even all numbers sort(arr, arr+n); // Retaining original array for (int i=0 ; i<n ; i++) if (arr[i] & 1) arr[i] *= -1; // sorts all the numbers. sort(arr+count_pos, arr+n);}// Driver codeint main(){ההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
https://ide.geeksforgeeks.org/xXobxp
7 1 -5 -3 2 4 | [
{
"code": null,
"e": 164,
"s": 117,
"text": "Please enter your email address or userHandle."
},
{
"code": null,
"e": 1616,
"s": 164,
"text": "12345678910111213141516171819202122232425262728293031323334353637// C++ program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order#include<bits/stdc++.h>using namespace std;// To do two way sort. First sort even numbers in// ascending order, then odd numbers in descending// order.void twoWaySort(int arr[], int n){ int count_pos = 0; // Make all odd numbers negative for (int i=0 ; i<n ; i++) if (arr[i] & 1){ // Check for odd // counting only positive odd numbers if(arr[i] > 0){ count_pos++; } arr[i] *= -1; } // Sort positive odd and all even all numbers sort(arr, arr+n); // Retaining original array for (int i=0 ; i<n ; i++) if (arr[i] & 1) arr[i] *= -1; // sorts all the numbers. sort(arr+count_pos, arr+n);}// Driver codeint main(){ההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
},
{
"code": null,
"e": 1653,
"s": 1616,
"text": "https://ide.geeksforgeeks.org/xXobxp"
}
]
|
Clockwise Spiral Traversal of Binary Tree - GeeksforGeeks | 14 Feb, 2022
Given a Binary Tree. The task is to print the circular clockwise spiral order traversal of the given binary tree.
For the above binary tree, the circular clockwise spiral order traversal will be 1, 4, 5, 6, 7, 2, 3.
Examples:
Input :
10
/ \
12 13
/ \
14 15
/ \ / \
21 22 23 24
Output : 10, 24, 23, 22, 21, 12, 13, 15, 14
Approach:
First calculate the width of the given tree.Create an auxiliary 2D array of order (width*width)Do level order traversal of the binary tree and store levels in the newly created 2D matrix one by one in respective rows. That is, store nodes at level 0 at row indexed 0, nodes at level 1 at row indexed 1 and so on.Finally, traverse the 2d array in the below fashion: Start from the first row from left to right and print elements.Then traverse the last row from right to left and print elements.Again traverse the second row from left to right and print.Then second last row from right to left and so on and repeat the steps until the complete 2-D array is traversed.
First calculate the width of the given tree.
Create an auxiliary 2D array of order (width*width)
Do level order traversal of the binary tree and store levels in the newly created 2D matrix one by one in respective rows. That is, store nodes at level 0 at row indexed 0, nodes at level 1 at row indexed 1 and so on.
Finally, traverse the 2d array in the below fashion: Start from the first row from left to right and print elements.Then traverse the last row from right to left and print elements.Again traverse the second row from left to right and print.Then second last row from right to left and so on and repeat the steps until the complete 2-D array is traversed.
Start from the first row from left to right and print elements.
Then traverse the last row from right to left and print elements.
Again traverse the second row from left to right and print.
Then second last row from right to left and so on and repeat the steps until the complete 2-D array is traversed.
Below is the implementation of the above approach:
C++
Python3
// C++ program for Clockwise Spiral Traversal// of Binary Tree #include <bits/stdc++.h>using namespace std; // A Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);}//function to calculate the height of the treeint findHeight(struct Node* node){ //Base condition if(node == NULL) return 0; int leftHeight = findHeight(node->left); int rightHeight = findHeight(node->right); //return maximum of left or right subtree height addition with one return 1+(leftHeight > rightHeight ? leftHeight : rightHeight );}// Function to find the width of treevoid findWidth(struct Node* node, int& maxValue, int& minValue, int hd){ if (node == NULL) return; if (hd > maxValue) { maxValue = hd; } if (hd < minValue) { minValue = hd; } findWidth(node->left, maxValue, minValue, hd - 1); findWidth(node->right, maxValue, minValue, hd + 1);} // Function to traverse the tree and// store level order traversal in a matrixvoid BFS(int** mtrx, struct Node* node){ // Create queue for storing // the addresses of nodes queue<struct Node*> qu; qu.push(node); int i = -1, j = -1; struct Node* poped_node = NULL; while (!qu.empty()) { i++; int qsize = qu.size(); while (qsize--) { j++; poped_node = qu.front(); // Store data of node into the matrix mtrx[i][j] = poped_node->key; qu.pop(); if (poped_node->left != NULL) { qu.push(poped_node->left); } if (poped_node->right != NULL) { qu.push(poped_node->right); } } j = -1; }} // Function for Clockwise Spiral Traversal// of Binary Treevoid traverse_matrix(int** mtrx, int height, int width){ int j = 0, k1 = 0, k2 = 0, k3 = height - 1; int k4 = width - 1; for (int round = 0; round < height / 2; round++) { for (j = k2; j < width; j++) { // only print those values which // are not MAX_INTEGER if (mtrx[k1][j] != INT_MAX) { cout << mtrx[k1][j] << ", "; } } k2 = 0; k1++; for (j = k4; j >= 0; j--) { // only print those values which are // not MAX_INTEGER if (mtrx[k3][j] != INT_MAX) { cout << mtrx[k3][j] << ", "; } } k4 = width - 1; k3--; } // condition (one row may be left traversing) // if number of rows in matrix are odd if (height % 2 != 0) { for (j = k2; j < width; j++) { // only print those values which are // not MAX_INTEGER if (mtrx[k1][j] != INT_MAX) { cout << mtrx[k1][j] << ", "; } } }} // A utility function to print clockwise// spiral traversal of treevoid printPattern(struct Node* node){ // max, min has taken for // calculating width of tree int max_value = INT_MIN; int min_value = INT_MAX; int hd = 0; // calculate the width of a tree findWidth(node, max_value, min_value, hd); int width = max_value + abs(min_value); //calculate the height of the tree int height = findHeight(node); // use double pointer to create 2D array int** mtrx = new int*[height]; // initialize width for each row of matrix for (int i = 0; i < height; i++) { mtrx[i] = new int[width]; } // initialize complete matrix with // MAX INTEGER(purpose garbage) for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { mtrx[i][j] = INT_MAX; } } // Store the BFS traversal of the tree // into the 2-D matrix BFS(mtrx, node); // Print the circular clockwise spiral // traversal of the tree traverse_matrix(mtrx, height, width); // release extra memory // allocated for matrix free(mtrx);} // Driver Codeint main(){ /* 10 / \ 12 13 / \ 14 15 / \ / \ 21 22 23 24 Let us create Binary Tree as shown in above example */ Node* root = newNode(10); root->left = newNode(12); root->right = newNode(13); root->right->left = newNode(14); root->right->right = newNode(15); root->right->left->left = newNode(21); root->right->left->right = newNode(22); root->right->right->left = newNode(23); root->right->right->right = newNode(24); cout << "Circular Clockwise Spiral Traversal : \n"; printPattern(root); return 0;}// This code is contributed by MOHAMMAD MUDASSIR
# Python3 program for Clockwise Spiral# Traversal of Binary TreeINT_MAX = 2**31INT_MIN = -2**31 # Binary tree nodeclass newNode: # Constructor to create a newNode def __init__(self, data): self.key = data self.left = None self.right = None # Function to find the width of treedef findWidth(node, maxValue, minValue, hd): if (node == None): return if (hd > maxValue[0]): maxValue[0] = hd if (hd < minValue[0]): minValue[0] = hd findWidth(node.left, maxValue, minValue, hd - 1) findWidth(node.right, maxValue, minValue, hd + 1) # Function to traverse the tree and# store level order traversal in a matrixdef BFS(mtrx,node): # Create queue for storing # the addresses of nodes qu = [] qu.append(node) i = -1 j = -1 poped_node = None while (len(qu)): i += 1 qsize = len(qu) while (qsize > 0): qsize -= 1 j += 1 poped_node = qu[0] # Store data of node into the matrix mtrx[i][j] = poped_node.key qu.pop(0) if (poped_node.left != None): qu.append(poped_node.left) if (poped_node.right != None): qu.append(poped_node.right) j = -1 # Function for Clockwise Spiral# Traversal of Binary Treedef traverse_matrix(mtrx, width): j = 0 k1 = 0 k2 = 0 k3 = width - 1 k4 = width - 1 for round in range(width // 2): for j in range(k2, width): # only print those values which # are not MAX_INTEGER if (mtrx[k1][j] != INT_MAX): print(mtrx[k1][j], ", ", end = "") k2 = 0 k1 += 1 for j in range(k4, -1, -1): # only print those values which are # not MAX_INTEGER if (mtrx[k3][j] != INT_MAX): print(mtrx[k3][j], ", ", end = "") k4 = width - 1 k3 -= 1 # condition (one row may be left traversing) # if number of rows in matrix are odd if (width % 2 != 0): for j in ramge(k2, width): # only print those values which # are not MAX_INTEGER if (mtrx[k1][j] != INT_MAX): print(mtrx[k1][j], ", ", end = "") # A utility function to prclockwise# spiral traversal of treedef printPattern(node): # max, min has taken for # calculating width of tree max_value = [INT_MIN] min_value = [INT_MAX ] hd = 0 # calculate the width of a tree findWidth(node, max_value, min_value, hd) width = max_value[0] + abs(min_value[0]) # use double pointer to # create 2D array mtrx = [0]*width # initialize width for each # row of matrix for i in range(width): mtrx[i] = [0] * width # initialize complete matrix with # MAX INTEGER(purpose garbage) for i in range(width): for j in range(width): mtrx[i][j] = INT_MAX # Store the BFS traversal of the # tree into the 2-D matrix BFS(mtrx, node) # Print the circular clockwise spiral # traversal of the tree traverse_matrix(mtrx, width) # Driver Codeif __name__ == '__main__': """ 10 / \ 12 13 / \ 14 15 / \ / \ 21 22 23 24 Let us create Binary Tree as shown in above example """ root = newNode(10) root.left = newNode(12) root.right = newNode(13) root.right.left = newNode(14) root.right.right = newNode(15) root.right.left.left = newNode(21) root.right.left.right = newNode(22) root.right.right.left = newNode(23) root.right.right.right = newNode(24) print("Circular Clockwise Spiral Traversal :") printPattern(root) # This code is contributed by# SHUBHAMSINGH10
Circular Clockwise Spiral Traversal :
10, 24, 23, 22, 21, 12, 13, 15, 14,
SHUBHAMSINGH10
MohammadMudassir
nidhi_biet
simmytarika5
Binary Tree
C++ Programs
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
cin in C++
CSV file management using C++
Shallow Copy and Deep Copy in C++
Check if given number is perfect square
Passing a function as a parameter in C++
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion | [
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 25358,
"s": 25242,
"text": "Given a Binary Tree. The task is to print the circular clockwise spiral order traversal of the given binary tree. "
},
{
"code": null,
"e": 25461,
"s": 25358,
"text": "For the above binary tree, the circular clockwise spiral order traversal will be 1, 4, 5, 6, 7, 2, 3. "
},
{
"code": null,
"e": 25473,
"s": 25461,
"text": "Examples: "
},
{
"code": null,
"e": 25757,
"s": 25473,
"text": "Input : \n 10\n / \\\n 12 13\n / \\\n 14 15\n / \\ / \\\n 21 22 23 24\nOutput : 10, 24, 23, 22, 21, 12, 13, 15, 14"
},
{
"code": null,
"e": 25771,
"s": 25759,
"text": "Approach: "
},
{
"code": null,
"e": 26437,
"s": 25771,
"text": "First calculate the width of the given tree.Create an auxiliary 2D array of order (width*width)Do level order traversal of the binary tree and store levels in the newly created 2D matrix one by one in respective rows. That is, store nodes at level 0 at row indexed 0, nodes at level 1 at row indexed 1 and so on.Finally, traverse the 2d array in the below fashion: Start from the first row from left to right and print elements.Then traverse the last row from right to left and print elements.Again traverse the second row from left to right and print.Then second last row from right to left and so on and repeat the steps until the complete 2-D array is traversed."
},
{
"code": null,
"e": 26482,
"s": 26437,
"text": "First calculate the width of the given tree."
},
{
"code": null,
"e": 26534,
"s": 26482,
"text": "Create an auxiliary 2D array of order (width*width)"
},
{
"code": null,
"e": 26752,
"s": 26534,
"text": "Do level order traversal of the binary tree and store levels in the newly created 2D matrix one by one in respective rows. That is, store nodes at level 0 at row indexed 0, nodes at level 1 at row indexed 1 and so on."
},
{
"code": null,
"e": 27106,
"s": 26752,
"text": "Finally, traverse the 2d array in the below fashion: Start from the first row from left to right and print elements.Then traverse the last row from right to left and print elements.Again traverse the second row from left to right and print.Then second last row from right to left and so on and repeat the steps until the complete 2-D array is traversed."
},
{
"code": null,
"e": 27170,
"s": 27106,
"text": "Start from the first row from left to right and print elements."
},
{
"code": null,
"e": 27236,
"s": 27170,
"text": "Then traverse the last row from right to left and print elements."
},
{
"code": null,
"e": 27296,
"s": 27236,
"text": "Again traverse the second row from left to right and print."
},
{
"code": null,
"e": 27410,
"s": 27296,
"text": "Then second last row from right to left and so on and repeat the steps until the complete 2-D array is traversed."
},
{
"code": null,
"e": 27463,
"s": 27410,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27467,
"s": 27463,
"text": "C++"
},
{
"code": null,
"e": 27475,
"s": 27467,
"text": "Python3"
},
{
"code": "// C++ program for Clockwise Spiral Traversal// of Binary Tree #include <bits/stdc++.h>using namespace std; // A Tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);}//function to calculate the height of the treeint findHeight(struct Node* node){ //Base condition if(node == NULL) return 0; int leftHeight = findHeight(node->left); int rightHeight = findHeight(node->right); //return maximum of left or right subtree height addition with one return 1+(leftHeight > rightHeight ? leftHeight : rightHeight );}// Function to find the width of treevoid findWidth(struct Node* node, int& maxValue, int& minValue, int hd){ if (node == NULL) return; if (hd > maxValue) { maxValue = hd; } if (hd < minValue) { minValue = hd; } findWidth(node->left, maxValue, minValue, hd - 1); findWidth(node->right, maxValue, minValue, hd + 1);} // Function to traverse the tree and// store level order traversal in a matrixvoid BFS(int** mtrx, struct Node* node){ // Create queue for storing // the addresses of nodes queue<struct Node*> qu; qu.push(node); int i = -1, j = -1; struct Node* poped_node = NULL; while (!qu.empty()) { i++; int qsize = qu.size(); while (qsize--) { j++; poped_node = qu.front(); // Store data of node into the matrix mtrx[i][j] = poped_node->key; qu.pop(); if (poped_node->left != NULL) { qu.push(poped_node->left); } if (poped_node->right != NULL) { qu.push(poped_node->right); } } j = -1; }} // Function for Clockwise Spiral Traversal// of Binary Treevoid traverse_matrix(int** mtrx, int height, int width){ int j = 0, k1 = 0, k2 = 0, k3 = height - 1; int k4 = width - 1; for (int round = 0; round < height / 2; round++) { for (j = k2; j < width; j++) { // only print those values which // are not MAX_INTEGER if (mtrx[k1][j] != INT_MAX) { cout << mtrx[k1][j] << \", \"; } } k2 = 0; k1++; for (j = k4; j >= 0; j--) { // only print those values which are // not MAX_INTEGER if (mtrx[k3][j] != INT_MAX) { cout << mtrx[k3][j] << \", \"; } } k4 = width - 1; k3--; } // condition (one row may be left traversing) // if number of rows in matrix are odd if (height % 2 != 0) { for (j = k2; j < width; j++) { // only print those values which are // not MAX_INTEGER if (mtrx[k1][j] != INT_MAX) { cout << mtrx[k1][j] << \", \"; } } }} // A utility function to print clockwise// spiral traversal of treevoid printPattern(struct Node* node){ // max, min has taken for // calculating width of tree int max_value = INT_MIN; int min_value = INT_MAX; int hd = 0; // calculate the width of a tree findWidth(node, max_value, min_value, hd); int width = max_value + abs(min_value); //calculate the height of the tree int height = findHeight(node); // use double pointer to create 2D array int** mtrx = new int*[height]; // initialize width for each row of matrix for (int i = 0; i < height; i++) { mtrx[i] = new int[width]; } // initialize complete matrix with // MAX INTEGER(purpose garbage) for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { mtrx[i][j] = INT_MAX; } } // Store the BFS traversal of the tree // into the 2-D matrix BFS(mtrx, node); // Print the circular clockwise spiral // traversal of the tree traverse_matrix(mtrx, height, width); // release extra memory // allocated for matrix free(mtrx);} // Driver Codeint main(){ /* 10 / \\ 12 13 / \\ 14 15 / \\ / \\ 21 22 23 24 Let us create Binary Tree as shown in above example */ Node* root = newNode(10); root->left = newNode(12); root->right = newNode(13); root->right->left = newNode(14); root->right->right = newNode(15); root->right->left->left = newNode(21); root->right->left->right = newNode(22); root->right->right->left = newNode(23); root->right->right->right = newNode(24); cout << \"Circular Clockwise Spiral Traversal : \\n\"; printPattern(root); return 0;}// This code is contributed by MOHAMMAD MUDASSIR",
"e": 32239,
"s": 27475,
"text": null
},
{
"code": "# Python3 program for Clockwise Spiral# Traversal of Binary TreeINT_MAX = 2**31INT_MIN = -2**31 # Binary tree nodeclass newNode: # Constructor to create a newNode def __init__(self, data): self.key = data self.left = None self.right = None # Function to find the width of treedef findWidth(node, maxValue, minValue, hd): if (node == None): return if (hd > maxValue[0]): maxValue[0] = hd if (hd < minValue[0]): minValue[0] = hd findWidth(node.left, maxValue, minValue, hd - 1) findWidth(node.right, maxValue, minValue, hd + 1) # Function to traverse the tree and# store level order traversal in a matrixdef BFS(mtrx,node): # Create queue for storing # the addresses of nodes qu = [] qu.append(node) i = -1 j = -1 poped_node = None while (len(qu)): i += 1 qsize = len(qu) while (qsize > 0): qsize -= 1 j += 1 poped_node = qu[0] # Store data of node into the matrix mtrx[i][j] = poped_node.key qu.pop(0) if (poped_node.left != None): qu.append(poped_node.left) if (poped_node.right != None): qu.append(poped_node.right) j = -1 # Function for Clockwise Spiral# Traversal of Binary Treedef traverse_matrix(mtrx, width): j = 0 k1 = 0 k2 = 0 k3 = width - 1 k4 = width - 1 for round in range(width // 2): for j in range(k2, width): # only print those values which # are not MAX_INTEGER if (mtrx[k1][j] != INT_MAX): print(mtrx[k1][j], \", \", end = \"\") k2 = 0 k1 += 1 for j in range(k4, -1, -1): # only print those values which are # not MAX_INTEGER if (mtrx[k3][j] != INT_MAX): print(mtrx[k3][j], \", \", end = \"\") k4 = width - 1 k3 -= 1 # condition (one row may be left traversing) # if number of rows in matrix are odd if (width % 2 != 0): for j in ramge(k2, width): # only print those values which # are not MAX_INTEGER if (mtrx[k1][j] != INT_MAX): print(mtrx[k1][j], \", \", end = \"\") # A utility function to prclockwise# spiral traversal of treedef printPattern(node): # max, min has taken for # calculating width of tree max_value = [INT_MIN] min_value = [INT_MAX ] hd = 0 # calculate the width of a tree findWidth(node, max_value, min_value, hd) width = max_value[0] + abs(min_value[0]) # use double pointer to # create 2D array mtrx = [0]*width # initialize width for each # row of matrix for i in range(width): mtrx[i] = [0] * width # initialize complete matrix with # MAX INTEGER(purpose garbage) for i in range(width): for j in range(width): mtrx[i][j] = INT_MAX # Store the BFS traversal of the # tree into the 2-D matrix BFS(mtrx, node) # Print the circular clockwise spiral # traversal of the tree traverse_matrix(mtrx, width) # Driver Codeif __name__ == '__main__': \"\"\" 10 / \\ 12 13 / \\ 14 15 / \\ / \\ 21 22 23 24 Let us create Binary Tree as shown in above example \"\"\" root = newNode(10) root.left = newNode(12) root.right = newNode(13) root.right.left = newNode(14) root.right.right = newNode(15) root.right.left.left = newNode(21) root.right.left.right = newNode(22) root.right.right.left = newNode(23) root.right.right.right = newNode(24) print(\"Circular Clockwise Spiral Traversal :\") printPattern(root) # This code is contributed by# SHUBHAMSINGH10",
"e": 36133,
"s": 32239,
"text": null
},
{
"code": null,
"e": 36208,
"s": 36133,
"text": "Circular Clockwise Spiral Traversal : \n10, 24, 23, 22, 21, 12, 13, 15, 14,"
},
{
"code": null,
"e": 36225,
"s": 36210,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 36242,
"s": 36225,
"text": "MohammadMudassir"
},
{
"code": null,
"e": 36253,
"s": 36242,
"text": "nidhi_biet"
},
{
"code": null,
"e": 36266,
"s": 36253,
"text": "simmytarika5"
},
{
"code": null,
"e": 36278,
"s": 36266,
"text": "Binary Tree"
},
{
"code": null,
"e": 36291,
"s": 36278,
"text": "C++ Programs"
},
{
"code": null,
"e": 36296,
"s": 36291,
"text": "Tree"
},
{
"code": null,
"e": 36301,
"s": 36296,
"text": "Tree"
},
{
"code": null,
"e": 36399,
"s": 36301,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36410,
"s": 36399,
"text": "cin in C++"
},
{
"code": null,
"e": 36440,
"s": 36410,
"text": "CSV file management using C++"
},
{
"code": null,
"e": 36474,
"s": 36440,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 36514,
"s": 36474,
"text": "Check if given number is perfect square"
},
{
"code": null,
"e": 36555,
"s": 36514,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 36605,
"s": 36555,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 36640,
"s": 36605,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 36674,
"s": 36640,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 36703,
"s": 36674,
"text": "AVL Tree | Set 1 (Insertion)"
}
]
|
Print all sequences of given length in C++ | In this problem, we are given two integer values, k, and n. And we have to
print all the sequences of length k from numbers from 1 to n in sorted order.
Let’s take an example to understand the topic −
Input:k = 2 ; n = 3
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
So in this problem, we have to print the sequence as stated above.
A simple way to solve this problem is by incrementing integers of the sequence till they get to the max value i.e. n. The following is a detailed description of the solution.
1) Create an array of size k with all values = 1 i.e. {1, 1, ..ktimes}.
2) Repeat step 3 and 4 till the array becomes {n, n, ..., n}.
3) Print the array.
4) Increment the value such that the elements of the array become the next value. For example, {1, 1, 1} incremented to {1, 1, 2} and {1, 3, 3} incremented to {2, 1, 1}. For this we need to check the kth element of the array, if it’s equal to n become update, then check k-1 element in the sequence and so on for the same condition.
The following program will make the concept more clear to you.
Live Demo
#include<iostream>
using namespace std;
void printSequence(int arr[], int size){
for(int i = 0; i < size; i++)
cout<<arr[i]<<"\t";
cout<<endl;
return;
}
int nextElement(int arr[], int k, int n){
int s = k - 1;
while (arr[s] == n)
s--;
if (s < 0)
return 0;
arr[s] = arr[s] + 1;
for(int i = s + 1; i < k; i++)
arr[i] = 1;
return 1;
}
void generateSequence(int n, int k){
int *arr = new int[k];
for(int i = 0; i < k; i++)
arr[i] = 1;
while(1){
printSequence(arr, k);
if(nextElement(arr, k, n) == 0)
break;
}
return;
}
int main(){
int n = 3;
int k = 2;
cout<<"The sequence is :\n";
generateSequence(n, k);
return 0;
}
The sequence is −
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
This method is easy to understand but can be made better and more efficient.
This method uses recursion and an extra index to check for sequence offset (value after which the sequence will be flipped). The function will be called recursively and will not update the terms till index. And recure the function for next terms after index.
Live Demo
#include<iostream>
using namespace std;
void printSequence (int arr[], int size){
for (int i = 0; i < size; i++)
cout << arr[i] << "\t";
cout << endl;
return;
}
void generateSequence (int arr[], int n, int k, int index){
int i;
if (k == 0){
printSequence (arr, index);
}
if (k > 0){
for (i = 1; i <= n; ++i){
arr[index] = i;
generateSequence (arr, n, k - 1, index + 1);
}
}
}
int main (){
int n = 3;
int k = 2;
int *arr = new int[k];
cout<<"The sequence is:\n";
generateSequence (arr, n, k, 0);
return 0;
}
The sequence is −
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3 | [
{
"code": null,
"e": 1215,
"s": 1062,
"text": "In this problem, we are given two integer values, k, and n. And we have to\nprint all the sequences of length k from numbers from 1 to n in sorted order."
},
{
"code": null,
"e": 1263,
"s": 1215,
"text": "Let’s take an example to understand the topic −"
},
{
"code": null,
"e": 1327,
"s": 1263,
"text": "Input:k = 2 ; n = 3\nOutput:\n1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n3 3"
},
{
"code": null,
"e": 1394,
"s": 1327,
"text": "So in this problem, we have to print the sequence as stated above."
},
{
"code": null,
"e": 1569,
"s": 1394,
"text": "A simple way to solve this problem is by incrementing integers of the sequence till they get to the max value i.e. n. The following is a detailed description of the solution."
},
{
"code": null,
"e": 2056,
"s": 1569,
"text": "1) Create an array of size k with all values = 1 i.e. {1, 1, ..ktimes}.\n2) Repeat step 3 and 4 till the array becomes {n, n, ..., n}.\n3) Print the array.\n4) Increment the value such that the elements of the array become the next value. For example, {1, 1, 1} incremented to {1, 1, 2} and {1, 3, 3} incremented to {2, 1, 1}. For this we need to check the kth element of the array, if it’s equal to n become update, then check k-1 element in the sequence and so on for the same condition."
},
{
"code": null,
"e": 2119,
"s": 2056,
"text": "The following program will make the concept more clear to you."
},
{
"code": null,
"e": 2130,
"s": 2119,
"text": " Live Demo"
},
{
"code": null,
"e": 2846,
"s": 2130,
"text": "#include<iostream>\nusing namespace std;\nvoid printSequence(int arr[], int size){\n for(int i = 0; i < size; i++)\n cout<<arr[i]<<\"\\t\";\n cout<<endl;\n return;\n}\nint nextElement(int arr[], int k, int n){\n int s = k - 1;\n while (arr[s] == n)\n s--;\n if (s < 0)\n return 0;\n arr[s] = arr[s] + 1;\n for(int i = s + 1; i < k; i++)\n arr[i] = 1;\n return 1;\n}\nvoid generateSequence(int n, int k){\n int *arr = new int[k];\n for(int i = 0; i < k; i++)\n arr[i] = 1;\n while(1){\n printSequence(arr, k);\n if(nextElement(arr, k, n) == 0)\n break;\n }\n return;\n}\nint main(){\n int n = 3;\n int k = 2;\n cout<<\"The sequence is :\\n\";\n generateSequence(n, k);\n return 0;\n}"
},
{
"code": null,
"e": 2864,
"s": 2846,
"text": "The sequence is −"
},
{
"code": null,
"e": 2900,
"s": 2864,
"text": "1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n3 3"
},
{
"code": null,
"e": 2977,
"s": 2900,
"text": "This method is easy to understand but can be made better and more efficient."
},
{
"code": null,
"e": 3236,
"s": 2977,
"text": "This method uses recursion and an extra index to check for sequence offset (value after which the sequence will be flipped). The function will be called recursively and will not update the terms till index. And recure the function for next terms after index."
},
{
"code": null,
"e": 3247,
"s": 3236,
"text": " Live Demo"
},
{
"code": null,
"e": 3838,
"s": 3247,
"text": "#include<iostream>\nusing namespace std;\nvoid printSequence (int arr[], int size){\n for (int i = 0; i < size; i++)\n cout << arr[i] << \"\\t\";\n cout << endl;\n return;\n}\nvoid generateSequence (int arr[], int n, int k, int index){\n int i;\n if (k == 0){\n printSequence (arr, index);\n }\n if (k > 0){\n for (i = 1; i <= n; ++i){\n arr[index] = i;\n generateSequence (arr, n, k - 1, index + 1);\n }\n }\n}\nint main (){\n int n = 3;\n int k = 2;\n int *arr = new int[k];\n cout<<\"The sequence is:\\n\";\n generateSequence (arr, n, k, 0);\n return 0;\n}"
},
{
"code": null,
"e": 3856,
"s": 3838,
"text": "The sequence is −"
},
{
"code": null,
"e": 3892,
"s": 3856,
"text": "1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n3 3"
}
]
|
Explain jQuery.append(), jQuery.prepend(), jQuery.after() and jQuery.before() methods. | jQuery.append()
The append( content ) method appends content to the inside of every matched element. Here is the description of all the parameters used by this method −
content − Content to insert after each target. This could be HTML or Text content
You can try to run the following code to learn how to work with jQuery.append() method:
Live Demo
<html>
<head>
<title>jQuery append() method</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
$(this).append('<div class = "div"></div>' );
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:green;"></div>
<div class = "div" style = "background-color:red;"></div>
</body>
</html>
jQuery.prepend()
The prepend( content ) method prepends content to the inside of every matched element. Here is the description of all the parameters used by this method −
content − Content to insert after each target. This could be HTML or Text content
You can try to run the following code to learn prepend() method:
Live Demo
<html>
<head>
<title>jQuery prepend() method</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
$(this).prepend('<div class = "div"></div>' );
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:green;"></div>
<div class = "div" style = "background-color:red;"></div>
</body>
</html>
jQuery.after()
The after( content ) method inserts content after each of the matched elements. Here is the description of all the parameters used by this method −
content − Content to insert after each target. This could be HTML or Text content
You can try to run the following code to learn how to work with after() method in jQuery:
Live Demo
<html>
<head>
<title>jQuery after() method</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
$(this).after('<div class = "div"></div>' );
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:green;"></div>
<div class = "div" style = "background-color:red;"></div>
</body>
</html>
jQuery.before()
The before( content ) method inserts content before each of the matched elements. Here is the description of the parameters used by this method −
content − Content to insert before each target. This could be HTML or Text content
You can try to run the following code to learn how to work with jQuery before() method:
Live Demo
<html>
<head>
<title>jQuery before() method</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
$(this).before('<div class = "div"></div>' );
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;"></div>
<div class = "div" style = "background-color:green;"></div>
<div class = "div" style = "background-color:red;"></div>
</body>
</html> | [
{
"code": null,
"e": 1078,
"s": 1062,
"text": "jQuery.append()"
},
{
"code": null,
"e": 1231,
"s": 1078,
"text": "The append( content ) method appends content to the inside of every matched element. Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 1313,
"s": 1231,
"text": "content − Content to insert after each target. This could be HTML or Text content"
},
{
"code": null,
"e": 1401,
"s": 1313,
"text": "You can try to run the following code to learn how to work with jQuery.append() method:"
},
{
"code": null,
"e": 1411,
"s": 1401,
"text": "Live Demo"
},
{
"code": null,
"e": 2279,
"s": 1411,
"text": "<html>\n\n <head>\n <title>jQuery append() method</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 $(\"div\").click(function () {\n $(this).append('<div class = \"div\"></div>' );\n });\n });\n </script>\n \n <style>\n .div {\n margin:10px;\n padding:12px;\n border:2px solid #666;\n width:60px;\n }\n </style>\n </head>\n \n <body>\n \n <p>Click on any square below to see the result:</p>\n \n <div class = \"div\" style = \"background-color:blue;\"></div>\n <div class = \"div\" style = \"background-color:green;\"></div>\n <div class = \"div\" style = \"background-color:red;\"></div>\n \n </body>\n \n</html>"
},
{
"code": null,
"e": 2296,
"s": 2279,
"text": "jQuery.prepend()"
},
{
"code": null,
"e": 2451,
"s": 2296,
"text": "The prepend( content ) method prepends content to the inside of every matched element. Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 2533,
"s": 2451,
"text": "content − Content to insert after each target. This could be HTML or Text content"
},
{
"code": null,
"e": 2598,
"s": 2533,
"text": "You can try to run the following code to learn prepend() method:"
},
{
"code": null,
"e": 2608,
"s": 2598,
"text": "Live Demo"
},
{
"code": null,
"e": 3478,
"s": 2608,
"text": "<html>\n\n <head>\n <title>jQuery prepend() method</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n $(\"div\").click(function () {\n $(this).prepend('<div class = \"div\"></div>' );\n });\n });\n </script>\n \n <style>\n .div {\n margin:10px;\n padding:12px;\n border:2px solid #666;\n width:60px;\n }\n </style>\n </head>\n \n <body>\n \n <p>Click on any square below to see the result:</p>\n \n <div class = \"div\" style = \"background-color:blue;\"></div>\n <div class = \"div\" style = \"background-color:green;\"></div>\n <div class = \"div\" style = \"background-color:red;\"></div>\n \n </body>\n \n</html>"
},
{
"code": null,
"e": 3493,
"s": 3478,
"text": "jQuery.after()"
},
{
"code": null,
"e": 3641,
"s": 3493,
"text": "The after( content ) method inserts content after each of the matched elements. Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 3723,
"s": 3641,
"text": "content − Content to insert after each target. This could be HTML or Text content"
},
{
"code": null,
"e": 3813,
"s": 3723,
"text": "You can try to run the following code to learn how to work with after() method in jQuery:"
},
{
"code": null,
"e": 3823,
"s": 3813,
"text": "Live Demo"
},
{
"code": null,
"e": 4689,
"s": 3823,
"text": "<html>\n\n <head>\n <title>jQuery after() method</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n $(\"div\").click(function () {\n $(this).after('<div class = \"div\"></div>' );\n });\n });\n </script>\n \n <style>\n .div {\n margin:10px;\n padding:12px;\n border:2px solid #666;\n width:60px;\n }\n </style>\n </head>\n \n <body>\n \n <p>Click on any square below to see the result:</p>\n \n <div class = \"div\" style = \"background-color:blue;\"></div>\n <div class = \"div\" style = \"background-color:green;\"></div>\n <div class = \"div\" style = \"background-color:red;\"></div>\n \n </body>\n \n</html>"
},
{
"code": null,
"e": 4705,
"s": 4689,
"text": "jQuery.before()"
},
{
"code": null,
"e": 4851,
"s": 4705,
"text": "The before( content ) method inserts content before each of the matched elements. Here is the description of the parameters used by this method −"
},
{
"code": null,
"e": 4934,
"s": 4851,
"text": "content − Content to insert before each target. This could be HTML or Text content"
},
{
"code": null,
"e": 5022,
"s": 4934,
"text": "You can try to run the following code to learn how to work with jQuery before() method:"
},
{
"code": null,
"e": 5032,
"s": 5022,
"text": "Live Demo"
},
{
"code": null,
"e": 5888,
"s": 5032,
"text": "<html>\n\n <head>\n <title>jQuery before() method</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n $(\"div\").click(function () {\n $(this).before('<div class = \"div\"></div>' );\n });\n });\n </script>\n \n <style>\n .div {\n margin:10px;\n padding:12px;\n border:2px solid #666;\n width:60px;\n }\n </style>\n </head>\n \n <body>\n \n <p>Click on any square below to see the result:</p>\n <div class = \"div\" style = \"background-color:blue;\"></div>\n <div class = \"div\" style = \"background-color:green;\"></div>\n <div class = \"div\" style = \"background-color:red;\"></div>\n \n </body>\n</html>"
}
]
|
How to change the visibility of the Cursor of Console in C# | To change the visibility of the Cursor, use the Console.CursorVisible property.
Let us see an example −
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Demo {
public static void Main (string[] args) {
Console.BackgroundColor = ConsoleColor. Black;
Console.WriteLine("Background color changed = "+Console.BackgroundColor);
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("\nForeground color changed = "+Console.ForegroundColor);
Console.InputEncoding = Encoding.ASCII;
Console.WriteLine("Input Encoding Scheme = "+Console.InputEncoding);
Console.OutputEncoding = Encoding.ASCII;
Console.WriteLine("Output Encoding Scheme = "+Console.OutputEncoding);
Console.CursorVisible = false;
Console.Write("\nCursor is Visible? "+ Console.CursorVisible);
}
}
This will produce the following output − | [
{
"code": null,
"e": 1142,
"s": 1062,
"text": "To change the visibility of the Cursor, use the Console.CursorVisible property."
},
{
"code": null,
"e": 1166,
"s": 1142,
"text": "Let us see an example −"
},
{
"code": null,
"e": 1966,
"s": 1166,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nclass Demo {\n public static void Main (string[] args) {\n Console.BackgroundColor = ConsoleColor. Black;\n Console.WriteLine(\"Background color changed = \"+Console.BackgroundColor);\n Console.ForegroundColor = ConsoleColor.White;\n Console.WriteLine(\"\\nForeground color changed = \"+Console.ForegroundColor);\n Console.InputEncoding = Encoding.ASCII;\n Console.WriteLine(\"Input Encoding Scheme = \"+Console.InputEncoding);\n Console.OutputEncoding = Encoding.ASCII;\n Console.WriteLine(\"Output Encoding Scheme = \"+Console.OutputEncoding);\n Console.CursorVisible = false;\n Console.Write(\"\\nCursor is Visible? \"+ Console.CursorVisible);\n }\n}\n"
},
{
"code": null,
"e": 2007,
"s": 1966,
"text": "This will produce the following output −"
}
]
|
Comprehensive Guide To Approximate Nearest Neighbors Algorithms | by Eyal Trabelsi | Towards Data Science | Today as users consume more and more information from the internet at a moment’s notice, there is an increasing need for efficient ways to do search. This is why “Nearest Neighbor” has become a hot research topic, in order to increase the chance of users to find the information they are looking for in reasonable time.
The use cases for “Nearest Neighbor” are endless, and it is in use in many computer-science areas, such as image recognition, machine learning, and computational linguistics (1, 2 and more).
In order to calculate exact nearest neighbors, the following techniques exist:
Exhaustive search- Comparing each point to every other point, which will require Linear query time (the size of the dataset).
The Grid Trick- Subdividing the space into a Grid, which will require exponential space/time (in the dimensionality of the dataset). Since we are speaking on high dimension datasets this is impractical.
I am gonna show how to find similar vectors and will use the movielens dataset to do so (which contain 100k rows), by using an enriched version of the dataset (which already consists of movie labels and their semantic representation). The entire code for this article can be found as a Jupyter Notebook here.
First, we going to load our dataset which already consists of movie labels and their semantic representation which is calculated here.
import pickleimport faissdef load_data(): with open('movies.pickle', 'rb') as f: data = pickle.load(f) return datadata = load_data()data
As we can see data is actually a dictionary, the name column consists of the movies’ names, and the vector column consists of the movies vector representation.
I am going to show how to do an exhaustive search using faiss. We first going to create the index class.
class ExactIndex(): def __init__(self, vectors, labels): self.dimension = vectors.shape[1] self.vectors = vectors.astype('float32') self.labels = labels def build(self): self.index = faiss.IndexFlatL2(self.dimension,) self.index.add(self.vectors) def query(self, vectors, k=10): distances, indices = self.index.search(vectors, k) # I expect only query on one vector thus the slice return [self.labels[i] for i in indices[0]]
After I define the index class I can build the index with my dataset using the following snippets.
index = ExactIndex(data["vector"], data["name"])index.build()
Now it’s pretty easy to search, let’s say I want to search for the movies that are most similar to “Toy Story” (its located in index number 0) I can write the following code:
index.query(data['vector'][0])
And that’s it, we have done exact search, we can go nap now :).
Unfortunately, most modern-day applications have massive datasets with high dimensionality (hundreds or thousands) so linear scan will take a while. If that’s not enough, often there are additional constraints such as reasonable memory consumption and/or low latency.
It’s important to note that despite all recent advances on the topic, the only available method for guaranteed retrieval of the exact nearest neighbor is exhaustive search (due to the curse of dimensionality.)
This makes exact nearest neighbors impractical even and allows “Approximate Nearest Neighbors “ (ANN) to come into the game. A similarity search can be orders of magnitude faster if we’re willing to trade some accuracy.
To give a small intuition why approximate nearest neighbors might be good enough I will give two examples:
Visual Search: As a user, if I look for a bee picture I don’t mind which ones I get out of these three pictures.
Recommendations: As a user, I don’t really mind the order of the nearest neighbors or even if I have only eight of the ten best candidates.
Approximate Nearest Neighbor techniques speed up the search by preprocessing the data into an efficient index and are often tackled using these phases:
Vector Transformation — applied on vectors before they are indexed, amongst them, there is dimensionality reduction and vector rotation. In order to this article well structured and somewhat concise, I won't discuss this.
Vector Encoding — applied on vectors in order to construct the actual index for search, amongst these, there are data structure-based techniques like Trees, LSH, and Quantization a technique to encode the vector to a much more compact form.
None Exhaustive Search Component — applied on vectors in order to avoid exhaustive search, amongst these techniques there are Inverted Files and Neighborhood Graphs.
Tree-based algorithms are one of the most common strategies when it comes to ANN. They construct forests (collection of trees) as their data structure by splitting the dataset into subsets.
One of the most prominent solutions out there is Annoy, which uses trees (more accurately forests) to enable Spotify’ music recommendations. Since there is a comprehensive explanation I will only provide here the intuition behind it, how it should be used, the pros and the cons.
In Annoy, in order to construct the index we create a forest (aka many trees) Each tree is constructed in the following way, we pick two points at random and split the space into two by their hyperplane, we keep splitting into the subspaces recursively until the points associated with a node is small enough.
In order to search the constructed index, the forest is traversed in order to obtain a set of candidate points from which the closest to the query point is returned.
We are going to create an index class like before. We are going to use annoy library. As you can imagine most of the logic is in the build method (index creation), where the accuracy-performance tradeoff is controlled by :
number_of_trees — the number of binary trees we build, a larger value will give more accurate results, but larger indexes.
search_k — the number of binary trees we search for each point, a larger value will give more accurate results, but will take a longer time to return.
class AnnoyIndex(): def __init__(self, vectors, labels): self.dimension = vectors.shape[1] self.vectors = vectors.astype('float32') self.labels = labels def build(self, number_of_trees=5): self.index = annoy.AnnoyIndex(self.dimension) for i, vec in enumerate(self.vectors): self.index.add_item(i, vec.tolist()) self.index.build(number_of_trees) def query(self, vector, k=10): indices = self.index.get_nns_by_vector( vector.tolist(), k, search_k=search_in_x_trees) return [self.labels[i] for i in indices]
After I define the Annoy index class I can build the index with my dataset using the following snippets.
index = AnnoyIndex(data["vector"], data["name"])index.build()
Now it’s pretty easy to search, let’s say I want to search for the movies that are most similar to “Toy Story” (it's located in index number 0).
index.query(data['vector'][0])
And that’s it, we have search efficiently using annoy for movies similar to “Toy Story” and we got approximated results.
It’s important to note, that I am going to declare Pros and Cons per implementation and not per technique.
Annoy Pros
Decouple index creation from loading them, so you can pass around indexes as files and map them into memory quickly.
We can tune the parameters to change the accuracy/speed tradeoff.
It has the ability to use static files as indexes, this means you can share indexes across processes.
Annoy Cons
The exact nearest neighbor might be across the boundary to one of the neighboring cells.
No support for GPU processing.
No support for batch processing, so in order to increase throughput “further hacking is required”.
Cant incrementally add points to it (annoy2 tries to fix this).
LSH-based algorithms are one of the most common strategies when it comes to ANN. They construct a hash table as their data structure by mapping points that are nearby into the same bucket.
One of the most prominent implementations out there is Faiss, by facebook. Since there are plenty of LSH explanations out there I will only provide here the intuition behind it, how it should be used, the pros, and the cons.
In LSH, in order to construct the index, we apply multiple hash functions to map data points into buckets so that data points near each other are located in the same buckets with high probability, while data points far from each other are likely to fall into different buckets.
In order to search the constructed index, the query point is hashed in order to obtain the closest buckets (a set of candidate points) from which the closest to the query points are returned.
It's important to note there are some advancements I have not to check yet like the fly algorithm and LSH on GPU.
I am going to show how to use faiss, to do “Approximate Nearest Neighbors Using LSH”. We are going to create the index class, as you can see most of the logic is in the build method (index creation), where you can control:
num_bits — A larger value will give more accurate results, but larger indexes.
class LSHIndex(): def __init__(self, vectors, labels): self.dimension = vectors.shape[1] self.vectors = vectors.astype('float32') self.labels = labels def build(self, num_bits=8): self.index = faiss.IndexLSH(self.dimension, num_bits) self.index.add(self.vectors) def query(self, vectors, k=10): distances, indices = self.index.search(vectors, k) # I expect only query on one vector thus the slice return [self.labels[i] for i in indices[0]]
After I define the LSH index class I can build the index with my dataset using the following snippets.
index = LSHIndex(data["vector"], data["name"])index.build()
Now it’s pretty easy to search, let’s say I want to search for the movies that are most similar to “Toy Story” (it's located in index number 0).
index.query(data['vector'][0])
And that’s it, we have search efficiently using annoy for movies similar to “Toy Story” and we got approximated results.
Like before I am going to declare Pros and Cons per implementation and not per technique.
LSH Pros
Data characteristics such as data distribution are not needed to generate these random hash functions.
The accuracy of the approximate search can be tuned without rebuilding the data structure.
Good theoretical guarantees of sub-linear query time.
LSH Cons
In practice, the algorithm MIGHT runs slower than a linear scan.
No support for GPU processing.
Require a lot of RAM.
Although we managed to improve query performance by constructing an index, we didn’t take into account additional constraints.
Like many engineers, we assumed that linear storage as a “no issue” (due to systems like S3). However in practice, linear storage can become very costly very fast, and the fact that some algorithm requires to load them to RAM and that many systems don’t have separation of storage/compute definitely don’t improve the situation.
This is why Quantization-based algorithms are one of the most common strategies when it comes to ANN.
Quantization is a technique to reduce dataset size (from linear) by defining a function (quantizer) that encodes our data into a compact approximated representation.
The intuition of this method is as follows, we can reduce the size of the dataset by replacing every vector with a leaner approximated representation of the vectors (using quantizer) in the encoding phase.
One way to achieve a leaner approximated representation is to give similar vectors to the same representation. This can be done by clustering similar vectors and represent each of those in the same manner (the centroid representation), the most popular way to do so is using k-means.
Since k-means divide the vectors in space into k clusters, each vector can be represented as one of these k centroids (the most similar one).
This will allow us to represent each vector in a much more efficient way log(k) bit per vector since each vector can be represented in the label of the centroid.
In our example, each vector is represented by one of the centroids. since we have 2042 centroids we can represent each vector with 11 bits, as opposed to 4096 ( 1024*32 ).
But, this amazing compaction comes with a great cost, we lost accuracy as we now cant separate the original vector from the centroid.
We saw that using a quantizer like k-means comes with a price, in order to increase the accuracy of our vectors we need to increase drastically the number of centroids, which makes the Quantization phase infeasible in practice.
This is what gave birth to Product Quantization, we can increase drastically the number of centroids by dividing each vector into many vectors and run our quantizer on all of these and thus improves accuracy.
In our example, each vector is represented by 8 sub-vectors which can be represented by one of the centroids. since we have 256 centroids we can represent each matrix in 1 byte, making vector representation 8byte only as oppose to 4096 ( 1024*32 ).
Although it increases the size of the vector a bit compared to the regular quantizer, it’s still O(log(k)) and allows us to increase the accuracy drastically and still work in practice.
Unfortunately in terms of search, even though we can calculate the distances in more efficiently using table look-ups and some addition. We are still going to do an exhaustive search.
The search is done using the following algorithm:
Construct a table with the calculated distance between each sub-vector and each of the centroids for that sub-vector.
Calculating approximate distance values for each of the vectors in the dataset, we just use those centroids id’s to look up the partial distances in the table and sum those up!
In our example, this means that this means building a table of subvector distances with 256 rows (one for each centroid) and 8 columns (one for each subvector). Remember that each database vector is now just a sequence of 8 centroid ids.
The exact nearest neighbor might be across the boundary to one of the neighboring cells.
The intuition of the algorithm is, that we can avoid the exhaustive search if we partition our dataset in such a way that on search, we only query relevant partitions (also called Voronoi cells). The reason this tends to work well in practice is since many datasets are actually multi-modal.
However, dividing the dataset up this way reduces accuracy yet again, because if a query vector falls on the outskirts of the closest cluster, then its nearest neighbors are likely sitting in multiple nearby clusters.
The solution to this issue is simply to search for multiple partitions (this is also called a probe), searching multiple nearby partitions obviously takes more time but it gives us better accuracy.
So as we saw by now it’s all about tradeoffs, the number of partitions and the number of the partitions to be searched can be tuned to find the time/accuracy tradeoff sweet spot.
It’s important to note that the Inverted File Index is a technique that can be used with other encoding strategies apart from quantization.
The intuition of the algorithm is, we want the same number of centroids to give has a more accurate representation. This can be achieved if the vectors are less distinct than they were.
In order, to do so, for each database vector, instead of using the PQ to encode the original database vector we instead encode the vector’s offset from its partition centroid.
However, replace vectors with their offsets will increase search time yet again, as we will need to calculate a separate distance table for each partition we probe since the query vector is different for each partition.
Apparently, the trade-off is worth it, though, because the IVFPQ works pretty well in practice.
The algorithm goes as follows, we partition our dataset ahead of time with k-means clustering to produce a large number of dataset partitions (Inverted Index). Then, for each of the partitions, we run regular product quantization.
Then, for each of the partitions, we are going to break each its’ vector into D/M sub-vectors, this will transform our N x D matrix to D/M matrices of N x M.
Then we are going to run the k-means algorithm on each sub-matrix, such that each sub-vector (row) will be connected to one of the k centroids.
We are going to replace each sub-vector with the id of the closest matching centroid. This is what we have waited for since we have repeated elements after the previous part, we can now represent each of them with a very small label and keep the actual value only once.
If you want to get even more theory you can watch this amazing video.
We are going to create the index class, as you can see most of the logic is in the build method (index creation), where you can control:
subvector_size — the target size of the sub-vectors (product quantization phase).
number_of_partitions — the numbers of partitions to divide the dataset by (Inverted File Index phase).
search_in_x_partitions — the numbers of partitions to search on (Inverted File Index phase).
class IVPQIndex(): def __init__(self, vectors, labels): self.dimension = vectors.shape[1] self.vectors = vectors.astype('float32') self.labels = labels def build(self, number_of_partition=8, search_in_x_partitions=2, subvector_size=8): quantizer = faiss.IndexFlatL2(self.dimension) self.index = faiss.IndexIVFPQ(quantizer, self.dimension, number_of_partition, search_in_x_partitions, subvector_size) self.index.train(self.vectors) self.index.add(self.vectors) def query(self, vectors, k=10): distances, indices = self.index.search(vectors, k) # I expect only query on one vector thus the slice return [self.labels[i] for i in indices[0]]
After I define the IVPQIndex class I can build the index with my dataset using the following snippets.
index = IVPQIndex(data["vector"], data["name"])index.build()
Now it’s pretty easy to search, let’s say I want to search for the movies that are most similar to “Toy Story” (its located in the 0 indexes).
index.query(data['vector'][0:1])
And that’s it, we have search efficiently using IVPQ for movies similar to “Toy Story” and we got approximated results.
Product Quantization With Inverted File Pros
The only method with sub-linear space, great compression ratio (log(k) bits per vector.
We can tune the parameters to change the accuracy/speed tradeoff.
We can tune the parameters to change the space/accuracy tradeoff.
Support batch queries.
Product Quantization With Inverted File Cons
The exact nearest neighbor might be across the boundary to one of the neighboring cells.
Cant incrementally add points to it.
The exact nearest neighbor might be across the boundary to one of the neighboring cells.
The intuition of this method is as follows, in order to reduce the search time on a graph we would want our graph to have an average path.
This is strongly connected to the famous “six handshake rule” statement.
“There is at most 6 degrees of separation between you and anyone else on Earth.” — Frigyes Karinthy
Many real-world graphs on average are highly clustered and tend to have nodes that are close to each other which are formally called small-world graph:
highly transitive (community structure) it’s often hierarchical.
small average distance ~log(N).
In order to search, we start at some entry point and iteratively traverse the graph. At each step of the traversal, the algorithm examines the distances from a query to the neighbors of a current base node and then selects as the next base node the adjacent node that minimizes the distance, while constantly keeping track of the best-discovered neighbors. The search is terminated when some stopping condition is met.
I am going to show how to use nmslib, to do “Approximate Nearest Neighbors Using HNSW”.
We are going to create the index class, as you can see most of the logic is in the build method (index creation).
class NMSLIBIndex(): def __init__(self, vectors, labels): self.dimention = vectors.shape[1] self.vectors = vectors.astype('float32') self.labels = labelsdef build(self): self.index = nmslib.init(method='hnsw', space='cosinesimil') self.index.addDataPointBatch(self.vectors) self.index.createIndex({'post': 2}) def query(self, vector, k=10): indices = self.index.knnQuery(vector, k=k) return [self.labels[i] for i in indices[0]]
After I define the NMSLIB index class I can build the index with my dataset using the following snippets.
index = NMSLIBIndex(data["vector"], data["name"])index.build()
Now it’s pretty easy to search, let’s say I want to search for the movies that are most similar to “Toy Story” (it's located in index number 0).
index.query(data['vector'][0])
And that’s it, we have search efficiently using annoy for movies similar to “Toy Story” and we got approximated results.
Like before I am going to declare Pros and Cons per implementation and not per technique.
We can tune the parameters to change the accuracy/speed tradeoff.
Support batch queries.
The NSW algorithm has polylogarithmic time complexity and can outperform rival algorithms on many real-world datasets.
The exact nearest neighbor might be across the boundary to one of the neighboring cells.
Cant incrementally add points to it.
Require quite a lot of RAM.
Evaluating which algorithms should be used and when is deeply depends on the use case and can be affected by these metrics:
Speed- Index creation and Index construction.
Hardware and Resources- Disk size, RAM size, and whether we have GPU.
Accuracy Requirements.
Access Patterns — Number of queries, batch or not, and whether we should update the index.
It’s important to note that there is no perfect algorithm it’s all about tradeoffs and that's what makes the subject so interesting.
I created a somewhat naive flow chart in order to allow one to choose which technique and implementation should one choose for his use-case and the metrics that we defined above.
Each implementation has its own parameters which affect either the accuracy/speed tradeoff or the space/accuracy tradeoff.
We started this article by showing the value Nearest Neighbours algorithms provide, then I listed the problems of using these algorithms in modern apps that led to the “birth of Approximate Nearest Neighbour techniques”.
Then I explained the intuition behind the leading techniques and how to use them in practice, these techniques allow us to play with the storage/accuracy tradeoff and the speed/accuracy tradeoff as well.
There are many things I didn’t cover like the usage of GPU by some of the algorithms, due to the extent of the topic.
I hope I was able to share my enthusiasm for this fascinating topic and that you find it useful, and as always I am open to any kind of constructive feedback. | [
{
"code": null,
"e": 492,
"s": 172,
"text": "Today as users consume more and more information from the internet at a moment’s notice, there is an increasing need for efficient ways to do search. This is why “Nearest Neighbor” has become a hot research topic, in order to increase the chance of users to find the information they are looking for in reasonable time."
},
{
"code": null,
"e": 683,
"s": 492,
"text": "The use cases for “Nearest Neighbor” are endless, and it is in use in many computer-science areas, such as image recognition, machine learning, and computational linguistics (1, 2 and more)."
},
{
"code": null,
"e": 762,
"s": 683,
"text": "In order to calculate exact nearest neighbors, the following techniques exist:"
},
{
"code": null,
"e": 888,
"s": 762,
"text": "Exhaustive search- Comparing each point to every other point, which will require Linear query time (the size of the dataset)."
},
{
"code": null,
"e": 1091,
"s": 888,
"text": "The Grid Trick- Subdividing the space into a Grid, which will require exponential space/time (in the dimensionality of the dataset). Since we are speaking on high dimension datasets this is impractical."
},
{
"code": null,
"e": 1400,
"s": 1091,
"text": "I am gonna show how to find similar vectors and will use the movielens dataset to do so (which contain 100k rows), by using an enriched version of the dataset (which already consists of movie labels and their semantic representation). The entire code for this article can be found as a Jupyter Notebook here."
},
{
"code": null,
"e": 1535,
"s": 1400,
"text": "First, we going to load our dataset which already consists of movie labels and their semantic representation which is calculated here."
},
{
"code": null,
"e": 1685,
"s": 1535,
"text": "import pickleimport faissdef load_data(): with open('movies.pickle', 'rb') as f: data = pickle.load(f) return datadata = load_data()data"
},
{
"code": null,
"e": 1845,
"s": 1685,
"text": "As we can see data is actually a dictionary, the name column consists of the movies’ names, and the vector column consists of the movies vector representation."
},
{
"code": null,
"e": 1950,
"s": 1845,
"text": "I am going to show how to do an exhaustive search using faiss. We first going to create the index class."
},
{
"code": null,
"e": 2457,
"s": 1950,
"text": "class ExactIndex(): def __init__(self, vectors, labels): self.dimension = vectors.shape[1] self.vectors = vectors.astype('float32') self.labels = labels def build(self): self.index = faiss.IndexFlatL2(self.dimension,) self.index.add(self.vectors) def query(self, vectors, k=10): distances, indices = self.index.search(vectors, k) # I expect only query on one vector thus the slice return [self.labels[i] for i in indices[0]]"
},
{
"code": null,
"e": 2556,
"s": 2457,
"text": "After I define the index class I can build the index with my dataset using the following snippets."
},
{
"code": null,
"e": 2618,
"s": 2556,
"text": "index = ExactIndex(data[\"vector\"], data[\"name\"])index.build()"
},
{
"code": null,
"e": 2793,
"s": 2618,
"text": "Now it’s pretty easy to search, let’s say I want to search for the movies that are most similar to “Toy Story” (its located in index number 0) I can write the following code:"
},
{
"code": null,
"e": 2824,
"s": 2793,
"text": "index.query(data['vector'][0])"
},
{
"code": null,
"e": 2888,
"s": 2824,
"text": "And that’s it, we have done exact search, we can go nap now :)."
},
{
"code": null,
"e": 3156,
"s": 2888,
"text": "Unfortunately, most modern-day applications have massive datasets with high dimensionality (hundreds or thousands) so linear scan will take a while. If that’s not enough, often there are additional constraints such as reasonable memory consumption and/or low latency."
},
{
"code": null,
"e": 3366,
"s": 3156,
"text": "It’s important to note that despite all recent advances on the topic, the only available method for guaranteed retrieval of the exact nearest neighbor is exhaustive search (due to the curse of dimensionality.)"
},
{
"code": null,
"e": 3586,
"s": 3366,
"text": "This makes exact nearest neighbors impractical even and allows “Approximate Nearest Neighbors “ (ANN) to come into the game. A similarity search can be orders of magnitude faster if we’re willing to trade some accuracy."
},
{
"code": null,
"e": 3693,
"s": 3586,
"text": "To give a small intuition why approximate nearest neighbors might be good enough I will give two examples:"
},
{
"code": null,
"e": 3806,
"s": 3693,
"text": "Visual Search: As a user, if I look for a bee picture I don’t mind which ones I get out of these three pictures."
},
{
"code": null,
"e": 3946,
"s": 3806,
"text": "Recommendations: As a user, I don’t really mind the order of the nearest neighbors or even if I have only eight of the ten best candidates."
},
{
"code": null,
"e": 4098,
"s": 3946,
"text": "Approximate Nearest Neighbor techniques speed up the search by preprocessing the data into an efficient index and are often tackled using these phases:"
},
{
"code": null,
"e": 4320,
"s": 4098,
"text": "Vector Transformation — applied on vectors before they are indexed, amongst them, there is dimensionality reduction and vector rotation. In order to this article well structured and somewhat concise, I won't discuss this."
},
{
"code": null,
"e": 4561,
"s": 4320,
"text": "Vector Encoding — applied on vectors in order to construct the actual index for search, amongst these, there are data structure-based techniques like Trees, LSH, and Quantization a technique to encode the vector to a much more compact form."
},
{
"code": null,
"e": 4727,
"s": 4561,
"text": "None Exhaustive Search Component — applied on vectors in order to avoid exhaustive search, amongst these techniques there are Inverted Files and Neighborhood Graphs."
},
{
"code": null,
"e": 4917,
"s": 4727,
"text": "Tree-based algorithms are one of the most common strategies when it comes to ANN. They construct forests (collection of trees) as their data structure by splitting the dataset into subsets."
},
{
"code": null,
"e": 5197,
"s": 4917,
"text": "One of the most prominent solutions out there is Annoy, which uses trees (more accurately forests) to enable Spotify’ music recommendations. Since there is a comprehensive explanation I will only provide here the intuition behind it, how it should be used, the pros and the cons."
},
{
"code": null,
"e": 5507,
"s": 5197,
"text": "In Annoy, in order to construct the index we create a forest (aka many trees) Each tree is constructed in the following way, we pick two points at random and split the space into two by their hyperplane, we keep splitting into the subspaces recursively until the points associated with a node is small enough."
},
{
"code": null,
"e": 5673,
"s": 5507,
"text": "In order to search the constructed index, the forest is traversed in order to obtain a set of candidate points from which the closest to the query point is returned."
},
{
"code": null,
"e": 5896,
"s": 5673,
"text": "We are going to create an index class like before. We are going to use annoy library. As you can imagine most of the logic is in the build method (index creation), where the accuracy-performance tradeoff is controlled by :"
},
{
"code": null,
"e": 6019,
"s": 5896,
"text": "number_of_trees — the number of binary trees we build, a larger value will give more accurate results, but larger indexes."
},
{
"code": null,
"e": 6170,
"s": 6019,
"text": "search_k — the number of binary trees we search for each point, a larger value will give more accurate results, but will take a longer time to return."
},
{
"code": null,
"e": 6850,
"s": 6170,
"text": "class AnnoyIndex(): def __init__(self, vectors, labels): self.dimension = vectors.shape[1] self.vectors = vectors.astype('float32') self.labels = labels def build(self, number_of_trees=5): self.index = annoy.AnnoyIndex(self.dimension) for i, vec in enumerate(self.vectors): self.index.add_item(i, vec.tolist()) self.index.build(number_of_trees) def query(self, vector, k=10): indices = self.index.get_nns_by_vector( vector.tolist(), k, search_k=search_in_x_trees) return [self.labels[i] for i in indices]"
},
{
"code": null,
"e": 6955,
"s": 6850,
"text": "After I define the Annoy index class I can build the index with my dataset using the following snippets."
},
{
"code": null,
"e": 7017,
"s": 6955,
"text": "index = AnnoyIndex(data[\"vector\"], data[\"name\"])index.build()"
},
{
"code": null,
"e": 7162,
"s": 7017,
"text": "Now it’s pretty easy to search, let’s say I want to search for the movies that are most similar to “Toy Story” (it's located in index number 0)."
},
{
"code": null,
"e": 7193,
"s": 7162,
"text": "index.query(data['vector'][0])"
},
{
"code": null,
"e": 7314,
"s": 7193,
"text": "And that’s it, we have search efficiently using annoy for movies similar to “Toy Story” and we got approximated results."
},
{
"code": null,
"e": 7421,
"s": 7314,
"text": "It’s important to note, that I am going to declare Pros and Cons per implementation and not per technique."
},
{
"code": null,
"e": 7432,
"s": 7421,
"text": "Annoy Pros"
},
{
"code": null,
"e": 7549,
"s": 7432,
"text": "Decouple index creation from loading them, so you can pass around indexes as files and map them into memory quickly."
},
{
"code": null,
"e": 7615,
"s": 7549,
"text": "We can tune the parameters to change the accuracy/speed tradeoff."
},
{
"code": null,
"e": 7717,
"s": 7615,
"text": "It has the ability to use static files as indexes, this means you can share indexes across processes."
},
{
"code": null,
"e": 7728,
"s": 7717,
"text": "Annoy Cons"
},
{
"code": null,
"e": 7817,
"s": 7728,
"text": "The exact nearest neighbor might be across the boundary to one of the neighboring cells."
},
{
"code": null,
"e": 7848,
"s": 7817,
"text": "No support for GPU processing."
},
{
"code": null,
"e": 7947,
"s": 7848,
"text": "No support for batch processing, so in order to increase throughput “further hacking is required”."
},
{
"code": null,
"e": 8011,
"s": 7947,
"text": "Cant incrementally add points to it (annoy2 tries to fix this)."
},
{
"code": null,
"e": 8200,
"s": 8011,
"text": "LSH-based algorithms are one of the most common strategies when it comes to ANN. They construct a hash table as their data structure by mapping points that are nearby into the same bucket."
},
{
"code": null,
"e": 8425,
"s": 8200,
"text": "One of the most prominent implementations out there is Faiss, by facebook. Since there are plenty of LSH explanations out there I will only provide here the intuition behind it, how it should be used, the pros, and the cons."
},
{
"code": null,
"e": 8703,
"s": 8425,
"text": "In LSH, in order to construct the index, we apply multiple hash functions to map data points into buckets so that data points near each other are located in the same buckets with high probability, while data points far from each other are likely to fall into different buckets."
},
{
"code": null,
"e": 8895,
"s": 8703,
"text": "In order to search the constructed index, the query point is hashed in order to obtain the closest buckets (a set of candidate points) from which the closest to the query points are returned."
},
{
"code": null,
"e": 9009,
"s": 8895,
"text": "It's important to note there are some advancements I have not to check yet like the fly algorithm and LSH on GPU."
},
{
"code": null,
"e": 9232,
"s": 9009,
"text": "I am going to show how to use faiss, to do “Approximate Nearest Neighbors Using LSH”. We are going to create the index class, as you can see most of the logic is in the build method (index creation), where you can control:"
},
{
"code": null,
"e": 9311,
"s": 9232,
"text": "num_bits — A larger value will give more accurate results, but larger indexes."
},
{
"code": null,
"e": 9834,
"s": 9311,
"text": "class LSHIndex(): def __init__(self, vectors, labels): self.dimension = vectors.shape[1] self.vectors = vectors.astype('float32') self.labels = labels def build(self, num_bits=8): self.index = faiss.IndexLSH(self.dimension, num_bits) self.index.add(self.vectors) def query(self, vectors, k=10): distances, indices = self.index.search(vectors, k) # I expect only query on one vector thus the slice return [self.labels[i] for i in indices[0]]"
},
{
"code": null,
"e": 9937,
"s": 9834,
"text": "After I define the LSH index class I can build the index with my dataset using the following snippets."
},
{
"code": null,
"e": 9997,
"s": 9937,
"text": "index = LSHIndex(data[\"vector\"], data[\"name\"])index.build()"
},
{
"code": null,
"e": 10142,
"s": 9997,
"text": "Now it’s pretty easy to search, let’s say I want to search for the movies that are most similar to “Toy Story” (it's located in index number 0)."
},
{
"code": null,
"e": 10173,
"s": 10142,
"text": "index.query(data['vector'][0])"
},
{
"code": null,
"e": 10294,
"s": 10173,
"text": "And that’s it, we have search efficiently using annoy for movies similar to “Toy Story” and we got approximated results."
},
{
"code": null,
"e": 10384,
"s": 10294,
"text": "Like before I am going to declare Pros and Cons per implementation and not per technique."
},
{
"code": null,
"e": 10393,
"s": 10384,
"text": "LSH Pros"
},
{
"code": null,
"e": 10496,
"s": 10393,
"text": "Data characteristics such as data distribution are not needed to generate these random hash functions."
},
{
"code": null,
"e": 10587,
"s": 10496,
"text": "The accuracy of the approximate search can be tuned without rebuilding the data structure."
},
{
"code": null,
"e": 10641,
"s": 10587,
"text": "Good theoretical guarantees of sub-linear query time."
},
{
"code": null,
"e": 10650,
"s": 10641,
"text": "LSH Cons"
},
{
"code": null,
"e": 10715,
"s": 10650,
"text": "In practice, the algorithm MIGHT runs slower than a linear scan."
},
{
"code": null,
"e": 10746,
"s": 10715,
"text": "No support for GPU processing."
},
{
"code": null,
"e": 10768,
"s": 10746,
"text": "Require a lot of RAM."
},
{
"code": null,
"e": 10895,
"s": 10768,
"text": "Although we managed to improve query performance by constructing an index, we didn’t take into account additional constraints."
},
{
"code": null,
"e": 11224,
"s": 10895,
"text": "Like many engineers, we assumed that linear storage as a “no issue” (due to systems like S3). However in practice, linear storage can become very costly very fast, and the fact that some algorithm requires to load them to RAM and that many systems don’t have separation of storage/compute definitely don’t improve the situation."
},
{
"code": null,
"e": 11326,
"s": 11224,
"text": "This is why Quantization-based algorithms are one of the most common strategies when it comes to ANN."
},
{
"code": null,
"e": 11492,
"s": 11326,
"text": "Quantization is a technique to reduce dataset size (from linear) by defining a function (quantizer) that encodes our data into a compact approximated representation."
},
{
"code": null,
"e": 11698,
"s": 11492,
"text": "The intuition of this method is as follows, we can reduce the size of the dataset by replacing every vector with a leaner approximated representation of the vectors (using quantizer) in the encoding phase."
},
{
"code": null,
"e": 11982,
"s": 11698,
"text": "One way to achieve a leaner approximated representation is to give similar vectors to the same representation. This can be done by clustering similar vectors and represent each of those in the same manner (the centroid representation), the most popular way to do so is using k-means."
},
{
"code": null,
"e": 12124,
"s": 11982,
"text": "Since k-means divide the vectors in space into k clusters, each vector can be represented as one of these k centroids (the most similar one)."
},
{
"code": null,
"e": 12286,
"s": 12124,
"text": "This will allow us to represent each vector in a much more efficient way log(k) bit per vector since each vector can be represented in the label of the centroid."
},
{
"code": null,
"e": 12458,
"s": 12286,
"text": "In our example, each vector is represented by one of the centroids. since we have 2042 centroids we can represent each vector with 11 bits, as opposed to 4096 ( 1024*32 )."
},
{
"code": null,
"e": 12592,
"s": 12458,
"text": "But, this amazing compaction comes with a great cost, we lost accuracy as we now cant separate the original vector from the centroid."
},
{
"code": null,
"e": 12820,
"s": 12592,
"text": "We saw that using a quantizer like k-means comes with a price, in order to increase the accuracy of our vectors we need to increase drastically the number of centroids, which makes the Quantization phase infeasible in practice."
},
{
"code": null,
"e": 13029,
"s": 12820,
"text": "This is what gave birth to Product Quantization, we can increase drastically the number of centroids by dividing each vector into many vectors and run our quantizer on all of these and thus improves accuracy."
},
{
"code": null,
"e": 13278,
"s": 13029,
"text": "In our example, each vector is represented by 8 sub-vectors which can be represented by one of the centroids. since we have 256 centroids we can represent each matrix in 1 byte, making vector representation 8byte only as oppose to 4096 ( 1024*32 )."
},
{
"code": null,
"e": 13464,
"s": 13278,
"text": "Although it increases the size of the vector a bit compared to the regular quantizer, it’s still O(log(k)) and allows us to increase the accuracy drastically and still work in practice."
},
{
"code": null,
"e": 13648,
"s": 13464,
"text": "Unfortunately in terms of search, even though we can calculate the distances in more efficiently using table look-ups and some addition. We are still going to do an exhaustive search."
},
{
"code": null,
"e": 13698,
"s": 13648,
"text": "The search is done using the following algorithm:"
},
{
"code": null,
"e": 13816,
"s": 13698,
"text": "Construct a table with the calculated distance between each sub-vector and each of the centroids for that sub-vector."
},
{
"code": null,
"e": 13993,
"s": 13816,
"text": "Calculating approximate distance values for each of the vectors in the dataset, we just use those centroids id’s to look up the partial distances in the table and sum those up!"
},
{
"code": null,
"e": 14231,
"s": 13993,
"text": "In our example, this means that this means building a table of subvector distances with 256 rows (one for each centroid) and 8 columns (one for each subvector). Remember that each database vector is now just a sequence of 8 centroid ids."
},
{
"code": null,
"e": 14320,
"s": 14231,
"text": "The exact nearest neighbor might be across the boundary to one of the neighboring cells."
},
{
"code": null,
"e": 14612,
"s": 14320,
"text": "The intuition of the algorithm is, that we can avoid the exhaustive search if we partition our dataset in such a way that on search, we only query relevant partitions (also called Voronoi cells). The reason this tends to work well in practice is since many datasets are actually multi-modal."
},
{
"code": null,
"e": 14830,
"s": 14612,
"text": "However, dividing the dataset up this way reduces accuracy yet again, because if a query vector falls on the outskirts of the closest cluster, then its nearest neighbors are likely sitting in multiple nearby clusters."
},
{
"code": null,
"e": 15028,
"s": 14830,
"text": "The solution to this issue is simply to search for multiple partitions (this is also called a probe), searching multiple nearby partitions obviously takes more time but it gives us better accuracy."
},
{
"code": null,
"e": 15207,
"s": 15028,
"text": "So as we saw by now it’s all about tradeoffs, the number of partitions and the number of the partitions to be searched can be tuned to find the time/accuracy tradeoff sweet spot."
},
{
"code": null,
"e": 15347,
"s": 15207,
"text": "It’s important to note that the Inverted File Index is a technique that can be used with other encoding strategies apart from quantization."
},
{
"code": null,
"e": 15533,
"s": 15347,
"text": "The intuition of the algorithm is, we want the same number of centroids to give has a more accurate representation. This can be achieved if the vectors are less distinct than they were."
},
{
"code": null,
"e": 15709,
"s": 15533,
"text": "In order, to do so, for each database vector, instead of using the PQ to encode the original database vector we instead encode the vector’s offset from its partition centroid."
},
{
"code": null,
"e": 15929,
"s": 15709,
"text": "However, replace vectors with their offsets will increase search time yet again, as we will need to calculate a separate distance table for each partition we probe since the query vector is different for each partition."
},
{
"code": null,
"e": 16025,
"s": 15929,
"text": "Apparently, the trade-off is worth it, though, because the IVFPQ works pretty well in practice."
},
{
"code": null,
"e": 16256,
"s": 16025,
"text": "The algorithm goes as follows, we partition our dataset ahead of time with k-means clustering to produce a large number of dataset partitions (Inverted Index). Then, for each of the partitions, we run regular product quantization."
},
{
"code": null,
"e": 16414,
"s": 16256,
"text": "Then, for each of the partitions, we are going to break each its’ vector into D/M sub-vectors, this will transform our N x D matrix to D/M matrices of N x M."
},
{
"code": null,
"e": 16558,
"s": 16414,
"text": "Then we are going to run the k-means algorithm on each sub-matrix, such that each sub-vector (row) will be connected to one of the k centroids."
},
{
"code": null,
"e": 16828,
"s": 16558,
"text": "We are going to replace each sub-vector with the id of the closest matching centroid. This is what we have waited for since we have repeated elements after the previous part, we can now represent each of them with a very small label and keep the actual value only once."
},
{
"code": null,
"e": 16898,
"s": 16828,
"text": "If you want to get even more theory you can watch this amazing video."
},
{
"code": null,
"e": 17035,
"s": 16898,
"text": "We are going to create the index class, as you can see most of the logic is in the build method (index creation), where you can control:"
},
{
"code": null,
"e": 17117,
"s": 17035,
"text": "subvector_size — the target size of the sub-vectors (product quantization phase)."
},
{
"code": null,
"e": 17220,
"s": 17117,
"text": "number_of_partitions — the numbers of partitions to divide the dataset by (Inverted File Index phase)."
},
{
"code": null,
"e": 17313,
"s": 17220,
"text": "search_in_x_partitions — the numbers of partitions to search on (Inverted File Index phase)."
},
{
"code": null,
"e": 18233,
"s": 17313,
"text": "class IVPQIndex(): def __init__(self, vectors, labels): self.dimension = vectors.shape[1] self.vectors = vectors.astype('float32') self.labels = labels def build(self, number_of_partition=8, search_in_x_partitions=2, subvector_size=8): quantizer = faiss.IndexFlatL2(self.dimension) self.index = faiss.IndexIVFPQ(quantizer, self.dimension, number_of_partition, search_in_x_partitions, subvector_size) self.index.train(self.vectors) self.index.add(self.vectors) def query(self, vectors, k=10): distances, indices = self.index.search(vectors, k) # I expect only query on one vector thus the slice return [self.labels[i] for i in indices[0]]"
},
{
"code": null,
"e": 18336,
"s": 18233,
"text": "After I define the IVPQIndex class I can build the index with my dataset using the following snippets."
},
{
"code": null,
"e": 18397,
"s": 18336,
"text": "index = IVPQIndex(data[\"vector\"], data[\"name\"])index.build()"
},
{
"code": null,
"e": 18540,
"s": 18397,
"text": "Now it’s pretty easy to search, let’s say I want to search for the movies that are most similar to “Toy Story” (its located in the 0 indexes)."
},
{
"code": null,
"e": 18573,
"s": 18540,
"text": "index.query(data['vector'][0:1])"
},
{
"code": null,
"e": 18693,
"s": 18573,
"text": "And that’s it, we have search efficiently using IVPQ for movies similar to “Toy Story” and we got approximated results."
},
{
"code": null,
"e": 18738,
"s": 18693,
"text": "Product Quantization With Inverted File Pros"
},
{
"code": null,
"e": 18826,
"s": 18738,
"text": "The only method with sub-linear space, great compression ratio (log(k) bits per vector."
},
{
"code": null,
"e": 18892,
"s": 18826,
"text": "We can tune the parameters to change the accuracy/speed tradeoff."
},
{
"code": null,
"e": 18958,
"s": 18892,
"text": "We can tune the parameters to change the space/accuracy tradeoff."
},
{
"code": null,
"e": 18981,
"s": 18958,
"text": "Support batch queries."
},
{
"code": null,
"e": 19026,
"s": 18981,
"text": "Product Quantization With Inverted File Cons"
},
{
"code": null,
"e": 19115,
"s": 19026,
"text": "The exact nearest neighbor might be across the boundary to one of the neighboring cells."
},
{
"code": null,
"e": 19152,
"s": 19115,
"text": "Cant incrementally add points to it."
},
{
"code": null,
"e": 19241,
"s": 19152,
"text": "The exact nearest neighbor might be across the boundary to one of the neighboring cells."
},
{
"code": null,
"e": 19380,
"s": 19241,
"text": "The intuition of this method is as follows, in order to reduce the search time on a graph we would want our graph to have an average path."
},
{
"code": null,
"e": 19453,
"s": 19380,
"text": "This is strongly connected to the famous “six handshake rule” statement."
},
{
"code": null,
"e": 19553,
"s": 19453,
"text": "“There is at most 6 degrees of separation between you and anyone else on Earth.” — Frigyes Karinthy"
},
{
"code": null,
"e": 19705,
"s": 19553,
"text": "Many real-world graphs on average are highly clustered and tend to have nodes that are close to each other which are formally called small-world graph:"
},
{
"code": null,
"e": 19770,
"s": 19705,
"text": "highly transitive (community structure) it’s often hierarchical."
},
{
"code": null,
"e": 19802,
"s": 19770,
"text": "small average distance ~log(N)."
},
{
"code": null,
"e": 20221,
"s": 19802,
"text": "In order to search, we start at some entry point and iteratively traverse the graph. At each step of the traversal, the algorithm examines the distances from a query to the neighbors of a current base node and then selects as the next base node the adjacent node that minimizes the distance, while constantly keeping track of the best-discovered neighbors. The search is terminated when some stopping condition is met."
},
{
"code": null,
"e": 20309,
"s": 20221,
"text": "I am going to show how to use nmslib, to do “Approximate Nearest Neighbors Using HNSW”."
},
{
"code": null,
"e": 20423,
"s": 20309,
"text": "We are going to create the index class, as you can see most of the logic is in the build method (index creation)."
},
{
"code": null,
"e": 20921,
"s": 20423,
"text": "class NMSLIBIndex(): def __init__(self, vectors, labels): self.dimention = vectors.shape[1] self.vectors = vectors.astype('float32') self.labels = labelsdef build(self): self.index = nmslib.init(method='hnsw', space='cosinesimil') self.index.addDataPointBatch(self.vectors) self.index.createIndex({'post': 2}) def query(self, vector, k=10): indices = self.index.knnQuery(vector, k=k) return [self.labels[i] for i in indices[0]]"
},
{
"code": null,
"e": 21027,
"s": 20921,
"text": "After I define the NMSLIB index class I can build the index with my dataset using the following snippets."
},
{
"code": null,
"e": 21090,
"s": 21027,
"text": "index = NMSLIBIndex(data[\"vector\"], data[\"name\"])index.build()"
},
{
"code": null,
"e": 21235,
"s": 21090,
"text": "Now it’s pretty easy to search, let’s say I want to search for the movies that are most similar to “Toy Story” (it's located in index number 0)."
},
{
"code": null,
"e": 21266,
"s": 21235,
"text": "index.query(data['vector'][0])"
},
{
"code": null,
"e": 21387,
"s": 21266,
"text": "And that’s it, we have search efficiently using annoy for movies similar to “Toy Story” and we got approximated results."
},
{
"code": null,
"e": 21477,
"s": 21387,
"text": "Like before I am going to declare Pros and Cons per implementation and not per technique."
},
{
"code": null,
"e": 21543,
"s": 21477,
"text": "We can tune the parameters to change the accuracy/speed tradeoff."
},
{
"code": null,
"e": 21566,
"s": 21543,
"text": "Support batch queries."
},
{
"code": null,
"e": 21685,
"s": 21566,
"text": "The NSW algorithm has polylogarithmic time complexity and can outperform rival algorithms on many real-world datasets."
},
{
"code": null,
"e": 21774,
"s": 21685,
"text": "The exact nearest neighbor might be across the boundary to one of the neighboring cells."
},
{
"code": null,
"e": 21811,
"s": 21774,
"text": "Cant incrementally add points to it."
},
{
"code": null,
"e": 21839,
"s": 21811,
"text": "Require quite a lot of RAM."
},
{
"code": null,
"e": 21963,
"s": 21839,
"text": "Evaluating which algorithms should be used and when is deeply depends on the use case and can be affected by these metrics:"
},
{
"code": null,
"e": 22009,
"s": 21963,
"text": "Speed- Index creation and Index construction."
},
{
"code": null,
"e": 22079,
"s": 22009,
"text": "Hardware and Resources- Disk size, RAM size, and whether we have GPU."
},
{
"code": null,
"e": 22102,
"s": 22079,
"text": "Accuracy Requirements."
},
{
"code": null,
"e": 22193,
"s": 22102,
"text": "Access Patterns — Number of queries, batch or not, and whether we should update the index."
},
{
"code": null,
"e": 22326,
"s": 22193,
"text": "It’s important to note that there is no perfect algorithm it’s all about tradeoffs and that's what makes the subject so interesting."
},
{
"code": null,
"e": 22505,
"s": 22326,
"text": "I created a somewhat naive flow chart in order to allow one to choose which technique and implementation should one choose for his use-case and the metrics that we defined above."
},
{
"code": null,
"e": 22628,
"s": 22505,
"text": "Each implementation has its own parameters which affect either the accuracy/speed tradeoff or the space/accuracy tradeoff."
},
{
"code": null,
"e": 22849,
"s": 22628,
"text": "We started this article by showing the value Nearest Neighbours algorithms provide, then I listed the problems of using these algorithms in modern apps that led to the “birth of Approximate Nearest Neighbour techniques”."
},
{
"code": null,
"e": 23053,
"s": 22849,
"text": "Then I explained the intuition behind the leading techniques and how to use them in practice, these techniques allow us to play with the storage/accuracy tradeoff and the speed/accuracy tradeoff as well."
},
{
"code": null,
"e": 23171,
"s": 23053,
"text": "There are many things I didn’t cover like the usage of GPU by some of the algorithms, due to the extent of the topic."
}
]
|
Images and masks splitting into multiple pieces in Python with Google Colab | by Oleksii Sheremet | Towards Data Science | Data labelers use special annotation tools for objects annotation. For example, the Computer Vision Annotation Tool (CVAT) is widely known in computer vision. Naturally, it is more convenient for labelers to work with high-resolution images. This is especially true when you need to mark a large number of objects.
In one of the roof segmentation tasks that I participated in, it was necessary to highlight triangular segments, quadrangular segments, other segments and edges of the roof. An example of such markup is shown in the following figure (white color for edges, red color for triangles, green color for quadrangles, blue color for other polygons):
The original images were obtained from Google Earth at 2048x1208 pixels. The masks were annotated by data labelers using CVAT at the same resolution. To train the model, images and masks should be in a lower resolution (from 128x128 to 512x512 pixels). It is well known that image splitting is a technique most often used to slice a large image into smaller parts. Thus, the logical solution was to split the images and their corresponding masks into the parts with the same resolution.
All code for splitting was implemented in Google Colab. Let’s take a closer look. Import libraries:
import osimport sysimport shutilimport globimport matplotlib.pyplot as pltimport matplotlib.image as mpimgfrom PIL import Image
Mount the Google Drive (with images and masks) to Google Colab:
from google.colab import drivedrive.mount('/content/gdrive')%cd "gdrive/My Drive/File Folder"
A useful function for creating a new directory and recursively deleting the contents of an existing one:
def dir_create(path): if (os.path.exists(path)) and (os.listdir(path) != []): shutil.rmtree(path) os.makedirs(path) if not os.path.exists(path): os.makedirs(path)
The crop function that goes over the original image are adjusted to the original image limit and contain the original pixels:
def crop(input_file, height, width): img = Image.open(input_file) img_width, img_height = img.size for i in range(img_height//height): for j in range(img_width//width): box = (j*width, i*height, (j+1)*width, (i+1)*height) yield img.crop(box)
The function for splitting images and masks into smaller parts (the height and width of the cropping window, and the starting number are taken as input parameters):
def split(inp_img_dir, inp_msk_dir, out_dir, height, width, start_num): image_dir = os.path.join(out_dir, 'images') mask_dir = os.path.join(out_dir, 'masks') dir_create(out_dir) dir_create(image_dir) dir_create(mask_dir) img_list = [f for f in os.listdir(inp_img_dir) if os.path.isfile(os.path.join(inp_img_dir, f))] file_num = 0 for infile in img_list: infile_path = os.path.join(inp_img_dir, infile) for k, piece in enumerate(crop(infile_path, height, width), start_num): img = Image.new('RGB', (height, width), 255) img.paste(piece) img_path = os.path.join(image_dir, infile.split('.')[0]+ '_' + str(k).zfill(5) + '.png') img.save(img_path) infile_path = os.path.join(inp_msk_dir, infile.split('.')[0] + '.png') for k, piece in enumerate(crop(infile_path, height, width), start_num): msk = Image.new('RGB', (height, width), 255) msk.paste(piece) msk_path = os.path.join(mask_dir, infile.split('.')[0] + '_' + str(k).zfill(5) + '.png') msk.save(msk_path) file_num += 1 sys.stdout.write("\rFile %s was processed." % file_num) sys.stdout.flush()
Let’s set the necessary variables:
inp_img_dir = ‘./input_dir/images’inp_msk_dir = ‘./input_dir/masks’out_dir = ‘./output_dir’height = 512width = 512start_num = 1
Let’s form a list of files with original images and masks and split them:
input_images_list = glob.glob(inp_img_dir + ‘/*.jpg’)input_masks_list = glob.glob(inp_msk_dir + ‘/*.png’)split(inp_img_dir, inp_msk_dir, out_dir, height, width, start_num)
As an example, two original images and masks are shown using the following code:
for i, (image_path, mask_path) in enumerate(zip(input_images_list, input_masks_list)): fig, [ax1, ax2] = plt.subplots(1, 2, figsize=(18, 9)) image = mpimg.imread(image_path) mask = mpimg.imread(mask_path) ax1.set_title(‘Image ‘ + str(i+1)) ax1.imshow(image) ax2.imshow(mask) ax2.set_title(‘Mask ‘ + str(i+1))
Using the following function, you can show all parts of the splitted image (divided into 8 parts):
def image_part_plotter(images_list, offset): fig = plt.figure(figsize=(12, 6)) columns = 4 rows = 2 # ax enables access to manipulate each of subplots ax = [] for i in range(columns*rows): # create subplot and append to ax img = mpimg.imread(images_list[i+offset]) ax.append(fig.add_subplot(rows, columns, i+1)) ax[-1].set_title(“image part number “ + str(i+1)) plt.imshow(img) plt.show() # Render the plot
Let’s see what we got as result of images and masks splitting. For the first image:
image_part_plotter(output_images_list, 0)image_part_plotter(output_masks_list, 0)
image_part_plotter(output_images_list, 8)image_part_plotter(output_masks_list, 8)
Conclusion
The images and masks splitted using the proposed approach are saved with the same file names in different directories, that is, if the file ‘./output_dir/images/1_00001.png’ is in the folder with images, then the file ‘./output_dir/masks/1_00001.png’ will correspond to it in the directory with masks. After splitting the image and mask, you can apply augmentation to each part of it (for example, change brightness, contrast, rotate or flip). To do this, just add the augmentation function.
References
Pillow (PIL Fork)
Computer Vision Annotation Tool (CVAT)
This notebook provides recipes for loading and saving data from external sources | [
{
"code": null,
"e": 486,
"s": 171,
"text": "Data labelers use special annotation tools for objects annotation. For example, the Computer Vision Annotation Tool (CVAT) is widely known in computer vision. Naturally, it is more convenient for labelers to work with high-resolution images. This is especially true when you need to mark a large number of objects."
},
{
"code": null,
"e": 829,
"s": 486,
"text": "In one of the roof segmentation tasks that I participated in, it was necessary to highlight triangular segments, quadrangular segments, other segments and edges of the roof. An example of such markup is shown in the following figure (white color for edges, red color for triangles, green color for quadrangles, blue color for other polygons):"
},
{
"code": null,
"e": 1316,
"s": 829,
"text": "The original images were obtained from Google Earth at 2048x1208 pixels. The masks were annotated by data labelers using CVAT at the same resolution. To train the model, images and masks should be in a lower resolution (from 128x128 to 512x512 pixels). It is well known that image splitting is a technique most often used to slice a large image into smaller parts. Thus, the logical solution was to split the images and their corresponding masks into the parts with the same resolution."
},
{
"code": null,
"e": 1416,
"s": 1316,
"text": "All code for splitting was implemented in Google Colab. Let’s take a closer look. Import libraries:"
},
{
"code": null,
"e": 1544,
"s": 1416,
"text": "import osimport sysimport shutilimport globimport matplotlib.pyplot as pltimport matplotlib.image as mpimgfrom PIL import Image"
},
{
"code": null,
"e": 1608,
"s": 1544,
"text": "Mount the Google Drive (with images and masks) to Google Colab:"
},
{
"code": null,
"e": 1702,
"s": 1608,
"text": "from google.colab import drivedrive.mount('/content/gdrive')%cd \"gdrive/My Drive/File Folder\""
},
{
"code": null,
"e": 1807,
"s": 1702,
"text": "A useful function for creating a new directory and recursively deleting the contents of an existing one:"
},
{
"code": null,
"e": 1997,
"s": 1807,
"text": "def dir_create(path): if (os.path.exists(path)) and (os.listdir(path) != []): shutil.rmtree(path) os.makedirs(path) if not os.path.exists(path): os.makedirs(path)"
},
{
"code": null,
"e": 2123,
"s": 1997,
"text": "The crop function that goes over the original image are adjusted to the original image limit and contain the original pixels:"
},
{
"code": null,
"e": 2403,
"s": 2123,
"text": "def crop(input_file, height, width): img = Image.open(input_file) img_width, img_height = img.size for i in range(img_height//height): for j in range(img_width//width): box = (j*width, i*height, (j+1)*width, (i+1)*height) yield img.crop(box)"
},
{
"code": null,
"e": 2568,
"s": 2403,
"text": "The function for splitting images and masks into smaller parts (the height and width of the cropping window, and the starting number are taken as input parameters):"
},
{
"code": null,
"e": 4066,
"s": 2568,
"text": "def split(inp_img_dir, inp_msk_dir, out_dir, height, width, start_num): image_dir = os.path.join(out_dir, 'images') mask_dir = os.path.join(out_dir, 'masks') dir_create(out_dir) dir_create(image_dir) dir_create(mask_dir) img_list = [f for f in os.listdir(inp_img_dir) if os.path.isfile(os.path.join(inp_img_dir, f))] file_num = 0 for infile in img_list: infile_path = os.path.join(inp_img_dir, infile) for k, piece in enumerate(crop(infile_path, height, width), start_num): img = Image.new('RGB', (height, width), 255) img.paste(piece) img_path = os.path.join(image_dir, infile.split('.')[0]+ '_' + str(k).zfill(5) + '.png') img.save(img_path) infile_path = os.path.join(inp_msk_dir, infile.split('.')[0] + '.png') for k, piece in enumerate(crop(infile_path, height, width), start_num): msk = Image.new('RGB', (height, width), 255) msk.paste(piece) msk_path = os.path.join(mask_dir, infile.split('.')[0] + '_' + str(k).zfill(5) + '.png') msk.save(msk_path) file_num += 1 sys.stdout.write(\"\\rFile %s was processed.\" % file_num) sys.stdout.flush()"
},
{
"code": null,
"e": 4101,
"s": 4066,
"text": "Let’s set the necessary variables:"
},
{
"code": null,
"e": 4229,
"s": 4101,
"text": "inp_img_dir = ‘./input_dir/images’inp_msk_dir = ‘./input_dir/masks’out_dir = ‘./output_dir’height = 512width = 512start_num = 1"
},
{
"code": null,
"e": 4303,
"s": 4229,
"text": "Let’s form a list of files with original images and masks and split them:"
},
{
"code": null,
"e": 4475,
"s": 4303,
"text": "input_images_list = glob.glob(inp_img_dir + ‘/*.jpg’)input_masks_list = glob.glob(inp_msk_dir + ‘/*.png’)split(inp_img_dir, inp_msk_dir, out_dir, height, width, start_num)"
},
{
"code": null,
"e": 4556,
"s": 4475,
"text": "As an example, two original images and masks are shown using the following code:"
},
{
"code": null,
"e": 4933,
"s": 4556,
"text": "for i, (image_path, mask_path) in enumerate(zip(input_images_list, input_masks_list)): fig, [ax1, ax2] = plt.subplots(1, 2, figsize=(18, 9)) image = mpimg.imread(image_path) mask = mpimg.imread(mask_path) ax1.set_title(‘Image ‘ + str(i+1)) ax1.imshow(image) ax2.imshow(mask) ax2.set_title(‘Mask ‘ + str(i+1))"
},
{
"code": null,
"e": 5032,
"s": 4933,
"text": "Using the following function, you can show all parts of the splitted image (divided into 8 parts):"
},
{
"code": null,
"e": 5495,
"s": 5032,
"text": "def image_part_plotter(images_list, offset): fig = plt.figure(figsize=(12, 6)) columns = 4 rows = 2 # ax enables access to manipulate each of subplots ax = [] for i in range(columns*rows): # create subplot and append to ax img = mpimg.imread(images_list[i+offset]) ax.append(fig.add_subplot(rows, columns, i+1)) ax[-1].set_title(“image part number “ + str(i+1)) plt.imshow(img) plt.show() # Render the plot"
},
{
"code": null,
"e": 5579,
"s": 5495,
"text": "Let’s see what we got as result of images and masks splitting. For the first image:"
},
{
"code": null,
"e": 5661,
"s": 5579,
"text": "image_part_plotter(output_images_list, 0)image_part_plotter(output_masks_list, 0)"
},
{
"code": null,
"e": 5743,
"s": 5661,
"text": "image_part_plotter(output_images_list, 8)image_part_plotter(output_masks_list, 8)"
},
{
"code": null,
"e": 5754,
"s": 5743,
"text": "Conclusion"
},
{
"code": null,
"e": 6246,
"s": 5754,
"text": "The images and masks splitted using the proposed approach are saved with the same file names in different directories, that is, if the file ‘./output_dir/images/1_00001.png’ is in the folder with images, then the file ‘./output_dir/masks/1_00001.png’ will correspond to it in the directory with masks. After splitting the image and mask, you can apply augmentation to each part of it (for example, change brightness, contrast, rotate or flip). To do this, just add the augmentation function."
},
{
"code": null,
"e": 6257,
"s": 6246,
"text": "References"
},
{
"code": null,
"e": 6275,
"s": 6257,
"text": "Pillow (PIL Fork)"
},
{
"code": null,
"e": 6314,
"s": 6275,
"text": "Computer Vision Annotation Tool (CVAT)"
}
]
|
Load and Query CSV File in S3 with Presto | by Yifeng Jiang | Towards Data Science | It is such a simple and common task in big data that I thought folks must have done this a thousand times, so when a customer asked me this, I went straight to the internet trying to find some good examples to share with the customer. Guess what? I couldn’t find one! So I decided to write one myself.
A typical data ETL flow with Presto and S3 looks like:
Upload CSV files into S3.Load the CSV files on S3 into Presto.(optional) Convert to analytics optimised format in Parquet or ORC.Run complex query against the Parquet or ORC table.
Upload CSV files into S3.
Load the CSV files on S3 into Presto.
(optional) Convert to analytics optimised format in Parquet or ORC.
Run complex query against the Parquet or ORC table.
In this blog, I use the NewYork City 2018 Yellow Taxi Trip Dataset. The dataset has 112 million rows, 17 columns each row in CSV format. Total size is 9.8GB.
Here is some example data:
head -n 3 tlc_yellow_trips_2018.csvVendorID,tpep_pickup_datetime,tpep_dropoff_datetime,passenger_count,trip_distance,RatecodeID,store_and_fwd_flag,PULocationID,DOLocationID,payment_type,fare_amount,extra,mta_tax,tip_amount,tolls_amount,improvement_surcharge,total_amount2,05/19/2018 11:51:48 PM,05/20/2018 12:07:31 AM,1,2.01,1,N,48,158,2,11.5,0.5,0.5,0,0,0.3,12.81,05/19/2018 11:22:53 PM,05/19/2018 11:35:14 PM,1,1.3,1,N,142,164,2,9,0.5,0.5,0,0,0.3,10.31,05/19/2018 11:37:02 PM,05/19/2018 11:52:41 PM,1,2.2,1,N,164,114,1,11,0.5,0.5,3.05,0,0.3,15.35
I assume you have completed a basic Presto and S3 setup. You also need to set up the Hive catalog in Presto for it to query data in S3. If you haven’t, please take a look at my blog Presto with Kubernetes and S3 — Deployment.
Create a directory in S3 to store the CSV file. We can use any S3 client to create a S3 directory, here I simply use the hdfs command because it is available on the Hive Metastore node as part of the Hive catalog setup in the above blog.
Run the below command from the Hive Metastore node. Change bucket name to match your environment. Note I specified s3a:// as the directory path schema so that hdfs command creates the directory on S3 instead of HDFS.
hdfs dfs -mkdir -p s3a://deephub/warehouse/nyc_text.db/tlc_yellow_trips_2018
Upload the CSV file to S3 under the directory we just created. Any S3 client should work, I use s5cmd, a very fast S3 client, to upload the CSV file into my S3 directory. Here I use FlashBlade S3, so I specified endpoint-url to my FlashBlade data VIP.
s5cmd --endpoint-url=http://192.168.170.12:80 cp tlc_yellow_trips_2018.csv s3://deephub/warehouse/nyc_text.db/tlc_yellow_trips_2018/tlc_yellow_trips_2018.csv
In order to query data in S3, I need to create a table in Presto and map its schema and location to the CSV file.
Launch Presto CLI:
presto-cli --server <coordinate_node:port> --catalog hive
Create a new schema for text data using Presto CLI.
presto> CREATE SCHEMA nyc_text WITH (LOCATION = 's3a://deephub/warehouse/nyc_text.db');
Create an external table for CSV data. You can create many tables under a single schema. Notes:
CSV format table currently only supports VARCHAR data type.
I set skip_header_line_count = 1 to the table property so that first line header in our CSV file is skipped. Remove this property if your CSV file does not include header.
Presto’s CSV format support requires metastore.storage.schema.reader.impl=org.apache.hadoop.hive.metastore.SerDeStorageSchemaReader in the metastore-site.xml Hive Metastore configuration file.
presto> CREATE TABLE hive.nyc_text.tlc_yellow_trips_2018 ( vendorid VARCHAR, tpep_pickup_datetime VARCHAR, tpep_dropoff_datetime VARCHAR, passenger_count VARCHAR, trip_distance VARCHAR, ratecodeid VARCHAR, store_and_fwd_flag VARCHAR, pulocationid VARCHAR, dolocationid VARCHAR, payment_type VARCHAR, fare_amount VARCHAR, extra VARCHAR, mta_tax VARCHAR, tip_amount VARCHAR, tolls_amount VARCHAR, improvement_surcharge VARCHAR, total_amount VARCHAR)WITH (FORMAT = 'CSV', skip_header_line_count = 1, EXTERNAL_LOCATION = 's3a://deephub/warehouse/nyc_text.db/tlc_yellow_trips_2018');
Now I can query the CSV data.
presto> SELECT * FROM nyc_text.tlc_yellow_trips_2018 LIMIT 10;
At this point, I can connect Tableau to visualise data in the Presto table. However, because CSV format table only supports VARCHAR data type, it may expose limits to Tableau. If this is the case, convert CSV to Parquet or ORC format (see below). Parquet or ORC tables generally have better performance than Text/CSV tables.
This is an optional task, but it is recommended if the data will be queried multiple times. By converting text data into analytics optimised format in Parquet or ORC, it does not only improve query performance, but also reduce server and storage resource consumption.
Presto is good for simple conversions that can be done in SQL. For those with complex business logics that cannot be easily done with SQL (e.g., requires Java/Python programming), it is better to use Apache Spark. In this example, I simply convert text to Parquet format without introducing any complex business logic, so I will use Presto for the conversion.
A common practice for managing data in Presto is to use different schemas for your raw text (CSV/TSV) tables and optimised (Parquet/ORC) tables. So I will create a new schema nyc_parq for the Parquet table.
Create a S3 directory for the new schema. Change bucket name to match your environment.
hdfs dfs -mkdir -p s3a://deephub/warehouse/nyc_parq.db
Create the nyc_parq schema in Presto CLI.
presto> CREATE SCHEMA nyc_parq WITH (LOCATION = 's3a://deephub/warehouse/nyc_parq.db');
Create a Parquet table, convert CSV data to Parquet format. You can change the SELECT cause to add simple business and conversion logic.
presto> CREATE TABLE hive.nyc_parq.tlc_yellow_trips_2018COMMENT '2018 Newyork City taxi data'WITH (FORMAT = 'PARQUET')ASSELECT cast(vendorid as INTEGER) as vendorid, date_parse(tpep_pickup_datetime, '%m/%d/%Y %h:%i:%s %p') as tpep_pickup_datetime, date_parse(tpep_dropoff_datetime, '%m/%d/%Y %h:%i:%s %p') as tpep_dropoff_datetime, cast(passenger_count as SMALLINT) as passenger_count, cast(trip_distance as DECIMAL(8, 2)) as trip_distance, cast(ratecodeid as INTEGER) as ratecodeid, cast(store_and_fwd_flag as CHAR(1)) as store_and_fwd_flag, cast(pulocationid as INTEGER) as pulocationid, cast(dolocationid as INTEGER) as dolocationid, cast(payment_type as SMALLINT) as payment_type, cast(fare_amount as DECIMAL(8, 2)) as fare_amount, cast(extra as DECIMAL(8, 2)) as extra, cast(mta_tax as DECIMAL(8, 2)) as mta_tax, cast(tip_amount as DECIMAL(8, 2)) as tip_amount, cast(tolls_amount as DECIMAL(8, 2)) as tolls_amount, cast(improvement_surcharge as DECIMAL(8, 2)) as improvement_surcharge, cast(total_amount as DECIMAL(8, 2)) as total_amountFROM hive.nyc_text.tlc_yellow_trips_2018;
Depending on the data size, this conversion may take time. Once it is done, I can query the Parquet data.
presto> SELECT * FROM nyc_parq.tlc_yellow_trips_2018 LIMIT 10;
Confirm the Parquet table’s schema. Note columns are with desired type in this table.
presto> describe nyc_parq.tlc_yellow_trips_2018; Column | Type | Extra | Comment-----------------------+--------------+-------+--------- vendorid | integer | | tpep_pickup_datetime | timestamp | | tpep_dropoff_datetime | timestamp | | passenger_count | smallint | | trip_distance | decimal(8,2) | | ratecodeid | integer | | store_and_fwd_flag | char(1) | | pulocationid | integer | | dolocationid | integer | | payment_type | smallint | | fare_amount | decimal(8,2) | | extra | decimal(8,2) | | mta_tax | decimal(8,2) | | tip_amount | decimal(8,2) | | tolls_amount | decimal(8,2) | | improvement_surcharge | decimal(8,2) | | total_amount | decimal(8,2) | |(17 rows)
Finally, I configure my analytics application / Tableau to use the optimised nyc_parq schema and Parquet tables.
As data size grows larger (e.g., over TBs), organising data in a way that is optimal for query performance becomes more important. Using Parquet or ORC formant is one optimisation, there are others such as:
Predicate pushdown.
Partitioned table.
Data sorting in Parquet and ORC.
Join strategy and cost based optimisation.
These topics are not Presto specific, they apply to most storages and query engines, including S3 and Presto. The details of these topics are beyond the scope of this blog. Stay tuned on my blogs. | [
{
"code": null,
"e": 473,
"s": 171,
"text": "It is such a simple and common task in big data that I thought folks must have done this a thousand times, so when a customer asked me this, I went straight to the internet trying to find some good examples to share with the customer. Guess what? I couldn’t find one! So I decided to write one myself."
},
{
"code": null,
"e": 528,
"s": 473,
"text": "A typical data ETL flow with Presto and S3 looks like:"
},
{
"code": null,
"e": 709,
"s": 528,
"text": "Upload CSV files into S3.Load the CSV files on S3 into Presto.(optional) Convert to analytics optimised format in Parquet or ORC.Run complex query against the Parquet or ORC table."
},
{
"code": null,
"e": 735,
"s": 709,
"text": "Upload CSV files into S3."
},
{
"code": null,
"e": 773,
"s": 735,
"text": "Load the CSV files on S3 into Presto."
},
{
"code": null,
"e": 841,
"s": 773,
"text": "(optional) Convert to analytics optimised format in Parquet or ORC."
},
{
"code": null,
"e": 893,
"s": 841,
"text": "Run complex query against the Parquet or ORC table."
},
{
"code": null,
"e": 1051,
"s": 893,
"text": "In this blog, I use the NewYork City 2018 Yellow Taxi Trip Dataset. The dataset has 112 million rows, 17 columns each row in CSV format. Total size is 9.8GB."
},
{
"code": null,
"e": 1078,
"s": 1051,
"text": "Here is some example data:"
},
{
"code": null,
"e": 1627,
"s": 1078,
"text": "head -n 3 tlc_yellow_trips_2018.csvVendorID,tpep_pickup_datetime,tpep_dropoff_datetime,passenger_count,trip_distance,RatecodeID,store_and_fwd_flag,PULocationID,DOLocationID,payment_type,fare_amount,extra,mta_tax,tip_amount,tolls_amount,improvement_surcharge,total_amount2,05/19/2018 11:51:48 PM,05/20/2018 12:07:31 AM,1,2.01,1,N,48,158,2,11.5,0.5,0.5,0,0,0.3,12.81,05/19/2018 11:22:53 PM,05/19/2018 11:35:14 PM,1,1.3,1,N,142,164,2,9,0.5,0.5,0,0,0.3,10.31,05/19/2018 11:37:02 PM,05/19/2018 11:52:41 PM,1,2.2,1,N,164,114,1,11,0.5,0.5,3.05,0,0.3,15.35"
},
{
"code": null,
"e": 1853,
"s": 1627,
"text": "I assume you have completed a basic Presto and S3 setup. You also need to set up the Hive catalog in Presto for it to query data in S3. If you haven’t, please take a look at my blog Presto with Kubernetes and S3 — Deployment."
},
{
"code": null,
"e": 2091,
"s": 1853,
"text": "Create a directory in S3 to store the CSV file. We can use any S3 client to create a S3 directory, here I simply use the hdfs command because it is available on the Hive Metastore node as part of the Hive catalog setup in the above blog."
},
{
"code": null,
"e": 2308,
"s": 2091,
"text": "Run the below command from the Hive Metastore node. Change bucket name to match your environment. Note I specified s3a:// as the directory path schema so that hdfs command creates the directory on S3 instead of HDFS."
},
{
"code": null,
"e": 2385,
"s": 2308,
"text": "hdfs dfs -mkdir -p s3a://deephub/warehouse/nyc_text.db/tlc_yellow_trips_2018"
},
{
"code": null,
"e": 2637,
"s": 2385,
"text": "Upload the CSV file to S3 under the directory we just created. Any S3 client should work, I use s5cmd, a very fast S3 client, to upload the CSV file into my S3 directory. Here I use FlashBlade S3, so I specified endpoint-url to my FlashBlade data VIP."
},
{
"code": null,
"e": 2795,
"s": 2637,
"text": "s5cmd --endpoint-url=http://192.168.170.12:80 cp tlc_yellow_trips_2018.csv s3://deephub/warehouse/nyc_text.db/tlc_yellow_trips_2018/tlc_yellow_trips_2018.csv"
},
{
"code": null,
"e": 2909,
"s": 2795,
"text": "In order to query data in S3, I need to create a table in Presto and map its schema and location to the CSV file."
},
{
"code": null,
"e": 2928,
"s": 2909,
"text": "Launch Presto CLI:"
},
{
"code": null,
"e": 2986,
"s": 2928,
"text": "presto-cli --server <coordinate_node:port> --catalog hive"
},
{
"code": null,
"e": 3038,
"s": 2986,
"text": "Create a new schema for text data using Presto CLI."
},
{
"code": null,
"e": 3126,
"s": 3038,
"text": "presto> CREATE SCHEMA nyc_text WITH (LOCATION = 's3a://deephub/warehouse/nyc_text.db');"
},
{
"code": null,
"e": 3222,
"s": 3126,
"text": "Create an external table for CSV data. You can create many tables under a single schema. Notes:"
},
{
"code": null,
"e": 3282,
"s": 3222,
"text": "CSV format table currently only supports VARCHAR data type."
},
{
"code": null,
"e": 3454,
"s": 3282,
"text": "I set skip_header_line_count = 1 to the table property so that first line header in our CSV file is skipped. Remove this property if your CSV file does not include header."
},
{
"code": null,
"e": 3647,
"s": 3454,
"text": "Presto’s CSV format support requires metastore.storage.schema.reader.impl=org.apache.hadoop.hive.metastore.SerDeStorageSchemaReader in the metastore-site.xml Hive Metastore configuration file."
},
{
"code": null,
"e": 4283,
"s": 3647,
"text": "presto> CREATE TABLE hive.nyc_text.tlc_yellow_trips_2018 ( vendorid VARCHAR, tpep_pickup_datetime VARCHAR, tpep_dropoff_datetime VARCHAR, passenger_count VARCHAR, trip_distance VARCHAR, ratecodeid VARCHAR, store_and_fwd_flag VARCHAR, pulocationid VARCHAR, dolocationid VARCHAR, payment_type VARCHAR, fare_amount VARCHAR, extra VARCHAR, mta_tax VARCHAR, tip_amount VARCHAR, tolls_amount VARCHAR, improvement_surcharge VARCHAR, total_amount VARCHAR)WITH (FORMAT = 'CSV', skip_header_line_count = 1, EXTERNAL_LOCATION = 's3a://deephub/warehouse/nyc_text.db/tlc_yellow_trips_2018');"
},
{
"code": null,
"e": 4313,
"s": 4283,
"text": "Now I can query the CSV data."
},
{
"code": null,
"e": 4376,
"s": 4313,
"text": "presto> SELECT * FROM nyc_text.tlc_yellow_trips_2018 LIMIT 10;"
},
{
"code": null,
"e": 4701,
"s": 4376,
"text": "At this point, I can connect Tableau to visualise data in the Presto table. However, because CSV format table only supports VARCHAR data type, it may expose limits to Tableau. If this is the case, convert CSV to Parquet or ORC format (see below). Parquet or ORC tables generally have better performance than Text/CSV tables."
},
{
"code": null,
"e": 4969,
"s": 4701,
"text": "This is an optional task, but it is recommended if the data will be queried multiple times. By converting text data into analytics optimised format in Parquet or ORC, it does not only improve query performance, but also reduce server and storage resource consumption."
},
{
"code": null,
"e": 5329,
"s": 4969,
"text": "Presto is good for simple conversions that can be done in SQL. For those with complex business logics that cannot be easily done with SQL (e.g., requires Java/Python programming), it is better to use Apache Spark. In this example, I simply convert text to Parquet format without introducing any complex business logic, so I will use Presto for the conversion."
},
{
"code": null,
"e": 5536,
"s": 5329,
"text": "A common practice for managing data in Presto is to use different schemas for your raw text (CSV/TSV) tables and optimised (Parquet/ORC) tables. So I will create a new schema nyc_parq for the Parquet table."
},
{
"code": null,
"e": 5624,
"s": 5536,
"text": "Create a S3 directory for the new schema. Change bucket name to match your environment."
},
{
"code": null,
"e": 5679,
"s": 5624,
"text": "hdfs dfs -mkdir -p s3a://deephub/warehouse/nyc_parq.db"
},
{
"code": null,
"e": 5721,
"s": 5679,
"text": "Create the nyc_parq schema in Presto CLI."
},
{
"code": null,
"e": 5809,
"s": 5721,
"text": "presto> CREATE SCHEMA nyc_parq WITH (LOCATION = 's3a://deephub/warehouse/nyc_parq.db');"
},
{
"code": null,
"e": 5946,
"s": 5809,
"text": "Create a Parquet table, convert CSV data to Parquet format. You can change the SELECT cause to add simple business and conversion logic."
},
{
"code": null,
"e": 7082,
"s": 5946,
"text": "presto> CREATE TABLE hive.nyc_parq.tlc_yellow_trips_2018COMMENT '2018 Newyork City taxi data'WITH (FORMAT = 'PARQUET')ASSELECT cast(vendorid as INTEGER) as vendorid, date_parse(tpep_pickup_datetime, '%m/%d/%Y %h:%i:%s %p') as tpep_pickup_datetime, date_parse(tpep_dropoff_datetime, '%m/%d/%Y %h:%i:%s %p') as tpep_dropoff_datetime, cast(passenger_count as SMALLINT) as passenger_count, cast(trip_distance as DECIMAL(8, 2)) as trip_distance, cast(ratecodeid as INTEGER) as ratecodeid, cast(store_and_fwd_flag as CHAR(1)) as store_and_fwd_flag, cast(pulocationid as INTEGER) as pulocationid, cast(dolocationid as INTEGER) as dolocationid, cast(payment_type as SMALLINT) as payment_type, cast(fare_amount as DECIMAL(8, 2)) as fare_amount, cast(extra as DECIMAL(8, 2)) as extra, cast(mta_tax as DECIMAL(8, 2)) as mta_tax, cast(tip_amount as DECIMAL(8, 2)) as tip_amount, cast(tolls_amount as DECIMAL(8, 2)) as tolls_amount, cast(improvement_surcharge as DECIMAL(8, 2)) as improvement_surcharge, cast(total_amount as DECIMAL(8, 2)) as total_amountFROM hive.nyc_text.tlc_yellow_trips_2018;"
},
{
"code": null,
"e": 7188,
"s": 7082,
"text": "Depending on the data size, this conversion may take time. Once it is done, I can query the Parquet data."
},
{
"code": null,
"e": 7251,
"s": 7188,
"text": "presto> SELECT * FROM nyc_parq.tlc_yellow_trips_2018 LIMIT 10;"
},
{
"code": null,
"e": 7337,
"s": 7251,
"text": "Confirm the Parquet table’s schema. Note columns are with desired type in this table."
},
{
"code": null,
"e": 8305,
"s": 7337,
"text": "presto> describe nyc_parq.tlc_yellow_trips_2018; Column | Type | Extra | Comment-----------------------+--------------+-------+--------- vendorid | integer | | tpep_pickup_datetime | timestamp | | tpep_dropoff_datetime | timestamp | | passenger_count | smallint | | trip_distance | decimal(8,2) | | ratecodeid | integer | | store_and_fwd_flag | char(1) | | pulocationid | integer | | dolocationid | integer | | payment_type | smallint | | fare_amount | decimal(8,2) | | extra | decimal(8,2) | | mta_tax | decimal(8,2) | | tip_amount | decimal(8,2) | | tolls_amount | decimal(8,2) | | improvement_surcharge | decimal(8,2) | | total_amount | decimal(8,2) | |(17 rows)"
},
{
"code": null,
"e": 8418,
"s": 8305,
"text": "Finally, I configure my analytics application / Tableau to use the optimised nyc_parq schema and Parquet tables."
},
{
"code": null,
"e": 8625,
"s": 8418,
"text": "As data size grows larger (e.g., over TBs), organising data in a way that is optimal for query performance becomes more important. Using Parquet or ORC formant is one optimisation, there are others such as:"
},
{
"code": null,
"e": 8645,
"s": 8625,
"text": "Predicate pushdown."
},
{
"code": null,
"e": 8664,
"s": 8645,
"text": "Partitioned table."
},
{
"code": null,
"e": 8697,
"s": 8664,
"text": "Data sorting in Parquet and ORC."
},
{
"code": null,
"e": 8740,
"s": 8697,
"text": "Join strategy and cost based optimisation."
}
]
|
Convert HashMap to LinkedList in Java - GeeksforGeeks | 21 Feb, 2022
HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values.
LinkedList is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node.
Example:
Input:
l.put(2, 5);
l.put(3, 6);
l.put(4, 1);
l.put(8, 2);
Output:
LinkedList of key-> [2, 3, 4, 8]
LinkedList of values-> [5, 6, 1, 2]
respectively the output for key and values.
Syntax of keySet() Method
hash_map.keySet()
Parameters: The method does not take any parameters.
Return Value: The method returns a set having the keys of the hash map.
Syntax of values() Method
Hash_Map.values()
Parameters: The method does not accept any parameters.
Return Value: The method is used to return a collection view containing all the values of the map.
PseudoCode
List<Integer> list = new LinkedList<>(l.keySet());
List<Integer> listOfValue = new LinkedList<>(l.values());
Example 1:
Java
// Java program to Convert HashMap to LinkedList import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // create a hashmap instance HashMap<Integer, Integer> l = new HashMap<>(); // add mappings l.put(2, 5); l.put(3, 6); l.put(4, 1); l.put(8, 2); // list of keys List<Integer> list = new LinkedList<>(l.keySet()); // list of values List<Integer> listOfValue = new LinkedList<>(l.values()); // print the list System.out.println("LinkedList of key-> " + list); System.out.println("LinkedList of values-> " + listOfValue); }}
LinkedList of key-> [2, 3, 4, 8]
LinkedList of values-> [5, 6, 1, 2]
Example 2:
Java
// Java program to Convert HashMap to LinkedList import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // create a hashmap instance HashMap<Integer, String> l = new HashMap<>(); // add mappings l.put(1, "Geeks"); l.put(4, "For"); l.put(3, "Geeks"); // list of keys List<Integer> list = new LinkedList<>(l.keySet()); // list of values List<String> listOfValue = new LinkedList<>(l.values()); // print the list System.out.println("LinkedList of key-> " + list); System.out.println("LinkedList of values-> " + listOfValue); }}
LinkedList of key-> [1, 3, 4]
LinkedList of values-> [Geeks, Geeks, For]
simmytarika5
rkbhola5
Java-HashMap
java-LinkedList
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 24142,
"s": 23948,
"text": "HashMap is similar to the HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values."
},
{
"code": null,
"e": 24538,
"s": 24142,
"text": "LinkedList is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node."
},
{
"code": null,
"e": 24547,
"s": 24538,
"text": "Example:"
},
{
"code": null,
"e": 24768,
"s": 24547,
"text": "Input: \n l.put(2, 5);\n l.put(3, 6);\n l.put(4, 1);\n l.put(8, 2);\n \nOutput: \n LinkedList of key-> [2, 3, 4, 8]\n LinkedList of values-> [5, 6, 1, 2]\n respectively the output for key and values."
},
{
"code": null,
"e": 24794,
"s": 24768,
"text": "Syntax of keySet() Method"
},
{
"code": null,
"e": 24812,
"s": 24794,
"text": "hash_map.keySet()"
},
{
"code": null,
"e": 24865,
"s": 24812,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 24937,
"s": 24865,
"text": "Return Value: The method returns a set having the keys of the hash map."
},
{
"code": null,
"e": 24963,
"s": 24937,
"text": "Syntax of values() Method"
},
{
"code": null,
"e": 24981,
"s": 24963,
"text": "Hash_Map.values()"
},
{
"code": null,
"e": 25036,
"s": 24981,
"text": "Parameters: The method does not accept any parameters."
},
{
"code": null,
"e": 25135,
"s": 25036,
"text": "Return Value: The method is used to return a collection view containing all the values of the map."
},
{
"code": null,
"e": 25146,
"s": 25135,
"text": "PseudoCode"
},
{
"code": null,
"e": 25255,
"s": 25146,
"text": "List<Integer> list = new LinkedList<>(l.keySet());\nList<Integer> listOfValue = new LinkedList<>(l.values());"
},
{
"code": null,
"e": 25266,
"s": 25255,
"text": "Example 1:"
},
{
"code": null,
"e": 25271,
"s": 25266,
"text": "Java"
},
{
"code": "// Java program to Convert HashMap to LinkedList import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // create a hashmap instance HashMap<Integer, Integer> l = new HashMap<>(); // add mappings l.put(2, 5); l.put(3, 6); l.put(4, 1); l.put(8, 2); // list of keys List<Integer> list = new LinkedList<>(l.keySet()); // list of values List<Integer> listOfValue = new LinkedList<>(l.values()); // print the list System.out.println(\"LinkedList of key-> \" + list); System.out.println(\"LinkedList of values-> \" + listOfValue); }}",
"e": 25984,
"s": 25271,
"text": null
},
{
"code": null,
"e": 26053,
"s": 25984,
"text": "LinkedList of key-> [2, 3, 4, 8]\nLinkedList of values-> [5, 6, 1, 2]"
},
{
"code": null,
"e": 26064,
"s": 26053,
"text": "Example 2:"
},
{
"code": null,
"e": 26069,
"s": 26064,
"text": "Java"
},
{
"code": "// Java program to Convert HashMap to LinkedList import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // create a hashmap instance HashMap<Integer, String> l = new HashMap<>(); // add mappings l.put(1, \"Geeks\"); l.put(4, \"For\"); l.put(3, \"Geeks\"); // list of keys List<Integer> list = new LinkedList<>(l.keySet()); // list of values List<String> listOfValue = new LinkedList<>(l.values()); // print the list System.out.println(\"LinkedList of key-> \" + list); System.out.println(\"LinkedList of values-> \" + listOfValue); }}",
"e": 26804,
"s": 26069,
"text": null
},
{
"code": null,
"e": 26877,
"s": 26804,
"text": "LinkedList of key-> [1, 3, 4]\nLinkedList of values-> [Geeks, Geeks, For]"
},
{
"code": null,
"e": 26890,
"s": 26877,
"text": "simmytarika5"
},
{
"code": null,
"e": 26899,
"s": 26890,
"text": "rkbhola5"
},
{
"code": null,
"e": 26912,
"s": 26899,
"text": "Java-HashMap"
},
{
"code": null,
"e": 26928,
"s": 26912,
"text": "java-LinkedList"
},
{
"code": null,
"e": 26935,
"s": 26928,
"text": "Picked"
},
{
"code": null,
"e": 26959,
"s": 26935,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 26964,
"s": 26959,
"text": "Java"
},
{
"code": null,
"e": 26978,
"s": 26964,
"text": "Java Programs"
},
{
"code": null,
"e": 26997,
"s": 26978,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27002,
"s": 26997,
"text": "Java"
},
{
"code": null,
"e": 27100,
"s": 27002,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27115,
"s": 27100,
"text": "Stream In Java"
},
{
"code": null,
"e": 27136,
"s": 27115,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27182,
"s": 27136,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27201,
"s": 27182,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27231,
"s": 27201,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27275,
"s": 27231,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 27301,
"s": 27275,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27335,
"s": 27301,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 27382,
"s": 27335,
"text": "Implementing a Linked List in Java using Class"
}
]
|
Difference Between Packages and Interfaces in Java | In this post, we will understand the difference between packages and interfaces in Java.
It is a group of classes and/or interfaces that are together.
It is a group of classes and/or interfaces that are together.
It can be created using the "Package" keyword.
It can be created using the "Package" keyword.
It can be imported.
It can be imported.
It can be done using the "import" keyword.
It can be done using the "import" keyword.
package package_name;
public class class_name {
.
(body of class)
.
}
It is a group of abstract methods and constants.
It is a group of abstract methods and constants.
It can be created using the "Interface" keyword.
It can be created using the "Interface" keyword.
It can be extended by another interface.
It can be extended by another interface.
It can also be implemented by a class.
It can also be implemented by a class.
It can be implemented using the ‘implement’ keyword.
It can be implemented using the ‘implement’ keyword.
interface interface_name {
variable declaration;
method declaration;
} | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "In this post, we will understand the difference between packages and interfaces in Java."
},
{
"code": null,
"e": 1213,
"s": 1151,
"text": "It is a group of classes and/or interfaces that are together."
},
{
"code": null,
"e": 1275,
"s": 1213,
"text": "It is a group of classes and/or interfaces that are together."
},
{
"code": null,
"e": 1322,
"s": 1275,
"text": "It can be created using the \"Package\" keyword."
},
{
"code": null,
"e": 1369,
"s": 1322,
"text": "It can be created using the \"Package\" keyword."
},
{
"code": null,
"e": 1389,
"s": 1369,
"text": "It can be imported."
},
{
"code": null,
"e": 1409,
"s": 1389,
"text": "It can be imported."
},
{
"code": null,
"e": 1452,
"s": 1409,
"text": "It can be done using the \"import\" keyword."
},
{
"code": null,
"e": 1495,
"s": 1452,
"text": "It can be done using the \"import\" keyword."
},
{
"code": null,
"e": 1574,
"s": 1495,
"text": "package package_name;\npublic class class_name {\n .\n (body of class)\n .\n}"
},
{
"code": null,
"e": 1623,
"s": 1574,
"text": "It is a group of abstract methods and constants."
},
{
"code": null,
"e": 1672,
"s": 1623,
"text": "It is a group of abstract methods and constants."
},
{
"code": null,
"e": 1721,
"s": 1672,
"text": "It can be created using the \"Interface\" keyword."
},
{
"code": null,
"e": 1770,
"s": 1721,
"text": "It can be created using the \"Interface\" keyword."
},
{
"code": null,
"e": 1811,
"s": 1770,
"text": "It can be extended by another interface."
},
{
"code": null,
"e": 1852,
"s": 1811,
"text": "It can be extended by another interface."
},
{
"code": null,
"e": 1891,
"s": 1852,
"text": "It can also be implemented by a class."
},
{
"code": null,
"e": 1930,
"s": 1891,
"text": "It can also be implemented by a class."
},
{
"code": null,
"e": 1983,
"s": 1930,
"text": "It can be implemented using the ‘implement’ keyword."
},
{
"code": null,
"e": 2036,
"s": 1983,
"text": "It can be implemented using the ‘implement’ keyword."
},
{
"code": null,
"e": 2113,
"s": 2036,
"text": "interface interface_name {\n variable declaration;\n method declaration;\n}"
}
]
|
Write program to shutdown a system in C/C++ | A program to shutdown the system works on the operating systems like windows, linux or macOS. To shut it off and close all opened applications.
Shut down or Power off a computer means removing power from a computer's main components in an organised prescribed way and turning off all the works that are done by the computer i.e. all applications and processings are shut off. After a computer is shut down, the main components such as CPU, RAM modules and hard disk drives are powered down, although some internal components, such as an internal clock, may access power.
This program turns off, i.e., shut down your computer system. System function of "stdio.h" is to run an executable file shutdown.exe which is present in C:\WINDOWS\system32 folder in Windows.
For Linux program the process is similar and is mentioned below.
#include <stdio.h>
int main() {
system("c:\\windows\\system32\\shutdown /i");
return 0;
}
The program works as a command that commands the operating system to close all applications and shutdown the system.
#include <stdio.h>
int main() {
system("shutdown -P now");
return 0;
}
This is a code that can shut any linux based operating systems. Code directly puts a command for the system which executes it and shuts the system as soon as possible. | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "A program to shutdown the system works on the operating systems like windows, linux or macOS. To shut it off and close all opened applications."
},
{
"code": null,
"e": 1633,
"s": 1206,
"text": "Shut down or Power off a computer means removing power from a computer's main components in an organised prescribed way and turning off all the works that are done by the computer i.e. all applications and processings are shut off. After a computer is shut down, the main components such as CPU, RAM modules and hard disk drives are powered down, although some internal components, such as an internal clock, may access power."
},
{
"code": null,
"e": 1825,
"s": 1633,
"text": "This program turns off, i.e., shut down your computer system. System function of \"stdio.h\" is to run an executable file shutdown.exe which is present in C:\\WINDOWS\\system32 folder in Windows."
},
{
"code": null,
"e": 1890,
"s": 1825,
"text": "For Linux program the process is similar and is mentioned below."
},
{
"code": null,
"e": 1986,
"s": 1890,
"text": "#include <stdio.h>\nint main() {\n system(\"c:\\\\windows\\\\system32\\\\shutdown /i\");\n return 0;\n}"
},
{
"code": null,
"e": 2103,
"s": 1986,
"text": "The program works as a command that commands the operating system to close all applications and shutdown the system."
},
{
"code": null,
"e": 2180,
"s": 2103,
"text": "#include <stdio.h>\nint main() {\n system(\"shutdown -P now\");\n return 0;\n}"
},
{
"code": null,
"e": 2348,
"s": 2180,
"text": "This is a code that can shut any linux based operating systems. Code directly puts a command for the system which executes it and shuts the system as soon as possible."
}
]
|
Program to print multiplication table of any number in PHP - GeeksforGeeks | 27 Oct, 2021
In this article, we will see how to print the multiplication table of any given number using PHP. To make the multiplication table, first, we get a number input from the user and then use for loop to display the multiplication table.
We use HTML and PHP to display the multiplication table. The HTML part is used to design a form to get the input from the user and the PHP part is used to execute the multiplication and display the results in table format.
Example:
PHP
<!DOCTYPE html>
<html>
<body>
<center>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>
Program to print multiplication<br>
table of any number in PHP
</h3>
<form method="POST">
Enter a number:
<input type="text" name="number">
<input type="Submit"
value="Get Multiplication Table">
</form>
</center>
</body>
</html>
<?php
if($_POST) {
$num = $_POST["number"];
echo nl2br("<p style='text-align: center;'>
Multiplication Table of $num: </p>
");
for ($i = 1; $i <= 10; $i++) {
echo ("<p style='text-align: center;'>$num"
. " X " . "$i" . " = "
. $num * $i . "</p>
");
}
}
?>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Questions
loop
PHP-math
PHP-Questions
HTML
PHP
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
How to convert array to string in PHP ? | [
{
"code": null,
"e": 24866,
"s": 24835,
"text": " \n27 Oct, 2021\n"
},
{
"code": null,
"e": 25100,
"s": 24866,
"text": "In this article, we will see how to print the multiplication table of any given number using PHP. To make the multiplication table, first, we get a number input from the user and then use for loop to display the multiplication table."
},
{
"code": null,
"e": 25323,
"s": 25100,
"text": "We use HTML and PHP to display the multiplication table. The HTML part is used to design a form to get the input from the user and the PHP part is used to execute the multiplication and display the results in table format."
},
{
"code": null,
"e": 25332,
"s": 25323,
"text": "Example:"
},
{
"code": null,
"e": 25336,
"s": 25332,
"text": "PHP"
},
{
"code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html> \n \n<body> \n <center> \n <h1 style=\"color: green;\"> \n GeeksforGeeks \n </h1> \n \n <h3> \n Program to print multiplication<br> \n table of any number in PHP \n </h3> \n \n <form method=\"POST\"> \n Enter a number: \n <input type=\"text\" name=\"number\"> \n \n <input type=\"Submit\" \n value=\"Get Multiplication Table\"> \n </form> \n </center> \n</body> \n \n</html> \n \n<?php \nif($_POST) { \n $num = $_POST[\"number\"]; \n \n echo nl2br(\"<p style='text-align: center;'> \n Multiplication Table of $num: </p> \n \"); \n \n for ($i = 1; $i <= 10; $i++) { \n echo (\"<p style='text-align: center;'>$num\"\n . \" X \" . \"$i\" . \" = \" \n . $num * $i . \"</p> \n \"); \n } \n} \n?>\n\n\n\n\n\n",
"e": 26224,
"s": 25346,
"text": null
},
{
"code": null,
"e": 26232,
"s": 26224,
"text": "Output:"
},
{
"code": null,
"e": 26369,
"s": 26232,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26386,
"s": 26369,
"text": "\nHTML-Questions\n"
},
{
"code": null,
"e": 26393,
"s": 26386,
"text": "\nloop\n"
},
{
"code": null,
"e": 26404,
"s": 26393,
"text": "\nPHP-math\n"
},
{
"code": null,
"e": 26420,
"s": 26404,
"text": "\nPHP-Questions\n"
},
{
"code": null,
"e": 26427,
"s": 26420,
"text": "\nHTML\n"
},
{
"code": null,
"e": 26433,
"s": 26427,
"text": "\nPHP\n"
},
{
"code": null,
"e": 26452,
"s": 26433,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 26657,
"s": 26452,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26705,
"s": 26657,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26756,
"s": 26705,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26780,
"s": 26756,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26830,
"s": 26780,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26867,
"s": 26830,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26912,
"s": 26867,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 26963,
"s": 26912,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26987,
"s": 26963,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 27031,
"s": 26987,
"text": "How to pop an alert message box using PHP ?"
}
]
|
Jagged Array in Java | Jagged array is a multidimensional array where member arrays are of different size. For example, we can create a 2D array where first array is of 3 elements, and is of 4 elements. Following is the example demonstrating the concept of jagged array.
Live Demo
public class Tester {
public static void main(String[] args){
int[][] twoDimenArray = new int[2][];
//first row has 3 columns
twoDimenArray[0] = new int[3];
//second row has 4 columns
twoDimenArray[1] = new int[4];
int counter = 0;
//initializing array
for(int row=0; row < twoDimenArray.length; row++){
for(int col=0; col < twoDimenArray[row].length; col++){
twoDimenArray[row][col] = counter++;
}
}
//printing array
for(int row=0; row < twoDimenArray.length; row++){
System.out.println();
for(int col=0; col < twoDimenArray[row].length; col++){
System.out.print(twoDimenArray[row][col] + " ");
}
}
}
}
0 1 2
3 4 5 6 | [
{
"code": null,
"e": 1310,
"s": 1062,
"text": "Jagged array is a multidimensional array where member arrays are of different size. For example, we can create a 2D array where first array is of 3 elements, and is of 4 elements. Following is the example demonstrating the concept of jagged array."
},
{
"code": null,
"e": 1321,
"s": 1310,
"text": " Live Demo"
},
{
"code": null,
"e": 2077,
"s": 1321,
"text": "public class Tester {\n public static void main(String[] args){\n int[][] twoDimenArray = new int[2][];\n\n //first row has 3 columns\n twoDimenArray[0] = new int[3];\n\n //second row has 4 columns\n twoDimenArray[1] = new int[4];\n\n int counter = 0;\n //initializing array\n for(int row=0; row < twoDimenArray.length; row++){\n\n for(int col=0; col < twoDimenArray[row].length; col++){\n twoDimenArray[row][col] = counter++;\n }\n }\n\n //printing array\n for(int row=0; row < twoDimenArray.length; row++){\n System.out.println();\n for(int col=0; col < twoDimenArray[row].length; col++){\n System.out.print(twoDimenArray[row][col] + \" \");\n }\n }\n }\n}"
},
{
"code": null,
"e": 2091,
"s": 2077,
"text": "0 1 2\n3 4 5 6"
}
]
|
How to Calculate Minkowski Distance in R? - GeeksforGeeks | 14 Jan, 2022
In this article, we are going to see how to calculate Minkowski Distance in the R Programming language.
Minkowski distance is a distance measured between two points in N-dimensional space. It is basically a generalization of the Euclidean distance and the Manhattan distance. It is widely used in the field of Machine learning, especially in the concept to find the optimal correlation or classification of data. Minkowski distance is used in certain algorithms also like K-Nearest Neighbors, Learning Vector Quantization (LVQ), Self-Organizing Map (SOM), and K-Means Clustering.
Let us consider a 2-dimensional space having three points P1 (X1, Y1), P2 (X2, Y2), and P3 (X3, Y3), the Minkowski distance is given by ( |X1 – Y1|p + |X2 – Y2|p + |X2 – Y2|p )1/p. In R, Minkowski distance is calculated with respect to vectors.
For example,
we are given two vectors, vect1 as (4, 2, 6, 8) and vect2 as (5, 1, 7, 9). Their Minkowski distance for p = 2 is given by, ( |4 – 5|2 + |2 – 1|2 + |6 – 7|2 + |8 – 9|2 )1/2 which is equal to 2. This article focuses upon how we can calculate Minkowski distance in R.
We can calculate Minkowski distance between a pair of vectors by apply the formula,
( Σ|vector1i – vector2i|p )1/p
Here,
vector1 is the first vector
vector2 is the second vector
p is an integer
Below is the implementation in R to calculate Minkowski distance by using a custom function.
R
# R program to illustrate how to# calculate Minkowski distance# using a custom function # Custom function to calculate Minkowski distance calculateMinkowskiDistance <- function(vect1, vect2, p) { # Initializing answer variable as 0 answer <- as.integer(0) # Iterating over the length of the vector # Using for-in loop for (index in 0 : length(vect1)) { # temp stores the absolute difference raised to power p temp = as.integer(abs(vect1[index] - vect2[index]) ^ p) # Updating answer variable answer = sum(temp, answer) } # The final answer would be answer raised to # power 1 / p answer = answer ^ (1 / p) # Return the answer return(answer)} # Initializing a vectorvect1 <- c(1, 3, 5, 7) # Initializing another vectorvect2 <- c(2, 4, 6, 8) # Set p equal to 4p <- as.integer(1) # Call the function to calculate MinkowskiDistancedistance = calculateMinkowskiDistance(vect1, vect2, p) # Print the calculated distanceprint(paste("The Minkowski distance between vect1\and vect2 having the value of p =",p, "is", distance )) # Set p equal to 5p <- as.integer(2) # Call the function to calculate MinkowskiDistancedistance = calculateMinkowskiDistance(vect1, vect2, p) # Print the calculated distanceprint(paste("The Minkowski distance between vect1\and vect2 having the value of p =",p, "is", distance )) # Set p equal to 5p <- as.integer(3) # Call the function to calculate MinkowskiDistancedistance = calculateMinkowskiDistance(vect1, vect2, p) # Print the calculated distanceprint(paste("The Minkowski distance between vect1\and vect2 having the value of p =",p, "is", distance )) # Set p equal to 5p <- as.integer(4) # Call the function to calculate MinkowskiDistancedistance = calculateMinkowskiDistance(vect1, vect2, p) # Print the calculated distanceprint(paste("The Minkowski distance between vect1 \and vect2 having the value of p =",p, "is", distance ))
Output:
R provides inbuilt dist function using which we can calculate six types of distances including Minkowski distance. This function accepts a two-dimensional vector or a matrix as a parameter. This function is quite useful as it calculates the Minkowski distance between each unique pair of vectors specified in a two-dimensional vector.
Syntax: dist(vect, method = “minkowski”, p = integer, diag = TRUE or FALSE, upper = TRUE or FALSE)
Parameters:
vect: A two-dimensional vector
method: It must be equal to “minkowski”
p: It must be equal to an integer
diag: logical value (TRUE or FALSE) that conveys whether the diagonal of the distance matrix should be printed by print.dist or not.
upper: logical value (TRUE or FALSE) that conveys whether the upper triangle of the distance matrix should be printed by print.dist or not.
Return type:
It return an object of class “dist” which represents Minkowski distance between each unique pair of rows or vectors.
Note: diag and upper parameters are optional
Example 1: Implementation using vectors of equal length.
R
# R program to illustrate how to calculate# Minkowski distance By using inbuilt dist()# function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print("Minkowski distance between each pair of vectors is: ")cat("\n\n") # Calculate Minkowski distance between vectors# using built in dist method# By passing two-dimensional vector as a parameter# Since we want to calculate Minkowski distance# between each unique pair of vectors# That is why we are passing Minkowski as a methoddist(twoDimensionalVect, method = "minkowski", diag = TRUE, upper = TRUE p = 2)
Output:
Note that the length of all vectors present in a two-dimensional vector has to be the same. Otherwise, the compiler will produce a warning message.
Example 2: Implementation using vectors of unequal length.
R
# R program to illustrate# how to calculate Minkowski distance# By using inbuilt dist() function # Initializing a vector# Note that the length of vec1 is one# more than the other vectorsvect1 <- c(2, 4, 1, 9, 2, 3, 10) # Initializing another vectorvect2 <- c(4, 8, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(11, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(21, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(11, 4, 8, 3, 9, 21) # Initializing another vectorvect6 <- c(6, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print("Minkowski distance between each pair of vectors is: ")cat("\n\n") # Calculate Minkowski distance between# vectors using built in dist method# By passing two-dimensional vector as a parameter# Since we want to calculate Minkowski# distance between each unique pair of vectors# That is why we are passing Minkowski as a methoddist(twoDimensionalVect, method = "minkowski", diag = TRUE, upper = TRUE p = 2)
Output:
As you can in the output, the compiler produces a warning message when vectors are of unequal lengths.
sweetyty
arorakashish0911
simranarora5sos
bhuwanesh
Picked
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
R - if statement
How to filter R dataframe by multiple conditions?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R | [
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 26701,
"s": 26597,
"text": "In this article, we are going to see how to calculate Minkowski Distance in the R Programming language."
},
{
"code": null,
"e": 27177,
"s": 26701,
"text": "Minkowski distance is a distance measured between two points in N-dimensional space. It is basically a generalization of the Euclidean distance and the Manhattan distance. It is widely used in the field of Machine learning, especially in the concept to find the optimal correlation or classification of data. Minkowski distance is used in certain algorithms also like K-Nearest Neighbors, Learning Vector Quantization (LVQ), Self-Organizing Map (SOM), and K-Means Clustering."
},
{
"code": null,
"e": 27423,
"s": 27177,
"text": "Let us consider a 2-dimensional space having three points P1 (X1, Y1), P2 (X2, Y2), and P3 (X3, Y3), the Minkowski distance is given by ( |X1 – Y1|p + |X2 – Y2|p + |X2 – Y2|p )1/p. In R, Minkowski distance is calculated with respect to vectors."
},
{
"code": null,
"e": 27436,
"s": 27423,
"text": "For example,"
},
{
"code": null,
"e": 27702,
"s": 27436,
"text": "we are given two vectors, vect1 as (4, 2, 6, 8) and vect2 as (5, 1, 7, 9). Their Minkowski distance for p = 2 is given by, ( |4 – 5|2 + |2 – 1|2 + |6 – 7|2 + |8 – 9|2 )1/2 which is equal to 2. This article focuses upon how we can calculate Minkowski distance in R."
},
{
"code": null,
"e": 27786,
"s": 27702,
"text": "We can calculate Minkowski distance between a pair of vectors by apply the formula,"
},
{
"code": null,
"e": 27817,
"s": 27786,
"text": "( Σ|vector1i – vector2i|p )1/p"
},
{
"code": null,
"e": 27823,
"s": 27817,
"text": "Here,"
},
{
"code": null,
"e": 27851,
"s": 27823,
"text": "vector1 is the first vector"
},
{
"code": null,
"e": 27880,
"s": 27851,
"text": "vector2 is the second vector"
},
{
"code": null,
"e": 27896,
"s": 27880,
"text": "p is an integer"
},
{
"code": null,
"e": 27989,
"s": 27896,
"text": "Below is the implementation in R to calculate Minkowski distance by using a custom function."
},
{
"code": null,
"e": 27991,
"s": 27989,
"text": "R"
},
{
"code": "# R program to illustrate how to# calculate Minkowski distance# using a custom function # Custom function to calculate Minkowski distance calculateMinkowskiDistance <- function(vect1, vect2, p) { # Initializing answer variable as 0 answer <- as.integer(0) # Iterating over the length of the vector # Using for-in loop for (index in 0 : length(vect1)) { # temp stores the absolute difference raised to power p temp = as.integer(abs(vect1[index] - vect2[index]) ^ p) # Updating answer variable answer = sum(temp, answer) } # The final answer would be answer raised to # power 1 / p answer = answer ^ (1 / p) # Return the answer return(answer)} # Initializing a vectorvect1 <- c(1, 3, 5, 7) # Initializing another vectorvect2 <- c(2, 4, 6, 8) # Set p equal to 4p <- as.integer(1) # Call the function to calculate MinkowskiDistancedistance = calculateMinkowskiDistance(vect1, vect2, p) # Print the calculated distanceprint(paste(\"The Minkowski distance between vect1\\and vect2 having the value of p =\",p, \"is\", distance )) # Set p equal to 5p <- as.integer(2) # Call the function to calculate MinkowskiDistancedistance = calculateMinkowskiDistance(vect1, vect2, p) # Print the calculated distanceprint(paste(\"The Minkowski distance between vect1\\and vect2 having the value of p =\",p, \"is\", distance )) # Set p equal to 5p <- as.integer(3) # Call the function to calculate MinkowskiDistancedistance = calculateMinkowskiDistance(vect1, vect2, p) # Print the calculated distanceprint(paste(\"The Minkowski distance between vect1\\and vect2 having the value of p =\",p, \"is\", distance )) # Set p equal to 5p <- as.integer(4) # Call the function to calculate MinkowskiDistancedistance = calculateMinkowskiDistance(vect1, vect2, p) # Print the calculated distanceprint(paste(\"The Minkowski distance between vect1 \\and vect2 having the value of p =\",p, \"is\", distance ))",
"e": 29917,
"s": 27991,
"text": null
},
{
"code": null,
"e": 29925,
"s": 29917,
"text": "Output:"
},
{
"code": null,
"e": 30260,
"s": 29925,
"text": "R provides inbuilt dist function using which we can calculate six types of distances including Minkowski distance. This function accepts a two-dimensional vector or a matrix as a parameter. This function is quite useful as it calculates the Minkowski distance between each unique pair of vectors specified in a two-dimensional vector."
},
{
"code": null,
"e": 30359,
"s": 30260,
"text": "Syntax: dist(vect, method = “minkowski”, p = integer, diag = TRUE or FALSE, upper = TRUE or FALSE)"
},
{
"code": null,
"e": 30371,
"s": 30359,
"text": "Parameters:"
},
{
"code": null,
"e": 30402,
"s": 30371,
"text": "vect: A two-dimensional vector"
},
{
"code": null,
"e": 30442,
"s": 30402,
"text": "method: It must be equal to “minkowski”"
},
{
"code": null,
"e": 30476,
"s": 30442,
"text": "p: It must be equal to an integer"
},
{
"code": null,
"e": 30609,
"s": 30476,
"text": "diag: logical value (TRUE or FALSE) that conveys whether the diagonal of the distance matrix should be printed by print.dist or not."
},
{
"code": null,
"e": 30749,
"s": 30609,
"text": "upper: logical value (TRUE or FALSE) that conveys whether the upper triangle of the distance matrix should be printed by print.dist or not."
},
{
"code": null,
"e": 30762,
"s": 30749,
"text": "Return type:"
},
{
"code": null,
"e": 30880,
"s": 30762,
"text": "It return an object of class “dist” which represents Minkowski distance between each unique pair of rows or vectors. "
},
{
"code": null,
"e": 30925,
"s": 30880,
"text": "Note: diag and upper parameters are optional"
},
{
"code": null,
"e": 30982,
"s": 30925,
"text": "Example 1: Implementation using vectors of equal length."
},
{
"code": null,
"e": 30984,
"s": 30982,
"text": "R"
},
{
"code": "# R program to illustrate how to calculate# Minkowski distance By using inbuilt dist()# function # Initializing a vectorvect1 <- c(1, 4, 8, 9, 2, 3) # Initializing another vectorvect2 <- c(9, 4, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(1, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(2, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(1, 4, 8, 3, 9, 2) # Initializing another vectorvect6 <- c(3, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print(\"Minkowski distance between each pair of vectors is: \")cat(\"\\n\\n\") # Calculate Minkowski distance between vectors# using built in dist method# By passing two-dimensional vector as a parameter# Since we want to calculate Minkowski distance# between each unique pair of vectors# That is why we are passing Minkowski as a methoddist(twoDimensionalVect, method = \"minkowski\", diag = TRUE, upper = TRUE p = 2)",
"e": 31973,
"s": 30984,
"text": null
},
{
"code": null,
"e": 31981,
"s": 31973,
"text": "Output:"
},
{
"code": null,
"e": 32129,
"s": 31981,
"text": "Note that the length of all vectors present in a two-dimensional vector has to be the same. Otherwise, the compiler will produce a warning message."
},
{
"code": null,
"e": 32188,
"s": 32129,
"text": "Example 2: Implementation using vectors of unequal length."
},
{
"code": null,
"e": 32190,
"s": 32188,
"text": "R"
},
{
"code": "# R program to illustrate# how to calculate Minkowski distance# By using inbuilt dist() function # Initializing a vector# Note that the length of vec1 is one# more than the other vectorsvect1 <- c(2, 4, 1, 9, 2, 3, 10) # Initializing another vectorvect2 <- c(4, 8, 1, 2, 4, 7) # Initializing another vectorvect3 <- c(11, 7, 9, 3, 2, 8) # Initializing another vectorvect4 <- c(21, 1, 4, 7, 8, 9) # Initializing another vectorvect5 <- c(11, 4, 8, 3, 9, 21) # Initializing another vectorvect6 <- c(6, 7, 8, 6, 5, 9) #Row bind vectors into a single matrixtwoDimensionalVect <- rbind(vect1, vect2, vect3, vect4, vect5, vect6) print(\"Minkowski distance between each pair of vectors is: \")cat(\"\\n\\n\") # Calculate Minkowski distance between# vectors using built in dist method# By passing two-dimensional vector as a parameter# Since we want to calculate Minkowski# distance between each unique pair of vectors# That is why we are passing Minkowski as a methoddist(twoDimensionalVect, method = \"minkowski\", diag = TRUE, upper = TRUE p = 2)",
"e": 33280,
"s": 32190,
"text": null
},
{
"code": null,
"e": 33288,
"s": 33280,
"text": "Output:"
},
{
"code": null,
"e": 33391,
"s": 33288,
"text": "As you can in the output, the compiler produces a warning message when vectors are of unequal lengths."
},
{
"code": null,
"e": 33400,
"s": 33391,
"text": "sweetyty"
},
{
"code": null,
"e": 33417,
"s": 33400,
"text": "arorakashish0911"
},
{
"code": null,
"e": 33433,
"s": 33417,
"text": "simranarora5sos"
},
{
"code": null,
"e": 33443,
"s": 33433,
"text": "bhuwanesh"
},
{
"code": null,
"e": 33450,
"s": 33443,
"text": "Picked"
},
{
"code": null,
"e": 33463,
"s": 33450,
"text": "R-Statistics"
},
{
"code": null,
"e": 33474,
"s": 33463,
"text": "R Language"
},
{
"code": null,
"e": 33572,
"s": 33474,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33624,
"s": 33572,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 33659,
"s": 33624,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 33717,
"s": 33659,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 33755,
"s": 33717,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 33798,
"s": 33755,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 33815,
"s": 33798,
"text": "R - if statement"
},
{
"code": null,
"e": 33865,
"s": 33815,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 33914,
"s": 33865,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 33951,
"s": 33914,
"text": "How to import an Excel File into R ?"
}
]
|
Java ResultSetMetaData getColumnName() method with example | The getColumnName() method of the ResultSetMetaData (interface) retrieves and returns the name of the specified column in the current ResultSet object.
This method accepts an integer value representing the index of a column and, returns a String value representing the name of the specified column.
To get the ResultSetMetaData object, you need to −
Register the Driver: Select the required database register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class.
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Get connection: Create a connection object by passing the URL of the database, username and password of a user in the database (in string format) as parameters to the getConnection() method of the DriverManager class.
Connection mysqlCon = DriverManager.getConnection(mysqlUrl, "root", "password");
Create a Statement object: Create a Statement object using the createStatement method of the connection interface.
Statement stmt = con.createStatement();
Execute the Query: Execute the SELECT query using the executeQuery() methods of the Statement interface and Retrieve the results into the ResultSet object.
String query = "Select * from MyPlayers";
ResultSet rs = stmt.executeQuery(query);
Get the ResultSetMetaData object: Retrieve the ResultSetMetsdata object of the current ResultSet by invoking the getMetaData() method.
ResultSetMetaData resultSetMetaData = rs.getMetaData();
Finally, using the getColumnName() method of the ResultSetMetaData interface get the name of the specified column as −
int columnType = resultSetMetaData.getColumnName();
Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −
CREATE TABLE MyPlayers(
ID INT,
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Date_Of_Birth date,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255),
PRIMARY KEY (ID)
);
Now, we will insert 7 records in MyPlayers table using INSERT statements −
insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');
insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');
Following JDBC program establishes connection with MySQL database, retrieves and displays the name of the 4th column in the MyPlayers table using the getColumnName() method.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class ResultSetMetadata_getColumnName {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to retrieve records
String query = "Select ID, First_Name, Last_Name, Date_Of_Birth as DOB, Place_Of_Birth as POB, Country from MyPlayers";
//Executing the query
ResultSet rs = stmt.executeQuery(query);
//retrieving the ResultSetMetaData object
ResultSetMetaData resultSetMetaData = rs.getMetaData();
//Retrieving the column names
String columnName = resultSetMetaData.getColumnName(4);
System.out.println("Name of the column with index 4: "+ columnName);
}
}
Connection established......
Name of the column with index 4: Date_Of_Birth | [
{
"code": null,
"e": 1214,
"s": 1062,
"text": "The getColumnName() method of the ResultSetMetaData (interface) retrieves and returns the name of the specified column in the current ResultSet object."
},
{
"code": null,
"e": 1361,
"s": 1214,
"text": "This method accepts an integer value representing the index of a column and, returns a String value representing the name of the specified column."
},
{
"code": null,
"e": 1412,
"s": 1361,
"text": "To get the ResultSetMetaData object, you need to −"
},
{
"code": null,
"e": 1627,
"s": 1412,
"text": "Register the Driver: Select the required database register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class."
},
{
"code": null,
"e": 1686,
"s": 1627,
"text": "DriverManager.registerDriver(new com.mysql.jdbc.Driver());"
},
{
"code": null,
"e": 1904,
"s": 1686,
"text": "Get connection: Create a connection object by passing the URL of the database, username and password of a user in the database (in string format) as parameters to the getConnection() method of the DriverManager class."
},
{
"code": null,
"e": 1985,
"s": 1904,
"text": "Connection mysqlCon = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");"
},
{
"code": null,
"e": 2100,
"s": 1985,
"text": "Create a Statement object: Create a Statement object using the createStatement method of the connection interface."
},
{
"code": null,
"e": 2140,
"s": 2100,
"text": "Statement stmt = con.createStatement();"
},
{
"code": null,
"e": 2296,
"s": 2140,
"text": "Execute the Query: Execute the SELECT query using the executeQuery() methods of the Statement interface and Retrieve the results into the ResultSet object."
},
{
"code": null,
"e": 2379,
"s": 2296,
"text": "String query = \"Select * from MyPlayers\";\nResultSet rs = stmt.executeQuery(query);"
},
{
"code": null,
"e": 2514,
"s": 2379,
"text": "Get the ResultSetMetaData object: Retrieve the ResultSetMetsdata object of the current ResultSet by invoking the getMetaData() method."
},
{
"code": null,
"e": 2570,
"s": 2514,
"text": "ResultSetMetaData resultSetMetaData = rs.getMetaData();"
},
{
"code": null,
"e": 2689,
"s": 2570,
"text": "Finally, using the getColumnName() method of the ResultSetMetaData interface get the name of the specified column as −"
},
{
"code": null,
"e": 2741,
"s": 2689,
"text": "int columnType = resultSetMetaData.getColumnName();"
},
{
"code": null,
"e": 2841,
"s": 2741,
"text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −"
},
{
"code": null,
"e": 3034,
"s": 2841,
"text": "CREATE TABLE MyPlayers(\n ID INT,\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255),\n PRIMARY KEY (ID)\n);"
},
{
"code": null,
"e": 3109,
"s": 3034,
"text": "Now, we will insert 7 records in MyPlayers table using INSERT statements −"
},
{
"code": null,
"e": 3771,
"s": 3109,
"text": "insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\ninsert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\ninsert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');"
},
{
"code": null,
"e": 3945,
"s": 3771,
"text": "Following JDBC program establishes connection with MySQL database, retrieves and displays the name of the 4th column in the MyPlayers table using the getColumnName() method."
},
{
"code": null,
"e": 5164,
"s": 3945,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.ResultSetMetaData;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class ResultSetMetadata_getColumnName {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to retrieve records\n String query = \"Select ID, First_Name, Last_Name, Date_Of_Birth as DOB, Place_Of_Birth as POB, Country from MyPlayers\";\n //Executing the query\n ResultSet rs = stmt.executeQuery(query);\n //retrieving the ResultSetMetaData object\n ResultSetMetaData resultSetMetaData = rs.getMetaData();\n //Retrieving the column names\n String columnName = resultSetMetaData.getColumnName(4);\n System.out.println(\"Name of the column with index 4: \"+ columnName);\n }\n}"
},
{
"code": null,
"e": 5240,
"s": 5164,
"text": "Connection established......\nName of the column with index 4: Date_Of_Birth"
}
]
|
React.js Error Boundaries - GeeksforGeeks | 20 Nov, 2021
Error Boundaries: Error Boundaries basically provide some sort of boundaries or checks on errors, They are React components that are used to handle JavaScript errors in their child component tree.
React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI. It catches errors during rendering, in lifecycle methods, etc.
Reason to Use: Suppose there is an error in JavaScript inside component then it used to corrupt React’s internal state and cause it to emit cryptic errors. Error boundaries help in removing these errors and display a Fallback UI instead(Which means a display of an error that something broke in the code).
Working Principle: Error Boundary works almost similar to catch in JavaScript. Suppose an error is encountered then what happens is as soon as there is a broken JavaScript part in Rendering or Lifecycle Methods, It tries to find the nearest Error Boundaries Tag.
Creating React Application:
Step 1: Create a React application using the following command:
create-react-app error-boundary
Step 2: After creating the error-boundary directory move to it.
cd error-boundary
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Filename: App.js
Javascript
import React from "react"; class ErrorBoundary extends React.Component { // Constructor for initializing Variables etc in a state // Just similar to initial line of useState if you are familiar // with Functional Components constructor(props) { super(props); this.state = { error: null, errorInfo: null }; } // This method is called if any error is encountered componentDidCatch(error, errorInfo) { // Catch errors in any components below and // re-render with error message this.setState({ error: error, errorInfo: errorInfo }) // You can also log error messages to an error // reporting service here } // This will render this component wherever called render() { if (this.state.errorInfo) { // Error path return ( <div> <h2>An Error Has Occured</h2> <details> {this.state.error && this.state.error.toString()} <br /> {this.state.errorInfo.componentStack} </details> </div> ); } // Normally, just render children, i.e. in // case no error is Found return this.props.children; }} // This is a component for Counter,Named Counterclass Counter extends React.Component { constructor(props) { super(props); this.state = { counter: 0 }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(({ counter }) => ({ counter: counter + 1 })); } render() { if (this.state.counter === 3) { // Simulate a JS error throw new Error('Crashed!!!!'); } return <h1 onClick={this.handleClick}>{this.state.counter}</h1>; }} function App() { return ( <div style={{ marginLeft: '30px', marginTop: '50px' }}> <div style={{ textAlign: "center" }}> <h1> <strong>To see the working of Error boundaries click on the Counters to increase the value </strong> </h1> <p> Program is made such a way that as soon as the counter reaches the value of 3, Error boundaries will throw an error. </p> </div> <hr style={{ width: "500px" }} /> <ErrorBoundary> <p> These two counters are inside the same error boundary. If one crashes, then the effect will be done on both as the error boundary will replace both of them. </p> <Counter /> <Counter /> </ErrorBoundary> <hr style={{ width: "500px" }} /> <p> These two counters are each inside of their own error boundary. So if one crashes, the other is not affected. </p> <ErrorBoundary><Counter /></ErrorBoundary> <ErrorBoundary><Counter /></ErrorBoundary> </div> );} export default App;
Filename: index.js
Javascript
import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root')); reportWebVitals();
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.
Explanation: The above code is written in such a way that if the counter reaches the value of 3 then Error Boundaries will throw an error.
As shown in the above code that two counters are included in the same Error Boundary Component through which if any one of them causes any sort of error by reaching the value of 3, then instead of rendering any of them a detailed message will be provided on the screen.
On the other end below both counters are included in the individual error Boundaries component through which what happens is only that counter which has caused the error is not rendered, while others are rendered normally.
Error boundaries do not catch errors for the following events:
Event Handlers
Asynchronous code(Example request Animation Frame etc)
Server-Side Rendering
Errors are thrown in the error boundary itself (rather than its children)
Try/Catch: One question which might be tickling in your mind is since Error Boundaries works like Catch, Why not just go with try/catch and why should you learn this new Concept. Well, the answer is try/catch is used with imperative code but As we know that React is declarative in nature, and Error Boundaries help in preserving the declarative nature of React.
Uncaught changes: Since it does not catch errors in some particular cases, So what about those errors that left unchecked or Uncaught. As of React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree. This means after migrating to React 16 and using Error Boundaries, you will be able to provide a better user experience as now users will be able to see the reason before an unexpected crash, instead of just guessing.
Component Stack Trace: React 16 prints all errors that occurred, it provides component Stack Trace. This helps the user in identifying the point where an error has occurred.
Event Listeners: Error Boundaries does not check errors in event handlers, So should this be counted as some sort of Limitation of Error Boundaries, Well the answer is no, the Reason being Event Listeners does not happen during rendering, So if any error is caused due to them React will simply display it on the screen.
Error Boundaries:
It can only be used with Class Components.
It does not catch errors for Event Handlers, Asynchronous code(Example request Animation Frame), Server Side Rendering, and Errors are thrown in the error boundary itself (rather than its children).
It is available only in react 16 or after.
Reference: https://reactjs.org/docs/error-boundaries.html
sweetyty
Picked
ReactJS-Basics
ReactJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
How to create a multi-page website using React.js ?
How to build a basic CRUD app with Node.js and ReactJS ?
How to Use Bootstrap with React?
How to check the version of ReactJS ?
Destructuring of Props in ReactJS | [
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n20 Nov, 2021"
},
{
"code": null,
"e": 26268,
"s": 26071,
"text": "Error Boundaries: Error Boundaries basically provide some sort of boundaries or checks on errors, They are React components that are used to handle JavaScript errors in their child component tree."
},
{
"code": null,
"e": 26462,
"s": 26268,
"text": "React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI. It catches errors during rendering, in lifecycle methods, etc."
},
{
"code": null,
"e": 26768,
"s": 26462,
"text": "Reason to Use: Suppose there is an error in JavaScript inside component then it used to corrupt React’s internal state and cause it to emit cryptic errors. Error boundaries help in removing these errors and display a Fallback UI instead(Which means a display of an error that something broke in the code)."
},
{
"code": null,
"e": 27031,
"s": 26768,
"text": "Working Principle: Error Boundary works almost similar to catch in JavaScript. Suppose an error is encountered then what happens is as soon as there is a broken JavaScript part in Rendering or Lifecycle Methods, It tries to find the nearest Error Boundaries Tag."
},
{
"code": null,
"e": 27060,
"s": 27031,
"text": "Creating React Application: "
},
{
"code": null,
"e": 27124,
"s": 27060,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27156,
"s": 27124,
"text": "create-react-app error-boundary"
},
{
"code": null,
"e": 27220,
"s": 27156,
"text": "Step 2: After creating the error-boundary directory move to it."
},
{
"code": null,
"e": 27238,
"s": 27220,
"text": "cd error-boundary"
},
{
"code": null,
"e": 27290,
"s": 27238,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 27421,
"s": 27290,
"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": 27438,
"s": 27421,
"text": "Filename: App.js"
},
{
"code": null,
"e": 27449,
"s": 27438,
"text": "Javascript"
},
{
"code": "import React from \"react\"; class ErrorBoundary extends React.Component { // Constructor for initializing Variables etc in a state // Just similar to initial line of useState if you are familiar // with Functional Components constructor(props) { super(props); this.state = { error: null, errorInfo: null }; } // This method is called if any error is encountered componentDidCatch(error, errorInfo) { // Catch errors in any components below and // re-render with error message this.setState({ error: error, errorInfo: errorInfo }) // You can also log error messages to an error // reporting service here } // This will render this component wherever called render() { if (this.state.errorInfo) { // Error path return ( <div> <h2>An Error Has Occured</h2> <details> {this.state.error && this.state.error.toString()} <br /> {this.state.errorInfo.componentStack} </details> </div> ); } // Normally, just render children, i.e. in // case no error is Found return this.props.children; }} // This is a component for Counter,Named Counterclass Counter extends React.Component { constructor(props) { super(props); this.state = { counter: 0 }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(({ counter }) => ({ counter: counter + 1 })); } render() { if (this.state.counter === 3) { // Simulate a JS error throw new Error('Crashed!!!!'); } return <h1 onClick={this.handleClick}>{this.state.counter}</h1>; }} function App() { return ( <div style={{ marginLeft: '30px', marginTop: '50px' }}> <div style={{ textAlign: \"center\" }}> <h1> <strong>To see the working of Error boundaries click on the Counters to increase the value </strong> </h1> <p> Program is made such a way that as soon as the counter reaches the value of 3, Error boundaries will throw an error. </p> </div> <hr style={{ width: \"500px\" }} /> <ErrorBoundary> <p> These two counters are inside the same error boundary. If one crashes, then the effect will be done on both as the error boundary will replace both of them. </p> <Counter /> <Counter /> </ErrorBoundary> <hr style={{ width: \"500px\" }} /> <p> These two counters are each inside of their own error boundary. So if one crashes, the other is not affected. </p> <ErrorBoundary><Counter /></ErrorBoundary> <ErrorBoundary><Counter /></ErrorBoundary> </div> );} export default App;",
"e": 30225,
"s": 27449,
"text": null
},
{
"code": null,
"e": 30245,
"s": 30225,
"text": " Filename: index.js"
},
{
"code": null,
"e": 30256,
"s": 30245,
"text": "Javascript"
},
{
"code": "import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root')); reportWebVitals();",
"e": 30533,
"s": 30256,
"text": null
},
{
"code": null,
"e": 30647,
"s": 30533,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project. "
},
{
"code": null,
"e": 30657,
"s": 30647,
"text": "npm start"
},
{
"code": null,
"e": 30757,
"s": 30657,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output. "
},
{
"code": null,
"e": 30896,
"s": 30757,
"text": "Explanation: The above code is written in such a way that if the counter reaches the value of 3 then Error Boundaries will throw an error."
},
{
"code": null,
"e": 31166,
"s": 30896,
"text": "As shown in the above code that two counters are included in the same Error Boundary Component through which if any one of them causes any sort of error by reaching the value of 3, then instead of rendering any of them a detailed message will be provided on the screen."
},
{
"code": null,
"e": 31389,
"s": 31166,
"text": "On the other end below both counters are included in the individual error Boundaries component through which what happens is only that counter which has caused the error is not rendered, while others are rendered normally."
},
{
"code": null,
"e": 31452,
"s": 31389,
"text": "Error boundaries do not catch errors for the following events:"
},
{
"code": null,
"e": 31467,
"s": 31452,
"text": "Event Handlers"
},
{
"code": null,
"e": 31522,
"s": 31467,
"text": "Asynchronous code(Example request Animation Frame etc)"
},
{
"code": null,
"e": 31544,
"s": 31522,
"text": "Server-Side Rendering"
},
{
"code": null,
"e": 31618,
"s": 31544,
"text": "Errors are thrown in the error boundary itself (rather than its children)"
},
{
"code": null,
"e": 31981,
"s": 31618,
"text": "Try/Catch: One question which might be tickling in your mind is since Error Boundaries works like Catch, Why not just go with try/catch and why should you learn this new Concept. Well, the answer is try/catch is used with imperative code but As we know that React is declarative in nature, and Error Boundaries help in preserving the declarative nature of React."
},
{
"code": null,
"e": 32461,
"s": 31981,
"text": "Uncaught changes: Since it does not catch errors in some particular cases, So what about those errors that left unchecked or Uncaught. As of React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree. This means after migrating to React 16 and using Error Boundaries, you will be able to provide a better user experience as now users will be able to see the reason before an unexpected crash, instead of just guessing."
},
{
"code": null,
"e": 32635,
"s": 32461,
"text": "Component Stack Trace: React 16 prints all errors that occurred, it provides component Stack Trace. This helps the user in identifying the point where an error has occurred."
},
{
"code": null,
"e": 32957,
"s": 32635,
"text": "Event Listeners: Error Boundaries does not check errors in event handlers, So should this be counted as some sort of Limitation of Error Boundaries, Well the answer is no, the Reason being Event Listeners does not happen during rendering, So if any error is caused due to them React will simply display it on the screen. "
},
{
"code": null,
"e": 32975,
"s": 32957,
"text": "Error Boundaries:"
},
{
"code": null,
"e": 33018,
"s": 32975,
"text": "It can only be used with Class Components."
},
{
"code": null,
"e": 33217,
"s": 33018,
"text": "It does not catch errors for Event Handlers, Asynchronous code(Example request Animation Frame), Server Side Rendering, and Errors are thrown in the error boundary itself (rather than its children)."
},
{
"code": null,
"e": 33260,
"s": 33217,
"text": "It is available only in react 16 or after."
},
{
"code": null,
"e": 33318,
"s": 33260,
"text": "Reference: https://reactjs.org/docs/error-boundaries.html"
},
{
"code": null,
"e": 33329,
"s": 33320,
"text": "sweetyty"
},
{
"code": null,
"e": 33336,
"s": 33329,
"text": "Picked"
},
{
"code": null,
"e": 33351,
"s": 33336,
"text": "ReactJS-Basics"
},
{
"code": null,
"e": 33359,
"s": 33351,
"text": "ReactJS"
},
{
"code": null,
"e": 33457,
"s": 33359,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33484,
"s": 33457,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 33526,
"s": 33484,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 33564,
"s": 33526,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 33599,
"s": 33564,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 33657,
"s": 33599,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 33709,
"s": 33657,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 33766,
"s": 33709,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 33799,
"s": 33766,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 33837,
"s": 33799,
"text": "How to check the version of ReactJS ?"
}
]
|
Area of triangle formed by the axes of co-ordinates and a given straight line - GeeksforGeeks | 18 Mar, 2021
Given a straight line with equation coefficients as a, b & c(ax + by + c = 0), the task is to find the area of the triangle formed by the axes of co-ordinates and this straight line.Examples:
Input: a = -2, b = 4, c = 3
Output: 0.5625
Input: a = 4, b = 3, c = 12
Output: 6
Approach:
Let PQ be the straight line having AB, the line segment between the axes. The equation is, ax + by + c = 0 so, in intercept form it can be expressed as, x/(-c/a) + y/(-c/b) = 1 So, the x-intercept = -c/a the y-intercept = -c/b So, it is very clear now the base of the triangle AOB will be -c/a and the base of the triangle AOB will be -c/b So, area of the triangle
Let PQ be the straight line having AB, the line segment between the axes. The equation is, ax + by + c = 0
so, in intercept form it can be expressed as, x/(-c/a) + y/(-c/b) = 1
So, the x-intercept = -c/a the y-intercept = -c/b
So, it is very clear now the base of the triangle AOB will be -c/a and the base of the triangle AOB will be -c/b
So, area of the triangle
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program area of triangle// formed by the axes of co-ordinates// and a given straight line #include <bits/stdc++.h>using namespace std; // Function to find areadouble area(double a, double b, double c){ double d = fabs((c * c) / (2 * a * b)); return d;} // Driver codeint main(){ double a = -2, b = 4, c = 3; cout << area(a, b, c); return 0;}
// Java program area of triangle// formed by the axes of co-ordinates// and a given straight line import java.io.*; class GFG{ // Function to find areastatic double area(double a, double b, double c){ double d = Math.abs((c * c) / (2 * a * b)); return d;} // Driver codepublic static void main (String[] args){ double a = -2, b = 4, c = 3; System.out.println(area(a, b, c));}} // This code is contributed by ajit.
# Python3 program area of triangle# formed by the axes of co-ordinates# and a given straight line # Function to find areadef area(a, b, c): d = abs((c * c) / (2 * a * b)) return d # Driver codea = -2b = 4c = 3print(area(a, b, c)) # This code is contributed# by mohit kumar
// C# program area of triangle// formed by the axes of co-ordinates// and a given straight lineusing System; class GFG{ // Function to find areastatic double area(double a, double b, double c){ double d = Math.Abs((c * c) / (2 * a * b)); return d;} // Driver codestatic public void Main (){ double a = -2, b = 4, c = 3; Console.WriteLine (area(a, b, c));}} // This code is contributed by akt_mit.
<?php// PHP program area of triangle// formed by the axes of co-ordinates// and a given straight line // Function to find areafunction area($a, $b, $c){ $d = abs(($c * $c) / (2 * $a * $b)); return $d;} // Driver code$a = -2;$b = 4;$c = 3; echo area($a, $b, $c); // This code is contributed by Ryuga?>
<script> // javascript program area of triangle// formed by the axes of co-ordinates// and a given straight line // Function to find areafunction area(a , b , c){ var d = Math.abs((c * c) / (2 * a * b)); return d;} // Driver code var a = -2, b = 4, c = 3;document.write(area(a, b, c)); // This code is contributed by Amit Katiyar </script>
0.5625
ankthon
mohit kumar 29
jit_t
amit143katiyar
area-volume-programs
school-programming
triangle
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Singular Value Decomposition (SVD)
Check if a number is Palindrome
Segment Tree | Set 1 (Sum of given range)
How to check if a given point lies inside or outside a polygon?
Program to multiply two matrices
Count ways to reach the n'th stair
Merge two sorted arrays with O(1) extra space | [
{
"code": null,
"e": 26047,
"s": 26019,
"text": "\n18 Mar, 2021"
},
{
"code": null,
"e": 26241,
"s": 26047,
"text": "Given a straight line with equation coefficients as a, b & c(ax + by + c = 0), the task is to find the area of the triangle formed by the axes of co-ordinates and this straight line.Examples: "
},
{
"code": null,
"e": 26323,
"s": 26241,
"text": "Input: a = -2, b = 4, c = 3\nOutput: 0.5625\n\nInput: a = 4, b = 3, c = 12\nOutput: 6"
},
{
"code": null,
"e": 26337,
"s": 26325,
"text": "Approach: "
},
{
"code": null,
"e": 26708,
"s": 26337,
"text": "Let PQ be the straight line having AB, the line segment between the axes. The equation is, ax + by + c = 0 so, in intercept form it can be expressed as, x/(-c/a) + y/(-c/b) = 1 So, the x-intercept = -c/a the y-intercept = -c/b So, it is very clear now the base of the triangle AOB will be -c/a and the base of the triangle AOB will be -c/b So, area of the triangle "
},
{
"code": null,
"e": 26817,
"s": 26708,
"text": "Let PQ be the straight line having AB, the line segment between the axes. The equation is, ax + by + c = 0 "
},
{
"code": null,
"e": 26889,
"s": 26817,
"text": "so, in intercept form it can be expressed as, x/(-c/a) + y/(-c/b) = 1 "
},
{
"code": null,
"e": 26941,
"s": 26889,
"text": "So, the x-intercept = -c/a the y-intercept = -c/b "
},
{
"code": null,
"e": 27056,
"s": 26941,
"text": "So, it is very clear now the base of the triangle AOB will be -c/a and the base of the triangle AOB will be -c/b "
},
{
"code": null,
"e": 27083,
"s": 27056,
"text": "So, area of the triangle "
},
{
"code": null,
"e": 27136,
"s": 27083,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27140,
"s": 27136,
"text": "C++"
},
{
"code": null,
"e": 27145,
"s": 27140,
"text": "Java"
},
{
"code": null,
"e": 27153,
"s": 27145,
"text": "Python3"
},
{
"code": null,
"e": 27156,
"s": 27153,
"text": "C#"
},
{
"code": null,
"e": 27160,
"s": 27156,
"text": "PHP"
},
{
"code": null,
"e": 27171,
"s": 27160,
"text": "Javascript"
},
{
"code": "// C++ program area of triangle// formed by the axes of co-ordinates// and a given straight line #include <bits/stdc++.h>using namespace std; // Function to find areadouble area(double a, double b, double c){ double d = fabs((c * c) / (2 * a * b)); return d;} // Driver codeint main(){ double a = -2, b = 4, c = 3; cout << area(a, b, c); return 0;}",
"e": 27535,
"s": 27171,
"text": null
},
{
"code": "// Java program area of triangle// formed by the axes of co-ordinates// and a given straight line import java.io.*; class GFG{ // Function to find areastatic double area(double a, double b, double c){ double d = Math.abs((c * c) / (2 * a * b)); return d;} // Driver codepublic static void main (String[] args){ double a = -2, b = 4, c = 3; System.out.println(area(a, b, c));}} // This code is contributed by ajit.",
"e": 27966,
"s": 27535,
"text": null
},
{
"code": "# Python3 program area of triangle# formed by the axes of co-ordinates# and a given straight line # Function to find areadef area(a, b, c): d = abs((c * c) / (2 * a * b)) return d # Driver codea = -2b = 4c = 3print(area(a, b, c)) # This code is contributed# by mohit kumar",
"e": 28246,
"s": 27966,
"text": null
},
{
"code": "// C# program area of triangle// formed by the axes of co-ordinates// and a given straight lineusing System; class GFG{ // Function to find areastatic double area(double a, double b, double c){ double d = Math.Abs((c * c) / (2 * a * b)); return d;} // Driver codestatic public void Main (){ double a = -2, b = 4, c = 3; Console.WriteLine (area(a, b, c));}} // This code is contributed by akt_mit.",
"e": 28664,
"s": 28246,
"text": null
},
{
"code": "<?php// PHP program area of triangle// formed by the axes of co-ordinates// and a given straight line // Function to find areafunction area($a, $b, $c){ $d = abs(($c * $c) / (2 * $a * $b)); return $d;} // Driver code$a = -2;$b = 4;$c = 3; echo area($a, $b, $c); // This code is contributed by Ryuga?>",
"e": 28971,
"s": 28664,
"text": null
},
{
"code": "<script> // javascript program area of triangle// formed by the axes of co-ordinates// and a given straight line // Function to find areafunction area(a , b , c){ var d = Math.abs((c * c) / (2 * a * b)); return d;} // Driver code var a = -2, b = 4, c = 3;document.write(area(a, b, c)); // This code is contributed by Amit Katiyar </script>",
"e": 29322,
"s": 28971,
"text": null
},
{
"code": null,
"e": 29329,
"s": 29322,
"text": "0.5625"
},
{
"code": null,
"e": 29339,
"s": 29331,
"text": "ankthon"
},
{
"code": null,
"e": 29354,
"s": 29339,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 29360,
"s": 29354,
"text": "jit_t"
},
{
"code": null,
"e": 29375,
"s": 29360,
"text": "amit143katiyar"
},
{
"code": null,
"e": 29396,
"s": 29375,
"text": "area-volume-programs"
},
{
"code": null,
"e": 29415,
"s": 29396,
"text": "school-programming"
},
{
"code": null,
"e": 29424,
"s": 29415,
"text": "triangle"
},
{
"code": null,
"e": 29437,
"s": 29424,
"text": "Mathematical"
},
{
"code": null,
"e": 29450,
"s": 29437,
"text": "Mathematical"
},
{
"code": null,
"e": 29548,
"s": 29450,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29592,
"s": 29548,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 29623,
"s": 29592,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 29648,
"s": 29623,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 29683,
"s": 29648,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 29715,
"s": 29683,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 29757,
"s": 29715,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 29821,
"s": 29757,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 29854,
"s": 29821,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 29889,
"s": 29854,
"text": "Count ways to reach the n'th stair"
}
]
|
Interfacing a speaker with Arduino | In this tutorial, we will interface a simple piezo-buzzer with Arduino to create beeping sounds. Such an arrangement can be used in applications like burglar alarms, or water level indicators or such similar projects.
As you can see, the circuit diagram is quite straightforward. You need to connect the buzzer’s GND to Arduino’s GND, and the other wire to one GPIO of the Arduino (we have chosen pin 7). You can optionally add a small resistor (~100 Ohm), between the GPIO and the buzzer.
The entire code is given below −
#define buzzerPin 7 // buzzer to arduino uno pin 7
void setup(){
pinMode(buzzerPin, OUTPUT); // Set buzzer - pin 9 as an output
}
void loop(){
tone(buzzerPin, 2000); // Send 2000Hz sound signal...
delay(500); // ...for 0.5 sec
noTone(buzzerPin); // Stop sound...
delay(500); // ...for 0.5 sec
}
As you can see, the code is pretty straightforward. We first define the buzzerPin
#define buzzerPin 7 //buzzer to arduino uno pin 7
In the Setup, we just initialize the pin as OUTPUT.
void setup(){
pinMode(buzzerPin, OUTPUT); // Set buzzer - pin 9 as an output
}
In the loop, we use the tone() function to create a 2000 Hz tone on the buzzerPin for half a second, after which we stop the tone using the noTone() function, for another half second. This goes on in the loop and creates the beeping effect. You can read more about the tone() function here.
void loop(){
tone(buzzerPin, 2000); // Send 2000Hz sound signal...
delay(500); // ...for 0.5 sec
noTone(buzzerPin); // Stop sound...
delay(500); // ...for 0.5 sec
} | [
{
"code": null,
"e": 1280,
"s": 1062,
"text": "In this tutorial, we will interface a simple piezo-buzzer with Arduino to create beeping sounds. Such an arrangement can be used in applications like burglar alarms, or water level indicators or such similar projects."
},
{
"code": null,
"e": 1552,
"s": 1280,
"text": "As you can see, the circuit diagram is quite straightforward. You need to connect the buzzer’s GND to Arduino’s GND, and the other wire to one GPIO of the Arduino (we have chosen pin 7). You can optionally add a small resistor (~100 Ohm), between the GPIO and the buzzer."
},
{
"code": null,
"e": 1585,
"s": 1552,
"text": "The entire code is given below −"
},
{
"code": null,
"e": 1957,
"s": 1585,
"text": "#define buzzerPin 7 // buzzer to arduino uno pin 7\n\nvoid setup(){\n pinMode(buzzerPin, OUTPUT); // Set buzzer - pin 9 as an output\n}\n\nvoid loop(){\n tone(buzzerPin, 2000); // Send 2000Hz sound signal...\n delay(500); // ...for 0.5 sec\n noTone(buzzerPin); // Stop sound...\n delay(500); // ...for 0.5 sec\n}"
},
{
"code": null,
"e": 2039,
"s": 1957,
"text": "As you can see, the code is pretty straightforward. We first define the buzzerPin"
},
{
"code": null,
"e": 2089,
"s": 2039,
"text": "#define buzzerPin 7 //buzzer to arduino uno pin 7"
},
{
"code": null,
"e": 2141,
"s": 2089,
"text": "In the Setup, we just initialize the pin as OUTPUT."
},
{
"code": null,
"e": 2223,
"s": 2141,
"text": "void setup(){\n pinMode(buzzerPin, OUTPUT); // Set buzzer - pin 9 as an output\n}"
},
{
"code": null,
"e": 2514,
"s": 2223,
"text": "In the loop, we use the tone() function to create a 2000 Hz tone on the buzzerPin for half a second, after which we stop the tone using the noTone() function, for another half second. This goes on in the loop and creates the beeping effect. You can read more about the tone() function here."
},
{
"code": null,
"e": 2749,
"s": 2514,
"text": "void loop(){\n tone(buzzerPin, 2000); // Send 2000Hz sound signal...\n delay(500); // ...for 0.5 sec\n noTone(buzzerPin); // Stop sound...\n delay(500); // ...for 0.5 sec\n}"
}
]
|
Minimum number of distinct elements after removing m items - GeeksforGeeks | 28 Mar, 2022
Given an array of items, an i-th index element denotes the item id’s, and given a number m, the task is to remove m elements such that there should be minimum distinct id’s left. Print the number of distinct id’s.Examples:
Input : arr[] = { 2, 2, 1, 3, 3, 3}
m = 3
Output : 1
Remove 1 and both 2's.So, only 3 will be
left that's why distinct id is 1.
Input : arr[] = { 2, 4, 1, 5, 3, 5, 1, 3}
m = 2
Output : 3
Remove 2 and 4 completely. So, remaining ids
are 1, 3 and 5 i.e. 3
Asked in: Morgan Stanley
1- Count the occurrence of elements and store them in the hash. 2- Sort the hash. 3- Start removing elements from the hash whose frequency count is less than m. 4- Return the number of values left in the hash.
C++
Java
Python3
C#
Javascript
// C++ program for above implementation#include <bits/stdc++.h>using namespace std; // Function to find distinct id'sint distinctIds(int arr[], int n, int mi){ unordered_map<int, int> m; vector<pair<int, int> > v; int count = 0; // Store the occurrence of ids for (int i = 0; i < n; i++) m[arr[i]]++; // Store into the vector second as first and vice-versa for (auto it = m.begin(); it != m.end(); it++) v.push_back(make_pair(it->second, it->first)); // Sort the vector sort(v.begin(), v.end()); int size = v.size(); // Start removing elements from the beginning for (int i = 0; i < size; i++) { // Remove if current value is less than // or equal to mi if (v[i].first <= mi) { mi -= v[i].first; count++; } // Return the remaining size else return size - count; } return size - count;} // Driver codeint main(){ int arr[] = { 2, 3, 1, 2, 3, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int m = 3; cout << distinctIds(arr, n, m); return 0;}
import java.util.*; class Solution { static int distinctIds(int arr[], int n, int m) { // Creating HashMap to store frequency count HashMap<Integer, Integer> h = new HashMap<>(); for (int i = 0; i < n; i++) { if (h.containsKey(arr[i])) { h.put(arr[i], h.get(arr[i]) + 1); } else { h.put(arr[i], 1); } } // Creating a list to sort HashMap according to // values List<Map.Entry<Integer, Integer> > l = new LinkedList<Map.Entry<Integer, Integer> >( h.entrySet()); // sorting using Comparator Collections.sort( l, new Comparator<Map.Entry<Integer, Integer> >() { public int compare( Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return o1.getValue() - o2.getValue(); } }); // Creating new map after sorting and also // maintaining insertion order LinkedHashMap<Integer, Integer> lh = new LinkedHashMap<>(); for (Map.Entry<Integer, Integer> e : l) { lh.put(e.getKey(), e.getValue()); } for (Integer i : lh.keySet()) { // removing element from whose frequency count is // less than m ,Sorted manner to get minimum // distinct ids if (h.get(i) <= m) { m -= h.get(i); h.remove(i); } } return h.size(); } public static void main(String[] args) { // TODO Auto-generated method stub int arr[] = { 2, 4, 1, 5, 3, 5, 1, 3 }; int m = 2; System.out.println(distinctIds(arr, arr.length, m)); }}
# Python program for above implementation # Function to find distinct id'sdef distinctIds(arr, n, mi): m = {} v = [] count = 0 # Store the occurrence of ids for i in range(n): if arr[i] in m: m[arr[i]] += 1 else: m[arr[i]] = 1 # Store into the list value as key and vice-versa for i in m: v.append([m[i],i]) v.sort() size = len(v) # Start removing elements from the beginning for i in range(size): # Remove if current value is less than # or equal to mi if (v[i][0] <= mi): mi -= v[i][0] count += 1 else: # Return the remaining size return size - count return size - count # Driver codearr = [ 2, 3, 1, 2, 3, 3 ]n = len(arr) m = 3 # To display the resultprint(distinctIds(arr, n, m)) # This code is contributed by rohitsingh07052
// C# program for Minimum number of// distinct elements after removing m itemsusing System;using System.Collections.Generic; class GFG{ // Function to find distinct id's static int distinctIds(int[] arr, int n, int mi) { Dictionary<int, int> m = new Dictionary<int, int>(); int count = 0; int size = 0; // Store the occurrence of ids for (int i = 0; i < n; i++) { // If the key is not add it to map if (m.ContainsKey(arr[i]) == false) { m[arr[i]] = 1; size++; } // If it is present then increase the value by 1 else { m[arr[i]]++; } } // Start removing elements from the beginning foreach(KeyValuePair<int, int> mp in m) { // Remove if current value is less than // or equal to mi if (mp.Key <= mi) { mi -= mp.Key; count++; } } return size - count; } // Driver code static void Main() { // TODO Auto-generated method stub int[] arr = {2, 3, 1, 2, 3, 3}; int m = 3; Console.WriteLine(distinctIds(arr, arr.Length, m)); }} // This code is contributed by divyeshrabadiya07
<script> // Javascript program for above implementation // Function to find distinct id'sfunction distinctIds(arr, n, mi){ var m = new Map(); var v = []; var count = 0; // Store the occurrence of ids for (var i = 0; i < n; i++) { if(m.has(arr[i])) m.set(arr[i], m.get(arr[i])+1) else m.set(arr[i], 1) } // Store into the vector second as first and vice-versa m.forEach((value, key) => { v.push([value, key]); }); // Sort the vector v.sort() var size = v.length; // Start removing elements from the beginning for (var i = 0; i < size; i++) { // Remove if current value is less than // or equal to mi if (v[i][0] <= mi) { mi -= v[i][0]; count++; } // Return the remaining size else return size - count; } return size - count;} // Driver codevar arr = [2, 3, 1, 2, 3, 3 ];var n = arr.length;var m = 3;document.write( distinctIds(arr, n, m)); // This code is contributed by immportantly.</script>
Output:
1
Time Complexity: O(n log n)This article is contributed by Sahil Chhabra. 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.
rohitsingh07052
divyeshrabadiya07
importantly
gautamsingh12
surinderdawra388
simmytarika5
cpp-unordered_map
Morgan Stanley
Hash
Sorting
Morgan Stanley
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hashing | Set 2 (Separate Chaining)
Counting frequencies of array elements
Most frequent element in an array
Double Hashing
Sorting a Map by value in C++ STL | [
{
"code": null,
"e": 26717,
"s": 26689,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 26942,
"s": 26717,
"text": "Given an array of items, an i-th index element denotes the item id’s, and given a number m, the task is to remove m elements such that there should be minimum distinct id’s left. Print the number of distinct id’s.Examples: "
},
{
"code": null,
"e": 27225,
"s": 26942,
"text": "Input : arr[] = { 2, 2, 1, 3, 3, 3} \n m = 3\nOutput : 1\nRemove 1 and both 2's.So, only 3 will be \nleft that's why distinct id is 1.\n\nInput : arr[] = { 2, 4, 1, 5, 3, 5, 1, 3} \n m = 2\nOutput : 3\nRemove 2 and 4 completely. So, remaining ids \nare 1, 3 and 5 i.e. 3"
},
{
"code": null,
"e": 27251,
"s": 27225,
"text": "Asked in: Morgan Stanley "
},
{
"code": null,
"e": 27462,
"s": 27251,
"text": "1- Count the occurrence of elements and store them in the hash. 2- Sort the hash. 3- Start removing elements from the hash whose frequency count is less than m. 4- Return the number of values left in the hash. "
},
{
"code": null,
"e": 27466,
"s": 27462,
"text": "C++"
},
{
"code": null,
"e": 27471,
"s": 27466,
"text": "Java"
},
{
"code": null,
"e": 27479,
"s": 27471,
"text": "Python3"
},
{
"code": null,
"e": 27482,
"s": 27479,
"text": "C#"
},
{
"code": null,
"e": 27493,
"s": 27482,
"text": "Javascript"
},
{
"code": "// C++ program for above implementation#include <bits/stdc++.h>using namespace std; // Function to find distinct id'sint distinctIds(int arr[], int n, int mi){ unordered_map<int, int> m; vector<pair<int, int> > v; int count = 0; // Store the occurrence of ids for (int i = 0; i < n; i++) m[arr[i]]++; // Store into the vector second as first and vice-versa for (auto it = m.begin(); it != m.end(); it++) v.push_back(make_pair(it->second, it->first)); // Sort the vector sort(v.begin(), v.end()); int size = v.size(); // Start removing elements from the beginning for (int i = 0; i < size; i++) { // Remove if current value is less than // or equal to mi if (v[i].first <= mi) { mi -= v[i].first; count++; } // Return the remaining size else return size - count; } return size - count;} // Driver codeint main(){ int arr[] = { 2, 3, 1, 2, 3, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int m = 3; cout << distinctIds(arr, n, m); return 0;}",
"e": 28586,
"s": 27493,
"text": null
},
{
"code": "import java.util.*; class Solution { static int distinctIds(int arr[], int n, int m) { // Creating HashMap to store frequency count HashMap<Integer, Integer> h = new HashMap<>(); for (int i = 0; i < n; i++) { if (h.containsKey(arr[i])) { h.put(arr[i], h.get(arr[i]) + 1); } else { h.put(arr[i], 1); } } // Creating a list to sort HashMap according to // values List<Map.Entry<Integer, Integer> > l = new LinkedList<Map.Entry<Integer, Integer> >( h.entrySet()); // sorting using Comparator Collections.sort( l, new Comparator<Map.Entry<Integer, Integer> >() { public int compare( Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return o1.getValue() - o2.getValue(); } }); // Creating new map after sorting and also // maintaining insertion order LinkedHashMap<Integer, Integer> lh = new LinkedHashMap<>(); for (Map.Entry<Integer, Integer> e : l) { lh.put(e.getKey(), e.getValue()); } for (Integer i : lh.keySet()) { // removing element from whose frequency count is // less than m ,Sorted manner to get minimum // distinct ids if (h.get(i) <= m) { m -= h.get(i); h.remove(i); } } return h.size(); } public static void main(String[] args) { // TODO Auto-generated method stub int arr[] = { 2, 4, 1, 5, 3, 5, 1, 3 }; int m = 2; System.out.println(distinctIds(arr, arr.length, m)); }}",
"e": 30400,
"s": 28586,
"text": null
},
{
"code": "# Python program for above implementation # Function to find distinct id'sdef distinctIds(arr, n, mi): m = {} v = [] count = 0 # Store the occurrence of ids for i in range(n): if arr[i] in m: m[arr[i]] += 1 else: m[arr[i]] = 1 # Store into the list value as key and vice-versa for i in m: v.append([m[i],i]) v.sort() size = len(v) # Start removing elements from the beginning for i in range(size): # Remove if current value is less than # or equal to mi if (v[i][0] <= mi): mi -= v[i][0] count += 1 else: # Return the remaining size return size - count return size - count # Driver codearr = [ 2, 3, 1, 2, 3, 3 ]n = len(arr) m = 3 # To display the resultprint(distinctIds(arr, n, m)) # This code is contributed by rohitsingh07052",
"e": 31208,
"s": 30400,
"text": null
},
{
"code": "// C# program for Minimum number of// distinct elements after removing m itemsusing System;using System.Collections.Generic; class GFG{ // Function to find distinct id's static int distinctIds(int[] arr, int n, int mi) { Dictionary<int, int> m = new Dictionary<int, int>(); int count = 0; int size = 0; // Store the occurrence of ids for (int i = 0; i < n; i++) { // If the key is not add it to map if (m.ContainsKey(arr[i]) == false) { m[arr[i]] = 1; size++; } // If it is present then increase the value by 1 else { m[arr[i]]++; } } // Start removing elements from the beginning foreach(KeyValuePair<int, int> mp in m) { // Remove if current value is less than // or equal to mi if (mp.Key <= mi) { mi -= mp.Key; count++; } } return size - count; } // Driver code static void Main() { // TODO Auto-generated method stub int[] arr = {2, 3, 1, 2, 3, 3}; int m = 3; Console.WriteLine(distinctIds(arr, arr.Length, m)); }} // This code is contributed by divyeshrabadiya07",
"e": 32344,
"s": 31208,
"text": null
},
{
"code": "<script> // Javascript program for above implementation // Function to find distinct id'sfunction distinctIds(arr, n, mi){ var m = new Map(); var v = []; var count = 0; // Store the occurrence of ids for (var i = 0; i < n; i++) { if(m.has(arr[i])) m.set(arr[i], m.get(arr[i])+1) else m.set(arr[i], 1) } // Store into the vector second as first and vice-versa m.forEach((value, key) => { v.push([value, key]); }); // Sort the vector v.sort() var size = v.length; // Start removing elements from the beginning for (var i = 0; i < size; i++) { // Remove if current value is less than // or equal to mi if (v[i][0] <= mi) { mi -= v[i][0]; count++; } // Return the remaining size else return size - count; } return size - count;} // Driver codevar arr = [2, 3, 1, 2, 3, 3 ];var n = arr.length;var m = 3;document.write( distinctIds(arr, n, m)); // This code is contributed by immportantly.</script>",
"e": 33422,
"s": 32344,
"text": null
},
{
"code": null,
"e": 33432,
"s": 33422,
"text": "Output: "
},
{
"code": null,
"e": 33434,
"s": 33432,
"text": "1"
},
{
"code": null,
"e": 33883,
"s": 33434,
"text": "Time Complexity: O(n log n)This article is contributed by Sahil Chhabra. 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": 33899,
"s": 33883,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 33917,
"s": 33899,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 33929,
"s": 33917,
"text": "importantly"
},
{
"code": null,
"e": 33943,
"s": 33929,
"text": "gautamsingh12"
},
{
"code": null,
"e": 33960,
"s": 33943,
"text": "surinderdawra388"
},
{
"code": null,
"e": 33973,
"s": 33960,
"text": "simmytarika5"
},
{
"code": null,
"e": 33991,
"s": 33973,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 34006,
"s": 33991,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 34011,
"s": 34006,
"text": "Hash"
},
{
"code": null,
"e": 34019,
"s": 34011,
"text": "Sorting"
},
{
"code": null,
"e": 34034,
"s": 34019,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 34039,
"s": 34034,
"text": "Hash"
},
{
"code": null,
"e": 34047,
"s": 34039,
"text": "Sorting"
},
{
"code": null,
"e": 34145,
"s": 34047,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34181,
"s": 34145,
"text": "Hashing | Set 2 (Separate Chaining)"
},
{
"code": null,
"e": 34220,
"s": 34181,
"text": "Counting frequencies of array elements"
},
{
"code": null,
"e": 34254,
"s": 34220,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 34269,
"s": 34254,
"text": "Double Hashing"
}
]
|
Meaningful Metrics: Cumulative Gains and Lyft Charts | by RAFFI SAHAKYAN | Towards Data Science | Nowadays, all major companies rely heavily on their data science capabilities. Business data units are becoming larger and more sophisticated in terms of the complexity and diversity of analysis. However, the success of delivering data science solutions into business reality largely depends on the interpretability of findings. Even if the developed models provide outstanding accuracy scores, they may be neglected if they do not match the demands of various business stakeholders.
All beloved ROC AUC score is not informative enough for the business unit since it is abstract for non-technical managers. For the latter reason, I will present two meaningful metrics that every analyst should take into consideration when illustrating the results of their models: Cumulative Gains and Lift charts. I will demonstrate the example of a customer churn case study in the telecommunications industry.
Imagine a business scenario, when a telecom company decides to minimize the customer attrition rate by giving out one month of unlimited data usage to 20% of its customers. One of the managers suggests, for the promotion to be unbiased, to send the gift to every 5th customer ordered by their last names. The decision is almost there: unless someone proposes a better strategy for this marketing promotion.
Having the sample data of customers (actually can be accessed from my GitHub), we would decide to build a RandomForestClassifier model to predict the customer churn before this promotion begins. Then we will preprocess data, remove unnecessary columns, eliminate multicollinearity, and visualize. Final steps: model training and optimization with GridSearchCV. Yet, this article is not about the project; it is about the interpretability of your findings. The case question remains unanswered.
For this, I will present the cumulative gains and lift curves. The cumulative gains curve is an evaluation curve that assesses the performance of the model and compares the results with the random pick. It shows the percentage of targets reached when considering a certain percentage of the population with the highest probability to be target according to the model. In python, we are provided with scikitplot library, that will make the plot for us.
import scikitplot as skplt# Deriving Class probabilitiespredicted_probabilities = model_rf_best_params.predict_proba(x_test)# Creating the plotskplt.metrics.plot_cumulative_gain(y_test, predicted_probabilities)
First, we order all the observations according to the output of the model. On the left-hand side of the horizontal axis, we place the observations with the highest probability to be target according to the model and vice versa for the right-hand side. In our case, at the 20% point of the horizontal axis, the 80% observations with the highest probability are located. On the vertical axis, the curve indicates which percentage of all targets is included in this curve. So, if we can target the 20% of the observations, the model will ensure that 80% of the churners in total are in this group, while the random pick would provide only the 20% of the targets.
In addition to the cumulative gains curve, the lift curve is a widely used visualization of model performance. In definitive terms, the lift is a measure of the performance of a targeting model at predicting or classifying cases as having an enhanced response (for the population as a whole), measured against a random choice targeting model. Constructing a lift curve follows a similar process as forming the cumulative gain curve. Indeed, it is derived from the gain chart. First, we order observations on the horizontal axis with the highest probability of being a target on the left and vice versa for the right-hand side. On the vertical axis, the lift curve indicates how many times more than average targets are included in this group. Lift is calculated as the ratio of Cumulative Gains from classification and random models. Consider the lift at 20%(the desired target of promotion); we can notice that the top 20% of observations contain 80% of targets. If the average incidence of targets is 20%, so the lift is 4. Thus, the model allows addressing four times more targets for this group, compared with addressing without the model, that is randomly.
#Scikitplot library is there to helpskplt.metrics.plot_lift_curve(y_test, predicted_probabilities)
Eventually, we are ready to present the findings for the marketing strategy. With the help of our model, we can target 80% of churners if the company delivers free promotion to 20% of its customers. While with a random pick, we would be able to focus only on 20% of churners.
So, we were able to observe that the Cumulative Gain and Lift charts are useful tools for decision making and model evaluation. They are relatively easy to interpret not only by professionals with a technical background but by others as well. Eventually, those charts can be applied in various fields, which are market segment targeting, financial budgeting, human resource evaluation, etc.
For full implementation, please refer to my GitHub repository and feel free to use this data for the same analysis yet with other classification models: GradientBoostingClassifier, LogisticRegression, etc.
Try, Fail, Learn, Succeed. | [
{
"code": null,
"e": 655,
"s": 171,
"text": "Nowadays, all major companies rely heavily on their data science capabilities. Business data units are becoming larger and more sophisticated in terms of the complexity and diversity of analysis. However, the success of delivering data science solutions into business reality largely depends on the interpretability of findings. Even if the developed models provide outstanding accuracy scores, they may be neglected if they do not match the demands of various business stakeholders."
},
{
"code": null,
"e": 1068,
"s": 655,
"text": "All beloved ROC AUC score is not informative enough for the business unit since it is abstract for non-technical managers. For the latter reason, I will present two meaningful metrics that every analyst should take into consideration when illustrating the results of their models: Cumulative Gains and Lift charts. I will demonstrate the example of a customer churn case study in the telecommunications industry."
},
{
"code": null,
"e": 1475,
"s": 1068,
"text": "Imagine a business scenario, when a telecom company decides to minimize the customer attrition rate by giving out one month of unlimited data usage to 20% of its customers. One of the managers suggests, for the promotion to be unbiased, to send the gift to every 5th customer ordered by their last names. The decision is almost there: unless someone proposes a better strategy for this marketing promotion."
},
{
"code": null,
"e": 1969,
"s": 1475,
"text": "Having the sample data of customers (actually can be accessed from my GitHub), we would decide to build a RandomForestClassifier model to predict the customer churn before this promotion begins. Then we will preprocess data, remove unnecessary columns, eliminate multicollinearity, and visualize. Final steps: model training and optimization with GridSearchCV. Yet, this article is not about the project; it is about the interpretability of your findings. The case question remains unanswered."
},
{
"code": null,
"e": 2421,
"s": 1969,
"text": "For this, I will present the cumulative gains and lift curves. The cumulative gains curve is an evaluation curve that assesses the performance of the model and compares the results with the random pick. It shows the percentage of targets reached when considering a certain percentage of the population with the highest probability to be target according to the model. In python, we are provided with scikitplot library, that will make the plot for us."
},
{
"code": null,
"e": 2632,
"s": 2421,
"text": "import scikitplot as skplt# Deriving Class probabilitiespredicted_probabilities = model_rf_best_params.predict_proba(x_test)# Creating the plotskplt.metrics.plot_cumulative_gain(y_test, predicted_probabilities)"
},
{
"code": null,
"e": 3292,
"s": 2632,
"text": "First, we order all the observations according to the output of the model. On the left-hand side of the horizontal axis, we place the observations with the highest probability to be target according to the model and vice versa for the right-hand side. In our case, at the 20% point of the horizontal axis, the 80% observations with the highest probability are located. On the vertical axis, the curve indicates which percentage of all targets is included in this curve. So, if we can target the 20% of the observations, the model will ensure that 80% of the churners in total are in this group, while the random pick would provide only the 20% of the targets."
},
{
"code": null,
"e": 4454,
"s": 3292,
"text": "In addition to the cumulative gains curve, the lift curve is a widely used visualization of model performance. In definitive terms, the lift is a measure of the performance of a targeting model at predicting or classifying cases as having an enhanced response (for the population as a whole), measured against a random choice targeting model. Constructing a lift curve follows a similar process as forming the cumulative gain curve. Indeed, it is derived from the gain chart. First, we order observations on the horizontal axis with the highest probability of being a target on the left and vice versa for the right-hand side. On the vertical axis, the lift curve indicates how many times more than average targets are included in this group. Lift is calculated as the ratio of Cumulative Gains from classification and random models. Consider the lift at 20%(the desired target of promotion); we can notice that the top 20% of observations contain 80% of targets. If the average incidence of targets is 20%, so the lift is 4. Thus, the model allows addressing four times more targets for this group, compared with addressing without the model, that is randomly."
},
{
"code": null,
"e": 4553,
"s": 4454,
"text": "#Scikitplot library is there to helpskplt.metrics.plot_lift_curve(y_test, predicted_probabilities)"
},
{
"code": null,
"e": 4829,
"s": 4553,
"text": "Eventually, we are ready to present the findings for the marketing strategy. With the help of our model, we can target 80% of churners if the company delivers free promotion to 20% of its customers. While with a random pick, we would be able to focus only on 20% of churners."
},
{
"code": null,
"e": 5220,
"s": 4829,
"text": "So, we were able to observe that the Cumulative Gain and Lift charts are useful tools for decision making and model evaluation. They are relatively easy to interpret not only by professionals with a technical background but by others as well. Eventually, those charts can be applied in various fields, which are market segment targeting, financial budgeting, human resource evaluation, etc."
},
{
"code": null,
"e": 5426,
"s": 5220,
"text": "For full implementation, please refer to my GitHub repository and feel free to use this data for the same analysis yet with other classification models: GradientBoostingClassifier, LogisticRegression, etc."
}
]
|
Java & MySQL - Insert Records Example | This chapter provides an example on how to insert records in a table using JDBC application. Before executing following example, make sure you have the following in place −
To execute the following example you can replace the username and password with your actual user name and password.
To execute the following example you can replace the username and password with your actual user name and password.
Your MySQL database you are using is up and running.
Your MySQL database you are using is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database.
Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table.
Clean up the environment − try with resources automatically closes the resources.
Clean up the environment − try with resources automatically closes the resources.
Copy and paste the following example in TestApplication.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
// Execute a query
System.out.println("Inserting records into the table...");
String sql = "INSERT INTO Registration VALUES (100, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (101, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac TestApplication.java
C:\>
When you run TestApplication, it produces the following result −
C:\>java TestApplication
Inserting records into the table...
Inserted records into the table...
C:\>
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": 2859,
"s": 2686,
"text": "This chapter provides an example on how to insert records in a table using JDBC application. Before executing following example, make sure you have the following in place −"
},
{
"code": null,
"e": 2975,
"s": 2859,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 3091,
"s": 2975,
"text": "To execute the following example you can replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 3144,
"s": 3091,
"text": "Your MySQL database you are using is up and running."
},
{
"code": null,
"e": 3197,
"s": 3144,
"text": "Your MySQL database you are using is up and running."
},
{
"code": null,
"e": 3280,
"s": 3197,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 3452,
"s": 3280,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 3624,
"s": 3452,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 3749,
"s": 3624,
"text": "Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database."
},
{
"code": null,
"e": 3874,
"s": 3749,
"text": "Register the JDBC driver − Requires that you initialize a driver so you can open a communications channel with the database."
},
{
"code": null,
"e": 4044,
"s": 3874,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 4214,
"s": 4044,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server."
},
{
"code": null,
"e": 4352,
"s": 4214,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table."
},
{
"code": null,
"e": 4490,
"s": 4352,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to insert records into a table."
},
{
"code": null,
"e": 4572,
"s": 4490,
"text": "Clean up the environment − try with resources automatically closes the resources."
},
{
"code": null,
"e": 4654,
"s": 4572,
"text": "Clean up the environment − try with resources automatically closes the resources."
},
{
"code": null,
"e": 4745,
"s": 4654,
"text": "Copy and paste the following example in TestApplication.java, compile and run as follows −"
},
{
"code": null,
"e": 5973,
"s": 4745,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class TestApplication {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n // Execute a query\n System.out.println(\"Inserting records into the table...\"); \n String sql = \"INSERT INTO Registration VALUES (100, 'Zara', 'Ali', 18)\";\n stmt.executeUpdate(sql);\n sql = \"INSERT INTO Registration VALUES (101, 'Mahnaz', 'Fatma', 25)\";\n stmt.executeUpdate(sql);\n sql = \"INSERT INTO Registration VALUES (102, 'Zaid', 'Khan', 30)\";\n stmt.executeUpdate(sql);\n sql = \"INSERT INTO Registration VALUES(103, 'Sumit', 'Mittal', 28)\";\n stmt.executeUpdate(sql);\n System.out.println(\"Inserted records into the table...\"); \t \n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 6023,
"s": 5973,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 6060,
"s": 6023,
"text": "C:\\>javac TestApplication.java\nC:\\>\n"
},
{
"code": null,
"e": 6125,
"s": 6060,
"text": "When you run TestApplication, it produces the following result −"
},
{
"code": null,
"e": 6227,
"s": 6125,
"text": "C:\\>java TestApplication\nInserting records into the table...\nInserted records into the table...\nC:\\>\n"
},
{
"code": null,
"e": 6260,
"s": 6227,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6276,
"s": 6260,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6309,
"s": 6276,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6325,
"s": 6309,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6360,
"s": 6325,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6374,
"s": 6360,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6408,
"s": 6374,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6422,
"s": 6408,
"text": " Tushar Kale"
},
{
"code": null,
"e": 6459,
"s": 6422,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6474,
"s": 6459,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6507,
"s": 6474,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6526,
"s": 6507,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6533,
"s": 6526,
"text": " Print"
},
{
"code": null,
"e": 6544,
"s": 6533,
"text": " Add Notes"
}
]
|
CSS | ::after Selector | 20 Dec, 2018
::after selector is used to add same content multiple times after the content of other elements. This selector is same as ::before selector.
Syntax:
::after{
content:
}
Below HTMl/CSS code shows the functionality of ::after selector :
<!DOCTYPE html><html> <head> <style> p::after { content: " - Remember this"; background-color: blue; } </style></head> <body> <h3>After Selector</h3> <p>User ID: @dmor1</p> <p>Name: dharam</p></body> </html>
Output:
Supported Browsers
Google Chrome 4.0
Edge 9.0
Firefox 3.5
Safari 3.1
Opera 7.0
Note: Internet Explorer 8 and Opera 4-6 supports with single-colon.(:after)
CSS-Selectors
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Dec, 2018"
},
{
"code": null,
"e": 195,
"s": 54,
"text": "::after selector is used to add same content multiple times after the content of other elements. This selector is same as ::before selector."
},
{
"code": null,
"e": 203,
"s": 195,
"text": "Syntax:"
},
{
"code": null,
"e": 232,
"s": 203,
"text": "::after{\n content:\n}\n"
},
{
"code": null,
"e": 298,
"s": 232,
"text": "Below HTMl/CSS code shows the functionality of ::after selector :"
},
{
"code": "<!DOCTYPE html><html> <head> <style> p::after { content: \" - Remember this\"; background-color: blue; } </style></head> <body> <h3>After Selector</h3> <p>User ID: @dmor1</p> <p>Name: dharam</p></body> </html>",
"e": 560,
"s": 298,
"text": null
},
{
"code": null,
"e": 568,
"s": 560,
"text": "Output:"
},
{
"code": null,
"e": 587,
"s": 568,
"text": "Supported Browsers"
},
{
"code": null,
"e": 605,
"s": 587,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 614,
"s": 605,
"text": "Edge 9.0"
},
{
"code": null,
"e": 626,
"s": 614,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 637,
"s": 626,
"text": "Safari 3.1"
},
{
"code": null,
"e": 647,
"s": 637,
"text": "Opera 7.0"
},
{
"code": null,
"e": 723,
"s": 647,
"text": "Note: Internet Explorer 8 and Opera 4-6 supports with single-colon.(:after)"
},
{
"code": null,
"e": 737,
"s": 723,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 741,
"s": 737,
"text": "CSS"
},
{
"code": null,
"e": 758,
"s": 741,
"text": "Web Technologies"
}
]
|
How to Display an Image in Grayscale in Matplotlib? | 01 Feb, 2022
In this article, we are going to depict images using matplotlib module in grayscale representation i.e. image representation using two colors only i.e. black and white.
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. PIL.Image.open() method in PIL module opens and identifies the given image file.
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. The matplotlib module can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc.
Step-by-step Approach:
Import required modules
Python3
# importing libraries.import numpy as npimport matplotlib.pyplot as pltfrom PIL import Image
Displaying Original picture.
Python3
# storing image pathfname = r'g4g.png' # opening image using pilimage = Image.open(fname) # plottingimageplt.imshow(image)plt.show()
Output:
Displaying Grayscale image, store the image path here let’s say it fname. Now open the image using PIL image method and convert it to L mode If you have an L mode image, that means it is a single-channel image – normally interpreted as grayscale. It only stores a grayscale, not color. Plotting the image as cmap = ‘gray’ convert the colours. All the work is done you can now see your image.
Python3
# storing image pathfname = r'g4g.png' # opening image using pilimage = Image.open(fname).convert("L") # maping image to gray scaleplt.imshow(image, cmap='gray')plt.show()
Output:
Below are some programs which depict how to display an image in grayscale using Matplotlib module:
Example 1:
Image used:
Python3
# importing libraries.import numpy as npimport matplotlib.pyplot as pltfrom PIL import Image # storing image pathfname = r'gfg.png' # opening image using pilimage = Image.open(fname).convert("L") # mapping image to gray scaleplt.imshow(image, cmap='gray')plt.show()
Output:
Example 2:
Image Used:
Python3
# importing libraries.import numpy as npimport matplotlib.pyplot as pltfrom PIL import Image # storing image pathfname = r'geeks.png' # opening image using pilimage = Image.open(fname).convert("L") # mapping image to gray scaleplt.imshow(image, cmap='gray')plt.show()
Output:
adnanirshad158
clintra
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 221,
"s": 52,
"text": "In this article, we are going to depict images using matplotlib module in grayscale representation i.e. image representation using two colors only i.e. black and white."
},
{
"code": null,
"e": 629,
"s": 221,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. PIL.Image.open() method in PIL module opens and identifies the given image file."
},
{
"code": null,
"e": 919,
"s": 629,
"text": "Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. The matplotlib module can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc."
},
{
"code": null,
"e": 942,
"s": 919,
"text": "Step-by-step Approach:"
},
{
"code": null,
"e": 966,
"s": 942,
"text": "Import required modules"
},
{
"code": null,
"e": 974,
"s": 966,
"text": "Python3"
},
{
"code": "# importing libraries.import numpy as npimport matplotlib.pyplot as pltfrom PIL import Image",
"e": 1067,
"s": 974,
"text": null
},
{
"code": null,
"e": 1096,
"s": 1067,
"text": "Displaying Original picture."
},
{
"code": null,
"e": 1104,
"s": 1096,
"text": "Python3"
},
{
"code": "# storing image pathfname = r'g4g.png' # opening image using pilimage = Image.open(fname) # plottingimageplt.imshow(image)plt.show()",
"e": 1237,
"s": 1104,
"text": null
},
{
"code": null,
"e": 1245,
"s": 1237,
"text": "Output:"
},
{
"code": null,
"e": 1637,
"s": 1245,
"text": "Displaying Grayscale image, store the image path here let’s say it fname. Now open the image using PIL image method and convert it to L mode If you have an L mode image, that means it is a single-channel image – normally interpreted as grayscale. It only stores a grayscale, not color. Plotting the image as cmap = ‘gray’ convert the colours. All the work is done you can now see your image."
},
{
"code": null,
"e": 1645,
"s": 1637,
"text": "Python3"
},
{
"code": "# storing image pathfname = r'g4g.png' # opening image using pilimage = Image.open(fname).convert(\"L\") # maping image to gray scaleplt.imshow(image, cmap='gray')plt.show()",
"e": 1817,
"s": 1645,
"text": null
},
{
"code": null,
"e": 1825,
"s": 1817,
"text": "Output:"
},
{
"code": null,
"e": 1924,
"s": 1825,
"text": "Below are some programs which depict how to display an image in grayscale using Matplotlib module:"
},
{
"code": null,
"e": 1935,
"s": 1924,
"text": "Example 1:"
},
{
"code": null,
"e": 1947,
"s": 1935,
"text": "Image used:"
},
{
"code": null,
"e": 1955,
"s": 1947,
"text": "Python3"
},
{
"code": "# importing libraries.import numpy as npimport matplotlib.pyplot as pltfrom PIL import Image # storing image pathfname = r'gfg.png' # opening image using pilimage = Image.open(fname).convert(\"L\") # mapping image to gray scaleplt.imshow(image, cmap='gray')plt.show()",
"e": 2222,
"s": 1955,
"text": null
},
{
"code": null,
"e": 2230,
"s": 2222,
"text": "Output:"
},
{
"code": null,
"e": 2241,
"s": 2230,
"text": "Example 2:"
},
{
"code": null,
"e": 2253,
"s": 2241,
"text": "Image Used:"
},
{
"code": null,
"e": 2261,
"s": 2253,
"text": "Python3"
},
{
"code": "# importing libraries.import numpy as npimport matplotlib.pyplot as pltfrom PIL import Image # storing image pathfname = r'geeks.png' # opening image using pilimage = Image.open(fname).convert(\"L\") # mapping image to gray scaleplt.imshow(image, cmap='gray')plt.show()",
"e": 2530,
"s": 2261,
"text": null
},
{
"code": null,
"e": 2538,
"s": 2530,
"text": "Output:"
},
{
"code": null,
"e": 2553,
"s": 2538,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2561,
"s": 2553,
"text": "clintra"
},
{
"code": null,
"e": 2568,
"s": 2561,
"text": "Picked"
},
{
"code": null,
"e": 2586,
"s": 2568,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2593,
"s": 2586,
"text": "Python"
}
]
|
HSBC Campus Placement | 31 Aug, 2018
Round 1: On Screen Test
Part 1(90 questions and 75 mins)
There were three sections in part 1
Aptitude : Very basic and easy questions. Consisted of 30 questions.
Verbal Ability : Consisted of 30 questions. Among which one was a comprehension passage.
Technical : Consisted moderate level questions. Included questions on Java, C++, Android, JavaScript, HTML, Operating Systems (Thrashing), Tree traversal (In order, Pre order, Post order)
First and second sections were very easy while the technical section is time consuming. Distribute time accordingly. I managed to finish the first two sections in 30 mins. Each section has individual cut off. You can’t just score good in the first two sections and manage to get away with the third section without reaching the cut off.
Part 2(2 questions and 30 mins)
One section of coding in part 2
Coding was allowed in C++, Java8, Perl and Python.
The first question was very easy. Solved in 5 mins. Asked to print the sum of numbers from 1 to n leaving all the numbers divisible by k.
The second question was of moderate to difficult level. It was
Given a matrix of dimension m*n where each cell in the matrix can have values 0, 1 or 2 which has the following meaning:
0: Empty cell
1: Cells have fresh oranges
2: Cells have rotten oranges
So we have to determine what is the minimum time required so that all the oranges become rotten. A rotten orange at index [i, j] can rot other fresh orange at indexes [i-1, j], [i+1, j], [i, j-1], [i, j+1] (up, down, left and right). If it is impossible to rot every orange then simply return -1.
If you manage to do any question, I suppose you will get through with the cut off.
Among from over 160 students, 42 qualified for the technical interview round.
Round 2: Technical Interview
Being an Electronics student I didn’t have much of the CS profile resume. Was nervous since I was interviewed by the toughest interviewer among three of ’em. Firstly I was asked to tell about myself(He listened to everything very carefully). Then I was asked to tell about my strengths to which I responded Java. I was asked four questions. Level of questions increased as I started answering them.
Inheritance
Class A {some code;}
Class B extends A{
B a = new A();
}
Wrote this on a paper and showed it to me. Didn’t ask anything. I answered myself that this was wrong since B is an instance of A but not vice versa. He asked me to write down the correct statement.
Answer : B a = new B(); OR A a = new B();
Multiple inheritance and Multiple interfacing
Class A extends B, C{}
Class A implements b, c{}
Again showed it to me.
Answer: First statement was wrong since java does not support multiple inheritance however second statement was right as it supports multiple interfacing. Then asked me a bit about interfaces in Java.
Dynamic list
public void test(){ List l = new ArrayList(); l.add("summer"); l.add("spring"); test(l); System.out.print(l);} public static test(List p){ p.add("autumn"); p.add("winters"); p = null;}
Answer: I am not sure, although I answered that it prints everything (“summer”, “spring”, “autumn”, “winters”) since P is only referred to null however l is printed.
Method Overloading
public static void test(byte b){}public static void test(short s){}public static void test(int i){}test(5)
Question: Are these statements correct?
Answer: Yes, it depicts overloading in java.
Question: What are the rules for overloading?
Answer: The method name should be the same while the number of parameters should be different or if count of parameters is also the same, data type should be different.
Question(Main): Which of the method would be executed?
Answer: The one containing parameter ( int i ) since the system priority of int (in Java) is greater than that of short. And of short is greater than that of byte.
He was quite impressed and passed me for the HR round.
17 students were shortlisted.
Round 3: HR Round
Basic questions.
What do I like
How will my friends describe me
Challenges faced in life
My role in my team projects.
The HR will basically see how confident and well spoken you are.
11 of us were offered the role of Strikers. :’)
HSBC
On-Campus
Interview Experiences
HSBC
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Aug, 2018"
},
{
"code": null,
"e": 53,
"s": 28,
"text": "Round 1: On Screen Test "
},
{
"code": null,
"e": 86,
"s": 53,
"text": "Part 1(90 questions and 75 mins)"
},
{
"code": null,
"e": 122,
"s": 86,
"text": "There were three sections in part 1"
},
{
"code": null,
"e": 191,
"s": 122,
"text": "Aptitude : Very basic and easy questions. Consisted of 30 questions."
},
{
"code": null,
"e": 280,
"s": 191,
"text": "Verbal Ability : Consisted of 30 questions. Among which one was a comprehension passage."
},
{
"code": null,
"e": 469,
"s": 280,
"text": "Technical : Consisted moderate level questions. Included questions on Java, C++, Android, JavaScript, HTML, Operating Systems (Thrashing), Tree traversal (In order, Pre order, Post order)"
},
{
"code": null,
"e": 806,
"s": 469,
"text": "First and second sections were very easy while the technical section is time consuming. Distribute time accordingly. I managed to finish the first two sections in 30 mins. Each section has individual cut off. You can’t just score good in the first two sections and manage to get away with the third section without reaching the cut off."
},
{
"code": null,
"e": 838,
"s": 806,
"text": "Part 2(2 questions and 30 mins)"
},
{
"code": null,
"e": 870,
"s": 838,
"text": "One section of coding in part 2"
},
{
"code": null,
"e": 921,
"s": 870,
"text": "Coding was allowed in C++, Java8, Perl and Python."
},
{
"code": null,
"e": 1059,
"s": 921,
"text": "The first question was very easy. Solved in 5 mins. Asked to print the sum of numbers from 1 to n leaving all the numbers divisible by k."
},
{
"code": null,
"e": 1122,
"s": 1059,
"text": "The second question was of moderate to difficult level. It was"
},
{
"code": null,
"e": 1243,
"s": 1122,
"text": "Given a matrix of dimension m*n where each cell in the matrix can have values 0, 1 or 2 which has the following meaning:"
},
{
"code": null,
"e": 1316,
"s": 1243,
"text": "0: Empty cell\n\n1: Cells have fresh oranges\n\n2: Cells have rotten oranges"
},
{
"code": null,
"e": 1613,
"s": 1316,
"text": "So we have to determine what is the minimum time required so that all the oranges become rotten. A rotten orange at index [i, j] can rot other fresh orange at indexes [i-1, j], [i+1, j], [i, j-1], [i, j+1] (up, down, left and right). If it is impossible to rot every orange then simply return -1."
},
{
"code": null,
"e": 1696,
"s": 1613,
"text": "If you manage to do any question, I suppose you will get through with the cut off."
},
{
"code": null,
"e": 1774,
"s": 1696,
"text": "Among from over 160 students, 42 qualified for the technical interview round."
},
{
"code": null,
"e": 1803,
"s": 1774,
"text": "Round 2: Technical Interview"
},
{
"code": null,
"e": 2202,
"s": 1803,
"text": "Being an Electronics student I didn’t have much of the CS profile resume. Was nervous since I was interviewed by the toughest interviewer among three of ’em. Firstly I was asked to tell about myself(He listened to everything very carefully). Then I was asked to tell about my strengths to which I responded Java. I was asked four questions. Level of questions increased as I started answering them."
},
{
"code": null,
"e": 2214,
"s": 2202,
"text": "Inheritance"
},
{
"code": null,
"e": 2235,
"s": 2214,
"text": "Class A {some code;}"
},
{
"code": null,
"e": 2254,
"s": 2235,
"text": "Class B extends A{"
},
{
"code": null,
"e": 2269,
"s": 2254,
"text": "B a = new A();"
},
{
"code": null,
"e": 2271,
"s": 2269,
"text": "}"
},
{
"code": null,
"e": 2470,
"s": 2271,
"text": "Wrote this on a paper and showed it to me. Didn’t ask anything. I answered myself that this was wrong since B is an instance of A but not vice versa. He asked me to write down the correct statement."
},
{
"code": null,
"e": 2514,
"s": 2470,
"text": "Answer : B a = new B(); OR A a = new B();"
},
{
"code": null,
"e": 2560,
"s": 2514,
"text": "Multiple inheritance and Multiple interfacing"
},
{
"code": null,
"e": 2583,
"s": 2560,
"text": "Class A extends B, C{}"
},
{
"code": null,
"e": 2609,
"s": 2583,
"text": "Class A implements b, c{}"
},
{
"code": null,
"e": 2632,
"s": 2609,
"text": "Again showed it to me."
},
{
"code": null,
"e": 2833,
"s": 2632,
"text": "Answer: First statement was wrong since java does not support multiple inheritance however second statement was right as it supports multiple interfacing. Then asked me a bit about interfaces in Java."
},
{
"code": null,
"e": 2846,
"s": 2833,
"text": "Dynamic list"
},
{
"code": "public void test(){ List l = new ArrayList(); l.add(\"summer\"); l.add(\"spring\"); test(l); System.out.print(l);} public static test(List p){ p.add(\"autumn\"); p.add(\"winters\"); p = null;}",
"e": 3046,
"s": 2846,
"text": null
},
{
"code": null,
"e": 3212,
"s": 3046,
"text": "Answer: I am not sure, although I answered that it prints everything (“summer”, “spring”, “autumn”, “winters”) since P is only referred to null however l is printed."
},
{
"code": null,
"e": 3231,
"s": 3212,
"text": "Method Overloading"
},
{
"code": "public static void test(byte b){}public static void test(short s){}public static void test(int i){}test(5)",
"e": 3338,
"s": 3231,
"text": null
},
{
"code": null,
"e": 3378,
"s": 3338,
"text": "Question: Are these statements correct?"
},
{
"code": null,
"e": 3423,
"s": 3378,
"text": "Answer: Yes, it depicts overloading in java."
},
{
"code": null,
"e": 3469,
"s": 3423,
"text": "Question: What are the rules for overloading?"
},
{
"code": null,
"e": 3638,
"s": 3469,
"text": "Answer: The method name should be the same while the number of parameters should be different or if count of parameters is also the same, data type should be different."
},
{
"code": null,
"e": 3693,
"s": 3638,
"text": "Question(Main): Which of the method would be executed?"
},
{
"code": null,
"e": 3857,
"s": 3693,
"text": "Answer: The one containing parameter ( int i ) since the system priority of int (in Java) is greater than that of short. And of short is greater than that of byte."
},
{
"code": null,
"e": 3914,
"s": 3859,
"text": "He was quite impressed and passed me for the HR round."
},
{
"code": null,
"e": 3944,
"s": 3914,
"text": "17 students were shortlisted."
},
{
"code": null,
"e": 3962,
"s": 3944,
"text": "Round 3: HR Round"
},
{
"code": null,
"e": 3979,
"s": 3962,
"text": "Basic questions."
},
{
"code": null,
"e": 3994,
"s": 3979,
"text": "What do I like"
},
{
"code": null,
"e": 4026,
"s": 3994,
"text": "How will my friends describe me"
},
{
"code": null,
"e": 4051,
"s": 4026,
"text": "Challenges faced in life"
},
{
"code": null,
"e": 4080,
"s": 4051,
"text": "My role in my team projects."
},
{
"code": null,
"e": 4145,
"s": 4080,
"text": "The HR will basically see how confident and well spoken you are."
},
{
"code": null,
"e": 4193,
"s": 4145,
"text": "11 of us were offered the role of Strikers. :’)"
},
{
"code": null,
"e": 4200,
"s": 4195,
"text": "HSBC"
},
{
"code": null,
"e": 4210,
"s": 4200,
"text": "On-Campus"
},
{
"code": null,
"e": 4232,
"s": 4210,
"text": "Interview Experiences"
},
{
"code": null,
"e": 4237,
"s": 4232,
"text": "HSBC"
}
]
|
Get current time in milliseconds using Python | 27 Dec, 2019
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules, so there is no need to install it externally.
time.time() method of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform dependent.
Note: The epoch is the point where the time starts, and is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0).
Syntax: time.time()
Return type: This method returns a float value which represents the time in seconds since the epoch.
Example 1:
# Python program to get# time in milliseconds # Import class time from time modulefrom time import time # time() function is multiplied with # 1000 to convert seconds into milliseconds.milliseconds = int(time() * 1000) print("Time in milliseconds since epoch", milliseconds)
Output:
Time in milliseconds since epoch 1576071104408
Example 2: Using lambda function
# Python program to get# time in milliseconds # Import class time from time modulefrom time import time # Get time in milliseconds using# lambda functionmilliseconds = lambda: int(time() * 1000) print("Time in milliseconds since epoch", milliseconds())
Output:
Time in milliseconds since epoch 1576071316487
Python time-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2019"
},
{
"code": null,
"e": 196,
"s": 28,
"text": "Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules, so there is no need to install it externally."
},
{
"code": null,
"e": 330,
"s": 196,
"text": "time.time() method of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform dependent."
},
{
"code": null,
"e": 640,
"s": 330,
"text": "Note: The epoch is the point where the time starts, and is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0)."
},
{
"code": null,
"e": 660,
"s": 640,
"text": "Syntax: time.time()"
},
{
"code": null,
"e": 761,
"s": 660,
"text": "Return type: This method returns a float value which represents the time in seconds since the epoch."
},
{
"code": null,
"e": 772,
"s": 761,
"text": "Example 1:"
},
{
"code": "# Python program to get# time in milliseconds # Import class time from time modulefrom time import time # time() function is multiplied with # 1000 to convert seconds into milliseconds.milliseconds = int(time() * 1000) print(\"Time in milliseconds since epoch\", milliseconds)",
"e": 1050,
"s": 772,
"text": null
},
{
"code": null,
"e": 1058,
"s": 1050,
"text": "Output:"
},
{
"code": null,
"e": 1106,
"s": 1058,
"text": "Time in milliseconds since epoch 1576071104408\n"
},
{
"code": null,
"e": 1139,
"s": 1106,
"text": "Example 2: Using lambda function"
},
{
"code": "# Python program to get# time in milliseconds # Import class time from time modulefrom time import time # Get time in milliseconds using# lambda functionmilliseconds = lambda: int(time() * 1000) print(\"Time in milliseconds since epoch\", milliseconds())",
"e": 1397,
"s": 1139,
"text": null
},
{
"code": null,
"e": 1405,
"s": 1397,
"text": "Output:"
},
{
"code": null,
"e": 1453,
"s": 1405,
"text": "Time in milliseconds since epoch 1576071316487\n"
},
{
"code": null,
"e": 1472,
"s": 1453,
"text": "Python time-module"
},
{
"code": null,
"e": 1479,
"s": 1472,
"text": "Python"
}
]
|
How to use <mat-chip-list> and <mat-chip> in Angular Material ? | 08 Feb, 2021
Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. mat-chip-list is used mainly for labels.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatChipsModule’ from ‘@angular/material/chips’ in the app.module.ts file.
Then use the <mat-chip-list> tag to group all the labels or items inside this group tag.
Inside the <mat-chip-list> tag we need to use <mat-chip> tag for every item or labels.
In Angular material, we also have a chip-list type called stack chip-list where all the chips or labels are displayed vertically like a stack.
In order to display in such a form, we need to use this class name “mat-chip-list-stacked”.
If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn.
Once done with the above steps then serve or start the project.
Project Structure: It will look like the following.
Code Implementation:
app.module.ts:
Javascript
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { MatChipsModule } from '@angular/material/chips'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ imports: [ BrowserModule, FormsModule, MatChipsModule, BrowserAnimationsModule], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
app.component.html:
HTML
<p>Default Chip List</p> <mat-chip-list aria-label="Fish selection"> <mat-chip color="primary" selected> Primary theme chip </mat-chip> <mat-chip color="accent" selected> Accent theme chip </mat-chip> <mat-chip color="warn" selected> Warn theme chip </mat-chip> <mat-chip>Default theme chip </mat-chip></mat-chip-list><br><br><br> <p>Stacked Chip List</p> <mat-chip-list class="mat-chip-list-stacked" aria-label="Fish selection"> <mat-chip color="primary" selected> Primary theme chip </mat-chip> <mat-chip color="accent" selected> Accent theme chip </mat-chip> <mat-chip color="warn" selected> Warn theme chip </mat-chip> <mat-chip>Default theme chip </mat-chip></mat-chip-list>
Output:
Angular-material
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to setup 404 page in angular routing ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Feb, 2021"
},
{
"code": null,
"e": 362,
"s": 28,
"text": "Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. mat-chip-list is used mainly for labels."
},
{
"code": null,
"e": 383,
"s": 362,
"text": "Installation syntax:"
},
{
"code": null,
"e": 408,
"s": 383,
"text": "ng add @angular/material"
},
{
"code": null,
"e": 418,
"s": 408,
"text": "Approach:"
},
{
"code": null,
"e": 489,
"s": 418,
"text": "First, install the angular material using the above-mentioned command."
},
{
"code": null,
"e": 606,
"s": 489,
"text": "After completing the installation, Import ‘MatChipsModule’ from ‘@angular/material/chips’ in the app.module.ts file."
},
{
"code": null,
"e": 695,
"s": 606,
"text": "Then use the <mat-chip-list> tag to group all the labels or items inside this group tag."
},
{
"code": null,
"e": 782,
"s": 695,
"text": "Inside the <mat-chip-list> tag we need to use <mat-chip> tag for every item or labels."
},
{
"code": null,
"e": 925,
"s": 782,
"text": "In Angular material, we also have a chip-list type called stack chip-list where all the chips or labels are displayed vertically like a stack."
},
{
"code": null,
"e": 1017,
"s": 925,
"text": "In order to display in such a form, we need to use this class name “mat-chip-list-stacked”."
},
{
"code": null,
"e": 1164,
"s": 1017,
"text": "If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn."
},
{
"code": null,
"e": 1228,
"s": 1164,
"text": "Once done with the above steps then serve or start the project."
},
{
"code": null,
"e": 1280,
"s": 1228,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1301,
"s": 1280,
"text": "Code Implementation:"
},
{
"code": null,
"e": 1316,
"s": 1301,
"text": "app.module.ts:"
},
{
"code": null,
"e": 1327,
"s": 1316,
"text": "Javascript"
},
{
"code": "import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { MatChipsModule } from '@angular/material/chips'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ imports: [ BrowserModule, FormsModule, MatChipsModule, BrowserAnimationsModule], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }",
"e": 1871,
"s": 1327,
"text": null
},
{
"code": null,
"e": 1891,
"s": 1871,
"text": "app.component.html:"
},
{
"code": null,
"e": 1896,
"s": 1891,
"text": "HTML"
},
{
"code": "<p>Default Chip List</p> <mat-chip-list aria-label=\"Fish selection\"> <mat-chip color=\"primary\" selected> Primary theme chip </mat-chip> <mat-chip color=\"accent\" selected> Accent theme chip </mat-chip> <mat-chip color=\"warn\" selected> Warn theme chip </mat-chip> <mat-chip>Default theme chip </mat-chip></mat-chip-list><br><br><br> <p>Stacked Chip List</p> <mat-chip-list class=\"mat-chip-list-stacked\" aria-label=\"Fish selection\"> <mat-chip color=\"primary\" selected> Primary theme chip </mat-chip> <mat-chip color=\"accent\" selected> Accent theme chip </mat-chip> <mat-chip color=\"warn\" selected> Warn theme chip </mat-chip> <mat-chip>Default theme chip </mat-chip></mat-chip-list>",
"e": 2710,
"s": 1896,
"text": null
},
{
"code": null,
"e": 2718,
"s": 2710,
"text": "Output:"
},
{
"code": null,
"e": 2735,
"s": 2718,
"text": "Angular-material"
},
{
"code": null,
"e": 2742,
"s": 2735,
"text": "Picked"
},
{
"code": null,
"e": 2752,
"s": 2742,
"text": "AngularJS"
},
{
"code": null,
"e": 2769,
"s": 2752,
"text": "Web Technologies"
},
{
"code": null,
"e": 2867,
"s": 2769,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2891,
"s": 2867,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 2926,
"s": 2891,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 2950,
"s": 2926,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 3003,
"s": 2950,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 3046,
"s": 3003,
"text": "How to setup 404 page in angular routing ?"
},
{
"code": null,
"e": 3079,
"s": 3046,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3141,
"s": 3079,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3202,
"s": 3141,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3252,
"s": 3202,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Overlay an image on another image in Python | 03 Jan, 2021
Overlaying an image over another refers to the process of copying the image data of one image over the other. Overlaying could refer to other types of image processing methods as well such as overlaying similar images for noise reduction, Blending, etc. But for now, we will concentrate on the former one. In this article, we will learn how to overlay an image on top of another image using Image processing.
Module required:
Pillow: Python Imaging Library (expansion of PIL) is the de facto image processing package for the Python language. It incorporates lightweight image processing tools for editing, creating, and saving images.
pip install pillow
For demonstration purposes, we would be using the following image as the primary image.
Example 1: Overlaying an alpha image.
If we overlay an image containing transparent regions on an opaque image, then only opaque regions of the overlaid image would appear in the final image. The pixel may not be fully opaque and hence could have analog opacity (alpha channel). This type of overlay is the predominant one, as it allows for images to be blended in seamlessly.
For overlaying the image we would be using the paste() function found inside the pillow library.
Syntax: paste(self, im, box=None, mask=None)
Pastes another image into this image.
Parameters:
im: Source image or pixel value (integer or tuple).
box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it’s treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner.
mask: An optional mask image.
For demonstration, we would be overlaying the following image:
Below is the implementation:
Python3
from PIL import Image # Opening the primary image (used in background)img1 = Image.open(r"BACKGROUND_IMAGE_PATH") # Opening the secondary image (overlay image)img2 = Image.open(r"OVERLAY_IMAGE_PATH") # Pasting img2 image on top of img1 # starting at coordinates (0, 0)img1.paste(img2, (0,0), mask = img2) # Displaying the imageimg1.show()
Output:
Explanation:
Firstly we opened the primary image and saved its image object into variable img1. Then we opened the image that would be used as an overlay and saved its image object into variable img2. Then we called the paste method to overlay/paste the passed image on img1. The first argument is img2 which is the image object of the image containing transparent text. This image would be used for overlay. The second argument is a size 2 tuple denoting the coordinates of img1, where the img2 should be pasted. Since it is (0, 0), hence the second image would be pasted at the top left side of img1. The third argument is img2 which is passed to the mask parameter. It will specify the transparency mask, for img2. In the end we displayed the image.
Example 2: Overlaying a non-alpha image
If we overlay a fully opaque image on top of an opaque image, all pixels values of the overlaid image get retained in the final image. In this process pixel values of the background image get lost during the process (at the region occupied by the overlaid image).
We would be using the following image as the overlay image:
Below is the implementation:
Python3
from PIL import Image img1 = Image.open(r"BACKGROUND_IMAGE_PATH")img2 = Image.open(r"OVERLAY_IMAGE_PATH") # No transparency mask specified, # simulating an raster overlayimg1.paste(img2, (0,0)) img1.show()
Output:
Explanation:
The code is largely the same as the previous one, so only the changed code is of interest to us. In the paste method call, we omitted the mask argument, this allows no transparency mask to be used for the overlay. Therefore, the image is simply copy-pasted onto img1. Since the pixel values of img2 are copied as it is, the white background is also present in the output image. It gives the viewer a clue that the image is modified without much consideration in the quality of the final image, due to abrupt color changes found in the final image (this situation is mitigated when the overlay image contains transparent regions).
Picked
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 463,
"s": 54,
"text": "Overlaying an image over another refers to the process of copying the image data of one image over the other. Overlaying could refer to other types of image processing methods as well such as overlaying similar images for noise reduction, Blending, etc. But for now, we will concentrate on the former one. In this article, we will learn how to overlay an image on top of another image using Image processing."
},
{
"code": null,
"e": 480,
"s": 463,
"text": "Module required:"
},
{
"code": null,
"e": 689,
"s": 480,
"text": "Pillow: Python Imaging Library (expansion of PIL) is the de facto image processing package for the Python language. It incorporates lightweight image processing tools for editing, creating, and saving images."
},
{
"code": null,
"e": 708,
"s": 689,
"text": "pip install pillow"
},
{
"code": null,
"e": 796,
"s": 708,
"text": "For demonstration purposes, we would be using the following image as the primary image."
},
{
"code": null,
"e": 834,
"s": 796,
"text": "Example 1: Overlaying an alpha image."
},
{
"code": null,
"e": 1173,
"s": 834,
"text": "If we overlay an image containing transparent regions on an opaque image, then only opaque regions of the overlaid image would appear in the final image. The pixel may not be fully opaque and hence could have analog opacity (alpha channel). This type of overlay is the predominant one, as it allows for images to be blended in seamlessly."
},
{
"code": null,
"e": 1270,
"s": 1173,
"text": "For overlaying the image we would be using the paste() function found inside the pillow library."
},
{
"code": null,
"e": 1315,
"s": 1270,
"text": "Syntax: paste(self, im, box=None, mask=None)"
},
{
"code": null,
"e": 1356,
"s": 1315,
"text": " Pastes another image into this image."
},
{
"code": null,
"e": 1368,
"s": 1356,
"text": "Parameters:"
},
{
"code": null,
"e": 1420,
"s": 1368,
"text": "im: Source image or pixel value (integer or tuple)."
},
{
"code": null,
"e": 1616,
"s": 1420,
"text": "box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it’s treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner."
},
{
"code": null,
"e": 1646,
"s": 1616,
"text": "mask: An optional mask image."
},
{
"code": null,
"e": 1709,
"s": 1646,
"text": "For demonstration, we would be overlaying the following image:"
},
{
"code": null,
"e": 1738,
"s": 1709,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 1746,
"s": 1738,
"text": "Python3"
},
{
"code": "from PIL import Image # Opening the primary image (used in background)img1 = Image.open(r\"BACKGROUND_IMAGE_PATH\") # Opening the secondary image (overlay image)img2 = Image.open(r\"OVERLAY_IMAGE_PATH\") # Pasting img2 image on top of img1 # starting at coordinates (0, 0)img1.paste(img2, (0,0), mask = img2) # Displaying the imageimg1.show()",
"e": 2089,
"s": 1746,
"text": null
},
{
"code": null,
"e": 2097,
"s": 2089,
"text": "Output:"
},
{
"code": null,
"e": 2110,
"s": 2097,
"text": "Explanation:"
},
{
"code": null,
"e": 2850,
"s": 2110,
"text": "Firstly we opened the primary image and saved its image object into variable img1. Then we opened the image that would be used as an overlay and saved its image object into variable img2. Then we called the paste method to overlay/paste the passed image on img1. The first argument is img2 which is the image object of the image containing transparent text. This image would be used for overlay. The second argument is a size 2 tuple denoting the coordinates of img1, where the img2 should be pasted. Since it is (0, 0), hence the second image would be pasted at the top left side of img1. The third argument is img2 which is passed to the mask parameter. It will specify the transparency mask, for img2. In the end we displayed the image."
},
{
"code": null,
"e": 2890,
"s": 2850,
"text": "Example 2: Overlaying a non-alpha image"
},
{
"code": null,
"e": 3154,
"s": 2890,
"text": "If we overlay a fully opaque image on top of an opaque image, all pixels values of the overlaid image get retained in the final image. In this process pixel values of the background image get lost during the process (at the region occupied by the overlaid image)."
},
{
"code": null,
"e": 3214,
"s": 3154,
"text": "We would be using the following image as the overlay image:"
},
{
"code": null,
"e": 3243,
"s": 3214,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 3251,
"s": 3243,
"text": "Python3"
},
{
"code": "from PIL import Image img1 = Image.open(r\"BACKGROUND_IMAGE_PATH\")img2 = Image.open(r\"OVERLAY_IMAGE_PATH\") # No transparency mask specified, # simulating an raster overlayimg1.paste(img2, (0,0)) img1.show()",
"e": 3460,
"s": 3251,
"text": null
},
{
"code": null,
"e": 3468,
"s": 3460,
"text": "Output:"
},
{
"code": null,
"e": 3481,
"s": 3468,
"text": "Explanation:"
},
{
"code": null,
"e": 4113,
"s": 3481,
"text": "The code is largely the same as the previous one, so only the changed code is of interest to us. In the paste method call, we omitted the mask argument, this allows no transparency mask to be used for the overlay. Therefore, the image is simply copy-pasted onto img1. Since the pixel values of img2 are copied as it is, the white background is also present in the output image. It gives the viewer a clue that the image is modified without much consideration in the quality of the final image, due to abrupt color changes found in the final image (this situation is mitigated when the overlay image contains transparent regions). "
},
{
"code": null,
"e": 4120,
"s": 4113,
"text": "Picked"
},
{
"code": null,
"e": 4131,
"s": 4120,
"text": "Python-pil"
},
{
"code": null,
"e": 4138,
"s": 4131,
"text": "Python"
}
]
|
Largest factor of a given number which is a perfect square | 21 Sep, 2021
Given a number . The task is to find the largest factor of that number which is a perfect square.Examples:
Input : N = 420
Output : 4
Input : N = 100
Output : 100
A Simple Solution is to traverse all of the numbers in decreasing order from the given number down till 1 and if any of these numbers is a factor of the given number and is also a perfect square, print that number.Time Complexity: O(N)Better Solution : A better solution is to use prime factorization of the given number.
First find all the prime factors of that number till sqrt(num).
Take a variable, answer and initialize it to 1. It represents the largest square number which is also a factor of that number.
Now, Check If any prime number occurs even number of times in the prime factorization of the given number, if yes then multiply the answer with that prime factor the number of times it occurs.
Else, if it occurs odd number of times then multiply the answer with prime number (K – 1) times, K is the frequency of that prime factor in the prime factorization.
Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to find the largest factor of// a number which is also a perfect square #include <cmath>#include <iostream>using namespace std; // Function to find the largest factor// of a given number which// is a perfect squareint largestSquareFactor(int num){ // Initialise the answer to 1 int answer = 1; // Finding the prime factors till sqrt(num) for (int i = 2; i < sqrt(num); ++i) { // Frequency of the prime factor in the // factorisation initialised to 0 int cnt = 0; int j = i; while (num % j == 0) { cnt++; j *= i; } // If the frequency is odd then multiply i // frequency-1 times to the answer if (cnt & 1) { cnt--; answer *= pow(i, cnt); } // Else if it is even, multiply // it frequency times else { answer *= pow(i, cnt); } } return answer;} // Driver Codeint main(){ int N = 420; cout << largestSquareFactor(N); return 0;}
// Java program to find the largest factor of// a number which is also a perfect square class GFG{ // Function to find the largest factor// of a given number which// is a perfect squarestatic int largestSquareFactor(int num){ // Initialise the answer to 1 int answer = 1; // Finding the prime factors till sqrt(num) for (int i = 2; i < Math.sqrt(num); ++i) { // Frequency of the prime factor in the // factorisation initialised to 0 int cnt = 0; int j = i; while (num % j == 0) { cnt++; j *= i; } // If the frequency is odd then multiply i // frequency-1 times to the answer if ((cnt & 1)!=0) { cnt--; answer *= Math.pow(i, cnt); } // Else if it is even, multiply // it frequency times else { answer *= Math.pow(i, cnt); } } return answer;} // Driver Codepublic static void main(String args[]){ int N = 420; System.out.println(largestSquareFactor(N)); }}
# Python 3 program to find the largest# factor of a number which is also a# perfect squareimport math # Function to find the largest factor# of a given number which is a# perfect squaredef largestSquareFactor( num): # Initialise the answer to 1 answer = 1 # Finding the prime factors till sqrt(num) for i in range(2, int(math.sqrt(num))) : # Frequency of the prime factor in the # factorisation initialised to 0 cnt = 0 j = i while (num % j == 0) : cnt += 1 j *= i # If the frequency is odd then multiply i # frequency-1 times to the answer if (cnt & 1) : cnt -= 1 answer *= pow(i, cnt) # Else if it is even, multiply # it frequency times else : answer *= pow(i, cnt) return answer # Driver Codeif __name__ == "__main__": N = 420 print(largestSquareFactor(N)) # This code is contributed# by ChitraNayal
// C# program to find the largest factor of// a number which is also a perfect squareusing System; class GFG{ // Function to find the largest factor of// a given number which is a perfect squarestatic double largestSquareFactor(double num){ // Initialise the answer to 1 double answer = 1; // Finding the prime factors // till sqrt(num) for (int i = 2; i < Math.Sqrt(num); ++i) { // Frequency of the prime factor in // the factorisation initialised to 0 int cnt = 0; int j = i; while (num % j == 0) { cnt++; j *= i; } // If the frequency is odd then multiply i // frequency-1 times to the answer if ((cnt & 1) != 0) { cnt--; answer *= Math.Pow(i, cnt); } // Else if it is even, multiply // it frequency times else { answer *= Math.Pow(i, cnt); } } return answer;} // Driver Codestatic public void Main (){ int N = 420; Console.WriteLine(largestSquareFactor(N));}} // This code is contributed by Sach_Code
<?php// PHP program to find the largest// factor of a number which is also// a perfect square // Function to find the largest// factor of a given number which// is a perfect squarefunction largestSquareFactor($num){ // Initialise the answer to 1 $answer = 1; // Finding the prime factors // till sqrt(num) for ($i = 2; $i < sqrt($num); ++$i) { // Frequency of the prime factor // in the factorisation initialised to 0 $cnt = 0; $j = $i; while ($num % $j == 0) { $cnt++; $j *= $i; } // If the frequency is odd then // multiply i frequency-1 times // to the answer if ($cnt & 1) { $cnt--; $answer *= pow($i, $cnt); } // Else if it is even, multiply // it frequency times else { $answer *= pow($i, $cnt); } } return $answer;} // Driver Code$N = 420;echo largestSquareFactor($N); // This code is contributed// by Sach_Code?>
<script>// Javascript program to find the largest factor of// a number which is also a perfect square // Function to find the largest factor// of a given number which// is a perfect squarefunction largestSquareFactor(num){ // Initialise the answer to 1 let answer = 1; // Finding the prime factors till sqrt(num) for (let i = 2; i < Math.sqrt(num); ++i) { // Frequency of the prime factor in the // factorisation initialised to 0 let cnt = 0; let j = i; while (num % j == 0) { cnt++; j *= i; } // If the frequency is odd then multiply i // frequency-1 times to the answer if (cnt & 1) { cnt--; answer *= Math.pow(i, cnt); } // Else if it is even, multiply // it frequency times else { answer *= Math.pow(i, cnt); } } return answer;} // Driver Codelet N = 420; document.write(largestSquareFactor(N)); // This code is contributed by souravmahato348.</script>
4
Time Complexity: O( sqrt(N) )
tufan_gupta2000
Sach_Code
ukasp
souravmahato348
rajeev0719singh
simmytarika5
maths-perfect-square
prime-factor
sieve
Technical Scripter 2018
Algorithms
Competitive Programming
Mathematical
Technical Scripter
Mathematical
sieve
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 162,
"s": 54,
"text": "Given a number . The task is to find the largest factor of that number which is a perfect square.Examples: "
},
{
"code": null,
"e": 219,
"s": 162,
"text": "Input : N = 420\nOutput : 4\n\nInput : N = 100\nOutput : 100"
},
{
"code": null,
"e": 543,
"s": 221,
"text": "A Simple Solution is to traverse all of the numbers in decreasing order from the given number down till 1 and if any of these numbers is a factor of the given number and is also a perfect square, print that number.Time Complexity: O(N)Better Solution : A better solution is to use prime factorization of the given number."
},
{
"code": null,
"e": 607,
"s": 543,
"text": "First find all the prime factors of that number till sqrt(num)."
},
{
"code": null,
"e": 734,
"s": 607,
"text": "Take a variable, answer and initialize it to 1. It represents the largest square number which is also a factor of that number."
},
{
"code": null,
"e": 927,
"s": 734,
"text": "Now, Check If any prime number occurs even number of times in the prime factorization of the given number, if yes then multiply the answer with that prime factor the number of times it occurs."
},
{
"code": null,
"e": 1092,
"s": 927,
"text": "Else, if it occurs odd number of times then multiply the answer with prime number (K – 1) times, K is the frequency of that prime factor in the prime factorization."
},
{
"code": null,
"e": 1144,
"s": 1092,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1148,
"s": 1144,
"text": "C++"
},
{
"code": null,
"e": 1153,
"s": 1148,
"text": "Java"
},
{
"code": null,
"e": 1162,
"s": 1153,
"text": "Python 3"
},
{
"code": null,
"e": 1165,
"s": 1162,
"text": "C#"
},
{
"code": null,
"e": 1169,
"s": 1165,
"text": "PHP"
},
{
"code": null,
"e": 1180,
"s": 1169,
"text": "Javascript"
},
{
"code": "// C++ program to find the largest factor of// a number which is also a perfect square #include <cmath>#include <iostream>using namespace std; // Function to find the largest factor// of a given number which// is a perfect squareint largestSquareFactor(int num){ // Initialise the answer to 1 int answer = 1; // Finding the prime factors till sqrt(num) for (int i = 2; i < sqrt(num); ++i) { // Frequency of the prime factor in the // factorisation initialised to 0 int cnt = 0; int j = i; while (num % j == 0) { cnt++; j *= i; } // If the frequency is odd then multiply i // frequency-1 times to the answer if (cnt & 1) { cnt--; answer *= pow(i, cnt); } // Else if it is even, multiply // it frequency times else { answer *= pow(i, cnt); } } return answer;} // Driver Codeint main(){ int N = 420; cout << largestSquareFactor(N); return 0;}",
"e": 2206,
"s": 1180,
"text": null
},
{
"code": "// Java program to find the largest factor of// a number which is also a perfect square class GFG{ // Function to find the largest factor// of a given number which// is a perfect squarestatic int largestSquareFactor(int num){ // Initialise the answer to 1 int answer = 1; // Finding the prime factors till sqrt(num) for (int i = 2; i < Math.sqrt(num); ++i) { // Frequency of the prime factor in the // factorisation initialised to 0 int cnt = 0; int j = i; while (num % j == 0) { cnt++; j *= i; } // If the frequency is odd then multiply i // frequency-1 times to the answer if ((cnt & 1)!=0) { cnt--; answer *= Math.pow(i, cnt); } // Else if it is even, multiply // it frequency times else { answer *= Math.pow(i, cnt); } } return answer;} // Driver Codepublic static void main(String args[]){ int N = 420; System.out.println(largestSquareFactor(N)); }}",
"e": 3260,
"s": 2206,
"text": null
},
{
"code": "# Python 3 program to find the largest# factor of a number which is also a# perfect squareimport math # Function to find the largest factor# of a given number which is a# perfect squaredef largestSquareFactor( num): # Initialise the answer to 1 answer = 1 # Finding the prime factors till sqrt(num) for i in range(2, int(math.sqrt(num))) : # Frequency of the prime factor in the # factorisation initialised to 0 cnt = 0 j = i while (num % j == 0) : cnt += 1 j *= i # If the frequency is odd then multiply i # frequency-1 times to the answer if (cnt & 1) : cnt -= 1 answer *= pow(i, cnt) # Else if it is even, multiply # it frequency times else : answer *= pow(i, cnt) return answer # Driver Codeif __name__ == \"__main__\": N = 420 print(largestSquareFactor(N)) # This code is contributed# by ChitraNayal",
"e": 4239,
"s": 3260,
"text": null
},
{
"code": "// C# program to find the largest factor of// a number which is also a perfect squareusing System; class GFG{ // Function to find the largest factor of// a given number which is a perfect squarestatic double largestSquareFactor(double num){ // Initialise the answer to 1 double answer = 1; // Finding the prime factors // till sqrt(num) for (int i = 2; i < Math.Sqrt(num); ++i) { // Frequency of the prime factor in // the factorisation initialised to 0 int cnt = 0; int j = i; while (num % j == 0) { cnt++; j *= i; } // If the frequency is odd then multiply i // frequency-1 times to the answer if ((cnt & 1) != 0) { cnt--; answer *= Math.Pow(i, cnt); } // Else if it is even, multiply // it frequency times else { answer *= Math.Pow(i, cnt); } } return answer;} // Driver Codestatic public void Main (){ int N = 420; Console.WriteLine(largestSquareFactor(N));}} // This code is contributed by Sach_Code",
"e": 5365,
"s": 4239,
"text": null
},
{
"code": "<?php// PHP program to find the largest// factor of a number which is also// a perfect square // Function to find the largest// factor of a given number which// is a perfect squarefunction largestSquareFactor($num){ // Initialise the answer to 1 $answer = 1; // Finding the prime factors // till sqrt(num) for ($i = 2; $i < sqrt($num); ++$i) { // Frequency of the prime factor // in the factorisation initialised to 0 $cnt = 0; $j = $i; while ($num % $j == 0) { $cnt++; $j *= $i; } // If the frequency is odd then // multiply i frequency-1 times // to the answer if ($cnt & 1) { $cnt--; $answer *= pow($i, $cnt); } // Else if it is even, multiply // it frequency times else { $answer *= pow($i, $cnt); } } return $answer;} // Driver Code$N = 420;echo largestSquareFactor($N); // This code is contributed// by Sach_Code?>",
"e": 6404,
"s": 5365,
"text": null
},
{
"code": "<script>// Javascript program to find the largest factor of// a number which is also a perfect square // Function to find the largest factor// of a given number which// is a perfect squarefunction largestSquareFactor(num){ // Initialise the answer to 1 let answer = 1; // Finding the prime factors till sqrt(num) for (let i = 2; i < Math.sqrt(num); ++i) { // Frequency of the prime factor in the // factorisation initialised to 0 let cnt = 0; let j = i; while (num % j == 0) { cnt++; j *= i; } // If the frequency is odd then multiply i // frequency-1 times to the answer if (cnt & 1) { cnt--; answer *= Math.pow(i, cnt); } // Else if it is even, multiply // it frequency times else { answer *= Math.pow(i, cnt); } } return answer;} // Driver Codelet N = 420; document.write(largestSquareFactor(N)); // This code is contributed by souravmahato348.</script>",
"e": 7461,
"s": 6404,
"text": null
},
{
"code": null,
"e": 7463,
"s": 7461,
"text": "4"
},
{
"code": null,
"e": 7495,
"s": 7465,
"text": "Time Complexity: O( sqrt(N) )"
},
{
"code": null,
"e": 7511,
"s": 7495,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 7521,
"s": 7511,
"text": "Sach_Code"
},
{
"code": null,
"e": 7527,
"s": 7521,
"text": "ukasp"
},
{
"code": null,
"e": 7543,
"s": 7527,
"text": "souravmahato348"
},
{
"code": null,
"e": 7559,
"s": 7543,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 7572,
"s": 7559,
"text": "simmytarika5"
},
{
"code": null,
"e": 7593,
"s": 7572,
"text": "maths-perfect-square"
},
{
"code": null,
"e": 7606,
"s": 7593,
"text": "prime-factor"
},
{
"code": null,
"e": 7612,
"s": 7606,
"text": "sieve"
},
{
"code": null,
"e": 7636,
"s": 7612,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 7647,
"s": 7636,
"text": "Algorithms"
},
{
"code": null,
"e": 7671,
"s": 7647,
"text": "Competitive Programming"
},
{
"code": null,
"e": 7684,
"s": 7671,
"text": "Mathematical"
},
{
"code": null,
"e": 7703,
"s": 7684,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7716,
"s": 7703,
"text": "Mathematical"
},
{
"code": null,
"e": 7722,
"s": 7716,
"text": "sieve"
},
{
"code": null,
"e": 7733,
"s": 7722,
"text": "Algorithms"
}
]
|
Packages in Golang | 20 Nov, 2019
Packages are the most powerful part of the Go language. The purpose of a package is to design and maintain a large number of programs by grouping related features together into single units so that they can be easy to maintain and understand and independent of the other package programs. This modularity allows them to share and reuse. In Go language, every package is defined with a different name and that name is close to their functionality like “strings” package and it contains methods and functions that only related to strings.
1. Import paths: In Go language, every package is defined by a unique string and this string is known as import path. With the help of an import path, you can import packages in your program. For example:
import "fmt"
This statement states that you are importing an fmt package in your program. The import path of packages is globally unique. To avoid conflict between the path of the packages other than the standard library, the package path should start with the internet domain name of the organization that owns or host the package. For example:
import "geeksforgeeks.com/example/strings"
2. Package Declaration: In Go language, package declaration is always present at the beginning of the source file and the purpose of this declaration is to determine the default identifier for that package when it is imported by another package. For example:
package main
3. Import declaration: The import declaration immediately comes after the package declaration. The Go source file contains zero or more import declaration and each import declaration specifies the path of one or more packages in the parentheses. For example:
// Importing single package
import "fmt"
// Importing multiple packages
import(
"fmt"
"strings"
"bytes"
)
When you import a package in your program you’re allowed to access the members of that package. For example, we have a package named as a “sort”, so when you import this package in your program you are allowed to access sort.Float64s(), sort.SearchStrings(), etc functions of that package.
4. Blank import: In Go programming, sometimes we import some packages in our program, but we do not use them in our program. When you run such types of programs that contain unused packages, then the compiler will give an error. So, to avoid this error, we use a blank identifier before the name of the package. For example:
import _ "strings"
It is known as blank import. It is used in many or some occasions when the main program can enable the optional features provided by the blank importing additional packages at the compile-time.
5. Nested Packages: In Go language, you are allowed to create a package inside another package simply by creating a subdirectory. And the nested package can import just like the root package. For example:
import "math/cmplx"
Here, the math package is the main package and cmplx package is the nested package.
6. Sometimes some packages may have the same names, but the path of such type of packages is always different. For example, both math and crypto packages contain a rand named package, but the path of this package is different, i.e, math/rand and crypto/rand.
7. In Go programming, why always the main package is present on the top of the program? Because the main package tells the go build that it must activate the linker to make an executable file.
In Go language, when you name a package you must always follow the following points:
When you create a package the name of the package must be short and simple. For example strings, time, flag, etc. are standard library package.
The package name should be descriptive and unambiguous.
Always try to avoid choosing names that are commonly used or used for local relative variables.
The name of the package generally in the singular form. Sometimes some packages named in plural form like strings, bytes, buffers, etc. Because to avoid conflicts with the keywords.
Always avoid package names that already have other connotations. For example:
Example:
// Go program to illustrate the// concept of packages// Package declarationpackage main // Importing multiple packagesimport ( "bytes" "fmt" "sort") func main() { // Creating and initializing slice // Using shorthand declaration slice_1 := []byte{'*', 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', '^', '^'} slice_2 := []string{"Gee", "ks", "for", "Gee", "ks"} // Displaying slices fmt.Println("Original Slice:") fmt.Printf("Slice 1 : %s", slice_1) fmt.Println("\nSlice 2: ", slice_2) // Trimming specified leading // and trailing Unicode points // from the given slice of bytes // Using Trim function res := bytes.Trim(slice_1, "*^") fmt.Printf("\nNew Slice : %s", res) // Sorting slice 2 // Using Strings function sort.Strings(slice_2) fmt.Println("\nSorted slice:", slice_2)}
Output:
Original Slice:
Slice 1 : *GeeksforGeeks^^
Slice 2: [Gee ks for Gee ks]
New Slice : GeeksforGeeks
Sorted slice: [Gee Gee for ks ks]
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Nov, 2019"
},
{
"code": null,
"e": 565,
"s": 28,
"text": "Packages are the most powerful part of the Go language. The purpose of a package is to design and maintain a large number of programs by grouping related features together into single units so that they can be easy to maintain and understand and independent of the other package programs. This modularity allows them to share and reuse. In Go language, every package is defined with a different name and that name is close to their functionality like “strings” package and it contains methods and functions that only related to strings."
},
{
"code": null,
"e": 770,
"s": 565,
"text": "1. Import paths: In Go language, every package is defined by a unique string and this string is known as import path. With the help of an import path, you can import packages in your program. For example:"
},
{
"code": null,
"e": 783,
"s": 770,
"text": "import \"fmt\""
},
{
"code": null,
"e": 1116,
"s": 783,
"text": "This statement states that you are importing an fmt package in your program. The import path of packages is globally unique. To avoid conflict between the path of the packages other than the standard library, the package path should start with the internet domain name of the organization that owns or host the package. For example:"
},
{
"code": null,
"e": 1159,
"s": 1116,
"text": "import \"geeksforgeeks.com/example/strings\""
},
{
"code": null,
"e": 1418,
"s": 1159,
"text": "2. Package Declaration: In Go language, package declaration is always present at the beginning of the source file and the purpose of this declaration is to determine the default identifier for that package when it is imported by another package. For example:"
},
{
"code": null,
"e": 1431,
"s": 1418,
"text": "package main"
},
{
"code": null,
"e": 1690,
"s": 1431,
"text": "3. Import declaration: The import declaration immediately comes after the package declaration. The Go source file contains zero or more import declaration and each import declaration specifies the path of one or more packages in the parentheses. For example:"
},
{
"code": null,
"e": 1799,
"s": 1690,
"text": "// Importing single package\nimport \"fmt\"\n\n// Importing multiple packages\nimport(\n\"fmt\"\n\"strings\"\n\"bytes\"\n) \n"
},
{
"code": null,
"e": 2089,
"s": 1799,
"text": "When you import a package in your program you’re allowed to access the members of that package. For example, we have a package named as a “sort”, so when you import this package in your program you are allowed to access sort.Float64s(), sort.SearchStrings(), etc functions of that package."
},
{
"code": null,
"e": 2414,
"s": 2089,
"text": "4. Blank import: In Go programming, sometimes we import some packages in our program, but we do not use them in our program. When you run such types of programs that contain unused packages, then the compiler will give an error. So, to avoid this error, we use a blank identifier before the name of the package. For example:"
},
{
"code": null,
"e": 2433,
"s": 2414,
"text": "import _ \"strings\""
},
{
"code": null,
"e": 2627,
"s": 2433,
"text": "It is known as blank import. It is used in many or some occasions when the main program can enable the optional features provided by the blank importing additional packages at the compile-time."
},
{
"code": null,
"e": 2832,
"s": 2627,
"text": "5. Nested Packages: In Go language, you are allowed to create a package inside another package simply by creating a subdirectory. And the nested package can import just like the root package. For example:"
},
{
"code": null,
"e": 2852,
"s": 2832,
"text": "import \"math/cmplx\""
},
{
"code": null,
"e": 2936,
"s": 2852,
"text": "Here, the math package is the main package and cmplx package is the nested package."
},
{
"code": null,
"e": 3195,
"s": 2936,
"text": "6. Sometimes some packages may have the same names, but the path of such type of packages is always different. For example, both math and crypto packages contain a rand named package, but the path of this package is different, i.e, math/rand and crypto/rand."
},
{
"code": null,
"e": 3388,
"s": 3195,
"text": "7. In Go programming, why always the main package is present on the top of the program? Because the main package tells the go build that it must activate the linker to make an executable file."
},
{
"code": null,
"e": 3473,
"s": 3388,
"text": "In Go language, when you name a package you must always follow the following points:"
},
{
"code": null,
"e": 3617,
"s": 3473,
"text": "When you create a package the name of the package must be short and simple. For example strings, time, flag, etc. are standard library package."
},
{
"code": null,
"e": 3673,
"s": 3617,
"text": "The package name should be descriptive and unambiguous."
},
{
"code": null,
"e": 3769,
"s": 3673,
"text": "Always try to avoid choosing names that are commonly used or used for local relative variables."
},
{
"code": null,
"e": 3951,
"s": 3769,
"text": "The name of the package generally in the singular form. Sometimes some packages named in plural form like strings, bytes, buffers, etc. Because to avoid conflicts with the keywords."
},
{
"code": null,
"e": 4029,
"s": 3951,
"text": "Always avoid package names that already have other connotations. For example:"
},
{
"code": null,
"e": 4038,
"s": 4029,
"text": "Example:"
},
{
"code": "// Go program to illustrate the// concept of packages// Package declarationpackage main // Importing multiple packagesimport ( \"bytes\" \"fmt\" \"sort\") func main() { // Creating and initializing slice // Using shorthand declaration slice_1 := []byte{'*', 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', '^', '^'} slice_2 := []string{\"Gee\", \"ks\", \"for\", \"Gee\", \"ks\"} // Displaying slices fmt.Println(\"Original Slice:\") fmt.Printf(\"Slice 1 : %s\", slice_1) fmt.Println(\"\\nSlice 2: \", slice_2) // Trimming specified leading // and trailing Unicode points // from the given slice of bytes // Using Trim function res := bytes.Trim(slice_1, \"*^\") fmt.Printf(\"\\nNew Slice : %s\", res) // Sorting slice 2 // Using Strings function sort.Strings(slice_2) fmt.Println(\"\\nSorted slice:\", slice_2)}",
"e": 4916,
"s": 4038,
"text": null
},
{
"code": null,
"e": 4924,
"s": 4916,
"text": "Output:"
},
{
"code": null,
"e": 5059,
"s": 4924,
"text": "Original Slice:\nSlice 1 : *GeeksforGeeks^^\nSlice 2: [Gee ks for Gee ks]\n\nNew Slice : GeeksforGeeks\nSorted slice: [Gee Gee for ks ks]\n"
},
{
"code": null,
"e": 5071,
"s": 5059,
"text": "Go Language"
}
]
|
Timing Functions With Decorators – Python | 05 Apr, 2021
Everything in Python is an object. Functions in Python also object. Hence, like any other object they can be referenced by variables, stored in data structures like dictionary or list, passed as an argument to another function, and returned as a value from another function. In this article, we are going to see the timing function with decorators.
Decorator: A decorator is used to supercharge or modify a function. A decorator is a higher-order function that wraps another function and enhances it or changes it.
Example :
The best way to explain what it is by coding our own decorator. Suppose, you want to print * 10 times before and after the output of some function. It would be very inconvenient to use print statements in every function again and again. We can do this efficiently with the help of a decorator.
Code:
Python3
def my_decorator(func): def wrapper_function(*args, **kwargs): print("*"*10) func(*args, **kwargs) print("*"*10) return wrapper_function def say_hello(): print("Hello Geeks!") @my_decoratordef say_bye(): print("Bye Geeks!") say_hello = my_decorator(say_hello)say_hello()say_bye()
Output:
**********
Hello Geeks!
**********
**********
Bye Geeks!
**********
Explanation :
In the above example, my_decorator is a decorator function, which accepts func, a function object as an argument. It defines a wrapper_function which calls func and executes the code that it contains as well. The my_decorator function returns this wrapper_function.
So, what happens when we write @my_decorator before defining any function? Consider the example of the say_hello function above which is not decorated by any decorator at the time of definition. We can still use our decorator for decorating its output by calling the my_decorator function and passing the say_hello function object as a parameter, which will return a wrapper_function with two print statements, calling the say_hello() function in between. If we receive this modified function in the say_hello object itself, whenever we call say_hello() we’ll get the modified output.
Instead of writing this complex syntax, we can simply write @my_decorator before defining the function and leave the rest of the work for python interpreter as shown in the case of say_bye function.
The timer function is one of the applications of decorators. In the below example, we have made a timer_func function that accepts a function object func. Inside the timer function, we have defined wrap_func which can take any number of arguments (*args) and any number of keyword arguments (**kwargs) passed to it. We did this to make our timer_func more flexible.
In the body of wrap_func, we recorded the current time t1 using the time method of the time module, then we have called the function func passing the same parameters (*args, **kwargs) that were received by wrap_func and stored the returned value in the result. Now we have again recorded the current time t2 and printed the difference between the recorded times i.e. { t2 – t1 } with precision up to the 4th decimal place. This {t2 – t1} is the time passed during the execution of the function func. At last, we have returned the result value inside wrap_func function and returned this wrap_func function inside timer_func function.
We have also defined the long_time function using @timer_func decorator, so whenever we call long_time function it will be called like :
timer_func(long_time)(5)
The timer_func function when called passing long_time as a parameter returns a wrap_func function and a function object func starts pointing to the long_time function.
wrap_func(5)
Now the wrap_func will execute as explained above and the result is returned.
Python3
from time import time def timer_func(func): # This function shows the execution time of # the function object passed def wrap_func(*args, **kwargs): t1 = time() result = func(*args, **kwargs) t2 = time() print(f'Function {func.__name__!r} executed in {(t2-t1):.4f}s') return result return wrap_func @timer_funcdef long_time(n): for i in range(n): for j in range(100000): i*j long_time(5)
Output:
Function 'long_time' executed in 0.0219s
Picked
Python Decorators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 401,
"s": 52,
"text": "Everything in Python is an object. Functions in Python also object. Hence, like any other object they can be referenced by variables, stored in data structures like dictionary or list, passed as an argument to another function, and returned as a value from another function. In this article, we are going to see the timing function with decorators."
},
{
"code": null,
"e": 568,
"s": 401,
"text": "Decorator: A decorator is used to supercharge or modify a function. A decorator is a higher-order function that wraps another function and enhances it or changes it. "
},
{
"code": null,
"e": 578,
"s": 568,
"text": "Example :"
},
{
"code": null,
"e": 872,
"s": 578,
"text": "The best way to explain what it is by coding our own decorator. Suppose, you want to print * 10 times before and after the output of some function. It would be very inconvenient to use print statements in every function again and again. We can do this efficiently with the help of a decorator."
},
{
"code": null,
"e": 878,
"s": 872,
"text": "Code:"
},
{
"code": null,
"e": 886,
"s": 878,
"text": "Python3"
},
{
"code": "def my_decorator(func): def wrapper_function(*args, **kwargs): print(\"*\"*10) func(*args, **kwargs) print(\"*\"*10) return wrapper_function def say_hello(): print(\"Hello Geeks!\") @my_decoratordef say_bye(): print(\"Bye Geeks!\") say_hello = my_decorator(say_hello)say_hello()say_bye()",
"e": 1207,
"s": 886,
"text": null
},
{
"code": null,
"e": 1215,
"s": 1207,
"text": "Output:"
},
{
"code": null,
"e": 1283,
"s": 1215,
"text": "**********\nHello Geeks!\n**********\n**********\nBye Geeks!\n**********"
},
{
"code": null,
"e": 1297,
"s": 1283,
"text": "Explanation :"
},
{
"code": null,
"e": 1563,
"s": 1297,
"text": "In the above example, my_decorator is a decorator function, which accepts func, a function object as an argument. It defines a wrapper_function which calls func and executes the code that it contains as well. The my_decorator function returns this wrapper_function."
},
{
"code": null,
"e": 2148,
"s": 1563,
"text": "So, what happens when we write @my_decorator before defining any function? Consider the example of the say_hello function above which is not decorated by any decorator at the time of definition. We can still use our decorator for decorating its output by calling the my_decorator function and passing the say_hello function object as a parameter, which will return a wrapper_function with two print statements, calling the say_hello() function in between. If we receive this modified function in the say_hello object itself, whenever we call say_hello() we’ll get the modified output."
},
{
"code": null,
"e": 2347,
"s": 2148,
"text": "Instead of writing this complex syntax, we can simply write @my_decorator before defining the function and leave the rest of the work for python interpreter as shown in the case of say_bye function."
},
{
"code": null,
"e": 2714,
"s": 2347,
"text": "The timer function is one of the applications of decorators. In the below example, we have made a timer_func function that accepts a function object func. Inside the timer function, we have defined wrap_func which can take any number of arguments (*args) and any number of keyword arguments (**kwargs) passed to it. We did this to make our timer_func more flexible. "
},
{
"code": null,
"e": 3348,
"s": 2714,
"text": "In the body of wrap_func, we recorded the current time t1 using the time method of the time module, then we have called the function func passing the same parameters (*args, **kwargs) that were received by wrap_func and stored the returned value in the result. Now we have again recorded the current time t2 and printed the difference between the recorded times i.e. { t2 – t1 } with precision up to the 4th decimal place. This {t2 – t1} is the time passed during the execution of the function func. At last, we have returned the result value inside wrap_func function and returned this wrap_func function inside timer_func function."
},
{
"code": null,
"e": 3485,
"s": 3348,
"text": "We have also defined the long_time function using @timer_func decorator, so whenever we call long_time function it will be called like :"
},
{
"code": null,
"e": 3510,
"s": 3485,
"text": "timer_func(long_time)(5)"
},
{
"code": null,
"e": 3678,
"s": 3510,
"text": "The timer_func function when called passing long_time as a parameter returns a wrap_func function and a function object func starts pointing to the long_time function."
},
{
"code": null,
"e": 3691,
"s": 3678,
"text": "wrap_func(5)"
},
{
"code": null,
"e": 3769,
"s": 3691,
"text": "Now the wrap_func will execute as explained above and the result is returned."
},
{
"code": null,
"e": 3777,
"s": 3769,
"text": "Python3"
},
{
"code": "from time import time def timer_func(func): # This function shows the execution time of # the function object passed def wrap_func(*args, **kwargs): t1 = time() result = func(*args, **kwargs) t2 = time() print(f'Function {func.__name__!r} executed in {(t2-t1):.4f}s') return result return wrap_func @timer_funcdef long_time(n): for i in range(n): for j in range(100000): i*j long_time(5)",
"e": 4243,
"s": 3777,
"text": null
},
{
"code": null,
"e": 4251,
"s": 4243,
"text": "Output:"
},
{
"code": null,
"e": 4292,
"s": 4251,
"text": "Function 'long_time' executed in 0.0219s"
},
{
"code": null,
"e": 4299,
"s": 4292,
"text": "Picked"
},
{
"code": null,
"e": 4317,
"s": 4299,
"text": "Python Decorators"
},
{
"code": null,
"e": 4324,
"s": 4317,
"text": "Python"
}
]
|
Nearest prime less than given number n | 22 Apr, 2022
You are given a number n ( 3 <= n < 10^6 ) and you have to find nearest prime less than n?
Examples:
Input : n = 10
Output: 7
Input : n = 17
Output: 13
Input : n = 30
Output: 29
A simple solution for this problem is to iterate from n-1 to 2, and for every number, check if it is a prime. If prime, then return it and break the loop. This solution looks fine if there is only one query. But not efficient if there are multiple queries for different values of n.
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 return nearest prime numberint prime(int n){ // All prime numbers are odd except two if (n & 1) n -= 2; else n--; int i, j; for (i = n; i >= 2; i -= 2) { if (i % 2 == 0) continue; for (j = 3; j <= sqrt(i); j += 2) { if (i % j == 0) break; } if (j > sqrt(i)) return i; } // It will only be executed when n is 3 return 2;} // Driver Codeint main(){ int n = 17; cout << prime(n); return 0;}
// Java program for the above approach import java.io.*; class GFG { // Function to return nearest prime number static int prime(int n) { // All prime numbers are odd except two if (n % 2 != 0) n -= 2; else n--; int i, j; for (i = n; i >= 2; i -= 2) { if (i % 2 == 0) continue; for (j = 3; j <= Math.sqrt(i); j += 2) { if (i % j == 0) break; } if (j > Math.sqrt(i)) return i; } // It will only be executed when n is 3 return 2; } // Driver Code public static void main(String[] args) { int n = 17; System.out.print(prime(n)); }} // This code is contributed by subham348.
# Python program for the above approach # Function to return nearest prime numberfrom math import floor, sqrt def prime(n): # All prime numbers are odd except two if (n & 1): n -= 2 else: n -= 1 i,j = 0,3 for i in range(n, 2, -2): if(i % 2 == 0): continue while(j <= floor(sqrt(i)) + 1): if (i % j == 0): break j += 2 if (j > floor(sqrt(i))): return i # It will only be executed when n is 3 return 2 # Driver Coden = 17 print(prime(n)) # This code is contributed by shinjanpatra
// C# program for the above approachusing System; class GFG{ // Function to return nearest prime number static int prime(int n) { // All prime numbers are odd except two if (n % 2 != 0) n -= 2; else n--; int i, j; for (i = n; i >= 2; i -= 2) { if (i % 2 == 0) continue; for (j = 3; j <= Math.Sqrt(i); j += 2) { if (i % j == 0) break; } if (j > Math.Sqrt(i)) return i; } // It will only be executed when n is 3 return 2; } // Driver Code public static void Main() { int n = 17; Console.Write(prime(n)); }} // This code is contributed by subham348.
<script> // Javascript program for the above approach // Function to return nearest prime numberfunction prime(n){ // All prime numbers are odd except two if (n & 1) n -= 2; else n--; let i, j; for(i = n; i >= 2; i -= 2) { if (i % 2 == 0) continue; for(j = 3; j <= Math.sqrt(i); j += 2) { if (i % j == 0) break; } if (j > Math.sqrt(i)) return i; } // It will only be executed when n is 3 return 2;} // Driver Codelet n = 17; document.write(prime(n)); // This code is contributed by souravmahato348 </script>
13
An efficient solution for this problem is to generate all primes less than 10^6 using Sieve of Sundaram and store then in a array in increasing order. Now apply modified binary search to search nearest prime less than n. Time complexity of this solution is O(n log n + log n) = O(n log n).
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the nearest prime to n.#include<bits/stdc++.h>#define MAX 1000000using namespace std; // array to store all primes less than 10^6vector<int> primes; // Utility function of Sieve of Sundaramvoid Sieve(){ int n = MAX; // In general Sieve of Sundaram, produces primes // smaller than (2*x + 2) for a number given // number x int nNew = sqrt(n); // This array is used to separate numbers of the // form i+j+2ij from others where 1 <= i <= j int marked[n/2+500] = {0}; // eliminate indexes which does not produce primes for (int i=1; i<=(nNew-1)/2; i++) for (int j=(i*(i+1))<<1; j<=n/2; j=j+2*i+1) marked[j] = 1; // Since 2 is a prime number primes.push_back(2); // Remaining primes are of the form 2*i + 1 such // that marked[i] is false. for (int i=1; i<=n/2; i++) if (marked[i] == 0) primes.push_back(2*i + 1);} // modified binary search to find nearest prime less than Nint binarySearch(int left,int right,int n){ if (left<=right) { int mid = (left + right)/2; // base condition is, if we are reaching at left // corner or right corner of primes[] array then // return that corner element because before or // after that we don't have any prime number in // primes array if (mid == 0 || mid == primes.size()-1) return primes[mid]; // now if n is itself a prime so it will be present // in primes array and here we have to find nearest // prime less than n so we will return primes[mid-1] if (primes[mid] == n) return primes[mid-1]; // now if primes[mid]<n and primes[mid+1]>n that // mean we reached at nearest prime if (primes[mid] < n && primes[mid+1] > n) return primes[mid]; if (n < primes[mid]) return binarySearch(left, mid-1, n); else return binarySearch(mid+1, right, n); } return 0;} // Driver program to run the caseint main(){ Sieve(); int n = 17; cout << binarySearch(0, primes.size()-1, n); return 0;}
// Java program to find the nearest prime to n.import java.util.*; class GFG{ static int MAX=1000000; // array to store all primes less than 10^6static ArrayList<Integer> primes = new ArrayList<Integer>(); // Utility function of Sieve of Sundaramstatic void Sieve(){ int n = MAX; // In general Sieve of Sundaram, produces primes // smaller than (2*x + 2) for a number given // number x int nNew = (int)Math.sqrt(n); // This array is used to separate numbers of the // form i+j+2ij from others where 1 <= i <= j int[] marked = new int[n / 2 + 500]; // eliminate indexes which does not produce primes for (int i = 1; i <= (nNew - 1) / 2; i++) for (int j = (i * (i + 1)) << 1; j <= n / 2; j = j + 2 * i + 1) marked[j] = 1; // Since 2 is a prime number primes.add(2); // Remaining primes are of the form 2*i + 1 such // that marked[i] is false. for (int i = 1; i <= n / 2; i++) if (marked[i] == 0) primes.add(2 * i + 1);} // modified binary search to find nearest prime less than Nstatic int binarySearch(int left,int right,int n){ if (left <= right) { int mid = (left + right) / 2; // base condition is, if we are reaching at left // corner or right corner of primes[] array then // return that corner element because before or // after that we don't have any prime number in // primes array if (mid == 0 || mid == primes.size() - 1) return primes.get(mid); // now if n is itself a prime so it will be present // in primes array and here we have to find nearest // prime less than n so we will return primes[mid-1] if (primes.get(mid) == n) return primes.get(mid - 1); // now if primes[mid]<n and primes[mid+1]>n that // mean we reached at nearest prime if (primes.get(mid) < n && primes.get(mid + 1) > n) return primes.get(mid); if (n < primes.get(mid)) return binarySearch(left, mid - 1, n); else return binarySearch(mid + 1, right, n); } return 0;} // Driver codepublic static void main (String[] args){ Sieve(); int n = 17; System.out.println(binarySearch(0, primes.size() - 1, n));}} // This code is contributed by mits
# Python3 program to find the nearest# prime to n.import mathMAX = 10000; # array to store all primes less# than 10^6primes = []; # Utility function of Sieve of Sundaramdef Sieve(): n = MAX; # In general Sieve of Sundaram, produces # primes smaller than (2*x + 2) for a # number given number x nNew = int(math.sqrt(n)); # This array is used to separate numbers # of the form i+j+2ij from others where # 1 <= i <= j marked = [0] * (int(n / 2 + 500)); # eliminate indexes which does not # produce primes for i in range(1, int((nNew - 1) / 2) + 1): for j in range(((i * (i + 1)) << 1), (int(n / 2) + 1), (2 * i + 1)): marked[j] = 1; # Since 2 is a prime number primes.append(2); # Remaining primes are of the form # 2*i + 1 such that marked[i] is false. for i in range(1, int(n / 2) + 1): if (marked[i] == 0): primes.append(2 * i + 1); # modified binary search to find nearest# prime less than Ndef binarySearch(left, right, n): if (left <= right): mid = int((left + right) / 2); # base condition is, if we are reaching # at left corner or right corner of # primes[] array then return that corner # element because before or after that # we don't have any prime number in # primes array if (mid == 0 or mid == len(primes) - 1): return primes[mid]; # now if n is itself a prime so it will # be present in primes array and here # we have to find nearest prime less than # n so we will return primes[mid-1] if (primes[mid] == n): return primes[mid - 1]; # now if primes[mid]<n and primes[mid+1]>n # that means we reached at nearest prime if (primes[mid] < n and primes[mid + 1] > n): return primes[mid]; if (n < primes[mid]): return binarySearch(left, mid - 1, n); else: return binarySearch(mid + 1, right, n); return 0; # Driver CodeSieve();n = 17;print(binarySearch(0, len(primes) - 1, n)); # This code is contributed by chandan_jnu
// C# program to find the nearest prime to n.using System;using System.Collections;class GFG{ static int MAX = 1000000; // array to store all primes less than 10^6static ArrayList primes = new ArrayList(); // Utility function of Sieve of Sundaramstatic void Sieve(){ int n = MAX; // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x int nNew = (int)Math.Sqrt(n); // This array is used to separate numbers of the // form i+j+2ij from others where 1 <= i <= j int[] marked = new int[n / 2 + 500]; // eliminate indexes which does not produce primes for (int i = 1; i <= (nNew - 1) / 2; i++) for (int j = (i * (i + 1)) << 1; j <= n / 2; j = j + 2 * i + 1) marked[j] = 1; // Since 2 is a prime number primes.Add(2); // Remaining primes are of the form 2*i + 1 // such that marked[i] is false. for (int i = 1; i <= n / 2; i++) if (marked[i] == 0) primes.Add(2 * i + 1);} // modified binary search to find// nearest prime less than Nstatic int binarySearch(int left, int right, int n){ if (left <= right) { int mid = (left + right) / 2; // base condition is, if we are reaching at left // corner or right corner of primes[] array then // return that corner element because before or // after that we don't have any prime number in // primes array if (mid == 0 || mid == primes.Count - 1) return (int)primes[mid]; // now if n is itself a prime so it will be // present in primes array and here we have // to find nearest prime less than n so we // will return primes[mid-1] if ((int)primes[mid] == n) return (int)primes[mid - 1]; // now if primes[mid]<n and primes[mid+1]>n // that mean we reached at nearest prime if ((int)primes[mid] < n && (int)primes[mid + 1] > n) return (int)primes[mid]; if (n < (int)primes[mid]) return binarySearch(left, mid - 1, n); else return binarySearch(mid + 1, right, n); } return 0;} // Driver codestatic void Main(){ Sieve(); int n = 17; Console.WriteLine(binarySearch(0, primes.Count - 1, n));}} // This code is contributed by chandan_jnu
<?php// PHP program to find the nearest// prime to n. $MAX = 10000; // array to store all primes less// than 10^6$primes = array(); // Utility function of Sieve of Sundaramfunction Sieve(){ global $MAX, $primes; $n = $MAX; // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x $nNew = (int)(sqrt($n)); // This array is used to separate numbers // of the form i+j+2ij from others where // 1 <= i <= j $marked = array_fill(0, (int)($n / 2 + 500), 0); // eliminate indexes which does not // produce primes for ($i = 1; $i <= ($nNew - 1) / 2; $i++) for ($j = ($i * ($i + 1)) << 1; $j <= $n / 2; $j = $j + 2 * $i + 1) $marked[$j] = 1; // Since 2 is a prime number array_push($primes, 2); // Remaining primes are of the form // 2*i + 1 such that marked[i] is false. for ($i = 1; $i <= $n / 2; $i++) if ($marked[$i] == 0) array_push($primes, 2 * $i + 1);} // modified binary search to find nearest// prime less than Nfunction binarySearch($left, $right, $n){ global $primes; if ($left <= $right) { $mid = (int)(($left + $right) / 2); // base condition is, if we are reaching // at left corner or right corner of // primes[] array then return that corner // element because before or after that // we don't have any prime number in // primes array if ($mid == 0 || $mid == count($primes) - 1) return $primes[$mid]; // now if n is itself a prime so it will // be present in primes array and here // we have to find nearest prime less than // n so we will return primes[mid-1] if ($primes[$mid] == $n) return $primes[$mid - 1]; // now if primes[mid]<n and primes[mid+1]>n // that means we reached at nearest prime if ($primes[$mid] < $n && $primes[$mid + 1] > $n) return $primes[$mid]; if ($n < $primes[$mid]) return binarySearch($left, $mid - 1, $n); else return binarySearch($mid + 1, $right, $n); } return 0;} // Driver CodeSieve();$n = 17;echo binarySearch(0, count($primes) - 1, $n); // This code is contributed by chandan_jnu?>
<script> // JavaScript program to find the nearest prime to n. // array to store all primes less than 10^6 var primes = []; // Utility function of Sieve of Sundaram var MAX = 1000000; function Sieve() { let n = MAX; // In general Sieve of Sundaram, produces primes // smaller than (2*x + 2) for a number given // number x let nNew = parseInt(Math.sqrt(n)); // This array is used to separate numbers of the // form i+j+2ij from others where 1 <= i <= j var marked = new Array(n / 2 + 500).fill(0); // eliminate indexes which does not produce primes for (let i = 1; i <= parseInt((nNew - 1) / 2); i++) for (let j = (i * (i + 1)) << 1; j <= parseInt(n / 2); j = j + 2 * i + 1) marked[j] = 1; // Since 2 is a prime number primes.push(2); // Remaining primes are of the form 2*i + 1 such // that marked[i] is false. for (let i = 1; i <= parseInt(n / 2); i++) if (marked[i] == 0) primes.push(2 * i + 1); } // modified binary search to find nearest prime less than N function binarySearch(left, right, n) { if (left <= right) { let mid = parseInt((left + right) / 2); // base condition is, if we are reaching at left // corner or right corner of primes[] array then // return that corner element because before or // after that we don't have any prime number in // primes array if (mid == 0 || mid == primes.length - 1) return primes[mid]; // now if n is itself a prime so it will be present // in primes array and here we have to find nearest // prime less than n so we will return primes[mid-1] if (primes[mid] == n) return primes[mid - 1]; // now if primes[mid]<n and primes[mid+1]>n that // mean we reached at nearest prime if (primes[mid] < n && primes[mid + 1] > n) return primes[mid]; if (n < primes[mid]) return binarySearch(left, mid - 1, n); else return binarySearch(mid + 1, right, n); } return 0; } // Driver program to run the case Sieve(); let n = 17; document.write(binarySearch(0, primes.length - 1, n)); // This code is contributed by Potta Lokesh </script>
13
If you have another approach to solve this problem then please share in comments.This article is contributed by Shashank Mishra ( Gullu ). 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.
Mithun Kumar
Chandan_Kumar
subhammahato348
subham348
souravmahato348
lokeshpotta20
sooda367
shinjanpatra
Binary Search
MAQ Software
Prime Number
sieve
Mathematical
MAQ Software
Mathematical
Prime Number
sieve
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 145,
"s": 54,
"text": "You are given a number n ( 3 <= n < 10^6 ) and you have to find nearest prime less than n?"
},
{
"code": null,
"e": 156,
"s": 145,
"text": "Examples: "
},
{
"code": null,
"e": 236,
"s": 156,
"text": "Input : n = 10\nOutput: 7\n\nInput : n = 17\nOutput: 13\n\nInput : n = 30\nOutput: 29 "
},
{
"code": null,
"e": 519,
"s": 236,
"text": "A simple solution for this problem is to iterate from n-1 to 2, and for every number, check if it is a prime. If prime, then return it and break the loop. This solution looks fine if there is only one query. But not efficient if there are multiple queries for different values of n."
},
{
"code": null,
"e": 570,
"s": 519,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 574,
"s": 570,
"text": "C++"
},
{
"code": null,
"e": 579,
"s": 574,
"text": "Java"
},
{
"code": null,
"e": 587,
"s": 579,
"text": "Python3"
},
{
"code": null,
"e": 590,
"s": 587,
"text": "C#"
},
{
"code": null,
"e": 601,
"s": 590,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to return nearest prime numberint prime(int n){ // All prime numbers are odd except two if (n & 1) n -= 2; else n--; int i, j; for (i = n; i >= 2; i -= 2) { if (i % 2 == 0) continue; for (j = 3; j <= sqrt(i); j += 2) { if (i % j == 0) break; } if (j > sqrt(i)) return i; } // It will only be executed when n is 3 return 2;} // Driver Codeint main(){ int n = 17; cout << prime(n); return 0;}",
"e": 1213,
"s": 601,
"text": null
},
{
"code": "// Java program for the above approach import java.io.*; class GFG { // Function to return nearest prime number static int prime(int n) { // All prime numbers are odd except two if (n % 2 != 0) n -= 2; else n--; int i, j; for (i = n; i >= 2; i -= 2) { if (i % 2 == 0) continue; for (j = 3; j <= Math.sqrt(i); j += 2) { if (i % j == 0) break; } if (j > Math.sqrt(i)) return i; } // It will only be executed when n is 3 return 2; } // Driver Code public static void main(String[] args) { int n = 17; System.out.print(prime(n)); }} // This code is contributed by subham348.",
"e": 2013,
"s": 1213,
"text": null
},
{
"code": "# Python program for the above approach # Function to return nearest prime numberfrom math import floor, sqrt def prime(n): # All prime numbers are odd except two if (n & 1): n -= 2 else: n -= 1 i,j = 0,3 for i in range(n, 2, -2): if(i % 2 == 0): continue while(j <= floor(sqrt(i)) + 1): if (i % j == 0): break j += 2 if (j > floor(sqrt(i))): return i # It will only be executed when n is 3 return 2 # Driver Coden = 17 print(prime(n)) # This code is contributed by shinjanpatra",
"e": 2622,
"s": 2013,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to return nearest prime number static int prime(int n) { // All prime numbers are odd except two if (n % 2 != 0) n -= 2; else n--; int i, j; for (i = n; i >= 2; i -= 2) { if (i % 2 == 0) continue; for (j = 3; j <= Math.Sqrt(i); j += 2) { if (i % j == 0) break; } if (j > Math.Sqrt(i)) return i; } // It will only be executed when n is 3 return 2; } // Driver Code public static void Main() { int n = 17; Console.Write(prime(n)); }} // This code is contributed by subham348.",
"e": 3398,
"s": 2622,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to return nearest prime numberfunction prime(n){ // All prime numbers are odd except two if (n & 1) n -= 2; else n--; let i, j; for(i = n; i >= 2; i -= 2) { if (i % 2 == 0) continue; for(j = 3; j <= Math.sqrt(i); j += 2) { if (i % j == 0) break; } if (j > Math.sqrt(i)) return i; } // It will only be executed when n is 3 return 2;} // Driver Codelet n = 17; document.write(prime(n)); // This code is contributed by souravmahato348 </script>",
"e": 4037,
"s": 3398,
"text": null
},
{
"code": null,
"e": 4040,
"s": 4037,
"text": "13"
},
{
"code": null,
"e": 4330,
"s": 4040,
"text": "An efficient solution for this problem is to generate all primes less than 10^6 using Sieve of Sundaram and store then in a array in increasing order. Now apply modified binary search to search nearest prime less than n. Time complexity of this solution is O(n log n + log n) = O(n log n)."
},
{
"code": null,
"e": 4334,
"s": 4330,
"text": "C++"
},
{
"code": null,
"e": 4339,
"s": 4334,
"text": "Java"
},
{
"code": null,
"e": 4347,
"s": 4339,
"text": "Python3"
},
{
"code": null,
"e": 4350,
"s": 4347,
"text": "C#"
},
{
"code": null,
"e": 4354,
"s": 4350,
"text": "PHP"
},
{
"code": null,
"e": 4365,
"s": 4354,
"text": "Javascript"
},
{
"code": "// C++ program to find the nearest prime to n.#include<bits/stdc++.h>#define MAX 1000000using namespace std; // array to store all primes less than 10^6vector<int> primes; // Utility function of Sieve of Sundaramvoid Sieve(){ int n = MAX; // In general Sieve of Sundaram, produces primes // smaller than (2*x + 2) for a number given // number x int nNew = sqrt(n); // This array is used to separate numbers of the // form i+j+2ij from others where 1 <= i <= j int marked[n/2+500] = {0}; // eliminate indexes which does not produce primes for (int i=1; i<=(nNew-1)/2; i++) for (int j=(i*(i+1))<<1; j<=n/2; j=j+2*i+1) marked[j] = 1; // Since 2 is a prime number primes.push_back(2); // Remaining primes are of the form 2*i + 1 such // that marked[i] is false. for (int i=1; i<=n/2; i++) if (marked[i] == 0) primes.push_back(2*i + 1);} // modified binary search to find nearest prime less than Nint binarySearch(int left,int right,int n){ if (left<=right) { int mid = (left + right)/2; // base condition is, if we are reaching at left // corner or right corner of primes[] array then // return that corner element because before or // after that we don't have any prime number in // primes array if (mid == 0 || mid == primes.size()-1) return primes[mid]; // now if n is itself a prime so it will be present // in primes array and here we have to find nearest // prime less than n so we will return primes[mid-1] if (primes[mid] == n) return primes[mid-1]; // now if primes[mid]<n and primes[mid+1]>n that // mean we reached at nearest prime if (primes[mid] < n && primes[mid+1] > n) return primes[mid]; if (n < primes[mid]) return binarySearch(left, mid-1, n); else return binarySearch(mid+1, right, n); } return 0;} // Driver program to run the caseint main(){ Sieve(); int n = 17; cout << binarySearch(0, primes.size()-1, n); return 0;}",
"e": 6483,
"s": 4365,
"text": null
},
{
"code": "// Java program to find the nearest prime to n.import java.util.*; class GFG{ static int MAX=1000000; // array to store all primes less than 10^6static ArrayList<Integer> primes = new ArrayList<Integer>(); // Utility function of Sieve of Sundaramstatic void Sieve(){ int n = MAX; // In general Sieve of Sundaram, produces primes // smaller than (2*x + 2) for a number given // number x int nNew = (int)Math.sqrt(n); // This array is used to separate numbers of the // form i+j+2ij from others where 1 <= i <= j int[] marked = new int[n / 2 + 500]; // eliminate indexes which does not produce primes for (int i = 1; i <= (nNew - 1) / 2; i++) for (int j = (i * (i + 1)) << 1; j <= n / 2; j = j + 2 * i + 1) marked[j] = 1; // Since 2 is a prime number primes.add(2); // Remaining primes are of the form 2*i + 1 such // that marked[i] is false. for (int i = 1; i <= n / 2; i++) if (marked[i] == 0) primes.add(2 * i + 1);} // modified binary search to find nearest prime less than Nstatic int binarySearch(int left,int right,int n){ if (left <= right) { int mid = (left + right) / 2; // base condition is, if we are reaching at left // corner or right corner of primes[] array then // return that corner element because before or // after that we don't have any prime number in // primes array if (mid == 0 || mid == primes.size() - 1) return primes.get(mid); // now if n is itself a prime so it will be present // in primes array and here we have to find nearest // prime less than n so we will return primes[mid-1] if (primes.get(mid) == n) return primes.get(mid - 1); // now if primes[mid]<n and primes[mid+1]>n that // mean we reached at nearest prime if (primes.get(mid) < n && primes.get(mid + 1) > n) return primes.get(mid); if (n < primes.get(mid)) return binarySearch(left, mid - 1, n); else return binarySearch(mid + 1, right, n); } return 0;} // Driver codepublic static void main (String[] args){ Sieve(); int n = 17; System.out.println(binarySearch(0, primes.size() - 1, n));}} // This code is contributed by mits",
"e": 8824,
"s": 6483,
"text": null
},
{
"code": "# Python3 program to find the nearest# prime to n.import mathMAX = 10000; # array to store all primes less# than 10^6primes = []; # Utility function of Sieve of Sundaramdef Sieve(): n = MAX; # In general Sieve of Sundaram, produces # primes smaller than (2*x + 2) for a # number given number x nNew = int(math.sqrt(n)); # This array is used to separate numbers # of the form i+j+2ij from others where # 1 <= i <= j marked = [0] * (int(n / 2 + 500)); # eliminate indexes which does not # produce primes for i in range(1, int((nNew - 1) / 2) + 1): for j in range(((i * (i + 1)) << 1), (int(n / 2) + 1), (2 * i + 1)): marked[j] = 1; # Since 2 is a prime number primes.append(2); # Remaining primes are of the form # 2*i + 1 such that marked[i] is false. for i in range(1, int(n / 2) + 1): if (marked[i] == 0): primes.append(2 * i + 1); # modified binary search to find nearest# prime less than Ndef binarySearch(left, right, n): if (left <= right): mid = int((left + right) / 2); # base condition is, if we are reaching # at left corner or right corner of # primes[] array then return that corner # element because before or after that # we don't have any prime number in # primes array if (mid == 0 or mid == len(primes) - 1): return primes[mid]; # now if n is itself a prime so it will # be present in primes array and here # we have to find nearest prime less than # n so we will return primes[mid-1] if (primes[mid] == n): return primes[mid - 1]; # now if primes[mid]<n and primes[mid+1]>n # that means we reached at nearest prime if (primes[mid] < n and primes[mid + 1] > n): return primes[mid]; if (n < primes[mid]): return binarySearch(left, mid - 1, n); else: return binarySearch(mid + 1, right, n); return 0; # Driver CodeSieve();n = 17;print(binarySearch(0, len(primes) - 1, n)); # This code is contributed by chandan_jnu",
"e": 10964,
"s": 8824,
"text": null
},
{
"code": "// C# program to find the nearest prime to n.using System;using System.Collections;class GFG{ static int MAX = 1000000; // array to store all primes less than 10^6static ArrayList primes = new ArrayList(); // Utility function of Sieve of Sundaramstatic void Sieve(){ int n = MAX; // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x int nNew = (int)Math.Sqrt(n); // This array is used to separate numbers of the // form i+j+2ij from others where 1 <= i <= j int[] marked = new int[n / 2 + 500]; // eliminate indexes which does not produce primes for (int i = 1; i <= (nNew - 1) / 2; i++) for (int j = (i * (i + 1)) << 1; j <= n / 2; j = j + 2 * i + 1) marked[j] = 1; // Since 2 is a prime number primes.Add(2); // Remaining primes are of the form 2*i + 1 // such that marked[i] is false. for (int i = 1; i <= n / 2; i++) if (marked[i] == 0) primes.Add(2 * i + 1);} // modified binary search to find// nearest prime less than Nstatic int binarySearch(int left, int right, int n){ if (left <= right) { int mid = (left + right) / 2; // base condition is, if we are reaching at left // corner or right corner of primes[] array then // return that corner element because before or // after that we don't have any prime number in // primes array if (mid == 0 || mid == primes.Count - 1) return (int)primes[mid]; // now if n is itself a prime so it will be // present in primes array and here we have // to find nearest prime less than n so we // will return primes[mid-1] if ((int)primes[mid] == n) return (int)primes[mid - 1]; // now if primes[mid]<n and primes[mid+1]>n // that mean we reached at nearest prime if ((int)primes[mid] < n && (int)primes[mid + 1] > n) return (int)primes[mid]; if (n < (int)primes[mid]) return binarySearch(left, mid - 1, n); else return binarySearch(mid + 1, right, n); } return 0;} // Driver codestatic void Main(){ Sieve(); int n = 17; Console.WriteLine(binarySearch(0, primes.Count - 1, n));}} // This code is contributed by chandan_jnu",
"e": 13319,
"s": 10964,
"text": null
},
{
"code": "<?php// PHP program to find the nearest// prime to n. $MAX = 10000; // array to store all primes less// than 10^6$primes = array(); // Utility function of Sieve of Sundaramfunction Sieve(){ global $MAX, $primes; $n = $MAX; // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x $nNew = (int)(sqrt($n)); // This array is used to separate numbers // of the form i+j+2ij from others where // 1 <= i <= j $marked = array_fill(0, (int)($n / 2 + 500), 0); // eliminate indexes which does not // produce primes for ($i = 1; $i <= ($nNew - 1) / 2; $i++) for ($j = ($i * ($i + 1)) << 1; $j <= $n / 2; $j = $j + 2 * $i + 1) $marked[$j] = 1; // Since 2 is a prime number array_push($primes, 2); // Remaining primes are of the form // 2*i + 1 such that marked[i] is false. for ($i = 1; $i <= $n / 2; $i++) if ($marked[$i] == 0) array_push($primes, 2 * $i + 1);} // modified binary search to find nearest// prime less than Nfunction binarySearch($left, $right, $n){ global $primes; if ($left <= $right) { $mid = (int)(($left + $right) / 2); // base condition is, if we are reaching // at left corner or right corner of // primes[] array then return that corner // element because before or after that // we don't have any prime number in // primes array if ($mid == 0 || $mid == count($primes) - 1) return $primes[$mid]; // now if n is itself a prime so it will // be present in primes array and here // we have to find nearest prime less than // n so we will return primes[mid-1] if ($primes[$mid] == $n) return $primes[$mid - 1]; // now if primes[mid]<n and primes[mid+1]>n // that means we reached at nearest prime if ($primes[$mid] < $n && $primes[$mid + 1] > $n) return $primes[$mid]; if ($n < $primes[$mid]) return binarySearch($left, $mid - 1, $n); else return binarySearch($mid + 1, $right, $n); } return 0;} // Driver CodeSieve();$n = 17;echo binarySearch(0, count($primes) - 1, $n); // This code is contributed by chandan_jnu?>",
"e": 15605,
"s": 13319,
"text": null
},
{
"code": "<script> // JavaScript program to find the nearest prime to n. // array to store all primes less than 10^6 var primes = []; // Utility function of Sieve of Sundaram var MAX = 1000000; function Sieve() { let n = MAX; // In general Sieve of Sundaram, produces primes // smaller than (2*x + 2) for a number given // number x let nNew = parseInt(Math.sqrt(n)); // This array is used to separate numbers of the // form i+j+2ij from others where 1 <= i <= j var marked = new Array(n / 2 + 500).fill(0); // eliminate indexes which does not produce primes for (let i = 1; i <= parseInt((nNew - 1) / 2); i++) for (let j = (i * (i + 1)) << 1; j <= parseInt(n / 2); j = j + 2 * i + 1) marked[j] = 1; // Since 2 is a prime number primes.push(2); // Remaining primes are of the form 2*i + 1 such // that marked[i] is false. for (let i = 1; i <= parseInt(n / 2); i++) if (marked[i] == 0) primes.push(2 * i + 1); } // modified binary search to find nearest prime less than N function binarySearch(left, right, n) { if (left <= right) { let mid = parseInt((left + right) / 2); // base condition is, if we are reaching at left // corner or right corner of primes[] array then // return that corner element because before or // after that we don't have any prime number in // primes array if (mid == 0 || mid == primes.length - 1) return primes[mid]; // now if n is itself a prime so it will be present // in primes array and here we have to find nearest // prime less than n so we will return primes[mid-1] if (primes[mid] == n) return primes[mid - 1]; // now if primes[mid]<n and primes[mid+1]>n that // mean we reached at nearest prime if (primes[mid] < n && primes[mid + 1] > n) return primes[mid]; if (n < primes[mid]) return binarySearch(left, mid - 1, n); else return binarySearch(mid + 1, right, n); } return 0; } // Driver program to run the case Sieve(); let n = 17; document.write(binarySearch(0, primes.length - 1, n)); // This code is contributed by Potta Lokesh </script>",
"e": 18243,
"s": 15605,
"text": null
},
{
"code": null,
"e": 18246,
"s": 18243,
"text": "13"
},
{
"code": null,
"e": 18760,
"s": 18246,
"text": "If you have another approach to solve this problem then please share in comments.This article is contributed by Shashank Mishra ( Gullu ). 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": 18773,
"s": 18760,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 18787,
"s": 18773,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 18803,
"s": 18787,
"text": "subhammahato348"
},
{
"code": null,
"e": 18813,
"s": 18803,
"text": "subham348"
},
{
"code": null,
"e": 18829,
"s": 18813,
"text": "souravmahato348"
},
{
"code": null,
"e": 18843,
"s": 18829,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 18852,
"s": 18843,
"text": "sooda367"
},
{
"code": null,
"e": 18865,
"s": 18852,
"text": "shinjanpatra"
},
{
"code": null,
"e": 18879,
"s": 18865,
"text": "Binary Search"
},
{
"code": null,
"e": 18892,
"s": 18879,
"text": "MAQ Software"
},
{
"code": null,
"e": 18905,
"s": 18892,
"text": "Prime Number"
},
{
"code": null,
"e": 18911,
"s": 18905,
"text": "sieve"
},
{
"code": null,
"e": 18924,
"s": 18911,
"text": "Mathematical"
},
{
"code": null,
"e": 18937,
"s": 18924,
"text": "MAQ Software"
},
{
"code": null,
"e": 18950,
"s": 18937,
"text": "Mathematical"
},
{
"code": null,
"e": 18963,
"s": 18950,
"text": "Prime Number"
},
{
"code": null,
"e": 18969,
"s": 18963,
"text": "sieve"
},
{
"code": null,
"e": 18983,
"s": 18969,
"text": "Binary Search"
}
]
|
JavaScript | Generator | 13 Jun, 2022
Like Python Generators, JavaScript also supports Generator functions and Generator Objects.Generator-Function : A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. The yield statement suspends function’s execution and sends a value back to caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. Syntax :
// An example of generator function
function* gen(){
yield 1;
yield 2;
...
...
}
Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for of” loop (as shown in the above program) The Generator object is returned by a generating function and it conforms to both the iterable protocol and the iterator protocol.
javascript
<script>// Generate Function generates three// different numbers in three callsfunction * fun(){ yield 10; yield 20; yield 30; } // Calling the Generate Functionvar gen = fun();document.write(gen.next().value);document.write("<br>");document.write(gen.next().value);document.write("<br>");document.write(gen.next().value);</script>
Below is an example code to print infinite series of natural numbers using a simple generator.
javascript
<script>// Generate Function generates an// infinite series of Natural Numbersfunction * nextNatural(){ var naturalNumber = 1; // Infinite Generation while (true) { yield naturalNumber++; }} // Calling the Generate Functionvar gen = nextNatural(); // Loop to print the first// 10 Generated numberfor (var i = 0; i < 10; i++) { // Generating Next Number document.write(gen.next().value); // New Line document.write("<br>");}</script>
Output
1
2
3
4
5
6
7
8
9
10
Below is an example of how to manually return from a generator
javascript
<script> var array = ['a', 'b', 'c'];function* generator(arr) { let i = 0; while (i < arr.length) { yield arr[i++] }} const it = generator(array); // we can do it.return() to finish the generator </script>
Encountering yield and yield* syntaxyield: pauses the generator execution and returns the value of the expression which is being written after the yield keyword.yield*: it iterates over the operand and returns each value until done is true.
javascript
<script> const arr = ['a', 'b', 'c']; function* generator() { yield 1; yield* arr; yield 2;} for (let value of generator()) { document.write(value); document.write("<br>");} </script>
Output
1
a
b
c
2
Another method to create iterable
javascript
<script> var createOwnIterable = { *[Symbol.iterator]() { yield 'a'; yield 'b'; yield 'c'; }} for (let value of createOwnIterable) { document.write(value); document.write("<br>");} <script>
Output
a
b
c
Return from a generator function
javascript
<script> function* generator() { yield 'a'; return 'result'; yield 'b';} var it = generator();document.write(JSON.stringify(it.next()));// {value: "a", done: false}document.write(JSON.stringify(it.next()));// {value: "result", done: true} </script>
How to throw an exception from generator
javascript
<script> function* generator() { throw new Error('Error Occurred');} const it = generator();it.next();// Uncaught Error: Error Occurred </script>
Calling a generator from another generator
javascript
<script> function* firstGenerator() { yield 2; yield 3;} function* secondGenerator() { yield 1; yield* firstGenerator(); yield 4;} for (let value of secondGenerator()) { document.write(value) document.write("<br>");} </script>
Output
1
2
3
4
Limitation of Generators you can’t yield inside a callback in generators
javascript
<script> function* generator() { ['a', 'b', 'c'].forEach(value => yield value) // This will give syntax error} </script>
Using async generators (for api call)
javascript
<script> const firstPromise = () => { return new Promise((resolve, reject) => { setTimeout(() => resolve(1), 5000) })} const secondPromise = () => { return new Promise((resolve, reject) => { setTimeout(() => resolve(2), 3000) })} async function* generator() { const firstPromiseResult = await firstPromise(); yield firstPromiseResult; const secondPromiseResult = await secondPromise(); yield secondPromiseResult;} var it = generator();for await(let value of it){ document.write(value); document.write("<br>");} </script>
Output
(after 5 seconds)
1
(after 3 seconds)
2
Advantages of generators: They are memory efficient as lazy evaluation takes place, i.e, delays the evaluation of an expression until its value is needed.use-case (generators)
writing generators in redux-saga
async-await (Implemented with promise and generators)
Supported Browser:
Google Chrome 39 and above
Microsoft Edge 13 and above
Firefox 26 and above
Opera 26 and above
Safari 10 and above
khandelwalsarthak31193
ysachin2314
Pushpender007
nikhatkhan11
javascript-functions
JavaScript-Misc
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 549,
"s": 28,
"text": "Like Python Generators, JavaScript also supports Generator functions and Generator Objects.Generator-Function : A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. The yield statement suspends function’s execution and sends a value back to caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. Syntax : "
},
{
"code": null,
"e": 650,
"s": 549,
"text": "// An example of generator function\nfunction* gen(){\n yield 1;\n yield 2;\n ...\n ...\n}"
},
{
"code": null,
"e": 1014,
"s": 650,
"text": "Generator-Object : Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for of” loop (as shown in the above program) The Generator object is returned by a generating function and it conforms to both the iterable protocol and the iterator protocol. "
},
{
"code": null,
"e": 1025,
"s": 1014,
"text": "javascript"
},
{
"code": "<script>// Generate Function generates three// different numbers in three callsfunction * fun(){ yield 10; yield 20; yield 30; } // Calling the Generate Functionvar gen = fun();document.write(gen.next().value);document.write(\"<br>\");document.write(gen.next().value);document.write(\"<br>\");document.write(gen.next().value);</script> ",
"e": 1387,
"s": 1025,
"text": null
},
{
"code": null,
"e": 1483,
"s": 1387,
"text": "Below is an example code to print infinite series of natural numbers using a simple generator. "
},
{
"code": null,
"e": 1494,
"s": 1483,
"text": "javascript"
},
{
"code": "<script>// Generate Function generates an// infinite series of Natural Numbersfunction * nextNatural(){ var naturalNumber = 1; // Infinite Generation while (true) { yield naturalNumber++; }} // Calling the Generate Functionvar gen = nextNatural(); // Loop to print the first// 10 Generated numberfor (var i = 0; i < 10; i++) { // Generating Next Number document.write(gen.next().value); // New Line document.write(\"<br>\");}</script>",
"e": 1961,
"s": 1494,
"text": null
},
{
"code": null,
"e": 1970,
"s": 1961,
"text": "Output "
},
{
"code": null,
"e": 1991,
"s": 1970,
"text": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10"
},
{
"code": null,
"e": 2055,
"s": 1991,
"text": "Below is an example of how to manually return from a generator "
},
{
"code": null,
"e": 2066,
"s": 2055,
"text": "javascript"
},
{
"code": "<script> var array = ['a', 'b', 'c'];function* generator(arr) { let i = 0; while (i < arr.length) { yield arr[i++] }} const it = generator(array); // we can do it.return() to finish the generator </script>",
"e": 2278,
"s": 2066,
"text": null
},
{
"code": null,
"e": 2520,
"s": 2278,
"text": "Encountering yield and yield* syntaxyield: pauses the generator execution and returns the value of the expression which is being written after the yield keyword.yield*: it iterates over the operand and returns each value until done is true. "
},
{
"code": null,
"e": 2531,
"s": 2520,
"text": "javascript"
},
{
"code": "<script> const arr = ['a', 'b', 'c']; function* generator() { yield 1; yield* arr; yield 2;} for (let value of generator()) { document.write(value); document.write(\"<br>\");} </script>",
"e": 2720,
"s": 2531,
"text": null
},
{
"code": null,
"e": 2729,
"s": 2720,
"text": "Output "
},
{
"code": null,
"e": 2739,
"s": 2729,
"text": "1\na\nb\nc\n2"
},
{
"code": null,
"e": 2774,
"s": 2739,
"text": "Another method to create iterable "
},
{
"code": null,
"e": 2785,
"s": 2774,
"text": "javascript"
},
{
"code": "<script> var createOwnIterable = { *[Symbol.iterator]() { yield 'a'; yield 'b'; yield 'c'; }} for (let value of createOwnIterable) { document.write(value); document.write(\"<br>\");} <script>",
"e": 2988,
"s": 2785,
"text": null
},
{
"code": null,
"e": 2997,
"s": 2988,
"text": "Output "
},
{
"code": null,
"e": 3003,
"s": 2997,
"text": "a\nb\nc"
},
{
"code": null,
"e": 3038,
"s": 3003,
"text": "Return from a generator function "
},
{
"code": null,
"e": 3049,
"s": 3038,
"text": "javascript"
},
{
"code": "<script> function* generator() { yield 'a'; return 'result'; yield 'b';} var it = generator();document.write(JSON.stringify(it.next()));// {value: \"a\", done: false}document.write(JSON.stringify(it.next()));// {value: \"result\", done: true} </script>",
"e": 3301,
"s": 3049,
"text": null
},
{
"code": null,
"e": 3343,
"s": 3301,
"text": "How to throw an exception from generator "
},
{
"code": null,
"e": 3354,
"s": 3343,
"text": "javascript"
},
{
"code": "<script> function* generator() { throw new Error('Error Occurred');} const it = generator();it.next();// Uncaught Error: Error Occurred </script>",
"e": 3501,
"s": 3354,
"text": null
},
{
"code": null,
"e": 3545,
"s": 3501,
"text": "Calling a generator from another generator "
},
{
"code": null,
"e": 3556,
"s": 3545,
"text": "javascript"
},
{
"code": "<script> function* firstGenerator() { yield 2; yield 3;} function* secondGenerator() { yield 1; yield* firstGenerator(); yield 4;} for (let value of secondGenerator()) { document.write(value) document.write(\"<br>\");} </script>",
"e": 3791,
"s": 3556,
"text": null
},
{
"code": null,
"e": 3800,
"s": 3791,
"text": "Output "
},
{
"code": null,
"e": 3808,
"s": 3800,
"text": "1\n2\n3\n4"
},
{
"code": null,
"e": 3883,
"s": 3808,
"text": "Limitation of Generators you can’t yield inside a callback in generators "
},
{
"code": null,
"e": 3894,
"s": 3883,
"text": "javascript"
},
{
"code": "<script> function* generator() { ['a', 'b', 'c'].forEach(value => yield value) // This will give syntax error} </script>",
"e": 4016,
"s": 3894,
"text": null
},
{
"code": null,
"e": 4055,
"s": 4016,
"text": "Using async generators (for api call) "
},
{
"code": null,
"e": 4066,
"s": 4055,
"text": "javascript"
},
{
"code": "<script> const firstPromise = () => { return new Promise((resolve, reject) => { setTimeout(() => resolve(1), 5000) })} const secondPromise = () => { return new Promise((resolve, reject) => { setTimeout(() => resolve(2), 3000) })} async function* generator() { const firstPromiseResult = await firstPromise(); yield firstPromiseResult; const secondPromiseResult = await secondPromise(); yield secondPromiseResult;} var it = generator();for await(let value of it){ document.write(value); document.write(\"<br>\");} </script>",
"e": 4603,
"s": 4066,
"text": null
},
{
"code": null,
"e": 4612,
"s": 4603,
"text": "Output "
},
{
"code": null,
"e": 4653,
"s": 4612,
"text": "(after 5 seconds)\n1 \n(after 3 seconds)\n2"
},
{
"code": null,
"e": 4831,
"s": 4653,
"text": "Advantages of generators: They are memory efficient as lazy evaluation takes place, i.e, delays the evaluation of an expression until its value is needed.use-case (generators) "
},
{
"code": null,
"e": 4864,
"s": 4831,
"text": "writing generators in redux-saga"
},
{
"code": null,
"e": 4918,
"s": 4864,
"text": "async-await (Implemented with promise and generators)"
},
{
"code": null,
"e": 4937,
"s": 4918,
"text": "Supported Browser:"
},
{
"code": null,
"e": 4964,
"s": 4937,
"text": "Google Chrome 39 and above"
},
{
"code": null,
"e": 4992,
"s": 4964,
"text": "Microsoft Edge 13 and above"
},
{
"code": null,
"e": 5013,
"s": 4992,
"text": "Firefox 26 and above"
},
{
"code": null,
"e": 5032,
"s": 5013,
"text": "Opera 26 and above"
},
{
"code": null,
"e": 5052,
"s": 5032,
"text": "Safari 10 and above"
},
{
"code": null,
"e": 5075,
"s": 5052,
"text": "khandelwalsarthak31193"
},
{
"code": null,
"e": 5087,
"s": 5075,
"text": "ysachin2314"
},
{
"code": null,
"e": 5101,
"s": 5087,
"text": "Pushpender007"
},
{
"code": null,
"e": 5114,
"s": 5101,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 5135,
"s": 5114,
"text": "javascript-functions"
},
{
"code": null,
"e": 5151,
"s": 5135,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 5162,
"s": 5151,
"text": "JavaScript"
}
]
|
Bar Chart Race & Choropleth Map of COVID-19 python | Towards Data Science | “Visualization gives you answers to questions you didn’t know you had” — Ben Schneiderman
In the era of data science, we must say data is beauty. We can not even think of a day without data. More or less modern technologies are dependent on the data-driven process. But only raw data doesn't make any charm to us until it is processed. When data is processed, we get information from it. Information may be visual, statistical, predictive, and so on. If we can aesthetically visualize data, we can easily get the insight into the data. It provides an overview of the data. Proper visualization makes a clear intuition of the whole scenario in the human brain.
“Most of us need to listen to the music to understand how beautiful it is. But often that’s how we present statistics: we just show the notes, we don’t play the music ” — Hans Rosling
And Hans Rosling indicated the actual thinking of data visualization. Data visualization is essential for each and every profession. In this article, we will try our best to represent the COVID-19 scenario, all over the world. At the same time, we will learn some interactive plotting techniques with python.
Python provides so many libraries which makes our life easy and beautiful. We will learn some interesting plotting techniques with the COVID-19 dataset.
When you go through the whole article you will be able to create animations as shown in the harder part of the article. No background knowledge is needed to read the article. It is nothing but a few lines of python code. Let me guide through.
Python provides us with the flexibility to use different libraries for different tasks. Here, we will use matplotlib and plotly libraries to have the visual output with bar chart race and choropleth map with the COVID-19 dataset.
Little bit data preprocessing for our desired plots.
Stylish bar chart race with COVID-19 dataset for Confirmed, Recovered, and Death cases.
Interactive choropleth map with COVID-19 dataset
Let’s move on to the next step...
Download the COVID-19 dataset from kaggle. The data is well organized and updated daily. I am using the dataset which is last updated on 25 April 2020.
Importing pandas for working with dataframe, numpy for different mathematical operation and matplotlib for our bar chart race.
import pandas as pdimport numpy as npimport matplotlib.ticker as tickerimport matplotlib.pyplot as plt
The dataset contains all the affected countries’ confirmed positive cases, death cases, and recovered cases of coronavirus. If we want to catch sight of the data, it will look like this.
covid = pd.read_csv('covid_19_data.csv')covid.head(5)
Now, we want to rename the columns because it will help us to manipulate the data more easily.
covid.rename(columns={'ObservationDate':'Date','Province/State':'State','Country/Region':'Country'},inplace=True)
From the first 5 rows of the dataset, we come to know that there are some redundant and unnecessary columns, we will leave the columns and keep only the necessary columns.
covid=covid[["Date","State","Country","Confirmed","Deaths","Recovered"]]
Our main target is to make a bar chart race based on the country, so we can group the country by date for finding out the total number of cases in a country.
grouped = covid.groupby(['Country','Date'])covid_confirmed = grouped.sum().reset_index().sort_values(['Date'],ascending=False)
We saved the output dataframe to covid_confirmed and it seems like below.
Finding out the top ten countries of coronavirus confirmed cases for plotting an initial bar chart. We are stepping down to the steps of the bar chart race.
df = (covid_confirmed[covid_confirmed['Date'].eq("04/25/2020")].sort_values(by="Confirmed",ascending=False).head(10))
Output
Making a Bar Chart Race with matplotlib of coronavirus spread
#plotting the initial horaizontal barchart fig, ax = plt.subplots(figsize=(15, 8))ax.barh(df['Country'], df['Confirmed'])plt.xlabel('Number of Confirmend Cases')plt.ylabel('Country')
This few lines of code will generate the following output with matplotlib.
But we want to have the highest confirmed case at the top. For this, we need to flip the dataframe.df[::-1] ,this piece of code will flip the dataframe df
dff=df[::-1]fig, ax = plt.subplots(figsize=(15, 8))ax.barh(dff['Country'], dff['Confirmed'])plt.xlabel('Number of Confirmed Cases')plt.ylabel('Country')
Wow! we are a few steps ahead of our desired output. The above bar chart does not seem too good. We need more information and visual color in the chart. For this, we can follow the following techniques
i.Color code each country with different colors
ii.Color code with a fixed number of colors
iii.Serially 10 different colors for the top ten affected countries.
I will show you each and every step.
Coding each country with individual colors with a dictionary.
colors holds a dictionary of country’s name as key and color code is the values for each country.
You can also use the following method.
colors = dict(zip(df_date_series.Country.unique(),['#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#f7bb5f','#fb6b19','#1fb1fb'] * 31))
Just set 10 color codes for the 10 affected country
This method is used in the draw_barchartfunction shown in the function section.
color=["#980505","#CD1212","#D84E4E","#CB6262","#D39B5F","#F7EC10","#D0F710","#9CF710","#B4D67F","#969C8E"]
However, I am using the first method for the following bar chart.
Congratulations! we are at the very final step of our bar chart race with the COVID-19 dataset. we will create a function integrating with all of the above codes and some stylish.
“Bar Chart Race in Python with Matplotlib” article helped me a lot. For the better style of the bar chart. I am quoting some functionalities of the polish style from the article,
Text: Update font sizes, color, orientation
Axis: Move X-axis to top, add color & subtitle
Grid: Add lines behind bars
Format: comma-separated values and axes tickers
Add title, credits, gutter space
Remove: box frame, y-axis labels
We will use these things for the aesthetic design of our bar chart race.
Function
In the draw_barchart function, I have implemented the third color code option. I have set fixed colors for the top 10 affected countries with the list of 10 color codes.
For individual function call, the function will output like this for draw_barchart(“04/25/2020”).
Making an animation is our final goal, we are going to do this. Are you ready? Here is the code for your animation.
Now we have the following animation.
Instead of using HTML, you can also save the animation using animator.save() method. If you change the parameter case to Deaths or Recovered the animation will show the bar chart race of Deaths and Recovered.
Interactive and Animated Choropleth Map of coronavirus spread with Plotly
At the end of the part of this article, we will create an interactive choropleth map like the following animation.
We need not deal with any country where there are no confirmed corona cases. So, we will drop the rows where is no coronavirus confirmed cases.
modified_confirmed = covid_confirmed[covid_confirmed.Confirmed > 0]
For making an effective choropleth map, we must have a distinguishable number of coronavirus affected cases. Let’s have some intuition about the COVID-19 dataset with a kernel density plot.
The first plot shows that most of the countries' values are condensed to a point. But when we plot the values with log10 values, it shows more spread in nature. It indicates that if we use the original number of confirmed cases, we can not distinguish between the colors of the map. Because most of the countries will be plotted with similar types of colors. We must include the log10 value of our dataset for better results. Let's do it.
modified_confirmed['Affected_Factor'] = np.log10(modified_confirmed.Confirmed)
Now, our modified_confirmed dataset looks like this.
Yes! we have added a column named Affected_Factor to the dataframe based on the log10 value of Confirmed cases. And we are just one step ahead for our final interactive choropleth map.
About Plotly Library
The plotly Python library (plotly.py) is an interactive, open-source plotting library that supports over 40 unique chart types covering a wide range of statistical, financial, geographic, scientific, and 3-dimensional use-cases.
Installation
If you use an anaconda environment, you can install the library with the following conda command in the conda comment prompt.
conda install -c plotly plotly
You can also check the official website of anaconda for the installation process. For other environments, pip install can be used.
$ pip install plotly
Importing the Necessary modules
import plotly as pyimport plotly.express as px
We will plot the interactive choropleth maps using COVID-19 dataset with plotly.express module. Now we will write our final code for the interactive map.
We have passed some parameter into the plotly.express object px.
Here is a short description of the parameters.
Dataframe: I have reversed the dataframe modified_confirmed with [::-1]. Because the dataframe is sorted according to the recent to past date but we need to show the animation from the date when coronavirus started to affect people.
location parameter is set according to the Country column.
And all other parameters definition are embedded as comment in the code.
What does the Affected_Factor legend indicate in the plot?
The legend Affected_Factor maybe confusing though I have mentioned it in the preprocessing section. It is the log10 value of the confirmed cases. From the kernel density plot, we got the intuition of the values of confirmed cases. The number of confirmed cases in different countries is very close. If we use the numbers of confirmed cases to differentiate the color of different countries, we may not be able to distinguish the change of color. Most of the countries will be plotted with similar types of colors. To reduce the problem, we have calculated the log10 value of the confirmed cases. It is more distinguishable. The second kernel density plot also indicates the fact. You can also check it out by yourself.
Now, our interactive choropleth map is ready. The map provides information about the spread of COVID-19 in the whole world. The color of the map is getting changed with the increasing number of confirmed coronavirus cases with the passage of time. We can also find out all the information by hover over the mouse courser. The map also supports zooming in and out.
Data visualization is the best way to represent the overall condition of anything at a glance. Enrich libraries of python make it easy for us. We just need to know how to use it, how the function works. Official documentation can help you a lot in this regard.
If you want to get the full project, just reach out to the GitHub repository. You can also view the whole jupyter notebook from here.
Python supports so many visualization libraries. Among then matplotlib is the popular one and it is a huge library. You can also find other visualization libraries’ documentation like seaborn, geopandas, geopy, plotly etc. for more aesthetic plotting of data.
For any query, let me know in the comment section.
Thank you for spending the time to read the article.
[Note: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here.] | [
{
"code": null,
"e": 262,
"s": 172,
"text": "“Visualization gives you answers to questions you didn’t know you had” — Ben Schneiderman"
},
{
"code": null,
"e": 832,
"s": 262,
"text": "In the era of data science, we must say data is beauty. We can not even think of a day without data. More or less modern technologies are dependent on the data-driven process. But only raw data doesn't make any charm to us until it is processed. When data is processed, we get information from it. Information may be visual, statistical, predictive, and so on. If we can aesthetically visualize data, we can easily get the insight into the data. It provides an overview of the data. Proper visualization makes a clear intuition of the whole scenario in the human brain."
},
{
"code": null,
"e": 1016,
"s": 832,
"text": "“Most of us need to listen to the music to understand how beautiful it is. But often that’s how we present statistics: we just show the notes, we don’t play the music ” — Hans Rosling"
},
{
"code": null,
"e": 1325,
"s": 1016,
"text": "And Hans Rosling indicated the actual thinking of data visualization. Data visualization is essential for each and every profession. In this article, we will try our best to represent the COVID-19 scenario, all over the world. At the same time, we will learn some interactive plotting techniques with python."
},
{
"code": null,
"e": 1478,
"s": 1325,
"text": "Python provides so many libraries which makes our life easy and beautiful. We will learn some interesting plotting techniques with the COVID-19 dataset."
},
{
"code": null,
"e": 1721,
"s": 1478,
"text": "When you go through the whole article you will be able to create animations as shown in the harder part of the article. No background knowledge is needed to read the article. It is nothing but a few lines of python code. Let me guide through."
},
{
"code": null,
"e": 1951,
"s": 1721,
"text": "Python provides us with the flexibility to use different libraries for different tasks. Here, we will use matplotlib and plotly libraries to have the visual output with bar chart race and choropleth map with the COVID-19 dataset."
},
{
"code": null,
"e": 2004,
"s": 1951,
"text": "Little bit data preprocessing for our desired plots."
},
{
"code": null,
"e": 2092,
"s": 2004,
"text": "Stylish bar chart race with COVID-19 dataset for Confirmed, Recovered, and Death cases."
},
{
"code": null,
"e": 2141,
"s": 2092,
"text": "Interactive choropleth map with COVID-19 dataset"
},
{
"code": null,
"e": 2175,
"s": 2141,
"text": "Let’s move on to the next step..."
},
{
"code": null,
"e": 2327,
"s": 2175,
"text": "Download the COVID-19 dataset from kaggle. The data is well organized and updated daily. I am using the dataset which is last updated on 25 April 2020."
},
{
"code": null,
"e": 2454,
"s": 2327,
"text": "Importing pandas for working with dataframe, numpy for different mathematical operation and matplotlib for our bar chart race."
},
{
"code": null,
"e": 2557,
"s": 2454,
"text": "import pandas as pdimport numpy as npimport matplotlib.ticker as tickerimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 2744,
"s": 2557,
"text": "The dataset contains all the affected countries’ confirmed positive cases, death cases, and recovered cases of coronavirus. If we want to catch sight of the data, it will look like this."
},
{
"code": null,
"e": 2798,
"s": 2744,
"text": "covid = pd.read_csv('covid_19_data.csv')covid.head(5)"
},
{
"code": null,
"e": 2893,
"s": 2798,
"text": "Now, we want to rename the columns because it will help us to manipulate the data more easily."
},
{
"code": null,
"e": 3007,
"s": 2893,
"text": "covid.rename(columns={'ObservationDate':'Date','Province/State':'State','Country/Region':'Country'},inplace=True)"
},
{
"code": null,
"e": 3179,
"s": 3007,
"text": "From the first 5 rows of the dataset, we come to know that there are some redundant and unnecessary columns, we will leave the columns and keep only the necessary columns."
},
{
"code": null,
"e": 3252,
"s": 3179,
"text": "covid=covid[[\"Date\",\"State\",\"Country\",\"Confirmed\",\"Deaths\",\"Recovered\"]]"
},
{
"code": null,
"e": 3410,
"s": 3252,
"text": "Our main target is to make a bar chart race based on the country, so we can group the country by date for finding out the total number of cases in a country."
},
{
"code": null,
"e": 3537,
"s": 3410,
"text": "grouped = covid.groupby(['Country','Date'])covid_confirmed = grouped.sum().reset_index().sort_values(['Date'],ascending=False)"
},
{
"code": null,
"e": 3611,
"s": 3537,
"text": "We saved the output dataframe to covid_confirmed and it seems like below."
},
{
"code": null,
"e": 3768,
"s": 3611,
"text": "Finding out the top ten countries of coronavirus confirmed cases for plotting an initial bar chart. We are stepping down to the steps of the bar chart race."
},
{
"code": null,
"e": 3886,
"s": 3768,
"text": "df = (covid_confirmed[covid_confirmed['Date'].eq(\"04/25/2020\")].sort_values(by=\"Confirmed\",ascending=False).head(10))"
},
{
"code": null,
"e": 3893,
"s": 3886,
"text": "Output"
},
{
"code": null,
"e": 3955,
"s": 3893,
"text": "Making a Bar Chart Race with matplotlib of coronavirus spread"
},
{
"code": null,
"e": 4138,
"s": 3955,
"text": "#plotting the initial horaizontal barchart fig, ax = plt.subplots(figsize=(15, 8))ax.barh(df['Country'], df['Confirmed'])plt.xlabel('Number of Confirmend Cases')plt.ylabel('Country')"
},
{
"code": null,
"e": 4213,
"s": 4138,
"text": "This few lines of code will generate the following output with matplotlib."
},
{
"code": null,
"e": 4368,
"s": 4213,
"text": "But we want to have the highest confirmed case at the top. For this, we need to flip the dataframe.df[::-1] ,this piece of code will flip the dataframe df"
},
{
"code": null,
"e": 4521,
"s": 4368,
"text": "dff=df[::-1]fig, ax = plt.subplots(figsize=(15, 8))ax.barh(dff['Country'], dff['Confirmed'])plt.xlabel('Number of Confirmed Cases')plt.ylabel('Country')"
},
{
"code": null,
"e": 4723,
"s": 4521,
"text": "Wow! we are a few steps ahead of our desired output. The above bar chart does not seem too good. We need more information and visual color in the chart. For this, we can follow the following techniques"
},
{
"code": null,
"e": 4771,
"s": 4723,
"text": "i.Color code each country with different colors"
},
{
"code": null,
"e": 4815,
"s": 4771,
"text": "ii.Color code with a fixed number of colors"
},
{
"code": null,
"e": 4884,
"s": 4815,
"text": "iii.Serially 10 different colors for the top ten affected countries."
},
{
"code": null,
"e": 4921,
"s": 4884,
"text": "I will show you each and every step."
},
{
"code": null,
"e": 4983,
"s": 4921,
"text": "Coding each country with individual colors with a dictionary."
},
{
"code": null,
"e": 5081,
"s": 4983,
"text": "colors holds a dictionary of country’s name as key and color code is the values for each country."
},
{
"code": null,
"e": 5120,
"s": 5081,
"text": "You can also use the following method."
},
{
"code": null,
"e": 5253,
"s": 5120,
"text": "colors = dict(zip(df_date_series.Country.unique(),['#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#f7bb5f','#fb6b19','#1fb1fb'] * 31))"
},
{
"code": null,
"e": 5305,
"s": 5253,
"text": "Just set 10 color codes for the 10 affected country"
},
{
"code": null,
"e": 5385,
"s": 5305,
"text": "This method is used in the draw_barchartfunction shown in the function section."
},
{
"code": null,
"e": 5493,
"s": 5385,
"text": "color=[\"#980505\",\"#CD1212\",\"#D84E4E\",\"#CB6262\",\"#D39B5F\",\"#F7EC10\",\"#D0F710\",\"#9CF710\",\"#B4D67F\",\"#969C8E\"]"
},
{
"code": null,
"e": 5559,
"s": 5493,
"text": "However, I am using the first method for the following bar chart."
},
{
"code": null,
"e": 5739,
"s": 5559,
"text": "Congratulations! we are at the very final step of our bar chart race with the COVID-19 dataset. we will create a function integrating with all of the above codes and some stylish."
},
{
"code": null,
"e": 5918,
"s": 5739,
"text": "“Bar Chart Race in Python with Matplotlib” article helped me a lot. For the better style of the bar chart. I am quoting some functionalities of the polish style from the article,"
},
{
"code": null,
"e": 5962,
"s": 5918,
"text": "Text: Update font sizes, color, orientation"
},
{
"code": null,
"e": 6009,
"s": 5962,
"text": "Axis: Move X-axis to top, add color & subtitle"
},
{
"code": null,
"e": 6037,
"s": 6009,
"text": "Grid: Add lines behind bars"
},
{
"code": null,
"e": 6085,
"s": 6037,
"text": "Format: comma-separated values and axes tickers"
},
{
"code": null,
"e": 6118,
"s": 6085,
"text": "Add title, credits, gutter space"
},
{
"code": null,
"e": 6151,
"s": 6118,
"text": "Remove: box frame, y-axis labels"
},
{
"code": null,
"e": 6224,
"s": 6151,
"text": "We will use these things for the aesthetic design of our bar chart race."
},
{
"code": null,
"e": 6233,
"s": 6224,
"text": "Function"
},
{
"code": null,
"e": 6403,
"s": 6233,
"text": "In the draw_barchart function, I have implemented the third color code option. I have set fixed colors for the top 10 affected countries with the list of 10 color codes."
},
{
"code": null,
"e": 6501,
"s": 6403,
"text": "For individual function call, the function will output like this for draw_barchart(“04/25/2020”)."
},
{
"code": null,
"e": 6617,
"s": 6501,
"text": "Making an animation is our final goal, we are going to do this. Are you ready? Here is the code for your animation."
},
{
"code": null,
"e": 6654,
"s": 6617,
"text": "Now we have the following animation."
},
{
"code": null,
"e": 6863,
"s": 6654,
"text": "Instead of using HTML, you can also save the animation using animator.save() method. If you change the parameter case to Deaths or Recovered the animation will show the bar chart race of Deaths and Recovered."
},
{
"code": null,
"e": 6937,
"s": 6863,
"text": "Interactive and Animated Choropleth Map of coronavirus spread with Plotly"
},
{
"code": null,
"e": 7052,
"s": 6937,
"text": "At the end of the part of this article, we will create an interactive choropleth map like the following animation."
},
{
"code": null,
"e": 7196,
"s": 7052,
"text": "We need not deal with any country where there are no confirmed corona cases. So, we will drop the rows where is no coronavirus confirmed cases."
},
{
"code": null,
"e": 7264,
"s": 7196,
"text": "modified_confirmed = covid_confirmed[covid_confirmed.Confirmed > 0]"
},
{
"code": null,
"e": 7454,
"s": 7264,
"text": "For making an effective choropleth map, we must have a distinguishable number of coronavirus affected cases. Let’s have some intuition about the COVID-19 dataset with a kernel density plot."
},
{
"code": null,
"e": 7893,
"s": 7454,
"text": "The first plot shows that most of the countries' values are condensed to a point. But when we plot the values with log10 values, it shows more spread in nature. It indicates that if we use the original number of confirmed cases, we can not distinguish between the colors of the map. Because most of the countries will be plotted with similar types of colors. We must include the log10 value of our dataset for better results. Let's do it."
},
{
"code": null,
"e": 7972,
"s": 7893,
"text": "modified_confirmed['Affected_Factor'] = np.log10(modified_confirmed.Confirmed)"
},
{
"code": null,
"e": 8025,
"s": 7972,
"text": "Now, our modified_confirmed dataset looks like this."
},
{
"code": null,
"e": 8210,
"s": 8025,
"text": "Yes! we have added a column named Affected_Factor to the dataframe based on the log10 value of Confirmed cases. And we are just one step ahead for our final interactive choropleth map."
},
{
"code": null,
"e": 8231,
"s": 8210,
"text": "About Plotly Library"
},
{
"code": null,
"e": 8460,
"s": 8231,
"text": "The plotly Python library (plotly.py) is an interactive, open-source plotting library that supports over 40 unique chart types covering a wide range of statistical, financial, geographic, scientific, and 3-dimensional use-cases."
},
{
"code": null,
"e": 8473,
"s": 8460,
"text": "Installation"
},
{
"code": null,
"e": 8599,
"s": 8473,
"text": "If you use an anaconda environment, you can install the library with the following conda command in the conda comment prompt."
},
{
"code": null,
"e": 8630,
"s": 8599,
"text": "conda install -c plotly plotly"
},
{
"code": null,
"e": 8761,
"s": 8630,
"text": "You can also check the official website of anaconda for the installation process. For other environments, pip install can be used."
},
{
"code": null,
"e": 8782,
"s": 8761,
"text": "$ pip install plotly"
},
{
"code": null,
"e": 8814,
"s": 8782,
"text": "Importing the Necessary modules"
},
{
"code": null,
"e": 8861,
"s": 8814,
"text": "import plotly as pyimport plotly.express as px"
},
{
"code": null,
"e": 9015,
"s": 8861,
"text": "We will plot the interactive choropleth maps using COVID-19 dataset with plotly.express module. Now we will write our final code for the interactive map."
},
{
"code": null,
"e": 9080,
"s": 9015,
"text": "We have passed some parameter into the plotly.express object px."
},
{
"code": null,
"e": 9127,
"s": 9080,
"text": "Here is a short description of the parameters."
},
{
"code": null,
"e": 9360,
"s": 9127,
"text": "Dataframe: I have reversed the dataframe modified_confirmed with [::-1]. Because the dataframe is sorted according to the recent to past date but we need to show the animation from the date when coronavirus started to affect people."
},
{
"code": null,
"e": 9419,
"s": 9360,
"text": "location parameter is set according to the Country column."
},
{
"code": null,
"e": 9492,
"s": 9419,
"text": "And all other parameters definition are embedded as comment in the code."
},
{
"code": null,
"e": 9551,
"s": 9492,
"text": "What does the Affected_Factor legend indicate in the plot?"
},
{
"code": null,
"e": 10270,
"s": 9551,
"text": "The legend Affected_Factor maybe confusing though I have mentioned it in the preprocessing section. It is the log10 value of the confirmed cases. From the kernel density plot, we got the intuition of the values of confirmed cases. The number of confirmed cases in different countries is very close. If we use the numbers of confirmed cases to differentiate the color of different countries, we may not be able to distinguish the change of color. Most of the countries will be plotted with similar types of colors. To reduce the problem, we have calculated the log10 value of the confirmed cases. It is more distinguishable. The second kernel density plot also indicates the fact. You can also check it out by yourself."
},
{
"code": null,
"e": 10634,
"s": 10270,
"text": "Now, our interactive choropleth map is ready. The map provides information about the spread of COVID-19 in the whole world. The color of the map is getting changed with the increasing number of confirmed coronavirus cases with the passage of time. We can also find out all the information by hover over the mouse courser. The map also supports zooming in and out."
},
{
"code": null,
"e": 10895,
"s": 10634,
"text": "Data visualization is the best way to represent the overall condition of anything at a glance. Enrich libraries of python make it easy for us. We just need to know how to use it, how the function works. Official documentation can help you a lot in this regard."
},
{
"code": null,
"e": 11029,
"s": 10895,
"text": "If you want to get the full project, just reach out to the GitHub repository. You can also view the whole jupyter notebook from here."
},
{
"code": null,
"e": 11289,
"s": 11029,
"text": "Python supports so many visualization libraries. Among then matplotlib is the popular one and it is a huge library. You can also find other visualization libraries’ documentation like seaborn, geopandas, geopy, plotly etc. for more aesthetic plotting of data."
},
{
"code": null,
"e": 11340,
"s": 11289,
"text": "For any query, let me know in the comment section."
},
{
"code": null,
"e": 11393,
"s": 11340,
"text": "Thank you for spending the time to read the article."
}
]
|
Tryit Editor v3.7 | Tryit: A list with i, ii, iii | []
|
Using Pandas Method Chaining to improve code readability | by B. Chen | Towards Data Science | We have been talking about using the Pandas pipe function to improve code readability. In this article, let’s have a look at Pandas Method Chaining.
In Data Processing, it is often necessary to perform operations on a certain row or column to obtain new data. Instead of writing
df = pd.read_csv('data.csv')df = df.fillna(...)df = df.query('some_condition')df['new_column'] = df.cut(...)df = df.pivot_table(...)df = df.rename(...)
We can do
(pd.read_csv('data.csv') .fillna(...) .query('some_condition') .assign(new_column = df.cut(...)) .pivot_table(...) .rename(...))
Method Chaining has always been available in Pandas, but support for chaining has increased through the addition of new “chain-able” methods. For example, query(), assign(), pivot_table(), and in particular pipe() for allowing user-defined methods in method chaining.
Method chaining is a programmatic style of invoking multiple method calls sequentially with each call performing an action on the same object and returning it.
It eliminates the cognitive burden of naming variables at each intermediate step. Fluent Interface, a method of creating object-oriented API relies on method cascading (aka method chaining). This is akin to piping in Unix systems.
By Adiamaan Keerthi
Method chaining substantially increases the readability of the code. Let’s dive into a tutorial to see how it improves our code readability.
For source code, please visit my Github notebook.
For this tutorial, we will be working on the Titanic Dataset from Kaggle. This is a very famous dataset and very often is a student’s first step in data science. Let’s import some libraries and load data to get started.
import pandas as pdimport sysimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline%config InlineBackend.figure_format = 'svg'df = pd.read_csv('data/train.csv')df.head()
We load train.csv file into Pandas DataFrame
Let’s start by checking out missing values. We can use seaborn to create a simple heatmap to see where are missing values
sns.heatmap(df.isnull(), yticklabels=False, cbar=False, cmap='viridis')
Age, Cabin, and Embarked have missing values. The proportion of Age missing is likely small enough for reasonable replacement with some form of imputation. Looking at the Cabin column, it looks like a lot of missing values. The proportion of Embarked missing is very small.
Suppose we have been asked to take a look at passengers departed from Southampton, and work out the survival rate for different age groups and Pclass.
Let’s split this task into several steps and accomplish them step by step.
Data cleaning: replace the missing Age with some form of imputationSelect passengers departed from SouthamptonConvert ages to groups of age ranges: ≤12, Teen (≤ 18), Adult (≤ 60) and Older (>60)Create a pivot table to display the survival rate for different age groups and PclassImprove the display of pivot table by renaming axis labels and formatting values.
Data cleaning: replace the missing Age with some form of imputation
Select passengers departed from Southampton
Convert ages to groups of age ranges: ≤12, Teen (≤ 18), Adult (≤ 60) and Older (>60)
Create a pivot table to display the survival rate for different age groups and Pclass
Improve the display of pivot table by renaming axis labels and formatting values.
Cool, let’s go ahead and use Pandas Method Chaining to accomplish them.
As mentioned in the Data preparation, we would like to replace the missing Age with some form of imputation. One way to do this is by filling in the mean age of all the passengers. However, we can be smarter about this and check the average age by passenger class. For example:
sns.boxplot(x='Pclass', y='Age', data=df, palette='winter')
We can see the wealthier passengers in the higher classes tend to be older, which makes sense. We’ll use these average age values to impute based on Pclass for Age.
pclass_age_map = { 1: 37, 2: 29, 3: 24,}def replace_age_na(x_df, fill_map): cond=x_df['Age'].isna() res=x_df.loc[cond,'Pclass'].map(fill_map) x_df.loc[cond,'Age']=res return x_df
x_df['Age'].isna() selects the Age column and detects the missing values. Then, x_df.loc[cond, 'Pclass'] is used to access Pclass values conditionally and call Pandas map() for substituting each value with another value. Finally, x_df.loc[cond, 'Age']=res conditionally replace all missing Age values with res.
Running the following code
res = ( pd.read_csv('data/train.csv') .pipe(replace_age_na, pclass_age_map))res.head()
All missing ages should be replaced based on Pclass for Age. Let’s check this by running the heatmap on res.
sns.heatmap(res.isnull(), yticklabels=False, cbar=False, cmap='viridis')
Great, it works!
According to Titanic Data Dictionary, passengers departed from Southampton should have Embarked with value S . Let’s query that using the Pandas query() function.
res = ( pd.read_csv('data/train.csv') .pipe(replace_age_na, pclass_age_map) .query('Embarked == "S"'))res.head()
To evaluate the query result, we can check it with value_counts()
res.Embarked.value_counts()S 644Name: Embarked, dtype: int64
We did this with a custom function in the Pandas pipe function article. Alternatively, we can use Pandas built-in function assign() to add new columns to a DataFrame. Let’s go ahead withassign().
bins=[0, 13, 19, 61, sys.maxsize]labels=['<12', 'Teen', 'Adult', 'Older']res = ( pd.read_csv('data/train.csv') .pipe(replace_age_na, pclass_age_map) .query('Embarked == "S"') .assign(ageGroup = lambda df: pd.cut(df['Age'], bins=bins, labels=labels)))res.head()
Pandas assign() is used to create a new column ageGroup. The new column is created with a lambda function together with Pandas cut() to convert ages to groups of ranges.
By running the code, we should get an output like below:
A pivot table allows us to insights into our data. Let’s figure out the survival rate with it.
bins=[0, 13, 19, 61, sys.maxsize]labels=['<12', 'Teen', 'Adult', 'Older']( pd.read_csv('data/train.csv') .pipe(replace_age_na, pclass_age_map) .query('Embarked == "S"') .assign(ageGroup = lambda df: pd.cut(df['Age'], bins=bins, labels=labels)) .pivot_table( values='Survived', columns='Pclass', index='ageGroup', aggfunc='mean'))
The first parameter values='Survived' specifies the column Survived to aggregate. Since the value of Survived is 1 or 0, we can use the aggregation function mean to calculate the survival rate and therefore aggfunc='mean' is used. index='ageGroup' and columns='Pclass' will display ageGroup as rows and Pclass as columns in the output table.
By running the code, we should get an output like below:
The output we have got so far is not very self-explanatory. Let’s go ahead and improve the display.
bins=[0, 13, 19, 61, sys.maxsize]labels=['<12', 'Teen', 'Adult', 'Older']( pd.read_csv('data/train.csv') .pipe(replace_age_na, pclass_age_map) .query('Embarked == "S"') .assign(ageGroup = lambda df: pd.cut(df['Age'], bins=bins, labels=labels)) .pivot_table( values='Survived', columns='Pclass', index='ageGroup', aggfunc='mean') .rename_axis('', axis='columns') .rename('Class {}'.format, axis='columns') .style.format('{:.2%}'))
rename_axis() is used to clear the columns label. After that, rename('Class {}'.format, axis='columns') is used to format the columns label. Finally,style.format('{:.2%}') is used to format values into percentages with 2 decimal places.
By running the code, we should get an output like below
In terms of performance, according to DataSchool [2], the method chain tells pandas everything ahead of time, so pandas can plan its operations more efficiently, and thus it should have better performance than conventional ways.
Method Chainings are more readable. However, a very long method chaining could be less readable, especially when other functions get called inside the chain, for example, the cut() is used inside the assign() method in our tutorial.
In addition, a major drawback of using Method Chaining is that debugging can be harder, especially in a very long chain. If something looks wrong at the end, you don’t have intermediate values to inspect.
For a longer discussion of this topic, see Tom Augspurger’s Method Chaining post [1].
Thanks for reading.
Please checkout the notebook on my Github for the source code.
Stay tuned if you are interested in the practical aspect of machine learning.
Lastly, here are 2 related articles you may be interested in
Working with missing values in Pandas
Using Pandas pipe function to improve code readability
[1] Method Chaining from Tom Augspurger https://tomaugspurger.github.io/method-chaining.html
[2] Future of Pandas from DataSchool.io | [
{
"code": null,
"e": 320,
"s": 171,
"text": "We have been talking about using the Pandas pipe function to improve code readability. In this article, let’s have a look at Pandas Method Chaining."
},
{
"code": null,
"e": 450,
"s": 320,
"text": "In Data Processing, it is often necessary to perform operations on a certain row or column to obtain new data. Instead of writing"
},
{
"code": null,
"e": 602,
"s": 450,
"text": "df = pd.read_csv('data.csv')df = df.fillna(...)df = df.query('some_condition')df['new_column'] = df.cut(...)df = df.pivot_table(...)df = df.rename(...)"
},
{
"code": null,
"e": 612,
"s": 602,
"text": "We can do"
},
{
"code": null,
"e": 751,
"s": 612,
"text": "(pd.read_csv('data.csv') .fillna(...) .query('some_condition') .assign(new_column = df.cut(...)) .pivot_table(...) .rename(...))"
},
{
"code": null,
"e": 1019,
"s": 751,
"text": "Method Chaining has always been available in Pandas, but support for chaining has increased through the addition of new “chain-able” methods. For example, query(), assign(), pivot_table(), and in particular pipe() for allowing user-defined methods in method chaining."
},
{
"code": null,
"e": 1179,
"s": 1019,
"text": "Method chaining is a programmatic style of invoking multiple method calls sequentially with each call performing an action on the same object and returning it."
},
{
"code": null,
"e": 1410,
"s": 1179,
"text": "It eliminates the cognitive burden of naming variables at each intermediate step. Fluent Interface, a method of creating object-oriented API relies on method cascading (aka method chaining). This is akin to piping in Unix systems."
},
{
"code": null,
"e": 1430,
"s": 1410,
"text": "By Adiamaan Keerthi"
},
{
"code": null,
"e": 1571,
"s": 1430,
"text": "Method chaining substantially increases the readability of the code. Let’s dive into a tutorial to see how it improves our code readability."
},
{
"code": null,
"e": 1621,
"s": 1571,
"text": "For source code, please visit my Github notebook."
},
{
"code": null,
"e": 1841,
"s": 1621,
"text": "For this tutorial, we will be working on the Titanic Dataset from Kaggle. This is a very famous dataset and very often is a student’s first step in data science. Let’s import some libraries and load data to get started."
},
{
"code": null,
"e": 2027,
"s": 1841,
"text": "import pandas as pdimport sysimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inline%config InlineBackend.figure_format = 'svg'df = pd.read_csv('data/train.csv')df.head()"
},
{
"code": null,
"e": 2072,
"s": 2027,
"text": "We load train.csv file into Pandas DataFrame"
},
{
"code": null,
"e": 2194,
"s": 2072,
"text": "Let’s start by checking out missing values. We can use seaborn to create a simple heatmap to see where are missing values"
},
{
"code": null,
"e": 2302,
"s": 2194,
"text": "sns.heatmap(df.isnull(), yticklabels=False, cbar=False, cmap='viridis')"
},
{
"code": null,
"e": 2576,
"s": 2302,
"text": "Age, Cabin, and Embarked have missing values. The proportion of Age missing is likely small enough for reasonable replacement with some form of imputation. Looking at the Cabin column, it looks like a lot of missing values. The proportion of Embarked missing is very small."
},
{
"code": null,
"e": 2727,
"s": 2576,
"text": "Suppose we have been asked to take a look at passengers departed from Southampton, and work out the survival rate for different age groups and Pclass."
},
{
"code": null,
"e": 2802,
"s": 2727,
"text": "Let’s split this task into several steps and accomplish them step by step."
},
{
"code": null,
"e": 3163,
"s": 2802,
"text": "Data cleaning: replace the missing Age with some form of imputationSelect passengers departed from SouthamptonConvert ages to groups of age ranges: ≤12, Teen (≤ 18), Adult (≤ 60) and Older (>60)Create a pivot table to display the survival rate for different age groups and PclassImprove the display of pivot table by renaming axis labels and formatting values."
},
{
"code": null,
"e": 3231,
"s": 3163,
"text": "Data cleaning: replace the missing Age with some form of imputation"
},
{
"code": null,
"e": 3275,
"s": 3231,
"text": "Select passengers departed from Southampton"
},
{
"code": null,
"e": 3360,
"s": 3275,
"text": "Convert ages to groups of age ranges: ≤12, Teen (≤ 18), Adult (≤ 60) and Older (>60)"
},
{
"code": null,
"e": 3446,
"s": 3360,
"text": "Create a pivot table to display the survival rate for different age groups and Pclass"
},
{
"code": null,
"e": 3528,
"s": 3446,
"text": "Improve the display of pivot table by renaming axis labels and formatting values."
},
{
"code": null,
"e": 3600,
"s": 3528,
"text": "Cool, let’s go ahead and use Pandas Method Chaining to accomplish them."
},
{
"code": null,
"e": 3878,
"s": 3600,
"text": "As mentioned in the Data preparation, we would like to replace the missing Age with some form of imputation. One way to do this is by filling in the mean age of all the passengers. However, we can be smarter about this and check the average age by passenger class. For example:"
},
{
"code": null,
"e": 3971,
"s": 3878,
"text": "sns.boxplot(x='Pclass', y='Age', data=df, palette='winter')"
},
{
"code": null,
"e": 4136,
"s": 3971,
"text": "We can see the wealthier passengers in the higher classes tend to be older, which makes sense. We’ll use these average age values to impute based on Pclass for Age."
},
{
"code": null,
"e": 4330,
"s": 4136,
"text": "pclass_age_map = { 1: 37, 2: 29, 3: 24,}def replace_age_na(x_df, fill_map): cond=x_df['Age'].isna() res=x_df.loc[cond,'Pclass'].map(fill_map) x_df.loc[cond,'Age']=res return x_df"
},
{
"code": null,
"e": 4641,
"s": 4330,
"text": "x_df['Age'].isna() selects the Age column and detects the missing values. Then, x_df.loc[cond, 'Pclass'] is used to access Pclass values conditionally and call Pandas map() for substituting each value with another value. Finally, x_df.loc[cond, 'Age']=res conditionally replace all missing Age values with res."
},
{
"code": null,
"e": 4668,
"s": 4641,
"text": "Running the following code"
},
{
"code": null,
"e": 4759,
"s": 4668,
"text": "res = ( pd.read_csv('data/train.csv') .pipe(replace_age_na, pclass_age_map))res.head()"
},
{
"code": null,
"e": 4868,
"s": 4759,
"text": "All missing ages should be replaced based on Pclass for Age. Let’s check this by running the heatmap on res."
},
{
"code": null,
"e": 4977,
"s": 4868,
"text": "sns.heatmap(res.isnull(), yticklabels=False, cbar=False, cmap='viridis')"
},
{
"code": null,
"e": 4994,
"s": 4977,
"text": "Great, it works!"
},
{
"code": null,
"e": 5157,
"s": 4994,
"text": "According to Titanic Data Dictionary, passengers departed from Southampton should have Embarked with value S . Let’s query that using the Pandas query() function."
},
{
"code": null,
"e": 5277,
"s": 5157,
"text": "res = ( pd.read_csv('data/train.csv') .pipe(replace_age_na, pclass_age_map) .query('Embarked == \"S\"'))res.head()"
},
{
"code": null,
"e": 5343,
"s": 5277,
"text": "To evaluate the query result, we can check it with value_counts()"
},
{
"code": null,
"e": 5407,
"s": 5343,
"text": "res.Embarked.value_counts()S 644Name: Embarked, dtype: int64"
},
{
"code": null,
"e": 5603,
"s": 5407,
"text": "We did this with a custom function in the Pandas pipe function article. Alternatively, we can use Pandas built-in function assign() to add new columns to a DataFrame. Let’s go ahead withassign()."
},
{
"code": null,
"e": 5874,
"s": 5603,
"text": "bins=[0, 13, 19, 61, sys.maxsize]labels=['<12', 'Teen', 'Adult', 'Older']res = ( pd.read_csv('data/train.csv') .pipe(replace_age_na, pclass_age_map) .query('Embarked == \"S\"') .assign(ageGroup = lambda df: pd.cut(df['Age'], bins=bins, labels=labels)))res.head()"
},
{
"code": null,
"e": 6044,
"s": 5874,
"text": "Pandas assign() is used to create a new column ageGroup. The new column is created with a lambda function together with Pandas cut() to convert ages to groups of ranges."
},
{
"code": null,
"e": 6101,
"s": 6044,
"text": "By running the code, we should get an output like below:"
},
{
"code": null,
"e": 6196,
"s": 6101,
"text": "A pivot table allows us to insights into our data. Let’s figure out the survival rate with it."
},
{
"code": null,
"e": 6570,
"s": 6196,
"text": "bins=[0, 13, 19, 61, sys.maxsize]labels=['<12', 'Teen', 'Adult', 'Older']( pd.read_csv('data/train.csv') .pipe(replace_age_na, pclass_age_map) .query('Embarked == \"S\"') .assign(ageGroup = lambda df: pd.cut(df['Age'], bins=bins, labels=labels)) .pivot_table( values='Survived', columns='Pclass', index='ageGroup', aggfunc='mean'))"
},
{
"code": null,
"e": 6912,
"s": 6570,
"text": "The first parameter values='Survived' specifies the column Survived to aggregate. Since the value of Survived is 1 or 0, we can use the aggregation function mean to calculate the survival rate and therefore aggfunc='mean' is used. index='ageGroup' and columns='Pclass' will display ageGroup as rows and Pclass as columns in the output table."
},
{
"code": null,
"e": 6969,
"s": 6912,
"text": "By running the code, we should get an output like below:"
},
{
"code": null,
"e": 7069,
"s": 6969,
"text": "The output we have got so far is not very self-explanatory. Let’s go ahead and improve the display."
},
{
"code": null,
"e": 7552,
"s": 7069,
"text": "bins=[0, 13, 19, 61, sys.maxsize]labels=['<12', 'Teen', 'Adult', 'Older']( pd.read_csv('data/train.csv') .pipe(replace_age_na, pclass_age_map) .query('Embarked == \"S\"') .assign(ageGroup = lambda df: pd.cut(df['Age'], bins=bins, labels=labels)) .pivot_table( values='Survived', columns='Pclass', index='ageGroup', aggfunc='mean') .rename_axis('', axis='columns') .rename('Class {}'.format, axis='columns') .style.format('{:.2%}'))"
},
{
"code": null,
"e": 7789,
"s": 7552,
"text": "rename_axis() is used to clear the columns label. After that, rename('Class {}'.format, axis='columns') is used to format the columns label. Finally,style.format('{:.2%}') is used to format values into percentages with 2 decimal places."
},
{
"code": null,
"e": 7845,
"s": 7789,
"text": "By running the code, we should get an output like below"
},
{
"code": null,
"e": 8074,
"s": 7845,
"text": "In terms of performance, according to DataSchool [2], the method chain tells pandas everything ahead of time, so pandas can plan its operations more efficiently, and thus it should have better performance than conventional ways."
},
{
"code": null,
"e": 8307,
"s": 8074,
"text": "Method Chainings are more readable. However, a very long method chaining could be less readable, especially when other functions get called inside the chain, for example, the cut() is used inside the assign() method in our tutorial."
},
{
"code": null,
"e": 8512,
"s": 8307,
"text": "In addition, a major drawback of using Method Chaining is that debugging can be harder, especially in a very long chain. If something looks wrong at the end, you don’t have intermediate values to inspect."
},
{
"code": null,
"e": 8598,
"s": 8512,
"text": "For a longer discussion of this topic, see Tom Augspurger’s Method Chaining post [1]."
},
{
"code": null,
"e": 8618,
"s": 8598,
"text": "Thanks for reading."
},
{
"code": null,
"e": 8681,
"s": 8618,
"text": "Please checkout the notebook on my Github for the source code."
},
{
"code": null,
"e": 8759,
"s": 8681,
"text": "Stay tuned if you are interested in the practical aspect of machine learning."
},
{
"code": null,
"e": 8820,
"s": 8759,
"text": "Lastly, here are 2 related articles you may be interested in"
},
{
"code": null,
"e": 8858,
"s": 8820,
"text": "Working with missing values in Pandas"
},
{
"code": null,
"e": 8913,
"s": 8858,
"text": "Using Pandas pipe function to improve code readability"
},
{
"code": null,
"e": 9006,
"s": 8913,
"text": "[1] Method Chaining from Tom Augspurger https://tomaugspurger.github.io/method-chaining.html"
}
]
|
How to determine if network type (2G, 3G or 4G) in Android Kotlin? | This example demonstrates how to determine if network type (2G, 3G or 4G) in Android Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/textViewTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:padding="8dp"
android:text="Tutorials Point"
android:textColor="@color/colorPrimaryDark"
android:textSize="48sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Detecting the network type 2G/3G/4G"
android:textAlignment="center"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 4 − Add the following code to src/MainActivity.kt
import android.content.Context
import android.os.Bundle
import android.telephony.TelephonyManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
getNetworkClass(applicationContext)
}
private fun getNetworkClass(context: Context) {
val mTelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as
TelephonyManager
when (Objects.requireNonNull(mTelephonyManager).networkType) {
TelephonyManager.NETWORK_TYPE_GPRS,
TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_CDMA,
TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN -> {
run { Toast.makeText(applicationContext, "Connection Available is 2G",
Toast.LENGTH_SHORT).show() }
run {
Toast.makeText(applicationContext, "Connection Available is 3G",
Toast.LENGTH_SHORT).show()
}
run {
Toast.makeText(applicationContext, "Connection Available is 4G",
Toast.LENGTH_SHORT).show()
}
return
}
TelephonyManager.NETWORK_TYPE_UMTS,
TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A,
TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA,
TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_EVDO_B,
TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP ->{
run {
Toast.makeText(applicationContext, "Connection Available is 3G",
Toast.LENGTH_SHORT).show()
}
run {
Toast.makeText(applicationContext, "Connection Available is 4G",
Toast.LENGTH_SHORT).show()
}
return
}
TelephonyManager.NETWORK_TYPE_LTE -> {
run {
Toast.makeText(applicationContext, "Connection Available is 4G",
Toast.LENGTH_SHORT).show()
}
return
}
else -> {
}
}
}
}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.kotlipapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "This example demonstrates how to determine if network type (2G, 3G or 4G) in Android Kotlin."
},
{
"code": null,
"e": 1283,
"s": 1155,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1348,
"s": 1283,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2449,
"s": 1348,
"text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/relativeLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textViewTitle\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:padding=\"8dp\"\n android:text=\"Tutorials Point\"\n android:textColor=\"@color/colorPrimaryDark\"\n android:textSize=\"48sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Detecting the network type 2G/3G/4G\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2504,
"s": 2449,
"text": "Step 4 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4854,
"s": 2504,
"text": "import android.content.Context\nimport android.os.Bundle\nimport android.telephony.TelephonyManager\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport java.util.*\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n getNetworkClass(applicationContext)\n }\n private fun getNetworkClass(context: Context) {\n val mTelephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as\n TelephonyManager\n when (Objects.requireNonNull(mTelephonyManager).networkType) {\n TelephonyManager.NETWORK_TYPE_GPRS,\n TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_CDMA,\n TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN -> {\n run { Toast.makeText(applicationContext, \"Connection Available is 2G\",\n Toast.LENGTH_SHORT).show() }\n run {\n Toast.makeText(applicationContext, \"Connection Available is 3G\",\n Toast.LENGTH_SHORT).show()\n }\n run {\n Toast.makeText(applicationContext, \"Connection Available is 4G\",\n Toast.LENGTH_SHORT).show()\n }\n return\n }\n TelephonyManager.NETWORK_TYPE_UMTS,\n TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A,\n TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA,\n TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_EVDO_B,\n TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP ->{\n run {\n Toast.makeText(applicationContext, \"Connection Available is 3G\",\n Toast.LENGTH_SHORT).show()\n }\n run {\n Toast.makeText(applicationContext, \"Connection Available is 4G\",\n Toast.LENGTH_SHORT).show()\n }\n return\n }\n TelephonyManager.NETWORK_TYPE_LTE -> {\n run {\n Toast.makeText(applicationContext, \"Connection Available is 4G\",\n Toast.LENGTH_SHORT).show()\n }\n return\n }\n else -> {\n }\n }\n }\n}"
},
{
"code": null,
"e": 4909,
"s": 4854,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5582,
"s": 4909,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.kotlipapp\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5930,
"s": 5582,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
]
|
MINUTE(), MICROSECOND() and HOUR() functions in MySQL - GeeksforGeeks | 09 Dec, 2021
1. MINUTE() : The MySQL MINUTE() function is used for return the minute part of a datetime value. It can be between 0 to 59.When the datetime is passed in MINUTE() function then it will return the minute value .
Syntax –
MINUTE(datetime)
Parameter – It take parameter a dateline value.
Return – It returns a minute numeric value between 0 to 59.
Example-1:
SELECT MINUTE ("2020-06-29 10:34:00");
Output –
34
Example-2:
SELECT MINUTE("4:10:17");
Output –
10
2. MICROSECOND() – The Mysql function MICROSECOND() is used for return the microsecond part of datetime value .It can be between 0 to 999999.When the datetime is passed in MINUTE() function then it will return the microsecond value .
Syntax [-
MICROSECOND(datetime)
Parameter – A datetime value.
Return – Return an integer
Example-1:
SELECT MICROSECOND("2010-07-20 06:24:10.967423");
Output –
967423
Example-2:
SELECT MICROSECOND("2005-10-10 12:24:17.000007");
Output –
7
3. HOUR() : The MySQL function HOUR() returns the hour part of a given datetime. It can be between 0 to 838.
Syntax –
HOUR(datetime)
Parameter – A datetime value.
Return – It return an integer value.
Example-1:
SELECT HOUR("12:24:17.000007");
Output –
12
Example-2:
SELECT MICROSECOND(""838:59:59"");
Output –
838
Supported Versions of MySQL :
MySQL 4.0
MySQL 4.1
MySQL 5.0
MySQL 5.1
MySQL 5.5
MySQL 5.6
MySQL 5.7
surindertarika1234
DBMS-SQL
mysql
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Trigger | Student Database
Introduction of B-Tree
Difference between Clustered and Non-clustered index
Introduction of ER Model
Introduction of DBMS (Database Management System) | Set 1
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
SQL Trigger | Student Database
CTE in SQL | [
{
"code": null,
"e": 23950,
"s": 23922,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 24163,
"s": 23950,
"text": "1. MINUTE() : The MySQL MINUTE() function is used for return the minute part of a datetime value. It can be between 0 to 59.When the datetime is passed in MINUTE() function then it will return the minute value . "
},
{
"code": null,
"e": 24173,
"s": 24163,
"text": "Syntax – "
},
{
"code": null,
"e": 24191,
"s": 24173,
"text": "MINUTE(datetime) "
},
{
"code": null,
"e": 24240,
"s": 24191,
"text": "Parameter – It take parameter a dateline value. "
},
{
"code": null,
"e": 24301,
"s": 24240,
"text": "Return – It returns a minute numeric value between 0 to 59. "
},
{
"code": null,
"e": 24314,
"s": 24301,
"text": "Example-1: "
},
{
"code": null,
"e": 24354,
"s": 24314,
"text": "SELECT MINUTE (\"2020-06-29 10:34:00\"); "
},
{
"code": null,
"e": 24365,
"s": 24354,
"text": "Output – "
},
{
"code": null,
"e": 24368,
"s": 24365,
"text": "34"
},
{
"code": null,
"e": 24381,
"s": 24368,
"text": "Example-2: "
},
{
"code": null,
"e": 24407,
"s": 24381,
"text": "SELECT MINUTE(\"4:10:17\");"
},
{
"code": null,
"e": 24418,
"s": 24407,
"text": "Output – "
},
{
"code": null,
"e": 24421,
"s": 24418,
"text": "10"
},
{
"code": null,
"e": 24656,
"s": 24421,
"text": "2. MICROSECOND() – The Mysql function MICROSECOND() is used for return the microsecond part of datetime value .It can be between 0 to 999999.When the datetime is passed in MINUTE() function then it will return the microsecond value . "
},
{
"code": null,
"e": 24668,
"s": 24656,
"text": "Syntax [- "
},
{
"code": null,
"e": 24690,
"s": 24668,
"text": "MICROSECOND(datetime)"
},
{
"code": null,
"e": 24721,
"s": 24690,
"text": "Parameter – A datetime value. "
},
{
"code": null,
"e": 24749,
"s": 24721,
"text": "Return – Return an integer "
},
{
"code": null,
"e": 24762,
"s": 24749,
"text": "Example-1: "
},
{
"code": null,
"e": 24813,
"s": 24762,
"text": "SELECT MICROSECOND(\"2010-07-20 06:24:10.967423\"); "
},
{
"code": null,
"e": 24824,
"s": 24813,
"text": "Output – "
},
{
"code": null,
"e": 24831,
"s": 24824,
"text": "967423"
},
{
"code": null,
"e": 24844,
"s": 24831,
"text": "Example-2: "
},
{
"code": null,
"e": 24895,
"s": 24844,
"text": "SELECT MICROSECOND(\"2005-10-10 12:24:17.000007\"); "
},
{
"code": null,
"e": 24906,
"s": 24895,
"text": "Output – "
},
{
"code": null,
"e": 24908,
"s": 24906,
"text": "7"
},
{
"code": null,
"e": 25018,
"s": 24908,
"text": "3. HOUR() : The MySQL function HOUR() returns the hour part of a given datetime. It can be between 0 to 838. "
},
{
"code": null,
"e": 25029,
"s": 25018,
"text": "Syntax – "
},
{
"code": null,
"e": 25045,
"s": 25029,
"text": "HOUR(datetime) "
},
{
"code": null,
"e": 25076,
"s": 25045,
"text": "Parameter – A datetime value. "
},
{
"code": null,
"e": 25114,
"s": 25076,
"text": "Return – It return an integer value. "
},
{
"code": null,
"e": 25127,
"s": 25114,
"text": "Example-1: "
},
{
"code": null,
"e": 25160,
"s": 25127,
"text": "SELECT HOUR(\"12:24:17.000007\"); "
},
{
"code": null,
"e": 25171,
"s": 25160,
"text": "Output – "
},
{
"code": null,
"e": 25174,
"s": 25171,
"text": "12"
},
{
"code": null,
"e": 25187,
"s": 25174,
"text": "Example-2: "
},
{
"code": null,
"e": 25223,
"s": 25187,
"text": "SELECT MICROSECOND(\"\"838:59:59\"\"); "
},
{
"code": null,
"e": 25234,
"s": 25223,
"text": "Output – "
},
{
"code": null,
"e": 25238,
"s": 25234,
"text": "838"
},
{
"code": null,
"e": 25270,
"s": 25238,
"text": "Supported Versions of MySQL : "
},
{
"code": null,
"e": 25280,
"s": 25270,
"text": "MySQL 4.0"
},
{
"code": null,
"e": 25290,
"s": 25280,
"text": "MySQL 4.1"
},
{
"code": null,
"e": 25300,
"s": 25290,
"text": "MySQL 5.0"
},
{
"code": null,
"e": 25310,
"s": 25300,
"text": "MySQL 5.1"
},
{
"code": null,
"e": 25320,
"s": 25310,
"text": "MySQL 5.5"
},
{
"code": null,
"e": 25330,
"s": 25320,
"text": "MySQL 5.6"
},
{
"code": null,
"e": 25341,
"s": 25330,
"text": "MySQL 5.7 "
},
{
"code": null,
"e": 25360,
"s": 25341,
"text": "surindertarika1234"
},
{
"code": null,
"e": 25369,
"s": 25360,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 25375,
"s": 25369,
"text": "mysql"
},
{
"code": null,
"e": 25380,
"s": 25375,
"text": "DBMS"
},
{
"code": null,
"e": 25384,
"s": 25380,
"text": "SQL"
},
{
"code": null,
"e": 25389,
"s": 25384,
"text": "DBMS"
},
{
"code": null,
"e": 25393,
"s": 25389,
"text": "SQL"
},
{
"code": null,
"e": 25491,
"s": 25393,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25522,
"s": 25491,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 25545,
"s": 25522,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 25598,
"s": 25545,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 25623,
"s": 25598,
"text": "Introduction of ER Model"
},
{
"code": null,
"e": 25681,
"s": 25623,
"text": "Introduction of DBMS (Database Management System) | Set 1"
},
{
"code": null,
"e": 25723,
"s": 25681,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 25767,
"s": 25723,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 25788,
"s": 25767,
"text": "SQL | ALTER (RENAME)"
},
{
"code": null,
"e": 25819,
"s": 25788,
"text": "SQL Trigger | Student Database"
}
]
|
Random Forest Algorithm in Python from Scratch | by Eligijus Bujokas | Towards Data Science | This article aims to demystify the popular random forest (here and throughout the text — RF) algorithm and show its principles by using graphs, code snippets and code outputs.
The full implementation of the RF algorithm written by me in python can be accessed via: https://github.com/Eligijus112/decision-tree-python
I highly encourage anyone who stumbled upon this article to dive deep into the code because the understanding of the code will make any future documentation reading about RF much more straightforward and less stressful.
Any suggestions about optimizations are highly encouraged and are welcomed via a pull request on GitHub.
The building blocks of RF are simple decision trees. This article will be much easier to read if the reader is familiar with the concept of a classification decision tree. It is highly recommended to go through the following article before going any further:
towardsdatascience.com
Scikit-learn in python has an implementation of the RF algorithm which is fast and reviewed hundreds of times:
scikit-learn.org
In the documentation, the first hyperparameter which needs to be defined is the n_estimators parameter with a default value of 100. The explanation of this parameter is very elegant:
The number of trees in the forest.
This explanation is very romantic but a stubborn mathematician reading for the first time may find this a little bit puzzling: what kind of forest and what kind of trees are we talking about?
The intuition behind the random forest algorithm can be split into two big parts: the random part and the forest part. Let us start with the latter.
A forest in real life is made up of a bunch of trees. A random forest classifier is made up of a bunch of decision tree classifiers (here and throughout the text — DT). The exact amount of DTs that make up the whole forest is defined with the n_estimators variable mentioned earlier.
Each DT in an RF algorithm is completely independent of one another. If the n_estimators variable is set to 50 then the forest is made up of 50 decision trees that were grown completely independently from one another and do not share any information.
A binary classification decision tree can be viewed as a function that takes input X and outputs either 1 or 0:
DT: X → {0, 1}
The final prediction of RF is a majority vote of the predictions made from each individual DT.
If out of 50 trees, 30 trees label a new observation as a 1 and 20 trees label the same observation as a 0 the final prediction of the random forest will be 1.
In the article about simple classification decision trees it is clear that with the same input and the same hyperparameters, the same output and the same rules will be learnt by a decision tree. So why grow 50 (or 100, or 1000, or k) of them? This is where the second part of the RF intuition comes in: the random part.
The random part in RF can be split into two parts.
The first part is the bootstrapping of data. A data bootstrap is a subsample of its rows with replacement. The part of the python implementation that creates a bootstrapped sample:
For example, if the whole dataset d were 10 rows:
The response variable is the Churn column and the three other columns are the features.
Three independent bootstrapped datasets of d might look like:
As we can see from the picture above, in the first sample, the 5th and the 8th rows are the same. Additionally, not all original observations are present.
If we define that the RF has k decision trees (n_estimators = k) then there will be k different bootstrapped datasets created and each tree will be grown with a different dataset. Each dataset can have the same number of rows as the original or can have fewer rows than the original dataset.
Thus if RF is made of 50 decision trees then the high-level graph of the RF would look like this:
Each of the fifty decision trees would be grown with a unique dataset.
The second part of random in the random forest is in the training phase. When fitting a classification decision tree on data, during each of the splitting choices, the features stays the same.
During a random forest classifier creation, each decision tree is grown a bit differently than in the algorithm implemented here
https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier
The only difference is that during each of the split creation moments, a random subsample of features is drawn and the maximum Gini gain is calculated with those features.
https://gist.github.com/Eligijus112/4c47be2f7566299bb8c4f97c107d82c6f
For example, let us assume that we have a bootstrapped data sample d and X matrix with 100 initial features. We can define how many features to leave during each splitting phase with the argument X_features_fraction (max_features in scikit-learn implementation). Let us set it to 0.05, meaning, that at each split, 5 random features (or 5%) will be selected for the split.
In the first node, there are five X features: 1, 25, 28, 30 and 98. The best split is found when splitting the 25th feature by value x. The two below nodes have another 5 random features where the best split is searched for.
Thus, the RF algorithm is as follows:
Select a set of hyperparameters.
For 1 to k trees do:
Generate a random bootstrapped data sample d.
Fit a decision tree on the data d. During each of the split during the growth stage, select a random subsample of features to split on.
When forecasting, get the prediction of each of the k trees and then select the label using a majority vote.
Let's fit an RF classifier on some real data. The full notebook and data can be accessed via:
https://github.com/Eligijus112/decision-tree-python/blob/main/RandomForestShowcase.ipynb
The dataset which is in my GitHub repository has 3333 rows and we will be using the following columns:
The objective is to create a classifier that predicts whether a telecom customer will churn or not. Churn is an event where a customer no longer uses a companies product. If churn = 1 it means that the user has switched to a different service provider or for any other reason shows no activity.
Let's split the data into train and test splits. The training data will have 75% of the rows (2500) and the test set will have 25% of the rows (833).
Growing 5 decision trees with 25% of features in every split and each tree having a depth of 2 we get the following forest:
------ Tree number: 1 Root | GINI impurity of the node: 0.27 | Class distribution in the node: {0: 2099, 1: 401} | Predicted class: 0|-------- Split rule: DayCalls <= 113.5 | GINI impurity of the node: 0.24 | Class distribution in the node: {0: 1598, 1: 257} | Predicted class: 0|---------------- Split rule: DayMins <= 287.7 | GINI impurity of the node: 0.21 | Class distribution in the node: {0: 1591, 1: 218} | Predicted class: 0|---------------- Split rule: DayMins > 287.7 | GINI impurity of the node: 0.26 | Class distribution in the node: {1: 39, 0: 7} | Predicted class: 1|-------- Split rule: DayCalls > 113.5 | GINI impurity of the node: 0.35 | Class distribution in the node: {0: 501, 1: 144} | Predicted class: 0|---------------- Split rule: DayMins <= 225.0 | GINI impurity of the node: 0.25 | Class distribution in the node: {0: 431, 1: 76} | Predicted class: 0|---------------- Split rule: DayMins > 225.0 | GINI impurity of the node: 0.5 | Class distribution in the node: {1: 68, 0: 70} | Predicted class: 0------ ------ Tree number: 2 Root | GINI impurity of the node: 0.26 | Class distribution in the node: {0: 2124, 1: 376} | Predicted class: 0|-------- Split rule: OverageFee <= 13.235 | GINI impurity of the node: 0.24 | Class distribution in the node: {0: 1921, 1: 307} | Predicted class: 0|---------------- Split rule: DayMins <= 261.45 | GINI impurity of the node: 0.18 | Class distribution in the node: {0: 1853, 1: 210} | Predicted class: 0|---------------- Split rule: DayMins > 261.45 | GINI impurity of the node: 0.48 | Class distribution in the node: {0: 68, 1: 97} | Predicted class: 1|-------- Split rule: OverageFee > 13.235 | GINI impurity of the node: 0.38 | Class distribution in the node: {1: 69, 0: 203} | Predicted class: 0|---------------- Split rule: DayMins <= 220.35 | GINI impurity of the node: 0.13 | Class distribution in the node: {0: 186, 1: 14} | Predicted class: 0|---------------- Split rule: DayMins > 220.35 | GINI impurity of the node: 0.36 | Class distribution in the node: {1: 55, 0: 17} | Predicted class: 1------ ------ Tree number: 3 Root | GINI impurity of the node: 0.25 | Class distribution in the node: {1: 366, 0: 2134} | Predicted class: 0|-------- Split rule: DataUsage <= 0.315 | GINI impurity of the node: 0.29 | Class distribution in the node: {1: 286, 0: 1364} | Predicted class: 0|---------------- Split rule: MonthlyCharge <= 62.05 | GINI impurity of the node: 0.18 | Class distribution in the node: {1: 144, 0: 1340} | Predicted class: 0|---------------- Split rule: MonthlyCharge > 62.05 | GINI impurity of the node: 0.25 | Class distribution in the node: {1: 142, 0: 24} | Predicted class: 1|-------- Split rule: DataUsage > 0.315 | GINI impurity of the node: 0.17 | Class distribution in the node: {0: 770, 1: 80} | Predicted class: 0|---------------- Split rule: RoamMins <= 13.45 | GINI impurity of the node: 0.12 | Class distribution in the node: {0: 701, 1: 49} | Predicted class: 0|---------------- Split rule: RoamMins > 13.45 | GINI impurity of the node: 0.43 | Class distribution in the node: {0: 69, 1: 31} | Predicted class: 0------ ------ Tree number: 4 Root | GINI impurity of the node: 0.26 | Class distribution in the node: {0: 2119, 1: 381} | Predicted class: 0|-------- Split rule: DayCalls <= 49.5 | GINI impurity of the node: 0.49 | Class distribution in the node: {1: 8, 0: 6} | Predicted class: 1|---------------- Split rule: MonthlyCharge <= 31.5 | GINI impurity of the node: 0.0 | Class distribution in the node: {0: 4} | Predicted class: 0|---------------- Split rule: MonthlyCharge > 31.5 | GINI impurity of the node: 0.32 | Class distribution in the node: {1: 8, 0: 2} | Predicted class: 1|-------- Split rule: DayCalls > 49.5 | GINI impurity of the node: 0.26 | Class distribution in the node: {0: 2113, 1: 373} | Predicted class: 0|---------------- Split rule: DayMins <= 264.6 | GINI impurity of the node: 0.21 | Class distribution in the node: {0: 2053, 1: 279} | Predicted class: 0|---------------- Split rule: DayMins > 264.6 | GINI impurity of the node: 0.48 | Class distribution in the node: {1: 94, 0: 60} | Predicted class: 1------ ------ Tree number: 5 Root | GINI impurity of the node: 0.24 | Class distribution in the node: {0: 2155, 1: 345} | Predicted class: 0|-------- Split rule: OverageFee <= 7.945 | GINI impurity of the node: 0.15 | Class distribution in the node: {0: 475, 1: 43} | Predicted class: 0|---------------- Split rule: AccountWeeks <= 7.0 | GINI impurity of the node: 0.28 | Class distribution in the node: {1: 5, 0: 1} | Predicted class: 1|---------------- Split rule: AccountWeeks > 7.0 | GINI impurity of the node: 0.14 | Class distribution in the node: {0: 474, 1: 38} | Predicted class: 0|-------- Split rule: OverageFee > 7.945 | GINI impurity of the node: 0.26 | Class distribution in the node: {0: 1680, 1: 302} | Predicted class: 0|---------------- Split rule: DayMins <= 259.9 | GINI impurity of the node: 0.2 | Class distribution in the node: {0: 1614, 1: 203} | Predicted class: 0|---------------- Split rule: DayMins > 259.9 | GINI impurity of the node: 0.48 | Class distribution in the node: {0: 66, 1: 99} | Predicted class: 1------
Every tree is a bit different from one another. The precision and recall scores on the test set with the selected hyperparameters are:
Let's try to increase the accuracy metrics by growing a more complex random forest.
When growing a random forest with 30 trees, 50% of features at each split and max_depth of 4 the accuracy in the test set is:
If we grow 100 trees, with 75% of the features and the maximum depth of the trees would be 5 the results are:
The scikit learn implementation gives very similar results:
# Skicit learn implementationfrom sklearn.ensemble import RandomForestClassifier# Initiatingrf_scikit = RandomForestClassifier(n_estimators=100, max_features=0.75, max_depth=5, min_samples_split=5)# Fitting start = time.time()rf_scikit.fit(X=train[features], y=train[‘Churn’])print(f”Time took for scikit learn: {round(time.time() — start, 2)} seconds”)# Forecasting yhatsc = rf_scikit.predict(test[features])test[‘yhatsc’] = yhatscprint(f”Total churns in test set: {test[‘Churn’].sum()}”)print(f”Total predicted churns in test set: {test[‘yhat’].sum()}”)print(f”Precision: {round(precision_score(test[‘Churn’], test[‘yhatsc’]), 2) * 100} %”)print(f”Recall: {round(recall_score(test[‘Churn’], test[‘yhatsc’]), 2) * 100} %”)
Note that the difference between the sklearn and the custom made code results may vary because of the random nature of bootstrapping data for each tree and the random features that are used to find the best split. Even running the same implementation with the same hyperparameters we will get slightly different results every time.
In summary, the random forest algorithm is made up of independent simple decision trees.
Each decision tree is created using a custom bootstrapped dataset. At every split and in every decision tree a random subsample of features is considered when searching for the best feature and feature value which increases the GINI gain.
The final prediction of an RF classifier is a majority vote of all the independent decision trees. | [
{
"code": null,
"e": 348,
"s": 172,
"text": "This article aims to demystify the popular random forest (here and throughout the text — RF) algorithm and show its principles by using graphs, code snippets and code outputs."
},
{
"code": null,
"e": 489,
"s": 348,
"text": "The full implementation of the RF algorithm written by me in python can be accessed via: https://github.com/Eligijus112/decision-tree-python"
},
{
"code": null,
"e": 709,
"s": 489,
"text": "I highly encourage anyone who stumbled upon this article to dive deep into the code because the understanding of the code will make any future documentation reading about RF much more straightforward and less stressful."
},
{
"code": null,
"e": 814,
"s": 709,
"text": "Any suggestions about optimizations are highly encouraged and are welcomed via a pull request on GitHub."
},
{
"code": null,
"e": 1073,
"s": 814,
"text": "The building blocks of RF are simple decision trees. This article will be much easier to read if the reader is familiar with the concept of a classification decision tree. It is highly recommended to go through the following article before going any further:"
},
{
"code": null,
"e": 1096,
"s": 1073,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1207,
"s": 1096,
"text": "Scikit-learn in python has an implementation of the RF algorithm which is fast and reviewed hundreds of times:"
},
{
"code": null,
"e": 1224,
"s": 1207,
"text": "scikit-learn.org"
},
{
"code": null,
"e": 1407,
"s": 1224,
"text": "In the documentation, the first hyperparameter which needs to be defined is the n_estimators parameter with a default value of 100. The explanation of this parameter is very elegant:"
},
{
"code": null,
"e": 1442,
"s": 1407,
"text": "The number of trees in the forest."
},
{
"code": null,
"e": 1634,
"s": 1442,
"text": "This explanation is very romantic but a stubborn mathematician reading for the first time may find this a little bit puzzling: what kind of forest and what kind of trees are we talking about?"
},
{
"code": null,
"e": 1783,
"s": 1634,
"text": "The intuition behind the random forest algorithm can be split into two big parts: the random part and the forest part. Let us start with the latter."
},
{
"code": null,
"e": 2067,
"s": 1783,
"text": "A forest in real life is made up of a bunch of trees. A random forest classifier is made up of a bunch of decision tree classifiers (here and throughout the text — DT). The exact amount of DTs that make up the whole forest is defined with the n_estimators variable mentioned earlier."
},
{
"code": null,
"e": 2318,
"s": 2067,
"text": "Each DT in an RF algorithm is completely independent of one another. If the n_estimators variable is set to 50 then the forest is made up of 50 decision trees that were grown completely independently from one another and do not share any information."
},
{
"code": null,
"e": 2430,
"s": 2318,
"text": "A binary classification decision tree can be viewed as a function that takes input X and outputs either 1 or 0:"
},
{
"code": null,
"e": 2445,
"s": 2430,
"text": "DT: X → {0, 1}"
},
{
"code": null,
"e": 2540,
"s": 2445,
"text": "The final prediction of RF is a majority vote of the predictions made from each individual DT."
},
{
"code": null,
"e": 2700,
"s": 2540,
"text": "If out of 50 trees, 30 trees label a new observation as a 1 and 20 trees label the same observation as a 0 the final prediction of the random forest will be 1."
},
{
"code": null,
"e": 3020,
"s": 2700,
"text": "In the article about simple classification decision trees it is clear that with the same input and the same hyperparameters, the same output and the same rules will be learnt by a decision tree. So why grow 50 (or 100, or 1000, or k) of them? This is where the second part of the RF intuition comes in: the random part."
},
{
"code": null,
"e": 3071,
"s": 3020,
"text": "The random part in RF can be split into two parts."
},
{
"code": null,
"e": 3252,
"s": 3071,
"text": "The first part is the bootstrapping of data. A data bootstrap is a subsample of its rows with replacement. The part of the python implementation that creates a bootstrapped sample:"
},
{
"code": null,
"e": 3302,
"s": 3252,
"text": "For example, if the whole dataset d were 10 rows:"
},
{
"code": null,
"e": 3390,
"s": 3302,
"text": "The response variable is the Churn column and the three other columns are the features."
},
{
"code": null,
"e": 3452,
"s": 3390,
"text": "Three independent bootstrapped datasets of d might look like:"
},
{
"code": null,
"e": 3607,
"s": 3452,
"text": "As we can see from the picture above, in the first sample, the 5th and the 8th rows are the same. Additionally, not all original observations are present."
},
{
"code": null,
"e": 3899,
"s": 3607,
"text": "If we define that the RF has k decision trees (n_estimators = k) then there will be k different bootstrapped datasets created and each tree will be grown with a different dataset. Each dataset can have the same number of rows as the original or can have fewer rows than the original dataset."
},
{
"code": null,
"e": 3997,
"s": 3899,
"text": "Thus if RF is made of 50 decision trees then the high-level graph of the RF would look like this:"
},
{
"code": null,
"e": 4068,
"s": 3997,
"text": "Each of the fifty decision trees would be grown with a unique dataset."
},
{
"code": null,
"e": 4261,
"s": 4068,
"text": "The second part of random in the random forest is in the training phase. When fitting a classification decision tree on data, during each of the splitting choices, the features stays the same."
},
{
"code": null,
"e": 4390,
"s": 4261,
"text": "During a random forest classifier creation, each decision tree is grown a bit differently than in the algorithm implemented here"
},
{
"code": null,
"e": 4517,
"s": 4390,
"text": "https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier"
},
{
"code": null,
"e": 4689,
"s": 4517,
"text": "The only difference is that during each of the split creation moments, a random subsample of features is drawn and the maximum Gini gain is calculated with those features."
},
{
"code": null,
"e": 4759,
"s": 4689,
"text": "https://gist.github.com/Eligijus112/4c47be2f7566299bb8c4f97c107d82c6f"
},
{
"code": null,
"e": 5132,
"s": 4759,
"text": "For example, let us assume that we have a bootstrapped data sample d and X matrix with 100 initial features. We can define how many features to leave during each splitting phase with the argument X_features_fraction (max_features in scikit-learn implementation). Let us set it to 0.05, meaning, that at each split, 5 random features (or 5%) will be selected for the split."
},
{
"code": null,
"e": 5357,
"s": 5132,
"text": "In the first node, there are five X features: 1, 25, 28, 30 and 98. The best split is found when splitting the 25th feature by value x. The two below nodes have another 5 random features where the best split is searched for."
},
{
"code": null,
"e": 5395,
"s": 5357,
"text": "Thus, the RF algorithm is as follows:"
},
{
"code": null,
"e": 5428,
"s": 5395,
"text": "Select a set of hyperparameters."
},
{
"code": null,
"e": 5449,
"s": 5428,
"text": "For 1 to k trees do:"
},
{
"code": null,
"e": 5495,
"s": 5449,
"text": "Generate a random bootstrapped data sample d."
},
{
"code": null,
"e": 5631,
"s": 5495,
"text": "Fit a decision tree on the data d. During each of the split during the growth stage, select a random subsample of features to split on."
},
{
"code": null,
"e": 5740,
"s": 5631,
"text": "When forecasting, get the prediction of each of the k trees and then select the label using a majority vote."
},
{
"code": null,
"e": 5834,
"s": 5740,
"text": "Let's fit an RF classifier on some real data. The full notebook and data can be accessed via:"
},
{
"code": null,
"e": 5923,
"s": 5834,
"text": "https://github.com/Eligijus112/decision-tree-python/blob/main/RandomForestShowcase.ipynb"
},
{
"code": null,
"e": 6026,
"s": 5923,
"text": "The dataset which is in my GitHub repository has 3333 rows and we will be using the following columns:"
},
{
"code": null,
"e": 6321,
"s": 6026,
"text": "The objective is to create a classifier that predicts whether a telecom customer will churn or not. Churn is an event where a customer no longer uses a companies product. If churn = 1 it means that the user has switched to a different service provider or for any other reason shows no activity."
},
{
"code": null,
"e": 6471,
"s": 6321,
"text": "Let's split the data into train and test splits. The training data will have 75% of the rows (2500) and the test set will have 25% of the rows (833)."
},
{
"code": null,
"e": 6595,
"s": 6471,
"text": "Growing 5 decision trees with 25% of features in every split and each tree having a depth of 2 we get the following forest:"
},
{
"code": null,
"e": 13186,
"s": 6595,
"text": "------ Tree number: 1 Root | GINI impurity of the node: 0.27 | Class distribution in the node: {0: 2099, 1: 401} | Predicted class: 0|-------- Split rule: DayCalls <= 113.5 | GINI impurity of the node: 0.24 | Class distribution in the node: {0: 1598, 1: 257} | Predicted class: 0|---------------- Split rule: DayMins <= 287.7 | GINI impurity of the node: 0.21 | Class distribution in the node: {0: 1591, 1: 218} | Predicted class: 0|---------------- Split rule: DayMins > 287.7 | GINI impurity of the node: 0.26 | Class distribution in the node: {1: 39, 0: 7} | Predicted class: 1|-------- Split rule: DayCalls > 113.5 | GINI impurity of the node: 0.35 | Class distribution in the node: {0: 501, 1: 144} | Predicted class: 0|---------------- Split rule: DayMins <= 225.0 | GINI impurity of the node: 0.25 | Class distribution in the node: {0: 431, 1: 76} | Predicted class: 0|---------------- Split rule: DayMins > 225.0 | GINI impurity of the node: 0.5 | Class distribution in the node: {1: 68, 0: 70} | Predicted class: 0------ ------ Tree number: 2 Root | GINI impurity of the node: 0.26 | Class distribution in the node: {0: 2124, 1: 376} | Predicted class: 0|-------- Split rule: OverageFee <= 13.235 | GINI impurity of the node: 0.24 | Class distribution in the node: {0: 1921, 1: 307} | Predicted class: 0|---------------- Split rule: DayMins <= 261.45 | GINI impurity of the node: 0.18 | Class distribution in the node: {0: 1853, 1: 210} | Predicted class: 0|---------------- Split rule: DayMins > 261.45 | GINI impurity of the node: 0.48 | Class distribution in the node: {0: 68, 1: 97} | Predicted class: 1|-------- Split rule: OverageFee > 13.235 | GINI impurity of the node: 0.38 | Class distribution in the node: {1: 69, 0: 203} | Predicted class: 0|---------------- Split rule: DayMins <= 220.35 | GINI impurity of the node: 0.13 | Class distribution in the node: {0: 186, 1: 14} | Predicted class: 0|---------------- Split rule: DayMins > 220.35 | GINI impurity of the node: 0.36 | Class distribution in the node: {1: 55, 0: 17} | Predicted class: 1------ ------ Tree number: 3 Root | GINI impurity of the node: 0.25 | Class distribution in the node: {1: 366, 0: 2134} | Predicted class: 0|-------- Split rule: DataUsage <= 0.315 | GINI impurity of the node: 0.29 | Class distribution in the node: {1: 286, 0: 1364} | Predicted class: 0|---------------- Split rule: MonthlyCharge <= 62.05 | GINI impurity of the node: 0.18 | Class distribution in the node: {1: 144, 0: 1340} | Predicted class: 0|---------------- Split rule: MonthlyCharge > 62.05 | GINI impurity of the node: 0.25 | Class distribution in the node: {1: 142, 0: 24} | Predicted class: 1|-------- Split rule: DataUsage > 0.315 | GINI impurity of the node: 0.17 | Class distribution in the node: {0: 770, 1: 80} | Predicted class: 0|---------------- Split rule: RoamMins <= 13.45 | GINI impurity of the node: 0.12 | Class distribution in the node: {0: 701, 1: 49} | Predicted class: 0|---------------- Split rule: RoamMins > 13.45 | GINI impurity of the node: 0.43 | Class distribution in the node: {0: 69, 1: 31} | Predicted class: 0------ ------ Tree number: 4 Root | GINI impurity of the node: 0.26 | Class distribution in the node: {0: 2119, 1: 381} | Predicted class: 0|-------- Split rule: DayCalls <= 49.5 | GINI impurity of the node: 0.49 | Class distribution in the node: {1: 8, 0: 6} | Predicted class: 1|---------------- Split rule: MonthlyCharge <= 31.5 | GINI impurity of the node: 0.0 | Class distribution in the node: {0: 4} | Predicted class: 0|---------------- Split rule: MonthlyCharge > 31.5 | GINI impurity of the node: 0.32 | Class distribution in the node: {1: 8, 0: 2} | Predicted class: 1|-------- Split rule: DayCalls > 49.5 | GINI impurity of the node: 0.26 | Class distribution in the node: {0: 2113, 1: 373} | Predicted class: 0|---------------- Split rule: DayMins <= 264.6 | GINI impurity of the node: 0.21 | Class distribution in the node: {0: 2053, 1: 279} | Predicted class: 0|---------------- Split rule: DayMins > 264.6 | GINI impurity of the node: 0.48 | Class distribution in the node: {1: 94, 0: 60} | Predicted class: 1------ ------ Tree number: 5 Root | GINI impurity of the node: 0.24 | Class distribution in the node: {0: 2155, 1: 345} | Predicted class: 0|-------- Split rule: OverageFee <= 7.945 | GINI impurity of the node: 0.15 | Class distribution in the node: {0: 475, 1: 43} | Predicted class: 0|---------------- Split rule: AccountWeeks <= 7.0 | GINI impurity of the node: 0.28 | Class distribution in the node: {1: 5, 0: 1} | Predicted class: 1|---------------- Split rule: AccountWeeks > 7.0 | GINI impurity of the node: 0.14 | Class distribution in the node: {0: 474, 1: 38} | Predicted class: 0|-------- Split rule: OverageFee > 7.945 | GINI impurity of the node: 0.26 | Class distribution in the node: {0: 1680, 1: 302} | Predicted class: 0|---------------- Split rule: DayMins <= 259.9 | GINI impurity of the node: 0.2 | Class distribution in the node: {0: 1614, 1: 203} | Predicted class: 0|---------------- Split rule: DayMins > 259.9 | GINI impurity of the node: 0.48 | Class distribution in the node: {0: 66, 1: 99} | Predicted class: 1------"
},
{
"code": null,
"e": 13321,
"s": 13186,
"text": "Every tree is a bit different from one another. The precision and recall scores on the test set with the selected hyperparameters are:"
},
{
"code": null,
"e": 13405,
"s": 13321,
"text": "Let's try to increase the accuracy metrics by growing a more complex random forest."
},
{
"code": null,
"e": 13531,
"s": 13405,
"text": "When growing a random forest with 30 trees, 50% of features at each split and max_depth of 4 the accuracy in the test set is:"
},
{
"code": null,
"e": 13641,
"s": 13531,
"text": "If we grow 100 trees, with 75% of the features and the maximum depth of the trees would be 5 the results are:"
},
{
"code": null,
"e": 13701,
"s": 13641,
"text": "The scikit learn implementation gives very similar results:"
},
{
"code": null,
"e": 14425,
"s": 13701,
"text": "# Skicit learn implementationfrom sklearn.ensemble import RandomForestClassifier# Initiatingrf_scikit = RandomForestClassifier(n_estimators=100, max_features=0.75, max_depth=5, min_samples_split=5)# Fitting start = time.time()rf_scikit.fit(X=train[features], y=train[‘Churn’])print(f”Time took for scikit learn: {round(time.time() — start, 2)} seconds”)# Forecasting yhatsc = rf_scikit.predict(test[features])test[‘yhatsc’] = yhatscprint(f”Total churns in test set: {test[‘Churn’].sum()}”)print(f”Total predicted churns in test set: {test[‘yhat’].sum()}”)print(f”Precision: {round(precision_score(test[‘Churn’], test[‘yhatsc’]), 2) * 100} %”)print(f”Recall: {round(recall_score(test[‘Churn’], test[‘yhatsc’]), 2) * 100} %”)"
},
{
"code": null,
"e": 14757,
"s": 14425,
"text": "Note that the difference between the sklearn and the custom made code results may vary because of the random nature of bootstrapping data for each tree and the random features that are used to find the best split. Even running the same implementation with the same hyperparameters we will get slightly different results every time."
},
{
"code": null,
"e": 14846,
"s": 14757,
"text": "In summary, the random forest algorithm is made up of independent simple decision trees."
},
{
"code": null,
"e": 15085,
"s": 14846,
"text": "Each decision tree is created using a custom bootstrapped dataset. At every split and in every decision tree a random subsample of features is considered when searching for the best feature and feature value which increases the GINI gain."
}
]
|
Character constants vs String literals in C# | Character literals are enclosed in single quotes. For example, 'x' and can be stored in a simple variable of char type. A character literal can be a plain character (such as 'x'), an escape sequence (such as '\t'), or a universal character (such as '\u02C0').
Certain characters in C# are preceded by a backslash. They have special meaning and they are used to represent like newline (\n) or tab (\t).
Live Demo
using System;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
Console.WriteLine("Welcome\t to the website\n\n");
Console.ReadLine();
}
}
}
Welcome to the website
String literals or constants are enclosed in double quotes "" or with @"". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. | [
{
"code": null,
"e": 1322,
"s": 1062,
"text": "Character literals are enclosed in single quotes. For example, 'x' and can be stored in a simple variable of char type. A character literal can be a plain character (such as 'x'), an escape sequence (such as '\\t'), or a universal character (such as '\\u02C0')."
},
{
"code": null,
"e": 1464,
"s": 1322,
"text": "Certain characters in C# are preceded by a backslash. They have special meaning and they are used to represent like newline (\\n) or tab (\\t)."
},
{
"code": null,
"e": 1475,
"s": 1464,
"text": " Live Demo"
},
{
"code": null,
"e": 1675,
"s": 1475,
"text": "using System;\nnamespace Demo {\n class MyApplication {\n static void Main(string[] args) {\n Console.WriteLine(\"Welcome\\t to the website\\n\\n\");\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 1698,
"s": 1675,
"text": "Welcome to the website"
},
{
"code": null,
"e": 1904,
"s": 1698,
"text": "String literals or constants are enclosed in double quotes \"\" or with @\"\". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters."
}
]
|
How MySQL IF ELSE statement can be used in a stored procedure? | MySQL IF ELSE statement implements a basic conditional construct when the expression evaluates to false. Its syntax is as follows −
IF expression THEN
statements;
ELSE
else-statements;
END IF;
The statements must end with a semicolon.
To demonstrate the use of IF ELSE statement within MySQL stored procedure, we are creating the following stored procedure which is based on the values, as shown below, of the table named ‘student_info’ −
mysql> Select * from student_info;
+------+---------+------------+------------+
| id | Name | Address | Subject |
+------+---------+------------+------------+
| 101 | YashPal | Amritsar | History |
| 105 | Gaurav | Jaipur | Literature |
| 125 | Raman | Shimla | Computers |
+------+---------+------------+------------+
3 rows in set (0.00 sec)
The following query will create a procedure named ‘coursedetails_IFELSE’ which have IF ELSE statements in it −
mysql> DELIMITER // ;
mysql> CREATE PROCEDURE coursedetails_IFELSE(IN S_Subject Varchar(20), OUT S_Course varchar(50))
-> BEGIN
-> DECLARE Sub Varchar(20);
-> SELECT Subject INTO SUB
-> FROM Student_info WHERE S_Subject = Subject;
-> IF Sub = 'Computers' THEN
-> SET S_Course = 'B.Tech(CSE)';
-> ELSE
-> SET S_Course = 'Subject Not in the table ';
-> END IF;
-> END //
Query OK, 0 rows affected (0.00 sec)
Now, we can see the result below when we invoke this procedure −
mysql> Delimiter ; //
mysql> CALL coursedetails_IFELSE('Computers', @S_Course);
Query OK, 1 row affected (0.00 sec)
mysql> Select @S_Course;
+-------------+
| @S_Course |
+-------------+
| B.Tech(CSE) |
+-------------+
1 row in set (0.00 sec)
mysql> CALL coursedetails_IFELSE ('History', @S_Course);
Query OK, 0 rows affected (0.00 sec)
mysql> Select @S_Course;
+--------------------------------+
| @S_Course |
+--------------------------------+
| Subject Not in the table |
+--------------------------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1194,
"s": 1062,
"text": "MySQL IF ELSE statement implements a basic conditional construct when the expression evaluates to false. Its syntax is as follows −"
},
{
"code": null,
"e": 1261,
"s": 1194,
"text": "IF expression THEN\n statements;\nELSE\n else-statements;\nEND IF;"
},
{
"code": null,
"e": 1303,
"s": 1261,
"text": "The statements must end with a semicolon."
},
{
"code": null,
"e": 1507,
"s": 1303,
"text": "To demonstrate the use of IF ELSE statement within MySQL stored procedure, we are creating the following stored procedure which is based on the values, as shown below, of the table named ‘student_info’ −"
},
{
"code": null,
"e": 1882,
"s": 1507,
"text": "mysql> Select * from student_info;\n+------+---------+------------+------------+\n| id | Name | Address | Subject |\n+------+---------+------------+------------+\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Jaipur | Literature |\n| 125 | Raman | Shimla | Computers |\n+------+---------+------------+------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1993,
"s": 1882,
"text": "The following query will create a procedure named ‘coursedetails_IFELSE’ which have IF ELSE statements in it −"
},
{
"code": null,
"e": 2429,
"s": 1993,
"text": "mysql> DELIMITER // ;\nmysql> CREATE PROCEDURE coursedetails_IFELSE(IN S_Subject Varchar(20), OUT S_Course varchar(50))\n -> BEGIN\n -> DECLARE Sub Varchar(20);\n -> SELECT Subject INTO SUB\n -> FROM Student_info WHERE S_Subject = Subject;\n -> IF Sub = 'Computers' THEN\n -> SET S_Course = 'B.Tech(CSE)';\n -> ELSE\n -> SET S_Course = 'Subject Not in the table ';\n -> END IF;\n -> END //\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 2494,
"s": 2429,
"text": "Now, we can see the result below when we invoke this procedure −"
},
{
"code": null,
"e": 3060,
"s": 2494,
"text": "mysql> Delimiter ; //\nmysql> CALL coursedetails_IFELSE('Computers', @S_Course);\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> Select @S_Course;\n+-------------+\n| @S_Course |\n+-------------+\n| B.Tech(CSE) |\n+-------------+\n1 row in set (0.00 sec)\n\nmysql> CALL coursedetails_IFELSE ('History', @S_Course);\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Select @S_Course;\n+--------------------------------+\n| @S_Course |\n+--------------------------------+\n| Subject Not in the table |\n+--------------------------------+\n1 row in set (0.00 sec)"
}
]
|
JSF - JDBC Integration | In this article, we'll demonstrate how to integrate database in JSF using JDBC.
Following are the database requirements to run this example.
Open Source and lightweight database
JDBC driver for PostgreSQL 9.1 and JDK 1.5 or above
Put PostgreSQL JDBC4 Driver jar in tomcat web server's lib directory.
create user user1;
create database testdb with owner = user1;
CREATE TABLE IF NOT EXISTS authors (
id int PRIMARY KEY,
name VARCHAR(25)
);
INSERT INTO authors(id, name) VALUES(1, 'Rob Bal');
INSERT INTO authors(id, name) VALUES(2, 'John Carter');
INSERT INTO authors(id, name) VALUES(3, 'Chris London');
INSERT INTO authors(id, name) VALUES(4, 'Truman De Bal');
INSERT INTO authors(id, name) VALUES(5, 'Emile Capote');
INSERT INTO authors(id, name) VALUES(7, 'Breech Jabber');
INSERT INTO authors(id, name) VALUES(8, 'Bob Carter');
INSERT INTO authors(id, name) VALUES(9, 'Nelson Mand');
INSERT INTO authors(id, name) VALUES(10, 'Tennant Mark');
alter user user1 with password 'user1';
grant all on authors to user1;
Let us create a test JSF application to test JDBC integration.
.authorTable {
border-collapse:collapse;
border-bottom:1px solid #000000;
}
.authorTableHeader {
text-align:center;
background:none repeat scroll 0 0 #B5B5B5;
border-bottom:1px solid #000000;
border-top:1px solid #000000;
padding:2px;
}
.authorTableOddRow {
text-align:center;
background:none repeat scroll 0 0 #FFFFFFF;
}
.authorTableEvenRow {
text-align:center;
background:none repeat scroll 0 0 #D3D3D3;
}
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.test</groupId>
<artifactId>helloworld</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>helloworld Maven Webapp</name>
<url>http://maven.apache.org</url >
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
</dependencies>
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/helloworld/resources
</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
package com.tutorialspoint.test;
public class Author {
int id;
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
package com.tutorialspoint.test;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ComponentSystemEvent;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
public List<Author> getAuthors() {
ResultSet rs = null;
PreparedStatement pst = null;
Connection con = getConnection();
String stm = "Select * from authors";
List<Author> records = new ArrayList<Author>();
try {
pst = con.prepareStatement(stm);
pst.execute();
rs = pst.getResultSet();
while(rs.next()) {
Author author = new Author();
author.setId(rs.getInt(1));
author.setName(rs.getString(2));
records.add(author);
}
} catch (SQLException e) {
e.printStackTrace();
}
return records;
}
public Connection getConnection() {
Connection con = null;
String url = "jdbc:postgresql://localhost/testdb";
String user = "user1";
String password = "user1";
try {
con = DriverManager.getConnection(url, user, password);
System.out.println("Connection completed.");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
finally {
}
return con;
}
}
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html">
<h:head>
<title>JSF Tutorial!</title>
<h:outputStylesheet library = "css" name = "styles.css" />
</h:head>
<h:body>
<h2>JDBC Integration Example</h2>
<h:dataTable value = "#{userData.authors}" var = "c"
styleClass = "authorTable"
headerClass = "authorTableHeader"
rowClasses = "authorTableOddRow,authorTableEvenRow">
<h:column><f:facet name = "header">Author ID</f:facet>
#{c.id}
</h:column>
<h:column><f:facet name = "header">Name</f:facet>
#{c.name}
</h:column>
</h:dataTable>
</h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
37 Lectures
3.5 hours
Chaand Sheikh
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2032,
"s": 1952,
"text": "In this article, we'll demonstrate how to integrate database in JSF using JDBC."
},
{
"code": null,
"e": 2093,
"s": 2032,
"text": "Following are the database requirements to run this example."
},
{
"code": null,
"e": 2130,
"s": 2093,
"text": "Open Source and lightweight database"
},
{
"code": null,
"e": 2182,
"s": 2130,
"text": "JDBC driver for PostgreSQL 9.1 and JDK 1.5 or above"
},
{
"code": null,
"e": 2252,
"s": 2182,
"text": "Put PostgreSQL JDBC4 Driver jar in tomcat web server's lib directory."
},
{
"code": null,
"e": 2982,
"s": 2252,
"text": "create user user1;\ncreate database testdb with owner = user1;\n\nCREATE TABLE IF NOT EXISTS authors (\n id int PRIMARY KEY, \n name VARCHAR(25)\n);\n\nINSERT INTO authors(id, name) VALUES(1, 'Rob Bal');\nINSERT INTO authors(id, name) VALUES(2, 'John Carter');\nINSERT INTO authors(id, name) VALUES(3, 'Chris London');\nINSERT INTO authors(id, name) VALUES(4, 'Truman De Bal');\nINSERT INTO authors(id, name) VALUES(5, 'Emile Capote');\nINSERT INTO authors(id, name) VALUES(7, 'Breech Jabber');\nINSERT INTO authors(id, name) VALUES(8, 'Bob Carter');\nINSERT INTO authors(id, name) VALUES(9, 'Nelson Mand');\nINSERT INTO authors(id, name) VALUES(10, 'Tennant Mark');\n\nalter user user1 with password 'user1';\n\ngrant all on authors to user1;"
},
{
"code": null,
"e": 3045,
"s": 2982,
"text": "Let us create a test JSF application to test JDBC integration."
},
{
"code": null,
"e": 3494,
"s": 3045,
"text": ".authorTable { \n border-collapse:collapse;\n border-bottom:1px solid #000000;\n}\n\n.authorTableHeader {\n text-align:center;\n background:none repeat scroll 0 0 #B5B5B5;\n border-bottom:1px solid #000000;\n border-top:1px solid #000000;\n padding:2px;\n}\n\n.authorTableOddRow {\n text-align:center;\n background:none repeat scroll 0 0 #FFFFFFF;\t\n}\n\n.authorTableEvenRow {\n text-align:center;\n background:none repeat scroll 0 0 #D3D3D3;\n}"
},
{
"code": null,
"e": 6232,
"s": 3494,
"text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/maven-v4_0_0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint.test</groupId>\n <artifactId>helloworld</artifactId>\n <packaging>war</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>helloworld Maven Webapp</name>\n <url>http://maven.apache.org</url >\n \n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n \n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-api</artifactId>\n <version>2.1.7</version>\n </dependency>\n \n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-impl</artifactId>\n <version>2.1.7</version>\n </dependency>\n \n <dependency>\n <groupId>javax.servlet</groupId>\n <artifactId>jstl</artifactId>\n <version>1.2</version>\n </dependency>\n \n <dependency>\n <groupId>postgresql</groupId>\n <artifactId>postgresql</artifactId>\n <version>9.1-901.jdbc4</version>\n </dependency>\n </dependencies>\n \n <build>\n <finalName>helloworld</finalName>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>2.3.1</version>\n <configuration>\n <source>1.6</source>\n <target>1.6</target>\n </configuration>\n </plugin>\n \n <plugin>\n <artifactId>maven-resources-plugin</artifactId>\n <version>2.6</version>\n <executions>\n <execution>\n <id>copy-resources</id>\n <phase>validate</phase>\n <goals>\n <goal>copy-resources</goal>\n </goals>\n \n <configuration>\n <outputDirectory>${basedir}/target/helloworld/resources\n </outputDirectory>\n <resources> \n <resource>\n <directory>src/main/resources</directory>\n <filtering>true</filtering>\n </resource>\n </resources> \n </configuration> \n </execution>\n </executions>\n </plugin>\n \n </plugins>\n </build>\n</project>"
},
{
"code": null,
"e": 6555,
"s": 6232,
"text": "package com.tutorialspoint.test;\n\npublic class Author {\n int id;\n String name;\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n public int getId() {\n return id;\n }\n \n public void setId(int id) {\n this.id = id;\n }\n}"
},
{
"code": null,
"e": 8242,
"s": 6555,
"text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\nimport javax.faces.event.ComponentSystemEvent;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n\n public List<Author> getAuthors() {\n ResultSet rs = null;\n PreparedStatement pst = null;\n Connection con = getConnection();\n String stm = \"Select * from authors\";\n List<Author> records = new ArrayList<Author>();\n \n try { \n pst = con.prepareStatement(stm);\n pst.execute();\n rs = pst.getResultSet();\n\n while(rs.next()) {\n Author author = new Author();\n author.setId(rs.getInt(1));\n author.setName(rs.getString(2));\n records.add(author);\t\t\t\t\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return records;\n }\n\n public Connection getConnection() {\n Connection con = null;\n String url = \"jdbc:postgresql://localhost/testdb\";\n String user = \"user1\";\n String password = \"user1\";\n \n try {\n con = DriverManager.getConnection(url, user, password);\n System.out.println(\"Connection completed.\");\n } catch (SQLException ex) {\n System.out.println(ex.getMessage());\n }\n \n finally {\n }\n return con;\n }\n}"
},
{
"code": null,
"e": 9211,
"s": 8242,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\">\n \n <h:head>\n <title>JSF Tutorial!</title>\n <h:outputStylesheet library = \"css\" name = \"styles.css\" /> \n </h:head>\n \n <h:body>\n <h2>JDBC Integration Example</h2>\n \n <h:dataTable value = \"#{userData.authors}\" var = \"c\"\n styleClass = \"authorTable\"\n headerClass = \"authorTableHeader\"\n rowClasses = \"authorTableOddRow,authorTableEvenRow\">\n \n <h:column><f:facet name = \"header\">Author ID</f:facet>\n #{c.id}\n </h:column>\n \n <h:column><f:facet name = \"header\">Name</f:facet>\n #{c.name}\n </h:column>\n </h:dataTable>\n </h:body>\n</html> "
},
{
"code": null,
"e": 9427,
"s": 9211,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result."
},
{
"code": null,
"e": 9462,
"s": 9427,
"text": "\n 37 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9477,
"s": 9462,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 9484,
"s": 9477,
"text": " Print"
},
{
"code": null,
"e": 9495,
"s": 9484,
"text": " Add Notes"
}
]
|
N-Queen Problem | Local Search using Hill climbing with random neighbour - GeeksforGeeks | 24 Jun, 2021
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 8 Queen problem.
Input: N = 4 Output: 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 Explanation: The Position of queens are: 1 – {1, 2} 2 – {2, 4} 3 – {3, 1} 4 – {4, 3}As we can see that we have placed all 4 queens in a way that no two queens are attacking each other. So, the output is correct
Input: N = 8 Output: 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0
Approach: The idea is to use Hill Climbing Algorithm.
While there are algorithms like Backtracking to solve N Queen problem, let’s take an AI approach in solving the problem.
It’s obvious that AI does not guarantee a globally correct solution all the time but it has quite a good success rate of about 97% which is not bad.
A description of the notions of all terminologies used in the problem will be given and are as follows:- Notion of a State – A state here in this context is any configuration of the N queens on the N X N board. Also, in order to reduce the search space let’s add an additional constraint that there can only be a single queen in a particular column. A state in the program is implemented using an array of length N, such that if state[i]=j then there is a queen at column index i and row index j.Notion of Neighbours – Neighbours of a state are other states with board configuration that differ from the current state’s board configuration with respect to the position of only a single queen. This queen that differs a state from its neighbour may be displaced anywhere in the same column.Optimisation function or Objective function – We know that local search is an optimization algorithm that searches the local space to optimize a function that takes the state as input and gives some value as an output. The value of the objective function of a state here in this context is the number of pairs of queens attacking each other. Our goal here is to find a state with the minimum objective value. This function has a maximum value of NC2 and a minimum value of 0.
Notion of a State – A state here in this context is any configuration of the N queens on the N X N board. Also, in order to reduce the search space let’s add an additional constraint that there can only be a single queen in a particular column. A state in the program is implemented using an array of length N, such that if state[i]=j then there is a queen at column index i and row index j.
Notion of Neighbours – Neighbours of a state are other states with board configuration that differ from the current state’s board configuration with respect to the position of only a single queen. This queen that differs a state from its neighbour may be displaced anywhere in the same column.
Optimisation function or Objective function – We know that local search is an optimization algorithm that searches the local space to optimize a function that takes the state as input and gives some value as an output. The value of the objective function of a state here in this context is the number of pairs of queens attacking each other. Our goal here is to find a state with the minimum objective value. This function has a maximum value of NC2 and a minimum value of 0.
Algorithm:
Start with a random state(i.e, a random configuration of the board).Scan through all possible neighbours of the current state and jump to the neighbour with the highest objective value, if found any. If there does not exist, a neighbour, with objective strictly higher than the current state but there exists one with equal then jump to any random neighbour(escaping shoulder and/or local optimum).Repeat step 2, until a state whose objective is strictly higher than all it’s neighbour’s objectives, is found and then go to step 4.The state thus found after the local search is either the local optimum or the global optimum. There is no way of escaping local optima but adding a random neighbour or a random restart each time a local optimum is encountered increases the chances of achieving global optimum(the solution to our problem).Output the state and return.
Start with a random state(i.e, a random configuration of the board).
Scan through all possible neighbours of the current state and jump to the neighbour with the highest objective value, if found any. If there does not exist, a neighbour, with objective strictly higher than the current state but there exists one with equal then jump to any random neighbour(escaping shoulder and/or local optimum).
Repeat step 2, until a state whose objective is strictly higher than all it’s neighbour’s objectives, is found and then go to step 4.
The state thus found after the local search is either the local optimum or the global optimum. There is no way of escaping local optima but adding a random neighbour or a random restart each time a local optimum is encountered increases the chances of achieving global optimum(the solution to our problem).
Output the state and return.
It is easily visible that the global optimum in our case is 0 since it is the minimum number of pairs of queens that can attack each other. Also, the random restart has a higher chance of achieving global optimum but we still use random neighbour because our problem of N queens does not has a high number of local optima and random neighbour is faster than random restart.
Conclusion: Random Neighbour escapes shoulders but only has a little chance of escaping local optima.Random Restart both escapes shoulders and has a high chance of escaping local optima.
Random Neighbour escapes shoulders but only has a little chance of escaping local optima.Random Restart both escapes shoulders and has a high chance of escaping local optima.
Random Neighbour escapes shoulders but only has a little chance of escaping local optima.
Random Restart both escapes shoulders and has a high chance of escaping local optima.
Below is the implementation of the Hill-Climbing algorithm:
CPP
// C++ implementation of the// above approach#include <iostream>#include <math.h> #define N 8using namespace std; // A utility function that configures// the 2D array "board" and// array "state" randomly to provide// a starting point for the algorithm.void configureRandomly(int board[][N], int* state){ // Seed for the random function srand(time(0)); // Iterating through the // column indices for (int i = 0; i < N; i++) { // Getting a random row index state[i] = rand() % N; // Placing a queen on the // obtained place in // chessboard. board[state[i]][i] = 1; }} // A utility function that prints// the 2D array "board".void printBoard(int board[][N]){ for (int i = 0; i < N; i++) { cout << " "; for (int j = 0; j < N; j++) { cout << board[i][j] << " "; } cout << "\n"; }} // A utility function that prints// the array "state".void printState(int* state){ for (int i = 0; i < N; i++) { cout << " " << state[i] << " "; } cout << endl;} // A utility function that compares// two arrays, state1 and state2 and// returns true if equal// and false otherwise.bool compareStates(int* state1, int* state2){ for (int i = 0; i < N; i++) { if (state1[i] != state2[i]) { return false; } } return true;} // A utility function that fills// the 2D array "board" with// values "value"void fill(int board[][N], int value){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { board[i][j] = value; } }} // This function calculates the// objective value of the// state(queens attacking each other)// using the board by the// following logic.int calculateObjective(int board[][N], int* state){ // For each queen in a column, we check // for other queens falling in the line // of our current queen and if found, // any, then we increment the variable // attacking count. // Number of queens attacking each other, // initially zero. int attacking = 0; // Variables to index a particular // row and column on board. int row, col; for (int i = 0; i < N; i++) { // At each column 'i', the queen is // placed at row 'state[i]', by the // definition of our state. // To the left of same row // (row remains constant // and col decreases) row = state[i], col = i - 1; while (col >= 0 && board[row][col] != 1) { col--; } if (col >= 0 && board[row][col] == 1) { attacking++; } // To the right of same row // (row remains constant // and col increases) row = state[i], col = i + 1; while (col < N && board[row][col] != 1) { col++; } if (col < N && board[row][col] == 1) { attacking++; } // Diagonally to the left up // (row and col simultaneously // decrease) row = state[i] - 1, col = i - 1; while (col >= 0 && row >= 0 && board[row][col] != 1) { col--; row--; } if (col >= 0 && row >= 0 && board[row][col] == 1) { attacking++; } // Diagonally to the right down // (row and col simultaneously // increase) row = state[i] + 1, col = i + 1; while (col < N && row < N && board[row][col] != 1) { col++; row++; } if (col < N && row < N && board[row][col] == 1) { attacking++; } // Diagonally to the left down // (col decreases and row // increases) row = state[i] + 1, col = i - 1; while (col >= 0 && row < N && board[row][col] != 1) { col--; row++; } if (col >= 0 && row < N && board[row][col] == 1) { attacking++; } // Diagonally to the right up // (col increases and row // decreases) row = state[i] - 1, col = i + 1; while (col < N && row >= 0 && board[row][col] != 1) { col++; row--; } if (col < N && row >= 0 && board[row][col] == 1) { attacking++; } } // Return pairs. return (int)(attacking / 2);} // A utility function that// generates a board configuration// given the state.void generateBoard(int board[][N], int* state){ fill(board, 0); for (int i = 0; i < N; i++) { board[state[i]][i] = 1; }} // A utility function that copies// contents of state2 to state1.void copyState(int* state1, int* state2){ for (int i = 0; i < N; i++) { state1[i] = state2[i]; }} // This function gets the neighbour// of the current state having// the least objective value// amongst all neighbours as// well as the current state.void getNeighbour(int board[][N], int* state){ // Declaring and initializing the // optimal board and state with // the current board and the state // as the starting point. int opBoard[N][N]; int opState[N]; copyState(opState, state); generateBoard(opBoard, opState); // Initializing the optimal // objective value int opObjective = calculateObjective(opBoard, opState); // Declaring and initializing // the temporary board and // state for the purpose // of computation. int NeighbourBoard[N][N]; int NeighbourState[N]; copyState(NeighbourState, state); generateBoard(NeighbourBoard, NeighbourState); // Iterating through all // possible neighbours // of the board. for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Condition for skipping the // current state if (j != state[i]) { // Initializing temporary // neighbour with the // current neighbour. NeighbourState[i] = j; NeighbourBoard[NeighbourState[i]][i] = 1; NeighbourBoard[state[i]][i] = 0; // Calculating the objective // value of the neighbour. int temp = calculateObjective( NeighbourBoard, NeighbourState); // Comparing temporary and optimal // neighbour objectives and if // temporary is less than optimal // then updating accordingly. if (temp <= opObjective) { opObjective = temp; copyState(opState, NeighbourState); generateBoard(opBoard, opState); } // Going back to the original // configuration for the next // iteration. NeighbourBoard[NeighbourState[i]][i] = 0; NeighbourState[i] = state[i]; NeighbourBoard[state[i]][i] = 1; } } } // Copying the optimal board and // state thus found to the current // board and, state since c++ doesn't // allow returning multiple values. copyState(state, opState); fill(board, 0); generateBoard(board, state);} void hillClimbing(int board[][N], int* state){ // Declaring and initializing the // neighbour board and state with // the current board and the state // as the starting point. int neighbourBoard[N][N] = {}; int neighbourState[N]; copyState(neighbourState, state); generateBoard(neighbourBoard, neighbourState); do { // Copying the neighbour board and // state to the current board and // state, since a neighbour // becomes current after the jump. copyState(state, neighbourState); generateBoard(board, state); // Getting the optimal neighbour getNeighbour(neighbourBoard, neighbourState); if (compareStates(state, neighbourState)) { // If neighbour and current are // equal then no optimal neighbour // exists and therefore output the // result and break the loop. printBoard(board); break; } else if (calculateObjective(board, state) == calculateObjective( neighbourBoard, neighbourState)) { // If neighbour and current are // not equal but their objectives // are equal then we are either // approaching a shoulder or a // local optimum, in any case, // jump to a random neighbour // to escape it. // Random neighbour neighbourState[rand() % N] = rand() % N; generateBoard(neighbourBoard, neighbourState); } } while (true);} // Driver codeint main(){ int state[N] = {}; int board[N][N] = {}; // Getting a starting point by // randomly configuring the board configureRandomly(board, state); // Do hill climbing on the // board obtained hillClimbing(board, state); return 0;}
0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
0 1 0 0 0 0 0 0
Complexity Analysis
The time complexity for this algorithm can be divided into three parts: Calculating Objective – The calculation of objective involves iterating through all queens on board and checking the no. of attacking queens, which is done by our calculateObjective function in O(N2) time. Neighbour Selection and Number of neighbours – The description of neighbours in our problem gives a total of N(N-1) neighbours for the current state. The selection procedure is best fit and therefore requires iterating through all neighbours, which is again O(N2). Search Space – Search space of our problem consists of a total of NN states, corresponding to all possible configurations of the N Queens on board. Note that this is after taking into account the additional constraint of one queen per column.
Calculating Objective – The calculation of objective involves iterating through all queens on board and checking the no. of attacking queens, which is done by our calculateObjective function in O(N2) time. Neighbour Selection and Number of neighbours – The description of neighbours in our problem gives a total of N(N-1) neighbours for the current state. The selection procedure is best fit and therefore requires iterating through all neighbours, which is again O(N2). Search Space – Search space of our problem consists of a total of NN states, corresponding to all possible configurations of the N Queens on board. Note that this is after taking into account the additional constraint of one queen per column.
Calculating Objective – The calculation of objective involves iterating through all queens on board and checking the no. of attacking queens, which is done by our calculateObjective function in O(N2) time.
Neighbour Selection and Number of neighbours – The description of neighbours in our problem gives a total of N(N-1) neighbours for the current state. The selection procedure is best fit and therefore requires iterating through all neighbours, which is again O(N2).
Search Space – Search space of our problem consists of a total of NN states, corresponding to all possible configurations of the N Queens on board. Note that this is after taking into account the additional constraint of one queen per column.
Therefore, the worst-case time complexity of our algorithm is O(NN). But, this worst-case occurs rarely in practice and thus we can safely consider it to be as good as any other algorithm there is for the N Queen problem. Hence, the effective time complexity consists of only calculating the objective for all neighbours up to a certain depth(no of jumps the search makes), which does not depend on N. Therefore, if the depth of search is d then the time complexity is O(N2 * N2 * d), which is O(d*N4).
prasantkpatel
clintra
chessboard-problems
Arrays
Backtracking
Mathematical
Arrays
Mathematical
Backtracking
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
Multidimensional Arrays in Java
Introduction to Arrays
Python | Using 2D arrays/lists the right way
Linked List vs Array
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Backtracking | Introduction
Sudoku | Backtracking-7
m Coloring Problem | Backtracking-5 | [
{
"code": null,
"e": 25172,
"s": 25144,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 25350,
"s": 25172,
"text": "The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for 8 Queen problem. "
},
{
"code": null,
"e": 25615,
"s": 25350,
"text": "Input: N = 4 Output: 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 Explanation: The Position of queens are: 1 – {1, 2} 2 – {2, 4} 3 – {3, 1} 4 – {4, 3}As we can see that we have placed all 4 queens in a way that no two queens are attacking each other. So, the output is correct "
},
{
"code": null,
"e": 25766,
"s": 25615,
"text": "Input: N = 8 Output: 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 "
},
{
"code": null,
"e": 25821,
"s": 25766,
"text": "Approach: The idea is to use Hill Climbing Algorithm. "
},
{
"code": null,
"e": 25942,
"s": 25821,
"text": "While there are algorithms like Backtracking to solve N Queen problem, let’s take an AI approach in solving the problem."
},
{
"code": null,
"e": 26091,
"s": 25942,
"text": "It’s obvious that AI does not guarantee a globally correct solution all the time but it has quite a good success rate of about 97% which is not bad."
},
{
"code": null,
"e": 27358,
"s": 26091,
"text": "A description of the notions of all terminologies used in the problem will be given and are as follows:- Notion of a State – A state here in this context is any configuration of the N queens on the N X N board. Also, in order to reduce the search space let’s add an additional constraint that there can only be a single queen in a particular column. A state in the program is implemented using an array of length N, such that if state[i]=j then there is a queen at column index i and row index j.Notion of Neighbours – Neighbours of a state are other states with board configuration that differ from the current state’s board configuration with respect to the position of only a single queen. This queen that differs a state from its neighbour may be displaced anywhere in the same column.Optimisation function or Objective function – We know that local search is an optimization algorithm that searches the local space to optimize a function that takes the state as input and gives some value as an output. The value of the objective function of a state here in this context is the number of pairs of queens attacking each other. Our goal here is to find a state with the minimum objective value. This function has a maximum value of NC2 and a minimum value of 0. "
},
{
"code": null,
"e": 27750,
"s": 27358,
"text": "Notion of a State – A state here in this context is any configuration of the N queens on the N X N board. Also, in order to reduce the search space let’s add an additional constraint that there can only be a single queen in a particular column. A state in the program is implemented using an array of length N, such that if state[i]=j then there is a queen at column index i and row index j."
},
{
"code": null,
"e": 28044,
"s": 27750,
"text": "Notion of Neighbours – Neighbours of a state are other states with board configuration that differ from the current state’s board configuration with respect to the position of only a single queen. This queen that differs a state from its neighbour may be displaced anywhere in the same column."
},
{
"code": null,
"e": 28522,
"s": 28044,
"text": "Optimisation function or Objective function – We know that local search is an optimization algorithm that searches the local space to optimize a function that takes the state as input and gives some value as an output. The value of the objective function of a state here in this context is the number of pairs of queens attacking each other. Our goal here is to find a state with the minimum objective value. This function has a maximum value of NC2 and a minimum value of 0. "
},
{
"code": null,
"e": 28535,
"s": 28522,
"text": "Algorithm: "
},
{
"code": null,
"e": 29401,
"s": 28535,
"text": "Start with a random state(i.e, a random configuration of the board).Scan through all possible neighbours of the current state and jump to the neighbour with the highest objective value, if found any. If there does not exist, a neighbour, with objective strictly higher than the current state but there exists one with equal then jump to any random neighbour(escaping shoulder and/or local optimum).Repeat step 2, until a state whose objective is strictly higher than all it’s neighbour’s objectives, is found and then go to step 4.The state thus found after the local search is either the local optimum or the global optimum. There is no way of escaping local optima but adding a random neighbour or a random restart each time a local optimum is encountered increases the chances of achieving global optimum(the solution to our problem).Output the state and return."
},
{
"code": null,
"e": 29470,
"s": 29401,
"text": "Start with a random state(i.e, a random configuration of the board)."
},
{
"code": null,
"e": 29801,
"s": 29470,
"text": "Scan through all possible neighbours of the current state and jump to the neighbour with the highest objective value, if found any. If there does not exist, a neighbour, with objective strictly higher than the current state but there exists one with equal then jump to any random neighbour(escaping shoulder and/or local optimum)."
},
{
"code": null,
"e": 29935,
"s": 29801,
"text": "Repeat step 2, until a state whose objective is strictly higher than all it’s neighbour’s objectives, is found and then go to step 4."
},
{
"code": null,
"e": 30242,
"s": 29935,
"text": "The state thus found after the local search is either the local optimum or the global optimum. There is no way of escaping local optima but adding a random neighbour or a random restart each time a local optimum is encountered increases the chances of achieving global optimum(the solution to our problem)."
},
{
"code": null,
"e": 30271,
"s": 30242,
"text": "Output the state and return."
},
{
"code": null,
"e": 30645,
"s": 30271,
"text": "It is easily visible that the global optimum in our case is 0 since it is the minimum number of pairs of queens that can attack each other. Also, the random restart has a higher chance of achieving global optimum but we still use random neighbour because our problem of N queens does not has a high number of local optima and random neighbour is faster than random restart."
},
{
"code": null,
"e": 30834,
"s": 30645,
"text": "Conclusion: Random Neighbour escapes shoulders but only has a little chance of escaping local optima.Random Restart both escapes shoulders and has a high chance of escaping local optima. "
},
{
"code": null,
"e": 31011,
"s": 30834,
"text": "Random Neighbour escapes shoulders but only has a little chance of escaping local optima.Random Restart both escapes shoulders and has a high chance of escaping local optima. "
},
{
"code": null,
"e": 31101,
"s": 31011,
"text": "Random Neighbour escapes shoulders but only has a little chance of escaping local optima."
},
{
"code": null,
"e": 31189,
"s": 31101,
"text": "Random Restart both escapes shoulders and has a high chance of escaping local optima. "
},
{
"code": null,
"e": 31249,
"s": 31189,
"text": "Below is the implementation of the Hill-Climbing algorithm:"
},
{
"code": null,
"e": 31253,
"s": 31249,
"text": "CPP"
},
{
"code": "// C++ implementation of the// above approach#include <iostream>#include <math.h> #define N 8using namespace std; // A utility function that configures// the 2D array \"board\" and// array \"state\" randomly to provide// a starting point for the algorithm.void configureRandomly(int board[][N], int* state){ // Seed for the random function srand(time(0)); // Iterating through the // column indices for (int i = 0; i < N; i++) { // Getting a random row index state[i] = rand() % N; // Placing a queen on the // obtained place in // chessboard. board[state[i]][i] = 1; }} // A utility function that prints// the 2D array \"board\".void printBoard(int board[][N]){ for (int i = 0; i < N; i++) { cout << \" \"; for (int j = 0; j < N; j++) { cout << board[i][j] << \" \"; } cout << \"\\n\"; }} // A utility function that prints// the array \"state\".void printState(int* state){ for (int i = 0; i < N; i++) { cout << \" \" << state[i] << \" \"; } cout << endl;} // A utility function that compares// two arrays, state1 and state2 and// returns true if equal// and false otherwise.bool compareStates(int* state1, int* state2){ for (int i = 0; i < N; i++) { if (state1[i] != state2[i]) { return false; } } return true;} // A utility function that fills// the 2D array \"board\" with// values \"value\"void fill(int board[][N], int value){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { board[i][j] = value; } }} // This function calculates the// objective value of the// state(queens attacking each other)// using the board by the// following logic.int calculateObjective(int board[][N], int* state){ // For each queen in a column, we check // for other queens falling in the line // of our current queen and if found, // any, then we increment the variable // attacking count. // Number of queens attacking each other, // initially zero. int attacking = 0; // Variables to index a particular // row and column on board. int row, col; for (int i = 0; i < N; i++) { // At each column 'i', the queen is // placed at row 'state[i]', by the // definition of our state. // To the left of same row // (row remains constant // and col decreases) row = state[i], col = i - 1; while (col >= 0 && board[row][col] != 1) { col--; } if (col >= 0 && board[row][col] == 1) { attacking++; } // To the right of same row // (row remains constant // and col increases) row = state[i], col = i + 1; while (col < N && board[row][col] != 1) { col++; } if (col < N && board[row][col] == 1) { attacking++; } // Diagonally to the left up // (row and col simultaneously // decrease) row = state[i] - 1, col = i - 1; while (col >= 0 && row >= 0 && board[row][col] != 1) { col--; row--; } if (col >= 0 && row >= 0 && board[row][col] == 1) { attacking++; } // Diagonally to the right down // (row and col simultaneously // increase) row = state[i] + 1, col = i + 1; while (col < N && row < N && board[row][col] != 1) { col++; row++; } if (col < N && row < N && board[row][col] == 1) { attacking++; } // Diagonally to the left down // (col decreases and row // increases) row = state[i] + 1, col = i - 1; while (col >= 0 && row < N && board[row][col] != 1) { col--; row++; } if (col >= 0 && row < N && board[row][col] == 1) { attacking++; } // Diagonally to the right up // (col increases and row // decreases) row = state[i] - 1, col = i + 1; while (col < N && row >= 0 && board[row][col] != 1) { col++; row--; } if (col < N && row >= 0 && board[row][col] == 1) { attacking++; } } // Return pairs. return (int)(attacking / 2);} // A utility function that// generates a board configuration// given the state.void generateBoard(int board[][N], int* state){ fill(board, 0); for (int i = 0; i < N; i++) { board[state[i]][i] = 1; }} // A utility function that copies// contents of state2 to state1.void copyState(int* state1, int* state2){ for (int i = 0; i < N; i++) { state1[i] = state2[i]; }} // This function gets the neighbour// of the current state having// the least objective value// amongst all neighbours as// well as the current state.void getNeighbour(int board[][N], int* state){ // Declaring and initializing the // optimal board and state with // the current board and the state // as the starting point. int opBoard[N][N]; int opState[N]; copyState(opState, state); generateBoard(opBoard, opState); // Initializing the optimal // objective value int opObjective = calculateObjective(opBoard, opState); // Declaring and initializing // the temporary board and // state for the purpose // of computation. int NeighbourBoard[N][N]; int NeighbourState[N]; copyState(NeighbourState, state); generateBoard(NeighbourBoard, NeighbourState); // Iterating through all // possible neighbours // of the board. for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Condition for skipping the // current state if (j != state[i]) { // Initializing temporary // neighbour with the // current neighbour. NeighbourState[i] = j; NeighbourBoard[NeighbourState[i]][i] = 1; NeighbourBoard[state[i]][i] = 0; // Calculating the objective // value of the neighbour. int temp = calculateObjective( NeighbourBoard, NeighbourState); // Comparing temporary and optimal // neighbour objectives and if // temporary is less than optimal // then updating accordingly. if (temp <= opObjective) { opObjective = temp; copyState(opState, NeighbourState); generateBoard(opBoard, opState); } // Going back to the original // configuration for the next // iteration. NeighbourBoard[NeighbourState[i]][i] = 0; NeighbourState[i] = state[i]; NeighbourBoard[state[i]][i] = 1; } } } // Copying the optimal board and // state thus found to the current // board and, state since c++ doesn't // allow returning multiple values. copyState(state, opState); fill(board, 0); generateBoard(board, state);} void hillClimbing(int board[][N], int* state){ // Declaring and initializing the // neighbour board and state with // the current board and the state // as the starting point. int neighbourBoard[N][N] = {}; int neighbourState[N]; copyState(neighbourState, state); generateBoard(neighbourBoard, neighbourState); do { // Copying the neighbour board and // state to the current board and // state, since a neighbour // becomes current after the jump. copyState(state, neighbourState); generateBoard(board, state); // Getting the optimal neighbour getNeighbour(neighbourBoard, neighbourState); if (compareStates(state, neighbourState)) { // If neighbour and current are // equal then no optimal neighbour // exists and therefore output the // result and break the loop. printBoard(board); break; } else if (calculateObjective(board, state) == calculateObjective( neighbourBoard, neighbourState)) { // If neighbour and current are // not equal but their objectives // are equal then we are either // approaching a shoulder or a // local optimum, in any case, // jump to a random neighbour // to escape it. // Random neighbour neighbourState[rand() % N] = rand() % N; generateBoard(neighbourBoard, neighbourState); } } while (true);} // Driver codeint main(){ int state[N] = {}; int board[N][N] = {}; // Getting a starting point by // randomly configuring the board configureRandomly(board, state); // Do hill climbing on the // board obtained hillClimbing(board, state); return 0;}",
"e": 40894,
"s": 31253,
"text": null
},
{
"code": null,
"e": 41037,
"s": 40894,
"text": " 0 0 1 0 0 0 0 0 \n 0 0 0 0 0 1 0 0 \n 0 0 0 0 0 0 0 1 \n 1 0 0 0 0 0 0 0 \n 0 0 0 1 0 0 0 0 \n 0 0 0 0 0 0 1 0 \n 0 0 0 0 1 0 0 0 \n 0 1 0 0 0 0 0 0"
},
{
"code": null,
"e": 41061,
"s": 41039,
"text": "Complexity Analysis "
},
{
"code": null,
"e": 41852,
"s": 41061,
"text": "The time complexity for this algorithm can be divided into three parts: Calculating Objective – The calculation of objective involves iterating through all queens on board and checking the no. of attacking queens, which is done by our calculateObjective function in O(N2) time. Neighbour Selection and Number of neighbours – The description of neighbours in our problem gives a total of N(N-1) neighbours for the current state. The selection procedure is best fit and therefore requires iterating through all neighbours, which is again O(N2). Search Space – Search space of our problem consists of a total of NN states, corresponding to all possible configurations of the N Queens on board. Note that this is after taking into account the additional constraint of one queen per column. "
},
{
"code": null,
"e": 42571,
"s": 41852,
"text": "Calculating Objective – The calculation of objective involves iterating through all queens on board and checking the no. of attacking queens, which is done by our calculateObjective function in O(N2) time. Neighbour Selection and Number of neighbours – The description of neighbours in our problem gives a total of N(N-1) neighbours for the current state. The selection procedure is best fit and therefore requires iterating through all neighbours, which is again O(N2). Search Space – Search space of our problem consists of a total of NN states, corresponding to all possible configurations of the N Queens on board. Note that this is after taking into account the additional constraint of one queen per column. "
},
{
"code": null,
"e": 42779,
"s": 42571,
"text": "Calculating Objective – The calculation of objective involves iterating through all queens on board and checking the no. of attacking queens, which is done by our calculateObjective function in O(N2) time. "
},
{
"code": null,
"e": 43046,
"s": 42779,
"text": "Neighbour Selection and Number of neighbours – The description of neighbours in our problem gives a total of N(N-1) neighbours for the current state. The selection procedure is best fit and therefore requires iterating through all neighbours, which is again O(N2). "
},
{
"code": null,
"e": 43292,
"s": 43046,
"text": "Search Space – Search space of our problem consists of a total of NN states, corresponding to all possible configurations of the N Queens on board. Note that this is after taking into account the additional constraint of one queen per column. "
},
{
"code": null,
"e": 43797,
"s": 43292,
"text": "Therefore, the worst-case time complexity of our algorithm is O(NN). But, this worst-case occurs rarely in practice and thus we can safely consider it to be as good as any other algorithm there is for the N Queen problem. Hence, the effective time complexity consists of only calculating the objective for all neighbours up to a certain depth(no of jumps the search makes), which does not depend on N. Therefore, if the depth of search is d then the time complexity is O(N2 * N2 * d), which is O(d*N4). "
},
{
"code": null,
"e": 43811,
"s": 43797,
"text": "prasantkpatel"
},
{
"code": null,
"e": 43819,
"s": 43811,
"text": "clintra"
},
{
"code": null,
"e": 43839,
"s": 43819,
"text": "chessboard-problems"
},
{
"code": null,
"e": 43846,
"s": 43839,
"text": "Arrays"
},
{
"code": null,
"e": 43859,
"s": 43846,
"text": "Backtracking"
},
{
"code": null,
"e": 43872,
"s": 43859,
"text": "Mathematical"
},
{
"code": null,
"e": 43879,
"s": 43872,
"text": "Arrays"
},
{
"code": null,
"e": 43892,
"s": 43879,
"text": "Mathematical"
},
{
"code": null,
"e": 43905,
"s": 43892,
"text": "Backtracking"
},
{
"code": null,
"e": 44003,
"s": 43905,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44071,
"s": 44003,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 44103,
"s": 44071,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 44126,
"s": 44103,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 44171,
"s": 44126,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 44192,
"s": 44171,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 44252,
"s": 44192,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 44337,
"s": 44252,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 44365,
"s": 44337,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 44389,
"s": 44365,
"text": "Sudoku | Backtracking-7"
}
]
|
How to Configure Github Actions the Easy Way. | by Salma El Shahawy | Towards Data Science | In my previous article, I walked you through a step by step tutorial to correctly setting up the python3 environment using pyenv on your local machine. However, some issues may arise in some circumstances due to some conflicts resulting from pull requests that use different python versions or even missing modules.
This tutorial will demonstrate the steps to build a standard workflow for any project utilizing Github actions plugins. Configuring Github actions in the project CI folder would protect the codebase pull requests that don’t meet the code standards regarding code formatting, syntax error, and version conflict. So, let’s get started!
Github account.Code editor — IDE, I prefer vscodeBasic Knowledge of YML syntax — quick review herePython 3 installed on your local machine — follow the steps here.
Github account.
Code editor — IDE, I prefer vscode
Basic Knowledge of YML syntax — quick review here
Python 3 installed on your local machine — follow the steps here.
Github actions are plugins that automate and manage the project workflow complete development life cycle. It is similar to Circleci, Travis, and Gitlab in functionality; however, it is free if the project repository is public.
Workflows for GitHub actions are a series of steps or directions written in the yml file that run every time you push to a specific branch on Github.
Setting up a workflow is a timesaver in the long run, where you can have peace of mind during pushing/merging code. The workflow could be customized to check against different tests stated as steps on the yml file. These checks could be using the correct version of the coding language, install dependence, or even check against code formatting and syntax error. This way, you could guarantee to be less anxious about merging code into the main branch — at least nothing would break!
You might have multiple workflows, and each one might have multiple jobs. The workflow is triggered every time, pushing to a specific branch.
In this guide, I will use the following:
pyenv-action was developed by Gabriel Falcão to pick the correct python version.Postgress docker image to configure Postgres as a database.Flak8 to check against syntax errorPylint to check against code formatting.
pyenv-action was developed by Gabriel Falcão to pick the correct python version.
Postgress docker image to configure Postgres as a database.
Flak8 to check against syntax error
Pylint to check against code formatting.
Github actions could be configured either on existing repos or creating one from scratch. For the sake of simplicity, I would start a new one from scratch; navigate to GitHub, and create a new repo and name it; I will name it github_actions . Then clone the repo into your local machine and create a GitHub workflow action file on .github/workflows/main.yml — this where the steps would be defined.
You could use the github workflows template by heading to the action tap and trigger the yml file.
You might include a requirements.txt file by running the following command in the terminal:
$ pip freeze > requirements.txt
Each workflow might have a bunch of jobs, and each job contains several steps to execute.
I am using the pyenv-action action developed by Gabrial. This action would do the following:
Installs pyenv 1.2.21.
Exports PYENV_ROOT environment variable.
Injects $PYENV_ROOT/bin in the PATH.
Injects pyenv shims in the PATH.
Pre-install specified python versions.
Set default python version (through pyenv local). — pyenv-action
Open the main.yml file and start configuring pyenv and pick the right python version. The following snippet is installing pyenv using the pyenv-action version 7, then upgrading the pip after picking version 3.8.6 and set it as the default. Following that, create a virtual environment with the default version and install project dependencies.
It has a successful build, and a green health check would appear associated with the commit id, as demonstrated above.
It is the same as the previous step; however, we will define the Postgres database connection in the services section using the Postgres docker image. Some health checks were configured to wait until Postgres started. Finally, port 5432 was mapped from the service container to the host.
The db_service service container has a successful build 😏.
Utilizing pylint would check every code snippet pushed to the master branch against errors and enforce a coding standard.
Pylint is a tool that checks for errors in Python code, tries to enforce a coding standard and looks for code smells. It can also look for certain type errors, it can recommend suggestions about how particular blocks can be refactored and can offer you details about the code’s complexity. — pylint 2.6.1-dev1
We could install pylint after installing the requirements and run pylint as a next step
- name: Install dependencies run: pip install -r requirements.txt --upgrade pip pip install pylint- name: Analysing the code with pylint run: | pylint `ls -R|grep .py$|xargs`
The final main.yml file might look like the following:
Now it is time to add some code and try to push it to the GitHub repository. I started by creating a demo file and developed a method for generating random sampling from an input array of distinct elements and size. All subsets should be equally likely.
The next step would be committing and pushing the Github repository changes using a pull request or direct push to master. Once the changes are made to the remote, different tests would be run against the changes before merging the changes into master.
As shown in the above image, there was an error generating because of inadequate formatting according to the pylint package; some of the errors were because I didn’t follow the snake_case naming conventions. As you can see, the pushed code had a rate of 4.29/10.
If you want to ignore the pylint checks for docstring, you could create a newfile named .pylint and add the following snippet into it to ignore docstring module.
[MASTER]disable= C0114, # missing-module-docstring
Now commit and push the Github repository changes after creating the pylint file, the build should be successful, and a healthy green check would appear near the repo 😎.
Github action is a powerful plugin that empowers the process of automating the machine learning development cycle. You could add more steps and jobs to the workflow, including deployment to different platforms, such as Iaas, Paas, Saas, and onsite premises. Also, it allows you to use docker containers as well as Kubernetes. There are plenty of GitHub-actions built by the community’s marketplace; you can even create your customized action if you have a programming background or follow the documentation.
Some of the references that helped me to configure this workflow are:
Workflow syntax for Github actionsPostgresql Github action by HarmonGithub actions documentations — environment variablesLearn Github actionsPyenv-action by Gabriel FalcãoPylint documentation
Workflow syntax for Github actions
Postgresql Github action by Harmon
Github actions documentations — environment variables
Learn Github actions
Pyenv-action by Gabriel Falcão
Pylint documentation
Finally, I hope this provided a comprehensive guide to utilizing the GitHub actions to automate machine learning projects. If you followed along and have a question or suggestion, please post them in the comment section below; I would be more than happy to help. Thanks for reading and happy learning👍 | [
{
"code": null,
"e": 487,
"s": 171,
"text": "In my previous article, I walked you through a step by step tutorial to correctly setting up the python3 environment using pyenv on your local machine. However, some issues may arise in some circumstances due to some conflicts resulting from pull requests that use different python versions or even missing modules."
},
{
"code": null,
"e": 821,
"s": 487,
"text": "This tutorial will demonstrate the steps to build a standard workflow for any project utilizing Github actions plugins. Configuring Github actions in the project CI folder would protect the codebase pull requests that don’t meet the code standards regarding code formatting, syntax error, and version conflict. So, let’s get started!"
},
{
"code": null,
"e": 985,
"s": 821,
"text": "Github account.Code editor — IDE, I prefer vscodeBasic Knowledge of YML syntax — quick review herePython 3 installed on your local machine — follow the steps here."
},
{
"code": null,
"e": 1001,
"s": 985,
"text": "Github account."
},
{
"code": null,
"e": 1036,
"s": 1001,
"text": "Code editor — IDE, I prefer vscode"
},
{
"code": null,
"e": 1086,
"s": 1036,
"text": "Basic Knowledge of YML syntax — quick review here"
},
{
"code": null,
"e": 1152,
"s": 1086,
"text": "Python 3 installed on your local machine — follow the steps here."
},
{
"code": null,
"e": 1379,
"s": 1152,
"text": "Github actions are plugins that automate and manage the project workflow complete development life cycle. It is similar to Circleci, Travis, and Gitlab in functionality; however, it is free if the project repository is public."
},
{
"code": null,
"e": 1529,
"s": 1379,
"text": "Workflows for GitHub actions are a series of steps or directions written in the yml file that run every time you push to a specific branch on Github."
},
{
"code": null,
"e": 2013,
"s": 1529,
"text": "Setting up a workflow is a timesaver in the long run, where you can have peace of mind during pushing/merging code. The workflow could be customized to check against different tests stated as steps on the yml file. These checks could be using the correct version of the coding language, install dependence, or even check against code formatting and syntax error. This way, you could guarantee to be less anxious about merging code into the main branch — at least nothing would break!"
},
{
"code": null,
"e": 2155,
"s": 2013,
"text": "You might have multiple workflows, and each one might have multiple jobs. The workflow is triggered every time, pushing to a specific branch."
},
{
"code": null,
"e": 2196,
"s": 2155,
"text": "In this guide, I will use the following:"
},
{
"code": null,
"e": 2412,
"s": 2196,
"text": "pyenv-action was developed by Gabriel Falcão to pick the correct python version.Postgress docker image to configure Postgres as a database.Flak8 to check against syntax errorPylint to check against code formatting."
},
{
"code": null,
"e": 2494,
"s": 2412,
"text": "pyenv-action was developed by Gabriel Falcão to pick the correct python version."
},
{
"code": null,
"e": 2554,
"s": 2494,
"text": "Postgress docker image to configure Postgres as a database."
},
{
"code": null,
"e": 2590,
"s": 2554,
"text": "Flak8 to check against syntax error"
},
{
"code": null,
"e": 2631,
"s": 2590,
"text": "Pylint to check against code formatting."
},
{
"code": null,
"e": 3030,
"s": 2631,
"text": "Github actions could be configured either on existing repos or creating one from scratch. For the sake of simplicity, I would start a new one from scratch; navigate to GitHub, and create a new repo and name it; I will name it github_actions . Then clone the repo into your local machine and create a GitHub workflow action file on .github/workflows/main.yml — this where the steps would be defined."
},
{
"code": null,
"e": 3129,
"s": 3030,
"text": "You could use the github workflows template by heading to the action tap and trigger the yml file."
},
{
"code": null,
"e": 3221,
"s": 3129,
"text": "You might include a requirements.txt file by running the following command in the terminal:"
},
{
"code": null,
"e": 3253,
"s": 3221,
"text": "$ pip freeze > requirements.txt"
},
{
"code": null,
"e": 3343,
"s": 3253,
"text": "Each workflow might have a bunch of jobs, and each job contains several steps to execute."
},
{
"code": null,
"e": 3436,
"s": 3343,
"text": "I am using the pyenv-action action developed by Gabrial. This action would do the following:"
},
{
"code": null,
"e": 3459,
"s": 3436,
"text": "Installs pyenv 1.2.21."
},
{
"code": null,
"e": 3500,
"s": 3459,
"text": "Exports PYENV_ROOT environment variable."
},
{
"code": null,
"e": 3537,
"s": 3500,
"text": "Injects $PYENV_ROOT/bin in the PATH."
},
{
"code": null,
"e": 3570,
"s": 3537,
"text": "Injects pyenv shims in the PATH."
},
{
"code": null,
"e": 3609,
"s": 3570,
"text": "Pre-install specified python versions."
},
{
"code": null,
"e": 3674,
"s": 3609,
"text": "Set default python version (through pyenv local). — pyenv-action"
},
{
"code": null,
"e": 4018,
"s": 3674,
"text": "Open the main.yml file and start configuring pyenv and pick the right python version. The following snippet is installing pyenv using the pyenv-action version 7, then upgrading the pip after picking version 3.8.6 and set it as the default. Following that, create a virtual environment with the default version and install project dependencies."
},
{
"code": null,
"e": 4137,
"s": 4018,
"text": "It has a successful build, and a green health check would appear associated with the commit id, as demonstrated above."
},
{
"code": null,
"e": 4425,
"s": 4137,
"text": "It is the same as the previous step; however, we will define the Postgres database connection in the services section using the Postgres docker image. Some health checks were configured to wait until Postgres started. Finally, port 5432 was mapped from the service container to the host."
},
{
"code": null,
"e": 4484,
"s": 4425,
"text": "The db_service service container has a successful build 😏."
},
{
"code": null,
"e": 4606,
"s": 4484,
"text": "Utilizing pylint would check every code snippet pushed to the master branch against errors and enforce a coding standard."
},
{
"code": null,
"e": 4916,
"s": 4606,
"text": "Pylint is a tool that checks for errors in Python code, tries to enforce a coding standard and looks for code smells. It can also look for certain type errors, it can recommend suggestions about how particular blocks can be refactored and can offer you details about the code’s complexity. — pylint 2.6.1-dev1"
},
{
"code": null,
"e": 5004,
"s": 4916,
"text": "We could install pylint after installing the requirements and run pylint as a next step"
},
{
"code": null,
"e": 5190,
"s": 5004,
"text": "- name: Install dependencies run: pip install -r requirements.txt --upgrade pip pip install pylint- name: Analysing the code with pylint run: | pylint `ls -R|grep .py$|xargs`"
},
{
"code": null,
"e": 5245,
"s": 5190,
"text": "The final main.yml file might look like the following:"
},
{
"code": null,
"e": 5499,
"s": 5245,
"text": "Now it is time to add some code and try to push it to the GitHub repository. I started by creating a demo file and developed a method for generating random sampling from an input array of distinct elements and size. All subsets should be equally likely."
},
{
"code": null,
"e": 5752,
"s": 5499,
"text": "The next step would be committing and pushing the Github repository changes using a pull request or direct push to master. Once the changes are made to the remote, different tests would be run against the changes before merging the changes into master."
},
{
"code": null,
"e": 6015,
"s": 5752,
"text": "As shown in the above image, there was an error generating because of inadequate formatting according to the pylint package; some of the errors were because I didn’t follow the snake_case naming conventions. As you can see, the pushed code had a rate of 4.29/10."
},
{
"code": null,
"e": 6177,
"s": 6015,
"text": "If you want to ignore the pylint checks for docstring, you could create a newfile named .pylint and add the following snippet into it to ignore docstring module."
},
{
"code": null,
"e": 6228,
"s": 6177,
"text": "[MASTER]disable= C0114, # missing-module-docstring"
},
{
"code": null,
"e": 6398,
"s": 6228,
"text": "Now commit and push the Github repository changes after creating the pylint file, the build should be successful, and a healthy green check would appear near the repo 😎."
},
{
"code": null,
"e": 6906,
"s": 6398,
"text": "Github action is a powerful plugin that empowers the process of automating the machine learning development cycle. You could add more steps and jobs to the workflow, including deployment to different platforms, such as Iaas, Paas, Saas, and onsite premises. Also, it allows you to use docker containers as well as Kubernetes. There are plenty of GitHub-actions built by the community’s marketplace; you can even create your customized action if you have a programming background or follow the documentation."
},
{
"code": null,
"e": 6976,
"s": 6906,
"text": "Some of the references that helped me to configure this workflow are:"
},
{
"code": null,
"e": 7169,
"s": 6976,
"text": "Workflow syntax for Github actionsPostgresql Github action by HarmonGithub actions documentations — environment variablesLearn Github actionsPyenv-action by Gabriel FalcãoPylint documentation"
},
{
"code": null,
"e": 7204,
"s": 7169,
"text": "Workflow syntax for Github actions"
},
{
"code": null,
"e": 7239,
"s": 7204,
"text": "Postgresql Github action by Harmon"
},
{
"code": null,
"e": 7293,
"s": 7239,
"text": "Github actions documentations — environment variables"
},
{
"code": null,
"e": 7314,
"s": 7293,
"text": "Learn Github actions"
},
{
"code": null,
"e": 7346,
"s": 7314,
"text": "Pyenv-action by Gabriel Falcão"
},
{
"code": null,
"e": 7367,
"s": 7346,
"text": "Pylint documentation"
}
]
|
Lambda Functions with Practical Examples in Python | by Susan Maina | Towards Data Science | When I first came across lambda functions in python, I was very much intimidated and thought they were for advanced Pythonistas. Beginner python tutorials applaud the language for its readable syntax, but lambdas sure didn’t seem user-friendly.
However, once I understood the general syntax and examined some simple use cases, using them was less scary.
Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code.
lambda argument(s): expression
A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression). The keyword lambda must come first. A full colon (:) separates the argument and the expression.
In the example code below, x is the argument and x+x is the expression.
#Normal python functiondef a_name(x): return x+x#Lambda functionlambda x: x+x
Before we get into practical applications, let’s mention some technicalities on what the python community thinks is good and bad with lambda functions.
Pros
Good for simple logical operations that are easy to understand. This makes the code more readable too.
Good when you want a function that you will use just one time.
Cons
They can only perform one expression. It’s not possible to have multiple independent operations in one lambda function.
Bad for operations that would span more than one line in a normal def function (For example nested conditional operations). If you need a minute or two to understand the code, use a named function instead.
Bad because you can’t write a doc-string to explain all the inputs, operations, and outputs as you would in a normal def function.
At the end of this article, we’ll look at commonly used code examples where Lambda functions are discouraged even though they seem legitimate.
But first, let’s look at situations when to use lambda functions. Note that we use lambda functions a lot with python classes that take in a function as an argument, for example, map() and filter(). These are also called Higher-order functions.
This is when you execute a lambda function on a single value.
(lambda x: x*2)(12)###Results24
In the code above, the function was created and then immediately executed. This is an example of an immediately invoked function expression or IIFE.
Filter(). This is a Python inbuilt library that returns only those values that fit certain criteria. The syntax is filter(function, iterable). The iterable can be any sequence such as a list, set, or series object (more below).
The example below filters a list for even numbers. Note that the filter function returns a ‘Filter object’ and you need to encapsulate it with a list to return the values.
list_1 = [1,2,3,4,5,6,7,8,9]filter(lambda x: x%2==0, list_1)### Results<filter at 0xf378982348>list(filter(lambda x: x%2==0, list_1))###Results[2, 4, 6, 8]
Map(). This is another inbuilt python library with the syntax map(function, iterable).
This returns a modified list where every value in the original list has been changed based on a function. The example below cubes every number in the list.
list_1 = [1,2,3,4,5,6,7,8,9]cubed = map(lambda x: pow(x,3), list_1)list(cubed)###Results[1, 8, 27, 64, 125, 216, 343, 512, 729]
A Series object is a column in a data frame, or put another way, a sequence of values with corresponding indices. Lambda functions can be used to manipulate values inside a Pandas dataframe.
Let’s create a dummy dataframe about members of a family.
import pandas as pddf = pd.DataFrame({ 'Name': ['Luke','Gina','Sam','Emma'], 'Status': ['Father', 'Mother', 'Son', 'Daughter'], 'Birthyear': [1976, 1984, 2013, 2016],})
Lambda with Apply() function by Pandas. This function applies an operation to every element of the column.
To get the current age of each member, we subtract their birth year from the current year. In the lambda function below, x refers to a value in the birthyear column, and the expression is 2021(current year) minus the value.
df['age'] = df['Birthyear'].apply(lambda x: 2021-x)
Lambda with Python’s Filter() function. This takes 2 arguments; one is a lambda function with a condition expression, two an iterable which for us is a series object. It returns a list of values that satisfy the condition.
list(filter(lambda x: x>18, df['age']))###Results[45, 37]
Lambda with Map() function by Pandas. Map works very much like apply() in that it modifies values of a column based on the expression.
#Double the age of everyonedf['double_age'] = df['age'].map(lambda x: x*2)
We can also perform conditional operations that return different values based on certain criteria.
The code below returns ‘Male’ if the Status value is father or son, and returns ‘Female’ otherwise. Note that apply and map are interchangeable in this context.
#Conditional Lambda statementdf['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')
I mostly use Lambda functions on specific columns (series object) rather than the entire data frame, unless I want to modify the entire data frame with one expression.
For example rounding all values to 1 decimal place, in which case all the columns have to be float or int datatypes because round() can’t work on strings.
df2.apply(lambda x:round(x,1))##Returns an error if some ##columns are not numeric
In the example below, we use apply on a dataframe and select the columns to modify in the Lambda function. Note that we must use axis=1 here so that the expression is applied column-wise.
#convert to lower-casedf[['Name','Status']] = df.apply(lambda x: x[['Name','Status']].str.lower(), axis=1)
Assigning a name to a Lambda function. This is discouraged in the PEP8 python style guide because Lambda creates an anonymous function that’s not meant to be stored. Instead, use a normal def function if you want to store the function for reuse.
Assigning a name to a Lambda function. This is discouraged in the PEP8 python style guide because Lambda creates an anonymous function that’s not meant to be stored. Instead, use a normal def function if you want to store the function for reuse.
#Badtriple = lambda x: x*3#Gooddef triple(x): return x*3
2. Passing functions inside Lambda functions. Using functions like abs which only take one number- argument is unnecessary with Lambda because you can directly pass the function into map() or apply().
#Badmap(lambda x:abs(x), list_3)#Goodmap(abs, list_3)#Goodmap(lambda x: pow(x, 2), float_nums)
Ideally, functions inside lambda functions should take two or more arguments. Examples are pow(number,power) and round(number,ndigit). You can experiment with various in-built python functions to see which ones need Lambda functions in this context. I’ve done so in this notebook.
3. Using Lambda functions when multiple lines of code are more readable. An example is when you are using if-else statements inside the lambda function. I used the example below earlier in this article.
#Conditional Lambda statementdf['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')
The same results can be achieved with the code below. I prefer this way because you can have endless conditions and the code is simple enough to follow. More on vectorized conditions here.
Many programmers who don’t like Lambdas usually argue that you can replace them with the more understandable list comprehensions, built-in functions, and standard libraries. Generator expressions (similar to list comprehensions) are also handy alternatives to the map() and filter() functions.
Whether or not you decide to embrace Lambda functions in your code, you need to understand what they are and how they are used because you will inevitably come across them in other peoples’ code.
Check out the code used here in my GitHub. Thank you for reading!
References:
https://www.analyticsvidhya.com/blog/2020/03/what-are-lambda-functions-in-python/
Overusing lambda expressions in Python | [
{
"code": null,
"e": 292,
"s": 47,
"text": "When I first came across lambda functions in python, I was very much intimidated and thought they were for advanced Pythonistas. Beginner python tutorials applaud the language for its readable syntax, but lambdas sure didn’t seem user-friendly."
},
{
"code": null,
"e": 401,
"s": 292,
"text": "However, once I understood the general syntax and examined some simple use cases, using them was less scary."
},
{
"code": null,
"e": 558,
"s": 401,
"text": "Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code."
},
{
"code": null,
"e": 589,
"s": 558,
"text": "lambda argument(s): expression"
},
{
"code": null,
"e": 835,
"s": 589,
"text": "A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression). The keyword lambda must come first. A full colon (:) separates the argument and the expression."
},
{
"code": null,
"e": 907,
"s": 835,
"text": "In the example code below, x is the argument and x+x is the expression."
},
{
"code": null,
"e": 988,
"s": 907,
"text": "#Normal python functiondef a_name(x): return x+x#Lambda functionlambda x: x+x"
},
{
"code": null,
"e": 1140,
"s": 988,
"text": "Before we get into practical applications, let’s mention some technicalities on what the python community thinks is good and bad with lambda functions."
},
{
"code": null,
"e": 1145,
"s": 1140,
"text": "Pros"
},
{
"code": null,
"e": 1248,
"s": 1145,
"text": "Good for simple logical operations that are easy to understand. This makes the code more readable too."
},
{
"code": null,
"e": 1311,
"s": 1248,
"text": "Good when you want a function that you will use just one time."
},
{
"code": null,
"e": 1316,
"s": 1311,
"text": "Cons"
},
{
"code": null,
"e": 1436,
"s": 1316,
"text": "They can only perform one expression. It’s not possible to have multiple independent operations in one lambda function."
},
{
"code": null,
"e": 1642,
"s": 1436,
"text": "Bad for operations that would span more than one line in a normal def function (For example nested conditional operations). If you need a minute or two to understand the code, use a named function instead."
},
{
"code": null,
"e": 1773,
"s": 1642,
"text": "Bad because you can’t write a doc-string to explain all the inputs, operations, and outputs as you would in a normal def function."
},
{
"code": null,
"e": 1916,
"s": 1773,
"text": "At the end of this article, we’ll look at commonly used code examples where Lambda functions are discouraged even though they seem legitimate."
},
{
"code": null,
"e": 2161,
"s": 1916,
"text": "But first, let’s look at situations when to use lambda functions. Note that we use lambda functions a lot with python classes that take in a function as an argument, for example, map() and filter(). These are also called Higher-order functions."
},
{
"code": null,
"e": 2223,
"s": 2161,
"text": "This is when you execute a lambda function on a single value."
},
{
"code": null,
"e": 2255,
"s": 2223,
"text": "(lambda x: x*2)(12)###Results24"
},
{
"code": null,
"e": 2404,
"s": 2255,
"text": "In the code above, the function was created and then immediately executed. This is an example of an immediately invoked function expression or IIFE."
},
{
"code": null,
"e": 2632,
"s": 2404,
"text": "Filter(). This is a Python inbuilt library that returns only those values that fit certain criteria. The syntax is filter(function, iterable). The iterable can be any sequence such as a list, set, or series object (more below)."
},
{
"code": null,
"e": 2804,
"s": 2632,
"text": "The example below filters a list for even numbers. Note that the filter function returns a ‘Filter object’ and you need to encapsulate it with a list to return the values."
},
{
"code": null,
"e": 2960,
"s": 2804,
"text": "list_1 = [1,2,3,4,5,6,7,8,9]filter(lambda x: x%2==0, list_1)### Results<filter at 0xf378982348>list(filter(lambda x: x%2==0, list_1))###Results[2, 4, 6, 8]"
},
{
"code": null,
"e": 3047,
"s": 2960,
"text": "Map(). This is another inbuilt python library with the syntax map(function, iterable)."
},
{
"code": null,
"e": 3203,
"s": 3047,
"text": "This returns a modified list where every value in the original list has been changed based on a function. The example below cubes every number in the list."
},
{
"code": null,
"e": 3331,
"s": 3203,
"text": "list_1 = [1,2,3,4,5,6,7,8,9]cubed = map(lambda x: pow(x,3), list_1)list(cubed)###Results[1, 8, 27, 64, 125, 216, 343, 512, 729]"
},
{
"code": null,
"e": 3522,
"s": 3331,
"text": "A Series object is a column in a data frame, or put another way, a sequence of values with corresponding indices. Lambda functions can be used to manipulate values inside a Pandas dataframe."
},
{
"code": null,
"e": 3580,
"s": 3522,
"text": "Let’s create a dummy dataframe about members of a family."
},
{
"code": null,
"e": 3758,
"s": 3580,
"text": "import pandas as pddf = pd.DataFrame({ 'Name': ['Luke','Gina','Sam','Emma'], 'Status': ['Father', 'Mother', 'Son', 'Daughter'], 'Birthyear': [1976, 1984, 2013, 2016],})"
},
{
"code": null,
"e": 3865,
"s": 3758,
"text": "Lambda with Apply() function by Pandas. This function applies an operation to every element of the column."
},
{
"code": null,
"e": 4089,
"s": 3865,
"text": "To get the current age of each member, we subtract their birth year from the current year. In the lambda function below, x refers to a value in the birthyear column, and the expression is 2021(current year) minus the value."
},
{
"code": null,
"e": 4141,
"s": 4089,
"text": "df['age'] = df['Birthyear'].apply(lambda x: 2021-x)"
},
{
"code": null,
"e": 4364,
"s": 4141,
"text": "Lambda with Python’s Filter() function. This takes 2 arguments; one is a lambda function with a condition expression, two an iterable which for us is a series object. It returns a list of values that satisfy the condition."
},
{
"code": null,
"e": 4422,
"s": 4364,
"text": "list(filter(lambda x: x>18, df['age']))###Results[45, 37]"
},
{
"code": null,
"e": 4557,
"s": 4422,
"text": "Lambda with Map() function by Pandas. Map works very much like apply() in that it modifies values of a column based on the expression."
},
{
"code": null,
"e": 4632,
"s": 4557,
"text": "#Double the age of everyonedf['double_age'] = df['age'].map(lambda x: x*2)"
},
{
"code": null,
"e": 4731,
"s": 4632,
"text": "We can also perform conditional operations that return different values based on certain criteria."
},
{
"code": null,
"e": 4892,
"s": 4731,
"text": "The code below returns ‘Male’ if the Status value is father or son, and returns ‘Female’ otherwise. Note that apply and map are interchangeable in this context."
},
{
"code": null,
"e": 5012,
"s": 4892,
"text": "#Conditional Lambda statementdf['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')"
},
{
"code": null,
"e": 5180,
"s": 5012,
"text": "I mostly use Lambda functions on specific columns (series object) rather than the entire data frame, unless I want to modify the entire data frame with one expression."
},
{
"code": null,
"e": 5335,
"s": 5180,
"text": "For example rounding all values to 1 decimal place, in which case all the columns have to be float or int datatypes because round() can’t work on strings."
},
{
"code": null,
"e": 5418,
"s": 5335,
"text": "df2.apply(lambda x:round(x,1))##Returns an error if some ##columns are not numeric"
},
{
"code": null,
"e": 5606,
"s": 5418,
"text": "In the example below, we use apply on a dataframe and select the columns to modify in the Lambda function. Note that we must use axis=1 here so that the expression is applied column-wise."
},
{
"code": null,
"e": 5713,
"s": 5606,
"text": "#convert to lower-casedf[['Name','Status']] = df.apply(lambda x: x[['Name','Status']].str.lower(), axis=1)"
},
{
"code": null,
"e": 5959,
"s": 5713,
"text": "Assigning a name to a Lambda function. This is discouraged in the PEP8 python style guide because Lambda creates an anonymous function that’s not meant to be stored. Instead, use a normal def function if you want to store the function for reuse."
},
{
"code": null,
"e": 6205,
"s": 5959,
"text": "Assigning a name to a Lambda function. This is discouraged in the PEP8 python style guide because Lambda creates an anonymous function that’s not meant to be stored. Instead, use a normal def function if you want to store the function for reuse."
},
{
"code": null,
"e": 6266,
"s": 6205,
"text": "#Badtriple = lambda x: x*3#Gooddef triple(x): return x*3"
},
{
"code": null,
"e": 6467,
"s": 6266,
"text": "2. Passing functions inside Lambda functions. Using functions like abs which only take one number- argument is unnecessary with Lambda because you can directly pass the function into map() or apply()."
},
{
"code": null,
"e": 6562,
"s": 6467,
"text": "#Badmap(lambda x:abs(x), list_3)#Goodmap(abs, list_3)#Goodmap(lambda x: pow(x, 2), float_nums)"
},
{
"code": null,
"e": 6843,
"s": 6562,
"text": "Ideally, functions inside lambda functions should take two or more arguments. Examples are pow(number,power) and round(number,ndigit). You can experiment with various in-built python functions to see which ones need Lambda functions in this context. I’ve done so in this notebook."
},
{
"code": null,
"e": 7046,
"s": 6843,
"text": "3. Using Lambda functions when multiple lines of code are more readable. An example is when you are using if-else statements inside the lambda function. I used the example below earlier in this article."
},
{
"code": null,
"e": 7166,
"s": 7046,
"text": "#Conditional Lambda statementdf['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')"
},
{
"code": null,
"e": 7355,
"s": 7166,
"text": "The same results can be achieved with the code below. I prefer this way because you can have endless conditions and the code is simple enough to follow. More on vectorized conditions here."
},
{
"code": null,
"e": 7649,
"s": 7355,
"text": "Many programmers who don’t like Lambdas usually argue that you can replace them with the more understandable list comprehensions, built-in functions, and standard libraries. Generator expressions (similar to list comprehensions) are also handy alternatives to the map() and filter() functions."
},
{
"code": null,
"e": 7845,
"s": 7649,
"text": "Whether or not you decide to embrace Lambda functions in your code, you need to understand what they are and how they are used because you will inevitably come across them in other peoples’ code."
},
{
"code": null,
"e": 7911,
"s": 7845,
"text": "Check out the code used here in my GitHub. Thank you for reading!"
},
{
"code": null,
"e": 7923,
"s": 7911,
"text": "References:"
},
{
"code": null,
"e": 8005,
"s": 7923,
"text": "https://www.analyticsvidhya.com/blog/2020/03/what-are-lambda-functions-in-python/"
}
]
|
Select all columns, except one given column in a Pandas DataFrame | 20 Aug, 2020
DataFrame Data structure are the heart of Pandas library. Dataframes are basically two dimension Series object. They have rows and columns with rows representing the index and columns representing the content. Now, let’s see how to Select all columns, except one given column in Pandas Dataframe.
First, Let’s create a Dataframe:
Python3
# import pandas libraryimport pandas as pd # create a Dataframedata = pd.DataFrame({ 'course_name': ['Data Structures', 'Python', 'Machine Learning'], 'student_name': ['A', 'B', 'C'], 'student_city': ['Chennai', 'Pune', 'Delhi'], 'student_gender': ['M', 'F', 'M'] })# show the Dataframedata
Output:
DataFrame
Method 1: Using Dataframe.loc[ ].
This GeeksForGeeks Dataframe is just a two dimension array with numerical index. Therefore, to except only one column we could use the columns methods to get all columns and use a not operator to exclude the columns which are not needed. This method works only when the Dataframe is not multi indexed (did not have more than one index).
Example: Select all columns, except one ‘student_gender’ column in Pandas Dataframe.
Python3
# import pandas libraryimport pandas as pd # create a Dataframedata = pd.DataFrame({ 'course_name': ['Data Structures', 'Python', 'Machine Learning'], 'student_name': ['A', 'B', 'C'], 'student_city': ['Chennai', 'Pune', 'Delhi'], 'student_gender': ['M', 'F', 'M'] }) df = data.loc[ : , data.columns != 'student_gender'] # show the dataframedf
Output:
filtered student_gender column
Method 2: Using drop() method.
Dataframe supports drop() method to drop a particular column. It accepts two arguments, column/row name and axis
Example: Select all columns, except one ‘student_city’ column in Pandas Dataframe.
Python3
# import pandas library import pandas as pd # create a Dataframedata = pd.DataFrame({ 'course_name': ['Data Structures', 'Python', 'Machine Learning'], 'student_name': ['A', 'B', 'C'], 'student_city': ['Chennai', 'Pune', 'Delhi'], 'student_gender': ['M', 'F', 'M'] }) # drop methoddf = data.drop('student_city', axis = 1) # show the dataframedf
Output:
student_city column removed
Method 3: Using Series.difference() method and [ ] operator together.
Series.difference() Method returns a new Index with elements from the index that are not in other.
Example: Select all columns, except one ‘student_name’ column in Pandas Dataframe.
Python3
# import pandas libraryimport pandas as pd # create a Dataframedata = pd.DataFrame({ 'course_name': ['Data Structures', 'Python', 'Machine Learning'], 'student_name': ['A', 'B', 'C'], 'student_city': ['Chennai', 'Pune', 'Delhi'], 'student_gender': ['M', 'F', 'M'] }) df = data[data.columns.difference(['student_name'])] # show the dataframedf
Output:
filtered student_name column
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 325,
"s": 28,
"text": "DataFrame Data structure are the heart of Pandas library. Dataframes are basically two dimension Series object. They have rows and columns with rows representing the index and columns representing the content. Now, let’s see how to Select all columns, except one given column in Pandas Dataframe."
},
{
"code": null,
"e": 358,
"s": 325,
"text": "First, Let’s create a Dataframe:"
},
{
"code": null,
"e": 366,
"s": 358,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # create a Dataframedata = pd.DataFrame({ 'course_name': ['Data Structures', 'Python', 'Machine Learning'], 'student_name': ['A', 'B', 'C'], 'student_city': ['Chennai', 'Pune', 'Delhi'], 'student_gender': ['M', 'F', 'M'] })# show the Dataframedata",
"e": 753,
"s": 366,
"text": null
},
{
"code": null,
"e": 761,
"s": 753,
"text": "Output:"
},
{
"code": null,
"e": 771,
"s": 761,
"text": "DataFrame"
},
{
"code": null,
"e": 805,
"s": 771,
"text": "Method 1: Using Dataframe.loc[ ]."
},
{
"code": null,
"e": 1143,
"s": 805,
"text": "This GeeksForGeeks Dataframe is just a two dimension array with numerical index. Therefore, to except only one column we could use the columns methods to get all columns and use a not operator to exclude the columns which are not needed. This method works only when the Dataframe is not multi indexed (did not have more than one index). "
},
{
"code": null,
"e": 1228,
"s": 1143,
"text": "Example: Select all columns, except one ‘student_gender’ column in Pandas Dataframe."
},
{
"code": null,
"e": 1236,
"s": 1228,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # create a Dataframedata = pd.DataFrame({ 'course_name': ['Data Structures', 'Python', 'Machine Learning'], 'student_name': ['A', 'B', 'C'], 'student_city': ['Chennai', 'Pune', 'Delhi'], 'student_gender': ['M', 'F', 'M'] }) df = data.loc[ : , data.columns != 'student_gender'] # show the dataframedf",
"e": 1700,
"s": 1236,
"text": null
},
{
"code": null,
"e": 1708,
"s": 1700,
"text": "Output:"
},
{
"code": null,
"e": 1739,
"s": 1708,
"text": "filtered student_gender column"
},
{
"code": null,
"e": 1770,
"s": 1739,
"text": "Method 2: Using drop() method."
},
{
"code": null,
"e": 1883,
"s": 1770,
"text": "Dataframe supports drop() method to drop a particular column. It accepts two arguments, column/row name and axis"
},
{
"code": null,
"e": 1967,
"s": 1883,
"text": "Example: Select all columns, except one ‘student_city’ column in Pandas Dataframe."
},
{
"code": null,
"e": 1975,
"s": 1967,
"text": "Python3"
},
{
"code": "# import pandas library import pandas as pd # create a Dataframedata = pd.DataFrame({ 'course_name': ['Data Structures', 'Python', 'Machine Learning'], 'student_name': ['A', 'B', 'C'], 'student_city': ['Chennai', 'Pune', 'Delhi'], 'student_gender': ['M', 'F', 'M'] }) # drop methoddf = data.drop('student_city', axis = 1) # show the dataframedf",
"e": 2430,
"s": 1975,
"text": null
},
{
"code": null,
"e": 2438,
"s": 2430,
"text": "Output:"
},
{
"code": null,
"e": 2466,
"s": 2438,
"text": "student_city column removed"
},
{
"code": null,
"e": 2536,
"s": 2466,
"text": "Method 3: Using Series.difference() method and [ ] operator together."
},
{
"code": null,
"e": 2635,
"s": 2536,
"text": "Series.difference() Method returns a new Index with elements from the index that are not in other."
},
{
"code": null,
"e": 2718,
"s": 2635,
"text": "Example: Select all columns, except one ‘student_name’ column in Pandas Dataframe."
},
{
"code": null,
"e": 2726,
"s": 2718,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # create a Dataframedata = pd.DataFrame({ 'course_name': ['Data Structures', 'Python', 'Machine Learning'], 'student_name': ['A', 'B', 'C'], 'student_city': ['Chennai', 'Pune', 'Delhi'], 'student_gender': ['M', 'F', 'M'] }) df = data[data.columns.difference(['student_name'])] # show the dataframedf",
"e": 3190,
"s": 2726,
"text": null
},
{
"code": null,
"e": 3198,
"s": 3190,
"text": "Output:"
},
{
"code": null,
"e": 3227,
"s": 3198,
"text": "filtered student_name column"
},
{
"code": null,
"e": 3251,
"s": 3227,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3274,
"s": 3251,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 3288,
"s": 3274,
"text": "Python-pandas"
},
{
"code": null,
"e": 3295,
"s": 3288,
"text": "Python"
}
]
|
Python | Program to implement simple FLAMES game | 11 Jun, 2021
Python is a multipurpose language and one can do literally anything with it. Python can also be used for game development. Let’s create a simple FLAMES game without using any external game libraries like PyGame.FLAMES is a popular game named after the acronym: Friends, Lovers, Affectionate, Marriage, Enemies, Sibling. This game does not accurately predict whether or not an individual is right for you, but it can be fun to play this with your friends.
There are two steps in this game:
Take the two names.
Remove the common characters with their respective common occurrences.
Get the count of the characters that are left .
Take FLAMES letters as [“F”, “L”, “A”, “M”, “E”, “S”]
Start removing letter using the count we got.
The letter which last the process is the result.
Example :
Input : player1 name : AJAY
player 2 name : PRIYA
Output : Relationship status : Friends
Explanation: In above given two names A and Y are common letters which are occurring one time(common count) in both names so we are removing these letters from both names. Now count the total letters that are left here it is 5. Now start removing letters one by one from FLAMES using the count we got and the letter which lasts the process is the result.
Counting is done in anti-clockwise circular fashion.
FLAMES counting is start from F, E is at 5th count so we remove E and start counting again but a this time start from S. FLAMS M is at 5th count so we remove M and counting start from S. FLAS S is at 5th count so we remove S and counting start from F. FLA L is at 5th count so we remove L and counting start from A. FA A is at 5th count so we remove A. now we have only one letter is remaining so this is the final answer. F So, the relationship is F i.e. Friends .
Approach: Take two names as input then remove the common characters with their respective common occurrences. For removing purpose we create user-defined remove_match_char function with two arguments as list1 and list2 which stores list of characters of two players name respectively and return list of concatenated list(list1 + “*” flagst2) and flag value which we store in ret_list variable.After removing all the common characters, count the total no. of remaining characters then create a result list with FLAMES acronym i.e [“Friends”, “Love”, “Affection”, “Marriage”, “Enemy”, “Siblings”]. Now start removing word one by one until list not contains only one word, using the total count which we got. the word which remains in the last, is the result.
Below is the implementation :
Python3
# function for removing common characters# with their respective occurrencesdef remove_match_char(list1, list2): for i in range(len(list1)) : for j in range(len(list2)) : # if common character is found # then remove that character # and return list of concatenated # list with True Flag if list1[i] == list2[j] : c = list1[i] # remove character from the list list1.remove(c) list2.remove(c) # concatenation of two list elements with * # * is act as border mark here list3 = list1 + ["*"] + list2 # return the concatenated list with True flag return [list3, True] # no common characters is found # return the concatenated list with False flag list3 = list1 + ["*"] + list2 return [list3, False] # Driver codeif __name__ == "__main__" : # take first name p1 = input("Player 1 name : ") # converted all letters into lower case p1 = p1.lower() # replace any space with empty string p1.replace(" ", "") # make a list of letters or characters p1_list = list(p1) # take 2nd name p2 = input("Player 2 name : ") p2 = p2.lower() p2.replace(" ", "") p2_list = list(p2) # taking a flag as True initially proceed = True # keep calling remove_match_char function # until common characters is found or # keep looping until proceed flag is True while proceed : # function calling and store return value ret_list = remove_match_char(p1_list, p2_list) # take out concatenated list from return list con_list = ret_list[0] # take out flag value from return list proceed = ret_list[1] # find the index of "*" / border mark star_index = con_list.index("*") # list slicing perform # all characters before * store in p1_list p1_list = con_list[ : star_index] # all characters after * store in p2_list p2_list = con_list[star_index + 1 : ] # count total remaining characters count = len(p1_list) + len(p2_list) # list of FLAMES acronym result = ["Friends", "Love", "Affection", "Marriage", "Enemy", "Siblings"] # keep looping until only one item # is not remaining in the result list while len(result) > 1 : # store that index value from # where we have to perform slicing. split_index = (count % len(result) - 1) # this steps is done for performing # anticlock-wise circular fashion counting. if split_index >= 0 : # list slicing right = result[split_index + 1 : ] left = result[ : split_index] # list concatenation result = right + left else : result = result[ : len(result) - 1] # print final result print("Relationship status :", result[0])
Output:
Player 1 name : ANKIT
Player 2 name : DEEPIKA
Relationship status : Marriage
nidhi_biet
Akanksha_Rai
surinderdawra388
surindertarika1234
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 509,
"s": 54,
"text": "Python is a multipurpose language and one can do literally anything with it. Python can also be used for game development. Let’s create a simple FLAMES game without using any external game libraries like PyGame.FLAMES is a popular game named after the acronym: Friends, Lovers, Affectionate, Marriage, Enemies, Sibling. This game does not accurately predict whether or not an individual is right for you, but it can be fun to play this with your friends."
},
{
"code": null,
"e": 543,
"s": 509,
"text": "There are two steps in this game:"
},
{
"code": null,
"e": 563,
"s": 543,
"text": "Take the two names."
},
{
"code": null,
"e": 634,
"s": 563,
"text": "Remove the common characters with their respective common occurrences."
},
{
"code": null,
"e": 682,
"s": 634,
"text": "Get the count of the characters that are left ."
},
{
"code": null,
"e": 736,
"s": 682,
"text": "Take FLAMES letters as [“F”, “L”, “A”, “M”, “E”, “S”]"
},
{
"code": null,
"e": 782,
"s": 736,
"text": "Start removing letter using the count we got."
},
{
"code": null,
"e": 831,
"s": 782,
"text": "The letter which last the process is the result."
},
{
"code": null,
"e": 842,
"s": 831,
"text": "Example : "
},
{
"code": null,
"e": 944,
"s": 842,
"text": "Input : player1 name : AJAY\n player 2 name : PRIYA\n\nOutput : Relationship status : Friends"
},
{
"code": null,
"e": 1299,
"s": 944,
"text": "Explanation: In above given two names A and Y are common letters which are occurring one time(common count) in both names so we are removing these letters from both names. Now count the total letters that are left here it is 5. Now start removing letters one by one from FLAMES using the count we got and the letter which lasts the process is the result."
},
{
"code": null,
"e": 1352,
"s": 1299,
"text": "Counting is done in anti-clockwise circular fashion."
},
{
"code": null,
"e": 1818,
"s": 1352,
"text": "FLAMES counting is start from F, E is at 5th count so we remove E and start counting again but a this time start from S. FLAMS M is at 5th count so we remove M and counting start from S. FLAS S is at 5th count so we remove S and counting start from F. FLA L is at 5th count so we remove L and counting start from A. FA A is at 5th count so we remove A. now we have only one letter is remaining so this is the final answer. F So, the relationship is F i.e. Friends ."
},
{
"code": null,
"e": 2575,
"s": 1818,
"text": "Approach: Take two names as input then remove the common characters with their respective common occurrences. For removing purpose we create user-defined remove_match_char function with two arguments as list1 and list2 which stores list of characters of two players name respectively and return list of concatenated list(list1 + “*” flagst2) and flag value which we store in ret_list variable.After removing all the common characters, count the total no. of remaining characters then create a result list with FLAMES acronym i.e [“Friends”, “Love”, “Affection”, “Marriage”, “Enemy”, “Siblings”]. Now start removing word one by one until list not contains only one word, using the total count which we got. the word which remains in the last, is the result."
},
{
"code": null,
"e": 2606,
"s": 2575,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 2614,
"s": 2606,
"text": "Python3"
},
{
"code": "# function for removing common characters# with their respective occurrencesdef remove_match_char(list1, list2): for i in range(len(list1)) : for j in range(len(list2)) : # if common character is found # then remove that character # and return list of concatenated # list with True Flag if list1[i] == list2[j] : c = list1[i] # remove character from the list list1.remove(c) list2.remove(c) # concatenation of two list elements with * # * is act as border mark here list3 = list1 + [\"*\"] + list2 # return the concatenated list with True flag return [list3, True] # no common characters is found # return the concatenated list with False flag list3 = list1 + [\"*\"] + list2 return [list3, False] # Driver codeif __name__ == \"__main__\" : # take first name p1 = input(\"Player 1 name : \") # converted all letters into lower case p1 = p1.lower() # replace any space with empty string p1.replace(\" \", \"\") # make a list of letters or characters p1_list = list(p1) # take 2nd name p2 = input(\"Player 2 name : \") p2 = p2.lower() p2.replace(\" \", \"\") p2_list = list(p2) # taking a flag as True initially proceed = True # keep calling remove_match_char function # until common characters is found or # keep looping until proceed flag is True while proceed : # function calling and store return value ret_list = remove_match_char(p1_list, p2_list) # take out concatenated list from return list con_list = ret_list[0] # take out flag value from return list proceed = ret_list[1] # find the index of \"*\" / border mark star_index = con_list.index(\"*\") # list slicing perform # all characters before * store in p1_list p1_list = con_list[ : star_index] # all characters after * store in p2_list p2_list = con_list[star_index + 1 : ] # count total remaining characters count = len(p1_list) + len(p2_list) # list of FLAMES acronym result = [\"Friends\", \"Love\", \"Affection\", \"Marriage\", \"Enemy\", \"Siblings\"] # keep looping until only one item # is not remaining in the result list while len(result) > 1 : # store that index value from # where we have to perform slicing. split_index = (count % len(result) - 1) # this steps is done for performing # anticlock-wise circular fashion counting. if split_index >= 0 : # list slicing right = result[split_index + 1 : ] left = result[ : split_index] # list concatenation result = right + left else : result = result[ : len(result) - 1] # print final result print(\"Relationship status :\", result[0])",
"e": 5584,
"s": 2614,
"text": null
},
{
"code": null,
"e": 5593,
"s": 5584,
"text": "Output: "
},
{
"code": null,
"e": 5670,
"s": 5593,
"text": "Player 1 name : ANKIT\nPlayer 2 name : DEEPIKA\nRelationship status : Marriage"
},
{
"code": null,
"e": 5683,
"s": 5672,
"text": "nidhi_biet"
},
{
"code": null,
"e": 5696,
"s": 5683,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5713,
"s": 5696,
"text": "surinderdawra388"
},
{
"code": null,
"e": 5732,
"s": 5713,
"text": "surindertarika1234"
},
{
"code": null,
"e": 5756,
"s": 5732,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 5763,
"s": 5756,
"text": "Python"
},
{
"code": null,
"e": 5782,
"s": 5763,
"text": "Technical Scripter"
}
]
|
string::npos in C++ with Examples | 16 Jul, 2021
What is string::npos:
It is a constant static member value with the highest possible value for an element of type size_t.
It actually means until the end of the string.
It is used as the value for a length parameter in the string’s member functions.
As a return value, it is usually used to indicate no matches.
Syntax:
static const size_t npos = -1;Where, npos is constant static value with the highest possible value for an element of type size_t and it is defined with -1.
Program 1: Below is the C++ program to illustrate the use of string::npos:
C++
// C++ program to demonstrate the use// of string::npos#include <bits/stdc++.h>using namespace std; // Function that using string::npos// to find the index of the occurrence// of any string in the given stringvoid fun(string s1, string s2){ // Find position of string s2 int found = s1.find(s2); // Check if position is -1 or not if (found != string::npos) { cout << "first " << s2 << " found at: " << (found) << endl; } else cout << s2 << " is not in" << "the string" << endl;} // Driver Codeint main(){ // Given strings string s1 = "geeksforgeeks"; string s2 = "for"; string s3 = "no"; // Function Call fun(s1, s2); return 0;}
first for found at: 5
Explanation: In the above program string:npos constant is defined with a value of -1, because size_t is an unsigned integral type, and -1 is the largest possible representable value for this type.
raghavrakh
shivprakash0820
chawla19gurpreet
cpp-string
cpp-strings
cpp-strings-library
C++
C++ Programs
Strings
cpp-strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ program for hashing with chaining | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 74,
"s": 52,
"text": "What is string::npos:"
},
{
"code": null,
"e": 174,
"s": 74,
"text": "It is a constant static member value with the highest possible value for an element of type size_t."
},
{
"code": null,
"e": 221,
"s": 174,
"text": "It actually means until the end of the string."
},
{
"code": null,
"e": 302,
"s": 221,
"text": "It is used as the value for a length parameter in the string’s member functions."
},
{
"code": null,
"e": 364,
"s": 302,
"text": "As a return value, it is usually used to indicate no matches."
},
{
"code": null,
"e": 372,
"s": 364,
"text": "Syntax:"
},
{
"code": null,
"e": 528,
"s": 372,
"text": "static const size_t npos = -1;Where, npos is constant static value with the highest possible value for an element of type size_t and it is defined with -1."
},
{
"code": null,
"e": 603,
"s": 528,
"text": "Program 1: Below is the C++ program to illustrate the use of string::npos:"
},
{
"code": null,
"e": 607,
"s": 603,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the use// of string::npos#include <bits/stdc++.h>using namespace std; // Function that using string::npos// to find the index of the occurrence// of any string in the given stringvoid fun(string s1, string s2){ // Find position of string s2 int found = s1.find(s2); // Check if position is -1 or not if (found != string::npos) { cout << \"first \" << s2 << \" found at: \" << (found) << endl; } else cout << s2 << \" is not in\" << \"the string\" << endl;} // Driver Codeint main(){ // Given strings string s1 = \"geeksforgeeks\"; string s2 = \"for\"; string s3 = \"no\"; // Function Call fun(s1, s2); return 0;}",
"e": 1330,
"s": 607,
"text": null
},
{
"code": null,
"e": 1355,
"s": 1333,
"text": "first for found at: 5"
},
{
"code": null,
"e": 1556,
"s": 1359,
"text": "Explanation: In the above program string:npos constant is defined with a value of -1, because size_t is an unsigned integral type, and -1 is the largest possible representable value for this type."
},
{
"code": null,
"e": 1569,
"s": 1558,
"text": "raghavrakh"
},
{
"code": null,
"e": 1585,
"s": 1569,
"text": "shivprakash0820"
},
{
"code": null,
"e": 1602,
"s": 1585,
"text": "chawla19gurpreet"
},
{
"code": null,
"e": 1613,
"s": 1602,
"text": "cpp-string"
},
{
"code": null,
"e": 1625,
"s": 1613,
"text": "cpp-strings"
},
{
"code": null,
"e": 1645,
"s": 1625,
"text": "cpp-strings-library"
},
{
"code": null,
"e": 1649,
"s": 1645,
"text": "C++"
},
{
"code": null,
"e": 1662,
"s": 1649,
"text": "C++ Programs"
},
{
"code": null,
"e": 1670,
"s": 1662,
"text": "Strings"
},
{
"code": null,
"e": 1682,
"s": 1670,
"text": "cpp-strings"
},
{
"code": null,
"e": 1690,
"s": 1682,
"text": "Strings"
},
{
"code": null,
"e": 1694,
"s": 1690,
"text": "CPP"
},
{
"code": null,
"e": 1792,
"s": 1694,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1816,
"s": 1792,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1836,
"s": 1816,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 1861,
"s": 1836,
"text": "std::string class in C++"
},
{
"code": null,
"e": 1894,
"s": 1861,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 1938,
"s": 1894,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1973,
"s": 1938,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 2007,
"s": 1973,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 2051,
"s": 2007,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 2110,
"s": 2051,
"text": "How to return multiple values from a function in C or C++?"
}
]
|
Fault Injection in Software Engineering | 24 Jun, 2019
Fault Injection is a technique for enhancing the testing quality by involving the intentional faults in the software. Fault injection is often in stress testing and it is considered as an important part of developing robust software.
The broadcast of a fault through to an noticeable failure follows a well defined cycle. During execution a fault can cause an error which is not a valid state within a system boundary. Same error can cause further errors within the system boundary, hence each new error acts as a fault and it may propagate to the system boundary and be observable. When an error state is observed at the system boundary that is called as failure.
Classification of Fault Injection:Fault injection can be categorized into two types on the basis of software implementation: Compile-time fault injection and Run-time fault injection. These are explained as following below.
1. Compile-time fault injection:Compile-time fault injection is a fault injection technique in which source code is modified to inject imitated faults into a system.
Two methods are used to implement fault while compile time:
Code Modification:Mutation testing is used to change existing lines of code so that there may exist faults. Code mutation produces faults which are similar to the faults unintentionally done by programmers.Example:Original Code:
int main()
{
int a = 10;
while ( a > 0 )
{
cout << "GFG";
a = a - 1;
}
return 0;
}
Modified Code:
int main()
{
int a = 10;
while ( a > 0 )
{
cout << "GFG";
a = a + 1; // '-' is changed to '+'
}
return 0;
} Now it can be observed that value of a will increase and "while loop" will never terminate and program will go into an infinite loop.
Example:
Original Code:
int main()
{
int a = 10;
while ( a > 0 )
{
cout << "GFG";
a = a - 1;
}
return 0;
}
Modified Code:
int main()
{
int a = 10;
while ( a > 0 )
{
cout << "GFG";
a = a + 1; // '-' is changed to '+'
}
return 0;
}
Now it can be observed that value of a will increase and "while loop" will never terminate and program will go into an infinite loop.
Code Insertion:A second method of code mutation is code insertion fault injection which adds code instead of modifying existing code. This is basically done by the use of anxiety functions which are simple functions which take an existing value and change it via some logic into another value.Example:Original Code:
int main()
{
int a = 10;
while ( a > 0 )
{
cout << "GFG";
a = a - 1;
}
return 0;
}
Modified Code:
int main()
{
int a = 10;
while ( a > 0 )
{
cout << "GFG";
a = a - 1;
a++; // Additional code
}
return 0;
} Now it can be observed that value of a will be fixed and "while loop" will never terminate and program will go into an infinite loop.
Example:
Original Code:
int main()
{
int a = 10;
while ( a > 0 )
{
cout << "GFG";
a = a - 1;
}
return 0;
}
Modified Code:
int main()
{
int a = 10;
while ( a > 0 )
{
cout << "GFG";
a = a - 1;
a++; // Additional code
}
return 0;
}
Now it can be observed that value of a will be fixed and "while loop" will never terminate and program will go into an infinite loop.
2. Run-time fault injection:Run-time fault injection technique uses a software trigger to inject a fault into a running software system. Faults can be injected via a number of physical methods and triggers can be implemented in different ways.
Software Triggers used in Run-time fault injection:
1. Time Based Triggers
2. Interrupt Based Triggers
3 methods are used to inject fault while run-time:
Corrupting memory space:This method involves corrupting main memory and processor registers.System call interposition:This method is related with the fault imitation from operating system kernel interfaces to executing system software. This is done by intercepting operating system calls made by user-level software and injecting faults into them.Network level:This method is related with the corrupting, loss or reordering of network packets at the network interface.
Corrupting memory space:This method involves corrupting main memory and processor registers.
System call interposition:This method is related with the fault imitation from operating system kernel interfaces to executing system software. This is done by intercepting operating system calls made by user-level software and injecting faults into them.
Network level:This method is related with the corrupting, loss or reordering of network packets at the network interface.
Fault Injection in different software testings:
(a) Robustness Testing – In robustness testing fault injection is used.
(b) Stress Testing – fault injection is also used in stress testing.
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Functional vs Non Functional Requirements
Differences between Verification and Validation
Unit Testing | Software Testing
Software Engineering | Classical Waterfall Model
Software Requirement Specification (SRS) Format
Difference between Spring and Spring Boot
Software Engineering | Requirements Engineering Process
Software Testing Life Cycle (STLC)
Difference between IAAS, PAAS and SAAS
Software Engineering | Architectural Design | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jun, 2019"
},
{
"code": null,
"e": 262,
"s": 28,
"text": "Fault Injection is a technique for enhancing the testing quality by involving the intentional faults in the software. Fault injection is often in stress testing and it is considered as an important part of developing robust software."
},
{
"code": null,
"e": 693,
"s": 262,
"text": "The broadcast of a fault through to an noticeable failure follows a well defined cycle. During execution a fault can cause an error which is not a valid state within a system boundary. Same error can cause further errors within the system boundary, hence each new error acts as a fault and it may propagate to the system boundary and be observable. When an error state is observed at the system boundary that is called as failure."
},
{
"code": null,
"e": 917,
"s": 693,
"text": "Classification of Fault Injection:Fault injection can be categorized into two types on the basis of software implementation: Compile-time fault injection and Run-time fault injection. These are explained as following below."
},
{
"code": null,
"e": 1083,
"s": 917,
"text": "1. Compile-time fault injection:Compile-time fault injection is a fault injection technique in which source code is modified to inject imitated faults into a system."
},
{
"code": null,
"e": 1143,
"s": 1083,
"text": "Two methods are used to implement fault while compile time:"
},
{
"code": null,
"e": 1749,
"s": 1143,
"text": "Code Modification:Mutation testing is used to change existing lines of code so that there may exist faults. Code mutation produces faults which are similar to the faults unintentionally done by programmers.Example:Original Code:\nint main()\n{\n int a = 10;\n while ( a > 0 )\n {\n cout << \"GFG\";\n a = a - 1;\n }\n return 0;\n}\n\nModified Code:\nint main()\n{\n int a = 10;\n while ( a > 0 )\n {\n cout << \"GFG\";\n a = a + 1; // '-' is changed to '+'\n }\n return 0;\n} Now it can be observed that value of a will increase and \"while loop\" will never terminate and program will go into an infinite loop."
},
{
"code": null,
"e": 1758,
"s": 1749,
"text": "Example:"
},
{
"code": null,
"e": 2017,
"s": 1758,
"text": "Original Code:\nint main()\n{\n int a = 10;\n while ( a > 0 )\n {\n cout << \"GFG\";\n a = a - 1;\n }\n return 0;\n}\n\nModified Code:\nint main()\n{\n int a = 10;\n while ( a > 0 )\n {\n cout << \"GFG\";\n a = a + 1; // '-' is changed to '+'\n }\n return 0;\n} "
},
{
"code": null,
"e": 2151,
"s": 2017,
"text": "Now it can be observed that value of a will increase and \"while loop\" will never terminate and program will go into an infinite loop."
},
{
"code": null,
"e": 2847,
"s": 2151,
"text": "Code Insertion:A second method of code mutation is code insertion fault injection which adds code instead of modifying existing code. This is basically done by the use of anxiety functions which are simple functions which take an existing value and change it via some logic into another value.Example:Original Code:\nint main()\n{\n int a = 10;\n while ( a > 0 )\n {\n cout << \"GFG\";\n a = a - 1;\n }\n return 0;\n}\n\nModified Code:\nint main()\n{\n int a = 10;\n while ( a > 0 )\n {\n cout << \"GFG\";\n a = a - 1;\n a++; // Additional code\n }\n return 0;\n} Now it can be observed that value of a will be fixed and \"while loop\" will never terminate and program will go into an infinite loop."
},
{
"code": null,
"e": 2856,
"s": 2847,
"text": "Example:"
},
{
"code": null,
"e": 3118,
"s": 2856,
"text": "Original Code:\nint main()\n{\n int a = 10;\n while ( a > 0 )\n {\n cout << \"GFG\";\n a = a - 1;\n }\n return 0;\n}\n\nModified Code:\nint main()\n{\n int a = 10;\n while ( a > 0 )\n {\n cout << \"GFG\";\n a = a - 1;\n a++; // Additional code\n }\n return 0;\n} "
},
{
"code": null,
"e": 3252,
"s": 3118,
"text": "Now it can be observed that value of a will be fixed and \"while loop\" will never terminate and program will go into an infinite loop."
},
{
"code": null,
"e": 3496,
"s": 3252,
"text": "2. Run-time fault injection:Run-time fault injection technique uses a software trigger to inject a fault into a running software system. Faults can be injected via a number of physical methods and triggers can be implemented in different ways."
},
{
"code": null,
"e": 3548,
"s": 3496,
"text": "Software Triggers used in Run-time fault injection:"
},
{
"code": null,
"e": 3600,
"s": 3548,
"text": "1. Time Based Triggers\n2. Interrupt Based Triggers "
},
{
"code": null,
"e": 3651,
"s": 3600,
"text": "3 methods are used to inject fault while run-time:"
},
{
"code": null,
"e": 4120,
"s": 3651,
"text": "Corrupting memory space:This method involves corrupting main memory and processor registers.System call interposition:This method is related with the fault imitation from operating system kernel interfaces to executing system software. This is done by intercepting operating system calls made by user-level software and injecting faults into them.Network level:This method is related with the corrupting, loss or reordering of network packets at the network interface."
},
{
"code": null,
"e": 4213,
"s": 4120,
"text": "Corrupting memory space:This method involves corrupting main memory and processor registers."
},
{
"code": null,
"e": 4469,
"s": 4213,
"text": "System call interposition:This method is related with the fault imitation from operating system kernel interfaces to executing system software. This is done by intercepting operating system calls made by user-level software and injecting faults into them."
},
{
"code": null,
"e": 4591,
"s": 4469,
"text": "Network level:This method is related with the corrupting, loss or reordering of network packets at the network interface."
},
{
"code": null,
"e": 4639,
"s": 4591,
"text": "Fault Injection in different software testings:"
},
{
"code": null,
"e": 4711,
"s": 4639,
"text": "(a) Robustness Testing – In robustness testing fault injection is used."
},
{
"code": null,
"e": 4780,
"s": 4711,
"text": "(b) Stress Testing – fault injection is also used in stress testing."
},
{
"code": null,
"e": 4797,
"s": 4780,
"text": "Software Testing"
},
{
"code": null,
"e": 4818,
"s": 4797,
"text": "Software Engineering"
},
{
"code": null,
"e": 4916,
"s": 4818,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4958,
"s": 4916,
"text": "Functional vs Non Functional Requirements"
},
{
"code": null,
"e": 5006,
"s": 4958,
"text": "Differences between Verification and Validation"
},
{
"code": null,
"e": 5038,
"s": 5006,
"text": "Unit Testing | Software Testing"
},
{
"code": null,
"e": 5087,
"s": 5038,
"text": "Software Engineering | Classical Waterfall Model"
},
{
"code": null,
"e": 5135,
"s": 5087,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 5177,
"s": 5135,
"text": "Difference between Spring and Spring Boot"
},
{
"code": null,
"e": 5233,
"s": 5177,
"text": "Software Engineering | Requirements Engineering Process"
},
{
"code": null,
"e": 5268,
"s": 5233,
"text": "Software Testing Life Cycle (STLC)"
},
{
"code": null,
"e": 5307,
"s": 5268,
"text": "Difference between IAAS, PAAS and SAAS"
}
]
|
MySQL - REVOKE Statement | The MySQL REVOKE statement is used to revoke the privileges or roles on an account.
Following is the syntax of the MySQL REVOKE Statement −
REVOKE
privilege1, privilege2, privilege3....
ON [object_type] priv_level
TO user_or_role1, user_or_role2, user_or_role3....
Assume we have created a user named 'test_user'@'localhost' in MySQL using the CREATE USER statement −
mysql> CREATE USER 'test_user'@'localhost' IDENTIFIED BY 'testpassword';
Query OK, 0 rows affected (0.23 sec)
Now, let us create a database and create a table in it.
mysql> CREATE DATABASE test_database;
Query OK, 1 row affected (0.56 sec)
mysql> USE test_database;
Database changed
mysql> CREATE TABLE MyTable(data VARCHAR(255));
Query OK, 0 rows affected (0.67 sec)
Following query grants privileges on the table created above, to the user 'test_user'@'localhost −
mysql> GRANT SELECT ON test_database.MyTable TO 'test_user'@'localhost';
Query OK, 0 rows affected (0.31 sec)
You can verify the granted privileges using the SHOW GRANTS statements −
mysql> SHOW GRANTS FOR 'test_user'@'localhost';
+----------------------------------------------------------------------+
| Grants for test_user@localhost |
+----------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `test_user`@`localhost` |
| GRANT SELECT ON `test_database`.`mytable` TO `test_user`@`localhost` |
+----------------------------------------------------------------------+
2 rows in set (0.00 sec)
Now, you can revoke the above granted privilege using the REVOKE statement as shown below −
mysql> REVOKE SELECT ON test_database.MyTable FROM 'test_user'@'localhost';
Query OK, 0 rows affected (0.25 sec)
If you verify the list of grants for the user aging you can observe that the SELECT privilege is removed from the list.
mysql> SHOW GRANTS FOR 'test_user'@'localhost';
+-----------------------------------------------+
| Grants for test_user@localhost |
+-----------------------------------------------+
| GRANT USAGE ON *.* TO `test_user`@`localhost` |
+-----------------------------------------------+
1 row in set (0.00 sec)
If a user has multiple privileges with a user, you can revoke all those privileges at once using the REVOKE ALL statement. Following is the syntax to do so −
REVOKE ALL [PRIVILEGES], GRANT OPTION
FROM user_or_role [, user_or_role] ...
Assume we have created a user, a procedure and a table with the name sample in the database as follows −
mysql> CREATE USER 'sample_user'@'localhost';
Query OK, 0 rows affected (0.18 sec)
//Creating a procedure
mysql> DELIMITER //
mysql> CREATE PROCEDURE sample ()
BEGIN
SELECT 'This is a sample procedure';
END//
Query OK, 0 rows affected (0.29 sec)
mysql> DELIMITER ;
mysql> CREATE TABLE sample(data INT);
Query OK, 0 rows affected (0.68 sec)
Following queries grants ALTER ROUTINE, EXECUTE privileges on the above created procedure to the user named 'sample_user'@'localhost'.
mysql> GRANT ALTER ROUTINE, EXECUTE ON PROCEDURE test_database.sample TO 'sample_user'@'localhost';
Query OK, 0 rows affected (0.20 sec)
Similarly, following query grants SELECT, INSERT and UPDATE privileges on the table sample to the user 'sample_user'@'localhost −
mysql> GRANT SELECT, INSERT, UPDATE ON test.sample TO 'sample_user'@'localhost';
Query OK, 0 rows affected (0.14 sec)
You can verify the list of all privileges granted for the user −
mysql> SHOW GRANTS FOR 'sample_user'@'localhost';
+-------------------------------------------------------------------------------------------------+
| Grants for sample_user@localhost |
+-------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `sample_user`@`localhost` |
| GRANT SELECT, INSERT, UPDATE ON `test`.`sample` TO `sample_user`@`localhost` |
| GRANT EXECUTE, ALTER ROUTINE ON PROCEDURE `test_database`.`sample` TO `sample_user`@`localhost` |
+-------------------------------------------------------------------------------------------------+
3 rows in set (0.00 sec)
Following query revokes all the privileges granted to the user 'sample_user'@'localhost' −
mysql> REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'sample_user'@'localhost';
Query OK, 0 rows affected (0.30 sec)
mysql> SHOW GRANTS FOR 'sample_user'@'localhost';
+-------------------------------------------------+
| Grants for sample_user@localhost |
+-------------------------------------------------+
| GRANT USAGE ON *.* TO `sample_user`@`localhost` |
+-------------------------------------------------+
1 row in set (0.00 sec)
You can make one user as a proxy of another by granting the PROXY privilege to it. If you do so both users have the same privileges.
Assume we have created a users named sample_user, proxy_user and a table named Emp in MySQL using the CREATE statement −
mysql> CREATE USER sample_user, proxy_user IDENTIFIED BY 'testpassword';
Query OK, 0 rows affected (0.52 sec)
mysql> CREATE TABLE Emp (ID INT, Name VARCHAR(15), Phone INT, SAL INT);
Query OK, 0 rows affected (6.47 sec)
Following query grants SELECT and INSERT privileges on the table created above, to the user sample_user −
mysql> GRANT SELECT, INSERT ON Emp TO sample_user;
Query OK, 0 rows affected (0.28 sec)
Now, we can assign proxy privileges to the user proxy_user, using the GRANT statement as shown below −
mysql> GRANT PROXY ON sample_user TO proxy_user;
Query OK, 0 rows affected (1.61 sec)
You can revoke a proxy privilege using the REVOKE PROXY statement as shown below −
mysql> REVOKE PROXY ON sample_user FROM proxy_user;
Query OK, 0 rows affected (0.33 sec)
A role in MySQL is a set of privileges with name. You can create one or more roles in MySQL using the CREATE ROLE statement. If you use the GRANT statement without the ON clause you can grant a role instead of privileges.
Following query creates a role named TestRole_ReadOnly.
mysql> CREATE ROLE 'TestRole_ReadOnly';
Query OK, 0 rows affected (0.13 sec)
Now, let’s grant read only privilege to the created role using the GRANT statement as −
mysql> GRANT SELECT ON * . * TO 'TestRole_ReadOnly';
Query OK, 0 rows affected (0.14 sec)
Then, you can GRANT the created role to a user as follows −
mysql> CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
Query OK, 0 rows affected (0.14 sec)
mysql> GRANT 'TestRole_ReadOnly' TO 'newuser'@'localhost';
Query OK, 0 rows affected (0.13 sec)
Following query revokes the role from the user −
mysql> REVOKE 'TestRole_ReadOnly' FROM 'newuser'@'localhost';
Query OK, 0 rows affected (1.23 sec) | [
{
"code": null,
"e": 2525,
"s": 2441,
"text": "The MySQL REVOKE statement is used to revoke the privileges or roles on an account."
},
{
"code": null,
"e": 2581,
"s": 2525,
"text": "Following is the syntax of the MySQL REVOKE Statement −"
},
{
"code": null,
"e": 2716,
"s": 2581,
"text": "REVOKE\n privilege1, privilege2, privilege3....\n ON [object_type] priv_level\n TO user_or_role1, user_or_role2, user_or_role3....\n"
},
{
"code": null,
"e": 2819,
"s": 2716,
"text": "Assume we have created a user named 'test_user'@'localhost' in MySQL using the CREATE USER statement −"
},
{
"code": null,
"e": 2929,
"s": 2819,
"text": "mysql> CREATE USER 'test_user'@'localhost' IDENTIFIED BY 'testpassword';\nQuery OK, 0 rows affected (0.23 sec)"
},
{
"code": null,
"e": 2985,
"s": 2929,
"text": "Now, let us create a database and create a table in it."
},
{
"code": null,
"e": 3189,
"s": 2985,
"text": "mysql> CREATE DATABASE test_database;\nQuery OK, 1 row affected (0.56 sec)\n\nmysql> USE test_database;\nDatabase changed\n\nmysql> CREATE TABLE MyTable(data VARCHAR(255));\nQuery OK, 0 rows affected (0.67 sec)"
},
{
"code": null,
"e": 3288,
"s": 3189,
"text": "Following query grants privileges on the table created above, to the user 'test_user'@'localhost −"
},
{
"code": null,
"e": 3398,
"s": 3288,
"text": "mysql> GRANT SELECT ON test_database.MyTable TO 'test_user'@'localhost';\nQuery OK, 0 rows affected (0.31 sec)"
},
{
"code": null,
"e": 3471,
"s": 3398,
"text": "You can verify the granted privileges using the SHOW GRANTS statements −"
},
{
"code": null,
"e": 3983,
"s": 3471,
"text": "mysql> SHOW GRANTS FOR 'test_user'@'localhost';\n+----------------------------------------------------------------------+ \n| Grants for test_user@localhost |\n+----------------------------------------------------------------------+\n| GRANT USAGE ON *.* TO `test_user`@`localhost` |\n| GRANT SELECT ON `test_database`.`mytable` TO `test_user`@`localhost` |\n+----------------------------------------------------------------------+\n2 rows in set (0.00 sec)"
},
{
"code": null,
"e": 4075,
"s": 3983,
"text": "Now, you can revoke the above granted privilege using the REVOKE statement as shown below −"
},
{
"code": null,
"e": 4188,
"s": 4075,
"text": "mysql> REVOKE SELECT ON test_database.MyTable FROM 'test_user'@'localhost';\nQuery OK, 0 rows affected (0.25 sec)"
},
{
"code": null,
"e": 4308,
"s": 4188,
"text": "If you verify the list of grants for the user aging you can observe that the SELECT privilege is removed from the list."
},
{
"code": null,
"e": 4630,
"s": 4308,
"text": "mysql> SHOW GRANTS FOR 'test_user'@'localhost';\n+-----------------------------------------------+\n| Grants for test_user@localhost |\n+-----------------------------------------------+\n| GRANT USAGE ON *.* TO `test_user`@`localhost` |\n+-----------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 4788,
"s": 4630,
"text": "If a user has multiple privileges with a user, you can revoke all those privileges at once using the REVOKE ALL statement. Following is the syntax to do so −"
},
{
"code": null,
"e": 4869,
"s": 4788,
"text": "REVOKE ALL [PRIVILEGES], GRANT OPTION\n FROM user_or_role [, user_or_role] ... "
},
{
"code": null,
"e": 4974,
"s": 4869,
"text": "Assume we have created a user, a procedure and a table with the name sample in the database as follows −"
},
{
"code": null,
"e": 5329,
"s": 4974,
"text": "mysql> CREATE USER 'sample_user'@'localhost';\nQuery OK, 0 rows affected (0.18 sec)\n\n//Creating a procedure\nmysql> DELIMITER //\n\nmysql> CREATE PROCEDURE sample ()\n BEGIN\n SELECT 'This is a sample procedure';\n END//\nQuery OK, 0 rows affected (0.29 sec)\nmysql> DELIMITER ;\n\nmysql> CREATE TABLE sample(data INT);\nQuery OK, 0 rows affected (0.68 sec)"
},
{
"code": null,
"e": 5464,
"s": 5329,
"text": "Following queries grants ALTER ROUTINE, EXECUTE privileges on the above created procedure to the user named 'sample_user'@'localhost'."
},
{
"code": null,
"e": 5601,
"s": 5464,
"text": "mysql> GRANT ALTER ROUTINE, EXECUTE ON PROCEDURE test_database.sample TO 'sample_user'@'localhost';\nQuery OK, 0 rows affected (0.20 sec)"
},
{
"code": null,
"e": 5731,
"s": 5601,
"text": "Similarly, following query grants SELECT, INSERT and UPDATE privileges on the table sample to the user 'sample_user'@'localhost −"
},
{
"code": null,
"e": 5849,
"s": 5731,
"text": "mysql> GRANT SELECT, INSERT, UPDATE ON test.sample TO 'sample_user'@'localhost';\nQuery OK, 0 rows affected (0.14 sec)"
},
{
"code": null,
"e": 5914,
"s": 5849,
"text": "You can verify the list of all privileges granted for the user −"
},
{
"code": null,
"e": 6689,
"s": 5914,
"text": "mysql> SHOW GRANTS FOR 'sample_user'@'localhost';\n+-------------------------------------------------------------------------------------------------+\n| Grants for sample_user@localhost |\n+-------------------------------------------------------------------------------------------------+\n| GRANT USAGE ON *.* TO `sample_user`@`localhost` |\n| GRANT SELECT, INSERT, UPDATE ON `test`.`sample` TO `sample_user`@`localhost` |\n| GRANT EXECUTE, ALTER ROUTINE ON PROCEDURE `test_database`.`sample` TO `sample_user`@`localhost` |\n+-------------------------------------------------------------------------------------------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 6780,
"s": 6689,
"text": "Following query revokes all the privileges granted to the user 'sample_user'@'localhost' −"
},
{
"code": null,
"e": 6892,
"s": 6780,
"text": "mysql> REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'sample_user'@'localhost';\nQuery OK, 0 rows affected (0.30 sec)"
},
{
"code": null,
"e": 7226,
"s": 6892,
"text": "mysql> SHOW GRANTS FOR 'sample_user'@'localhost';\n+-------------------------------------------------+\n| Grants for sample_user@localhost |\n+-------------------------------------------------+\n| GRANT USAGE ON *.* TO `sample_user`@`localhost` |\n+-------------------------------------------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 7359,
"s": 7226,
"text": "You can make one user as a proxy of another by granting the PROXY privilege to it. If you do so both users have the same privileges."
},
{
"code": null,
"e": 7480,
"s": 7359,
"text": "Assume we have created a users named sample_user, proxy_user and a table named Emp in MySQL using the CREATE statement −"
},
{
"code": null,
"e": 7700,
"s": 7480,
"text": "mysql> CREATE USER sample_user, proxy_user IDENTIFIED BY 'testpassword';\nQuery OK, 0 rows affected (0.52 sec)\n\nmysql> CREATE TABLE Emp (ID INT, Name VARCHAR(15), Phone INT, SAL INT);\nQuery OK, 0 rows affected (6.47 sec)"
},
{
"code": null,
"e": 7806,
"s": 7700,
"text": "Following query grants SELECT and INSERT privileges on the table created above, to the user sample_user −"
},
{
"code": null,
"e": 7894,
"s": 7806,
"text": "mysql> GRANT SELECT, INSERT ON Emp TO sample_user;\nQuery OK, 0 rows affected (0.28 sec)"
},
{
"code": null,
"e": 7997,
"s": 7894,
"text": "Now, we can assign proxy privileges to the user proxy_user, using the GRANT statement as shown below −"
},
{
"code": null,
"e": 8083,
"s": 7997,
"text": "mysql> GRANT PROXY ON sample_user TO proxy_user;\nQuery OK, 0 rows affected (1.61 sec)"
},
{
"code": null,
"e": 8166,
"s": 8083,
"text": "You can revoke a proxy privilege using the REVOKE PROXY statement as shown below −"
},
{
"code": null,
"e": 8255,
"s": 8166,
"text": "mysql> REVOKE PROXY ON sample_user FROM proxy_user;\nQuery OK, 0 rows affected (0.33 sec)"
},
{
"code": null,
"e": 8477,
"s": 8255,
"text": "A role in MySQL is a set of privileges with name. You can create one or more roles in MySQL using the CREATE ROLE statement. If you use the GRANT statement without the ON clause you can grant a role instead of privileges."
},
{
"code": null,
"e": 8533,
"s": 8477,
"text": "Following query creates a role named TestRole_ReadOnly."
},
{
"code": null,
"e": 8610,
"s": 8533,
"text": "mysql> CREATE ROLE 'TestRole_ReadOnly';\nQuery OK, 0 rows affected (0.13 sec)"
},
{
"code": null,
"e": 8698,
"s": 8610,
"text": "Now, let’s grant read only privilege to the created role using the GRANT statement as −"
},
{
"code": null,
"e": 8788,
"s": 8698,
"text": "mysql> GRANT SELECT ON * . * TO 'TestRole_ReadOnly';\nQuery OK, 0 rows affected (0.14 sec)"
},
{
"code": null,
"e": 8848,
"s": 8788,
"text": "Then, you can GRANT the created role to a user as follows −"
},
{
"code": null,
"e": 9050,
"s": 8848,
"text": "mysql> CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';\nQuery OK, 0 rows affected (0.14 sec)\n\nmysql> GRANT 'TestRole_ReadOnly' TO 'newuser'@'localhost';\nQuery OK, 0 rows affected (0.13 sec)"
},
{
"code": null,
"e": 9099,
"s": 9050,
"text": "Following query revokes the role from the user −"
}
]
|
How to register a BroadcastReceiver programmatically in Android? | This example demonstrates how do I register a BroadcastReceiver programtically in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:layout_centerInParent="true"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
ExampleBroadcastReceiver exampleBroadcastReceiver = new ExampleBroadcastReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void onStart(){
super.onStart();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(exampleBroadcastReceiver, filter);
}
@Override
protected void onStop(){
super.onStop();
unregisterReceiver(exampleBroadcastReceiver);
}
}
Step 4 – Create a new java class and the following code in exampleBroadcastReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;
class ExampleBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noConnectivity) {
Toast.makeText(context, "Disconnected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
}
}
}
}
Step 5 - Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code. | [
{
"code": null,
"e": 1278,
"s": 1187,
"text": "This example demonstrates how do I register a BroadcastReceiver programtically in android."
},
{
"code": null,
"e": 1407,
"s": 1278,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1472,
"s": 1407,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1943,
"s": 1472,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 2000,
"s": 1943,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2779,
"s": 2000,
"text": "import android.content.IntentFilter;\nimport android.net.ConnectivityManager;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n ExampleBroadcastReceiver exampleBroadcastReceiver = new ExampleBroadcastReceiver();\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n protected void onStart(){\n super.onStart();\n IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);\n registerReceiver(exampleBroadcastReceiver, filter);\n }\n @Override\n protected void onStop(){\n super.onStop();\n unregisterReceiver(exampleBroadcastReceiver);\n }\n}"
},
{
"code": null,
"e": 2868,
"s": 2779,
"text": "Step 4 – Create a new java class and the following code in exampleBroadcastReceiver.java"
},
{
"code": null,
"e": 3593,
"s": 2868,
"text": "import android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.ConnectivityManager;\nimport android.widget.Toast;\nclass ExampleBroadcastReceiver extends BroadcastReceiver {\n @Override\n public void onReceive(Context context, Intent intent) {\n if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {\n boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);\n if (noConnectivity) {\n Toast.makeText(context, \"Disconnected\", Toast.LENGTH_SHORT).show();\n } else {\n Toast.makeText(context, \"Connected\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n}"
},
{
"code": null,
"e": 3648,
"s": 3593,
"text": "Step 5 - Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4318,
"s": 3648,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4665,
"s": 4318,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 4706,
"s": 4665,
"text": "Click here to download the project code."
}
]
|
AngularJS | ng-mouseover Directive | 26 Mar, 2019
The ng-mouseover Directive in AngularJS is used to apply custom behavior when an mouseover event occurs on a specific HTML element. It can be used to show popup alert when mouse moves over a specific element. It is supported by all HTML elements.
Syntax:
<element ng-mouseover="expression"> Contents... </element>
Example 1: This example uses ng-mouseover Directive to display content when mouse move over the element.
<!DOCTYPE html><html> <head> <title>ng-mouseover Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <style type="text/css"> .geek { border: 1px solid black; width: 400px; background-color: green; border-radius: 4px; height: 20px; color: white; } </style></head> <body ng-app=""> <center> <h1 style="color:green"> GeeksforGeeks </h1> <h2>ng-mouseover Directive</h2> <div ng-init="geek=false"> <button ng-mouseover="geek=true" ng-mouseleave="geek=false"> Mouse over me! </button> <br><br> <div class="geek" ng-show="geek"> GeeksforGeeks is the computer science portal for geeks. </div> </div> </center></body> </html>
Output:Before mouseover the element:After mouseover the element:
Example 2: This example uses ng-mouseover Directive to display an alert message when mouse move over element.
<!DOCTYPE html><html> <head> <title>ng-mouseover Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body ng-app="app" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-mouseover Directive</h2> <div ng-controller="app"> Input: <input type="text" ng-mouseover="alert()" ng-model="click" /> </div> <script> var app = angular.module("app", []); app.controller('app', ['$scope', function ($scope) { $scope.click = 'geeksforgeeks'; $scope.alert = function () { alert($scope.click); } }]); </script></body> </html>
Output:Before mouseover the element:After mouseover the element:
AngularJS-Directives
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?
How to set input type date in dd-mm-yyyy format using HTML ?
Roadmap to Learn JavaScript For Beginners | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2019"
},
{
"code": null,
"e": 275,
"s": 28,
"text": "The ng-mouseover Directive in AngularJS is used to apply custom behavior when an mouseover event occurs on a specific HTML element. It can be used to show popup alert when mouse moves over a specific element. It is supported by all HTML elements."
},
{
"code": null,
"e": 283,
"s": 275,
"text": "Syntax:"
},
{
"code": null,
"e": 342,
"s": 283,
"text": "<element ng-mouseover=\"expression\"> Contents... </element>"
},
{
"code": null,
"e": 447,
"s": 342,
"text": "Example 1: This example uses ng-mouseover Directive to display content when mouse move over the element."
},
{
"code": "<!DOCTYPE html><html> <head> <title>ng-mouseover Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <style type=\"text/css\"> .geek { border: 1px solid black; width: 400px; background-color: green; border-radius: 4px; height: 20px; color: white; } </style></head> <body ng-app=\"\"> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2>ng-mouseover Directive</h2> <div ng-init=\"geek=false\"> <button ng-mouseover=\"geek=true\" ng-mouseleave=\"geek=false\"> Mouse over me! </button> <br><br> <div class=\"geek\" ng-show=\"geek\"> GeeksforGeeks is the computer science portal for geeks. </div> </div> </center></body> </html>",
"e": 1461,
"s": 447,
"text": null
},
{
"code": null,
"e": 1526,
"s": 1461,
"text": "Output:Before mouseover the element:After mouseover the element:"
},
{
"code": null,
"e": 1636,
"s": 1526,
"text": "Example 2: This example uses ng-mouseover Directive to display an alert message when mouse move over element."
},
{
"code": "<!DOCTYPE html><html> <head> <title>ng-mouseover Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body ng-app=\"app\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>ng-mouseover Directive</h2> <div ng-controller=\"app\"> Input: <input type=\"text\" ng-mouseover=\"alert()\" ng-model=\"click\" /> </div> <script> var app = angular.module(\"app\", []); app.controller('app', ['$scope', function ($scope) { $scope.click = 'geeksforgeeks'; $scope.alert = function () { alert($scope.click); } }]); </script></body> </html>",
"e": 2383,
"s": 1636,
"text": null
},
{
"code": null,
"e": 2448,
"s": 2383,
"text": "Output:Before mouseover the element:After mouseover the element:"
},
{
"code": null,
"e": 2469,
"s": 2448,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 2486,
"s": 2469,
"text": "Web Technologies"
},
{
"code": null,
"e": 2584,
"s": 2486,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2645,
"s": 2584,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2688,
"s": 2645,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2760,
"s": 2688,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2800,
"s": 2760,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2824,
"s": 2800,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2857,
"s": 2824,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 2917,
"s": 2857,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2975,
"s": 2917,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 3036,
"s": 2975,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
]
|
Android EditText in Kotlin - GeeksforGeeks | 18 Feb, 2021
EditText is used to get input from the user. EditText is commonly used in forms and login or registration screens. Following steps are used to create EditText in Kotlin:
Add a EditText in activity_main.xml file.Add a Button in activity_main.xml file.Open MainActivity.kt file and set OnClickListner for the button to get the user input from EditText and show the input as Toast message.
Add a EditText in activity_main.xml file.
Add a Button in activity_main.xml file.
Open MainActivity.kt file and set OnClickListner for the button to get the user input from EditText and show the input as Toast message.
Step 1: Open activity_main.xml file and create an EditText using id editText.
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--EditText with id editText--> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:hint="Input" android:inputType="text"/> </LinearLayout>
Step 2: In activity_main.xml file add code to show a button. Final activity_main.xml file is
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--EditText with id editText--> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:hint="Input" android:inputType="text"/> <!--Button with id showInput--> <Button android:id="@+id/showInput" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="show" android:backgroundTint="@color/colorPrimary" android:textColor="@android:color/white" /> </LinearLayout>
Step 3: Open MainActivity.kt file and get the reference of Button and EditText defined in the layout file.
// finding the button
val showButton = findViewById<Button>(R.id.showInput)
// finding the edit text
val editText = findViewById<EditText>(R.id.editText)
Setting the on click listener to the button
showButton.setOnClickListener {
}
Getting the text entered by user
val text = editText.text
Finally the MainActivity.kt file is
package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // finding the button val showButton = findViewById<Button>(R.id.showInput) // finding the edit text val editText = findViewById<EditText>(R.id.editText) // Setting On Click Listener showButton.setOnClickListener { // Getting the user input val text = editText.text // Showing the user input Toast.makeText(this, text, Toast.LENGTH_SHORT).show() } }}
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.geeksforgeeks.myfirstkotlinapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Android-View
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Broadcast Receiver in Android With Example
Services in Android with Example
How to Create and Add Data to SQLite Database in Android?
Content Providers in Android with Example
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Services in Android with Example
Content Providers in Android with Example
Android RecyclerView in Kotlin | [
{
"code": null,
"e": 23992,
"s": 23964,
"text": "\n18 Feb, 2021"
},
{
"code": null,
"e": 24162,
"s": 23992,
"text": "EditText is used to get input from the user. EditText is commonly used in forms and login or registration screens. Following steps are used to create EditText in Kotlin:"
},
{
"code": null,
"e": 24379,
"s": 24162,
"text": "Add a EditText in activity_main.xml file.Add a Button in activity_main.xml file.Open MainActivity.kt file and set OnClickListner for the button to get the user input from EditText and show the input as Toast message."
},
{
"code": null,
"e": 24421,
"s": 24379,
"text": "Add a EditText in activity_main.xml file."
},
{
"code": null,
"e": 24461,
"s": 24421,
"text": "Add a Button in activity_main.xml file."
},
{
"code": null,
"e": 24598,
"s": 24461,
"text": "Open MainActivity.kt file and set OnClickListner for the button to get the user input from EditText and show the input as Toast message."
},
{
"code": null,
"e": 24676,
"s": 24598,
"text": "Step 1: Open activity_main.xml file and create an EditText using id editText."
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--EditText with id editText--> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"16dp\" android:hint=\"Input\" android:inputType=\"text\"/> </LinearLayout>",
"e": 25325,
"s": 24676,
"text": null
},
{
"code": null,
"e": 25418,
"s": 25325,
"text": "Step 2: In activity_main.xml file add code to show a button. Final activity_main.xml file is"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--EditText with id editText--> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"16dp\" android:hint=\"Input\" android:inputType=\"text\"/> <!--Button with id showInput--> <Button android:id=\"@+id/showInput\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:text=\"show\" android:backgroundTint=\"@color/colorPrimary\" android:textColor=\"@android:color/white\" /> </LinearLayout>",
"e": 26458,
"s": 25418,
"text": null
},
{
"code": null,
"e": 26565,
"s": 26458,
"text": "Step 3: Open MainActivity.kt file and get the reference of Button and EditText defined in the layout file."
},
{
"code": null,
"e": 26761,
"s": 26565,
"text": " // finding the button\n val showButton = findViewById<Button>(R.id.showInput)\n \n // finding the edit text\n val editText = findViewById<EditText>(R.id.editText)\n"
},
{
"code": null,
"e": 26805,
"s": 26761,
"text": "Setting the on click listener to the button"
},
{
"code": null,
"e": 26861,
"s": 26805,
"text": "showButton.setOnClickListener {\n \n }\n"
},
{
"code": null,
"e": 26894,
"s": 26861,
"text": "Getting the text entered by user"
},
{
"code": null,
"e": 26920,
"s": 26894,
"text": "val text = editText.text\n"
},
{
"code": null,
"e": 26956,
"s": 26920,
"text": "Finally the MainActivity.kt file is"
},
{
"code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // finding the button val showButton = findViewById<Button>(R.id.showInput) // finding the edit text val editText = findViewById<EditText>(R.id.editText) // Setting On Click Listener showButton.setOnClickListener { // Getting the user input val text = editText.text // Showing the user input Toast.makeText(this, text, Toast.LENGTH_SHORT).show() } }}",
"e": 27804,
"s": 26956,
"text": null
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.geeksforgeeks.myfirstkotlinapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>",
"e": 28519,
"s": 27804,
"text": null
},
{
"code": null,
"e": 28532,
"s": 28519,
"text": "Android-View"
},
{
"code": null,
"e": 28547,
"s": 28532,
"text": "Kotlin Android"
},
{
"code": null,
"e": 28554,
"s": 28547,
"text": "Picked"
},
{
"code": null,
"e": 28562,
"s": 28554,
"text": "Android"
},
{
"code": null,
"e": 28569,
"s": 28562,
"text": "Kotlin"
},
{
"code": null,
"e": 28577,
"s": 28569,
"text": "Android"
},
{
"code": null,
"e": 28675,
"s": 28577,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28684,
"s": 28675,
"text": "Comments"
},
{
"code": null,
"e": 28697,
"s": 28684,
"text": "Old Comments"
},
{
"code": null,
"e": 28740,
"s": 28697,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 28773,
"s": 28740,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 28831,
"s": 28773,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 28873,
"s": 28831,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 28904,
"s": 28873,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 28947,
"s": 28904,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 28980,
"s": 28947,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 29022,
"s": 28980,
"text": "Content Providers in Android with Example"
}
]
|
6 Lesser Known Pandas Plotting Tools | by Soner Yıldırım | Towards Data Science | Pandas is the go-to Python library for data analysis and manipulation. It provides numerous functions and methods that expedice the data analysis process.
When it comes to data visualization, pandas is not the prominent choice because there exist great visualization libraries such as matplotlib, seaborn, and plotly.
With that being said, we cannot just ignore the plotting tools of pandas. They help to discover relations within dataframes or series and syntax is pretty simple. Very informative plots can be created with just one line of code.
In this post, we will cover 6 plotting tools of pandas which definitely add value to the exploratory data analysis process.
The first step to create a great machine learning model is to explore and understand the structure and relations within the data.
These 6 plotting tools will help you understand the data better:
Scatter matrix plot
Density plot
Andrews curves
Parallel coordinates
Lag plots
Autocorrelation plot
I will use a diabetes dataset available on kaggle. Let’s first read the dataset into a pandas dataframe.
import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinedf = pd.read_csv("/content/diabetes.csv")print(df.shape)df.head()
The dataset contains 8 numerical features and a target variable indicating if the person has diabetes.
Scatter plots are typically used to explore the correlation between two variables (or features). The values of data points are shown using the cartesian coordinates.
Scatter plot matrix produces a grid of scatter plots with just one line of code.
from pandas.plotting import scatter_matrixsubset = df[['Glucose','BloodPressure','Insulin','Age']]scatter_matrix(subset, figsize=(10,10), diagonal='hist')
I’ve selected a subset of the dataframe with 4 features for demonstration purposes. The diagonal shows the histogram of each variable but we can change it to show kde plot by setting diagonal parameter as ‘kde’.
We can produce density plots using kde() function on series or dataframe.
subset = df[['Glucose','BloodPressure','BMI']]subset.plot.kde(figsize=(12,6), alpha=1)
We are able to see the distribution of features with one line of code. Alpha parameter is used to adjust the darkness of lines.
Andrews curves, named after the statistician David F. Andrews, is a tool to plot multivariate data with lots of curves. The curves are created using the attributes (features) of samples as coefficients of Fourier series.
We get an overview of clustering of different classes by coloring the curves that belong to each class differently.
from pandas.plotting import andrews_curvesplt.figure(figsize=(12,8))subset = df[['Glucose','BloodPressure','BMI', 'Outcome']]andrews_curves(subset, 'Outcome', colormap='Paired')
We need to pass a dataframe and name of the variable that hold class information. Colormap parameter is optional. There seems to be a clear distinction (with some exceptions) between 2 classes based on the features in subset.
Parallel coordinates is another tool for plotting multivariate data. Let’s first create the plot and then talk about what it tells us.
from pandas.plotting import parallel_coordinatescols = ['Glucose','BloodPressure','BMI', 'Age']plt.figure(figsize=(12,8))parallel_coordinates(df,'Outcome',color=['Blue','Gray'],cols=cols)
We first import parallel_coordinates from pandas plotting tools. Then create a list of columns to use. Then a matplotlib figure is created. The last line creates parallel coordinates plot. We pass a dataframe and name of the class variable. Color parameter is optional and used to determine colors for each class. Finally cols parameter is used to select columns to be used in the plot. If not specified, all columns are used.
Each column is represented with a vertical line. The horizontal lines represent data points (rows in dataframe). We get an overview of how classes are separated according to features. “Glucose” variable seems to a good predictor to separate these two classes. On the other hand, lines of different classes overlap on “BloodPressure” which indicates it does not perform well in separating the classes.
Lag plots are used to check the randomness in a data set or time series. If a structure is displayed in lag plot, we can conclude that the data is not random.
from pandas.plotting import lag_plotplt.figure(figsize=(10,6))lag_plot(df)
There is no structure in our data set that indicates randomness.
Let’s see an example of non-random data. I will use the synthetic sample in pandas documentation page.
spacing = np.linspace(-99 * np.pi, 99 * np.pi, num=1000)data = pd.Series(0.1 * np.random.rand(1000) + 0.9 * np.sin(spacing))plt.figure(figsize=(10,6))lag_plot(data)
We can clearly see a structure on lag plot so the data is not random.
Autocorrelation plots are used to check the randomness in time series. They are produced by calculating the autocorrelations for data values at varying time lags.
Lag is the time difference. If the autocorrelations are very close to zero for all time lags, the time series is random.
If we observe one or more significantly non-zero autocorrelations, then we can conclude that time series is not random.
Let’s first create a random time series and see the autocorrelation plot.
noise = pd.Series(np.random.randn(250)*100)noise.plot(figsize=(12,6))
This time series is clearly random. The autocorrelation plot of this time series:
from pandas.plotting import autocorrelation_plotplt.figure(figsize=(12,6))autocorrelation_plot(noise)
As expected, all autocorrelation values are very close to zero.
Let’s do an example of non-random time series. The plot below shows a very simple upward trend.
upward = pd.Series(np.arange(100))upward.plot(figsize=(10,6))plt.grid()
The autocorrelation plot for this time series:
plt.figure(figsize=(12,6))autocorrelation_plot(upward)
This autocorrelation clearly indicates a non-random time series as there are many significantly non-zero values.
It is very easy to visually check the non-randomness of simple upward and downward trends. However, in real life data sets, we are likely to see highly complex time series. We may not able see the trends or seasonality in those series. In such cases, autocorrelation plots are very helpful for time series analysis.
Pandas provide two more plotting tools which are bootstap plot and RadViz. They can also be used in exploratory data analysis process.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 327,
"s": 172,
"text": "Pandas is the go-to Python library for data analysis and manipulation. It provides numerous functions and methods that expedice the data analysis process."
},
{
"code": null,
"e": 490,
"s": 327,
"text": "When it comes to data visualization, pandas is not the prominent choice because there exist great visualization libraries such as matplotlib, seaborn, and plotly."
},
{
"code": null,
"e": 719,
"s": 490,
"text": "With that being said, we cannot just ignore the plotting tools of pandas. They help to discover relations within dataframes or series and syntax is pretty simple. Very informative plots can be created with just one line of code."
},
{
"code": null,
"e": 843,
"s": 719,
"text": "In this post, we will cover 6 plotting tools of pandas which definitely add value to the exploratory data analysis process."
},
{
"code": null,
"e": 973,
"s": 843,
"text": "The first step to create a great machine learning model is to explore and understand the structure and relations within the data."
},
{
"code": null,
"e": 1038,
"s": 973,
"text": "These 6 plotting tools will help you understand the data better:"
},
{
"code": null,
"e": 1058,
"s": 1038,
"text": "Scatter matrix plot"
},
{
"code": null,
"e": 1071,
"s": 1058,
"text": "Density plot"
},
{
"code": null,
"e": 1086,
"s": 1071,
"text": "Andrews curves"
},
{
"code": null,
"e": 1107,
"s": 1086,
"text": "Parallel coordinates"
},
{
"code": null,
"e": 1117,
"s": 1107,
"text": "Lag plots"
},
{
"code": null,
"e": 1138,
"s": 1117,
"text": "Autocorrelation plot"
},
{
"code": null,
"e": 1243,
"s": 1138,
"text": "I will use a diabetes dataset available on kaggle. Let’s first read the dataset into a pandas dataframe."
},
{
"code": null,
"e": 1395,
"s": 1243,
"text": "import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inlinedf = pd.read_csv(\"/content/diabetes.csv\")print(df.shape)df.head()"
},
{
"code": null,
"e": 1498,
"s": 1395,
"text": "The dataset contains 8 numerical features and a target variable indicating if the person has diabetes."
},
{
"code": null,
"e": 1664,
"s": 1498,
"text": "Scatter plots are typically used to explore the correlation between two variables (or features). The values of data points are shown using the cartesian coordinates."
},
{
"code": null,
"e": 1745,
"s": 1664,
"text": "Scatter plot matrix produces a grid of scatter plots with just one line of code."
},
{
"code": null,
"e": 1900,
"s": 1745,
"text": "from pandas.plotting import scatter_matrixsubset = df[['Glucose','BloodPressure','Insulin','Age']]scatter_matrix(subset, figsize=(10,10), diagonal='hist')"
},
{
"code": null,
"e": 2112,
"s": 1900,
"text": "I’ve selected a subset of the dataframe with 4 features for demonstration purposes. The diagonal shows the histogram of each variable but we can change it to show kde plot by setting diagonal parameter as ‘kde’."
},
{
"code": null,
"e": 2186,
"s": 2112,
"text": "We can produce density plots using kde() function on series or dataframe."
},
{
"code": null,
"e": 2273,
"s": 2186,
"text": "subset = df[['Glucose','BloodPressure','BMI']]subset.plot.kde(figsize=(12,6), alpha=1)"
},
{
"code": null,
"e": 2401,
"s": 2273,
"text": "We are able to see the distribution of features with one line of code. Alpha parameter is used to adjust the darkness of lines."
},
{
"code": null,
"e": 2622,
"s": 2401,
"text": "Andrews curves, named after the statistician David F. Andrews, is a tool to plot multivariate data with lots of curves. The curves are created using the attributes (features) of samples as coefficients of Fourier series."
},
{
"code": null,
"e": 2738,
"s": 2622,
"text": "We get an overview of clustering of different classes by coloring the curves that belong to each class differently."
},
{
"code": null,
"e": 2916,
"s": 2738,
"text": "from pandas.plotting import andrews_curvesplt.figure(figsize=(12,8))subset = df[['Glucose','BloodPressure','BMI', 'Outcome']]andrews_curves(subset, 'Outcome', colormap='Paired')"
},
{
"code": null,
"e": 3142,
"s": 2916,
"text": "We need to pass a dataframe and name of the variable that hold class information. Colormap parameter is optional. There seems to be a clear distinction (with some exceptions) between 2 classes based on the features in subset."
},
{
"code": null,
"e": 3277,
"s": 3142,
"text": "Parallel coordinates is another tool for plotting multivariate data. Let’s first create the plot and then talk about what it tells us."
},
{
"code": null,
"e": 3465,
"s": 3277,
"text": "from pandas.plotting import parallel_coordinatescols = ['Glucose','BloodPressure','BMI', 'Age']plt.figure(figsize=(12,8))parallel_coordinates(df,'Outcome',color=['Blue','Gray'],cols=cols)"
},
{
"code": null,
"e": 3892,
"s": 3465,
"text": "We first import parallel_coordinates from pandas plotting tools. Then create a list of columns to use. Then a matplotlib figure is created. The last line creates parallel coordinates plot. We pass a dataframe and name of the class variable. Color parameter is optional and used to determine colors for each class. Finally cols parameter is used to select columns to be used in the plot. If not specified, all columns are used."
},
{
"code": null,
"e": 4293,
"s": 3892,
"text": "Each column is represented with a vertical line. The horizontal lines represent data points (rows in dataframe). We get an overview of how classes are separated according to features. “Glucose” variable seems to a good predictor to separate these two classes. On the other hand, lines of different classes overlap on “BloodPressure” which indicates it does not perform well in separating the classes."
},
{
"code": null,
"e": 4452,
"s": 4293,
"text": "Lag plots are used to check the randomness in a data set or time series. If a structure is displayed in lag plot, we can conclude that the data is not random."
},
{
"code": null,
"e": 4527,
"s": 4452,
"text": "from pandas.plotting import lag_plotplt.figure(figsize=(10,6))lag_plot(df)"
},
{
"code": null,
"e": 4592,
"s": 4527,
"text": "There is no structure in our data set that indicates randomness."
},
{
"code": null,
"e": 4695,
"s": 4592,
"text": "Let’s see an example of non-random data. I will use the synthetic sample in pandas documentation page."
},
{
"code": null,
"e": 4860,
"s": 4695,
"text": "spacing = np.linspace(-99 * np.pi, 99 * np.pi, num=1000)data = pd.Series(0.1 * np.random.rand(1000) + 0.9 * np.sin(spacing))plt.figure(figsize=(10,6))lag_plot(data)"
},
{
"code": null,
"e": 4930,
"s": 4860,
"text": "We can clearly see a structure on lag plot so the data is not random."
},
{
"code": null,
"e": 5093,
"s": 4930,
"text": "Autocorrelation plots are used to check the randomness in time series. They are produced by calculating the autocorrelations for data values at varying time lags."
},
{
"code": null,
"e": 5214,
"s": 5093,
"text": "Lag is the time difference. If the autocorrelations are very close to zero for all time lags, the time series is random."
},
{
"code": null,
"e": 5334,
"s": 5214,
"text": "If we observe one or more significantly non-zero autocorrelations, then we can conclude that time series is not random."
},
{
"code": null,
"e": 5408,
"s": 5334,
"text": "Let’s first create a random time series and see the autocorrelation plot."
},
{
"code": null,
"e": 5478,
"s": 5408,
"text": "noise = pd.Series(np.random.randn(250)*100)noise.plot(figsize=(12,6))"
},
{
"code": null,
"e": 5560,
"s": 5478,
"text": "This time series is clearly random. The autocorrelation plot of this time series:"
},
{
"code": null,
"e": 5662,
"s": 5560,
"text": "from pandas.plotting import autocorrelation_plotplt.figure(figsize=(12,6))autocorrelation_plot(noise)"
},
{
"code": null,
"e": 5726,
"s": 5662,
"text": "As expected, all autocorrelation values are very close to zero."
},
{
"code": null,
"e": 5822,
"s": 5726,
"text": "Let’s do an example of non-random time series. The plot below shows a very simple upward trend."
},
{
"code": null,
"e": 5894,
"s": 5822,
"text": "upward = pd.Series(np.arange(100))upward.plot(figsize=(10,6))plt.grid()"
},
{
"code": null,
"e": 5941,
"s": 5894,
"text": "The autocorrelation plot for this time series:"
},
{
"code": null,
"e": 5996,
"s": 5941,
"text": "plt.figure(figsize=(12,6))autocorrelation_plot(upward)"
},
{
"code": null,
"e": 6109,
"s": 5996,
"text": "This autocorrelation clearly indicates a non-random time series as there are many significantly non-zero values."
},
{
"code": null,
"e": 6425,
"s": 6109,
"text": "It is very easy to visually check the non-randomness of simple upward and downward trends. However, in real life data sets, we are likely to see highly complex time series. We may not able see the trends or seasonality in those series. In such cases, autocorrelation plots are very helpful for time series analysis."
},
{
"code": null,
"e": 6560,
"s": 6425,
"text": "Pandas provide two more plotting tools which are bootstap plot and RadViz. They can also be used in exploratory data analysis process."
}
]
|
How to markup postal address in HTML? | To markup postal address in HTML, use the <address> tag. The <address>...</address> tag is to add contact information. It can also be used to add contact information for the author of an article or document.
Just keep in mind too that each line should be followed by a <br> tag, as in address.
You can try to run the following code to add the postal address in HTML.
<!DOCTYPE html>
<html>
<head>
<title>HTML address tag</title>
</head>
<body>
<h1>Contact us</h1>
<address>
52nd Street<br>
New York,<br>
NY 10019<br>
USA
</address>
</body>
</html> | [
{
"code": null,
"e": 1270,
"s": 1062,
"text": "To markup postal address in HTML, use the <address> tag. The <address>...</address> tag is to add contact information. It can also be used to add contact information for the author of an article or document."
},
{
"code": null,
"e": 1356,
"s": 1270,
"text": "Just keep in mind too that each line should be followed by a <br> tag, as in address."
},
{
"code": null,
"e": 1429,
"s": 1356,
"text": "You can try to run the following code to add the postal address in HTML."
},
{
"code": null,
"e": 1683,
"s": 1429,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML address tag</title>\n </head>\n\n <body>\n <h1>Contact us</h1>\n <address>\n 52nd Street<br>\n New York,<br>\n NY 10019<br>\n USA\n </address>\n </body>\n</html>"
}
]
|
(Self-)Supervised Pre-training? Self-training? Which one to start with? | by KamWoh Ng | Towards Data Science | Recently, pre-training has been a hot topic in Computer Vision (and also NLP), especially one of the breakthroughs in NLP — BERT, which proposed a method to train an NLP model by using a “self-supervised” signal.
In short, we come up with an algorithm that can generate a “pseudo-label” itself (meaning a label that is true for a specific task), then we treat the learning task as a supervised learning task with the generated pseudo-label. It is commonly called “Pretext Task”. For example, BERT uses mask word prediction to train the model (we can then say it is a pre-trained model after it is trained), then fine-tune the model with the task we want (usually called “Downstream Task”), e.g. review comment classification. The mask word prediction is to randomly mask a word in the sentence, and ask the model to predict what is that word given the sentence.
As a result, we can obtain a very good performance NLP model, by training it with a huge amount of unlabelled training data i.e., millions of sentences from the Internet (e.g. ), which saves a lot of time for labeling data.
In NLP, we can easily obtain a sentence from the internet, as the sentence is discrete and usually legit (for example obtain a sentence from Wikipedia, it is uncommon that the sentence is erroneous and non-readable). Hence it is quite easy to define a pretext task in NLP. However, images are way more difficult as the signals are continuous, and pixels have a range of [0, 255], we as human are difficult to interpret a bunch of pixel values, and any shifting to the pixels will not be an issue to a human, but it will be completely different to a computer.
In this post, I will introduce what is a pre-trained model, downstream task, the current state of Self-Supervised Learning for Computer Vision, how to define a pretext task for the computer to learn meaningful and invariant features from images, and whether it is good to always apply pre-training, is there any alternative solution to pre-training. I assume readers have some basic understanding of CNN and Deep Learning.
Before talking about specific terms, let's look at the big picture of a deep learning project (specifically for computer vision project, but should apply to all others’ project)
from torchvision.models import alexnetmodel = alexnet(pretrained=True) # set pretrained=Truecustom_task_model = prepare_custom_model()dataset = load_dataset()dataloader = DataLoader(dataset)for epoch in range(epochs): for data, label in dataloader: # representation could be feature maps or vector representation = model(data) # compute specific outputs such as object detection outputs output = custom_task_model(representation) # compute specific task loss loss = criterion(output, label) loss.backward() # update model and/or custom_task_model optimizer.step()
For all almost open-source research projects, you will see the above pseudo-code. The common differences would be how to load the dataset, different model architecture, different tasks, and different loss functions (“criterion”).
As you have noticed from the above pseudo-code, the “representation” is the most important part for any specific tasks (e.g. classification task), there are a lot of names for it, e.g. “embedding”, “vector”, “feature”. It literally means that this vector of real values is the “representation” that describes the data, even though it is difficult to be interpreted by a human, but it is actually meaningful for a computer to understand the data. It is because we want the computer to classify the input data, but pixels of data are too complicated, hence we want to extract “features” from the pixels of data, that is, to find out what combination of pixels is actually able to describe the data. Hence, it is important to let the computer learn how to combine these pixels so that it can classify them.
Pre-trained models which are provided by torchvision.models were trained on ImageNet1000 through supervised learning (cross-entropy loss). The simplest way to obtain the pre-trained model is to set the keyword “pretrained=True” when you construct any models from this package (see the pseudo code above).
In the community of deep learning for computer vision, it is really common that we always begin with ImageNet pre-trained model, and fine-tune the model to a specific task with specific datasets. Because pre-trained model helps to save the time of training the model from scratch since the representation it has learned is already suitable (or easily to transfer) for a specific task such as Image Classification or Object Detection.
For example, the above figure is a deep visualization on a trained AlexNet. The feature maps (those with black background but with some white points) are the “activation” of some features, meaning that a specific channel in a Convolution layer has found how to combine the pixels to represent some meaningful contents, (e.g. the cat head). All pre-trained models are capable to do that (and it is a must! If not, it is a bad pre-trained model haha...), hence starting your project with a pre-trained model is definitely a good choice.
When research papers mention “downstream task” (which confused me when I was a beginner), it literally means what the pre-trained model can do with image classification, object detection, image segmentation, etc. All these tasks are called “downstream tasks”, which is actually a technical term that is used by most representation learning papers.
In short, we fine-tune the model to perform specific tasks with the pre-trained model weights as initialization. Because some domains (such as the medical field) are very difficult and expensive to obtain data, so it is important to initialize with the pre-trained model, and also it will reduce the training time if you have computation constraints.
As far as I know, SSL can be organized as handcrafted pretext tasks-based, contrastive learning-based, clustering learning-based. Note that some papers will mention self-supervised learning as unsupervised learning. Also, note that both generative models— AutoEncoder and GAN can also learn representations without labels, e.g. you can use the Encoder from the AE or the Discriminator from the GAN as the pre-trained model (both takes as input an image), but I did not list them down here because some of them are too specific on the tasks, hence I think it is not good enough to be a pre-trained model.
Some researchers propose to let the model learn to classify a human-designed task that does not need labeled data, but we can utilize the data to generate labels.
Context Prediction (predict location relationship)JigsawPredict RotationColorizationImage Inpainting (learn to fill up an empty space in an image)
To summarize, these tasks use algorithms to generate pseudo-labels, so that model can learn representation through supervised learning such as cross-entropy loss. For the details algorithm, you can read the paper which I have put a link in the list.
The term “contrastive” means to differentiate, hence contrastive learning means learning to compare between positive and negative samples.
SimCLRSimCLRv2MocoMocov2PIRL
These methods are sometimes called “instance discrimination” as well because they utilize the features of instances for learning. In short, the core concept is to maximize the dot product between the feature vectors which are similar and minimize the dot product between those of which are not similar. These methods have their own method to define similarity and dissimilarity. And most of them utilize “data augmentation”, that is, a positive pair is the same image with different kinds of augmentations, while a negative pair is just different images (with different kinds of augmentations as well).
These methods are the current trend of self-supervised learning because these papers claim that contrastive learning can learn features that are more invariant (e.g. the feature map of a cat head I shown earlier, the location of the cat head in the image doesn’t matter, it will activate as long as the cat head presents) as it can “compare” and find out what are the common features in the two augmented images.
I put nearest neighbor-based as clustering learning as I view every data point as a center and finding the nearest neighbor as a cluster.
DeepClusteringSeLASCANSwAV
These methods are easier to understand, I use DeepClustering for an explanation as I think it is simple. We first perform clustering on the features (the number of centroids is a hyperparameter), then using the predicted labels from the clustering result as pseudo-labels, then treat it as an image classification problem and learn with cross-entropy loss. Again, different methods have their own version of finding pseudo-labels.
I personally recommend clustering-based learning, as it is more intuitive, but I personally think that two of the big problems are how to perform online clustering efficiently and accurately (meaning no need to go through all the data, but only the batch itself) and how to define the number of centroids correctly. (Nevertheless, SwAV said, as long as the number of centroids is “enough”, the learning shouldn’t be a problem).
Well, the title is actually the same as a paper called “Rethinking Pre-training and Self-training”. This paper finds out that pre-training is not as good as self-training in some cases.
To summarize, a self-training method has common steps as below:
learn a (teacher) model with labeled data (often with strong augmentation)generate soft/hard pseudo labels for unlabeled data from the (teacher) modelretrain a (student) model with both labeled data and pseudo-labeled unlabeled data.repeats steps 1 2 and 3. (by initializing the teacher model with the student model)
learn a (teacher) model with labeled data (often with strong augmentation)
generate soft/hard pseudo labels for unlabeled data from the (teacher) model
retrain a (student) model with both labeled data and pseudo-labeled unlabeled data.
repeats steps 1 2 and 3. (by initializing the teacher model with the student model)
It is actually a semi-supervised learning method. The term “self” means that the model learns with some data first (and the model is initialized randomly), then using its own knowledge to classify new unseen data, and uses the highly confident prediction result as new data and learns with them. Hence, the term “self” means the model is teaching itself.
This paper said that although self-training is much slower than pre-training, it actually has many benefits such as able to learn more specific features for the specific task, works well even when pre-training fails and it works even well with more data. In the paper they demonstrate the benefit of self-training with object detection and semantic segmentation, it actually makes sense as the features from the pre-trained model were learned from classification task, but adapting it to localization task (i.e., object detection) might take time to adjust (or maybe not able to adjust accurately due to local minimum). While training from scratch will help as the features are tuned from random to the specific localization task, just that it takes more time for the training.
Nevertheless, I still think pre-training is good in practice because we can save a lot of time training the model, especially for fast demo or model deployment. But you can give self-training a try if you want to beat SOTA in your research field.
Hope this post can help you to understand more about the pre-training model, self-supervised learning methods, and also able to explore a new field that is called “self-training” (although it is not new to the community, it is new to me).
Auto-encoder-based can also consider as self-supervised learning, as it is reconstructing the input (the label is the input), but some papers said that auto-encoder (reconstructive based to be specific) will try to memorize every detail of the input, hence it is not “invariant” enough. It is good to have a discriminative feature, even if we lose information, as long as the information that is important to the main content in the image and we can use the information for the downstream task, then it is considered discriminative and invariant.
If you wish to know more about self-supervised learning, I recommend you to read these surveys, 1, 2, 3. You can also search in Google Scholar with the keyword “self-supervised learning survey”. There is also another paper called “How Useful is Self-Supervised Pretraining for Visual Tasks?”, explains how to self-supervised pretraining help in visual tasks, I recommend readers to read if you have interest in self-supervised learning. | [
{
"code": null,
"e": 385,
"s": 172,
"text": "Recently, pre-training has been a hot topic in Computer Vision (and also NLP), especially one of the breakthroughs in NLP — BERT, which proposed a method to train an NLP model by using a “self-supervised” signal."
},
{
"code": null,
"e": 1034,
"s": 385,
"text": "In short, we come up with an algorithm that can generate a “pseudo-label” itself (meaning a label that is true for a specific task), then we treat the learning task as a supervised learning task with the generated pseudo-label. It is commonly called “Pretext Task”. For example, BERT uses mask word prediction to train the model (we can then say it is a pre-trained model after it is trained), then fine-tune the model with the task we want (usually called “Downstream Task”), e.g. review comment classification. The mask word prediction is to randomly mask a word in the sentence, and ask the model to predict what is that word given the sentence."
},
{
"code": null,
"e": 1258,
"s": 1034,
"text": "As a result, we can obtain a very good performance NLP model, by training it with a huge amount of unlabelled training data i.e., millions of sentences from the Internet (e.g. ), which saves a lot of time for labeling data."
},
{
"code": null,
"e": 1817,
"s": 1258,
"text": "In NLP, we can easily obtain a sentence from the internet, as the sentence is discrete and usually legit (for example obtain a sentence from Wikipedia, it is uncommon that the sentence is erroneous and non-readable). Hence it is quite easy to define a pretext task in NLP. However, images are way more difficult as the signals are continuous, and pixels have a range of [0, 255], we as human are difficult to interpret a bunch of pixel values, and any shifting to the pixels will not be an issue to a human, but it will be completely different to a computer."
},
{
"code": null,
"e": 2240,
"s": 1817,
"text": "In this post, I will introduce what is a pre-trained model, downstream task, the current state of Self-Supervised Learning for Computer Vision, how to define a pretext task for the computer to learn meaningful and invariant features from images, and whether it is good to always apply pre-training, is there any alternative solution to pre-training. I assume readers have some basic understanding of CNN and Deep Learning."
},
{
"code": null,
"e": 2418,
"s": 2240,
"text": "Before talking about specific terms, let's look at the big picture of a deep learning project (specifically for computer vision project, but should apply to all others’ project)"
},
{
"code": null,
"e": 3013,
"s": 2418,
"text": "from torchvision.models import alexnetmodel = alexnet(pretrained=True) # set pretrained=Truecustom_task_model = prepare_custom_model()dataset = load_dataset()dataloader = DataLoader(dataset)for epoch in range(epochs): for data, label in dataloader: # representation could be feature maps or vector representation = model(data) # compute specific outputs such as object detection outputs output = custom_task_model(representation) # compute specific task loss loss = criterion(output, label) loss.backward() # update model and/or custom_task_model optimizer.step()"
},
{
"code": null,
"e": 3243,
"s": 3013,
"text": "For all almost open-source research projects, you will see the above pseudo-code. The common differences would be how to load the dataset, different model architecture, different tasks, and different loss functions (“criterion”)."
},
{
"code": null,
"e": 4047,
"s": 3243,
"text": "As you have noticed from the above pseudo-code, the “representation” is the most important part for any specific tasks (e.g. classification task), there are a lot of names for it, e.g. “embedding”, “vector”, “feature”. It literally means that this vector of real values is the “representation” that describes the data, even though it is difficult to be interpreted by a human, but it is actually meaningful for a computer to understand the data. It is because we want the computer to classify the input data, but pixels of data are too complicated, hence we want to extract “features” from the pixels of data, that is, to find out what combination of pixels is actually able to describe the data. Hence, it is important to let the computer learn how to combine these pixels so that it can classify them."
},
{
"code": null,
"e": 4352,
"s": 4047,
"text": "Pre-trained models which are provided by torchvision.models were trained on ImageNet1000 through supervised learning (cross-entropy loss). The simplest way to obtain the pre-trained model is to set the keyword “pretrained=True” when you construct any models from this package (see the pseudo code above)."
},
{
"code": null,
"e": 4786,
"s": 4352,
"text": "In the community of deep learning for computer vision, it is really common that we always begin with ImageNet pre-trained model, and fine-tune the model to a specific task with specific datasets. Because pre-trained model helps to save the time of training the model from scratch since the representation it has learned is already suitable (or easily to transfer) for a specific task such as Image Classification or Object Detection."
},
{
"code": null,
"e": 5321,
"s": 4786,
"text": "For example, the above figure is a deep visualization on a trained AlexNet. The feature maps (those with black background but with some white points) are the “activation” of some features, meaning that a specific channel in a Convolution layer has found how to combine the pixels to represent some meaningful contents, (e.g. the cat head). All pre-trained models are capable to do that (and it is a must! If not, it is a bad pre-trained model haha...), hence starting your project with a pre-trained model is definitely a good choice."
},
{
"code": null,
"e": 5669,
"s": 5321,
"text": "When research papers mention “downstream task” (which confused me when I was a beginner), it literally means what the pre-trained model can do with image classification, object detection, image segmentation, etc. All these tasks are called “downstream tasks”, which is actually a technical term that is used by most representation learning papers."
},
{
"code": null,
"e": 6020,
"s": 5669,
"text": "In short, we fine-tune the model to perform specific tasks with the pre-trained model weights as initialization. Because some domains (such as the medical field) are very difficult and expensive to obtain data, so it is important to initialize with the pre-trained model, and also it will reduce the training time if you have computation constraints."
},
{
"code": null,
"e": 6624,
"s": 6020,
"text": "As far as I know, SSL can be organized as handcrafted pretext tasks-based, contrastive learning-based, clustering learning-based. Note that some papers will mention self-supervised learning as unsupervised learning. Also, note that both generative models— AutoEncoder and GAN can also learn representations without labels, e.g. you can use the Encoder from the AE or the Discriminator from the GAN as the pre-trained model (both takes as input an image), but I did not list them down here because some of them are too specific on the tasks, hence I think it is not good enough to be a pre-trained model."
},
{
"code": null,
"e": 6787,
"s": 6624,
"text": "Some researchers propose to let the model learn to classify a human-designed task that does not need labeled data, but we can utilize the data to generate labels."
},
{
"code": null,
"e": 6934,
"s": 6787,
"text": "Context Prediction (predict location relationship)JigsawPredict RotationColorizationImage Inpainting (learn to fill up an empty space in an image)"
},
{
"code": null,
"e": 7184,
"s": 6934,
"text": "To summarize, these tasks use algorithms to generate pseudo-labels, so that model can learn representation through supervised learning such as cross-entropy loss. For the details algorithm, you can read the paper which I have put a link in the list."
},
{
"code": null,
"e": 7323,
"s": 7184,
"text": "The term “contrastive” means to differentiate, hence contrastive learning means learning to compare between positive and negative samples."
},
{
"code": null,
"e": 7352,
"s": 7323,
"text": "SimCLRSimCLRv2MocoMocov2PIRL"
},
{
"code": null,
"e": 7955,
"s": 7352,
"text": "These methods are sometimes called “instance discrimination” as well because they utilize the features of instances for learning. In short, the core concept is to maximize the dot product between the feature vectors which are similar and minimize the dot product between those of which are not similar. These methods have their own method to define similarity and dissimilarity. And most of them utilize “data augmentation”, that is, a positive pair is the same image with different kinds of augmentations, while a negative pair is just different images (with different kinds of augmentations as well)."
},
{
"code": null,
"e": 8368,
"s": 7955,
"text": "These methods are the current trend of self-supervised learning because these papers claim that contrastive learning can learn features that are more invariant (e.g. the feature map of a cat head I shown earlier, the location of the cat head in the image doesn’t matter, it will activate as long as the cat head presents) as it can “compare” and find out what are the common features in the two augmented images."
},
{
"code": null,
"e": 8506,
"s": 8368,
"text": "I put nearest neighbor-based as clustering learning as I view every data point as a center and finding the nearest neighbor as a cluster."
},
{
"code": null,
"e": 8533,
"s": 8506,
"text": "DeepClusteringSeLASCANSwAV"
},
{
"code": null,
"e": 8964,
"s": 8533,
"text": "These methods are easier to understand, I use DeepClustering for an explanation as I think it is simple. We first perform clustering on the features (the number of centroids is a hyperparameter), then using the predicted labels from the clustering result as pseudo-labels, then treat it as an image classification problem and learn with cross-entropy loss. Again, different methods have their own version of finding pseudo-labels."
},
{
"code": null,
"e": 9392,
"s": 8964,
"text": "I personally recommend clustering-based learning, as it is more intuitive, but I personally think that two of the big problems are how to perform online clustering efficiently and accurately (meaning no need to go through all the data, but only the batch itself) and how to define the number of centroids correctly. (Nevertheless, SwAV said, as long as the number of centroids is “enough”, the learning shouldn’t be a problem)."
},
{
"code": null,
"e": 9578,
"s": 9392,
"text": "Well, the title is actually the same as a paper called “Rethinking Pre-training and Self-training”. This paper finds out that pre-training is not as good as self-training in some cases."
},
{
"code": null,
"e": 9642,
"s": 9578,
"text": "To summarize, a self-training method has common steps as below:"
},
{
"code": null,
"e": 9959,
"s": 9642,
"text": "learn a (teacher) model with labeled data (often with strong augmentation)generate soft/hard pseudo labels for unlabeled data from the (teacher) modelretrain a (student) model with both labeled data and pseudo-labeled unlabeled data.repeats steps 1 2 and 3. (by initializing the teacher model with the student model)"
},
{
"code": null,
"e": 10034,
"s": 9959,
"text": "learn a (teacher) model with labeled data (often with strong augmentation)"
},
{
"code": null,
"e": 10111,
"s": 10034,
"text": "generate soft/hard pseudo labels for unlabeled data from the (teacher) model"
},
{
"code": null,
"e": 10195,
"s": 10111,
"text": "retrain a (student) model with both labeled data and pseudo-labeled unlabeled data."
},
{
"code": null,
"e": 10279,
"s": 10195,
"text": "repeats steps 1 2 and 3. (by initializing the teacher model with the student model)"
},
{
"code": null,
"e": 10634,
"s": 10279,
"text": "It is actually a semi-supervised learning method. The term “self” means that the model learns with some data first (and the model is initialized randomly), then using its own knowledge to classify new unseen data, and uses the highly confident prediction result as new data and learns with them. Hence, the term “self” means the model is teaching itself."
},
{
"code": null,
"e": 11412,
"s": 10634,
"text": "This paper said that although self-training is much slower than pre-training, it actually has many benefits such as able to learn more specific features for the specific task, works well even when pre-training fails and it works even well with more data. In the paper they demonstrate the benefit of self-training with object detection and semantic segmentation, it actually makes sense as the features from the pre-trained model were learned from classification task, but adapting it to localization task (i.e., object detection) might take time to adjust (or maybe not able to adjust accurately due to local minimum). While training from scratch will help as the features are tuned from random to the specific localization task, just that it takes more time for the training."
},
{
"code": null,
"e": 11659,
"s": 11412,
"text": "Nevertheless, I still think pre-training is good in practice because we can save a lot of time training the model, especially for fast demo or model deployment. But you can give self-training a try if you want to beat SOTA in your research field."
},
{
"code": null,
"e": 11898,
"s": 11659,
"text": "Hope this post can help you to understand more about the pre-training model, self-supervised learning methods, and also able to explore a new field that is called “self-training” (although it is not new to the community, it is new to me)."
},
{
"code": null,
"e": 12445,
"s": 11898,
"text": "Auto-encoder-based can also consider as self-supervised learning, as it is reconstructing the input (the label is the input), but some papers said that auto-encoder (reconstructive based to be specific) will try to memorize every detail of the input, hence it is not “invariant” enough. It is good to have a discriminative feature, even if we lose information, as long as the information that is important to the main content in the image and we can use the information for the downstream task, then it is considered discriminative and invariant."
}
]
|
How to add an audio player to an HTML webpage? | The HTML <audio> element is used to add audio to web page. To add an audio player, add the controls attribute.
The following three audio formats are supported in HTML − MP3, Wav, and Ogg.
You can try to run the following code to add an audio player to an HTML web page
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML audio Tag</title>
</head>
<body>
<p>Click on Play button...</p>
<p>(Song: Kalimba which is provided as a Sample Music in Windows)</p>
<audio controls>
<source src = "/html/Kalimba.mp3" type = "audio/mpeg">
</audio>
</body>
</html> | [
{
"code": null,
"e": 1173,
"s": 1062,
"text": "The HTML <audio> element is used to add audio to web page. To add an audio player, add the controls attribute."
},
{
"code": null,
"e": 1250,
"s": 1173,
"text": "The following three audio formats are supported in HTML − MP3, Wav, and Ogg."
},
{
"code": null,
"e": 1331,
"s": 1250,
"text": "You can try to run the following code to add an audio player to an HTML web page"
},
{
"code": null,
"e": 1341,
"s": 1331,
"text": "Live Demo"
},
{
"code": null,
"e": 1665,
"s": 1341,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML audio Tag</title>\n </head>\n <body>\n <p>Click on Play button...</p>\n <p>(Song: Kalimba which is provided as a Sample Music in Windows)</p>\n <audio controls>\n <source src = \"/html/Kalimba.mp3\" type = \"audio/mpeg\">\n </audio>\n </body>\n</html>"
}
]
|
Check if the given string is shuffled substring of another string - GeeksforGeeks | 20 Jan, 2022
Given strings str1 and str2. The task is to find if str1 is a substring in the shuffled form of str2 or not. Print “YES” if str1 is a substring in shuffled form of str2 else print “NO”.
Example
Input: str1 = “onetwofour”, str2 = “hellofourtwooneworld” Output: YES Explanation: str1 is substring in shuffled form of str2 as str2 = “hello” + “fourtwoone” + “world” str2 = “hello” + str1 + “world”, where str1 = “fourtwoone” (shuffled form) Hence, str1 is a substring of str2 in shuffled form.
Input: str1 = “roseyellow”, str2 = “yellow” Output: NO Explanation: As the length of str1 is greater than str2. Hence, str1 is not a substring of str2.
Approach: Let n = length of str1, m = length of str2.
If n > m, then string str1 can never be the substring of str2.
Else sort the string str1.
Traverse string str2 Put all the characters of str2 of length n in another string str.Sort the string str and Compare str and str1.If str = str1, then string str1 is a shuffled substring of string str2.else repeat the above process till ith index of str2 such that (i +n – 1 > m)(as after this index the length of remaining string str2 will be less than str1.If str is not equals to str1 in above steps, then string str1 can never be substring of str2.
Put all the characters of str2 of length n in another string str.Sort the string str and Compare str and str1.If str = str1, then string str1 is a shuffled substring of string str2.else repeat the above process till ith index of str2 such that (i +n – 1 > m)(as after this index the length of remaining string str2 will be less than str1.If str is not equals to str1 in above steps, then string str1 can never be substring of str2.
Put all the characters of str2 of length n in another string str.
Sort the string str and Compare str and str1.
If str = str1, then string str1 is a shuffled substring of string str2.
else repeat the above process till ith index of str2 such that (i +n – 1 > m)(as after this index the length of remaining string str2 will be less than str1.
If str is not equals to str1 in above steps, then string str1 can never be substring of str2.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if string// str1 is substring of str2 or not.#include <bits/stdc++.h>using namespace std; // Function two check string A// is shuffled substring of B// or notbool isShuffledSubstring(string A, string B){ int n = A.length(); int m = B.length(); // Return false if length of // string A is greater than // length of string B if (n > m) { return false; } else { // Sort string A sort(A.begin(), A.end()); // Traverse string B for (int i = 0; i < m; i++) { // Return false if (i+n-1 >= m) // doesn't satisfy if (i + n - 1 >= m) return false; // Initialise the new string string str = ""; // Copy the characters of // string B in str till // length n for (int j = 0; j < n; j++) str.push_back(B[i + j]); // Sort the string str sort(str.begin(), str.end()); // Return true if sorted // string of "str" & sorted // string of "A" are equal if (str == A) return true; } }} // Driver Codeint main(){ // Input str1 and str2 string str1 = "geekforgeeks"; string str2 = "ekegorfkeegsgeek"; // Function return true if // str1 is shuffled substring // of str2 bool a = isShuffledSubstring(str1, str2); // If str1 is substring of str2 // print "YES" else print "NO" if (a) cout << "YES"; else cout << "NO"; cout << endl; return 0;}
// Java program to check if String// str1 is subString of str2 or not.import java.util.*; class GFG{ // Function two check String A// is shuffled subString of B// or notstatic boolean isShuffledSubString(String A, String B){ int n = A.length(); int m = B.length(); // Return false if length of // String A is greater than // length of String B if (n > m) { return false; } else { // Sort String A A = sort(A); // Traverse String B for (int i = 0; i < m; i++) { // Return false if (i + n - 1 >= m) // doesn't satisfy if (i + n - 1 >= m) return false; // Initialise the new String String str = ""; // Copy the characters of // String B in str till // length n for (int j = 0; j < n; j++) str += B.charAt(i + j); // Sort the String str str = sort(str); // Return true if sorted // String of "str" & sorted // String of "A" are equal if (str.equals(A)) return true; } } return false;} // Method to sort a string alphabeticallystatic String sort(String inputString){ // convert input string to char array char tempArray[] = inputString.toCharArray(); // sort tempArray Arrays.sort(tempArray); // return new sorted string return String.valueOf(tempArray);} // Driver Codepublic static void main(String[] args){ // Input str1 and str2 String str1 = "geekforgeeks"; String str2 = "ekegorfkeegsgeek"; // Function return true if // str1 is shuffled subString // of str2 boolean a = isShuffledSubString(str1, str2); // If str1 is subString of str2 // print "YES" else print "NO" if (a) System.out.print("YES"); else System.out.print("NO"); System.out.println();}} // This code is contributed by PrinciRaj1992
# Python3 program to check if string# str1 is subof str2 or not. # Function two check A# is shuffled subof B# or notdef isShuffledSubstring(A, B): n = len(A) m = len(B) # Return false if length of # A is greater than # length of B if (n > m): return False else: # Sort A A = sorted(A) # Traverse B for i in range(m): # Return false if (i+n-1 >= m) # doesn't satisfy if (i + n - 1 >= m): return False # Initialise the new string Str = "" # Copy the characters of # B in str till # length n for j in range(n): Str += (B[i + j]) # Sort the str Str = sorted(Str) # Return true if sorted # of "str" & sorted # of "A" are equal if (Str == A): return True # Driver Codeif __name__ == '__main__': # Input str1 and str2 Str1 = "geekforgeeks" Str2 = "ekegorfkeegsgeek" # Function return true if # str1 is shuffled substring # of str2 a = isShuffledSubstring(Str1, Str2) # If str1 is subof str2 # print "YES" else print "NO" if (a): print("YES") else: print("NO") # This code is contributed by mohit kumar 29
// C# program to check if String// str1 is subString of str2 or not.using System; public class GFG{ // Function two check String A// is shuffled subString of B// or notstatic bool isShuffledSubString(String A, String B){ int n = A.Length; int m = B.Length; // Return false if length of // String A is greater than // length of String B if (n > m) { return false; } else { // Sort String A A = sort(A); // Traverse String B for (int i = 0; i < m; i++) { // Return false if (i + n - 1 >= m) // doesn't satisfy if (i + n - 1 >= m) return false; // Initialise the new String String str = ""; // Copy the characters of // String B in str till // length n for (int j = 0; j < n; j++) str += B[i + j]; // Sort the String str str = sort(str); // Return true if sorted // String of "str" & sorted // String of "A" are equal if (str.Equals(A)) return true; } } return false;} // Method to sort a string alphabeticallystatic String sort(String inputString){ // convert input string to char array char []tempArray = inputString.ToCharArray(); // sort tempArray Array.Sort(tempArray); // return new sorted string return String.Join("",tempArray);} // Driver Codepublic static void Main(String[] args){ // Input str1 and str2 String str1 = "geekforgeeks"; String str2 = "ekegorfkeegsgeek"; // Function return true if // str1 is shuffled subString // of str2 bool a = isShuffledSubString(str1, str2); // If str1 is subString of str2 // print "YES" else print "NO" if (a) Console.Write("YES"); else Console.Write("NO"); Console.WriteLine();}} // This code is contributed by PrinciRaj1992
<script> // Javascript program to check if string// str1 is substring of str2 or not. // Function two check string A// is shuffled substring of B// or notfunction isShuffledSubstring(A, B){ var n = A.length; var m = B.length; // Return false if length of // string A is greater than // length of string B if (n > m) { return false; } else { // Sort string A A = A.split('').sort().join(''); // Traverse string B for (var i = 0; i < m; i++) { // Return false if (i+n-1 >= m) // doesn't satisfy if (i + n - 1 >= m) return false; // Initialise the new string var str = []; // Copy the characters of // string B in str till // length n for (var j = 0; j < n; j++) str.push(B[i + j]); // Sort the string str str = str.sort() // Return true if sorted // string of "str" & sorted // string of "A" are equal if (str.join('') == A) return true; } }} // Driver Code// Input str1 and str2var str1 = "geekforgeeks";var str2 = "ekegorfkeegsgeek";// Function return true if// str1 is shuffled substring// of str2var a = isShuffledSubstring(str1, str2);// If str1 is substring of str2// print "YES" else print "NO"if (a) document.write( "YES");else document.write( "NO");document.write("<br>"); </script>
YES
Time Complexity: O(m*n*log(n)), where n = length of string str1 and m = length of string str2 Auxiliary Space: O(n)
Efficient Solution: This problem is a simpler version of Anagram Search. It can be solved in linear time using character frequency counting.We can achieve O(n) time complexity under the assumption that alphabet size is fixed which is typically true as we have maximum of 256 possible characters in ASCII. The idea is to use two count arrays:
1) The first count array stores frequencies of characters in a pattern. 2) The second count array stores frequencies of characters in the current window of text.The important thing to note is, time complexity to compare two counted arrays is O(1) as the number of elements in them is fixed (independent of pattern and text sizes). The following are steps of this algorithm. 1) Store counts of frequencies of pattern in first count array countP[]. Also, store counts of frequencies of characters in the first window of text in array countTW[].2) Now run a loop from i = M to N-1. Do following in loop. .....a) If the two count arrays are identical, we found an occurrence. .....b) Increment count of current character of text in countTW[] .....c) Decrement count of the first character in the previous window in countWT[]3) The last window is not checked by the above loop, so explicitly check it.
The following is the implementation of the above algorithm.
C++
Java
Python3
C#
Javascript
#include<iostream>#include<cstring>#define MAX 256using namespace std; // This function returns true if contents of arr1[] and arr2[]// are same, otherwise false.bool compare(char arr1[], char arr2[]){ for (int i=0; i<MAX; i++) if (arr1[i] != arr2[i]) return false; return true;} // This function search for all permutations of pat[] in txt[]bool search(char *pat, char *txt){ int M = strlen(pat), N = strlen(txt); // countP[]: Store count of all characters of pattern // countTW[]: Store count of current window of text int countP[MAX] = {0}, countTW[MAX] = {0}; for (int i = 0; i < M; i++) { countP[pat[i]]++; countTW[txt[i]]++; } // Traverse through remaining characters of pattern for (int i = M; i < N; i++) { // Compare counts of current window of text with // counts of pattern[] if (compare(countP, countTW)) return true; // Add current character to current window (countTW[txt[i]])++; // Remove the first character of previous window countTW[txt[i-M]]--; } // Check for the last window in text if (compare(countP, countTW)) return true; return false;} /* Driver program to test above function */int main(){ char txt[] = "BACDGABCDA"; char pat[] = "ABCD"; if (search(pat, txt)) cout << "Yes"; else cout << "No"; return 0;}
import java.util.*; class GFG{ // This function returns true if// contents of arr1[] and arr2[]// are same, otherwise false.static boolean compare(int []arr1, int []arr2){ for(int i = 0; i < 256; i++) if (arr1[i] != arr2[i]) return false; return true;} // This function search for all// permutations of pat[] in txt[]static boolean search(String pat, String txt){ int M = pat.length(); int N = txt.length(); // countP[]: Store count of all // characters of pattern // countTW[]: Store count of // current window of text int []countP = new int [256]; int []countTW = new int [256]; for(int i = 0; i < 256; i++) { countP[i] = 0; countTW[i] = 0; } for(int i = 0; i < M; i++) { (countP[pat.charAt(i)])++; (countTW[txt.charAt(i)])++; } // Traverse through remaining // characters of pattern for(int i = M; i < N; i++) { // Compare counts of current // window of text with // counts of pattern[] if (compare(countP, countTW)) return true; // Add current character to // current window (countTW[txt.charAt(i)])++; // Remove the first character // of previous window countTW[txt.charAt(i - M)]--; } // Check for the last window in text if (compare(countP, countTW)) return true; return false;} // Driver codepublic static void main(String[] args){ String txt = "BACDGABCDA"; String pat = "ABCD"; if (search(pat, txt)) System.out.println("Yes"); else System.out.println("NO");}} // This code is contributed by Stream_Cipher
MAX = 256 # This function returns true if contents# of arr1[] and arr2[] are same,# otherwise false.def compare(arr1, arr2): global MAX for i in range(MAX): if (arr1[i] != arr2[i]): return False return True # This function search for all permutations# of pat[] in txt[]def search(pat, txt): M = len(pat) N = len(txt) # countP[]: Store count of all characters # of pattern # countTW[]: Store count of current window # of text countP = [0 for i in range(MAX)] countTW = [0 for i in range(MAX)] for i in range(M): countP[ord(pat[i])] += 1 countTW[ord(txt[i])] += 1 # Traverse through remaining # characters of pattern for i in range(M, N): # Compare counts of current window # of text with counts of pattern[] if (compare(countP, countTW)): return True # Add current character # to current window countTW[ord(txt[i])] += 1 # Remove the first character # of previous window countTW[ord(txt[i - M])] -= 1 # Check for the last window in text if(compare(countP, countTW)): return True return False # Driver codetxt = "BACDGABCDA"pat = "ABCD" if (search(pat, txt)): print("Yes")else: print("No") # This code is contributed by avanitrachhadiya2155
using System.Collections.Generic;using System; class GFG{ // This function returns true if// contents of arr1[] and arr2[]// are same, otherwise false.static bool compare(int []arr1, int []arr2){ for(int i = 0; i < 256; i++) if (arr1[i] != arr2[i]) return false; return true;} // This function search for all// permutations of pat[] in txt[]static bool search(String pat, String txt){ int M = pat.Length; int N = txt.Length; // countP[]: Store count of all // characters of pattern // countTW[]: Store count of // current window of text int []countP = new int [256]; int []countTW = new int [256]; for(int i = 0; i < 256; i++) { countP[i] = 0; countTW[i] = 0; } for(int i = 0; i < M; i++) { (countP[pat[i]])++; (countTW[txt[i]])++; } // Traverse through remaining // characters of pattern for(int i = M; i < N; i++) { // Compare counts of current // window of text with // counts of pattern[] if (compare(countP, countTW)) return true; // Add current character to // current window (countTW[txt[i]])++; // Remove the first character // of previous window countTW[txt[i - M]]--; } // Check for the last window in text if (compare(countP, countTW)) return true; return false;} // Driver codepublic static void Main(){ string txt = "BACDGABCDA"; string pat = "ABCD"; if (search(pat, txt)) Console.WriteLine("Yes"); else Console.WriteLine("NO");}} // This code is contributed by Stream_Cipher
<script> // This function returns true if// contents of arr1[] and arr2[]// are same, otherwise false.function compare(arr1,arr2){ for(let i = 0; i < 256; i++) if (arr1[i] != arr2[i]) return false; return true;} // This function search for all// permutations of pat[] in txt[]function search(pat,txt){ let M = pat.length; let N = txt.length; // countP[]: Store count of all // characters of pattern // countTW[]: Store count of // current window of text let countP = new Array(256); let countTW = new Array(256); for(let i = 0; i < 256; i++) { countP[i] = 0; countTW[i] = 0; } for(let i = 0; i < 256; i++) { countP[i] = 0; countTW[i] = 0; } for(let i = 0; i < M; i++) { (countP[pat[i].charCodeAt(0)])++; (countTW[txt[i].charCodeAt(0)])++; } // Traverse through remaining // characters of pattern for(let i = M; i < N; i++) { // Compare counts of current // window of text with // counts of pattern[] if (compare(countP, countTW)) return true; // Add current character to // current window (countTW[txt[i].charCodeAt(0)])++; // Remove the first character // of previous window countTW[txt[i - M].charCodeAt(0)]--; } // Check for the last window in text if (compare(countP, countTW)) return true; return false;} // Driver codelet txt = "BACDGABCDA";let pat = "ABCD"; if (search(pat, txt)) document.write("Yes");else document.write("NO"); // This code is contributed by ab2127</script>
Yes
princiraj1992
mohit kumar 29
hawkanubhav
Stream_Cipher
avanitrachhadiya2155
noob2000
anikaseth98
ab2127
amansidd17861
abhishek2x
substring
Competitive Programming
Pattern Searching
Sorting
Strings
Strings
Sorting
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Formatted output in Java
Algorithm Library | C++ Magicians STL Algorithm
Use of FLAG in programming
Breadth First Traversal ( BFS ) on a 2D array
Maximum LCM among all pairs (i, j) from the given Array
Check if an URL is valid or not using Regular Expression
Wildcard Pattern Matching
Check if a string contains uppercase, lowercase, special characters and numeric values
Search a Word in a 2D Grid of characters
How to check if string contains only digits in Java | [
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 25563,
"s": 25376,
"text": "Given strings str1 and str2. The task is to find if str1 is a substring in the shuffled form of str2 or not. Print “YES” if str1 is a substring in shuffled form of str2 else print “NO”. "
},
{
"code": null,
"e": 25572,
"s": 25563,
"text": "Example "
},
{
"code": null,
"e": 25869,
"s": 25572,
"text": "Input: str1 = “onetwofour”, str2 = “hellofourtwooneworld” Output: YES Explanation: str1 is substring in shuffled form of str2 as str2 = “hello” + “fourtwoone” + “world” str2 = “hello” + str1 + “world”, where str1 = “fourtwoone” (shuffled form) Hence, str1 is a substring of str2 in shuffled form."
},
{
"code": null,
"e": 26021,
"s": 25869,
"text": "Input: str1 = “roseyellow”, str2 = “yellow” Output: NO Explanation: As the length of str1 is greater than str2. Hence, str1 is not a substring of str2."
},
{
"code": null,
"e": 26076,
"s": 26021,
"text": "Approach: Let n = length of str1, m = length of str2. "
},
{
"code": null,
"e": 26139,
"s": 26076,
"text": "If n > m, then string str1 can never be the substring of str2."
},
{
"code": null,
"e": 26166,
"s": 26139,
"text": "Else sort the string str1."
},
{
"code": null,
"e": 26619,
"s": 26166,
"text": "Traverse string str2 Put all the characters of str2 of length n in another string str.Sort the string str and Compare str and str1.If str = str1, then string str1 is a shuffled substring of string str2.else repeat the above process till ith index of str2 such that (i +n – 1 > m)(as after this index the length of remaining string str2 will be less than str1.If str is not equals to str1 in above steps, then string str1 can never be substring of str2."
},
{
"code": null,
"e": 27051,
"s": 26619,
"text": "Put all the characters of str2 of length n in another string str.Sort the string str and Compare str and str1.If str = str1, then string str1 is a shuffled substring of string str2.else repeat the above process till ith index of str2 such that (i +n – 1 > m)(as after this index the length of remaining string str2 will be less than str1.If str is not equals to str1 in above steps, then string str1 can never be substring of str2."
},
{
"code": null,
"e": 27117,
"s": 27051,
"text": "Put all the characters of str2 of length n in another string str."
},
{
"code": null,
"e": 27163,
"s": 27117,
"text": "Sort the string str and Compare str and str1."
},
{
"code": null,
"e": 27235,
"s": 27163,
"text": "If str = str1, then string str1 is a shuffled substring of string str2."
},
{
"code": null,
"e": 27393,
"s": 27235,
"text": "else repeat the above process till ith index of str2 such that (i +n – 1 > m)(as after this index the length of remaining string str2 will be less than str1."
},
{
"code": null,
"e": 27487,
"s": 27393,
"text": "If str is not equals to str1 in above steps, then string str1 can never be substring of str2."
},
{
"code": null,
"e": 27539,
"s": 27487,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27543,
"s": 27539,
"text": "C++"
},
{
"code": null,
"e": 27548,
"s": 27543,
"text": "Java"
},
{
"code": null,
"e": 27556,
"s": 27548,
"text": "Python3"
},
{
"code": null,
"e": 27559,
"s": 27556,
"text": "C#"
},
{
"code": null,
"e": 27570,
"s": 27559,
"text": "Javascript"
},
{
"code": "// C++ program to check if string// str1 is substring of str2 or not.#include <bits/stdc++.h>using namespace std; // Function two check string A// is shuffled substring of B// or notbool isShuffledSubstring(string A, string B){ int n = A.length(); int m = B.length(); // Return false if length of // string A is greater than // length of string B if (n > m) { return false; } else { // Sort string A sort(A.begin(), A.end()); // Traverse string B for (int i = 0; i < m; i++) { // Return false if (i+n-1 >= m) // doesn't satisfy if (i + n - 1 >= m) return false; // Initialise the new string string str = \"\"; // Copy the characters of // string B in str till // length n for (int j = 0; j < n; j++) str.push_back(B[i + j]); // Sort the string str sort(str.begin(), str.end()); // Return true if sorted // string of \"str\" & sorted // string of \"A\" are equal if (str == A) return true; } }} // Driver Codeint main(){ // Input str1 and str2 string str1 = \"geekforgeeks\"; string str2 = \"ekegorfkeegsgeek\"; // Function return true if // str1 is shuffled substring // of str2 bool a = isShuffledSubstring(str1, str2); // If str1 is substring of str2 // print \"YES\" else print \"NO\" if (a) cout << \"YES\"; else cout << \"NO\"; cout << endl; return 0;}",
"e": 29153,
"s": 27570,
"text": null
},
{
"code": "// Java program to check if String// str1 is subString of str2 or not.import java.util.*; class GFG{ // Function two check String A// is shuffled subString of B// or notstatic boolean isShuffledSubString(String A, String B){ int n = A.length(); int m = B.length(); // Return false if length of // String A is greater than // length of String B if (n > m) { return false; } else { // Sort String A A = sort(A); // Traverse String B for (int i = 0; i < m; i++) { // Return false if (i + n - 1 >= m) // doesn't satisfy if (i + n - 1 >= m) return false; // Initialise the new String String str = \"\"; // Copy the characters of // String B in str till // length n for (int j = 0; j < n; j++) str += B.charAt(i + j); // Sort the String str str = sort(str); // Return true if sorted // String of \"str\" & sorted // String of \"A\" are equal if (str.equals(A)) return true; } } return false;} // Method to sort a string alphabeticallystatic String sort(String inputString){ // convert input string to char array char tempArray[] = inputString.toCharArray(); // sort tempArray Arrays.sort(tempArray); // return new sorted string return String.valueOf(tempArray);} // Driver Codepublic static void main(String[] args){ // Input str1 and str2 String str1 = \"geekforgeeks\"; String str2 = \"ekegorfkeegsgeek\"; // Function return true if // str1 is shuffled subString // of str2 boolean a = isShuffledSubString(str1, str2); // If str1 is subString of str2 // print \"YES\" else print \"NO\" if (a) System.out.print(\"YES\"); else System.out.print(\"NO\"); System.out.println();}} // This code is contributed by PrinciRaj1992",
"e": 31134,
"s": 29153,
"text": null
},
{
"code": "# Python3 program to check if string# str1 is subof str2 or not. # Function two check A# is shuffled subof B# or notdef isShuffledSubstring(A, B): n = len(A) m = len(B) # Return false if length of # A is greater than # length of B if (n > m): return False else: # Sort A A = sorted(A) # Traverse B for i in range(m): # Return false if (i+n-1 >= m) # doesn't satisfy if (i + n - 1 >= m): return False # Initialise the new string Str = \"\" # Copy the characters of # B in str till # length n for j in range(n): Str += (B[i + j]) # Sort the str Str = sorted(Str) # Return true if sorted # of \"str\" & sorted # of \"A\" are equal if (Str == A): return True # Driver Codeif __name__ == '__main__': # Input str1 and str2 Str1 = \"geekforgeeks\" Str2 = \"ekegorfkeegsgeek\" # Function return true if # str1 is shuffled substring # of str2 a = isShuffledSubstring(Str1, Str2) # If str1 is subof str2 # print \"YES\" else print \"NO\" if (a): print(\"YES\") else: print(\"NO\") # This code is contributed by mohit kumar 29",
"e": 32460,
"s": 31134,
"text": null
},
{
"code": "// C# program to check if String// str1 is subString of str2 or not.using System; public class GFG{ // Function two check String A// is shuffled subString of B// or notstatic bool isShuffledSubString(String A, String B){ int n = A.Length; int m = B.Length; // Return false if length of // String A is greater than // length of String B if (n > m) { return false; } else { // Sort String A A = sort(A); // Traverse String B for (int i = 0; i < m; i++) { // Return false if (i + n - 1 >= m) // doesn't satisfy if (i + n - 1 >= m) return false; // Initialise the new String String str = \"\"; // Copy the characters of // String B in str till // length n for (int j = 0; j < n; j++) str += B[i + j]; // Sort the String str str = sort(str); // Return true if sorted // String of \"str\" & sorted // String of \"A\" are equal if (str.Equals(A)) return true; } } return false;} // Method to sort a string alphabeticallystatic String sort(String inputString){ // convert input string to char array char []tempArray = inputString.ToCharArray(); // sort tempArray Array.Sort(tempArray); // return new sorted string return String.Join(\"\",tempArray);} // Driver Codepublic static void Main(String[] args){ // Input str1 and str2 String str1 = \"geekforgeeks\"; String str2 = \"ekegorfkeegsgeek\"; // Function return true if // str1 is shuffled subString // of str2 bool a = isShuffledSubString(str1, str2); // If str1 is subString of str2 // print \"YES\" else print \"NO\" if (a) Console.Write(\"YES\"); else Console.Write(\"NO\"); Console.WriteLine();}} // This code is contributed by PrinciRaj1992",
"e": 34430,
"s": 32460,
"text": null
},
{
"code": "<script> // Javascript program to check if string// str1 is substring of str2 or not. // Function two check string A// is shuffled substring of B// or notfunction isShuffledSubstring(A, B){ var n = A.length; var m = B.length; // Return false if length of // string A is greater than // length of string B if (n > m) { return false; } else { // Sort string A A = A.split('').sort().join(''); // Traverse string B for (var i = 0; i < m; i++) { // Return false if (i+n-1 >= m) // doesn't satisfy if (i + n - 1 >= m) return false; // Initialise the new string var str = []; // Copy the characters of // string B in str till // length n for (var j = 0; j < n; j++) str.push(B[i + j]); // Sort the string str str = str.sort() // Return true if sorted // string of \"str\" & sorted // string of \"A\" are equal if (str.join('') == A) return true; } }} // Driver Code// Input str1 and str2var str1 = \"geekforgeeks\";var str2 = \"ekegorfkeegsgeek\";// Function return true if// str1 is shuffled substring// of str2var a = isShuffledSubstring(str1, str2);// If str1 is substring of str2// print \"YES\" else print \"NO\"if (a) document.write( \"YES\");else document.write( \"NO\");document.write(\"<br>\"); </script>",
"e": 35915,
"s": 34430,
"text": null
},
{
"code": null,
"e": 35919,
"s": 35915,
"text": "YES"
},
{
"code": null,
"e": 36038,
"s": 35921,
"text": "Time Complexity: O(m*n*log(n)), where n = length of string str1 and m = length of string str2 Auxiliary Space: O(n) "
},
{
"code": null,
"e": 36380,
"s": 36038,
"text": "Efficient Solution: This problem is a simpler version of Anagram Search. It can be solved in linear time using character frequency counting.We can achieve O(n) time complexity under the assumption that alphabet size is fixed which is typically true as we have maximum of 256 possible characters in ASCII. The idea is to use two count arrays:"
},
{
"code": null,
"e": 37277,
"s": 36380,
"text": "1) The first count array stores frequencies of characters in a pattern. 2) The second count array stores frequencies of characters in the current window of text.The important thing to note is, time complexity to compare two counted arrays is O(1) as the number of elements in them is fixed (independent of pattern and text sizes). The following are steps of this algorithm. 1) Store counts of frequencies of pattern in first count array countP[]. Also, store counts of frequencies of characters in the first window of text in array countTW[].2) Now run a loop from i = M to N-1. Do following in loop. .....a) If the two count arrays are identical, we found an occurrence. .....b) Increment count of current character of text in countTW[] .....c) Decrement count of the first character in the previous window in countWT[]3) The last window is not checked by the above loop, so explicitly check it."
},
{
"code": null,
"e": 37337,
"s": 37277,
"text": "The following is the implementation of the above algorithm."
},
{
"code": null,
"e": 37341,
"s": 37337,
"text": "C++"
},
{
"code": null,
"e": 37346,
"s": 37341,
"text": "Java"
},
{
"code": null,
"e": 37354,
"s": 37346,
"text": "Python3"
},
{
"code": null,
"e": 37357,
"s": 37354,
"text": "C#"
},
{
"code": null,
"e": 37368,
"s": 37357,
"text": "Javascript"
},
{
"code": "#include<iostream>#include<cstring>#define MAX 256using namespace std; // This function returns true if contents of arr1[] and arr2[]// are same, otherwise false.bool compare(char arr1[], char arr2[]){ for (int i=0; i<MAX; i++) if (arr1[i] != arr2[i]) return false; return true;} // This function search for all permutations of pat[] in txt[]bool search(char *pat, char *txt){ int M = strlen(pat), N = strlen(txt); // countP[]: Store count of all characters of pattern // countTW[]: Store count of current window of text int countP[MAX] = {0}, countTW[MAX] = {0}; for (int i = 0; i < M; i++) { countP[pat[i]]++; countTW[txt[i]]++; } // Traverse through remaining characters of pattern for (int i = M; i < N; i++) { // Compare counts of current window of text with // counts of pattern[] if (compare(countP, countTW)) return true; // Add current character to current window (countTW[txt[i]])++; // Remove the first character of previous window countTW[txt[i-M]]--; } // Check for the last window in text if (compare(countP, countTW)) return true; return false;} /* Driver program to test above function */int main(){ char txt[] = \"BACDGABCDA\"; char pat[] = \"ABCD\"; if (search(pat, txt)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 38781,
"s": 37368,
"text": null
},
{
"code": "import java.util.*; class GFG{ // This function returns true if// contents of arr1[] and arr2[]// are same, otherwise false.static boolean compare(int []arr1, int []arr2){ for(int i = 0; i < 256; i++) if (arr1[i] != arr2[i]) return false; return true;} // This function search for all// permutations of pat[] in txt[]static boolean search(String pat, String txt){ int M = pat.length(); int N = txt.length(); // countP[]: Store count of all // characters of pattern // countTW[]: Store count of // current window of text int []countP = new int [256]; int []countTW = new int [256]; for(int i = 0; i < 256; i++) { countP[i] = 0; countTW[i] = 0; } for(int i = 0; i < M; i++) { (countP[pat.charAt(i)])++; (countTW[txt.charAt(i)])++; } // Traverse through remaining // characters of pattern for(int i = M; i < N; i++) { // Compare counts of current // window of text with // counts of pattern[] if (compare(countP, countTW)) return true; // Add current character to // current window (countTW[txt.charAt(i)])++; // Remove the first character // of previous window countTW[txt.charAt(i - M)]--; } // Check for the last window in text if (compare(countP, countTW)) return true; return false;} // Driver codepublic static void main(String[] args){ String txt = \"BACDGABCDA\"; String pat = \"ABCD\"; if (search(pat, txt)) System.out.println(\"Yes\"); else System.out.println(\"NO\");}} // This code is contributed by Stream_Cipher",
"e": 40477,
"s": 38781,
"text": null
},
{
"code": "MAX = 256 # This function returns true if contents# of arr1[] and arr2[] are same,# otherwise false.def compare(arr1, arr2): global MAX for i in range(MAX): if (arr1[i] != arr2[i]): return False return True # This function search for all permutations# of pat[] in txt[]def search(pat, txt): M = len(pat) N = len(txt) # countP[]: Store count of all characters # of pattern # countTW[]: Store count of current window # of text countP = [0 for i in range(MAX)] countTW = [0 for i in range(MAX)] for i in range(M): countP[ord(pat[i])] += 1 countTW[ord(txt[i])] += 1 # Traverse through remaining # characters of pattern for i in range(M, N): # Compare counts of current window # of text with counts of pattern[] if (compare(countP, countTW)): return True # Add current character # to current window countTW[ord(txt[i])] += 1 # Remove the first character # of previous window countTW[ord(txt[i - M])] -= 1 # Check for the last window in text if(compare(countP, countTW)): return True return False # Driver codetxt = \"BACDGABCDA\"pat = \"ABCD\" if (search(pat, txt)): print(\"Yes\")else: print(\"No\") # This code is contributed by avanitrachhadiya2155",
"e": 41865,
"s": 40477,
"text": null
},
{
"code": "using System.Collections.Generic;using System; class GFG{ // This function returns true if// contents of arr1[] and arr2[]// are same, otherwise false.static bool compare(int []arr1, int []arr2){ for(int i = 0; i < 256; i++) if (arr1[i] != arr2[i]) return false; return true;} // This function search for all// permutations of pat[] in txt[]static bool search(String pat, String txt){ int M = pat.Length; int N = txt.Length; // countP[]: Store count of all // characters of pattern // countTW[]: Store count of // current window of text int []countP = new int [256]; int []countTW = new int [256]; for(int i = 0; i < 256; i++) { countP[i] = 0; countTW[i] = 0; } for(int i = 0; i < M; i++) { (countP[pat[i]])++; (countTW[txt[i]])++; } // Traverse through remaining // characters of pattern for(int i = M; i < N; i++) { // Compare counts of current // window of text with // counts of pattern[] if (compare(countP, countTW)) return true; // Add current character to // current window (countTW[txt[i]])++; // Remove the first character // of previous window countTW[txt[i - M]]--; } // Check for the last window in text if (compare(countP, countTW)) return true; return false;} // Driver codepublic static void Main(){ string txt = \"BACDGABCDA\"; string pat = \"ABCD\"; if (search(pat, txt)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"NO\");}} // This code is contributed by Stream_Cipher",
"e": 43536,
"s": 41865,
"text": null
},
{
"code": "<script> // This function returns true if// contents of arr1[] and arr2[]// are same, otherwise false.function compare(arr1,arr2){ for(let i = 0; i < 256; i++) if (arr1[i] != arr2[i]) return false; return true;} // This function search for all// permutations of pat[] in txt[]function search(pat,txt){ let M = pat.length; let N = txt.length; // countP[]: Store count of all // characters of pattern // countTW[]: Store count of // current window of text let countP = new Array(256); let countTW = new Array(256); for(let i = 0; i < 256; i++) { countP[i] = 0; countTW[i] = 0; } for(let i = 0; i < 256; i++) { countP[i] = 0; countTW[i] = 0; } for(let i = 0; i < M; i++) { (countP[pat[i].charCodeAt(0)])++; (countTW[txt[i].charCodeAt(0)])++; } // Traverse through remaining // characters of pattern for(let i = M; i < N; i++) { // Compare counts of current // window of text with // counts of pattern[] if (compare(countP, countTW)) return true; // Add current character to // current window (countTW[txt[i].charCodeAt(0)])++; // Remove the first character // of previous window countTW[txt[i - M].charCodeAt(0)]--; } // Check for the last window in text if (compare(countP, countTW)) return true; return false;} // Driver codelet txt = \"BACDGABCDA\";let pat = \"ABCD\"; if (search(pat, txt)) document.write(\"Yes\");else document.write(\"NO\"); // This code is contributed by ab2127</script>",
"e": 45207,
"s": 43536,
"text": null
},
{
"code": null,
"e": 45211,
"s": 45207,
"text": "Yes"
},
{
"code": null,
"e": 45227,
"s": 45213,
"text": "princiraj1992"
},
{
"code": null,
"e": 45242,
"s": 45227,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 45254,
"s": 45242,
"text": "hawkanubhav"
},
{
"code": null,
"e": 45268,
"s": 45254,
"text": "Stream_Cipher"
},
{
"code": null,
"e": 45289,
"s": 45268,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 45298,
"s": 45289,
"text": "noob2000"
},
{
"code": null,
"e": 45310,
"s": 45298,
"text": "anikaseth98"
},
{
"code": null,
"e": 45317,
"s": 45310,
"text": "ab2127"
},
{
"code": null,
"e": 45331,
"s": 45317,
"text": "amansidd17861"
},
{
"code": null,
"e": 45342,
"s": 45331,
"text": "abhishek2x"
},
{
"code": null,
"e": 45352,
"s": 45342,
"text": "substring"
},
{
"code": null,
"e": 45376,
"s": 45352,
"text": "Competitive Programming"
},
{
"code": null,
"e": 45394,
"s": 45376,
"text": "Pattern Searching"
},
{
"code": null,
"e": 45402,
"s": 45394,
"text": "Sorting"
},
{
"code": null,
"e": 45410,
"s": 45402,
"text": "Strings"
},
{
"code": null,
"e": 45418,
"s": 45410,
"text": "Strings"
},
{
"code": null,
"e": 45426,
"s": 45418,
"text": "Sorting"
},
{
"code": null,
"e": 45444,
"s": 45426,
"text": "Pattern Searching"
},
{
"code": null,
"e": 45542,
"s": 45444,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45551,
"s": 45542,
"text": "Comments"
},
{
"code": null,
"e": 45564,
"s": 45551,
"text": "Old Comments"
},
{
"code": null,
"e": 45589,
"s": 45564,
"text": "Formatted output in Java"
},
{
"code": null,
"e": 45637,
"s": 45589,
"text": "Algorithm Library | C++ Magicians STL Algorithm"
},
{
"code": null,
"e": 45664,
"s": 45637,
"text": "Use of FLAG in programming"
},
{
"code": null,
"e": 45710,
"s": 45664,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 45766,
"s": 45710,
"text": "Maximum LCM among all pairs (i, j) from the given Array"
},
{
"code": null,
"e": 45823,
"s": 45766,
"text": "Check if an URL is valid or not using Regular Expression"
},
{
"code": null,
"e": 45849,
"s": 45823,
"text": "Wildcard Pattern Matching"
},
{
"code": null,
"e": 45936,
"s": 45849,
"text": "Check if a string contains uppercase, lowercase, special characters and numeric values"
},
{
"code": null,
"e": 45977,
"s": 45936,
"text": "Search a Word in a 2D Grid of characters"
}
]
|
Building A Linear Regression with PySpark and MLlib | by Susan Li | Towards Data Science | Apache Spark has become one of the most commonly used and supported open-source tools for machine learning and data science.
In this post, I’ll help you get started using Apache Spark’s spark.ml Linear Regression for predicting Boston housing prices. Our data is from the Kaggle competition: Housing Values in Suburbs of Boston. For each house observation, we have the following information:
CRIM — per capita crime rate by town.
ZN — proportion of residential land zoned for lots over 25,000 sq.ft.
INDUS — proportion of non-retail business acres per town.
CHAS — Charles River dummy variable (= 1 if tract bounds river; 0 otherwise).
NOX — nitrogen oxides concentration (parts per 10 million).
RM — average number of rooms per dwelling.
AGE — proportion of owner-occupied units built prior to 1940.
DIS — weighted mean of distances to five Boston employment centres.
RAD — index of accessibility to radial highways.
TAX — full-value property-tax rate per $10,000.
PTRATIO — pupil-teacher ratio by town.
BLACK — 1000(Bk — 0.63)2 where Bk is the proportion of blacks by town.
LSTAT — lower status of the population (percent).
MV — median value of owner-occupied homes in $1000s. This is the target variable.
The input data set contains data about details of various houses. Based on the information provided, the goal is to come up with a model to predict median value of a given house in the area.
from pyspark import SparkConf, SparkContextfrom pyspark.sql import SQLContextsc= SparkContext()sqlContext = SQLContext(sc)house_df = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('boston.csv')house_df.take(1)
[Row(CRIM=0.00632, ZN=18.0, INDUS=2.309999943, CHAS=0, NOX=0.537999988, RM=6.574999809, AGE=65.19999695, DIS=4.090000153, RAD=1, TAX=296, PT=15.30000019, B=396.8999939, LSTAT=4.980000019, MV=24.0)]
Print Schema in a tree format.
house_df.cache()house_df.printSchema()root |-- CRIM: double (nullable = true) |-- ZN: double (nullable = true) |-- INDUS: double (nullable = true) |-- CHAS: integer (nullable = true) |-- NOX: double (nullable = true) |-- RM: double (nullable = true) |-- AGE: double (nullable = true) |-- DIS: double (nullable = true) |-- RAD: integer (nullable = true) |-- TAX: integer (nullable = true) |-- PT: double (nullable = true) |-- B: double (nullable = true) |-- LSTAT: double (nullable = true) |-- MV: double (nullable = true)
Perform descriptive analytics
house_df.describe().toPandas().transpose()
Scatter matrix is a great way to roughly determine if we have a linear correlation between multiple independent variables.
import pandas as pdnumeric_features = [t[0] for t in house_df.dtypes if t[1] == 'int' or t[1] == 'double']sampled_data = house_df.select(numeric_features).sample(False, 0.8).toPandas()axs = pd.scatter_matrix(sampled_data, figsize=(10, 10))n = len(sampled_data.columns)for i in range(n): v = axs[i, 0] v.yaxis.label.set_rotation(0) v.yaxis.label.set_ha('right') v.set_yticks(()) h = axs[n-1, i] h.xaxis.label.set_rotation(90) h.set_xticks(())
It’s hard to see. Let’s find correlation between independent variables and target variable.
import sixfor i in house_df.columns: if not( isinstance(house_df.select(i).take(1)[0][0], six.string_types)): print( "Correlation to MV for ", i, house_df.stat.corr('MV',i))Correlation to MV for CRIM -0.3883046116575088Correlation to MV for ZN 0.36044534463752903Correlation to MV for INDUS -0.48372517128143383Correlation to MV for CHAS 0.17526017775291847Correlation to MV for NOX -0.4273207763683772Correlation to MV for RM 0.695359937127267Correlation to MV for AGE -0.37695456714288667Correlation to MV for DIS 0.24992873873512172Correlation to MV for RAD -0.3816262315669168Correlation to MV for TAX -0.46853593528654536Correlation to MV for PT -0.5077867038116085Correlation to MV for B 0.3334608226834164Correlation to MV for LSTAT -0.7376627294671615Correlation to MV for MV 1.0
The correlation coefficient ranges from –1 to 1. When it is close to 1, it means that there is a strong positive correlation; for example, the median value tends to go up when the number of rooms goes up. When the coefficient is close to –1, it means that there is a strong negative correlation; the median value tends to go down when the percentage of the lower status of the population goes up. Finally, coefficients close to zero mean that there is no linear correlation.
We are going to keep all the variables, for now.
Prepare data for Machine Learning. And we need two columns only — features and label(“MV”):
from pyspark.ml.feature import VectorAssemblervectorAssembler = VectorAssembler(inputCols = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PT', 'B', 'LSTAT'], outputCol = 'features')vhouse_df = vectorAssembler.transform(house_df)vhouse_df = vhouse_df.select(['features', 'MV'])vhouse_df.show(3)
splits = vhouse_df.randomSplit([0.7, 0.3])train_df = splits[0]test_df = splits[1]
from pyspark.ml.regression import LinearRegressionlr = LinearRegression(featuresCol = 'features', labelCol='MV', maxIter=10, regParam=0.3, elasticNetParam=0.8)lr_model = lr.fit(train_df)print("Coefficients: " + str(lr_model.coefficients))print("Intercept: " + str(lr_model.intercept))
Coefficients: [0.0,0.007302310571175137,-0.03286303124593804,1.4134773328268,-7.91932366863737,5.341921692409693,0.0,-0.5791187396097941,0.0,-0.0010503197747184644,-0.7748333592630333,0.01126108224671488,-0.3932170620689197]Intercept: 11.327590788070061
Summarize the model over the training set and print out some metrics:
trainingSummary = lr_model.summaryprint("RMSE: %f" % trainingSummary.rootMeanSquaredError)print("r2: %f" % trainingSummary.r2)
RMSE: 4.675914r2: 0.743627
RMSE measures the differences between predicted values by the model and the actual values. However, RMSE alone is meaningless until we compare with the actual “MV” value, such as mean, min and max. After such comparison, our RMSE looks pretty good.
train_df.describe().show()
R squared at 0.74 indicates that in our model, approximate 74% of the variability in “MV” can be explained using the model. This is in align with the result from Scikit-Learn. It is not bad. However, we must be cautious that the performance on the training set may not a good approximation of the performance on the test set.
lr_predictions = lr_model.transform(test_df)lr_predictions.select("prediction","MV","features").show(5)from pyspark.ml.evaluation import RegressionEvaluatorlr_evaluator = RegressionEvaluator(predictionCol="prediction", \ labelCol="MV",metricName="r2")print("R Squared (R2) on test data = %g" % lr_evaluator.evaluate(lr_predictions))
test_result = lr_model.evaluate(test_df)print("Root Mean Squared Error (RMSE) on test data = %g" % test_result.rootMeanSquaredError)
Root Mean Squared Error (RMSE) on test data = 5.52048
Sure enough, we achieved worse RMSE and R squared on the test set.
print("numIterations: %d" % trainingSummary.totalIterations)print("objectiveHistory: %s" % str(trainingSummary.objectiveHistory))trainingSummary.residuals.show()
numIterations: 11objectiveHistory: [0.49999999999999956, 0.4281126976069304, 0.22539203628598917, 0.20185326295592582, 0.1686847843494657, 0.16588096079648484, 0.16543041085178495, 0.16508485781434112, 0.16484472289473545, 0.16454785266359198, 0.16447743850144508]
Using our Linear Regression model to make some predictions:
predictions = lr_model.transform(test_df)predictions.select("prediction","MV","features").show()
from pyspark.ml.regression import DecisionTreeRegressordt = DecisionTreeRegressor(featuresCol ='features', labelCol = 'MV')dt_model = dt.fit(train_df)dt_predictions = dt_model.transform(test_df)dt_evaluator = RegressionEvaluator( labelCol="MV", predictionCol="prediction", metricName="rmse")rmse = dt_evaluator.evaluate(dt_predictions)print("Root Mean Squared Error (RMSE) on test data = %g" % rmse)
Root Mean Squared Error (RMSE) on test data = 4.39053
Feature Importance
dt_model.featureImportances
SparseVector(13, {0: 0.0496, 1: 0.0, 4: 0.0118, 5: 0.624, 6: 0.0005, 7: 0.1167, 8: 0.0044, 10: 0.013, 12: 0.1799})
house_df.take(1)
[Row(CRIM=0.00632, ZN=18.0, INDUS=2.309999943, CHAS=0, NOX=0.537999988, RM=6.574999809, AGE=65.19999695, DIS=4.090000153, RAD=1, TAX=296, PT=15.30000019, B=396.8999939, LSTAT=4.980000019, MV=24.0)]
Apparently, the number of rooms is the most important feature to predict the house median price in our data.
from pyspark.ml.regression import GBTRegressorgbt = GBTRegressor(featuresCol = 'features', labelCol = 'MV', maxIter=10)gbt_model = gbt.fit(train_df)gbt_predictions = gbt_model.transform(test_df)gbt_predictions.select('prediction', 'MV', 'features').show(5)
gbt_evaluator = RegressionEvaluator( labelCol="MV", predictionCol="prediction", metricName="rmse")rmse = gbt_evaluator.evaluate(gbt_predictions)print("Root Mean Squared Error (RMSE) on test data = %g" % rmse)
Root Mean Squared Error (RMSE) on test data = 4.19795
Gradient-boosted tree regression performed the best on our data.
Source code can be found on Github. I am happy to hear any feedback or questions. | [
{
"code": null,
"e": 297,
"s": 172,
"text": "Apache Spark has become one of the most commonly used and supported open-source tools for machine learning and data science."
},
{
"code": null,
"e": 564,
"s": 297,
"text": "In this post, I’ll help you get started using Apache Spark’s spark.ml Linear Regression for predicting Boston housing prices. Our data is from the Kaggle competition: Housing Values in Suburbs of Boston. For each house observation, we have the following information:"
},
{
"code": null,
"e": 602,
"s": 564,
"text": "CRIM — per capita crime rate by town."
},
{
"code": null,
"e": 672,
"s": 602,
"text": "ZN — proportion of residential land zoned for lots over 25,000 sq.ft."
},
{
"code": null,
"e": 730,
"s": 672,
"text": "INDUS — proportion of non-retail business acres per town."
},
{
"code": null,
"e": 808,
"s": 730,
"text": "CHAS — Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)."
},
{
"code": null,
"e": 868,
"s": 808,
"text": "NOX — nitrogen oxides concentration (parts per 10 million)."
},
{
"code": null,
"e": 911,
"s": 868,
"text": "RM — average number of rooms per dwelling."
},
{
"code": null,
"e": 973,
"s": 911,
"text": "AGE — proportion of owner-occupied units built prior to 1940."
},
{
"code": null,
"e": 1041,
"s": 973,
"text": "DIS — weighted mean of distances to five Boston employment centres."
},
{
"code": null,
"e": 1090,
"s": 1041,
"text": "RAD — index of accessibility to radial highways."
},
{
"code": null,
"e": 1138,
"s": 1090,
"text": "TAX — full-value property-tax rate per $10,000."
},
{
"code": null,
"e": 1177,
"s": 1138,
"text": "PTRATIO — pupil-teacher ratio by town."
},
{
"code": null,
"e": 1248,
"s": 1177,
"text": "BLACK — 1000(Bk — 0.63)2 where Bk is the proportion of blacks by town."
},
{
"code": null,
"e": 1298,
"s": 1248,
"text": "LSTAT — lower status of the population (percent)."
},
{
"code": null,
"e": 1380,
"s": 1298,
"text": "MV — median value of owner-occupied homes in $1000s. This is the target variable."
},
{
"code": null,
"e": 1571,
"s": 1380,
"text": "The input data set contains data about details of various houses. Based on the information provided, the goal is to come up with a model to predict median value of a given house in the area."
},
{
"code": null,
"e": 1833,
"s": 1571,
"text": "from pyspark import SparkConf, SparkContextfrom pyspark.sql import SQLContextsc= SparkContext()sqlContext = SQLContext(sc)house_df = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('boston.csv')house_df.take(1)"
},
{
"code": null,
"e": 2031,
"s": 1833,
"text": "[Row(CRIM=0.00632, ZN=18.0, INDUS=2.309999943, CHAS=0, NOX=0.537999988, RM=6.574999809, AGE=65.19999695, DIS=4.090000153, RAD=1, TAX=296, PT=15.30000019, B=396.8999939, LSTAT=4.980000019, MV=24.0)]"
},
{
"code": null,
"e": 2062,
"s": 2031,
"text": "Print Schema in a tree format."
},
{
"code": null,
"e": 2584,
"s": 2062,
"text": "house_df.cache()house_df.printSchema()root |-- CRIM: double (nullable = true) |-- ZN: double (nullable = true) |-- INDUS: double (nullable = true) |-- CHAS: integer (nullable = true) |-- NOX: double (nullable = true) |-- RM: double (nullable = true) |-- AGE: double (nullable = true) |-- DIS: double (nullable = true) |-- RAD: integer (nullable = true) |-- TAX: integer (nullable = true) |-- PT: double (nullable = true) |-- B: double (nullable = true) |-- LSTAT: double (nullable = true) |-- MV: double (nullable = true)"
},
{
"code": null,
"e": 2614,
"s": 2584,
"text": "Perform descriptive analytics"
},
{
"code": null,
"e": 2657,
"s": 2614,
"text": "house_df.describe().toPandas().transpose()"
},
{
"code": null,
"e": 2780,
"s": 2657,
"text": "Scatter matrix is a great way to roughly determine if we have a linear correlation between multiple independent variables."
},
{
"code": null,
"e": 3243,
"s": 2780,
"text": "import pandas as pdnumeric_features = [t[0] for t in house_df.dtypes if t[1] == 'int' or t[1] == 'double']sampled_data = house_df.select(numeric_features).sample(False, 0.8).toPandas()axs = pd.scatter_matrix(sampled_data, figsize=(10, 10))n = len(sampled_data.columns)for i in range(n): v = axs[i, 0] v.yaxis.label.set_rotation(0) v.yaxis.label.set_ha('right') v.set_yticks(()) h = axs[n-1, i] h.xaxis.label.set_rotation(90) h.set_xticks(())"
},
{
"code": null,
"e": 3335,
"s": 3243,
"text": "It’s hard to see. Let’s find correlation between independent variables and target variable."
},
{
"code": null,
"e": 4147,
"s": 3335,
"text": "import sixfor i in house_df.columns: if not( isinstance(house_df.select(i).take(1)[0][0], six.string_types)): print( \"Correlation to MV for \", i, house_df.stat.corr('MV',i))Correlation to MV for CRIM -0.3883046116575088Correlation to MV for ZN 0.36044534463752903Correlation to MV for INDUS -0.48372517128143383Correlation to MV for CHAS 0.17526017775291847Correlation to MV for NOX -0.4273207763683772Correlation to MV for RM 0.695359937127267Correlation to MV for AGE -0.37695456714288667Correlation to MV for DIS 0.24992873873512172Correlation to MV for RAD -0.3816262315669168Correlation to MV for TAX -0.46853593528654536Correlation to MV for PT -0.5077867038116085Correlation to MV for B 0.3334608226834164Correlation to MV for LSTAT -0.7376627294671615Correlation to MV for MV 1.0"
},
{
"code": null,
"e": 4622,
"s": 4147,
"text": "The correlation coefficient ranges from –1 to 1. When it is close to 1, it means that there is a strong positive correlation; for example, the median value tends to go up when the number of rooms goes up. When the coefficient is close to –1, it means that there is a strong negative correlation; the median value tends to go down when the percentage of the lower status of the population goes up. Finally, coefficients close to zero mean that there is no linear correlation."
},
{
"code": null,
"e": 4671,
"s": 4622,
"text": "We are going to keep all the variables, for now."
},
{
"code": null,
"e": 4763,
"s": 4671,
"text": "Prepare data for Machine Learning. And we need two columns only — features and label(“MV”):"
},
{
"code": null,
"e": 5085,
"s": 4763,
"text": "from pyspark.ml.feature import VectorAssemblervectorAssembler = VectorAssembler(inputCols = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PT', 'B', 'LSTAT'], outputCol = 'features')vhouse_df = vectorAssembler.transform(house_df)vhouse_df = vhouse_df.select(['features', 'MV'])vhouse_df.show(3)"
},
{
"code": null,
"e": 5167,
"s": 5085,
"text": "splits = vhouse_df.randomSplit([0.7, 0.3])train_df = splits[0]test_df = splits[1]"
},
{
"code": null,
"e": 5452,
"s": 5167,
"text": "from pyspark.ml.regression import LinearRegressionlr = LinearRegression(featuresCol = 'features', labelCol='MV', maxIter=10, regParam=0.3, elasticNetParam=0.8)lr_model = lr.fit(train_df)print(\"Coefficients: \" + str(lr_model.coefficients))print(\"Intercept: \" + str(lr_model.intercept))"
},
{
"code": null,
"e": 5706,
"s": 5452,
"text": "Coefficients: [0.0,0.007302310571175137,-0.03286303124593804,1.4134773328268,-7.91932366863737,5.341921692409693,0.0,-0.5791187396097941,0.0,-0.0010503197747184644,-0.7748333592630333,0.01126108224671488,-0.3932170620689197]Intercept: 11.327590788070061"
},
{
"code": null,
"e": 5776,
"s": 5706,
"text": "Summarize the model over the training set and print out some metrics:"
},
{
"code": null,
"e": 5903,
"s": 5776,
"text": "trainingSummary = lr_model.summaryprint(\"RMSE: %f\" % trainingSummary.rootMeanSquaredError)print(\"r2: %f\" % trainingSummary.r2)"
},
{
"code": null,
"e": 5930,
"s": 5903,
"text": "RMSE: 4.675914r2: 0.743627"
},
{
"code": null,
"e": 6179,
"s": 5930,
"text": "RMSE measures the differences between predicted values by the model and the actual values. However, RMSE alone is meaningless until we compare with the actual “MV” value, such as mean, min and max. After such comparison, our RMSE looks pretty good."
},
{
"code": null,
"e": 6206,
"s": 6179,
"text": "train_df.describe().show()"
},
{
"code": null,
"e": 6532,
"s": 6206,
"text": "R squared at 0.74 indicates that in our model, approximate 74% of the variability in “MV” can be explained using the model. This is in align with the result from Scikit-Learn. It is not bad. However, we must be cautious that the performance on the training set may not a good approximation of the performance on the test set."
},
{
"code": null,
"e": 6881,
"s": 6532,
"text": "lr_predictions = lr_model.transform(test_df)lr_predictions.select(\"prediction\",\"MV\",\"features\").show(5)from pyspark.ml.evaluation import RegressionEvaluatorlr_evaluator = RegressionEvaluator(predictionCol=\"prediction\", \\ labelCol=\"MV\",metricName=\"r2\")print(\"R Squared (R2) on test data = %g\" % lr_evaluator.evaluate(lr_predictions))"
},
{
"code": null,
"e": 7014,
"s": 6881,
"text": "test_result = lr_model.evaluate(test_df)print(\"Root Mean Squared Error (RMSE) on test data = %g\" % test_result.rootMeanSquaredError)"
},
{
"code": null,
"e": 7068,
"s": 7014,
"text": "Root Mean Squared Error (RMSE) on test data = 5.52048"
},
{
"code": null,
"e": 7135,
"s": 7068,
"text": "Sure enough, we achieved worse RMSE and R squared on the test set."
},
{
"code": null,
"e": 7297,
"s": 7135,
"text": "print(\"numIterations: %d\" % trainingSummary.totalIterations)print(\"objectiveHistory: %s\" % str(trainingSummary.objectiveHistory))trainingSummary.residuals.show()"
},
{
"code": null,
"e": 7562,
"s": 7297,
"text": "numIterations: 11objectiveHistory: [0.49999999999999956, 0.4281126976069304, 0.22539203628598917, 0.20185326295592582, 0.1686847843494657, 0.16588096079648484, 0.16543041085178495, 0.16508485781434112, 0.16484472289473545, 0.16454785266359198, 0.16447743850144508]"
},
{
"code": null,
"e": 7622,
"s": 7562,
"text": "Using our Linear Regression model to make some predictions:"
},
{
"code": null,
"e": 7719,
"s": 7622,
"text": "predictions = lr_model.transform(test_df)predictions.select(\"prediction\",\"MV\",\"features\").show()"
},
{
"code": null,
"e": 8122,
"s": 7719,
"text": "from pyspark.ml.regression import DecisionTreeRegressordt = DecisionTreeRegressor(featuresCol ='features', labelCol = 'MV')dt_model = dt.fit(train_df)dt_predictions = dt_model.transform(test_df)dt_evaluator = RegressionEvaluator( labelCol=\"MV\", predictionCol=\"prediction\", metricName=\"rmse\")rmse = dt_evaluator.evaluate(dt_predictions)print(\"Root Mean Squared Error (RMSE) on test data = %g\" % rmse)"
},
{
"code": null,
"e": 8176,
"s": 8122,
"text": "Root Mean Squared Error (RMSE) on test data = 4.39053"
},
{
"code": null,
"e": 8195,
"s": 8176,
"text": "Feature Importance"
},
{
"code": null,
"e": 8223,
"s": 8195,
"text": "dt_model.featureImportances"
},
{
"code": null,
"e": 8338,
"s": 8223,
"text": "SparseVector(13, {0: 0.0496, 1: 0.0, 4: 0.0118, 5: 0.624, 6: 0.0005, 7: 0.1167, 8: 0.0044, 10: 0.013, 12: 0.1799})"
},
{
"code": null,
"e": 8355,
"s": 8338,
"text": "house_df.take(1)"
},
{
"code": null,
"e": 8553,
"s": 8355,
"text": "[Row(CRIM=0.00632, ZN=18.0, INDUS=2.309999943, CHAS=0, NOX=0.537999988, RM=6.574999809, AGE=65.19999695, DIS=4.090000153, RAD=1, TAX=296, PT=15.30000019, B=396.8999939, LSTAT=4.980000019, MV=24.0)]"
},
{
"code": null,
"e": 8662,
"s": 8553,
"text": "Apparently, the number of rooms is the most important feature to predict the house median price in our data."
},
{
"code": null,
"e": 8919,
"s": 8662,
"text": "from pyspark.ml.regression import GBTRegressorgbt = GBTRegressor(featuresCol = 'features', labelCol = 'MV', maxIter=10)gbt_model = gbt.fit(train_df)gbt_predictions = gbt_model.transform(test_df)gbt_predictions.select('prediction', 'MV', 'features').show(5)"
},
{
"code": null,
"e": 9131,
"s": 8919,
"text": "gbt_evaluator = RegressionEvaluator( labelCol=\"MV\", predictionCol=\"prediction\", metricName=\"rmse\")rmse = gbt_evaluator.evaluate(gbt_predictions)print(\"Root Mean Squared Error (RMSE) on test data = %g\" % rmse)"
},
{
"code": null,
"e": 9185,
"s": 9131,
"text": "Root Mean Squared Error (RMSE) on test data = 4.19795"
},
{
"code": null,
"e": 9250,
"s": 9185,
"text": "Gradient-boosted tree regression performed the best on our data."
}
]
|
Using the COUNT/GROUP BY/JOIN Combination in SQL | by Michael Grogan | Towards Data Science | It is often the case that when working with a table in SQL, one wishes to count the number of instances in that table. This could be of a product category, brand, etc.
This can prove simple enough when working with one table. However, the task can be somewhat cumbersome when working across multiple tables.
Here, we will look at an example of how to combine the COUNT and GROUP BY functions with an INNER JOIN to count the number of different product types across a particular retailer.
Let us suppose that a busy clothing store has several tables stored in a database containing all the items stored in their warehouse at any given time. These tables contain information on the name of the item, price, brand, product type, among others. The owner is having difficulty in estimating the specific number of each product in storage, i.e. how many pairs of jeans, how many t-shirts are stored in the warehouse?
Consider the following two tables:
>>> select * from clothes1 limit 1;item | colour | type --------------------+----------+----------Grass Green T-Shirt | Green | T-Shirt>>> select * from clothes2 limit 2;item | price | size -------------------+---------+--------Sky Blue Jeans | 79.99 | 31
Assume the following scenario. clothes1 represents all the clothing items that have ever been present in the warehouse. clothes2 represents all the clothing items that are present in the warehouse at any one time.
Given that only the clothes1 table contains information regarding the type, this means that the first table must be joined with the second table in order to identify each item present in the first table by their type.
Since we only want to count the type of the clothing items that are currently present, and not those which are stored in the second table but not present, we use an INNER JOIN as opposed to a FULL JOIN for this purpose.
Using a FULL JOIN would return all entries from clothes1, i.e. those that have ever been present in the warehouse. Since we are only interested in counting current inventory, we use an INNER JOIN instead.
Here is the query:
>>> select t1.type, count(*) from clothes1 as t1 inner join clothes2 as t2 on t1.item=t2.item group by t1.type;
Resulting from this query, we obtain a table that resembles as follows:
type | count -----------+------- T-Shirt | 2496 Jeans | 3133 Sneakers | 2990 Shirts | 3844 Ties | 1789 Trousers | 2500(6 rows)
In this short tutorial, you have seen how the COUNT/GROUP BY/JOIN combination can be used in SQL to aggregate entries across multiple tables.
While a GROUP BY query can accomplish this simply enough when working with just one table, the situation can become more complex when working across multiple tables.
Hope you enjoyed this tutorial, and you can find more programming and data science content at michael-grogan.com.
Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice. The findings and interpretations in this article are those of the author and are not endorsed by or affiliated with any third-party mentioned in this article. | [
{
"code": null,
"e": 339,
"s": 171,
"text": "It is often the case that when working with a table in SQL, one wishes to count the number of instances in that table. This could be of a product category, brand, etc."
},
{
"code": null,
"e": 479,
"s": 339,
"text": "This can prove simple enough when working with one table. However, the task can be somewhat cumbersome when working across multiple tables."
},
{
"code": null,
"e": 659,
"s": 479,
"text": "Here, we will look at an example of how to combine the COUNT and GROUP BY functions with an INNER JOIN to count the number of different product types across a particular retailer."
},
{
"code": null,
"e": 1081,
"s": 659,
"text": "Let us suppose that a busy clothing store has several tables stored in a database containing all the items stored in their warehouse at any given time. These tables contain information on the name of the item, price, brand, product type, among others. The owner is having difficulty in estimating the specific number of each product in storage, i.e. how many pairs of jeans, how many t-shirts are stored in the warehouse?"
},
{
"code": null,
"e": 1116,
"s": 1081,
"text": "Consider the following two tables:"
},
{
"code": null,
"e": 1414,
"s": 1116,
"text": ">>> select * from clothes1 limit 1;item | colour | type --------------------+----------+----------Grass Green T-Shirt | Green | T-Shirt>>> select * from clothes2 limit 2;item | price | size -------------------+---------+--------Sky Blue Jeans | 79.99 | 31"
},
{
"code": null,
"e": 1628,
"s": 1414,
"text": "Assume the following scenario. clothes1 represents all the clothing items that have ever been present in the warehouse. clothes2 represents all the clothing items that are present in the warehouse at any one time."
},
{
"code": null,
"e": 1846,
"s": 1628,
"text": "Given that only the clothes1 table contains information regarding the type, this means that the first table must be joined with the second table in order to identify each item present in the first table by their type."
},
{
"code": null,
"e": 2066,
"s": 1846,
"text": "Since we only want to count the type of the clothing items that are currently present, and not those which are stored in the second table but not present, we use an INNER JOIN as opposed to a FULL JOIN for this purpose."
},
{
"code": null,
"e": 2271,
"s": 2066,
"text": "Using a FULL JOIN would return all entries from clothes1, i.e. those that have ever been present in the warehouse. Since we are only interested in counting current inventory, we use an INNER JOIN instead."
},
{
"code": null,
"e": 2290,
"s": 2271,
"text": "Here is the query:"
},
{
"code": null,
"e": 2402,
"s": 2290,
"text": ">>> select t1.type, count(*) from clothes1 as t1 inner join clothes2 as t2 on t1.item=t2.item group by t1.type;"
},
{
"code": null,
"e": 2474,
"s": 2402,
"text": "Resulting from this query, we obtain a table that resembles as follows:"
},
{
"code": null,
"e": 2629,
"s": 2474,
"text": " type | count -----------+------- T-Shirt | 2496 Jeans | 3133 Sneakers | 2990 Shirts | 3844 Ties | 1789 Trousers | 2500(6 rows)"
},
{
"code": null,
"e": 2771,
"s": 2629,
"text": "In this short tutorial, you have seen how the COUNT/GROUP BY/JOIN combination can be used in SQL to aggregate entries across multiple tables."
},
{
"code": null,
"e": 2937,
"s": 2771,
"text": "While a GROUP BY query can accomplish this simply enough when working with just one table, the situation can become more complex when working across multiple tables."
},
{
"code": null,
"e": 3051,
"s": 2937,
"text": "Hope you enjoyed this tutorial, and you can find more programming and data science content at michael-grogan.com."
}
]
|
Img-circle Bootstrap class | Use the img-circle Bootstrap class to style your image and make it completely round.
You can try to run the following code to implement the img-circle class
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Images</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<p>Styling images with Bootstrap</p>
<h1>Original Image</h1>
<img src = "https://www.tutorialspoint.com/videotutorials/images/numerical_ability_home.jpg">
<h1>Image with Rounded Corners</h1>
<img src = "https://www.tutorialspoint.com/videotutorials/images/numerical_ability_home.jpg" class = "img-circle">
</body>
</html> | [
{
"code": null,
"e": 1147,
"s": 1062,
"text": "Use the img-circle Bootstrap class to style your image and make it completely round."
},
{
"code": null,
"e": 1219,
"s": 1147,
"text": "You can try to run the following code to implement the img-circle class"
},
{
"code": null,
"e": 1229,
"s": 1219,
"text": "Live Demo"
},
{
"code": null,
"e": 1868,
"s": 1229,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Images</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <p>Styling images with Bootstrap</p>\n <h1>Original Image</h1>\n <img src = \"https://www.tutorialspoint.com/videotutorials/images/numerical_ability_home.jpg\">\n <h1>Image with Rounded Corners</h1>\n <img src = \"https://www.tutorialspoint.com/videotutorials/images/numerical_ability_home.jpg\" class = \"img-circle\">\n </body>\n</html>"
}
]
|
Euler Circuit in an Undirected Graph | Practice | GeeksforGeeks | Eulerian Path is a path in a graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path that starts and ends on the same vertex. Given the number of vertices V and adjacency list adj denoting the graph. Your task is to find that there exists the Euler circuit or not
Note that: Given graph is connected.
Example 1:
Input:
Output: 1
Explanation: One of the Eularian circuit
starting from vertex 0 is as follows:
0->1->3->2->0
Your Task:
You don't need to read or print anything. Your task is to complete the function isEularCircuitExist() which takes V and adjacency list adj as input parameter and returns boolean value 1 if Eular circuit exists otherwise returns 0.
Expected Time Complexity: O(V + E)
Expected Space Complexity: O(V)
Constraints:
1 <= V <= 105
1 <= E <= 2*105
0
shyamprakash8071 week ago
Time Taken : 0.23 / 5.18
class Solution:def isEularCircuitExist(self, V, adj): #Code here odd = 0 for i in range(V): if len(adj[i])%2==1: odd += 1 if odd == 0: return 1 return 0
0
puranjanprithu2 months ago
def isEularCircuitExist(self, V, adj): #Code here inedge=[0 for _ in range(V)] for i in range(V): for s in adj[i]: inedge[s]+=1 odd=0 for i in range(V): if inedge[i]%2==1: odd+=1 if odd>0: return 0 return 1
0
lindan1233 months ago
bool isEularCircuitExist(int V, vector<int>adj[]){
for(int i=0;i<V;i++)
{
if(adj[i].size()%2!=0)
{
return false;
}
}
return true;
}
Very Easy Solution :
Cpp
Time Taken : 0.1sec
0
razhagarrix3 months ago
Where is the practice page for Euler Circuit in a directed graph ?
0
anutiger6 months ago
bool isEularCircuitExist(int V, vector<int>adj[]){
for(int i = 0 ; i < V ; i ++){
if(adj[i].size() % 2 != 0) return false;
}
return true;
}
+1
Saksham Jain8 months ago
Saksham Jain
There should be a test case which contains two components in a graph.Sir, please update the test cases.
0
Saksham Jain
This comment was deleted.
+1
Manhar Joshi9 months ago
Manhar Joshi
Logic:- All nodes must have even degree for graph to be Euler circuit
https://uploads.disquscdn.c...
I might add, the above code should fail if the graph has disconnected components containing more edges(Although it doesn't fail here. So we might be assuming a connected graph).
0
Manhar Joshi
This comment was deleted.
0
Sandip Dutta9 months ago
Sandip Dutta
Code is successful even if we do not check Connected Components
bool isEularCircuitExist(int V, vector<int>adj[]){(int i = 0; i < V; ++i) (adj[i].size() % 2) return false;return true;}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 526,
"s": 238,
"text": "Eulerian Path is a path in a graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path that starts and ends on the same vertex. Given the number of vertices V and adjacency list adj denoting the graph. Your task is to find that there exists the Euler circuit or not"
},
{
"code": null,
"e": 575,
"s": 526,
"text": "Note that: Given graph is connected.\n\nExample 1:"
},
{
"code": null,
"e": 689,
"s": 575,
"text": "Input: \n\nOutput: 1\nExplanation: One of the Eularian circuit \nstarting from vertex 0 is as follows:\n0->1->3->2->0\n"
},
{
"code": null,
"e": 935,
"s": 691,
"text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function isEularCircuitExist() which takes V and adjacency list adj as input parameter and returns boolean value 1 if Eular circuit exists otherwise returns 0.\n "
},
{
"code": null,
"e": 1004,
"s": 935,
"text": "Expected Time Complexity: O(V + E)\nExpected Space Complexity: O(V)\n "
},
{
"code": null,
"e": 1047,
"s": 1004,
"text": "Constraints:\n1 <= V <= 105\n1 <= E <= 2*105"
},
{
"code": null,
"e": 1049,
"s": 1047,
"text": "0"
},
{
"code": null,
"e": 1075,
"s": 1049,
"text": "shyamprakash8071 week ago"
},
{
"code": null,
"e": 1100,
"s": 1075,
"text": "Time Taken : 0.23 / 5.18"
},
{
"code": null,
"e": 1280,
"s": 1102,
"text": "class Solution:def isEularCircuitExist(self, V, adj): #Code here odd = 0 for i in range(V): if len(adj[i])%2==1: odd += 1 if odd == 0: return 1 return 0"
},
{
"code": null,
"e": 1282,
"s": 1280,
"text": "0"
},
{
"code": null,
"e": 1309,
"s": 1282,
"text": "puranjanprithu2 months ago"
},
{
"code": null,
"e": 1554,
"s": 1309,
"text": "def isEularCircuitExist(self, V, adj): #Code here inedge=[0 for _ in range(V)] for i in range(V): for s in adj[i]: inedge[s]+=1 odd=0 for i in range(V): if inedge[i]%2==1: odd+=1 if odd>0: return 0 return 1"
},
{
"code": null,
"e": 1556,
"s": 1554,
"text": "0"
},
{
"code": null,
"e": 1578,
"s": 1556,
"text": "lindan1233 months ago"
},
{
"code": null,
"e": 1777,
"s": 1578,
"text": "bool isEularCircuitExist(int V, vector<int>adj[]){\n\t \n\t for(int i=0;i<V;i++)\n\t {\n\t if(adj[i].size()%2!=0)\n\t {\n\t return false;\n\t }\n\t }\n\t return true;\n\t}"
},
{
"code": null,
"e": 1799,
"s": 1777,
"text": "Very Easy Solution : "
},
{
"code": null,
"e": 1803,
"s": 1799,
"text": "Cpp"
},
{
"code": null,
"e": 1823,
"s": 1803,
"text": "Time Taken : 0.1sec"
},
{
"code": null,
"e": 1825,
"s": 1823,
"text": "0"
},
{
"code": null,
"e": 1849,
"s": 1825,
"text": "razhagarrix3 months ago"
},
{
"code": null,
"e": 1916,
"s": 1849,
"text": "Where is the practice page for Euler Circuit in a directed graph ?"
},
{
"code": null,
"e": 1918,
"s": 1916,
"text": "0"
},
{
"code": null,
"e": 1939,
"s": 1918,
"text": "anutiger6 months ago"
},
{
"code": null,
"e": 2104,
"s": 1939,
"text": "\tbool isEularCircuitExist(int V, vector<int>adj[]){\n\t for(int i = 0 ; i < V ; i ++){\n\t if(adj[i].size() % 2 != 0) return false;\n\t }\n\t return true;\n\t}"
},
{
"code": null,
"e": 2107,
"s": 2104,
"text": "+1"
},
{
"code": null,
"e": 2132,
"s": 2107,
"text": "Saksham Jain8 months ago"
},
{
"code": null,
"e": 2145,
"s": 2132,
"text": "Saksham Jain"
},
{
"code": null,
"e": 2249,
"s": 2145,
"text": "There should be a test case which contains two components in a graph.Sir, please update the test cases."
},
{
"code": null,
"e": 2251,
"s": 2249,
"text": "0"
},
{
"code": null,
"e": 2264,
"s": 2251,
"text": "Saksham Jain"
},
{
"code": null,
"e": 2290,
"s": 2264,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2293,
"s": 2290,
"text": "+1"
},
{
"code": null,
"e": 2318,
"s": 2293,
"text": "Manhar Joshi9 months ago"
},
{
"code": null,
"e": 2331,
"s": 2318,
"text": "Manhar Joshi"
},
{
"code": null,
"e": 2401,
"s": 2331,
"text": "Logic:- All nodes must have even degree for graph to be Euler circuit"
},
{
"code": null,
"e": 2433,
"s": 2401,
"text": " https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 2611,
"s": 2433,
"text": "I might add, the above code should fail if the graph has disconnected components containing more edges(Although it doesn't fail here. So we might be assuming a connected graph)."
},
{
"code": null,
"e": 2613,
"s": 2611,
"text": "0"
},
{
"code": null,
"e": 2626,
"s": 2613,
"text": "Manhar Joshi"
},
{
"code": null,
"e": 2652,
"s": 2626,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2654,
"s": 2652,
"text": "0"
},
{
"code": null,
"e": 2679,
"s": 2654,
"text": "Sandip Dutta9 months ago"
},
{
"code": null,
"e": 2692,
"s": 2679,
"text": "Sandip Dutta"
},
{
"code": null,
"e": 2756,
"s": 2692,
"text": "Code is successful even if we do not check Connected Components"
},
{
"code": null,
"e": 2878,
"s": 2756,
"text": "bool isEularCircuitExist(int V, vector<int>adj[]){(int i = 0; i < V; ++i) (adj[i].size() % 2) return false;return true;}"
},
{
"code": null,
"e": 3024,
"s": 2878,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 3060,
"s": 3024,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3070,
"s": 3060,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3080,
"s": 3070,
"text": "\nContest\n"
},
{
"code": null,
"e": 3143,
"s": 3080,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3291,
"s": 3143,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 3499,
"s": 3291,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 3605,
"s": 3499,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Create MySQL Database Using PHP | To create and delete a database you should have admin privilege. Its very easy to create a new MySQL database. PHP uses mysql_query function to create a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure.
bool mysql_query( sql, connection );
sql
Required - SQL query to create a database
connection
Optional - if not specified then last opend connection by mysql_connect will be used.
Try out following example to create a database −
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'CREATE Database test_db';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create database: ' . mysql_error());
}
echo "Database test_db created successfully\n";
mysql_close($conn);
?>
Once you establish a connection with a database server then it is required to select a particular database where your all the tables are associated.
This is required because there may be multiple databases residing on a single server and you can do work with a single database at a time.
PHP provides function mysql_select_db to select a database.It returns TRUE on success or FALSE on failure.
bool mysql_select_db( db_name, connection );
db_name
Required - Database name to be selected
connection
Optional - if not specified then last opend connection by mysql_connect will be used.
Here is the example showing you how to select a database.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db( 'test_db' );
mysql_close($conn);
?>
To create tables in the new database you need to do the same thing as creating the database. First create the SQL query to create the tables then execute the query using mysql_query() function.
Try out following example to create a table −
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'CREATE TABLE employee( '.
'emp_id INT NOT NULL AUTO_INCREMENT, '.
'emp_name VARCHAR(20) NOT NULL, '.
'emp_address VARCHAR(20) NOT NULL, '.
'emp_salary INT NOT NULL, '.
'join_date timestamp(14) NOT NULL, '.
'primary key ( emp_id ))';
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create table: ' . mysql_error());
}
echo "Table employee created successfully\n";
mysql_close($conn);
?>
In case you need to create many tables then its better to create a text file first and put all the SQL commands in that text file and then load that file into $sql variable and excute those commands.
Consider the following content in sql_query.txt file
CREATE TABLE employee(
emp_id INT NOT NULL AUTO_INCREMENT,
emp_name VARCHAR(20) NOT NULL,
emp_address VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL,
join_date timestamp(14) NOT NULL,
primary key ( emp_id ));
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$query_file = 'sql_query.txt';
$fp = fopen($query_file, 'r');
$sql = fread($fp, filesize($query_file));
fclose($fp);
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create table: ' . mysql_error());
}
echo "Table employee created successfully\n";
mysql_close($conn);
?>
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3010,
"s": 2757,
"text": "To create and delete a database you should have admin privilege. Its very easy to create a new MySQL database. PHP uses mysql_query function to create a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure."
},
{
"code": null,
"e": 3048,
"s": 3010,
"text": "bool mysql_query( sql, connection );\n"
},
{
"code": null,
"e": 3052,
"s": 3048,
"text": "sql"
},
{
"code": null,
"e": 3094,
"s": 3052,
"text": "Required - SQL query to create a database"
},
{
"code": null,
"e": 3105,
"s": 3094,
"text": "connection"
},
{
"code": null,
"e": 3191,
"s": 3105,
"text": "Optional - if not specified then last opend connection by mysql_connect will be used."
},
{
"code": null,
"e": 3240,
"s": 3191,
"text": "Try out following example to create a database −"
},
{
"code": null,
"e": 3745,
"s": 3240,
"text": "<?php\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n \n echo 'Connected successfully';\n \n $sql = 'CREATE Database test_db';\n $retval = mysql_query( $sql, $conn );\n \n if(! $retval ) {\n die('Could not create database: ' . mysql_error());\n }\n \n echo \"Database test_db created successfully\\n\";\n mysql_close($conn);\n?>"
},
{
"code": null,
"e": 3894,
"s": 3745,
"text": "Once you establish a connection with a database server then it is required to select a particular database where your all the tables are associated."
},
{
"code": null,
"e": 4033,
"s": 3894,
"text": "This is required because there may be multiple databases residing on a single server and you can do work with a single database at a time."
},
{
"code": null,
"e": 4140,
"s": 4033,
"text": "PHP provides function mysql_select_db to select a database.It returns TRUE on success or FALSE on failure."
},
{
"code": null,
"e": 4186,
"s": 4140,
"text": "bool mysql_select_db( db_name, connection );\n"
},
{
"code": null,
"e": 4194,
"s": 4186,
"text": "db_name"
},
{
"code": null,
"e": 4234,
"s": 4194,
"text": "Required - Database name to be selected"
},
{
"code": null,
"e": 4245,
"s": 4234,
"text": "connection"
},
{
"code": null,
"e": 4331,
"s": 4245,
"text": "Optional - if not specified then last opend connection by mysql_connect will be used."
},
{
"code": null,
"e": 4389,
"s": 4331,
"text": "Here is the example showing you how to select a database."
},
{
"code": null,
"e": 4709,
"s": 4389,
"text": "<?php\n $dbhost = 'localhost:3036';\n $dbuser = 'guest';\n $dbpass = 'guest123';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) { \n die('Could not connect: ' . mysql_error());\n }\n \n echo 'Connected successfully';\n \n mysql_select_db( 'test_db' );\n mysql_close($conn);\n \n?>"
},
{
"code": null,
"e": 4903,
"s": 4709,
"text": "To create tables in the new database you need to do the same thing as creating the database. First create the SQL query to create the tables then execute the query using mysql_query() function."
},
{
"code": null,
"e": 4949,
"s": 4903,
"text": "Try out following example to create a table −"
},
{
"code": null,
"e": 5737,
"s": 4949,
"text": "<?php\n \n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n \n echo 'Connected successfully';\n \n $sql = 'CREATE TABLE employee( '.\n 'emp_id INT NOT NULL AUTO_INCREMENT, '.\n 'emp_name VARCHAR(20) NOT NULL, '.\n 'emp_address VARCHAR(20) NOT NULL, '.\n 'emp_salary INT NOT NULL, '.\n 'join_date timestamp(14) NOT NULL, '.\n 'primary key ( emp_id ))';\n mysql_select_db('test_db');\n $retval = mysql_query( $sql, $conn );\n \n if(! $retval ) {\n die('Could not create table: ' . mysql_error());\n }\n \n echo \"Table employee created successfully\\n\";\n \n mysql_close($conn);\n?>"
},
{
"code": null,
"e": 5937,
"s": 5737,
"text": "In case you need to create many tables then its better to create a text file first and put all the SQL commands in that text file and then load that file into $sql variable and excute those commands."
},
{
"code": null,
"e": 5990,
"s": 5937,
"text": "Consider the following content in sql_query.txt file"
},
{
"code": null,
"e": 6223,
"s": 5990,
"text": "CREATE TABLE employee(\n emp_id INT NOT NULL AUTO_INCREMENT,\n emp_name VARCHAR(20) NOT NULL,\n emp_address VARCHAR(20) NOT NULL,\n emp_salary INT NOT NULL,\n join_date timestamp(14) NOT NULL,\n primary key ( emp_id ));\n"
},
{
"code": null,
"e": 6817,
"s": 6223,
"text": "<?php\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n \n $query_file = 'sql_query.txt';\n \n $fp = fopen($query_file, 'r');\n $sql = fread($fp, filesize($query_file));\n fclose($fp); \n \n mysql_select_db('test_db');\n $retval = mysql_query( $sql, $conn );\n \n if(! $retval ) {\n die('Could not create table: ' . mysql_error());\n }\n \n echo \"Table employee created successfully\\n\";\n mysql_close($conn);\n?>"
},
{
"code": null,
"e": 6850,
"s": 6817,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6866,
"s": 6850,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6899,
"s": 6866,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6910,
"s": 6899,
"text": " Syed Raza"
},
{
"code": null,
"e": 6945,
"s": 6910,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6962,
"s": 6945,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6995,
"s": 6962,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7010,
"s": 6995,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 7045,
"s": 7010,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 7057,
"s": 7045,
"text": " Azaz Patel"
},
{
"code": null,
"e": 7092,
"s": 7057,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7120,
"s": 7092,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 7127,
"s": 7120,
"text": " Print"
},
{
"code": null,
"e": 7138,
"s": 7127,
"text": " Add Notes"
}
]
|
Display all the dates for a particular month using NumPy - GeeksforGeeks | 07 Sep, 2021
In NumPy to display all the dates for a particular month, we can do it with the help of NumPy.arrange() pass the first parameter the particular month and the second parameter the next month and the third parameter is the datatype datetime64[D]. It will return all the dates for the particular month.
Syntax: numpy.arrange([start, ] stop, [step, ] dtype=None)
Parameters:
start : Start of interval
stop : End of interval
Step : Spacing between values
dtype : The type of the output array. If dtype is not given, infer the data type from the other input arguments.
Returns:
arrange : ndarray
Example 1#:
Python3
import numpy as np # dates of july 2020print(np.arrange('2012-07', '2020-08', dtype='datetime64[D]'))
Output:
[‘2012-07-01’ ‘2012-07-02’ ‘2012-07-03’ ... ‘2020-07-29’ ‘2020-07-30’ ‘2020-07-31’]
Example 2#:
Python3
import numpy as np # dates of september 2020print(np.arrange('2012-09', '2020-10', dtype='datetime64[D]'))
Output:
[‘2012-09-01’ ‘2012-09-02’ ‘2012-09-03’ ... ‘2020-09-28’ ‘2020-09-29’ ‘2020-09-30’]
Example 3#:
Python3
import numpy as np # dates of Feb 2020print(np.arrange('2012-02', '2020-03', dtype='datetime64[D]'))
Output:
[‘2012-02-01’ ‘2012-02-02’ ‘2012-02-03’ ... ‘2020-02-27’ ‘2020-02-28’ ‘2020-02-29’]
akshaysingh98088
Python numpy-program
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 24592,
"s": 24292,
"text": "In NumPy to display all the dates for a particular month, we can do it with the help of NumPy.arrange() pass the first parameter the particular month and the second parameter the next month and the third parameter is the datatype datetime64[D]. It will return all the dates for the particular month."
},
{
"code": null,
"e": 24651,
"s": 24592,
"text": "Syntax: numpy.arrange([start, ] stop, [step, ] dtype=None)"
},
{
"code": null,
"e": 24663,
"s": 24651,
"text": "Parameters:"
},
{
"code": null,
"e": 24689,
"s": 24663,
"text": "start : Start of interval"
},
{
"code": null,
"e": 24712,
"s": 24689,
"text": "stop : End of interval"
},
{
"code": null,
"e": 24742,
"s": 24712,
"text": "Step : Spacing between values"
},
{
"code": null,
"e": 24855,
"s": 24742,
"text": "dtype : The type of the output array. If dtype is not given, infer the data type from the other input arguments."
},
{
"code": null,
"e": 24864,
"s": 24855,
"text": "Returns:"
},
{
"code": null,
"e": 24882,
"s": 24864,
"text": "arrange : ndarray"
},
{
"code": null,
"e": 24894,
"s": 24882,
"text": "Example 1#:"
},
{
"code": null,
"e": 24902,
"s": 24894,
"text": "Python3"
},
{
"code": "import numpy as np # dates of july 2020print(np.arrange('2012-07', '2020-08', dtype='datetime64[D]'))",
"e": 25021,
"s": 24902,
"text": null
},
{
"code": null,
"e": 25029,
"s": 25021,
"text": "Output:"
},
{
"code": null,
"e": 25115,
"s": 25029,
"text": "[‘2012-07-01’ ‘2012-07-02’ ‘2012-07-03’ ... ‘2020-07-29’ ‘2020-07-30’ ‘2020-07-31’] "
},
{
"code": null,
"e": 25127,
"s": 25115,
"text": "Example 2#:"
},
{
"code": null,
"e": 25135,
"s": 25127,
"text": "Python3"
},
{
"code": "import numpy as np # dates of september 2020print(np.arrange('2012-09', '2020-10', dtype='datetime64[D]'))",
"e": 25258,
"s": 25135,
"text": null
},
{
"code": null,
"e": 25266,
"s": 25258,
"text": "Output:"
},
{
"code": null,
"e": 25352,
"s": 25266,
"text": "[‘2012-09-01’ ‘2012-09-02’ ‘2012-09-03’ ... ‘2020-09-28’ ‘2020-09-29’ ‘2020-09-30’] "
},
{
"code": null,
"e": 25364,
"s": 25352,
"text": "Example 3#:"
},
{
"code": null,
"e": 25372,
"s": 25364,
"text": "Python3"
},
{
"code": "import numpy as np # dates of Feb 2020print(np.arrange('2012-02', '2020-03', dtype='datetime64[D]'))",
"e": 25489,
"s": 25372,
"text": null
},
{
"code": null,
"e": 25497,
"s": 25489,
"text": "Output:"
},
{
"code": null,
"e": 25583,
"s": 25497,
"text": "[‘2012-02-01’ ‘2012-02-02’ ‘2012-02-03’ ... ‘2020-02-27’ ‘2020-02-28’ ‘2020-02-29’] "
},
{
"code": null,
"e": 25600,
"s": 25583,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 25621,
"s": 25600,
"text": "Python numpy-program"
},
{
"code": null,
"e": 25634,
"s": 25621,
"text": "Python-numpy"
},
{
"code": null,
"e": 25641,
"s": 25634,
"text": "Python"
},
{
"code": null,
"e": 25739,
"s": 25641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25771,
"s": 25739,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25827,
"s": 25771,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25869,
"s": 25827,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25911,
"s": 25869,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25933,
"s": 25911,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25972,
"s": 25933,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26003,
"s": 25972,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26058,
"s": 26003,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26087,
"s": 26058,
"text": "Create a directory in Python"
}
]
|
Magical String[Duplicate Problem] | Practice | GeeksforGeeks | You are given a string S, convert it into a magical string.
A string can be made into a magical string if the alphabets are swapped in the given manner: a->z or z->a, b->y or y->b, and so on.
Note: All the alphabets in the string are in lowercase.
Example 1:
Input:
S = varun
Output:
ezifm
Explanation:
Magical string of "varun"
will be "ezifm"
since v->e , a->z ,
r->i , u->f and n->m.
Example 2:
Input:
S = akshay
Output:
zphszb
Explanation:
Magical string of "akshay"
will be "zphszb"
since a->z , k->p , s->h ,
h->s , a->z and y->b.
Your Task:
You don't need to read input or print anything. Your task is to complete the function magicalString() which takes the string S and returns the magical string.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1<=Length of String<=100
0
shirsathsantoshi901 week ago
string magicalString(string S){ string s=""; for(int i=0;i<S.length();i++) { s+=('z'-S[i]+'a'); } return s; }
0
prishita2 weeks ago
Java Solution:
class Solution{
static String magicalString(String S){
// code here
String a="abcdefghijklmnopqrstuvwxyz";
char[] ch=S.toCharArray();
int ind;
for(int i=0;i<ch.length;i++){
ind=25-a.indexOf(ch[i]);
ch[i]=a.charAt(ind);
}
return String.valueOf(ch);
}
}
0
imabheek1 month ago
/*JAVA*/ String s = ""; for(int i = 0; i < S.length() ; i++) {s += (char)(219 - (int)(S.charAt(i)));} return s;
0
imranmbhd24121 month ago
string magicalString(string s){ for(int i = 0; i < s.size(); i++) { if(s[i] >= 'a' && s[i] <= 'z') { s[i] = 'z' - (s[i]-'a'); } else if (s[i] >= 'A' && s[i] <= 'Z') { s[i] = 'Z' - (s[i]-'A'); } else { continue; } } return s; }
+1
imohdalam1 month ago
Java | O(n)
class Solution{
static String magicalString(String S){
StringBuilder ans = new StringBuilder();
for(int i=0; i<S.length(); i++)
ans.append((char)('z' + 'a' - S.charAt(i)));
return ans.toString();
}
}
0
rahulraj943912 months ago
Java solution using StringBuilder and Math.abs()
static String magicalString(String S) {
StringBuilder sb = new StringBuilder("");
for (char cc : S.toCharArray())
sb.append((char) (122 - Math.abs(97 - cc)));
return sb.toString();
}
0
rahulraj943912 months ago
Java solution using Math.abs()
static String magicalString(String S) {
String temp = "";
for (char cc : S.toCharArray())
temp += (char) (122 - Math.abs(97 - cc));
return temp;
}
0
mridulbhaskarabc2 months ago
#Contributed By: Mridul Bhaskar
class Solution:
def magicalString (ob,S):
# code here
list_= list(S)
for i in range(len(list_)):
list_[i] = 122-ord(list_[i])+97
list_[i] = chr(list_[i])
list_ = "".join(str(i) for i in list_)
return list_
0
vikasnayakmmmut2 months ago
int n=S.length(); for(int i=0;i<n;i++) { if(S[i]<='m') { S[i]='a'+(25-(S[i]-'a')); } else { S[i]='z'-(25-('z'-S[i])); } } return S;
0
madhukartemba2 months ago
SIMPLE JAVA SOLUTION:
class Solution{
static String magicalString(String S){
int n = S.length();
String ans = "";
for(int i=0; i<n; i++)
{
ans += (char)('a'+'a'+25-S.charAt(i));
}
return ans;
}
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 434,
"s": 238,
"text": "You are given a string S, convert it into a magical string.\nA string can be made into a magical string if the alphabets are swapped in the given manner: a->z or z->a, b->y or y->b, and so on. \n "
},
{
"code": null,
"e": 490,
"s": 434,
"text": "Note: All the alphabets in the string are in lowercase."
},
{
"code": null,
"e": 503,
"s": 492,
"text": "Example 1:"
},
{
"code": null,
"e": 635,
"s": 503,
"text": "Input:\nS = varun\nOutput:\nezifm\nExplanation:\nMagical string of \"varun\" \nwill be \"ezifm\" \nsince v->e , a->z , \nr->i , u->f and n->m.\n"
},
{
"code": null,
"e": 648,
"s": 637,
"text": "Example 2:"
},
{
"code": null,
"e": 791,
"s": 648,
"text": "Input:\nS = akshay\nOutput:\nzphszb\nExplanation:\nMagical string of \"akshay\" \nwill be \"zphszb\" \nsince a->z , k->p , s->h , \nh->s , a->z and y->b.\n"
},
{
"code": null,
"e": 804,
"s": 793,
"text": "Your Task:"
},
{
"code": null,
"e": 963,
"s": 804,
"text": "You don't need to read input or print anything. Your task is to complete the function magicalString() which takes the string S and returns the magical string."
},
{
"code": null,
"e": 1029,
"s": 965,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\n "
},
{
"code": null,
"e": 1069,
"s": 1029,
"text": " \nConstraints:\n1<=Length of String<=100"
},
{
"code": null,
"e": 1073,
"s": 1071,
"text": "0"
},
{
"code": null,
"e": 1102,
"s": 1073,
"text": "shirsathsantoshi901 week ago"
},
{
"code": null,
"e": 1254,
"s": 1102,
"text": "string magicalString(string S){ string s=\"\"; for(int i=0;i<S.length();i++) { s+=('z'-S[i]+'a'); } return s; }"
},
{
"code": null,
"e": 1256,
"s": 1254,
"text": "0"
},
{
"code": null,
"e": 1276,
"s": 1256,
"text": "prishita2 weeks ago"
},
{
"code": null,
"e": 1291,
"s": 1276,
"text": "Java Solution:"
},
{
"code": null,
"e": 1631,
"s": 1291,
"text": "class Solution{\n static String magicalString(String S){\n // code here\n String a=\"abcdefghijklmnopqrstuvwxyz\";\n char[] ch=S.toCharArray();\n int ind;\n for(int i=0;i<ch.length;i++){\n ind=25-a.indexOf(ch[i]);\n ch[i]=a.charAt(ind);\n }\n return String.valueOf(ch);\n }\n}"
},
{
"code": null,
"e": 1633,
"s": 1631,
"text": "0"
},
{
"code": null,
"e": 1653,
"s": 1633,
"text": "imabheek1 month ago"
},
{
"code": null,
"e": 1787,
"s": 1653,
"text": "/*JAVA*/ String s = \"\"; for(int i = 0; i < S.length() ; i++) {s += (char)(219 - (int)(S.charAt(i)));} return s;"
},
{
"code": null,
"e": 1789,
"s": 1787,
"text": "0"
},
{
"code": null,
"e": 1814,
"s": 1789,
"text": "imranmbhd24121 month ago"
},
{
"code": null,
"e": 2150,
"s": 1816,
"text": "string magicalString(string s){ for(int i = 0; i < s.size(); i++) { if(s[i] >= 'a' && s[i] <= 'z') { s[i] = 'z' - (s[i]-'a'); } else if (s[i] >= 'A' && s[i] <= 'Z') { s[i] = 'Z' - (s[i]-'A'); } else { continue; } } return s; }"
},
{
"code": null,
"e": 2153,
"s": 2150,
"text": "+1"
},
{
"code": null,
"e": 2174,
"s": 2153,
"text": "imohdalam1 month ago"
},
{
"code": null,
"e": 2186,
"s": 2174,
"text": "Java | O(n)"
},
{
"code": null,
"e": 2459,
"s": 2186,
"text": "class Solution{\n static String magicalString(String S){\n \n StringBuilder ans = new StringBuilder();\n \n for(int i=0; i<S.length(); i++)\n ans.append((char)('z' + 'a' - S.charAt(i)));\n \n return ans.toString();\n }\n}"
},
{
"code": null,
"e": 2461,
"s": 2459,
"text": "0"
},
{
"code": null,
"e": 2487,
"s": 2461,
"text": "rahulraj943912 months ago"
},
{
"code": null,
"e": 2536,
"s": 2487,
"text": "Java solution using StringBuilder and Math.abs()"
},
{
"code": null,
"e": 2756,
"s": 2538,
"text": "static String magicalString(String S) {\n StringBuilder sb = new StringBuilder(\"\");\n for (char cc : S.toCharArray())\n sb.append((char) (122 - Math.abs(97 - cc)));\n return sb.toString();\n }"
},
{
"code": null,
"e": 2758,
"s": 2756,
"text": "0"
},
{
"code": null,
"e": 2784,
"s": 2758,
"text": "rahulraj943912 months ago"
},
{
"code": null,
"e": 2815,
"s": 2784,
"text": "Java solution using Math.abs()"
},
{
"code": null,
"e": 2999,
"s": 2817,
"text": "static String magicalString(String S) {\n String temp = \"\";\n for (char cc : S.toCharArray())\n temp += (char) (122 - Math.abs(97 - cc));\n return temp;\n }"
},
{
"code": null,
"e": 3001,
"s": 2999,
"text": "0"
},
{
"code": null,
"e": 3030,
"s": 3001,
"text": "mridulbhaskarabc2 months ago"
},
{
"code": null,
"e": 3062,
"s": 3030,
"text": "#Contributed By: Mridul Bhaskar"
},
{
"code": null,
"e": 3350,
"s": 3062,
"text": "class Solution:\n def magicalString (ob,S):\n # code here \n list_= list(S)\n for i in range(len(list_)):\n list_[i] = 122-ord(list_[i])+97\n list_[i] = chr(list_[i])\n \n list_ = \"\".join(str(i) for i in list_)\n return list_"
},
{
"code": null,
"e": 3354,
"s": 3352,
"text": "0"
},
{
"code": null,
"e": 3382,
"s": 3354,
"text": "vikasnayakmmmut2 months ago"
},
{
"code": null,
"e": 3626,
"s": 3382,
"text": "int n=S.length(); for(int i=0;i<n;i++) { if(S[i]<='m') { S[i]='a'+(25-(S[i]-'a')); } else { S[i]='z'-(25-('z'-S[i])); } } return S;"
},
{
"code": null,
"e": 3628,
"s": 3626,
"text": "0"
},
{
"code": null,
"e": 3654,
"s": 3628,
"text": "madhukartemba2 months ago"
},
{
"code": null,
"e": 3676,
"s": 3654,
"text": "SIMPLE JAVA SOLUTION:"
},
{
"code": null,
"e": 3945,
"s": 3676,
"text": "class Solution{\n static String magicalString(String S){\n int n = S.length();\n \n String ans = \"\";\n \n for(int i=0; i<n; i++)\n {\n ans += (char)('a'+'a'+25-S.charAt(i));\n }\n \n return ans;\n }\n}"
},
{
"code": null,
"e": 4091,
"s": 3945,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 4127,
"s": 4091,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4137,
"s": 4127,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4147,
"s": 4137,
"text": "\nContest\n"
},
{
"code": null,
"e": 4210,
"s": 4147,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4358,
"s": 4210,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 4566,
"s": 4358,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 4672,
"s": 4566,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
How to deal with error 'height' must be a vector or a matrix while creating barplot? | The error 'height' must be a vector or a matrix while creating barplot occurs when we provide data frame name instead of column names or read it with as.matrix. If we want to create bar plot for columns in a data frame then the data frame needs to be read as matrix.
For Example, if we have a data frame called df then we can create the barplot of columns in df by using the command given below −
barplot(as.matrix(df))
Following snippet creates a sample data frame −
df<-data.frame(x=rpois(20,2),y=rpois(20,5))
df
The following dataframe is created
x y
1 2 10
2 2 3
3 1 6
4 2 6
5 4 4
6 2 5
7 3 4
8 2 4
9 2 9
10 3 5
11 3 4
12 2 2
13 1 4
14 2 6
15 1 8
16 2 2
17 4 1
18 1 5
19 4 4
20 2 9
To create the bar plot with data frame name on the above created data frame, add the following code to the above snippet −
df<-data.frame(x=rpois(20,2),y=rpois(20,5))
barplot(df)
Error in barplot.default(df) : 'height' must be a vector or a matrix
The correct way to create the bar plot is as follows −
df<-data.frame(x=rpois(20,2),y=rpois(20,5))
barplot(as.matrix(df))
If you execute all the above given snippets as a single program, it generates the following Output − | [
{
"code": null,
"e": 1329,
"s": 1062,
"text": "The error 'height' must be a vector or a matrix while creating barplot occurs when we provide data frame name instead of column names or read it with as.matrix. If we want to create bar plot for columns in a data frame then the data frame needs to be read as matrix."
},
{
"code": null,
"e": 1459,
"s": 1329,
"text": "For Example, if we have a data frame called df then we can create the barplot of columns in df by using the command given below −"
},
{
"code": null,
"e": 1482,
"s": 1459,
"text": "barplot(as.matrix(df))"
},
{
"code": null,
"e": 1530,
"s": 1482,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 1577,
"s": 1530,
"text": "df<-data.frame(x=rpois(20,2),y=rpois(20,5))\ndf"
},
{
"code": null,
"e": 1612,
"s": 1577,
"text": "The following dataframe is created"
},
{
"code": null,
"e": 1761,
"s": 1612,
"text": " x y\n1 2 10\n2 2 3\n3 1 6\n4 2 6\n5 4 4\n6 2 5\n7 3 4\n8 2 4\n9 2 9\n10 3 5\n11 3 4\n12 2 2\n13 1 4\n14 2 6\n15 1 8\n16 2 2\n17 4 1\n18 1 5\n19 4 4\n20 2 9"
},
{
"code": null,
"e": 1884,
"s": 1761,
"text": "To create the bar plot with data frame name on the above created data frame, add the following code to the above snippet −"
},
{
"code": null,
"e": 2009,
"s": 1884,
"text": "df<-data.frame(x=rpois(20,2),y=rpois(20,5))\nbarplot(df)\nError in barplot.default(df) : 'height' must be a vector or a matrix"
},
{
"code": null,
"e": 2064,
"s": 2009,
"text": "The correct way to create the bar plot is as follows −"
},
{
"code": null,
"e": 2131,
"s": 2064,
"text": "df<-data.frame(x=rpois(20,2),y=rpois(20,5))\nbarplot(as.matrix(df))"
},
{
"code": null,
"e": 2232,
"s": 2131,
"text": "If you execute all the above given snippets as a single program, it generates the following Output −"
}
]
|
CakePHP - Update a Record | To update a record in database, we first need to get hold of a table using TableRegistry class. We can fetch the instance out of registry using the get() method. The get() method will take the name of the database table as an argument. Now, this new instance is used to get particular record that we want to update.
Call the get() method with this new instance, and pass the primary key to find a record, which will be saved in another instance. Use this instance, to set new values that you want to update and then, finally call the save() method with the TableRegistry class’s instance to update record.
Make changes in the config/routes.php file as shown in the following code.
<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
$builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
'httpOnly' => true,
]));
$builder->applyMiddleware('csrf');
//$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
$builder->connect('/users/edit', ['controller' => 'Users', 'action' => 'edit']);
$builder->fallbacks();
});
Create a UsersController.php file at src/Controller/UsersController.php. Copy the following code in the controller file.
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
class UsersController extends AppController{
public function index(){
$users = TableRegistry::get('users');
$query = $users->find();
$this->set('results',$query);
}
public function edit($id){
if($this->request->is('post')){
$username = $this->request->getData('username');
$password = $this->request->getData('password');
$users_table = TableRegistry::get('users');
$users = $users_table->get($id);
$users->username = $username;
$users->password = $password;
if($users_table->save($users))
echo "User is udpated";
$this->setAction('index');
} else {
$users_table = TableRegistry::get('users')->find();
$users = $users_table->where(['id'=>$id])->first();
$this->set('username',$users->username);
$this->set('password',$users->password);
$this->set('id',$id);
}
}
}
?>
Create a directory Users at src/Template, ignore if already created, and under that directory create a view called index.php. Copy the following code in that file.
<a href="add">Add User</a>
<table>
<tr>
<td>ID</td>
<td>Username</td>
<td>Password</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php
foreach ($results as $row):
echo "<tr><td>".$row->id."</td>";
echo "<td>".$row->username."</td>";
echo "<td>".$row->password."</td>";
echo "<td><a href='".$this->Url->build(["controller" => "Users","action" => "edit",$row->id])."'>Edit</a></td>";
echo "<td><a href='".$this->Url->build(["controller" => "Users","action" => "delete",$row->id])."'>Delete</a></td></tr>";
endforeach;
?>
</table>
Create another View file under the Users directory called edit.php and copy the following code in it.
<?php
echo $this->Form->create(NULL,array('url'=>'/users/edit/'.$id));
echo $this->Form->control('username',['value'=>$username]);
echo $this->Form->control('password',['value'=>$password]);
echo $this->Form->button('Submit');
echo $this->Form->end();
?>
Execute the above example by visiting the following URL and click on Edit link to edit record.
http://localhost/cakephp4/users
After visiting the above URL, it will display the records in users table as shown below −
Click on Edit button and it will display you following screen −
Now, we will update the name Virat to Virat123 and submit the details. The next screen displayed will be as follows −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2558,
"s": 2242,
"text": "To update a record in database, we first need to get hold of a table using TableRegistry class. We can fetch the instance out of registry using the get() method. The get() method will take the name of the database table as an argument. Now, this new instance is used to get particular record that we want to update."
},
{
"code": null,
"e": 2848,
"s": 2558,
"text": "Call the get() method with this new instance, and pass the primary key to find a record, which will be saved in another instance. Use this instance, to set new values that you want to update and then, finally call the save() method with the TableRegistry class’s instance to update record."
},
{
"code": null,
"e": 2923,
"s": 2848,
"text": "Make changes in the config/routes.php file as shown in the following code."
},
{
"code": null,
"e": 3489,
"s": 2923,
"text": "<?php\nuse Cake\\Http\\Middleware\\CsrfProtectionMiddleware;\nuse Cake\\Routing\\Route\\DashedRoute;\nuse Cake\\Routing\\RouteBuilder;\n$routes->setRouteClass(DashedRoute::class);\n$routes->scope('/', function (RouteBuilder $builder) {\n $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([\n 'httpOnly' => true,\n ]));\n $builder->applyMiddleware('csrf');\n //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);\n $builder->connect('/users/edit', ['controller' => 'Users', 'action' => 'edit']);\n $builder->fallbacks();\n});"
},
{
"code": null,
"e": 3610,
"s": 3489,
"text": "Create a UsersController.php file at src/Controller/UsersController.php. Copy the following code in the controller file."
},
{
"code": null,
"e": 4774,
"s": 3610,
"text": "<?php\n namespace App\\Controller;\n use App\\Controller\\AppController;\n use Cake\\ORM\\TableRegistry;\n use Cake\\Datasource\\ConnectionManager;\n class UsersController extends AppController{\n public function index(){\n $users = TableRegistry::get('users');\n $query = $users->find();\n $this->set('results',$query);\n }\n public function edit($id){\n if($this->request->is('post')){\n $username = $this->request->getData('username');\n $password = $this->request->getData('password');\n $users_table = TableRegistry::get('users');\n $users = $users_table->get($id);\n $users->username = $username;\n $users->password = $password;\n if($users_table->save($users))\n echo \"User is udpated\";\n $this->setAction('index');\n } else {\n $users_table = TableRegistry::get('users')->find();\n $users = $users_table->where(['id'=>$id])->first();\n $this->set('username',$users->username);\n $this->set('password',$users->password);\n $this->set('id',$id);\n }\n }\n }\n?>"
},
{
"code": null,
"e": 4938,
"s": 4774,
"text": "Create a directory Users at src/Template, ignore if already created, and under that directory create a view called index.php. Copy the following code in that file."
},
{
"code": null,
"e": 5530,
"s": 4938,
"text": "<a href=\"add\">Add User</a>\n<table>\n <tr>\n <td>ID</td>\n <td>Username</td>\n <td>Password</td>\n <td>Edit</td>\n <td>Delete</td>\n </tr>\n <?php\n foreach ($results as $row):\n echo \"<tr><td>\".$row->id.\"</td>\";\n echo \"<td>\".$row->username.\"</td>\";\n echo \"<td>\".$row->password.\"</td>\";\n echo \"<td><a href='\".$this->Url->build([\"controller\" => \"Users\",\"action\" => \"edit\",$row->id]).\"'>Edit</a></td>\";\n echo \"<td><a href='\".$this->Url->build([\"controller\" => \"Users\",\"action\" => \"delete\",$row->id]).\"'>Delete</a></td></tr>\";\n endforeach;\n ?>\n</table>"
},
{
"code": null,
"e": 5632,
"s": 5530,
"text": "Create another View file under the Users directory called edit.php and copy the following code in it."
},
{
"code": null,
"e": 5902,
"s": 5632,
"text": "<?php\n echo $this->Form->create(NULL,array('url'=>'/users/edit/'.$id));\n echo $this->Form->control('username',['value'=>$username]);\n echo $this->Form->control('password',['value'=>$password]);\n echo $this->Form->button('Submit');\n echo $this->Form->end();\n?>"
},
{
"code": null,
"e": 5997,
"s": 5902,
"text": "Execute the above example by visiting the following URL and click on Edit link to edit record."
},
{
"code": null,
"e": 6029,
"s": 5997,
"text": "http://localhost/cakephp4/users"
},
{
"code": null,
"e": 6119,
"s": 6029,
"text": "After visiting the above URL, it will display the records in users table as shown below −"
},
{
"code": null,
"e": 6183,
"s": 6119,
"text": "Click on Edit button and it will display you following screen −"
},
{
"code": null,
"e": 6301,
"s": 6183,
"text": "Now, we will update the name Virat to Virat123 and submit the details. The next screen displayed will be as follows −"
},
{
"code": null,
"e": 6308,
"s": 6301,
"text": " Print"
},
{
"code": null,
"e": 6319,
"s": 6308,
"text": " Add Notes"
}
]
|
AWT MenuBar Class | The MenuBar class provides menu bar bound to a frame and is platform specific.
Following is the declaration for java.awt.MenuBar class:
public class MenuBar
extends MenuComponent
implements MenuContainer, Accessible
MenuBar()
Creates a new menu bar.
void dispatchEvent(AWTEvent e)
Menu add(Menu m)
Adds the specified menu to the menu bar.
void addNotify()
Creates the menu bar's peer.
int countMenus()
Deprecated. As of JDK version 1.1, replaced by getMenuCount().
void deleteShortcut(MenuShortcut s)
Deletes the specified menu shortcut.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this MenuBar.
Menu getHelpMenu()
Gets the help menu on the menu bar.
Menu getMenu(int i)
Gets the specified menu.
int getMenuCount()
Gets the number of menus on the menu bar.
MenuItem getShortcutMenuItem(MenuShortcut s)
Gets the instance of MenuItem associated with the specified MenuShortcut object, or null if none of the menu items being managed by this menu bar is associated with the specified menu shortcut.
void remove(int index)
Removes the menu located at the specified index from this menu bar.
void remove(MenuComponent m)
Removes the specified menu component from this menu bar.
void removeNotify()
Removes the menu bar's peer.
void setHelpMenu(Menu m)
Sets the specified menu to be this menu bar's help menu.
Enumeration shortcuts()
Gets an enumeration of all menu shortcuts this menu bar is managing.
This class inherits methods from the following classes:
java.awt.MenuComponent
java.awt.MenuComponent
java.lang.Object
java.lang.Object
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AWTMenuDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AWTMenuDemo(){
prepareGUI();
}
public static void main(String[] args){
AWTMenuDemo awtMenuDemo = new AWTMenuDemo();
awtMenuDemo.showMenuDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showMenuDemo(){
//create a menu bar
final MenuBar menuBar = new MenuBar();
//create menus
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
final Menu aboutMenu = new Menu("About");
//create menu items
MenuItem newMenuItem =
new MenuItem("New",new MenuShortcut(KeyEvent.VK_N));
newMenuItem.setActionCommand("New");
MenuItem openMenuItem = new MenuItem("Open");
openMenuItem.setActionCommand("Open");
MenuItem saveMenuItem = new MenuItem("Save");
saveMenuItem.setActionCommand("Save");
MenuItem exitMenuItem = new MenuItem("Exit");
exitMenuItem.setActionCommand("Exit");
MenuItem cutMenuItem = new MenuItem("Cut");
cutMenuItem.setActionCommand("Cut");
MenuItem copyMenuItem = new MenuItem("Copy");
copyMenuItem.setActionCommand("Copy");
MenuItem pasteMenuItem = new MenuItem("Paste");
pasteMenuItem.setActionCommand("Paste");
MenuItemListener menuItemListener = new MenuItemListener();
newMenuItem.addActionListener(menuItemListener);
openMenuItem.addActionListener(menuItemListener);
saveMenuItem.addActionListener(menuItemListener);
exitMenuItem.addActionListener(menuItemListener);
cutMenuItem.addActionListener(menuItemListener);
copyMenuItem.addActionListener(menuItemListener);
pasteMenuItem.addActionListener(menuItemListener);
final CheckboxMenuItem showWindowMenu =
new CheckboxMenuItem("Show About", true);
showWindowMenu.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(showWindowMenu.getState()){
menuBar.add(aboutMenu);
}else{
menuBar.remove(aboutMenu);
}
}
});
//add menu items to menus
fileMenu.add(newMenuItem);
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(showWindowMenu);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
//add menu to menubar
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(aboutMenu);
//add menubar to the frame
mainFrame.setMenuBar(menuBar);
mainFrame.setVisible(true);
}
class MenuItemListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
statusLabel.setText(e.getActionCommand()
+ " MenuItem clicked.");
}
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AWTMenuDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AWTMenuDemo
Verify the following output
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1826,
"s": 1747,
"text": "The MenuBar class provides menu bar bound to a frame and is platform specific."
},
{
"code": null,
"e": 1883,
"s": 1826,
"text": "Following is the declaration for java.awt.MenuBar class:"
},
{
"code": null,
"e": 1972,
"s": 1883,
"text": "public class MenuBar\n extends MenuComponent\n implements MenuContainer, Accessible"
},
{
"code": null,
"e": 1983,
"s": 1972,
"text": "MenuBar() "
},
{
"code": null,
"e": 2007,
"s": 1983,
"text": "Creates a new menu bar."
},
{
"code": null,
"e": 2039,
"s": 2007,
"text": "void dispatchEvent(AWTEvent e) "
},
{
"code": null,
"e": 2057,
"s": 2039,
"text": "Menu add(Menu m) "
},
{
"code": null,
"e": 2098,
"s": 2057,
"text": "Adds the specified menu to the menu bar."
},
{
"code": null,
"e": 2116,
"s": 2098,
"text": "void addNotify() "
},
{
"code": null,
"e": 2145,
"s": 2116,
"text": "Creates the menu bar's peer."
},
{
"code": null,
"e": 2163,
"s": 2145,
"text": "int countMenus() "
},
{
"code": null,
"e": 2226,
"s": 2163,
"text": "Deprecated. As of JDK version 1.1, replaced by getMenuCount()."
},
{
"code": null,
"e": 2263,
"s": 2226,
"text": "void deleteShortcut(MenuShortcut s) "
},
{
"code": null,
"e": 2300,
"s": 2263,
"text": "Deletes the specified menu shortcut."
},
{
"code": null,
"e": 2342,
"s": 2300,
"text": "AccessibleContext getAccessibleContext() "
},
{
"code": null,
"e": 2399,
"s": 2342,
"text": "Gets the AccessibleContext associated with this MenuBar."
},
{
"code": null,
"e": 2419,
"s": 2399,
"text": "Menu getHelpMenu() "
},
{
"code": null,
"e": 2455,
"s": 2419,
"text": "Gets the help menu on the menu bar."
},
{
"code": null,
"e": 2475,
"s": 2455,
"text": "Menu getMenu(int i)"
},
{
"code": null,
"e": 2500,
"s": 2475,
"text": "Gets the specified menu."
},
{
"code": null,
"e": 2520,
"s": 2500,
"text": "int getMenuCount() "
},
{
"code": null,
"e": 2562,
"s": 2520,
"text": "Gets the number of menus on the menu bar."
},
{
"code": null,
"e": 2608,
"s": 2562,
"text": "MenuItem getShortcutMenuItem(MenuShortcut s) "
},
{
"code": null,
"e": 2802,
"s": 2608,
"text": "Gets the instance of MenuItem associated with the specified MenuShortcut object, or null if none of the menu items being managed by this menu bar is associated with the specified menu shortcut."
},
{
"code": null,
"e": 2826,
"s": 2802,
"text": "void remove(int index) "
},
{
"code": null,
"e": 2894,
"s": 2826,
"text": "Removes the menu located at the specified index from this menu bar."
},
{
"code": null,
"e": 2924,
"s": 2894,
"text": "void remove(MenuComponent m) "
},
{
"code": null,
"e": 2981,
"s": 2924,
"text": "Removes the specified menu component from this menu bar."
},
{
"code": null,
"e": 3002,
"s": 2981,
"text": "void removeNotify() "
},
{
"code": null,
"e": 3031,
"s": 3002,
"text": "Removes the menu bar's peer."
},
{
"code": null,
"e": 3057,
"s": 3031,
"text": "void setHelpMenu(Menu m) "
},
{
"code": null,
"e": 3114,
"s": 3057,
"text": "Sets the specified menu to be this menu bar's help menu."
},
{
"code": null,
"e": 3139,
"s": 3114,
"text": "Enumeration shortcuts() "
},
{
"code": null,
"e": 3208,
"s": 3139,
"text": "Gets an enumeration of all menu shortcuts this menu bar is managing."
},
{
"code": null,
"e": 3264,
"s": 3208,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 3287,
"s": 3264,
"text": "java.awt.MenuComponent"
},
{
"code": null,
"e": 3310,
"s": 3287,
"text": "java.awt.MenuComponent"
},
{
"code": null,
"e": 3327,
"s": 3310,
"text": "java.lang.Object"
},
{
"code": null,
"e": 3344,
"s": 3327,
"text": "java.lang.Object"
},
{
"code": null,
"e": 3458,
"s": 3344,
"text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 7323,
"s": 3458,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AWTMenuDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AWTMenuDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AWTMenuDemo awtMenuDemo = new AWTMenuDemo(); \n awtMenuDemo.showMenuDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showMenuDemo(){\n //create a menu bar\n final MenuBar menuBar = new MenuBar();\n\n //create menus\n Menu fileMenu = new Menu(\"File\");\n Menu editMenu = new Menu(\"Edit\"); \n final Menu aboutMenu = new Menu(\"About\");\n\n //create menu items\n MenuItem newMenuItem = \n new MenuItem(\"New\",new MenuShortcut(KeyEvent.VK_N));\n newMenuItem.setActionCommand(\"New\");\n\n MenuItem openMenuItem = new MenuItem(\"Open\");\n openMenuItem.setActionCommand(\"Open\");\n\n MenuItem saveMenuItem = new MenuItem(\"Save\");\n saveMenuItem.setActionCommand(\"Save\");\n\n MenuItem exitMenuItem = new MenuItem(\"Exit\");\n exitMenuItem.setActionCommand(\"Exit\");\n\n MenuItem cutMenuItem = new MenuItem(\"Cut\");\n cutMenuItem.setActionCommand(\"Cut\");\n\n MenuItem copyMenuItem = new MenuItem(\"Copy\");\n copyMenuItem.setActionCommand(\"Copy\");\n\n MenuItem pasteMenuItem = new MenuItem(\"Paste\");\n pasteMenuItem.setActionCommand(\"Paste\");\n \n MenuItemListener menuItemListener = new MenuItemListener();\n\n newMenuItem.addActionListener(menuItemListener);\n openMenuItem.addActionListener(menuItemListener);\n saveMenuItem.addActionListener(menuItemListener);\n exitMenuItem.addActionListener(menuItemListener);\n cutMenuItem.addActionListener(menuItemListener);\n copyMenuItem.addActionListener(menuItemListener);\n pasteMenuItem.addActionListener(menuItemListener);\n\n final CheckboxMenuItem showWindowMenu = \n new CheckboxMenuItem(\"Show About\", true);\n showWindowMenu.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent e) {\n if(showWindowMenu.getState()){\n menuBar.add(aboutMenu);\n }else{\n menuBar.remove(aboutMenu);\n }\n }\n });\n\n //add menu items to menus\n fileMenu.add(newMenuItem);\n fileMenu.add(openMenuItem);\n fileMenu.add(saveMenuItem);\n fileMenu.addSeparator();\n fileMenu.add(showWindowMenu);\n fileMenu.addSeparator();\n fileMenu.add(exitMenuItem);\n\n editMenu.add(cutMenuItem);\n editMenu.add(copyMenuItem);\n editMenu.add(pasteMenuItem);\n\n //add menu to menubar\n menuBar.add(fileMenu);\n menuBar.add(editMenu);\n menuBar.add(aboutMenu);\n\n //add menubar to the frame\n mainFrame.setMenuBar(menuBar);\n mainFrame.setVisible(true); \n }\n\n class MenuItemListener implements ActionListener {\n public void actionPerformed(ActionEvent e) { \n statusLabel.setText(e.getActionCommand() \n + \" MenuItem clicked.\");\n } \n }\n}"
},
{
"code": null,
"e": 7414,
"s": 7323,
"text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command."
},
{
"code": null,
"e": 7467,
"s": 7414,
"text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AWTMenuDemo.java"
},
{
"code": null,
"e": 7564,
"s": 7467,
"text": "If no error comes that means compilation is successful. Run the program using following command."
},
{
"code": null,
"e": 7611,
"s": 7564,
"text": "D:\\AWT>java com.tutorialspoint.gui.AWTMenuDemo"
},
{
"code": null,
"e": 7639,
"s": 7611,
"text": "Verify the following output"
},
{
"code": null,
"e": 7672,
"s": 7639,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7680,
"s": 7672,
"text": " EduOLC"
},
{
"code": null,
"e": 7687,
"s": 7680,
"text": " Print"
},
{
"code": null,
"e": 7698,
"s": 7687,
"text": " Add Notes"
}
]
|
How to prevent Singleton Pattern from Reflection, Serialization and Cloning? | 05 Aug, 2021
Prerequisite: Singleton Pattern
In this article, we will see that what are various concepts which can break singleton property of a class and how to avoid them. There are mainly 3 concepts which can break singleton property of a class. Let’s discuss them one by one.
Reflection: Reflection can be caused to destroy singleton property of singleton class, as shown in following example:JavaJava// Java code to explain effect of Reflection// on Singleton property import java.lang.reflect.Constructor; // Singleton classclass Singleton { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG { public static void main(String[] args) { Singleton instance1 = Singleton.instance; Singleton instance2 = null; try { Constructor[] constructors = Singleton.class.getDeclaredConstructors(); for (Constructor constructor : constructors) { // Below code will destroy the singleton pattern constructor.setAccessible(true); instance2 = (Singleton) constructor.newInstance(); break; } } catch (Exception e) { e.printStackTrace(); } System.out.println("instance1.hashCode():- " + instance1.hashCode()); System.out.println("instance2.hashCode():- " + instance2.hashCode()); }}Output:-
instance1.hashCode():- 366712642
instance2.hashCode():- 1829164700
After running this class, you will see that hashCodes are different that means, 2 objects of same class are created and singleton pattern has been destroyed.Overcome reflection issue: To overcome issue raised by reflection, enums are used because java ensures internally that enum value is instantiated only once. Since java Enums are globally accessible, they can be used for singletons. Its only drawback is that it is not flexible i.e it does not allow lazy initialization.JavaJava//Java program for Enum type singletonpublic enum Singleton { INSTANCE;}As enums don’t have any constructor so it is not possible for Reflection to utilize it. Enums have their by-default constructor, we can’t invoke them by ourself. JVM handles the creation and invocation of enum constructors internally. As enums don’t give their constructor definition to the program, it is not possible for us to access them by Reflection also. Hence, reflection can’t break singleton property in case of enums.Serialization:- Serialization can also cause breakage of singleton property of singleton classes. Serialization is used to convert an object of byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class. Then if you de-serialize that object it will create a new instance and hence break the singleton pattern.JavaJava// Java code to explain effect of // Serialization on singleton classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInput;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable; class Singleton implements Serializable { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG { public static void main(String[] args) { try { Singleton instance1 = Singleton.instance; ObjectOutput out = new ObjectOutputStream(new FileOutputStream("file.text")); out.writeObject(instance1); out.close(); // deserialize from file to object ObjectInput in = new ObjectInputStream(new FileInputStream("file.text")); Singleton instance2 = (Singleton) in.readObject(); in.close(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); } catch (Exception e) { e.printStackTrace(); } }}Output:-
instance1 hashCode:- 1550089733
instance2 hashCode:- 865113938
As you can see, hashCode of both instances is different, hence there are 2 objects of a singleton class. Thus, the class is no more singleton.Overcome serialization issue:- To overcome this issue, we have to implement method readResolve() method.JavaJava// Java code to remove the effect of // Serialization on singleton classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInput;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable; class Singleton implements Serializable { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } // implement readResolve method protected Object readResolve() { return instance; }} public class GFG { public static void main(String[] args) { try { Singleton instance1 = Singleton.instance; ObjectOutput out = new ObjectOutputStream(new FileOutputStream("file.text")); out.writeObject(instance1); out.close(); // deserialize from file to object ObjectInput in = new ObjectInputStream(new FileInputStream("file.text")); Singleton instance2 = (Singleton) in.readObject(); in.close(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); } catch (Exception e) { e.printStackTrace(); } }}Output:-
instance1 hashCode:- 1550089733
instance2 hashCode:- 1550089733
Above both hashcodes are same hence no other instance is created.Cloning: Cloning is a concept to create duplicate objects. Using clone we can create copy of object. Suppose, we create clone of a singleton object, then it will create a copy that is there are two instances of a singleton class, hence the class is no more singleton.JavaJava// Java code to explain cloning // issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); }}Output :-
instance1 hashCode:- 366712642
instance2 hashCode:- 1829164700
Two different hashCode means there are 2 different objects of singleton class.Overcome Cloning issue:- To overcome this issue, override clone() method and throw an exception from clone method that is CloneNotSupportedException. Now whenever user will try to create clone of singleton object, it will throw exception and hence our class remains singleton.JavaJava// Java code to explain overcome // cloning issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); }}Output:-
Exception in thread "main" java.lang.CloneNotSupportedException
at GFG.Singleton.clone(GFG.java:29)
at GFG.GFG.main(GFG.java:38)
Now we have stopped user to create clone of singleton class. If you don;t want to throw exception you can also return the same instance from clone method.JavaJava// Java code to explain overcome // cloning issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } @Override protected Object clone() throws CloneNotSupportedException { return instance; }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); }}Output:-
instance1 hashCode:- 366712642
instance2 hashCode:- 366712642
Now, as hashcode of both the instances is same that means they represent a single instance.
Reflection: Reflection can be caused to destroy singleton property of singleton class, as shown in following example:JavaJava// Java code to explain effect of Reflection// on Singleton property import java.lang.reflect.Constructor; // Singleton classclass Singleton { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG { public static void main(String[] args) { Singleton instance1 = Singleton.instance; Singleton instance2 = null; try { Constructor[] constructors = Singleton.class.getDeclaredConstructors(); for (Constructor constructor : constructors) { // Below code will destroy the singleton pattern constructor.setAccessible(true); instance2 = (Singleton) constructor.newInstance(); break; } } catch (Exception e) { e.printStackTrace(); } System.out.println("instance1.hashCode():- " + instance1.hashCode()); System.out.println("instance2.hashCode():- " + instance2.hashCode()); }}Output:-
instance1.hashCode():- 366712642
instance2.hashCode():- 1829164700
After running this class, you will see that hashCodes are different that means, 2 objects of same class are created and singleton pattern has been destroyed.Overcome reflection issue: To overcome issue raised by reflection, enums are used because java ensures internally that enum value is instantiated only once. Since java Enums are globally accessible, they can be used for singletons. Its only drawback is that it is not flexible i.e it does not allow lazy initialization.JavaJava//Java program for Enum type singletonpublic enum Singleton { INSTANCE;}As enums don’t have any constructor so it is not possible for Reflection to utilize it. Enums have their by-default constructor, we can’t invoke them by ourself. JVM handles the creation and invocation of enum constructors internally. As enums don’t give their constructor definition to the program, it is not possible for us to access them by Reflection also. Hence, reflection can’t break singleton property in case of enums.
Java
// Java code to explain effect of Reflection// on Singleton property import java.lang.reflect.Constructor; // Singleton classclass Singleton { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG { public static void main(String[] args) { Singleton instance1 = Singleton.instance; Singleton instance2 = null; try { Constructor[] constructors = Singleton.class.getDeclaredConstructors(); for (Constructor constructor : constructors) { // Below code will destroy the singleton pattern constructor.setAccessible(true); instance2 = (Singleton) constructor.newInstance(); break; } } catch (Exception e) { e.printStackTrace(); } System.out.println("instance1.hashCode():- " + instance1.hashCode()); System.out.println("instance2.hashCode():- " + instance2.hashCode()); }}
Output:-
instance1.hashCode():- 366712642
instance2.hashCode():- 1829164700
After running this class, you will see that hashCodes are different that means, 2 objects of same class are created and singleton pattern has been destroyed.
Overcome reflection issue: To overcome issue raised by reflection, enums are used because java ensures internally that enum value is instantiated only once. Since java Enums are globally accessible, they can be used for singletons. Its only drawback is that it is not flexible i.e it does not allow lazy initialization.
Java
//Java program for Enum type singletonpublic enum Singleton { INSTANCE;}
Serialization:- Serialization can also cause breakage of singleton property of singleton classes. Serialization is used to convert an object of byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class. Then if you de-serialize that object it will create a new instance and hence break the singleton pattern.JavaJava// Java code to explain effect of // Serialization on singleton classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInput;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable; class Singleton implements Serializable { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG { public static void main(String[] args) { try { Singleton instance1 = Singleton.instance; ObjectOutput out = new ObjectOutputStream(new FileOutputStream("file.text")); out.writeObject(instance1); out.close(); // deserialize from file to object ObjectInput in = new ObjectInputStream(new FileInputStream("file.text")); Singleton instance2 = (Singleton) in.readObject(); in.close(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); } catch (Exception e) { e.printStackTrace(); } }}Output:-
instance1 hashCode:- 1550089733
instance2 hashCode:- 865113938
As you can see, hashCode of both instances is different, hence there are 2 objects of a singleton class. Thus, the class is no more singleton.Overcome serialization issue:- To overcome this issue, we have to implement method readResolve() method.JavaJava// Java code to remove the effect of // Serialization on singleton classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInput;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable; class Singleton implements Serializable { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } // implement readResolve method protected Object readResolve() { return instance; }} public class GFG { public static void main(String[] args) { try { Singleton instance1 = Singleton.instance; ObjectOutput out = new ObjectOutputStream(new FileOutputStream("file.text")); out.writeObject(instance1); out.close(); // deserialize from file to object ObjectInput in = new ObjectInputStream(new FileInputStream("file.text")); Singleton instance2 = (Singleton) in.readObject(); in.close(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); } catch (Exception e) { e.printStackTrace(); } }}Output:-
instance1 hashCode:- 1550089733
instance2 hashCode:- 1550089733
Above both hashcodes are same hence no other instance is created.
Java
// Java code to explain effect of // Serialization on singleton classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInput;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable; class Singleton implements Serializable { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG { public static void main(String[] args) { try { Singleton instance1 = Singleton.instance; ObjectOutput out = new ObjectOutputStream(new FileOutputStream("file.text")); out.writeObject(instance1); out.close(); // deserialize from file to object ObjectInput in = new ObjectInputStream(new FileInputStream("file.text")); Singleton instance2 = (Singleton) in.readObject(); in.close(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); } catch (Exception e) { e.printStackTrace(); } }}
Output:-
instance1 hashCode:- 1550089733
instance2 hashCode:- 865113938
As you can see, hashCode of both instances is different, hence there are 2 objects of a singleton class. Thus, the class is no more singleton.
Overcome serialization issue:- To overcome this issue, we have to implement method readResolve() method.
Java
// Java code to remove the effect of // Serialization on singleton classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInput;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable; class Singleton implements Serializable { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } // implement readResolve method protected Object readResolve() { return instance; }} public class GFG { public static void main(String[] args) { try { Singleton instance1 = Singleton.instance; ObjectOutput out = new ObjectOutputStream(new FileOutputStream("file.text")); out.writeObject(instance1); out.close(); // deserialize from file to object ObjectInput in = new ObjectInputStream(new FileInputStream("file.text")); Singleton instance2 = (Singleton) in.readObject(); in.close(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); } catch (Exception e) { e.printStackTrace(); } }}
Output:-
instance1 hashCode:- 1550089733
instance2 hashCode:- 1550089733
Above both hashcodes are same hence no other instance is created.
Cloning: Cloning is a concept to create duplicate objects. Using clone we can create copy of object. Suppose, we create clone of a singleton object, then it will create a copy that is there are two instances of a singleton class, hence the class is no more singleton.JavaJava// Java code to explain cloning // issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); }}Output :-
instance1 hashCode:- 366712642
instance2 hashCode:- 1829164700
Two different hashCode means there are 2 different objects of singleton class.Overcome Cloning issue:- To overcome this issue, override clone() method and throw an exception from clone method that is CloneNotSupportedException. Now whenever user will try to create clone of singleton object, it will throw exception and hence our class remains singleton.JavaJava// Java code to explain overcome // cloning issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); }}Output:-
Exception in thread "main" java.lang.CloneNotSupportedException
at GFG.Singleton.clone(GFG.java:29)
at GFG.GFG.main(GFG.java:38)
Now we have stopped user to create clone of singleton class. If you don;t want to throw exception you can also return the same instance from clone method.JavaJava// Java code to explain overcome // cloning issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } @Override protected Object clone() throws CloneNotSupportedException { return instance; }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); }}Output:-
instance1 hashCode:- 366712642
instance2 hashCode:- 366712642
Now, as hashcode of both the instances is same that means they represent a single instance.
Java
// Java code to explain cloning // issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); }}
Output :-
instance1 hashCode:- 366712642
instance2 hashCode:- 1829164700
Two different hashCode means there are 2 different objects of singleton class.
Overcome Cloning issue:- To overcome this issue, override clone() method and throw an exception from clone method that is CloneNotSupportedException. Now whenever user will try to create clone of singleton object, it will throw exception and hence our class remains singleton.
Java
// Java code to explain overcome // cloning issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); }}
Output:-
Exception in thread "main" java.lang.CloneNotSupportedException
at GFG.Singleton.clone(GFG.java:29)
at GFG.GFG.main(GFG.java:38)
Now we have stopped user to create clone of singleton class. If you don;t want to throw exception you can also return the same instance from clone method.
Java
// Java code to explain overcome // cloning issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } @Override protected Object clone() throws CloneNotSupportedException { return instance; }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println("instance1 hashCode:- " + instance1.hashCode()); System.out.println("instance2 hashCode:- " + instance2.hashCode()); }}
Output:-
instance1 hashCode:- 366712642
instance2 hashCode:- 366712642
Now, as hashcode of both the instances is same that means they represent a single instance.
This article is contributed by Vishal Garg. 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.
ShaiwaliSahu
akshaysingh98088
gabaa406
Design Pattern
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Builder Design Pattern
Unified Modeling Language (UML) | An Introduction
MVC Design Pattern
Introduction of Programming Paradigms
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Aug, 2021"
},
{
"code": null,
"e": 86,
"s": 54,
"text": "Prerequisite: Singleton Pattern"
},
{
"code": null,
"e": 321,
"s": 86,
"text": "In this article, we will see that what are various concepts which can break singleton property of a class and how to avoid them. There are mainly 3 concepts which can break singleton property of a class. Let’s discuss them one by one."
},
{
"code": null,
"e": 10434,
"s": 321,
"text": "Reflection: Reflection can be caused to destroy singleton property of singleton class, as shown in following example:JavaJava// Java code to explain effect of Reflection// on Singleton property import java.lang.reflect.Constructor; // Singleton classclass Singleton { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG { public static void main(String[] args) { Singleton instance1 = Singleton.instance; Singleton instance2 = null; try { Constructor[] constructors = Singleton.class.getDeclaredConstructors(); for (Constructor constructor : constructors) { // Below code will destroy the singleton pattern constructor.setAccessible(true); instance2 = (Singleton) constructor.newInstance(); break; } } catch (Exception e) { e.printStackTrace(); } System.out.println(\"instance1.hashCode():- \" + instance1.hashCode()); System.out.println(\"instance2.hashCode():- \" + instance2.hashCode()); }}Output:-\ninstance1.hashCode():- 366712642\ninstance2.hashCode():- 1829164700\nAfter running this class, you will see that hashCodes are different that means, 2 objects of same class are created and singleton pattern has been destroyed.Overcome reflection issue: To overcome issue raised by reflection, enums are used because java ensures internally that enum value is instantiated only once. Since java Enums are globally accessible, they can be used for singletons. Its only drawback is that it is not flexible i.e it does not allow lazy initialization.JavaJava//Java program for Enum type singletonpublic enum Singleton { INSTANCE;}As enums don’t have any constructor so it is not possible for Reflection to utilize it. Enums have their by-default constructor, we can’t invoke them by ourself. JVM handles the creation and invocation of enum constructors internally. As enums don’t give their constructor definition to the program, it is not possible for us to access them by Reflection also. Hence, reflection can’t break singleton property in case of enums.Serialization:- Serialization can also cause breakage of singleton property of singleton classes. Serialization is used to convert an object of byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class. Then if you de-serialize that object it will create a new instance and hence break the singleton pattern.JavaJava// Java code to explain effect of // Serialization on singleton classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInput;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable; class Singleton implements Serializable { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG { public static void main(String[] args) { try { Singleton instance1 = Singleton.instance; ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"file.text\")); out.writeObject(instance1); out.close(); // deserialize from file to object ObjectInput in = new ObjectInputStream(new FileInputStream(\"file.text\")); Singleton instance2 = (Singleton) in.readObject(); in.close(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); } catch (Exception e) { e.printStackTrace(); } }}Output:- \ninstance1 hashCode:- 1550089733\ninstance2 hashCode:- 865113938\nAs you can see, hashCode of both instances is different, hence there are 2 objects of a singleton class. Thus, the class is no more singleton.Overcome serialization issue:- To overcome this issue, we have to implement method readResolve() method.JavaJava// Java code to remove the effect of // Serialization on singleton classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInput;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable; class Singleton implements Serializable { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } // implement readResolve method protected Object readResolve() { return instance; }} public class GFG { public static void main(String[] args) { try { Singleton instance1 = Singleton.instance; ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"file.text\")); out.writeObject(instance1); out.close(); // deserialize from file to object ObjectInput in = new ObjectInputStream(new FileInputStream(\"file.text\")); Singleton instance2 = (Singleton) in.readObject(); in.close(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); } catch (Exception e) { e.printStackTrace(); } }}Output:- \ninstance1 hashCode:- 1550089733\ninstance2 hashCode:- 1550089733\nAbove both hashcodes are same hence no other instance is created.Cloning: Cloning is a concept to create duplicate objects. Using clone we can create copy of object. Suppose, we create clone of a singleton object, then it will create a copy that is there are two instances of a singleton class, hence the class is no more singleton.JavaJava// Java code to explain cloning // issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); }}Output :- \ninstance1 hashCode:- 366712642\ninstance2 hashCode:- 1829164700\nTwo different hashCode means there are 2 different objects of singleton class.Overcome Cloning issue:- To overcome this issue, override clone() method and throw an exception from clone method that is CloneNotSupportedException. Now whenever user will try to create clone of singleton object, it will throw exception and hence our class remains singleton.JavaJava// Java code to explain overcome // cloning issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); }}Output:-\nException in thread \"main\" java.lang.CloneNotSupportedException\n at GFG.Singleton.clone(GFG.java:29)\n at GFG.GFG.main(GFG.java:38)\nNow we have stopped user to create clone of singleton class. If you don;t want to throw exception you can also return the same instance from clone method.JavaJava// Java code to explain overcome // cloning issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } @Override protected Object clone() throws CloneNotSupportedException { return instance; }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); }}Output:-\ninstance1 hashCode:- 366712642\ninstance2 hashCode:- 366712642\nNow, as hashcode of both the instances is same that means they represent a single instance."
},
{
"code": null,
"e": 12837,
"s": 10434,
"text": "Reflection: Reflection can be caused to destroy singleton property of singleton class, as shown in following example:JavaJava// Java code to explain effect of Reflection// on Singleton property import java.lang.reflect.Constructor; // Singleton classclass Singleton { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG { public static void main(String[] args) { Singleton instance1 = Singleton.instance; Singleton instance2 = null; try { Constructor[] constructors = Singleton.class.getDeclaredConstructors(); for (Constructor constructor : constructors) { // Below code will destroy the singleton pattern constructor.setAccessible(true); instance2 = (Singleton) constructor.newInstance(); break; } } catch (Exception e) { e.printStackTrace(); } System.out.println(\"instance1.hashCode():- \" + instance1.hashCode()); System.out.println(\"instance2.hashCode():- \" + instance2.hashCode()); }}Output:-\ninstance1.hashCode():- 366712642\ninstance2.hashCode():- 1829164700\nAfter running this class, you will see that hashCodes are different that means, 2 objects of same class are created and singleton pattern has been destroyed.Overcome reflection issue: To overcome issue raised by reflection, enums are used because java ensures internally that enum value is instantiated only once. Since java Enums are globally accessible, they can be used for singletons. Its only drawback is that it is not flexible i.e it does not allow lazy initialization.JavaJava//Java program for Enum type singletonpublic enum Singleton { INSTANCE;}As enums don’t have any constructor so it is not possible for Reflection to utilize it. Enums have their by-default constructor, we can’t invoke them by ourself. JVM handles the creation and invocation of enum constructors internally. As enums don’t give their constructor definition to the program, it is not possible for us to access them by Reflection also. Hence, reflection can’t break singleton property in case of enums."
},
{
"code": null,
"e": 12842,
"s": 12837,
"text": "Java"
},
{
"code": "// Java code to explain effect of Reflection// on Singleton property import java.lang.reflect.Constructor; // Singleton classclass Singleton { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG { public static void main(String[] args) { Singleton instance1 = Singleton.instance; Singleton instance2 = null; try { Constructor[] constructors = Singleton.class.getDeclaredConstructors(); for (Constructor constructor : constructors) { // Below code will destroy the singleton pattern constructor.setAccessible(true); instance2 = (Singleton) constructor.newInstance(); break; } } catch (Exception e) { e.printStackTrace(); } System.out.println(\"instance1.hashCode():- \" + instance1.hashCode()); System.out.println(\"instance2.hashCode():- \" + instance2.hashCode()); }}",
"e": 14060,
"s": 12842,
"text": null
},
{
"code": null,
"e": 14137,
"s": 14060,
"text": "Output:-\ninstance1.hashCode():- 366712642\ninstance2.hashCode():- 1829164700\n"
},
{
"code": null,
"e": 14295,
"s": 14137,
"text": "After running this class, you will see that hashCodes are different that means, 2 objects of same class are created and singleton pattern has been destroyed."
},
{
"code": null,
"e": 14615,
"s": 14295,
"text": "Overcome reflection issue: To overcome issue raised by reflection, enums are used because java ensures internally that enum value is instantiated only once. Since java Enums are globally accessible, they can be used for singletons. Its only drawback is that it is not flexible i.e it does not allow lazy initialization."
},
{
"code": null,
"e": 14620,
"s": 14615,
"text": "Java"
},
{
"code": "//Java program for Enum type singletonpublic enum Singleton { INSTANCE;}",
"e": 14694,
"s": 14620,
"text": null
},
{
"code": null,
"e": 18496,
"s": 14694,
"text": "Serialization:- Serialization can also cause breakage of singleton property of singleton classes. Serialization is used to convert an object of byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class. Then if you de-serialize that object it will create a new instance and hence break the singleton pattern.JavaJava// Java code to explain effect of // Serialization on singleton classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInput;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable; class Singleton implements Serializable { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG { public static void main(String[] args) { try { Singleton instance1 = Singleton.instance; ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"file.text\")); out.writeObject(instance1); out.close(); // deserialize from file to object ObjectInput in = new ObjectInputStream(new FileInputStream(\"file.text\")); Singleton instance2 = (Singleton) in.readObject(); in.close(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); } catch (Exception e) { e.printStackTrace(); } }}Output:- \ninstance1 hashCode:- 1550089733\ninstance2 hashCode:- 865113938\nAs you can see, hashCode of both instances is different, hence there are 2 objects of a singleton class. Thus, the class is no more singleton.Overcome serialization issue:- To overcome this issue, we have to implement method readResolve() method.JavaJava// Java code to remove the effect of // Serialization on singleton classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInput;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable; class Singleton implements Serializable { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } // implement readResolve method protected Object readResolve() { return instance; }} public class GFG { public static void main(String[] args) { try { Singleton instance1 = Singleton.instance; ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"file.text\")); out.writeObject(instance1); out.close(); // deserialize from file to object ObjectInput in = new ObjectInputStream(new FileInputStream(\"file.text\")); Singleton instance2 = (Singleton) in.readObject(); in.close(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); } catch (Exception e) { e.printStackTrace(); } }}Output:- \ninstance1 hashCode:- 1550089733\ninstance2 hashCode:- 1550089733\nAbove both hashcodes are same hence no other instance is created."
},
{
"code": null,
"e": 18501,
"s": 18496,
"text": "Java"
},
{
"code": "// Java code to explain effect of // Serialization on singleton classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInput;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable; class Singleton implements Serializable { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG { public static void main(String[] args) { try { Singleton instance1 = Singleton.instance; ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"file.text\")); out.writeObject(instance1); out.close(); // deserialize from file to object ObjectInput in = new ObjectInputStream(new FileInputStream(\"file.text\")); Singleton instance2 = (Singleton) in.readObject(); in.close(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); } catch (Exception e) { e.printStackTrace(); } }}",
"e": 19941,
"s": 18501,
"text": null
},
{
"code": null,
"e": 20015,
"s": 19941,
"text": "Output:- \ninstance1 hashCode:- 1550089733\ninstance2 hashCode:- 865113938\n"
},
{
"code": null,
"e": 20158,
"s": 20015,
"text": "As you can see, hashCode of both instances is different, hence there are 2 objects of a singleton class. Thus, the class is no more singleton."
},
{
"code": null,
"e": 20263,
"s": 20158,
"text": "Overcome serialization issue:- To overcome this issue, we have to implement method readResolve() method."
},
{
"code": null,
"e": 20268,
"s": 20263,
"text": "Java"
},
{
"code": "// Java code to remove the effect of // Serialization on singleton classesimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInput;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;import java.io.Serializable; class Singleton implements Serializable { // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } // implement readResolve method protected Object readResolve() { return instance; }} public class GFG { public static void main(String[] args) { try { Singleton instance1 = Singleton.instance; ObjectOutput out = new ObjectOutputStream(new FileOutputStream(\"file.text\")); out.writeObject(instance1); out.close(); // deserialize from file to object ObjectInput in = new ObjectInputStream(new FileInputStream(\"file.text\")); Singleton instance2 = (Singleton) in.readObject(); in.close(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); } catch (Exception e) { e.printStackTrace(); } }}",
"e": 21799,
"s": 20268,
"text": null
},
{
"code": null,
"e": 21874,
"s": 21799,
"text": "Output:- \ninstance1 hashCode:- 1550089733\ninstance2 hashCode:- 1550089733\n"
},
{
"code": null,
"e": 21940,
"s": 21874,
"text": "Above both hashcodes are same hence no other instance is created."
},
{
"code": null,
"e": 25850,
"s": 21940,
"text": "Cloning: Cloning is a concept to create duplicate objects. Using clone we can create copy of object. Suppose, we create clone of a singleton object, then it will create a copy that is there are two instances of a singleton class, hence the class is no more singleton.JavaJava// Java code to explain cloning // issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); }}Output :- \ninstance1 hashCode:- 366712642\ninstance2 hashCode:- 1829164700\nTwo different hashCode means there are 2 different objects of singleton class.Overcome Cloning issue:- To overcome this issue, override clone() method and throw an exception from clone method that is CloneNotSupportedException. Now whenever user will try to create clone of singleton object, it will throw exception and hence our class remains singleton.JavaJava// Java code to explain overcome // cloning issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); }}Output:-\nException in thread \"main\" java.lang.CloneNotSupportedException\n at GFG.Singleton.clone(GFG.java:29)\n at GFG.GFG.main(GFG.java:38)\nNow we have stopped user to create clone of singleton class. If you don;t want to throw exception you can also return the same instance from clone method.JavaJava// Java code to explain overcome // cloning issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } @Override protected Object clone() throws CloneNotSupportedException { return instance; }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); }}Output:-\ninstance1 hashCode:- 366712642\ninstance2 hashCode:- 366712642\nNow, as hashcode of both the instances is same that means they represent a single instance."
},
{
"code": null,
"e": 25855,
"s": 25850,
"text": "Java"
},
{
"code": "// Java code to explain cloning // issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); }}",
"e": 26686,
"s": 25855,
"text": null
},
{
"code": null,
"e": 26761,
"s": 26686,
"text": "Output :- \ninstance1 hashCode:- 366712642\ninstance2 hashCode:- 1829164700\n"
},
{
"code": null,
"e": 26840,
"s": 26761,
"text": "Two different hashCode means there are 2 different objects of singleton class."
},
{
"code": null,
"e": 27117,
"s": 26840,
"text": "Overcome Cloning issue:- To overcome this issue, override clone() method and throw an exception from clone method that is CloneNotSupportedException. Now whenever user will try to create clone of singleton object, it will throw exception and hence our class remains singleton."
},
{
"code": null,
"e": 27122,
"s": 27117,
"text": "Java"
},
{
"code": "// Java code to explain overcome // cloning issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); }}",
"e": 28082,
"s": 27122,
"text": null
},
{
"code": null,
"e": 28229,
"s": 28082,
"text": "Output:-\nException in thread \"main\" java.lang.CloneNotSupportedException\n at GFG.Singleton.clone(GFG.java:29)\n at GFG.GFG.main(GFG.java:38)\n"
},
{
"code": null,
"e": 28384,
"s": 28229,
"text": "Now we have stopped user to create clone of singleton class. If you don;t want to throw exception you can also return the same instance from clone method."
},
{
"code": null,
"e": 28389,
"s": 28384,
"text": "Java"
},
{
"code": "// Java code to explain overcome // cloning issue with singletonclass SuperClass implements Cloneable{ int i = 10; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); }} // Singleton classclass Singleton extends SuperClass{ // public instance initialized when loading the class public static Singleton instance = new Singleton(); private Singleton() { // private constructor } @Override protected Object clone() throws CloneNotSupportedException { return instance; }} public class GFG{ public static void main(String[] args) throws CloneNotSupportedException { Singleton instance1 = Singleton.instance; Singleton instance2 = (Singleton) instance1.clone(); System.out.println(\"instance1 hashCode:- \" + instance1.hashCode()); System.out.println(\"instance2 hashCode:- \" + instance2.hashCode()); }}",
"e": 29329,
"s": 28389,
"text": null
},
{
"code": null,
"e": 29401,
"s": 29329,
"text": "Output:-\ninstance1 hashCode:- 366712642\ninstance2 hashCode:- 366712642\n"
},
{
"code": null,
"e": 29493,
"s": 29401,
"text": "Now, as hashcode of both the instances is same that means they represent a single instance."
},
{
"code": null,
"e": 29788,
"s": 29493,
"text": "This article is contributed by Vishal Garg. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29913,
"s": 29788,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29926,
"s": 29913,
"text": "ShaiwaliSahu"
},
{
"code": null,
"e": 29943,
"s": 29926,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 29952,
"s": 29943,
"text": "gabaa406"
},
{
"code": null,
"e": 29967,
"s": 29952,
"text": "Design Pattern"
},
{
"code": null,
"e": 29972,
"s": 29967,
"text": "Java"
},
{
"code": null,
"e": 29977,
"s": 29972,
"text": "Java"
},
{
"code": null,
"e": 30075,
"s": 29977,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30113,
"s": 30075,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 30136,
"s": 30113,
"text": "Builder Design Pattern"
},
{
"code": null,
"e": 30186,
"s": 30136,
"text": "Unified Modeling Language (UML) | An Introduction"
},
{
"code": null,
"e": 30205,
"s": 30186,
"text": "MVC Design Pattern"
},
{
"code": null,
"e": 30243,
"s": 30205,
"text": "Introduction of Programming Paradigms"
},
{
"code": null,
"e": 30258,
"s": 30243,
"text": "Arrays in Java"
},
{
"code": null,
"e": 30302,
"s": 30258,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 30338,
"s": 30302,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 30363,
"s": 30338,
"text": "Reverse a string in Java"
}
]
|
Implementing Apriori algorithm in Python | 18 May, 2022
Prerequisites: Apriori AlgorithmApriori Algorithm is a Machine Learning algorithm which is used to gain insight into the structured relationships between different items involved. The most prominent practical application of the algorithm is to recommend products based on the products already present in the user’s cart. Walmart especially has made great use of the algorithm in suggesting products to it’s users.
Dataset : Groceries data
Implementation of algorithm in Python: Step 1: Importing the required libraries
Python3
import numpy as npimport pandas as pdfrom mlxtend.frequent_patterns import apriori, association_rules
Step 2: Loading and exploring the data
Python3
# Changing the working location to the location of the filecd C:\Users\Dev\Desktop\Kaggle\Apriori Algorithm # Loading the Datadata = pd.read_excel('Online_Retail.xlsx')data.head()
Python3
# Exploring the columns of the datadata.columns
Python3
# Exploring the different regions of transactionsdata.Country.unique()
Step 3: Cleaning the Data
Python3
# Stripping extra spaces in the descriptiondata['Description'] = data['Description'].str.strip() # Dropping the rows without any invoice numberdata.dropna(axis = 0, subset =['InvoiceNo'], inplace = True)data['InvoiceNo'] = data['InvoiceNo'].astype('str') # Dropping all transactions which were done on creditdata = data[~data['InvoiceNo'].str.contains('C')]
Step 4: Splitting the data according to the region of transaction
Python3
# Transactions done in Francebasket_France = (data[data['Country'] =="France"] .groupby(['InvoiceNo', 'Description'])['Quantity'] .sum().unstack().reset_index().fillna(0) .set_index('InvoiceNo')) # Transactions done in the United Kingdombasket_UK = (data[data['Country'] =="United Kingdom"] .groupby(['InvoiceNo', 'Description'])['Quantity'] .sum().unstack().reset_index().fillna(0) .set_index('InvoiceNo')) # Transactions done in Portugalbasket_Por = (data[data['Country'] =="Portugal"] .groupby(['InvoiceNo', 'Description'])['Quantity'] .sum().unstack().reset_index().fillna(0) .set_index('InvoiceNo')) basket_Sweden = (data[data['Country'] =="Sweden"] .groupby(['InvoiceNo', 'Description'])['Quantity'] .sum().unstack().reset_index().fillna(0) .set_index('InvoiceNo'))
Step 5: Hot encoding the Data
Python3
# Defining the hot encoding function to make the data suitable # for the concerned librariesdef hot_encode(x): if(x<= 0): return 0 if(x>= 1): return 1 # Encoding the datasetsbasket_encoded = basket_France.applymap(hot_encode)basket_France = basket_encoded basket_encoded = basket_UK.applymap(hot_encode)basket_UK = basket_encoded basket_encoded = basket_Por.applymap(hot_encode)basket_Por = basket_encoded basket_encoded = basket_Sweden.applymap(hot_encode)basket_Sweden = basket_encoded
Step 6: Building the models and analyzing the resultsa) France:
Python3
# Building the modelfrq_items = apriori(basket_France, min_support = 0.05, use_colnames = True) # Collecting the inferred rules in a dataframerules = association_rules(frq_items, metric ="lift", min_threshold = 1)rules = rules.sort_values(['confidence', 'lift'], ascending =[False, False])print(rules.head())
From the above output, it can be seen that paper cups and paper and plates are bought together in France. This is because the French have a culture of having a get-together with their friends and family atleast once a week. Also, since the French government has banned the use of plastic in the country, the people have to purchase the paper-based alternatives. b) United Kingdom:
Python3
frq_items = apriori(basket_UK, min_support = 0.01, use_colnames = True)rules = association_rules(frq_items, metric ="lift", min_threshold = 1)rules = rules.sort_values(['confidence', 'lift'], ascending =[False, False])print(rules.head())
If the rules for British transactions are analyzed a little deeper, it is seen that the British people buy different colored tea-plates together. A reason behind this may be because typically the British enjoy tea very much and often collect different colored tea-plates for different occasions.c) Portugal:
Python3
frq_items = apriori(basket_Por, min_support = 0.05, use_colnames = True)rules = association_rules(frq_items, metric ="lift", min_threshold = 1)rules = rules.sort_values(['confidence', 'lift'], ascending =[False, False])print(rules.head())
On analyzing the association rules for Portuguese transactions, it is observed that Tiffin sets (Knick Knack Tins) and color pencils. These two products typically belong to a primary school going kid. These two products are required by children in school to carry their lunch and for creative work respectively and hence are logically make sense to be paired together.d) Sweden:
Python3
frq_items = apriori(basket_Sweden, min_support = 0.05, use_colnames = True)rules = association_rules(frq_items, metric ="lift", min_threshold = 1)rules = rules.sort_values(['confidence', 'lift'], ascending =[False, False])print(rules.head())
On analyzing the above rules, it is found that boys’ and girls’ cutlery are paired together. This makes practical sense because when a parent goes shopping for cutlery for his/her children, he/she would want the product to be a little customized according to the kid’s wishes.
gulshankumarar231
adnanirshad158
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Random Forest Regression in Python
ML | Underfitting and Overfitting
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 May, 2022"
},
{
"code": null,
"e": 468,
"s": 54,
"text": "Prerequisites: Apriori AlgorithmApriori Algorithm is a Machine Learning algorithm which is used to gain insight into the structured relationships between different items involved. The most prominent practical application of the algorithm is to recommend products based on the products already present in the user’s cart. Walmart especially has made great use of the algorithm in suggesting products to it’s users."
},
{
"code": null,
"e": 494,
"s": 468,
"text": "Dataset : Groceries data "
},
{
"code": null,
"e": 574,
"s": 494,
"text": "Implementation of algorithm in Python: Step 1: Importing the required libraries"
},
{
"code": null,
"e": 582,
"s": 574,
"text": "Python3"
},
{
"code": "import numpy as npimport pandas as pdfrom mlxtend.frequent_patterns import apriori, association_rules",
"e": 684,
"s": 582,
"text": null
},
{
"code": null,
"e": 723,
"s": 684,
"text": "Step 2: Loading and exploring the data"
},
{
"code": null,
"e": 731,
"s": 723,
"text": "Python3"
},
{
"code": "# Changing the working location to the location of the filecd C:\\Users\\Dev\\Desktop\\Kaggle\\Apriori Algorithm # Loading the Datadata = pd.read_excel('Online_Retail.xlsx')data.head()",
"e": 912,
"s": 731,
"text": null
},
{
"code": null,
"e": 920,
"s": 912,
"text": "Python3"
},
{
"code": "# Exploring the columns of the datadata.columns",
"e": 968,
"s": 920,
"text": null
},
{
"code": null,
"e": 976,
"s": 968,
"text": "Python3"
},
{
"code": "# Exploring the different regions of transactionsdata.Country.unique()",
"e": 1047,
"s": 976,
"text": null
},
{
"code": null,
"e": 1073,
"s": 1047,
"text": "Step 3: Cleaning the Data"
},
{
"code": null,
"e": 1081,
"s": 1073,
"text": "Python3"
},
{
"code": "# Stripping extra spaces in the descriptiondata['Description'] = data['Description'].str.strip() # Dropping the rows without any invoice numberdata.dropna(axis = 0, subset =['InvoiceNo'], inplace = True)data['InvoiceNo'] = data['InvoiceNo'].astype('str') # Dropping all transactions which were done on creditdata = data[~data['InvoiceNo'].str.contains('C')]",
"e": 1441,
"s": 1081,
"text": null
},
{
"code": null,
"e": 1507,
"s": 1441,
"text": "Step 4: Splitting the data according to the region of transaction"
},
{
"code": null,
"e": 1515,
"s": 1507,
"text": "Python3"
},
{
"code": "# Transactions done in Francebasket_France = (data[data['Country'] ==\"France\"] .groupby(['InvoiceNo', 'Description'])['Quantity'] .sum().unstack().reset_index().fillna(0) .set_index('InvoiceNo')) # Transactions done in the United Kingdombasket_UK = (data[data['Country'] ==\"United Kingdom\"] .groupby(['InvoiceNo', 'Description'])['Quantity'] .sum().unstack().reset_index().fillna(0) .set_index('InvoiceNo')) # Transactions done in Portugalbasket_Por = (data[data['Country'] ==\"Portugal\"] .groupby(['InvoiceNo', 'Description'])['Quantity'] .sum().unstack().reset_index().fillna(0) .set_index('InvoiceNo')) basket_Sweden = (data[data['Country'] ==\"Sweden\"] .groupby(['InvoiceNo', 'Description'])['Quantity'] .sum().unstack().reset_index().fillna(0) .set_index('InvoiceNo'))",
"e": 2398,
"s": 1515,
"text": null
},
{
"code": null,
"e": 2428,
"s": 2398,
"text": "Step 5: Hot encoding the Data"
},
{
"code": null,
"e": 2436,
"s": 2428,
"text": "Python3"
},
{
"code": "# Defining the hot encoding function to make the data suitable # for the concerned librariesdef hot_encode(x): if(x<= 0): return 0 if(x>= 1): return 1 # Encoding the datasetsbasket_encoded = basket_France.applymap(hot_encode)basket_France = basket_encoded basket_encoded = basket_UK.applymap(hot_encode)basket_UK = basket_encoded basket_encoded = basket_Por.applymap(hot_encode)basket_Por = basket_encoded basket_encoded = basket_Sweden.applymap(hot_encode)basket_Sweden = basket_encoded",
"e": 2948,
"s": 2436,
"text": null
},
{
"code": null,
"e": 3012,
"s": 2948,
"text": "Step 6: Building the models and analyzing the resultsa) France:"
},
{
"code": null,
"e": 3020,
"s": 3012,
"text": "Python3"
},
{
"code": "# Building the modelfrq_items = apriori(basket_France, min_support = 0.05, use_colnames = True) # Collecting the inferred rules in a dataframerules = association_rules(frq_items, metric =\"lift\", min_threshold = 1)rules = rules.sort_values(['confidence', 'lift'], ascending =[False, False])print(rules.head())",
"e": 3330,
"s": 3020,
"text": null
},
{
"code": null,
"e": 3711,
"s": 3330,
"text": "From the above output, it can be seen that paper cups and paper and plates are bought together in France. This is because the French have a culture of having a get-together with their friends and family atleast once a week. Also, since the French government has banned the use of plastic in the country, the people have to purchase the paper-based alternatives. b) United Kingdom:"
},
{
"code": null,
"e": 3719,
"s": 3711,
"text": "Python3"
},
{
"code": "frq_items = apriori(basket_UK, min_support = 0.01, use_colnames = True)rules = association_rules(frq_items, metric =\"lift\", min_threshold = 1)rules = rules.sort_values(['confidence', 'lift'], ascending =[False, False])print(rules.head())",
"e": 3957,
"s": 3719,
"text": null
},
{
"code": null,
"e": 4265,
"s": 3957,
"text": "If the rules for British transactions are analyzed a little deeper, it is seen that the British people buy different colored tea-plates together. A reason behind this may be because typically the British enjoy tea very much and often collect different colored tea-plates for different occasions.c) Portugal:"
},
{
"code": null,
"e": 4273,
"s": 4265,
"text": "Python3"
},
{
"code": "frq_items = apriori(basket_Por, min_support = 0.05, use_colnames = True)rules = association_rules(frq_items, metric =\"lift\", min_threshold = 1)rules = rules.sort_values(['confidence', 'lift'], ascending =[False, False])print(rules.head())",
"e": 4512,
"s": 4273,
"text": null
},
{
"code": null,
"e": 4891,
"s": 4512,
"text": "On analyzing the association rules for Portuguese transactions, it is observed that Tiffin sets (Knick Knack Tins) and color pencils. These two products typically belong to a primary school going kid. These two products are required by children in school to carry their lunch and for creative work respectively and hence are logically make sense to be paired together.d) Sweden:"
},
{
"code": null,
"e": 4899,
"s": 4891,
"text": "Python3"
},
{
"code": "frq_items = apriori(basket_Sweden, min_support = 0.05, use_colnames = True)rules = association_rules(frq_items, metric =\"lift\", min_threshold = 1)rules = rules.sort_values(['confidence', 'lift'], ascending =[False, False])print(rules.head())",
"e": 5141,
"s": 4899,
"text": null
},
{
"code": null,
"e": 5419,
"s": 5141,
"text": "On analyzing the above rules, it is found that boys’ and girls’ cutlery are paired together. This makes practical sense because when a parent goes shopping for cutlery for his/her children, he/she would want the product to be a little customized according to the kid’s wishes. "
},
{
"code": null,
"e": 5437,
"s": 5419,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 5452,
"s": 5437,
"text": "adnanirshad158"
},
{
"code": null,
"e": 5469,
"s": 5452,
"text": "Machine Learning"
},
{
"code": null,
"e": 5476,
"s": 5469,
"text": "Python"
},
{
"code": null,
"e": 5493,
"s": 5476,
"text": "Machine Learning"
},
{
"code": null,
"e": 5591,
"s": 5493,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5629,
"s": 5591,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 5670,
"s": 5629,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 5703,
"s": 5670,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 5738,
"s": 5703,
"text": "Random Forest Regression in Python"
},
{
"code": null,
"e": 5772,
"s": 5738,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 5800,
"s": 5772,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 5822,
"s": 5800,
"text": "Python map() function"
},
{
"code": null,
"e": 5872,
"s": 5822,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 5890,
"s": 5872,
"text": "Python Dictionary"
}
]
|
Angular forms FormGroupDirective | 02 Jun, 2021
In this article, we are going to see what is FormGroupDirective in Angular 10 and how to use it.
FormGroupDirective is used to Bind an existing FormGroup to a DOM element.
Syntax:
<form [FormGroup] ="name">
Exported from:
ReactiveFormsModule
Selectors:
[FormGroup]
Approach:
Create the Angular app to be used
In app.component.ts make an object that contains a value for the input.
In app.component.html use FormGroup to get values.
Serve the angular app using ng serve to see the output.
Example 1:
app.component.ts
import { Component, Inject } from '@angular/core'; import { FormGroup, FormControl, FormArray } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { form = new FormGroup({ name: new FormControl() }); get name(): any { return this.form.get('name'); } onSubmit(): void { console.log(this.form.value); } }
app.component.html
<br><form [formGroup]="form" (ngSubmit)="onSubmit()"> <input formControlName="name" placeholder="Name"> <br> <button type='submit'>Submit</button> <br> <br></form>
Output:
Reference: https://angular.io/api/forms/FormGroupDirective
Angular10
AngularJS-Directives
AngularJS
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": "\n02 Jun, 2021"
},
{
"code": null,
"e": 125,
"s": 28,
"text": "In this article, we are going to see what is FormGroupDirective in Angular 10 and how to use it."
},
{
"code": null,
"e": 200,
"s": 125,
"text": "FormGroupDirective is used to Bind an existing FormGroup to a DOM element."
},
{
"code": null,
"e": 208,
"s": 200,
"text": "Syntax:"
},
{
"code": null,
"e": 235,
"s": 208,
"text": "<form [FormGroup] =\"name\">"
},
{
"code": null,
"e": 250,
"s": 235,
"text": "Exported from:"
},
{
"code": null,
"e": 270,
"s": 250,
"text": "ReactiveFormsModule"
},
{
"code": null,
"e": 283,
"s": 272,
"text": "Selectors:"
},
{
"code": null,
"e": 295,
"s": 283,
"text": "[FormGroup]"
},
{
"code": null,
"e": 306,
"s": 295,
"text": "Approach: "
},
{
"code": null,
"e": 340,
"s": 306,
"text": "Create the Angular app to be used"
},
{
"code": null,
"e": 412,
"s": 340,
"text": "In app.component.ts make an object that contains a value for the input."
},
{
"code": null,
"e": 463,
"s": 412,
"text": "In app.component.html use FormGroup to get values."
},
{
"code": null,
"e": 519,
"s": 463,
"text": "Serve the angular app using ng serve to see the output."
},
{
"code": null,
"e": 530,
"s": 519,
"text": "Example 1:"
},
{
"code": null,
"e": 547,
"s": 530,
"text": "app.component.ts"
},
{
"code": "import { Component, Inject } from '@angular/core'; import { FormGroup, FormControl, FormArray } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { form = new FormGroup({ name: new FormControl() }); get name(): any { return this.form.get('name'); } onSubmit(): void { console.log(this.form.value); } }",
"e": 1018,
"s": 547,
"text": null
},
{
"code": null,
"e": 1037,
"s": 1018,
"text": "app.component.html"
},
{
"code": "<br><form [formGroup]=\"form\" (ngSubmit)=\"onSubmit()\"> <input formControlName=\"name\" placeholder=\"Name\"> <br> <button type='submit'>Submit</button> <br> <br></form>",
"e": 1206,
"s": 1037,
"text": null
},
{
"code": null,
"e": 1214,
"s": 1206,
"text": "Output:"
},
{
"code": null,
"e": 1273,
"s": 1214,
"text": "Reference: https://angular.io/api/forms/FormGroupDirective"
},
{
"code": null,
"e": 1283,
"s": 1273,
"text": "Angular10"
},
{
"code": null,
"e": 1304,
"s": 1283,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 1314,
"s": 1304,
"text": "AngularJS"
},
{
"code": null,
"e": 1331,
"s": 1314,
"text": "Web Technologies"
}
]
|
WEEKOFYEAR() Function in MySQL | 05 Oct, 2020
WEEKOFYEAR() function in MySQL is used to find the week number for a given date. If the date is NULL, the WEEKOFYEAR function will return NULL. Otherwise, it returns the value of week which ranges between 1 to 53.
Syntax :
WEEKOFYEAR( date)
Parameter :This method accepts only one parameter.
date –The date or datetime from which we want to extract the week number.
Returns :It returns the week number.
Example-1 :Finding the Current week number Using WEEKOFYEAR() Function on 29/09/2020.
SELECT WEEKOFYEAR(NOW()) AS Current_Week;
Output :
So, the current week number is 40.
Example-2 :Finding the Week from given DateTime Using WEEKOFYEAR() Function.
SELECT WEEKOFYEAR('2018-04-22 08:09:22')
AS Week_Number ;
Output :
So, the week number is 16 in this example.
Example-3 :Finding the Week from given date Using WEEKOFYEAR() Function.
SELECT WEEKOFYEAR('2019-07-25 ')
AS Week_Number ;
Output :
Example-4 :Finding the Week number from given datetime Using WEEKOFYEAR() Function when the date is NULL.
SELECT WEEKOFYEAR(NULL)
AS Week_Number;
Output :
Example-4 :In this example, we are going to find the number of students enrolled in a course for every week in a year. To demonstrate create a table named.Course.
CREATE TABLE Course
(
Course_name VARCHAR(100) NOT NULL,
Student_id INT NOT NULL,
Student_name VARCHAR(100) NOT NULL,
Enroll_Date Date NOT NULL,
PRIMARY KEY(Student_id)
);
Now inserting some data to the Course table.
INSERT INTO
Course(Course_Name, Student_id, Student_name, Enroll_Date)
VALUES
( 'CS101', 161011, 'Amit Singh', '2019-10-06' ),
( 'CS101', 161029, 'Arun Kumar', '2019-10-23' ),
( 'CS101', 161031, 'Sanya Jain', '2019-11-08' ),
( 'CS101', 161058, 'Riya Shah', '2019-11-20' ),
( 'CS101', 162051, 'Amit Sharma', '2019-11-30' ),
( 'CS101', 161951, 'Sayan Singh', '2019-12-07' ),
( 'CS101', 167051, 'Rishi Jana', '2019-12-15' ),
( 'CS101', 168001, 'Aniket Dravid', '2019-12-25' ),
( 'CS101', 168051, 'Rita Singh', '2019-12-28' ),
( 'CS101', 166051, 'Kalyan Ghandi', '2019-12-29' ) ;
So, Our table looks like.
Now, we are going to find the number of students enrolled in the course every week.
SELECT
WEEKOFYEAR(Enroll_Date) Week_Number,
COUNT(Student_id) Student_Enrolled
FROM
Course
GROUP BY WEEKOFYEAR(Enroll_Date)
ORDER BY WEEKOFYEAR(Enroll_Date);
Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Views
Difference between DELETE, DROP and TRUNCATE
CTE in SQL
SQL Trigger | Student Database
Difference between SQL and NoSQL
SQL using Python
Difference between DELETE and TRUNCATE
SQL | DDL, DML, TCL and DCL
SQL - ORDER BY
Window functions in SQL | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Oct, 2020"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "WEEKOFYEAR() function in MySQL is used to find the week number for a given date. If the date is NULL, the WEEKOFYEAR function will return NULL. Otherwise, it returns the value of week which ranges between 1 to 53."
},
{
"code": null,
"e": 251,
"s": 242,
"text": "Syntax :"
},
{
"code": null,
"e": 269,
"s": 251,
"text": "WEEKOFYEAR( date)"
},
{
"code": null,
"e": 320,
"s": 269,
"text": "Parameter :This method accepts only one parameter."
},
{
"code": null,
"e": 394,
"s": 320,
"text": "date –The date or datetime from which we want to extract the week number."
},
{
"code": null,
"e": 433,
"s": 394,
"text": "Returns :It returns the week number."
},
{
"code": null,
"e": 519,
"s": 433,
"text": "Example-1 :Finding the Current week number Using WEEKOFYEAR() Function on 29/09/2020."
},
{
"code": null,
"e": 562,
"s": 519,
"text": "SELECT WEEKOFYEAR(NOW()) AS Current_Week;\n"
},
{
"code": null,
"e": 571,
"s": 562,
"text": "Output :"
},
{
"code": null,
"e": 606,
"s": 571,
"text": "So, the current week number is 40."
},
{
"code": null,
"e": 683,
"s": 606,
"text": "Example-2 :Finding the Week from given DateTime Using WEEKOFYEAR() Function."
},
{
"code": null,
"e": 743,
"s": 683,
"text": "SELECT WEEKOFYEAR('2018-04-22 08:09:22') \nAS Week_Number ;\n"
},
{
"code": null,
"e": 752,
"s": 743,
"text": "Output :"
},
{
"code": null,
"e": 795,
"s": 752,
"text": "So, the week number is 16 in this example."
},
{
"code": null,
"e": 868,
"s": 795,
"text": "Example-3 :Finding the Week from given date Using WEEKOFYEAR() Function."
},
{
"code": null,
"e": 920,
"s": 868,
"text": "SELECT WEEKOFYEAR('2019-07-25 ') \nAS Week_Number ;\n"
},
{
"code": null,
"e": 929,
"s": 920,
"text": "Output :"
},
{
"code": null,
"e": 1036,
"s": 929,
"text": "Example-4 :Finding the Week number from given datetime Using WEEKOFYEAR() Function when the date is NULL."
},
{
"code": null,
"e": 1078,
"s": 1036,
"text": "SELECT WEEKOFYEAR(NULL) \nAS Week_Number;\n"
},
{
"code": null,
"e": 1087,
"s": 1078,
"text": "Output :"
},
{
"code": null,
"e": 1250,
"s": 1087,
"text": "Example-4 :In this example, we are going to find the number of students enrolled in a course for every week in a year. To demonstrate create a table named.Course."
},
{
"code": null,
"e": 1447,
"s": 1250,
"text": "CREATE TABLE Course\n(\n Course_name VARCHAR(100) NOT NULL,\n Student_id INT NOT NULL, \n Student_name VARCHAR(100) NOT NULL,\n Enroll_Date Date NOT NULL,\n PRIMARY KEY(Student_id)\n);\n"
},
{
"code": null,
"e": 1492,
"s": 1447,
"text": "Now inserting some data to the Course table."
},
{
"code": null,
"e": 2109,
"s": 1492,
"text": "INSERT INTO\nCourse(Course_Name, Student_id, Student_name, Enroll_Date)\nVALUES\n ( 'CS101', 161011, 'Amit Singh', '2019-10-06' ),\n ( 'CS101', 161029, 'Arun Kumar', '2019-10-23' ),\n ( 'CS101', 161031, 'Sanya Jain', '2019-11-08' ),\n ( 'CS101', 161058, 'Riya Shah', '2019-11-20' ),\n ( 'CS101', 162051, 'Amit Sharma', '2019-11-30' ),\n ( 'CS101', 161951, 'Sayan Singh', '2019-12-07' ),\n ( 'CS101', 167051, 'Rishi Jana', '2019-12-15' ),\n ( 'CS101', 168001, 'Aniket Dravid', '2019-12-25' ),\n ( 'CS101', 168051, 'Rita Singh', '2019-12-28' ),\n ( 'CS101', 166051, 'Kalyan Ghandi', '2019-12-29' ) ;\n"
},
{
"code": null,
"e": 2135,
"s": 2109,
"text": "So, Our table looks like."
},
{
"code": null,
"e": 2219,
"s": 2135,
"text": "Now, we are going to find the number of students enrolled in the course every week."
},
{
"code": null,
"e": 2390,
"s": 2219,
"text": "SELECT\nWEEKOFYEAR(Enroll_Date) Week_Number,\nCOUNT(Student_id) Student_Enrolled\nFROM\n Course\n GROUP BY WEEKOFYEAR(Enroll_Date)\n ORDER BY WEEKOFYEAR(Enroll_Date);\n"
},
{
"code": null,
"e": 2399,
"s": 2390,
"text": "Output :"
},
{
"code": null,
"e": 2408,
"s": 2399,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2414,
"s": 2408,
"text": "mysql"
},
{
"code": null,
"e": 2418,
"s": 2414,
"text": "SQL"
},
{
"code": null,
"e": 2422,
"s": 2418,
"text": "SQL"
},
{
"code": null,
"e": 2520,
"s": 2422,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2532,
"s": 2520,
"text": "SQL | Views"
},
{
"code": null,
"e": 2577,
"s": 2532,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 2588,
"s": 2577,
"text": "CTE in SQL"
},
{
"code": null,
"e": 2619,
"s": 2588,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 2652,
"s": 2619,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 2669,
"s": 2652,
"text": "SQL using Python"
},
{
"code": null,
"e": 2708,
"s": 2669,
"text": "Difference between DELETE and TRUNCATE"
},
{
"code": null,
"e": 2736,
"s": 2708,
"text": "SQL | DDL, DML, TCL and DCL"
},
{
"code": null,
"e": 2751,
"s": 2736,
"text": "SQL - ORDER BY"
}
]
|
XSS-Freak – XSS Scanner Fully Written in Kali Linux | 14 Sep, 2021
XSS or Cross-Site Scripting is the most emerging security flaw in Web Applications. When the arbitrary or malicious JavaScript is executed by the web application then it is said to be an XSS Vulnerable Website. There are various XSS Scanners through which we can detect the XSS on the target domain. XSS-Freak is an XSS Scanner developed in the Python Language. XSS-Freak tool is an open-source and free-to-use tool also available on GitHub. XSS-Freak tool crawls the target domain for all possible links and directories to increase the chances of attack.
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process – Python Installation Steps on Linux
Once the Script is executed through Python Interpreter, the user needs to specify the list of XSS payloads that will be tested on the target domain. XSS-Freak tool then crawls the directories and links and analysis the parameters from which the payloads can be inserted and the testing process can be done. Then the XSS-Freak tool adds all the found HTML INPUTS to its attack scope then the XSS-Freak tool launches an ATTACK on all HTML INPUTS with the XSS payloads the user provided from the list. if the HTML INPUT IS NOT SANITIZED PROPERLY and Filtered The Script Will Instantly Detect It and Will Print Out The Vulnerable Parameter.
XSS-Freak tool has support for Multi-threading for Higher Efficiency and Faster Performance Processing.
XSS-Freak has the Crawling ability over complete websites.
XSS-Freak tool is Versatile.
Not supported on the phones
Requires a high-speed Internet connection
Requires advanced hardware
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/AssetX/XSS-Freak.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd XSS-Freak
Step 3: You are in the directory of the XSS-Freak. Now you have to install a dependency of the XSS-Freak using the following command.
sudo pip3 install -r requirements.txt
Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section.
python3 XSS-Freak.py -h
Example 1: We will be testing http://geeksforgeeks.org target domain
In this example, We will be testing the geeksforgeeks.org domain. We will specify the list of XSS consisting of Payloads.
As geeksforgeeks.org is Secured Website, the tool has not detected any vulnerable parameters.
Example 2: We will be testing http://testphp.vulnweb.com target domain
In this example, We will be scanning the testphp.vulnweb.com domain.
We have got one vulnerable parameter or input through which we can insert the payload.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 584,
"s": 28,
"text": "XSS or Cross-Site Scripting is the most emerging security flaw in Web Applications. When the arbitrary or malicious JavaScript is executed by the web application then it is said to be an XSS Vulnerable Website. There are various XSS Scanners through which we can detect the XSS on the target domain. XSS-Freak is an XSS Scanner developed in the Python Language. XSS-Freak tool is an open-source and free-to-use tool also available on GitHub. XSS-Freak tool crawls the target domain for all possible links and directories to increase the chances of attack."
},
{
"code": null,
"e": 751,
"s": 584,
"text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process – Python Installation Steps on Linux"
},
{
"code": null,
"e": 1388,
"s": 751,
"text": "Once the Script is executed through Python Interpreter, the user needs to specify the list of XSS payloads that will be tested on the target domain. XSS-Freak tool then crawls the directories and links and analysis the parameters from which the payloads can be inserted and the testing process can be done. Then the XSS-Freak tool adds all the found HTML INPUTS to its attack scope then the XSS-Freak tool launches an ATTACK on all HTML INPUTS with the XSS payloads the user provided from the list. if the HTML INPUT IS NOT SANITIZED PROPERLY and Filtered The Script Will Instantly Detect It and Will Print Out The Vulnerable Parameter."
},
{
"code": null,
"e": 1492,
"s": 1388,
"text": "XSS-Freak tool has support for Multi-threading for Higher Efficiency and Faster Performance Processing."
},
{
"code": null,
"e": 1551,
"s": 1492,
"text": "XSS-Freak has the Crawling ability over complete websites."
},
{
"code": null,
"e": 1580,
"s": 1551,
"text": "XSS-Freak tool is Versatile."
},
{
"code": null,
"e": 1608,
"s": 1580,
"text": "Not supported on the phones"
},
{
"code": null,
"e": 1650,
"s": 1608,
"text": "Requires a high-speed Internet connection"
},
{
"code": null,
"e": 1677,
"s": 1650,
"text": "Requires advanced hardware"
},
{
"code": null,
"e": 1768,
"s": 1677,
"text": "Step 1: Use the following command to install the tool in your Kali Linux operating system."
},
{
"code": null,
"e": 1818,
"s": 1768,
"text": "git clone https://github.com/AssetX/XSS-Freak.git"
},
{
"code": null,
"e": 1956,
"s": 1818,
"text": "Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool."
},
{
"code": null,
"e": 1969,
"s": 1956,
"text": "cd XSS-Freak"
},
{
"code": null,
"e": 2103,
"s": 1969,
"text": "Step 3: You are in the directory of the XSS-Freak. Now you have to install a dependency of the XSS-Freak using the following command."
},
{
"code": null,
"e": 2141,
"s": 2103,
"text": "sudo pip3 install -r requirements.txt"
},
{
"code": null,
"e": 2301,
"s": 2141,
"text": "Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section."
},
{
"code": null,
"e": 2325,
"s": 2301,
"text": "python3 XSS-Freak.py -h"
},
{
"code": null,
"e": 2394,
"s": 2325,
"text": "Example 1: We will be testing http://geeksforgeeks.org target domain"
},
{
"code": null,
"e": 2516,
"s": 2394,
"text": "In this example, We will be testing the geeksforgeeks.org domain. We will specify the list of XSS consisting of Payloads."
},
{
"code": null,
"e": 2610,
"s": 2516,
"text": "As geeksforgeeks.org is Secured Website, the tool has not detected any vulnerable parameters."
},
{
"code": null,
"e": 2681,
"s": 2610,
"text": "Example 2: We will be testing http://testphp.vulnweb.com target domain"
},
{
"code": null,
"e": 2750,
"s": 2681,
"text": "In this example, We will be scanning the testphp.vulnweb.com domain."
},
{
"code": null,
"e": 2837,
"s": 2750,
"text": "We have got one vulnerable parameter or input through which we can insert the payload."
},
{
"code": null,
"e": 2848,
"s": 2837,
"text": "Kali-Linux"
},
{
"code": null,
"e": 2860,
"s": 2848,
"text": "Linux-Tools"
},
{
"code": null,
"e": 2871,
"s": 2860,
"text": "Linux-Unix"
}
]
|
Download Google Image Using Python and Selenium | 10 Jan, 2022
In this article, we are going to see how to download google Image using Python and Selenium.
On the terminal of your PC, type the following command.
pip install selenium
We also need to install a web driver that will help us to automatically run the web browser. You can install Firefox web driver, Internet Explorer web driver, or Chrome web driver. In this article, we will be using Chrome Web Driver.
The automation script interacts with the webpage by finding the element(s) we specified. There are various ways to find the elements in a webpage. The simplest way is to select the HTML tag of the desired element and copy its XPath. To do this, simply Right-Click on the webpage, click on “Inspect”, and copy the desired element’s XPath. You can also use the name or CSS of the element if you want to.
HTML of Google Images’ Result
Below is the implementation:
Python3
from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport time # What you enter here will be searched for in# Google Imagesquery = "dogs" # Creating a webdriver instancedriver = webdriver.Chrome('Enter-Location-Of-Your-Webdriver') # Maximize the screendriver.maximize_window() # Open Google Images in the browserdriver.get('https://images.google.com/') # Finding the search boxbox = driver.find_element_by_xpath('//*[@id="sbtc"]/div/div[2]/input') # Type the search query in the search boxbox.send_keys(query) # Pressing enterbox.send_keys(Keys.ENTER) # Function for scrolling to the bottom of Google# Images resultsdef scroll_to_bottom(): last_height = driver.execute_script('\ return document.body.scrollHeight') while True: driver.execute_script('\ window.scrollTo(0,document.body.scrollHeight)') # waiting for the results to load # Increase the sleep time if your internet is slow time.sleep(3) new_height = driver.execute_script('\ return document.body.scrollHeight') # click on "Show more results" (if exists) try: driver.find_element_by_css_selector(".YstHxe input").click() # waiting for the results to load # Increase the sleep time if your internet is slow time.sleep(3) except: pass # checking if we have reached the bottom of the page if new_height == last_height: break last_height = new_height # Calling the function # NOTE: If you only want to capture a few images,# there is no need to use the scroll_to_bottom() function.scroll_to_bottom() # Loop to capture and save each imagefor i in range(1, 50): # range(1, 50) will capture images 1 to 49 of the search results # You can change the range as per your need. try: # XPath of each image img = driver.find_element_by_xpath( '//*[@id="islrg"]/div[1]/div[' + str(i) + ']/a[1]/div[1]/img') # Enter the location of folder in which # the images will be saved img.screenshot('Download-Location' + query + ' (' + str(i) + ').png') # Each new screenshot will automatically # have its name updated # Just to avoid unwanted errors time.sleep(0.2) except: # if we can't find the XPath of an image, # we skip to the next image continue # Finally, we close the driverdriver.close()
Result:
Captured Images
Well, this is the simplest way to create an automation script. This small program can be your fun little project. This could be the starting point of your journey with Selenium. You can use Selenium to do different things like scrape news from Google News. So keep your mind open about new ideas and you might end up creating a great project with Selenium and Python.
prachisoda1234
Blogathon-2021
Python Selenium-Exercises
Python-selenium
Blogathon
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Jan, 2022"
},
{
"code": null,
"e": 148,
"s": 54,
"text": "In this article, we are going to see how to download google Image using Python and Selenium. "
},
{
"code": null,
"e": 204,
"s": 148,
"text": "On the terminal of your PC, type the following command."
},
{
"code": null,
"e": 225,
"s": 204,
"text": "pip install selenium"
},
{
"code": null,
"e": 459,
"s": 225,
"text": "We also need to install a web driver that will help us to automatically run the web browser. You can install Firefox web driver, Internet Explorer web driver, or Chrome web driver. In this article, we will be using Chrome Web Driver."
},
{
"code": null,
"e": 861,
"s": 459,
"text": "The automation script interacts with the webpage by finding the element(s) we specified. There are various ways to find the elements in a webpage. The simplest way is to select the HTML tag of the desired element and copy its XPath. To do this, simply Right-Click on the webpage, click on “Inspect”, and copy the desired element’s XPath. You can also use the name or CSS of the element if you want to."
},
{
"code": null,
"e": 891,
"s": 861,
"text": "HTML of Google Images’ Result"
},
{
"code": null,
"e": 920,
"s": 891,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 928,
"s": 920,
"text": "Python3"
},
{
"code": "from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport time # What you enter here will be searched for in# Google Imagesquery = \"dogs\" # Creating a webdriver instancedriver = webdriver.Chrome('Enter-Location-Of-Your-Webdriver') # Maximize the screendriver.maximize_window() # Open Google Images in the browserdriver.get('https://images.google.com/') # Finding the search boxbox = driver.find_element_by_xpath('//*[@id=\"sbtc\"]/div/div[2]/input') # Type the search query in the search boxbox.send_keys(query) # Pressing enterbox.send_keys(Keys.ENTER) # Function for scrolling to the bottom of Google# Images resultsdef scroll_to_bottom(): last_height = driver.execute_script('\\ return document.body.scrollHeight') while True: driver.execute_script('\\ window.scrollTo(0,document.body.scrollHeight)') # waiting for the results to load # Increase the sleep time if your internet is slow time.sleep(3) new_height = driver.execute_script('\\ return document.body.scrollHeight') # click on \"Show more results\" (if exists) try: driver.find_element_by_css_selector(\".YstHxe input\").click() # waiting for the results to load # Increase the sleep time if your internet is slow time.sleep(3) except: pass # checking if we have reached the bottom of the page if new_height == last_height: break last_height = new_height # Calling the function # NOTE: If you only want to capture a few images,# there is no need to use the scroll_to_bottom() function.scroll_to_bottom() # Loop to capture and save each imagefor i in range(1, 50): # range(1, 50) will capture images 1 to 49 of the search results # You can change the range as per your need. try: # XPath of each image img = driver.find_element_by_xpath( '//*[@id=\"islrg\"]/div[1]/div[' + str(i) + ']/a[1]/div[1]/img') # Enter the location of folder in which # the images will be saved img.screenshot('Download-Location' + query + ' (' + str(i) + ').png') # Each new screenshot will automatically # have its name updated # Just to avoid unwanted errors time.sleep(0.2) except: # if we can't find the XPath of an image, # we skip to the next image continue # Finally, we close the driverdriver.close()",
"e": 3419,
"s": 928,
"text": null
},
{
"code": null,
"e": 3427,
"s": 3419,
"text": "Result:"
},
{
"code": null,
"e": 3443,
"s": 3427,
"text": "Captured Images"
},
{
"code": null,
"e": 3811,
"s": 3443,
"text": "Well, this is the simplest way to create an automation script. This small program can be your fun little project. This could be the starting point of your journey with Selenium. You can use Selenium to do different things like scrape news from Google News. So keep your mind open about new ideas and you might end up creating a great project with Selenium and Python."
},
{
"code": null,
"e": 3826,
"s": 3811,
"text": "prachisoda1234"
},
{
"code": null,
"e": 3841,
"s": 3826,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 3867,
"s": 3841,
"text": "Python Selenium-Exercises"
},
{
"code": null,
"e": 3883,
"s": 3867,
"text": "Python-selenium"
},
{
"code": null,
"e": 3893,
"s": 3883,
"text": "Blogathon"
},
{
"code": null,
"e": 3900,
"s": 3893,
"text": "Python"
}
]
|
CSS touch-action Property | 20 Dec, 2020
The touch-action CSS property is used to change the view of the selected element with respect to the change in touch by the user, For example, zooming the image, scrolling the image, etc. It is the action made by the touchscreen user on a particular region selected on the screen.
Note: Panning is nothing but scrolling with one-finger on a touch-enabled.
Syntax:
touch-action: auto | none | [ [ pan-x | pan-left | pan-right ] ||
[ pan-y | pan-up | pan-down ] || pinch-zoom ] | manipulation
Property value:
none: This stops supporting all the activities like gestures and panning in the browser.
auto: This supports all the activities like gestures and panning in the browser.
pan-x | pan-y: pan-x supports horizontal panning interaction similarly pan-y supports vertical panning.
pan-left | pan-right | pan-up | pan-down: As the names describe they support left, right, up, down direction of panning activities.
pinch-zoom: This is used to make two-finger zoom-in and zoom-out interactions with the screen.
manipulation: It is the combination of pan-x pan-y pinch-zoom interactions.
Example 1: The following example demonstrates the touch-action: none option.
HTML
<!DOCTYPE html><html> <style type="text/css"> body { display: flex; flex-wrap: wrap; } .image { margin: 1rem; width: 300px; height: 300px; overflow: scroll; position: relative; margin-bottom: 15px; } .image img { width: 1200px; height: 1200px; } .touch-type { position: absolute; width: 100%; text-align: center; font-weight: bold; top: 130px; font-size: 24px; } .touch-none { touch-action: none; }</style> <body> <div class="image touch-none"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200617163105/gfg-logo.png"> <p class="touch-type"> touch-action:none; -This means we can't perform all paaning and zooming actions </p> </div></body> </html>
Output:
Example 2: The following example demonstrates the touch-action: auto option.
HTML
<!DOCTYPE html><html> <style type="text/css"> body { display: flex; flex-wrap: wrap; } .image { margin: 1rem; width: 300px; height: 300px; overflow: scroll; position: relative; margin-bottom: 15px; } .image img { width: 1200px; height: 1200px; } .touch-type { position: absolute; width: 100%; text-align: center; font-weight: bold; top: 130px; font-size: 24px; } .touch-auto { touch-action: auto; }</style> <body> <div class="image touch-auto"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200617163105/gfg-logo.png"> <p class="touch-type"> touch-action:auto - This means you can pan anywhere on screen </p> </div></body> </html>
Output:
Example 3: The following example demonstrates the touch-action: pan-x option.
HTML
<!DOCTYPE html><html> <style type="text/css"> body { display: flex; flex-wrap: wrap; } .image { margin: 1rem; width: 300px; height: 300px; overflow: scroll; position: relative; margin-bottom: 15px; } .image img { width: 1200px; height: 1200px; } .touch-type { position: absolute; width: 100%; text-align: center; font-weight: bold; top: 130px; font-size: 24px; } .touch-pan-x { touch-action: pan-x; }</style> <body> <div class="image touch-pan-x"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200617163105/gfg-logo.png"> <p class="touch-type"> touch-action: pan-x;-This means you can only scroll /pan in x-direction </p> </div></body> </html>
Output:
Example 4: The following example demonstrates the touch-action: pan-y option.
HTML
<!DOCTYPE html><html> <style type="text/css"> body { display: flex; flex-wrap: wrap; } .map { margin: 1rem; width: 300px; height: 300px; overflow: scroll; position: relative; margin-bottom: 15px; } .image img { width: 1200px; height: 1200px; } .touch-type { position: absolute; width: 100%; text-align: center; font-weight: bold; top: 130px; font-size: 24px; } .touch-pan-y { touch-action: pan-y; }</style> <body> <div class="image touch-pan-y"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200617163105/gfg-logo.png"> <p class="touch-type"> touch-action: pan-y;-This means you can only scroll /pan in y-direction </p> </div></body> </html>
Output:
Example 5: The following example demonstrates the touch-action: pan-right option.
HTML
<!DOCTYPE html><html> <style type="text/css"> body { display: flex; flex-wrap: wrap; } .image { margin: 1rem; width: 300px; height: 300px; overflow: scroll; position: relative; margin-bottom: 15px; } .image img { width: 1200px; height: 1200px; } .touch-type { position: absolute; width: 100%; text-align: center; font-weight: bold; top: 130px; font-size: 24px; } .touch-pan-right { touch-action: pan-right; }</style> <body> <div class="image touch-pan-right"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200617163105/gfg-logo.png"> <p class="touch-type"> touch-action:pan-right;-This means you can only scroll/pan in right direction </p> </div></body> </html>
Output:
CSS-Properties
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Dec, 2020"
},
{
"code": null,
"e": 309,
"s": 28,
"text": "The touch-action CSS property is used to change the view of the selected element with respect to the change in touch by the user, For example, zooming the image, scrolling the image, etc. It is the action made by the touchscreen user on a particular region selected on the screen."
},
{
"code": null,
"e": 384,
"s": 309,
"text": "Note: Panning is nothing but scrolling with one-finger on a touch-enabled."
},
{
"code": null,
"e": 392,
"s": 384,
"text": "Syntax:"
},
{
"code": null,
"e": 520,
"s": 392,
"text": "touch-action: auto | none | [ [ pan-x | pan-left | pan-right ] ||\n [ pan-y | pan-up | pan-down ] || pinch-zoom ] | manipulation"
},
{
"code": null,
"e": 536,
"s": 520,
"text": "Property value:"
},
{
"code": null,
"e": 625,
"s": 536,
"text": "none: This stops supporting all the activities like gestures and panning in the browser."
},
{
"code": null,
"e": 706,
"s": 625,
"text": "auto: This supports all the activities like gestures and panning in the browser."
},
{
"code": null,
"e": 810,
"s": 706,
"text": "pan-x | pan-y: pan-x supports horizontal panning interaction similarly pan-y supports vertical panning."
},
{
"code": null,
"e": 942,
"s": 810,
"text": "pan-left | pan-right | pan-up | pan-down: As the names describe they support left, right, up, down direction of panning activities."
},
{
"code": null,
"e": 1037,
"s": 942,
"text": "pinch-zoom: This is used to make two-finger zoom-in and zoom-out interactions with the screen."
},
{
"code": null,
"e": 1113,
"s": 1037,
"text": "manipulation: It is the combination of pan-x pan-y pinch-zoom interactions."
},
{
"code": null,
"e": 1190,
"s": 1113,
"text": "Example 1: The following example demonstrates the touch-action: none option."
},
{
"code": null,
"e": 1195,
"s": 1190,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <style type=\"text/css\"> body { display: flex; flex-wrap: wrap; } .image { margin: 1rem; width: 300px; height: 300px; overflow: scroll; position: relative; margin-bottom: 15px; } .image img { width: 1200px; height: 1200px; } .touch-type { position: absolute; width: 100%; text-align: center; font-weight: bold; top: 130px; font-size: 24px; } .touch-none { touch-action: none; }</style> <body> <div class=\"image touch-none\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200617163105/gfg-logo.png\"> <p class=\"touch-type\"> touch-action:none; -This means we can't perform all paaning and zooming actions </p> </div></body> </html>",
"e": 2089,
"s": 1195,
"text": null
},
{
"code": null,
"e": 2097,
"s": 2089,
"text": "Output:"
},
{
"code": null,
"e": 2174,
"s": 2097,
"text": "Example 2: The following example demonstrates the touch-action: auto option."
},
{
"code": null,
"e": 2179,
"s": 2174,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <style type=\"text/css\"> body { display: flex; flex-wrap: wrap; } .image { margin: 1rem; width: 300px; height: 300px; overflow: scroll; position: relative; margin-bottom: 15px; } .image img { width: 1200px; height: 1200px; } .touch-type { position: absolute; width: 100%; text-align: center; font-weight: bold; top: 130px; font-size: 24px; } .touch-auto { touch-action: auto; }</style> <body> <div class=\"image touch-auto\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200617163105/gfg-logo.png\"> <p class=\"touch-type\"> touch-action:auto - This means you can pan anywhere on screen </p> </div></body> </html>",
"e": 3043,
"s": 2179,
"text": null
},
{
"code": null,
"e": 3051,
"s": 3043,
"text": "Output:"
},
{
"code": null,
"e": 3129,
"s": 3051,
"text": "Example 3: The following example demonstrates the touch-action: pan-x option."
},
{
"code": null,
"e": 3134,
"s": 3129,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <style type=\"text/css\"> body { display: flex; flex-wrap: wrap; } .image { margin: 1rem; width: 300px; height: 300px; overflow: scroll; position: relative; margin-bottom: 15px; } .image img { width: 1200px; height: 1200px; } .touch-type { position: absolute; width: 100%; text-align: center; font-weight: bold; top: 130px; font-size: 24px; } .touch-pan-x { touch-action: pan-x; }</style> <body> <div class=\"image touch-pan-x\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200617163105/gfg-logo.png\"> <p class=\"touch-type\"> touch-action: pan-x;-This means you can only scroll /pan in x-direction </p> </div></body> </html>",
"e": 4020,
"s": 3134,
"text": null
},
{
"code": null,
"e": 4028,
"s": 4020,
"text": "Output:"
},
{
"code": null,
"e": 4106,
"s": 4028,
"text": "Example 4: The following example demonstrates the touch-action: pan-y option."
},
{
"code": null,
"e": 4111,
"s": 4106,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <style type=\"text/css\"> body { display: flex; flex-wrap: wrap; } .map { margin: 1rem; width: 300px; height: 300px; overflow: scroll; position: relative; margin-bottom: 15px; } .image img { width: 1200px; height: 1200px; } .touch-type { position: absolute; width: 100%; text-align: center; font-weight: bold; top: 130px; font-size: 24px; } .touch-pan-y { touch-action: pan-y; }</style> <body> <div class=\"image touch-pan-y\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200617163105/gfg-logo.png\"> <p class=\"touch-type\"> touch-action: pan-y;-This means you can only scroll /pan in y-direction </p> </div></body> </html>",
"e": 4997,
"s": 4111,
"text": null
},
{
"code": null,
"e": 5005,
"s": 4997,
"text": "Output:"
},
{
"code": null,
"e": 5087,
"s": 5005,
"text": "Example 5: The following example demonstrates the touch-action: pan-right option."
},
{
"code": null,
"e": 5092,
"s": 5087,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <style type=\"text/css\"> body { display: flex; flex-wrap: wrap; } .image { margin: 1rem; width: 300px; height: 300px; overflow: scroll; position: relative; margin-bottom: 15px; } .image img { width: 1200px; height: 1200px; } .touch-type { position: absolute; width: 100%; text-align: center; font-weight: bold; top: 130px; font-size: 24px; } .touch-pan-right { touch-action: pan-right; }</style> <body> <div class=\"image touch-pan-right\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200617163105/gfg-logo.png\"> <p class=\"touch-type\"> touch-action:pan-right;-This means you can only scroll/pan in right direction </p> </div></body> </html>",
"e": 6001,
"s": 5092,
"text": null
},
{
"code": null,
"e": 6009,
"s": 6001,
"text": "Output:"
},
{
"code": null,
"e": 6024,
"s": 6009,
"text": "CSS-Properties"
},
{
"code": null,
"e": 6031,
"s": 6024,
"text": "Picked"
},
{
"code": null,
"e": 6035,
"s": 6031,
"text": "CSS"
},
{
"code": null,
"e": 6052,
"s": 6035,
"text": "Web Technologies"
},
{
"code": null,
"e": 6150,
"s": 6052,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6189,
"s": 6150,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 6228,
"s": 6189,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 6267,
"s": 6228,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 6296,
"s": 6267,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 6333,
"s": 6296,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 6366,
"s": 6333,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 6427,
"s": 6366,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6470,
"s": 6427,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 6542,
"s": 6470,
"text": "Differences between Functional Components and Class Components in React"
}
]
|
Difference between Servlet and JSP | 29 Jun, 2022
Brief Introduction: Servlet technology is used to create a web application. A servlet is a Java class that is used to extend the capabilities of servers that host applications accessed by means of a request-response model. Servlets are mainly used to extend the applications hosted by web services.
JSP is used to create web applications just like Servlet technology. A JSP is a text document that contains two types of text: static data and dynamic data. The static data can be expressed in any text-based format (like HTML, XML, SVG, and WML), and the dynamic content can be expressed by JSP elements. Difference between Servlet and JSP
The difference between Servlet and JSP is as follows:
To read more about them in detail, read these articles on Servlet and JSP.
priyansh70890
siddharthredhu01
parkalevaibhav27
Java-JSP
java-servlet
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 352,
"s": 52,
"text": "Brief Introduction: Servlet technology is used to create a web application. A servlet is a Java class that is used to extend the capabilities of servers that host applications accessed by means of a request-response model. Servlets are mainly used to extend the applications hosted by web services. "
},
{
"code": null,
"e": 692,
"s": 352,
"text": "JSP is used to create web applications just like Servlet technology. A JSP is a text document that contains two types of text: static data and dynamic data. The static data can be expressed in any text-based format (like HTML, XML, SVG, and WML), and the dynamic content can be expressed by JSP elements. Difference between Servlet and JSP"
},
{
"code": null,
"e": 746,
"s": 692,
"text": "The difference between Servlet and JSP is as follows:"
},
{
"code": null,
"e": 821,
"s": 746,
"text": "To read more about them in detail, read these articles on Servlet and JSP."
},
{
"code": null,
"e": 835,
"s": 821,
"text": "priyansh70890"
},
{
"code": null,
"e": 852,
"s": 835,
"text": "siddharthredhu01"
},
{
"code": null,
"e": 869,
"s": 852,
"text": "parkalevaibhav27"
},
{
"code": null,
"e": 878,
"s": 869,
"text": "Java-JSP"
},
{
"code": null,
"e": 891,
"s": 878,
"text": "java-servlet"
},
{
"code": null,
"e": 896,
"s": 891,
"text": "Java"
},
{
"code": null,
"e": 901,
"s": 896,
"text": "Java"
}
]
|
How to return HTML or build HTML using JavaScript ? | 23 Apr, 2021
JavaScript is very powerful and with it, we can build dynamic web content and add many features to a web application. With HTML, we create the structure of the web page and the same thing can also be done with JavaScript.
There are few JavaScript methods called as createElement(), appendChild() with which we can add nodes to the DOM tree on the fly.
Example 1: Creating a div element
Say you just want to create a div element, then for that below is the code snippet:
let div_element = document.createElement("div")
Example 2: Adding a child node to an HTML element
Say there’s a div with ID “divele”
<div id="divele"></div>
And you want to add a paragraph element inside div. Below is the code snippet
Javascript
let div_elem = document.getElementById("divele") let child_p_elem = document.createElement("p") div_elem.appendChild(child_p_elem)
This code snippet is adding a paragraph element inside div with the help of appendChild() method.
Example 3: Removing a child node of an HTML element
Consider an unordered list having 3 list items in it. And you want to remove the first child <li> element in it.
HTML
<ul id="ulele"> <li>Food</li> <li>Milk</li> <li>Vegetable</li></ul>
Using the removeChild() method, we can remove the first <li> child from the unordered list:
Javascript
let ul_ele = document.getElementById("ulele") // 0 represents the first childul_ele.removeChild(ul_ele.childNodes[0])
Example 4: To access all the child elements of a parent HTML element
Now, to access all the child elements of the div having id “divele”, we will use the childNodes() method which will return the required child nodes.
Javascript
let div_ele = document.getElementById("divele") // Returns an array of child nodes// contained inside the parent nodelet div_ele_childs = div_ele.childNodes
Please find below the snapshot of the simple webpage that we are going to develop.
Complete Code:
HTML
<!DOCTYPE html><html lang="en"> <body> <div id="divele"> </div> <script type="text/javascript"> let parentDiv = document.getElementById("divele") let heading = document.createElement("h1") let unordered_list = document.createElement("ul") unordered_list.setAttribute("id", "ulele") heading.style.color = "green" heading.textContent = "GeeksforGeeks" parentDiv.appendChild(heading) parentDiv.appendChild(unordered_list) for (let i = 0; i < 4; i++) { let li_elem = document.createElement("li") unordered_list.appendChild(li_elem) } unordered_list.childNodes[0].textContent = "Java" unordered_list.childNodes[1].textContent = "Python" unordered_list.childNodes[2].textContent = "Javascript" unordered_list.childNodes[3].textContent = "C#" </script></body> </html>
Output:
HTML-Questions
JavaScript-Methods
JavaScript-Questions
Picked
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 252,
"s": 28,
"text": "JavaScript is very powerful and with it, we can build dynamic web content and add many features to a web application. With HTML, we create the structure of the web page and the same thing can also be done with JavaScript. "
},
{
"code": null,
"e": 383,
"s": 252,
"text": "There are few JavaScript methods called as createElement(), appendChild() with which we can add nodes to the DOM tree on the fly. "
},
{
"code": null,
"e": 417,
"s": 383,
"text": "Example 1: Creating a div element"
},
{
"code": null,
"e": 501,
"s": 417,
"text": "Say you just want to create a div element, then for that below is the code snippet:"
},
{
"code": null,
"e": 549,
"s": 501,
"text": "let div_element = document.createElement(\"div\")"
},
{
"code": null,
"e": 601,
"s": 551,
"text": "Example 2: Adding a child node to an HTML element"
},
{
"code": null,
"e": 636,
"s": 601,
"text": "Say there’s a div with ID “divele”"
},
{
"code": null,
"e": 660,
"s": 636,
"text": "<div id=\"divele\"></div>"
},
{
"code": null,
"e": 738,
"s": 660,
"text": "And you want to add a paragraph element inside div. Below is the code snippet"
},
{
"code": null,
"e": 749,
"s": 738,
"text": "Javascript"
},
{
"code": "let div_elem = document.getElementById(\"divele\") let child_p_elem = document.createElement(\"p\") div_elem.appendChild(child_p_elem)",
"e": 882,
"s": 749,
"text": null
},
{
"code": null,
"e": 980,
"s": 882,
"text": "This code snippet is adding a paragraph element inside div with the help of appendChild() method."
},
{
"code": null,
"e": 1032,
"s": 980,
"text": "Example 3: Removing a child node of an HTML element"
},
{
"code": null,
"e": 1146,
"s": 1032,
"text": "Consider an unordered list having 3 list items in it. And you want to remove the first child <li> element in it."
},
{
"code": null,
"e": 1151,
"s": 1146,
"text": "HTML"
},
{
"code": "<ul id=\"ulele\"> <li>Food</li> <li>Milk</li> <li>Vegetable</li></ul>",
"e": 1222,
"s": 1151,
"text": null
},
{
"code": null,
"e": 1314,
"s": 1222,
"text": "Using the removeChild() method, we can remove the first <li> child from the unordered list:"
},
{
"code": null,
"e": 1325,
"s": 1314,
"text": "Javascript"
},
{
"code": "let ul_ele = document.getElementById(\"ulele\") // 0 represents the first childul_ele.removeChild(ul_ele.childNodes[0])",
"e": 1444,
"s": 1325,
"text": null
},
{
"code": null,
"e": 1514,
"s": 1444,
"text": "Example 4: To access all the child elements of a parent HTML element "
},
{
"code": null,
"e": 1663,
"s": 1514,
"text": "Now, to access all the child elements of the div having id “divele”, we will use the childNodes() method which will return the required child nodes."
},
{
"code": null,
"e": 1674,
"s": 1663,
"text": "Javascript"
},
{
"code": "let div_ele = document.getElementById(\"divele\") // Returns an array of child nodes// contained inside the parent nodelet div_ele_childs = div_ele.childNodes ",
"e": 1833,
"s": 1674,
"text": null
},
{
"code": null,
"e": 1916,
"s": 1833,
"text": "Please find below the snapshot of the simple webpage that we are going to develop."
},
{
"code": null,
"e": 1931,
"s": 1916,
"text": "Complete Code:"
},
{
"code": null,
"e": 1936,
"s": 1931,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <body> <div id=\"divele\"> </div> <script type=\"text/javascript\"> let parentDiv = document.getElementById(\"divele\") let heading = document.createElement(\"h1\") let unordered_list = document.createElement(\"ul\") unordered_list.setAttribute(\"id\", \"ulele\") heading.style.color = \"green\" heading.textContent = \"GeeksforGeeks\" parentDiv.appendChild(heading) parentDiv.appendChild(unordered_list) for (let i = 0; i < 4; i++) { let li_elem = document.createElement(\"li\") unordered_list.appendChild(li_elem) } unordered_list.childNodes[0].textContent = \"Java\" unordered_list.childNodes[1].textContent = \"Python\" unordered_list.childNodes[2].textContent = \"Javascript\" unordered_list.childNodes[3].textContent = \"C#\" </script></body> </html>",
"e": 2849,
"s": 1936,
"text": null
},
{
"code": null,
"e": 2857,
"s": 2849,
"text": "Output:"
},
{
"code": null,
"e": 2872,
"s": 2857,
"text": "HTML-Questions"
},
{
"code": null,
"e": 2891,
"s": 2872,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 2912,
"s": 2891,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 2919,
"s": 2912,
"text": "Picked"
},
{
"code": null,
"e": 2924,
"s": 2919,
"text": "HTML"
},
{
"code": null,
"e": 2935,
"s": 2924,
"text": "JavaScript"
},
{
"code": null,
"e": 2952,
"s": 2935,
"text": "Web Technologies"
},
{
"code": null,
"e": 2957,
"s": 2952,
"text": "HTML"
},
{
"code": null,
"e": 3055,
"s": 2957,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3079,
"s": 3055,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3118,
"s": 3079,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3157,
"s": 3118,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 3194,
"s": 3157,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 3214,
"s": 3194,
"text": "Angular File Upload"
},
{
"code": null,
"e": 3275,
"s": 3214,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3347,
"s": 3275,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3387,
"s": 3347,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3439,
"s": 3387,
"text": "How to append HTML code to a div using JavaScript ?"
}
]
|
Different Input and Output Techniques in Python3 | 23 Jun, 2020
In this Article, we will learn some basic input-output techniques with the help of which we can easily follow the input and output format mentioned in the questions that we face in either daily coding life or in competitive programming.
1. Taking a single Input: A single input in Python can be taken using the input() method.
Example:
Python3
# For integersn = int(input()) # For floating or decimal numbersn = float(input()) # For Stringsn = input()
2. Taking Multiple Input: Multiple inputs in Python can be taken with the help of map() and split() method. The split() method splits the space separated inputs and returns an iterable whereas when this function is used with the map() function it can convert the inputs to float and int accordingly.
Example:
Python3
# For Stringsx, y = input().split() # For integers and floating point# numbersm, n = map(int, input().split()) m, n = map(float, input().split())
3. Taking variable number of input as list or tuple: For this the split() and map() functions can be used. As these functions return an iterable we can convert the given iterable to the list, tuple or set accordingly.
Example:
Python3
# For Input - 4 5 6 1 56 21 # (Space separated inputs)n = list(map(int, input().split()))print(n)
Output:
[4, 5, 6, 1, 56, 21]
4. Taking Fixed and variable number of input:
Python3
# Input: geeksforgeeks 2 0 2 0str, *lst = input().split()lst = list(map(int, lst)) print(str, lst)
Output:
geeksforgeeks [2, 0, 2, 0]
1. Output on different line: print() method is used in python for printing to console.
Example:
Python3
lst = ['geeks', 'for', 'geeks'] for i in lst: print(i)
Output:
geeks
for
geeks
2. Output on same line: end parameter in Python can be used to print on the same line.
Example 1:
Python3
lst = ['geeks', 'for', 'geeks'] for i in lst: print(i, end='')
Output:
geeksforgeeks
Example 2: Printing with space.
Python3
lst = ['geeks', 'for', 'geeks'] for i in lst: print(i,end=' ')
Output:
geeks for geeks
3. Output Formatting: If you want to format your output then you can do it with {} and format() function. {} is a placeholder for a variable that is provided in the format() like we have %d in C programming.
Example:
Python3
print('I love {}'.format('geeksforgeeks.')) print("I love {0} {1}".format('Python', 'programming.')
Output:
I love geeksforgeeks.
I love Python programming.
Note: For Formatting the integers or floating numbers the original method can be used in the {}. like ‘{%5.2f}’ or with the numbers we can write it as ‘{0:5.2f}’. We can also use string module ‘%’ operator to format our output.
nidhi_biet
python-basics
python-io
Python
python-io
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2020"
},
{
"code": null,
"e": 289,
"s": 52,
"text": "In this Article, we will learn some basic input-output techniques with the help of which we can easily follow the input and output format mentioned in the questions that we face in either daily coding life or in competitive programming."
},
{
"code": null,
"e": 380,
"s": 289,
"text": "1. Taking a single Input: A single input in Python can be taken using the input() method."
},
{
"code": null,
"e": 389,
"s": 380,
"text": "Example:"
},
{
"code": null,
"e": 397,
"s": 389,
"text": "Python3"
},
{
"code": "# For integersn = int(input()) # For floating or decimal numbersn = float(input()) # For Stringsn = input()",
"e": 507,
"s": 397,
"text": null
},
{
"code": null,
"e": 807,
"s": 507,
"text": "2. Taking Multiple Input: Multiple inputs in Python can be taken with the help of map() and split() method. The split() method splits the space separated inputs and returns an iterable whereas when this function is used with the map() function it can convert the inputs to float and int accordingly."
},
{
"code": null,
"e": 816,
"s": 807,
"text": "Example:"
},
{
"code": null,
"e": 824,
"s": 816,
"text": "Python3"
},
{
"code": "# For Stringsx, y = input().split() # For integers and floating point# numbersm, n = map(int, input().split()) m, n = map(float, input().split())",
"e": 971,
"s": 824,
"text": null
},
{
"code": null,
"e": 1189,
"s": 971,
"text": "3. Taking variable number of input as list or tuple: For this the split() and map() functions can be used. As these functions return an iterable we can convert the given iterable to the list, tuple or set accordingly."
},
{
"code": null,
"e": 1198,
"s": 1189,
"text": "Example:"
},
{
"code": null,
"e": 1206,
"s": 1198,
"text": "Python3"
},
{
"code": "# For Input - 4 5 6 1 56 21 # (Space separated inputs)n = list(map(int, input().split()))print(n)",
"e": 1304,
"s": 1206,
"text": null
},
{
"code": null,
"e": 1312,
"s": 1304,
"text": "Output:"
},
{
"code": null,
"e": 1334,
"s": 1312,
"text": "[4, 5, 6, 1, 56, 21]\n"
},
{
"code": null,
"e": 1381,
"s": 1334,
"text": "4. Taking Fixed and variable number of input: "
},
{
"code": null,
"e": 1389,
"s": 1381,
"text": "Python3"
},
{
"code": "# Input: geeksforgeeks 2 0 2 0str, *lst = input().split()lst = list(map(int, lst)) print(str, lst)",
"e": 1489,
"s": 1389,
"text": null
},
{
"code": null,
"e": 1497,
"s": 1489,
"text": "Output:"
},
{
"code": null,
"e": 1524,
"s": 1497,
"text": "geeksforgeeks [2, 0, 2, 0]"
},
{
"code": null,
"e": 1611,
"s": 1524,
"text": "1. Output on different line: print() method is used in python for printing to console."
},
{
"code": null,
"e": 1620,
"s": 1611,
"text": "Example:"
},
{
"code": null,
"e": 1628,
"s": 1620,
"text": "Python3"
},
{
"code": "lst = ['geeks', 'for', 'geeks'] for i in lst: print(i)",
"e": 1687,
"s": 1628,
"text": null
},
{
"code": null,
"e": 1695,
"s": 1687,
"text": "Output:"
},
{
"code": null,
"e": 1712,
"s": 1695,
"text": "geeks\nfor\ngeeks\n"
},
{
"code": null,
"e": 1799,
"s": 1712,
"text": "2. Output on same line: end parameter in Python can be used to print on the same line."
},
{
"code": null,
"e": 1810,
"s": 1799,
"text": "Example 1:"
},
{
"code": null,
"e": 1818,
"s": 1810,
"text": "Python3"
},
{
"code": "lst = ['geeks', 'for', 'geeks'] for i in lst: print(i, end='')",
"e": 1885,
"s": 1818,
"text": null
},
{
"code": null,
"e": 1893,
"s": 1885,
"text": "Output:"
},
{
"code": null,
"e": 1907,
"s": 1893,
"text": "geeksforgeeks"
},
{
"code": null,
"e": 1939,
"s": 1907,
"text": "Example 2: Printing with space."
},
{
"code": null,
"e": 1947,
"s": 1939,
"text": "Python3"
},
{
"code": "lst = ['geeks', 'for', 'geeks'] for i in lst: print(i,end=' ')",
"e": 2014,
"s": 1947,
"text": null
},
{
"code": null,
"e": 2022,
"s": 2014,
"text": "Output:"
},
{
"code": null,
"e": 2039,
"s": 2022,
"text": "geeks for geeks\n"
},
{
"code": null,
"e": 2247,
"s": 2039,
"text": "3. Output Formatting: If you want to format your output then you can do it with {} and format() function. {} is a placeholder for a variable that is provided in the format() like we have %d in C programming."
},
{
"code": null,
"e": 2256,
"s": 2247,
"text": "Example:"
},
{
"code": null,
"e": 2264,
"s": 2256,
"text": "Python3"
},
{
"code": "print('I love {}'.format('geeksforgeeks.')) print(\"I love {0} {1}\".format('Python', 'programming.')",
"e": 2365,
"s": 2264,
"text": null
},
{
"code": null,
"e": 2373,
"s": 2365,
"text": "Output:"
},
{
"code": null,
"e": 2423,
"s": 2373,
"text": "I love geeksforgeeks.\nI love Python programming.\n"
},
{
"code": null,
"e": 2651,
"s": 2423,
"text": "Note: For Formatting the integers or floating numbers the original method can be used in the {}. like ‘{%5.2f}’ or with the numbers we can write it as ‘{0:5.2f}’. We can also use string module ‘%’ operator to format our output."
},
{
"code": null,
"e": 2662,
"s": 2651,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2676,
"s": 2662,
"text": "python-basics"
},
{
"code": null,
"e": 2686,
"s": 2676,
"text": "python-io"
},
{
"code": null,
"e": 2693,
"s": 2686,
"text": "Python"
},
{
"code": null,
"e": 2703,
"s": 2693,
"text": "python-io"
}
]
|
How to change the plot line color from blue to black in Matplotlib? | To change the plot line color from blue to black, we can use setcolor() method−
Create x and y data points using numpy.
Plot line x and y using plot() method; store the returned value in line.
Set the color as black using set_color() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 10)
y = 4 * x + 5
line, = plt.plot(x, y, c='b')
line.set_color('black')
plt.show() | [
{
"code": null,
"e": 1142,
"s": 1062,
"text": "To change the plot line color from blue to black, we can use setcolor() method−"
},
{
"code": null,
"e": 1182,
"s": 1142,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1255,
"s": 1182,
"text": "Plot line x and y using plot() method; store the returned value in line."
},
{
"code": null,
"e": 1304,
"s": 1255,
"text": "Set the color as black using set_color() method."
},
{
"code": null,
"e": 1346,
"s": 1304,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1595,
"s": 1346,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(-2, 2, 10)\ny = 4 * x + 5\nline, = plt.plot(x, y, c='b')\nline.set_color('black')\nplt.show()"
}
]
|
SIP - Session Description Protocol | SDP stands for Session Description Protocol. It is used to describe multimedia sessions in a format understood by the participants over a network. Depending on this description, a party decides whether to join a conference or when or how to join a conference.
The owner of a conference advertises it over the network by sending multicast messages which contain description of the session e.g. the name of the owner, the name of the session, the coding, the timing etc. Depending on these information, the recipients of the advertisement take a decision about participation in the session.
The owner of a conference advertises it over the network by sending multicast messages which contain description of the session e.g. the name of the owner, the name of the session, the coding, the timing etc. Depending on these information, the recipients of the advertisement take a decision about participation in the session.
SDP is generally contained in the body part of Session Initiation Protocol popularly called SIP.
SDP is generally contained in the body part of Session Initiation Protocol popularly called SIP.
SDP is defined in RFC 2327. An SDP message is composed of a series of lines, called fields, whose names are abbreviated by a single lower-case letter, and are in a required order to simplify parsing.
SDP is defined in RFC 2327. An SDP message is composed of a series of lines, called fields, whose names are abbreviated by a single lower-case letter, and are in a required order to simplify parsing.
The purpose of SDP is to convey information about media streams in multimedia sessions to help participants join or gather info of a particular session.
SDP is a short structured textual description.
SDP is a short structured textual description.
It conveys the name and purpose of the session, the media, protocols, codec formats, timing and transport information.
It conveys the name and purpose of the session, the media, protocols, codec formats, timing and transport information.
A tentative participant checks these information and decides whether to join a session and how and when to join a session if it decides to do so.
A tentative participant checks these information and decides whether to join a session and how and when to join a session if it decides to do so.
The format has entries in the form of <type> = <value>, where the <type> defines a unique session parameter and the <value> provides a specific value for that parameter.
The format has entries in the form of <type> = <value>, where the <type> defines a unique session parameter and the <value> provides a specific value for that parameter.
The general form of a SDP message is −
x = parameter1 parameter2 ... parameterN
The general form of a SDP message is −
x = parameter1 parameter2 ... parameterN
The line begins with a single lower-case letter, for example, x. There are never any spaces between the letter and the =, and there is exactly one space between each parameter. Each field has a defined number of parameters.
The line begins with a single lower-case letter, for example, x. There are never any spaces between the letter and the =, and there is exactly one space between each parameter. Each field has a defined number of parameters.
Session description (* denotes optional)
v = (protocol version)
o = (owner/creator and session identifier)
s = (session name)
i =* (session information)
u =* (URI of description)
e =* (email address)
p =* (phone number)
c =* (connection information - not required if included in all media)
b =* (bandwidth information)
z =* (time zone adjustments)
k =* (encryption key)
a =* (zero or more session attribute lines)
The v= field contains the SDP version number. Because the current version of SDP is 0, a valid SDP message will always begin with v = 0.
The o= field contains information about the originator of the session and session identifiers. This field is used to uniquely identify the session.
The field contains −
o=<username><session-id><version><network-type><address-type>
The field contains −
o=<username><session-id><version><network-type><address-type>
The username parameter contains the originator’s login or host.
The username parameter contains the originator’s login or host.
The session-id parameter is a Network Time Protocol (NTP) timestamp or a random number used to ensure uniqueness.
The session-id parameter is a Network Time Protocol (NTP) timestamp or a random number used to ensure uniqueness.
The version is a numeric field that is increased for each change to the session, also recommended to be a NTP timestamp.
The version is a numeric field that is increased for each change to the session, also recommended to be a NTP timestamp.
The network-type is always IN for Internet. The address-type parameter is either IP4 or IP6 for IPv4 or IPv6 address either in dotted decimal form or a fully qualified host name.
The network-type is always IN for Internet. The address-type parameter is either IP4 or IP6 for IPv4 or IPv6 address either in dotted decimal form or a fully qualified host name.
The s= field contains a name for the session. It can contain any nonzero number of characters. The optional i= field contains information about the session. It can contain any number of characters.
The optional u= field contains a uniform resource indicator (URI) with more information about the session
The optional e= field contains an e-mail address of the host of the session. The optional p= field contains a phone number.
The c= field contains information about the media connection.
The field contains −
c =<network-type><address-type><connection-address>
The field contains −
c =<network-type><address-type><connection-address>
The network-type parameter is defined as IN for the Internet.
The network-type parameter is defined as IN for the Internet.
The address-type is defined as IP4 for IPv4 addresses and IP6 for IPv6 addresses.
The address-type is defined as IP4 for IPv4 addresses and IP6 for IPv6 addresses.
The connection-address is the IP address or host that will be sending the media packets, which could be either multicast or unicast.
The connection-address is the IP address or host that will be sending the media packets, which could be either multicast or unicast.
If multicast, the connection-address field contains −
connection-address=base-multicast-address/ttl/number-of-addresses
If multicast, the connection-address field contains −
connection-address=base-multicast-address/ttl/number-of-addresses
where ttl is the time-to-live value, and number-of-addresses indicates how many contiguous multicast addresses are included starting with the base-multicast address.
The optional b= field contains information about the bandwidth required. It is of the form −
b=modifier:bandwidth − value
The t= field contains the start time and stop time of the session.
t=start-time stop-time
The optional r= field contains information about the repeat times that can be specified in either in NTP or in days (d), hours (h), or minutes (m).
The optional z= field contains information about the time zone offsets. This field is used if are occurring session spans a change from daylight savings to standard time, or vice versa.
The optional m= field contains information about the type of media session. The field contains −
m= media port transport format-list
The media parameter is either audio, video, text, application, message, image, or control. The port parameter contains the port number.
The media parameter is either audio, video, text, application, message, image, or control. The port parameter contains the port number.
The transport parameter contains the transport protocol or the RTP profile used.
The transport parameter contains the transport protocol or the RTP profile used.
The format-list contains more information about the media. Usually, it contains media payload types defined in RTP audio video profiles.
The format-list contains more information about the media. Usually, it contains media payload types defined in RTP audio video profiles.
Example:
m = audio 49430 RTP/AVP 0 6 8 99
One of these three codecs can be used for the audio media session. If the intention is to establish three audio channels, three separate media fields would be used.
The optional a= field contains attributes of the preceding media session. This field can be used to extend SDP to provide more information about the media. If not fully understood by a SDP user, the attribute field can be ignored. There can be one or more attribute fields for each media payload type listed in the media field.
Attributes in SDP can be either
session level, or
media level.
Session level means that the attribute is listed before the first media line in the SDP. If this is the case, the attribute applies to all the media lines below it.
Media level means it is listed after a media line. In this case, the attribute only applies to this particular media stream.
SDP can include both session level and media level attributes. If the same attribute appears as both, the media level attribute overrides the session level attribute for that particular media stream. Note that the connection data field can also be either session level or media level.
Given below is an example session description, taken from RFC 2327 −
v = 0
o = mhandley2890844526 2890842807 IN IP4 126.16.64.4
s = SDP Seminar
i = A Seminar on the session description protocol
u = http://www.cs.ucl.ac.uk/staff/M.Handley/sdp.03.ps
e = [email protected](Mark Handley)
c = IN IP4 224.2.17.12/127
t = 2873397496 2873404696
a = recvonly
m = audio 49170 RTP/AVP 0
m = video 51372 RTP/AVP 31
m = application 32416udp wb
a = orient:portrait
27 Lectures
2.5 hours
Bernie Raffe
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2110,
"s": 1850,
"text": "SDP stands for Session Description Protocol. It is used to describe multimedia sessions in a format understood by the participants over a network. Depending on this description, a party decides whether to join a conference or when or how to join a conference."
},
{
"code": null,
"e": 2439,
"s": 2110,
"text": "The owner of a conference advertises it over the network by sending multicast messages which contain description of the session e.g. the name of the owner, the name of the session, the coding, the timing etc. Depending on these information, the recipients of the advertisement take a decision about participation in the session."
},
{
"code": null,
"e": 2768,
"s": 2439,
"text": "The owner of a conference advertises it over the network by sending multicast messages which contain description of the session e.g. the name of the owner, the name of the session, the coding, the timing etc. Depending on these information, the recipients of the advertisement take a decision about participation in the session."
},
{
"code": null,
"e": 2865,
"s": 2768,
"text": "SDP is generally contained in the body part of Session Initiation Protocol popularly called SIP."
},
{
"code": null,
"e": 2962,
"s": 2865,
"text": "SDP is generally contained in the body part of Session Initiation Protocol popularly called SIP."
},
{
"code": null,
"e": 3162,
"s": 2962,
"text": "SDP is defined in RFC 2327. An SDP message is composed of a series of lines, called fields, whose names are abbreviated by a single lower-case letter, and are in a required order to simplify parsing."
},
{
"code": null,
"e": 3362,
"s": 3162,
"text": "SDP is defined in RFC 2327. An SDP message is composed of a series of lines, called fields, whose names are abbreviated by a single lower-case letter, and are in a required order to simplify parsing."
},
{
"code": null,
"e": 3515,
"s": 3362,
"text": "The purpose of SDP is to convey information about media streams in multimedia sessions to help participants join or gather info of a particular session."
},
{
"code": null,
"e": 3562,
"s": 3515,
"text": "SDP is a short structured textual description."
},
{
"code": null,
"e": 3609,
"s": 3562,
"text": "SDP is a short structured textual description."
},
{
"code": null,
"e": 3728,
"s": 3609,
"text": "It conveys the name and purpose of the session, the media, protocols, codec formats, timing and transport information."
},
{
"code": null,
"e": 3847,
"s": 3728,
"text": "It conveys the name and purpose of the session, the media, protocols, codec formats, timing and transport information."
},
{
"code": null,
"e": 3993,
"s": 3847,
"text": "A tentative participant checks these information and decides whether to join a session and how and when to join a session if it decides to do so."
},
{
"code": null,
"e": 4139,
"s": 3993,
"text": "A tentative participant checks these information and decides whether to join a session and how and when to join a session if it decides to do so."
},
{
"code": null,
"e": 4309,
"s": 4139,
"text": "The format has entries in the form of <type> = <value>, where the <type> defines a unique session parameter and the <value> provides a specific value for that parameter."
},
{
"code": null,
"e": 4479,
"s": 4309,
"text": "The format has entries in the form of <type> = <value>, where the <type> defines a unique session parameter and the <value> provides a specific value for that parameter."
},
{
"code": null,
"e": 4559,
"s": 4479,
"text": "The general form of a SDP message is −\nx = parameter1 parameter2 ... parameterN"
},
{
"code": null,
"e": 4598,
"s": 4559,
"text": "The general form of a SDP message is −"
},
{
"code": null,
"e": 4639,
"s": 4598,
"text": "x = parameter1 parameter2 ... parameterN"
},
{
"code": null,
"e": 4863,
"s": 4639,
"text": "The line begins with a single lower-case letter, for example, x. There are never any spaces between the letter and the =, and there is exactly one space between each parameter. Each field has a defined number of parameters."
},
{
"code": null,
"e": 5087,
"s": 4863,
"text": "The line begins with a single lower-case letter, for example, x. There are never any spaces between the letter and the =, and there is exactly one space between each parameter. Each field has a defined number of parameters."
},
{
"code": null,
"e": 5128,
"s": 5087,
"text": "Session description (* denotes optional)"
},
{
"code": null,
"e": 5151,
"s": 5128,
"text": "v = (protocol version)"
},
{
"code": null,
"e": 5194,
"s": 5151,
"text": "o = (owner/creator and session identifier)"
},
{
"code": null,
"e": 5213,
"s": 5194,
"text": "s = (session name)"
},
{
"code": null,
"e": 5240,
"s": 5213,
"text": "i =* (session information)"
},
{
"code": null,
"e": 5266,
"s": 5240,
"text": "u =* (URI of description)"
},
{
"code": null,
"e": 5287,
"s": 5266,
"text": "e =* (email address)"
},
{
"code": null,
"e": 5307,
"s": 5287,
"text": "p =* (phone number)"
},
{
"code": null,
"e": 5377,
"s": 5307,
"text": "c =* (connection information - not required if included in all media)"
},
{
"code": null,
"e": 5406,
"s": 5377,
"text": "b =* (bandwidth information)"
},
{
"code": null,
"e": 5435,
"s": 5406,
"text": "z =* (time zone adjustments)"
},
{
"code": null,
"e": 5457,
"s": 5435,
"text": "k =* (encryption key)"
},
{
"code": null,
"e": 5501,
"s": 5457,
"text": "a =* (zero or more session attribute lines)"
},
{
"code": null,
"e": 5638,
"s": 5501,
"text": "The v= field contains the SDP version number. Because the current version of SDP is 0, a valid SDP message will always begin with v = 0."
},
{
"code": null,
"e": 5786,
"s": 5638,
"text": "The o= field contains information about the originator of the session and session identifiers. This field is used to uniquely identify the session."
},
{
"code": null,
"e": 5869,
"s": 5786,
"text": "The field contains −\no=<username><session-id><version><network-type><address-type>"
},
{
"code": null,
"e": 5890,
"s": 5869,
"text": "The field contains −"
},
{
"code": null,
"e": 5952,
"s": 5890,
"text": "o=<username><session-id><version><network-type><address-type>"
},
{
"code": null,
"e": 6016,
"s": 5952,
"text": "The username parameter contains the originator’s login or host."
},
{
"code": null,
"e": 6080,
"s": 6016,
"text": "The username parameter contains the originator’s login or host."
},
{
"code": null,
"e": 6194,
"s": 6080,
"text": "The session-id parameter is a Network Time Protocol (NTP) timestamp or a random number used to ensure uniqueness."
},
{
"code": null,
"e": 6308,
"s": 6194,
"text": "The session-id parameter is a Network Time Protocol (NTP) timestamp or a random number used to ensure uniqueness."
},
{
"code": null,
"e": 6429,
"s": 6308,
"text": "The version is a numeric field that is increased for each change to the session, also recommended to be a NTP timestamp."
},
{
"code": null,
"e": 6550,
"s": 6429,
"text": "The version is a numeric field that is increased for each change to the session, also recommended to be a NTP timestamp."
},
{
"code": null,
"e": 6729,
"s": 6550,
"text": "The network-type is always IN for Internet. The address-type parameter is either IP4 or IP6 for IPv4 or IPv6 address either in dotted decimal form or a fully qualified host name."
},
{
"code": null,
"e": 6908,
"s": 6729,
"text": "The network-type is always IN for Internet. The address-type parameter is either IP4 or IP6 for IPv4 or IPv6 address either in dotted decimal form or a fully qualified host name."
},
{
"code": null,
"e": 7106,
"s": 6908,
"text": "The s= field contains a name for the session. It can contain any nonzero number of characters. The optional i= field contains information about the session. It can contain any number of characters."
},
{
"code": null,
"e": 7212,
"s": 7106,
"text": "The optional u= field contains a uniform resource indicator (URI) with more information about the session"
},
{
"code": null,
"e": 7336,
"s": 7212,
"text": "The optional e= field contains an e-mail address of the host of the session. The optional p= field contains a phone number."
},
{
"code": null,
"e": 7398,
"s": 7336,
"text": "The c= field contains information about the media connection."
},
{
"code": null,
"e": 7471,
"s": 7398,
"text": "The field contains −\nc =<network-type><address-type><connection-address>"
},
{
"code": null,
"e": 7492,
"s": 7471,
"text": "The field contains −"
},
{
"code": null,
"e": 7544,
"s": 7492,
"text": "c =<network-type><address-type><connection-address>"
},
{
"code": null,
"e": 7606,
"s": 7544,
"text": "The network-type parameter is defined as IN for the Internet."
},
{
"code": null,
"e": 7668,
"s": 7606,
"text": "The network-type parameter is defined as IN for the Internet."
},
{
"code": null,
"e": 7750,
"s": 7668,
"text": "The address-type is defined as IP4 for IPv4 addresses and IP6 for IPv6 addresses."
},
{
"code": null,
"e": 7832,
"s": 7750,
"text": "The address-type is defined as IP4 for IPv4 addresses and IP6 for IPv6 addresses."
},
{
"code": null,
"e": 7965,
"s": 7832,
"text": "The connection-address is the IP address or host that will be sending the media packets, which could be either multicast or unicast."
},
{
"code": null,
"e": 8098,
"s": 7965,
"text": "The connection-address is the IP address or host that will be sending the media packets, which could be either multicast or unicast."
},
{
"code": null,
"e": 8218,
"s": 8098,
"text": "If multicast, the connection-address field contains −\nconnection-address=base-multicast-address/ttl/number-of-addresses"
},
{
"code": null,
"e": 8272,
"s": 8218,
"text": "If multicast, the connection-address field contains −"
},
{
"code": null,
"e": 8338,
"s": 8272,
"text": "connection-address=base-multicast-address/ttl/number-of-addresses"
},
{
"code": null,
"e": 8504,
"s": 8338,
"text": "where ttl is the time-to-live value, and number-of-addresses indicates how many contiguous multicast addresses are included starting with the base-multicast address."
},
{
"code": null,
"e": 8597,
"s": 8504,
"text": "The optional b= field contains information about the bandwidth required. It is of the form −"
},
{
"code": null,
"e": 8626,
"s": 8597,
"text": "b=modifier:bandwidth − value"
},
{
"code": null,
"e": 8693,
"s": 8626,
"text": "The t= field contains the start time and stop time of the session."
},
{
"code": null,
"e": 8716,
"s": 8693,
"text": "t=start-time stop-time"
},
{
"code": null,
"e": 8864,
"s": 8716,
"text": "The optional r= field contains information about the repeat times that can be specified in either in NTP or in days (d), hours (h), or minutes (m)."
},
{
"code": null,
"e": 9050,
"s": 8864,
"text": "The optional z= field contains information about the time zone offsets. This field is used if are occurring session spans a change from daylight savings to standard time, or vice versa."
},
{
"code": null,
"e": 9147,
"s": 9050,
"text": "The optional m= field contains information about the type of media session. The field contains −"
},
{
"code": null,
"e": 9183,
"s": 9147,
"text": "m= media port transport format-list"
},
{
"code": null,
"e": 9319,
"s": 9183,
"text": "The media parameter is either audio, video, text, application, message, image, or control. The port parameter contains the port number."
},
{
"code": null,
"e": 9455,
"s": 9319,
"text": "The media parameter is either audio, video, text, application, message, image, or control. The port parameter contains the port number."
},
{
"code": null,
"e": 9536,
"s": 9455,
"text": "The transport parameter contains the transport protocol or the RTP profile used."
},
{
"code": null,
"e": 9617,
"s": 9536,
"text": "The transport parameter contains the transport protocol or the RTP profile used."
},
{
"code": null,
"e": 9754,
"s": 9617,
"text": "The format-list contains more information about the media. Usually, it contains media payload types defined in RTP audio video profiles."
},
{
"code": null,
"e": 9891,
"s": 9754,
"text": "The format-list contains more information about the media. Usually, it contains media payload types defined in RTP audio video profiles."
},
{
"code": null,
"e": 9934,
"s": 9891,
"text": "Example:\nm = audio 49430 RTP/AVP 0 6 8 99\n"
},
{
"code": null,
"e": 10099,
"s": 9934,
"text": "One of these three codecs can be used for the audio media session. If the intention is to establish three audio channels, three separate media fields would be used."
},
{
"code": null,
"e": 10427,
"s": 10099,
"text": "The optional a= field contains attributes of the preceding media session. This field can be used to extend SDP to provide more information about the media. If not fully understood by a SDP user, the attribute field can be ignored. There can be one or more attribute fields for each media payload type listed in the media field."
},
{
"code": null,
"e": 10459,
"s": 10427,
"text": "Attributes in SDP can be either"
},
{
"code": null,
"e": 10477,
"s": 10459,
"text": "session level, or"
},
{
"code": null,
"e": 10490,
"s": 10477,
"text": "media level."
},
{
"code": null,
"e": 10655,
"s": 10490,
"text": "Session level means that the attribute is listed before the first media line in the SDP. If this is the case, the attribute applies to all the media lines below it."
},
{
"code": null,
"e": 10780,
"s": 10655,
"text": "Media level means it is listed after a media line. In this case, the attribute only applies to this particular media stream."
},
{
"code": null,
"e": 11065,
"s": 10780,
"text": "SDP can include both session level and media level attributes. If the same attribute appears as both, the media level attribute overrides the session level attribute for that particular media stream. Note that the connection data field can also be either session level or media level."
},
{
"code": null,
"e": 11134,
"s": 11065,
"text": "Given below is an example session description, taken from RFC 2327 −"
},
{
"code": null,
"e": 11511,
"s": 11134,
"text": "v = 0\no = mhandley2890844526 2890842807 IN IP4 126.16.64.4\ns = SDP Seminar\ni = A Seminar on the session description protocol\nu = http://www.cs.ucl.ac.uk/staff/M.Handley/sdp.03.ps\ne = [email protected](Mark Handley)\nc = IN IP4 224.2.17.12/127\nt = 2873397496 2873404696\na = recvonly\nm = audio 49170 RTP/AVP 0\nm = video 51372 RTP/AVP 31\nm = application 32416udp wb\na = orient:portrait\n"
},
{
"code": null,
"e": 11546,
"s": 11511,
"text": "\n 27 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11560,
"s": 11546,
"text": " Bernie Raffe"
},
{
"code": null,
"e": 11567,
"s": 11560,
"text": " Print"
},
{
"code": null,
"e": 11578,
"s": 11567,
"text": " Add Notes"
}
]
|
C library function - vprintf() | The C library function int vprintf(const char *format, va_list arg) sends formatted output to stdout using an argument list passed to it.
Following is the declaration for vprintf() function.
int vprintf(const char *format, va_list arg)
format − This is the String that contains the text to be written to buffer. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype would be − %[flags][width][.precision][length]specifier, as explained below −
format − This is the String that contains the text to be written to buffer. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype would be − %[flags][width][.precision][length]specifier, as explained below −
c
Character
d or i
Signed decimal integer
e
Scientific notation (mantissa/exponent) using e character
E
Scientific notation (mantissa/exponent) using E character
f
Decimal floating point
g
Uses the shorter of %e or %f
G
Uses the shorter of %E or %f
o
Signed octal
s
String of characters
u
Unsigned decimal integer
x
Unsigned hexadecimal integer
X
Unsigned hexadecimal integer (capital letters)
p
Pointer address
n
Nothing printed
%
Character
-
Left-justify within the given field width; Right justification is the default (see width sub-specifier).
+
Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a -ve sign.
(space)
If no sign is going to be written, a blank space is inserted before the value.
#
Used with o, x or X specifiers the value is preceded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed.
0
Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier).
(number)
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.number
For integer specifiers (d, i, o, u, x, X) − precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers − this is the number of digits to be printed after the decimal point. For g and G specifiers − This is the maximum number of significant digits to be printed. For s − this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type − it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
h
The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers − i, d, o, u, x and X).
l
The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.
L
The argument is interpreted as a long double (only applies to floating point specifiers − e, E, f, g and G).
arg − An object representing the variable arguments list. This should be initialized by the va_start macro defined in <stdarg>.
arg − An object representing the variable arguments list. This should be initialized by the va_start macro defined in <stdarg>.
If successful, the total number of characters written is returned otherwise a negative number is returned.
The following example shows the usage of vprintf() function.
#include <stdio.h>
#include <stdarg.h>
void WriteFrmtd(char *format, ...) {
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
}
int main () {
WriteFrmtd("%d variable argument\n", 1);
WriteFrmtd("%d variable %s\n", 2, "arguments");
return(0);
}
Let us compile and run the above program that will produce the following result −
1 variable argument
2 variable arguments
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2145,
"s": 2007,
"text": "The C library function int vprintf(const char *format, va_list arg) sends formatted output to stdout using an argument list passed to it."
},
{
"code": null,
"e": 2198,
"s": 2145,
"text": "Following is the declaration for vprintf() function."
},
{
"code": null,
"e": 2243,
"s": 2198,
"text": "int vprintf(const char *format, va_list arg)"
},
{
"code": null,
"e": 2571,
"s": 2243,
"text": "format − This is the String that contains the text to be written to buffer. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype would be − %[flags][width][.precision][length]specifier, as explained below −"
},
{
"code": null,
"e": 2899,
"s": 2571,
"text": "format − This is the String that contains the text to be written to buffer. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype would be − %[flags][width][.precision][length]specifier, as explained below −"
},
{
"code": null,
"e": 2901,
"s": 2899,
"text": "c"
},
{
"code": null,
"e": 2911,
"s": 2901,
"text": "Character"
},
{
"code": null,
"e": 2918,
"s": 2911,
"text": "d or i"
},
{
"code": null,
"e": 2941,
"s": 2918,
"text": "Signed decimal integer"
},
{
"code": null,
"e": 2943,
"s": 2941,
"text": "e"
},
{
"code": null,
"e": 3001,
"s": 2943,
"text": "Scientific notation (mantissa/exponent) using e character"
},
{
"code": null,
"e": 3003,
"s": 3001,
"text": "E"
},
{
"code": null,
"e": 3061,
"s": 3003,
"text": "Scientific notation (mantissa/exponent) using E character"
},
{
"code": null,
"e": 3063,
"s": 3061,
"text": "f"
},
{
"code": null,
"e": 3086,
"s": 3063,
"text": "Decimal floating point"
},
{
"code": null,
"e": 3088,
"s": 3086,
"text": "g"
},
{
"code": null,
"e": 3117,
"s": 3088,
"text": "Uses the shorter of %e or %f"
},
{
"code": null,
"e": 3119,
"s": 3117,
"text": "G"
},
{
"code": null,
"e": 3148,
"s": 3119,
"text": "Uses the shorter of %E or %f"
},
{
"code": null,
"e": 3150,
"s": 3148,
"text": "o"
},
{
"code": null,
"e": 3163,
"s": 3150,
"text": "Signed octal"
},
{
"code": null,
"e": 3165,
"s": 3163,
"text": "s"
},
{
"code": null,
"e": 3186,
"s": 3165,
"text": "String of characters"
},
{
"code": null,
"e": 3188,
"s": 3186,
"text": "u"
},
{
"code": null,
"e": 3213,
"s": 3188,
"text": "Unsigned decimal integer"
},
{
"code": null,
"e": 3215,
"s": 3213,
"text": "x"
},
{
"code": null,
"e": 3244,
"s": 3215,
"text": "Unsigned hexadecimal integer"
},
{
"code": null,
"e": 3246,
"s": 3244,
"text": "X"
},
{
"code": null,
"e": 3293,
"s": 3246,
"text": "Unsigned hexadecimal integer (capital letters)"
},
{
"code": null,
"e": 3295,
"s": 3293,
"text": "p"
},
{
"code": null,
"e": 3311,
"s": 3295,
"text": "Pointer address"
},
{
"code": null,
"e": 3313,
"s": 3311,
"text": "n"
},
{
"code": null,
"e": 3329,
"s": 3313,
"text": "Nothing printed"
},
{
"code": null,
"e": 3331,
"s": 3329,
"text": "%"
},
{
"code": null,
"e": 3341,
"s": 3331,
"text": "Character"
},
{
"code": null,
"e": 3343,
"s": 3341,
"text": "-"
},
{
"code": null,
"e": 3448,
"s": 3343,
"text": "Left-justify within the given field width; Right justification is the default (see width sub-specifier)."
},
{
"code": null,
"e": 3450,
"s": 3448,
"text": "+"
},
{
"code": null,
"e": 3605,
"s": 3450,
"text": "Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a -ve sign."
},
{
"code": null,
"e": 3613,
"s": 3605,
"text": "(space)"
},
{
"code": null,
"e": 3692,
"s": 3613,
"text": "If no sign is going to be written, a blank space is inserted before the value."
},
{
"code": null,
"e": 3694,
"s": 3692,
"text": "#"
},
{
"code": null,
"e": 4072,
"s": 3694,
"text": "Used with o, x or X specifiers the value is preceded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed."
},
{
"code": null,
"e": 4074,
"s": 4072,
"text": "0"
},
{
"code": null,
"e": 4184,
"s": 4074,
"text": "Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier)."
},
{
"code": null,
"e": 4193,
"s": 4184,
"text": "(number)"
},
{
"code": null,
"e": 4390,
"s": 4193,
"text": "Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger."
},
{
"code": null,
"e": 4392,
"s": 4390,
"text": "*"
},
{
"code": null,
"e": 4534,
"s": 4392,
"text": "The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted."
},
{
"code": null,
"e": 4542,
"s": 4534,
"text": ".number"
},
{
"code": null,
"e": 5371,
"s": 4542,
"text": "For integer specifiers (d, i, o, u, x, X) − precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers − this is the number of digits to be printed after the decimal point. For g and G specifiers − This is the maximum number of significant digits to be printed. For s − this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type − it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed."
},
{
"code": null,
"e": 5374,
"s": 5371,
"text": ".*"
},
{
"code": null,
"e": 5520,
"s": 5374,
"text": "The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted."
},
{
"code": null,
"e": 5522,
"s": 5520,
"text": "h"
},
{
"code": null,
"e": 5647,
"s": 5522,
"text": "The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers − i, d, o, u, x and X)."
},
{
"code": null,
"e": 5649,
"s": 5647,
"text": "l"
},
{
"code": null,
"e": 5831,
"s": 5649,
"text": "The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s."
},
{
"code": null,
"e": 5833,
"s": 5831,
"text": "L"
},
{
"code": null,
"e": 5942,
"s": 5833,
"text": "The argument is interpreted as a long double (only applies to floating point specifiers − e, E, f, g and G)."
},
{
"code": null,
"e": 6070,
"s": 5942,
"text": "arg − An object representing the variable arguments list. This should be initialized by the va_start macro defined in <stdarg>."
},
{
"code": null,
"e": 6198,
"s": 6070,
"text": "arg − An object representing the variable arguments list. This should be initialized by the va_start macro defined in <stdarg>."
},
{
"code": null,
"e": 6305,
"s": 6198,
"text": "If successful, the total number of characters written is returned otherwise a negative number is returned."
},
{
"code": null,
"e": 6366,
"s": 6305,
"text": "The following example shows the usage of vprintf() function."
},
{
"code": null,
"e": 6666,
"s": 6366,
"text": "#include <stdio.h>\n#include <stdarg.h>\n\nvoid WriteFrmtd(char *format, ...) {\n va_list args;\n \n va_start(args, format);\n vprintf(format, args);\n va_end(args);\n}\n\nint main () {\n WriteFrmtd(\"%d variable argument\\n\", 1);\n WriteFrmtd(\"%d variable %s\\n\", 2, \"arguments\");\n \n return(0);\n}"
},
{
"code": null,
"e": 6748,
"s": 6666,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 6790,
"s": 6748,
"text": "1 variable argument\n2 variable arguments\n"
},
{
"code": null,
"e": 6823,
"s": 6790,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6838,
"s": 6823,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6873,
"s": 6838,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6888,
"s": 6873,
"text": " Nishant Malik"
},
{
"code": null,
"e": 6923,
"s": 6888,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 6937,
"s": 6923,
"text": " Asif Hussain"
},
{
"code": null,
"e": 6970,
"s": 6937,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6988,
"s": 6970,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 7023,
"s": 6988,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7042,
"s": 7023,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 7075,
"s": 7042,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7087,
"s": 7075,
"text": " Amit Diwan"
},
{
"code": null,
"e": 7094,
"s": 7087,
"text": " Print"
},
{
"code": null,
"e": 7105,
"s": 7094,
"text": " Add Notes"
}
]
|
Groovy - subString() | Returns a new String that is a substring of this String. This method has 2 different variants
String substring(int beginIndex) − Pad the String with the spaces appended to the right.
String substring(int beginIndex) − Pad the String with the spaces appended to the right.
Syntax
String substring(int beginIndex)
Parameters
beginIndex − the begin index, inclusive.
beginIndex − the begin index, inclusive.
Return Value − The specified substring.
String substring(int beginIndex, int endIndex) − Pad the String with the padding characters appended to the right.
String substring(int beginIndex, int endIndex) − Pad the String with the padding characters appended to the right.
Syntax
String substring(int beginIndex, int endIndex)
Parameters
beginIndex − the begin index, inclusive.
beginIndex − the begin index, inclusive.
endIndex − the end index, exclusive.
endIndex − the end index, exclusive.
Return Value − The specified substring.
Following is an example of the usage of both variants −
class Example {
static void main(String[] args) {
String a = "HelloWorld";
println(a.substring(4));
println(a.substring(4,8));
}
}
When we run the above program, we will get the following result −
oWorld
oWor
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2332,
"s": 2238,
"text": "Returns a new String that is a substring of this String. This method has 2 different variants"
},
{
"code": null,
"e": 2421,
"s": 2332,
"text": "String substring(int beginIndex) − Pad the String with the spaces appended to the right."
},
{
"code": null,
"e": 2510,
"s": 2421,
"text": "String substring(int beginIndex) − Pad the String with the spaces appended to the right."
},
{
"code": null,
"e": 2517,
"s": 2510,
"text": "Syntax"
},
{
"code": null,
"e": 2551,
"s": 2517,
"text": "String substring(int beginIndex)\n"
},
{
"code": null,
"e": 2562,
"s": 2551,
"text": "Parameters"
},
{
"code": null,
"e": 2603,
"s": 2562,
"text": "beginIndex − the begin index, inclusive."
},
{
"code": null,
"e": 2644,
"s": 2603,
"text": "beginIndex − the begin index, inclusive."
},
{
"code": null,
"e": 2684,
"s": 2644,
"text": "Return Value − The specified substring."
},
{
"code": null,
"e": 2799,
"s": 2684,
"text": "String substring(int beginIndex, int endIndex) − Pad the String with the padding characters appended to the right."
},
{
"code": null,
"e": 2914,
"s": 2799,
"text": "String substring(int beginIndex, int endIndex) − Pad the String with the padding characters appended to the right."
},
{
"code": null,
"e": 2921,
"s": 2914,
"text": "Syntax"
},
{
"code": null,
"e": 2969,
"s": 2921,
"text": "String substring(int beginIndex, int endIndex)\n"
},
{
"code": null,
"e": 2980,
"s": 2969,
"text": "Parameters"
},
{
"code": null,
"e": 3021,
"s": 2980,
"text": "beginIndex − the begin index, inclusive."
},
{
"code": null,
"e": 3062,
"s": 3021,
"text": "beginIndex − the begin index, inclusive."
},
{
"code": null,
"e": 3099,
"s": 3062,
"text": "endIndex − the end index, exclusive."
},
{
"code": null,
"e": 3136,
"s": 3099,
"text": "endIndex − the end index, exclusive."
},
{
"code": null,
"e": 3176,
"s": 3136,
"text": "Return Value − The specified substring."
},
{
"code": null,
"e": 3232,
"s": 3176,
"text": "Following is an example of the usage of both variants −"
},
{
"code": null,
"e": 3391,
"s": 3232,
"text": "class Example { \n static void main(String[] args) { \n String a = \"HelloWorld\"; \n println(a.substring(4)); \n println(a.substring(4,8));\n }\n}"
},
{
"code": null,
"e": 3457,
"s": 3391,
"text": "When we run the above program, we will get the following result −"
},
{
"code": null,
"e": 3471,
"s": 3457,
"text": "oWorld \noWor\n"
},
{
"code": null,
"e": 3504,
"s": 3471,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3522,
"s": 3504,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 3557,
"s": 3522,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3575,
"s": 3557,
"text": " Packt Publishing"
},
{
"code": null,
"e": 3582,
"s": 3575,
"text": " Print"
},
{
"code": null,
"e": 3593,
"s": 3582,
"text": " Add Notes"
}
]
|
Count square and non-square numbers before n in C++ | We are given a number N. The goal is to find ordered pairs of positive numbers such that the sum of their cubes is N.
Traverse all numbers from 1 to N and check if it is a perfect square. If floor(sqrt(i))==ceil(sqrt(i)).
Then the number is a perfect square.
Perfect squares below N can be found using formula: floor(sqrt(N)).
Let’s understand with examples.
Input
N=20
Output
Count of square numbers: 4
Count of non-square numbers: 16
Explanation
Square numbers are 1, 4, 9 and 16. Rest all are non-squares and less than 20.
Input
N=40
Output
Count of square numbers: 6
Count of non-square numbers: 34
Explanation
Square numbers are 1, 4, 9, 16, 25, 36. Rest all are non-squares and less than 40.
We take integer N.
We take integer N.
Function squareNums(int n) takes n and returns the count of numbers below n that are perfect squares or non-squares.
Function squareNums(int n) takes n and returns the count of numbers below n that are perfect squares or non-squares.
Take the initial variable count as 0.
Take the initial variable count as 0.
Traverse using for loop from i=1 to i<=n
Traverse using for loop from i=1 to i<=n
If floor(sqrt(i))==ceil(sqrt(i)), then the number is a perfect square so increment count.
If floor(sqrt(i))==ceil(sqrt(i)), then the number is a perfect square so increment count.
At the end of all loops count will have a total number that are perfect squares.
At the end of all loops count will have a total number that are perfect squares.
N-squares will be numbers that are non squares
N-squares will be numbers that are non squares
Live Demo
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int squareNums(int n){
int count = 0;
for (int i = 1; i <= n; i++){
if(floor(sqrt(i))==ceil(sqrt(i)))
{ count++; }
}
return count;
}
int main(){
int N = 40;
int squares=squareNums(N);
cout <<endl<<"Count of squares numbers: "<<squares;
cout <<endl<<"Count of non-squares numbers: "<<N-squares;
return 0;
}
If we run the above code it will generate the following output −
Count of squares numbers: 6
Count of non-squares numbers: 34
We take integer N.
We take integer N.
Take variable squares = floor(sqrt(N)).
Take variable squares = floor(sqrt(N)).
Variable squares will have a number of perfect squares below N.
Variable squares will have a number of perfect squares below N.
N-squares will be the number of non-squares below N.
N-squares will be the number of non-squares below N.
Live Demo
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int main(){
int N = 40;
int squares=floor(sqrt(N));
cout <<endl<<"Count of squares numbers: "<<squares;
cout <<endl<<"Count of non-squares numbers: "<<N-squares;
return 0;
}
If we run the above code it will generate the following output −
Count of squares numbers: 6
Count of non-squares numbers: 34 | [
{
"code": null,
"e": 1180,
"s": 1062,
"text": "We are given a number N. The goal is to find ordered pairs of positive numbers such that the sum of their cubes is N."
},
{
"code": null,
"e": 1284,
"s": 1180,
"text": "Traverse all numbers from 1 to N and check if it is a perfect square. If floor(sqrt(i))==ceil(sqrt(i))."
},
{
"code": null,
"e": 1321,
"s": 1284,
"text": "Then the number is a perfect square."
},
{
"code": null,
"e": 1389,
"s": 1321,
"text": "Perfect squares below N can be found using formula: floor(sqrt(N))."
},
{
"code": null,
"e": 1421,
"s": 1389,
"text": "Let’s understand with examples."
},
{
"code": null,
"e": 1428,
"s": 1421,
"text": "Input "
},
{
"code": null,
"e": 1433,
"s": 1428,
"text": "N=20"
},
{
"code": null,
"e": 1441,
"s": 1433,
"text": "Output "
},
{
"code": null,
"e": 1500,
"s": 1441,
"text": "Count of square numbers: 4\nCount of non-square numbers: 16"
},
{
"code": null,
"e": 1513,
"s": 1500,
"text": "Explanation "
},
{
"code": null,
"e": 1591,
"s": 1513,
"text": "Square numbers are 1, 4, 9 and 16. Rest all are non-squares and less than 20."
},
{
"code": null,
"e": 1598,
"s": 1591,
"text": "Input "
},
{
"code": null,
"e": 1603,
"s": 1598,
"text": "N=40"
},
{
"code": null,
"e": 1611,
"s": 1603,
"text": "Output "
},
{
"code": null,
"e": 1670,
"s": 1611,
"text": "Count of square numbers: 6\nCount of non-square numbers: 34"
},
{
"code": null,
"e": 1683,
"s": 1670,
"text": "Explanation "
},
{
"code": null,
"e": 1766,
"s": 1683,
"text": "Square numbers are 1, 4, 9, 16, 25, 36. Rest all are non-squares and less than 40."
},
{
"code": null,
"e": 1785,
"s": 1766,
"text": "We take integer N."
},
{
"code": null,
"e": 1804,
"s": 1785,
"text": "We take integer N."
},
{
"code": null,
"e": 1921,
"s": 1804,
"text": "Function squareNums(int n) takes n and returns the count of numbers below n that are perfect squares or non-squares."
},
{
"code": null,
"e": 2038,
"s": 1921,
"text": "Function squareNums(int n) takes n and returns the count of numbers below n that are perfect squares or non-squares."
},
{
"code": null,
"e": 2076,
"s": 2038,
"text": "Take the initial variable count as 0."
},
{
"code": null,
"e": 2114,
"s": 2076,
"text": "Take the initial variable count as 0."
},
{
"code": null,
"e": 2155,
"s": 2114,
"text": "Traverse using for loop from i=1 to i<=n"
},
{
"code": null,
"e": 2196,
"s": 2155,
"text": "Traverse using for loop from i=1 to i<=n"
},
{
"code": null,
"e": 2286,
"s": 2196,
"text": "If floor(sqrt(i))==ceil(sqrt(i)), then the number is a perfect square so increment count."
},
{
"code": null,
"e": 2376,
"s": 2286,
"text": "If floor(sqrt(i))==ceil(sqrt(i)), then the number is a perfect square so increment count."
},
{
"code": null,
"e": 2457,
"s": 2376,
"text": "At the end of all loops count will have a total number that are perfect squares."
},
{
"code": null,
"e": 2538,
"s": 2457,
"text": "At the end of all loops count will have a total number that are perfect squares."
},
{
"code": null,
"e": 2585,
"s": 2538,
"text": "N-squares will be numbers that are non squares"
},
{
"code": null,
"e": 2632,
"s": 2585,
"text": "N-squares will be numbers that are non squares"
},
{
"code": null,
"e": 2643,
"s": 2632,
"text": " Live Demo"
},
{
"code": null,
"e": 3055,
"s": 2643,
"text": "#include <bits/stdc++.h>\n#include <math.h>\nusing namespace std;\nint squareNums(int n){\n int count = 0;\n for (int i = 1; i <= n; i++){\n if(floor(sqrt(i))==ceil(sqrt(i)))\n { count++; }\n }\n return count;\n}\nint main(){\n int N = 40;\n int squares=squareNums(N);\n cout <<endl<<\"Count of squares numbers: \"<<squares;\n cout <<endl<<\"Count of non-squares numbers: \"<<N-squares;\n return 0;\n}"
},
{
"code": null,
"e": 3120,
"s": 3055,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3181,
"s": 3120,
"text": "Count of squares numbers: 6\nCount of non-squares numbers: 34"
},
{
"code": null,
"e": 3200,
"s": 3181,
"text": "We take integer N."
},
{
"code": null,
"e": 3219,
"s": 3200,
"text": "We take integer N."
},
{
"code": null,
"e": 3259,
"s": 3219,
"text": "Take variable squares = floor(sqrt(N))."
},
{
"code": null,
"e": 3299,
"s": 3259,
"text": "Take variable squares = floor(sqrt(N))."
},
{
"code": null,
"e": 3363,
"s": 3299,
"text": "Variable squares will have a number of perfect squares below N."
},
{
"code": null,
"e": 3427,
"s": 3363,
"text": "Variable squares will have a number of perfect squares below N."
},
{
"code": null,
"e": 3480,
"s": 3427,
"text": "N-squares will be the number of non-squares below N."
},
{
"code": null,
"e": 3533,
"s": 3480,
"text": "N-squares will be the number of non-squares below N."
},
{
"code": null,
"e": 3544,
"s": 3533,
"text": " Live Demo"
},
{
"code": null,
"e": 3797,
"s": 3544,
"text": "#include <bits/stdc++.h>\n#include <math.h>\nusing namespace std;\nint main(){\n int N = 40;\n int squares=floor(sqrt(N));\n cout <<endl<<\"Count of squares numbers: \"<<squares;\n cout <<endl<<\"Count of non-squares numbers: \"<<N-squares;\n return 0;\n}"
},
{
"code": null,
"e": 3862,
"s": 3797,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3923,
"s": 3862,
"text": "Count of squares numbers: 6\nCount of non-squares numbers: 34"
}
]
|
Program to find the Nth Prime Number - GeeksforGeeks | 26 Apr, 2021
Given an integer N. The task is to find the Nth prime number.
Examples:
Input : 5 Output : 11
Input : 16 Output : 53
Input : 1049 Output : 8377
Approach:
Find the prime numbers up to MAX_SIZE using Sieve of Eratosthenes.
Store all primes in a vector.
For a given number N, return the element at (N-1)th index in a vector.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to the nth prime number #include <bits/stdc++.h>using namespace std; // initializing the max value#define MAX_SIZE 1000005 // Function to generate N prime numbers using// Sieve of Eratosthenesvoid SieveOfEratosthenes(vector<int>& primes){ // Create a boolean array "IsPrime[0..MAX_SIZE]" and // initialize all entries it as true. A value in // IsPrime[i] will finally be false if i is // Not a IsPrime, else true. bool IsPrime[MAX_SIZE]; memset(IsPrime, true, sizeof(IsPrime)); for (int p = 2; p * p < MAX_SIZE; p++) { // If IsPrime[p] is not changed, then it is a prime if (IsPrime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i < MAX_SIZE; i += p) IsPrime[i] = false; } } // Store all prime numbers for (int p = 2; p < MAX_SIZE; p++) if (IsPrime[p]) primes.push_back(p);} // Driver Codeint main(){ // To store all prime numbers vector<int> primes; // Function call SieveOfEratosthenes(primes); cout << "5th prime number is " << primes[4] << endl; cout << "16th prime number is " << primes[15] << endl; cout << "1049th prime number is " << primes[1048]; return 0;}
// Java program to the nth prime number import java.util.ArrayList;class GFG{ // initializing the max value static int MAX_SIZE = 1000005; // To store all prime numbers static ArrayList<Integer> primes = new ArrayList<Integer>(); // Function to generate N prime numbers // using Sieve of Eratosthenes static void SieveOfEratosthenes() { // Create a boolean array "IsPrime[0..MAX_SIZE]" // and initialize all entries it as true. // A value in IsPrime[i] will finally be false // if i is Not a IsPrime, else true. boolean [] IsPrime = new boolean[MAX_SIZE]; for(int i = 0; i < MAX_SIZE; i++) IsPrime[i] = true; for (int p = 2; p * p < MAX_SIZE; p++) { // If IsPrime[p] is not changed, // then it is a prime if (IsPrime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i < MAX_SIZE; i += p) IsPrime[i] = false; } } // Store all prime numbers for (int p = 2; p < MAX_SIZE; p++) if (IsPrime[p] == true) primes.add(p); } // Driver Code public static void main (String[] args) { // Function call SieveOfEratosthenes(); System.out.println("5th prime number is " + primes.get(4)); System.out.println("16th prime number is " + primes.get(15)); System.out.println("1049th prime number is " + primes.get(1048)); }} // This code is contributed by ihritik
# Python3 program to the nth prime number primes = [] # Function to generate N prime numbers using # Sieve of Eratosthenesdef SieveOfEratosthenes(): n = 1000005 # Create a boolean array "prime[0..n]" and # initialize all entries it as true. A value # in prime[i] will finally be false if i is # Not a prime, else true. prime = [True for i in range(n + 1)] p = 2 while (p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n + 1, p): prime[i] = False p += 1 # Print all prime numbers for p in range(2, n + 1): if prime[p]: primes.append(p) # Driver codeif __name__=='__main__': # Function call SieveOfEratosthenes() print("5th prime number is", primes[4]); print("16th prime number is", primes[15]); print("1049th prime number is", primes[1048]); # This code is contributed by grand_master
// C# program to the nth prime numberusing System;using System.Collections; class GFG{ // initializing the max valuestatic int MAX_SIZE = 1000005; // To store all prime numbersstatic ArrayList primes = new ArrayList(); // Function to generate N prime numbers using// Sieve of Eratosthenesstatic void SieveOfEratosthenes(){ // Create a boolean array "IsPrime[0..MAX_SIZE]" // and initialize all entries it as true. // A value in IsPrime[i] will finally be false // if i is Not a IsPrime, else true. bool [] IsPrime = new bool[MAX_SIZE]; for(int i = 0; i < MAX_SIZE; i++) IsPrime[i] = true; for (int p = 2; p * p < MAX_SIZE; p++) { // If IsPrime[p] is not changed, // then it is a prime if (IsPrime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i < MAX_SIZE; i += p) IsPrime[i] = false; } } // Store all prime numbers for (int p = 2; p < MAX_SIZE; p++) if (IsPrime[p] == true) primes.Add(p);} // Driver Codepublic static void Main (){ // Function call SieveOfEratosthenes(); Console.WriteLine("5th prime number is " + primes[4]); Console.WriteLine("16th prime number is " + primes[15]); Console.WriteLine("1049th prime number is " + primes[1048]);}} // This code is contributed by ihritik
<script> // Javascript program to the nth prime number // initializing the max valuevar MAX_SIZE = 1000005; // Function to generate N prime numbers using// Sieve of Eratosthenesfunction SieveOfEratosthenes(primes){ // Create a boolean array // "IsPrime[0..MAX_SIZE]" and // initialize all entries it as true. // A value in // IsPrime[i] will finally be false if i is // Not a IsPrime, else true. var IsPrime = Array(MAX_SIZE).fill(true); var p,i; for (p = 2; p * p < MAX_SIZE;p++) { // If IsPrime[p] is not changed, // then it is a prime if (IsPrime[p] == true) { // Update all multiples of p // greater than or // equal to the square of it // numbers which are multiple // of p and are // less than p^2 are already // been marked. for(i = p * p; i < MAX_SIZE; i += p) IsPrime[i] = false; } } // Store all prime numbers for (p = 2; p < MAX_SIZE; p++) if (IsPrime[p]) primes.push(p);} // Driver Code // To store all prime numbers var primes = []; // Function call SieveOfEratosthenes(primes); document.write( "5th prime number is "+primes[4]+"<br>" ); document.write( "16th prime number is "+primes[15]+"<br>" ); document.write( "1049th prime number is "+primes[1048]+"<br>" ); </script>
5th prime number is 11
16th prime number is 53
1049th prime number is 8377
ihritik
grand_master
ipg2016107
Prime Number
school-programming
sieve
Mathematical
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Program for Decimal to Binary Conversion
Algorithm to solve Rubik's Cube
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1 | [
{
"code": null,
"e": 24668,
"s": 24640,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 24730,
"s": 24668,
"text": "Given an integer N. The task is to find the Nth prime number."
},
{
"code": null,
"e": 24742,
"s": 24730,
"text": "Examples: "
},
{
"code": null,
"e": 24764,
"s": 24742,
"text": "Input : 5 Output : 11"
},
{
"code": null,
"e": 24787,
"s": 24764,
"text": "Input : 16 Output : 53"
},
{
"code": null,
"e": 24815,
"s": 24787,
"text": "Input : 1049 Output : 8377 "
},
{
"code": null,
"e": 24827,
"s": 24815,
"text": "Approach: "
},
{
"code": null,
"e": 24894,
"s": 24827,
"text": "Find the prime numbers up to MAX_SIZE using Sieve of Eratosthenes."
},
{
"code": null,
"e": 24924,
"s": 24894,
"text": "Store all primes in a vector."
},
{
"code": null,
"e": 24995,
"s": 24924,
"text": "For a given number N, return the element at (N-1)th index in a vector."
},
{
"code": null,
"e": 25047,
"s": 24995,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25051,
"s": 25047,
"text": "C++"
},
{
"code": null,
"e": 25056,
"s": 25051,
"text": "Java"
},
{
"code": null,
"e": 25064,
"s": 25056,
"text": "Python3"
},
{
"code": null,
"e": 25067,
"s": 25064,
"text": "C#"
},
{
"code": null,
"e": 25078,
"s": 25067,
"text": "Javascript"
},
{
"code": "// C++ program to the nth prime number #include <bits/stdc++.h>using namespace std; // initializing the max value#define MAX_SIZE 1000005 // Function to generate N prime numbers using// Sieve of Eratosthenesvoid SieveOfEratosthenes(vector<int>& primes){ // Create a boolean array \"IsPrime[0..MAX_SIZE]\" and // initialize all entries it as true. A value in // IsPrime[i] will finally be false if i is // Not a IsPrime, else true. bool IsPrime[MAX_SIZE]; memset(IsPrime, true, sizeof(IsPrime)); for (int p = 2; p * p < MAX_SIZE; p++) { // If IsPrime[p] is not changed, then it is a prime if (IsPrime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i < MAX_SIZE; i += p) IsPrime[i] = false; } } // Store all prime numbers for (int p = 2; p < MAX_SIZE; p++) if (IsPrime[p]) primes.push_back(p);} // Driver Codeint main(){ // To store all prime numbers vector<int> primes; // Function call SieveOfEratosthenes(primes); cout << \"5th prime number is \" << primes[4] << endl; cout << \"16th prime number is \" << primes[15] << endl; cout << \"1049th prime number is \" << primes[1048]; return 0;}",
"e": 26475,
"s": 25078,
"text": null
},
{
"code": "// Java program to the nth prime number import java.util.ArrayList;class GFG{ // initializing the max value static int MAX_SIZE = 1000005; // To store all prime numbers static ArrayList<Integer> primes = new ArrayList<Integer>(); // Function to generate N prime numbers // using Sieve of Eratosthenes static void SieveOfEratosthenes() { // Create a boolean array \"IsPrime[0..MAX_SIZE]\" // and initialize all entries it as true. // A value in IsPrime[i] will finally be false // if i is Not a IsPrime, else true. boolean [] IsPrime = new boolean[MAX_SIZE]; for(int i = 0; i < MAX_SIZE; i++) IsPrime[i] = true; for (int p = 2; p * p < MAX_SIZE; p++) { // If IsPrime[p] is not changed, // then it is a prime if (IsPrime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i < MAX_SIZE; i += p) IsPrime[i] = false; } } // Store all prime numbers for (int p = 2; p < MAX_SIZE; p++) if (IsPrime[p] == true) primes.add(p); } // Driver Code public static void main (String[] args) { // Function call SieveOfEratosthenes(); System.out.println(\"5th prime number is \" + primes.get(4)); System.out.println(\"16th prime number is \" + primes.get(15)); System.out.println(\"1049th prime number is \" + primes.get(1048)); }} // This code is contributed by ihritik",
"e": 28362,
"s": 26475,
"text": null
},
{
"code": "# Python3 program to the nth prime number primes = [] # Function to generate N prime numbers using # Sieve of Eratosthenesdef SieveOfEratosthenes(): n = 1000005 # Create a boolean array \"prime[0..n]\" and # initialize all entries it as true. A value # in prime[i] will finally be false if i is # Not a prime, else true. prime = [True for i in range(n + 1)] p = 2 while (p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n + 1, p): prime[i] = False p += 1 # Print all prime numbers for p in range(2, n + 1): if prime[p]: primes.append(p) # Driver codeif __name__=='__main__': # Function call SieveOfEratosthenes() print(\"5th prime number is\", primes[4]); print(\"16th prime number is\", primes[15]); print(\"1049th prime number is\", primes[1048]); # This code is contributed by grand_master",
"e": 29444,
"s": 28362,
"text": null
},
{
"code": "// C# program to the nth prime numberusing System;using System.Collections; class GFG{ // initializing the max valuestatic int MAX_SIZE = 1000005; // To store all prime numbersstatic ArrayList primes = new ArrayList(); // Function to generate N prime numbers using// Sieve of Eratosthenesstatic void SieveOfEratosthenes(){ // Create a boolean array \"IsPrime[0..MAX_SIZE]\" // and initialize all entries it as true. // A value in IsPrime[i] will finally be false // if i is Not a IsPrime, else true. bool [] IsPrime = new bool[MAX_SIZE]; for(int i = 0; i < MAX_SIZE; i++) IsPrime[i] = true; for (int p = 2; p * p < MAX_SIZE; p++) { // If IsPrime[p] is not changed, // then it is a prime if (IsPrime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i < MAX_SIZE; i += p) IsPrime[i] = false; } } // Store all prime numbers for (int p = 2; p < MAX_SIZE; p++) if (IsPrime[p] == true) primes.Add(p);} // Driver Codepublic static void Main (){ // Function call SieveOfEratosthenes(); Console.WriteLine(\"5th prime number is \" + primes[4]); Console.WriteLine(\"16th prime number is \" + primes[15]); Console.WriteLine(\"1049th prime number is \" + primes[1048]);}} // This code is contributed by ihritik",
"e": 31075,
"s": 29444,
"text": null
},
{
"code": "<script> // Javascript program to the nth prime number // initializing the max valuevar MAX_SIZE = 1000005; // Function to generate N prime numbers using// Sieve of Eratosthenesfunction SieveOfEratosthenes(primes){ // Create a boolean array // \"IsPrime[0..MAX_SIZE]\" and // initialize all entries it as true. // A value in // IsPrime[i] will finally be false if i is // Not a IsPrime, else true. var IsPrime = Array(MAX_SIZE).fill(true); var p,i; for (p = 2; p * p < MAX_SIZE;p++) { // If IsPrime[p] is not changed, // then it is a prime if (IsPrime[p] == true) { // Update all multiples of p // greater than or // equal to the square of it // numbers which are multiple // of p and are // less than p^2 are already // been marked. for(i = p * p; i < MAX_SIZE; i += p) IsPrime[i] = false; } } // Store all prime numbers for (p = 2; p < MAX_SIZE; p++) if (IsPrime[p]) primes.push(p);} // Driver Code // To store all prime numbers var primes = []; // Function call SieveOfEratosthenes(primes); document.write( \"5th prime number is \"+primes[4]+\"<br>\" ); document.write( \"16th prime number is \"+primes[15]+\"<br>\" ); document.write( \"1049th prime number is \"+primes[1048]+\"<br>\" ); </script>",
"e": 32504,
"s": 31075,
"text": null
},
{
"code": null,
"e": 32579,
"s": 32504,
"text": "5th prime number is 11\n16th prime number is 53\n1049th prime number is 8377"
},
{
"code": null,
"e": 32589,
"s": 32581,
"text": "ihritik"
},
{
"code": null,
"e": 32602,
"s": 32589,
"text": "grand_master"
},
{
"code": null,
"e": 32613,
"s": 32602,
"text": "ipg2016107"
},
{
"code": null,
"e": 32626,
"s": 32613,
"text": "Prime Number"
},
{
"code": null,
"e": 32645,
"s": 32626,
"text": "school-programming"
},
{
"code": null,
"e": 32651,
"s": 32645,
"text": "sieve"
},
{
"code": null,
"e": 32664,
"s": 32651,
"text": "Mathematical"
},
{
"code": null,
"e": 32677,
"s": 32664,
"text": "Mathematical"
},
{
"code": null,
"e": 32690,
"s": 32677,
"text": "Prime Number"
},
{
"code": null,
"e": 32696,
"s": 32690,
"text": "sieve"
},
{
"code": null,
"e": 32794,
"s": 32696,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32803,
"s": 32794,
"text": "Comments"
},
{
"code": null,
"e": 32816,
"s": 32803,
"text": "Old Comments"
},
{
"code": null,
"e": 32840,
"s": 32816,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 32883,
"s": 32840,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 32897,
"s": 32883,
"text": "Prime Numbers"
},
{
"code": null,
"e": 32946,
"s": 32897,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 32980,
"s": 32946,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 33001,
"s": 32980,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 33042,
"s": 33001,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 33074,
"s": 33042,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 33111,
"s": 33074,
"text": "Minimum number of jumps to reach end"
}
]
|
Getting Highest and Lowest Value Element From a Set by Using Sorting Logic on TreeSet in Java - GeeksforGeeks | 28 Dec, 2020
TreeSet in java implements the Set Interface and uses a red-black tree for storing values. We use TreeSet for sorting as the elements in TreeSet are stored in ascending order by default. Once the TreeSet is created, we can get the Highest Element Value from the Last element of the TreeSet and the first element value from the first element of TreeSet. We have to pass the Comparator objects along with the TreeSet declaration first. Now, we can simply do this by Creating a TreeSet and adding elements and then sorting the elements by a certain attribute, finally getting the Highest element by last() and lowest by first() functions on TreeSet. We will have to Override the compare method for implementing the Sorting. The TreeSet Declaration would follow the Syntax given below :
Syntax
TreeSet<Comparator> name = new TreeSet<Comparator>(new ComparatorClass());
Parameters
name: Name of the TreeSet Created
Comparator: Comparator Object
ComparatorClass(): Class used for implementing Sorting Function(compare method)
Returns: TreeSet where we can add values
For example, we want to create a TreeSet having names and Age of a group, and we want to find the Person with the highest Age and Value and with the lowest Age and Value
Example 1:
Input :
Name - "Ramesh" Age - 20
Name - "Suresh" Age - 48
Name - "Ankit" Age - 14
Name - "Madhav" Age - 78
Output :
Highest Age Person: Name : Madhav-- Age : 78
Lowest Age Person: Name : Ankit-- Age : 14
Example 2:
Input :
Name - "Ramesh" Age - 20
Name - "Suresh" Age - 20
Name - "Ankit" Age - 78
Name - "Madhav" Age - 78
Output :
Highest Age Person: Name : Ankit-- Age : 78
Lowest Age Person: Name : Suresh-- Age : 14
Explanation
For example1 all the ages are distinct so highest and lowest are found based on age value.
For example2 highest age values are the same so the person name at last() of treeset is given the highest value i.e ‘A’ < ‘M’ so Ankit has the highest age whereas if the lowest age values are the same name at first() of treeset is given lowest value i.e ‘S’ > ‘R’ so Suresh has the lowest age.
Example:
Java
// Getting Highest and Lowest Value // Element From a Set by Using Sorting // Logic on TreeSet in Java import java.util.*;import java.io.*;import java.util.Comparator;import java.util.TreeSet; // Implement sorting class using comparator to sortclass sorting implements Comparator<ages> { // Override the Compare Method @Override public int compare(ages age1, ages age2) { if (age1.value() > age2.value()) { return 1; } else { return -1; } }} // Implement ages for getting name and ageclass ages { private String name; private int age; public ages(String name, int a) { this.name = name; this.age = a; } public String Name() { return name; } public void NewName(String name) { this.name = name; } public int value() { return age; } public void NewAge(int age) { this.age = age; } // Convert to string output public String toString() { return "Name: " + this.name + "-- age: " + this.age; }} public class GFG { public static void main(String[] args) { // Create a TreeSet with Comporator Object TreeSet<ages> agetree = new TreeSet<ages>(new sorting()); // Add elements in TreeSet agetree.add(new ages("Ramesh", 20)); agetree.add(new ages("Suresh", 20)); agetree.add(new ages("Ankit", 78)); agetree.add(new ages("Madhav", 78)); // Output Highest Value Element System.out.println("Highest Age Person: " + agetree.last()); // Output Lowest Value Element System.out.println("Lowest Age Person: " + agetree.first()); }}
Highest Age Person: Name: Ankit-- age: 78
Lowest Age Person: Name: Suresh-- age: 20
java-treeset
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 24731,
"s": 23948,
"text": "TreeSet in java implements the Set Interface and uses a red-black tree for storing values. We use TreeSet for sorting as the elements in TreeSet are stored in ascending order by default. Once the TreeSet is created, we can get the Highest Element Value from the Last element of the TreeSet and the first element value from the first element of TreeSet. We have to pass the Comparator objects along with the TreeSet declaration first. Now, we can simply do this by Creating a TreeSet and adding elements and then sorting the elements by a certain attribute, finally getting the Highest element by last() and lowest by first() functions on TreeSet. We will have to Override the compare method for implementing the Sorting. The TreeSet Declaration would follow the Syntax given below :"
},
{
"code": null,
"e": 24738,
"s": 24731,
"text": "Syntax"
},
{
"code": null,
"e": 24813,
"s": 24738,
"text": "TreeSet<Comparator> name = new TreeSet<Comparator>(new ComparatorClass());"
},
{
"code": null,
"e": 24824,
"s": 24813,
"text": "Parameters"
},
{
"code": null,
"e": 24858,
"s": 24824,
"text": "name: Name of the TreeSet Created"
},
{
"code": null,
"e": 24888,
"s": 24858,
"text": "Comparator: Comparator Object"
},
{
"code": null,
"e": 24968,
"s": 24888,
"text": "ComparatorClass(): Class used for implementing Sorting Function(compare method)"
},
{
"code": null,
"e": 25009,
"s": 24968,
"text": "Returns: TreeSet where we can add values"
},
{
"code": null,
"e": 25179,
"s": 25009,
"text": "For example, we want to create a TreeSet having names and Age of a group, and we want to find the Person with the highest Age and Value and with the lowest Age and Value"
},
{
"code": null,
"e": 25190,
"s": 25179,
"text": "Example 1:"
},
{
"code": null,
"e": 25395,
"s": 25190,
"text": "Input :\nName - \"Ramesh\" Age - 20\nName - \"Suresh\" Age - 48\nName - \"Ankit\" Age - 14\nName - \"Madhav\" Age - 78\n\nOutput :\nHighest Age Person: Name : Madhav-- Age : 78\nLowest Age Person: Name : Ankit-- Age : 14"
},
{
"code": null,
"e": 25406,
"s": 25395,
"text": "Example 2:"
},
{
"code": null,
"e": 25611,
"s": 25406,
"text": "Input :\nName - \"Ramesh\" Age - 20\nName - \"Suresh\" Age - 20\nName - \"Ankit\" Age - 78\nName - \"Madhav\" Age - 78\n\nOutput :\nHighest Age Person: Name : Ankit-- Age : 78\nLowest Age Person: Name : Suresh-- Age : 14"
},
{
"code": null,
"e": 25624,
"s": 25611,
"text": "Explanation "
},
{
"code": null,
"e": 25715,
"s": 25624,
"text": "For example1 all the ages are distinct so highest and lowest are found based on age value."
},
{
"code": null,
"e": 26010,
"s": 25715,
"text": "For example2 highest age values are the same so the person name at last() of treeset is given the highest value i.e ‘A’ < ‘M’ so Ankit has the highest age whereas if the lowest age values are the same name at first() of treeset is given lowest value i.e ‘S’ > ‘R’ so Suresh has the lowest age."
},
{
"code": null,
"e": 26019,
"s": 26010,
"text": "Example:"
},
{
"code": null,
"e": 26024,
"s": 26019,
"text": "Java"
},
{
"code": "// Getting Highest and Lowest Value // Element From a Set by Using Sorting // Logic on TreeSet in Java import java.util.*;import java.io.*;import java.util.Comparator;import java.util.TreeSet; // Implement sorting class using comparator to sortclass sorting implements Comparator<ages> { // Override the Compare Method @Override public int compare(ages age1, ages age2) { if (age1.value() > age2.value()) { return 1; } else { return -1; } }} // Implement ages for getting name and ageclass ages { private String name; private int age; public ages(String name, int a) { this.name = name; this.age = a; } public String Name() { return name; } public void NewName(String name) { this.name = name; } public int value() { return age; } public void NewAge(int age) { this.age = age; } // Convert to string output public String toString() { return \"Name: \" + this.name + \"-- age: \" + this.age; }} public class GFG { public static void main(String[] args) { // Create a TreeSet with Comporator Object TreeSet<ages> agetree = new TreeSet<ages>(new sorting()); // Add elements in TreeSet agetree.add(new ages(\"Ramesh\", 20)); agetree.add(new ages(\"Suresh\", 20)); agetree.add(new ages(\"Ankit\", 78)); agetree.add(new ages(\"Madhav\", 78)); // Output Highest Value Element System.out.println(\"Highest Age Person: \" + agetree.last()); // Output Lowest Value Element System.out.println(\"Lowest Age Person: \" + agetree.first()); }}",
"e": 27713,
"s": 26024,
"text": null
},
{
"code": null,
"e": 27797,
"s": 27713,
"text": "Highest Age Person: Name: Ankit-- age: 78\nLowest Age Person: Name: Suresh-- age: 20"
},
{
"code": null,
"e": 27810,
"s": 27797,
"text": "java-treeset"
},
{
"code": null,
"e": 27817,
"s": 27810,
"text": "Picked"
},
{
"code": null,
"e": 27822,
"s": 27817,
"text": "Java"
},
{
"code": null,
"e": 27836,
"s": 27822,
"text": "Java Programs"
},
{
"code": null,
"e": 27841,
"s": 27836,
"text": "Java"
},
{
"code": null,
"e": 27939,
"s": 27841,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27948,
"s": 27939,
"text": "Comments"
},
{
"code": null,
"e": 27961,
"s": 27948,
"text": "Old Comments"
},
{
"code": null,
"e": 28007,
"s": 27961,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28028,
"s": 28007,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28043,
"s": 28028,
"text": "Stream In Java"
},
{
"code": null,
"e": 28060,
"s": 28043,
"text": "Generics in Java"
},
{
"code": null,
"e": 28079,
"s": 28060,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28123,
"s": 28079,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 28149,
"s": 28123,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28183,
"s": 28149,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 28230,
"s": 28183,
"text": "Implementing a Linked List in Java using Class"
}
]
|
Laravel - Retrieve Records | After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table.
$query(string) − query to execute in database
$bindings(array) − values to bind with queries
Step 1 − Execute the below command to create a controller called StudViewController.
php artisan make:controller StudViewController --plain
Step 2 − After the successful execution of step 1, you will receive the following output −
Step 3 − Copy the following code to file
app/Http/Controllers/StudViewController.php
app/Http/Controllers/StudViewController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class StudViewController extends Controller {
public function index() {
$users = DB::select('select * from student');
return view('stud_view',['users'=>$users]);
}
}
Step 4 − Create a view file called resources/views/stud_view.blade.php and copy the following code in that file.
resources/views/ stud_view.blade.php
<html>
<head>
<title>View Student Records</title>
</head>
<body>
<table border = 1>
<tr>
<td>ID</td>
<td>Name</td>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
</tr>
@endforeach
</table>
</body>
</html>
Step 5 − Add the following lines in app/Http/routes.php.
app/Http/routes.php
Route::get('view-records','StudViewController@index');
Step 6 − Visit the following URL to see records from database.
http://localhost:8000/view-records
Step 7 − The output will appear as shown in the following image.
13 Lectures
3 hours
Sebastian Sulinski
35 Lectures
3.5 hours
Antonio Papa
7 Lectures
1.5 hours
Sebastian Sulinski
42 Lectures
1 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
116 Lectures
13 hours
Hafizullah Masoudi
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2636,
"s": 2472,
"text": "After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table."
},
{
"code": null,
"e": 2682,
"s": 2636,
"text": "$query(string) − query to execute in database"
},
{
"code": null,
"e": 2729,
"s": 2682,
"text": "$bindings(array) − values to bind with queries"
},
{
"code": null,
"e": 2814,
"s": 2729,
"text": "Step 1 − Execute the below command to create a controller called StudViewController."
},
{
"code": null,
"e": 2870,
"s": 2814,
"text": "php artisan make:controller StudViewController --plain\n"
},
{
"code": null,
"e": 2961,
"s": 2870,
"text": "Step 2 − After the successful execution of step 1, you will receive the following output −"
},
{
"code": null,
"e": 3002,
"s": 2961,
"text": "Step 3 − Copy the following code to file"
},
{
"code": null,
"e": 3046,
"s": 3002,
"text": "app/Http/Controllers/StudViewController.php"
},
{
"code": null,
"e": 3090,
"s": 3046,
"text": "app/Http/Controllers/StudViewController.php"
},
{
"code": null,
"e": 3412,
"s": 3090,
"text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse DB;\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass StudViewController extends Controller {\n public function index() {\n $users = DB::select('select * from student');\n return view('stud_view',['users'=>$users]);\n }\n}"
},
{
"code": null,
"e": 3525,
"s": 3412,
"text": "Step 4 − Create a view file called resources/views/stud_view.blade.php and copy the following code in that file."
},
{
"code": null,
"e": 3562,
"s": 3525,
"text": "resources/views/ stud_view.blade.php"
},
{
"code": null,
"e": 3950,
"s": 3562,
"text": "<html>\n \n <head>\n <title>View Student Records</title>\n </head>\n \n <body>\n <table border = 1>\n <tr>\n <td>ID</td>\n <td>Name</td>\n </tr>\n @foreach ($users as $user)\n <tr>\n <td>{{ $user->id }}</td>\n <td>{{ $user->name }}</td>\n </tr>\n @endforeach\n </table>\n </body>\n</html>"
},
{
"code": null,
"e": 4007,
"s": 3950,
"text": "Step 5 − Add the following lines in app/Http/routes.php."
},
{
"code": null,
"e": 4027,
"s": 4007,
"text": "app/Http/routes.php"
},
{
"code": null,
"e": 4083,
"s": 4027,
"text": "Route::get('view-records','StudViewController@index');\n"
},
{
"code": null,
"e": 4146,
"s": 4083,
"text": "Step 6 − Visit the following URL to see records from database."
},
{
"code": null,
"e": 4182,
"s": 4146,
"text": "http://localhost:8000/view-records\n"
},
{
"code": null,
"e": 4247,
"s": 4182,
"text": "Step 7 − The output will appear as shown in the following image."
},
{
"code": null,
"e": 4280,
"s": 4247,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4300,
"s": 4280,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 4335,
"s": 4300,
"text": "\n 35 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4349,
"s": 4335,
"text": " Antonio Papa"
},
{
"code": null,
"e": 4383,
"s": 4349,
"text": "\n 7 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4403,
"s": 4383,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 4436,
"s": 4403,
"text": "\n 42 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4456,
"s": 4436,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 4491,
"s": 4456,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4514,
"s": 4491,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 4549,
"s": 4514,
"text": "\n 116 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4569,
"s": 4549,
"text": " Hafizullah Masoudi"
},
{
"code": null,
"e": 4576,
"s": 4569,
"text": " Print"
},
{
"code": null,
"e": 4587,
"s": 4576,
"text": " Add Notes"
}
]
|
Introduction to Simulation Modeling in Python - GeeksforGeeks | 03 Mar, 2021
Simulation is imitating the operations which take place within a system to study its behavior. Analyzing and creating the model of a system to predict its performance is called simulation modeling.
Simulation mimics a real-life process to determine or predict the response of the entire system. This helps to understand the dependency of each part of the system, their relations, and interactions. The process of simulating in real life can be costly. Therefore, we build a model to solve costly and complex ideas efficiently. Building a simulation model in an institution or organization increases profit.
A model is a replica of an original/real thing. A model can be either deterministic or probabilistic. A deterministic model is a model which does not involve any randomness. For a given initial condition you always get the same final condition.
A probabilistic model includes the randomness of elements. For example: tossing a coin, can be either heads or tails.
Now let’s understand the simulation model in one go.
Suppose you have to open a pizza restaurant and know how many employees you will need to run well. Different pizzas take different amounts of time to get prepared. Also, orders do not come uniformly with time. You want to provide them the best service possible while maintaining your budget. You can’t hire and then fire the employees to find the optimum number required to design a simulation model. We can solve the above problem of finding an optimum number of employees by building a simulation model in the following ways:
Designing: looking over the various services provided by the company and, therefore, different types of employees required for various jobs.
Experiment: Trends of customers’ arrival on weekdays, weekends, and on special occasions and therefore employees required accordingly.
Optimize: Optimizing the number of workers to employ permanently by looking over experimentation.
Analyze: If giving employment to those many people affordable or asking employees to work overtime, can get extra workers on festival season.
Improve: Further reducing the employment to given on visualizing the results of the analysis.
Simulation models are built before building a new system or altering an existing system to optimize the system’s performance and reduce the chances of failure. One of the leading simulation models in the present-day scenario is Monte Carlo Simulation.
Monte Carlo simulation is a mathematical technique that helps estimate the probability distribution of various event outcomes. Based on those probabilities, the risk analysis team decides whether they are ready to take the risk. This technique repeatedly takes random numbers between the minimum and maximum limit and predicts its outcome. Usually, the sampling is done on a large scale, so we get all the likely outcomes. Then we plot the probability distribution using which risk analysts calculate the risk probability.
For example, let’s consider the above example the arrival of customers can vary in a specific range. We can create a model that pics a random number between maximum and minimum number and can visualize the range of workers required accordingly.
Let’s take another elementary example to understand the Monte Carlo simulation by rolling the dice. Suppose we roll two dice, and we want to predict the probability of getting the sum as 12.
Below is the python code for the implementation with comments for better understanding:
Python3
# importing the required librariesimport randomimport numpy as npimport matplotlib.pyplot as plt # function to generate a random numberdef roll(): return random.randint(1, 6) # rolling dice 1000000 times and # storing in listval = []for i in range(0, 1000000): sum_of_roll = roll()+roll() val.append(sum_of_roll) # plotting the graphplt.hist(val, bins=11, density=True)
Output:
From the above probability distribution curve, we get the value of probability as 0.025 for getting a 12. Similarly, we can apply the Monte Carlo technique to solve various problems.
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
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 25845,
"s": 25647,
"text": "Simulation is imitating the operations which take place within a system to study its behavior. Analyzing and creating the model of a system to predict its performance is called simulation modeling."
},
{
"code": null,
"e": 26254,
"s": 25845,
"text": "Simulation mimics a real-life process to determine or predict the response of the entire system. This helps to understand the dependency of each part of the system, their relations, and interactions. The process of simulating in real life can be costly. Therefore, we build a model to solve costly and complex ideas efficiently. Building a simulation model in an institution or organization increases profit."
},
{
"code": null,
"e": 26499,
"s": 26254,
"text": "A model is a replica of an original/real thing. A model can be either deterministic or probabilistic. A deterministic model is a model which does not involve any randomness. For a given initial condition you always get the same final condition."
},
{
"code": null,
"e": 26617,
"s": 26499,
"text": "A probabilistic model includes the randomness of elements. For example: tossing a coin, can be either heads or tails."
},
{
"code": null,
"e": 26670,
"s": 26617,
"text": "Now let’s understand the simulation model in one go."
},
{
"code": null,
"e": 27198,
"s": 26670,
"text": "Suppose you have to open a pizza restaurant and know how many employees you will need to run well. Different pizzas take different amounts of time to get prepared. Also, orders do not come uniformly with time. You want to provide them the best service possible while maintaining your budget. You can’t hire and then fire the employees to find the optimum number required to design a simulation model. We can solve the above problem of finding an optimum number of employees by building a simulation model in the following ways:"
},
{
"code": null,
"e": 27339,
"s": 27198,
"text": "Designing: looking over the various services provided by the company and, therefore, different types of employees required for various jobs."
},
{
"code": null,
"e": 27474,
"s": 27339,
"text": "Experiment: Trends of customers’ arrival on weekdays, weekends, and on special occasions and therefore employees required accordingly."
},
{
"code": null,
"e": 27572,
"s": 27474,
"text": "Optimize: Optimizing the number of workers to employ permanently by looking over experimentation."
},
{
"code": null,
"e": 27714,
"s": 27572,
"text": "Analyze: If giving employment to those many people affordable or asking employees to work overtime, can get extra workers on festival season."
},
{
"code": null,
"e": 27808,
"s": 27714,
"text": "Improve: Further reducing the employment to given on visualizing the results of the analysis."
},
{
"code": null,
"e": 28060,
"s": 27808,
"text": "Simulation models are built before building a new system or altering an existing system to optimize the system’s performance and reduce the chances of failure. One of the leading simulation models in the present-day scenario is Monte Carlo Simulation."
},
{
"code": null,
"e": 28583,
"s": 28060,
"text": "Monte Carlo simulation is a mathematical technique that helps estimate the probability distribution of various event outcomes. Based on those probabilities, the risk analysis team decides whether they are ready to take the risk. This technique repeatedly takes random numbers between the minimum and maximum limit and predicts its outcome. Usually, the sampling is done on a large scale, so we get all the likely outcomes. Then we plot the probability distribution using which risk analysts calculate the risk probability."
},
{
"code": null,
"e": 28828,
"s": 28583,
"text": "For example, let’s consider the above example the arrival of customers can vary in a specific range. We can create a model that pics a random number between maximum and minimum number and can visualize the range of workers required accordingly."
},
{
"code": null,
"e": 29020,
"s": 28828,
"text": "Let’s take another elementary example to understand the Monte Carlo simulation by rolling the dice. Suppose we roll two dice, and we want to predict the probability of getting the sum as 12. "
},
{
"code": null,
"e": 29108,
"s": 29020,
"text": "Below is the python code for the implementation with comments for better understanding:"
},
{
"code": null,
"e": 29116,
"s": 29108,
"text": "Python3"
},
{
"code": "# importing the required librariesimport randomimport numpy as npimport matplotlib.pyplot as plt # function to generate a random numberdef roll(): return random.randint(1, 6) # rolling dice 1000000 times and # storing in listval = []for i in range(0, 1000000): sum_of_roll = roll()+roll() val.append(sum_of_roll) # plotting the graphplt.hist(val, bins=11, density=True)",
"e": 29504,
"s": 29116,
"text": null
},
{
"code": null,
"e": 29512,
"s": 29504,
"text": "Output:"
},
{
"code": null,
"e": 29695,
"s": 29512,
"text": "From the above probability distribution curve, we get the value of probability as 0.025 for getting a 12. Similarly, we can apply the Monte Carlo technique to solve various problems."
},
{
"code": null,
"e": 29702,
"s": 29695,
"text": "Python"
},
{
"code": null,
"e": 29800,
"s": 29702,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29832,
"s": 29800,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29874,
"s": 29832,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29916,
"s": 29874,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29972,
"s": 29916,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29999,
"s": 29972,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30030,
"s": 29999,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30059,
"s": 30030,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 30095,
"s": 30059,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 30117,
"s": 30095,
"text": "Defaultdict in Python"
}
]
|
Difference between print() and println() in Java | As we know in Java these both methods are primarily used to display text from code to console. Both these methods are of PrintStream class and are called on static member 'out' of 'System' class which is a final type class.
The following are the important differences between print() and println().
JavaTester.java
import java.io.*;
class JavaTester {
public static void main(String[] args){
System.out.print("Hello");
System.out.print("World");
}
}
HelloWorld
JavaTester.java
import java.io.*;
class JavaTester {
public static void main(String[] args){
System.out.println("Hello");
System.out.println("World");
}
}
Hello
World | [
{
"code": null,
"e": 1286,
"s": 1062,
"text": "As we know in Java these both methods are primarily used to display text from code to console. Both these methods are of PrintStream class and are called on static member 'out' of 'System' class which is a final type class."
},
{
"code": null,
"e": 1361,
"s": 1286,
"text": "The following are the important differences between print() and println()."
},
{
"code": null,
"e": 1377,
"s": 1361,
"text": "JavaTester.java"
},
{
"code": null,
"e": 1530,
"s": 1377,
"text": "import java.io.*;\nclass JavaTester {\n public static void main(String[] args){\n System.out.print(\"Hello\");\n System.out.print(\"World\");\n }\n}"
},
{
"code": null,
"e": 1541,
"s": 1530,
"text": "HelloWorld"
},
{
"code": null,
"e": 1557,
"s": 1541,
"text": "JavaTester.java"
},
{
"code": null,
"e": 1714,
"s": 1557,
"text": "import java.io.*;\nclass JavaTester {\n public static void main(String[] args){\n System.out.println(\"Hello\");\n System.out.println(\"World\");\n }\n}"
},
{
"code": null,
"e": 1726,
"s": 1714,
"text": "Hello\nWorld"
}
]
|
How to Install Python Pycharm on Linux? - GeeksforGeeks | 06 Oct, 2021
Prerequisite: Python Language Introduction Python is a widely-used general-purpose, high-level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.Python is a programming language that lets you work quickly and integrate systems more efficiently.We need to have an interpreter to interpret and run our programs. There are certain online interpreters like GFG-IDE, IDEONE or CodePad, etc. Running Python codes on an offline interpreter is much more compatible than using an online IDE. PyCharm is one of the most popular Python-IDE developed by JetBrains used for performing scripting in Python language. PyCharm provides some very useful features like Code completion and inspection, Debugging process, support for various programming frameworks such as Flask and Django, Package Management, etc. PyCharm provides various tools for productive development in Python.
Installing Python: Most of the Linux OS has Python pre-installed. To check if your device is pre-installed with Python or not, just go to terminal using Ctrl+Alt+T
Now run the following command:For Python2
python --version
For Python3.x
python3.x --version
If Python is already installed, it will generate a message with the Python version available.
If Python is not present, go through How to install Python on Linux? and follow the instructions provided.
Before beginning with the installation process, PyCharm needs to be downloaded. For that, PyCharm is available on jetbrains.com.Download the PyCharm and follow the further instructions for its Setup.
Begin setting up PyCharm:
Download the tar.gz file for PyCharm:
Extract Files to a Folder:
Extraction Process:
Extracted File for PyCharm:
Open Terminal in bin Folder:Go to home -> nikhil -> Documents -> pycharm-community-2019.3.1 -> bin and open Terminal Window
Command to Start PyCharm:In the terminal window, type the following command to start PyCharm../pycharm.sh
./pycharm.sh
Finished Setup:
how-to-install
python-basics
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS? | [
{
"code": null,
"e": 26197,
"s": 26169,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 27267,
"s": 26197,
"text": "Prerequisite: Python Language Introduction Python is a widely-used general-purpose, high-level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.Python is a programming language that lets you work quickly and integrate systems more efficiently.We need to have an interpreter to interpret and run our programs. There are certain online interpreters like GFG-IDE, IDEONE or CodePad, etc. Running Python codes on an offline interpreter is much more compatible than using an online IDE. PyCharm is one of the most popular Python-IDE developed by JetBrains used for performing scripting in Python language. PyCharm provides some very useful features like Code completion and inspection, Debugging process, support for various programming frameworks such as Flask and Django, Package Management, etc. PyCharm provides various tools for productive development in Python."
},
{
"code": null,
"e": 27431,
"s": 27267,
"text": "Installing Python: Most of the Linux OS has Python pre-installed. To check if your device is pre-installed with Python or not, just go to terminal using Ctrl+Alt+T"
},
{
"code": null,
"e": 27473,
"s": 27431,
"text": "Now run the following command:For Python2"
},
{
"code": null,
"e": 27491,
"s": 27473,
"text": "python --version\n"
},
{
"code": null,
"e": 27505,
"s": 27491,
"text": "For Python3.x"
},
{
"code": null,
"e": 27526,
"s": 27505,
"text": "python3.x --version\n"
},
{
"code": null,
"e": 27620,
"s": 27526,
"text": "If Python is already installed, it will generate a message with the Python version available."
},
{
"code": null,
"e": 27727,
"s": 27620,
"text": "If Python is not present, go through How to install Python on Linux? and follow the instructions provided."
},
{
"code": null,
"e": 27927,
"s": 27727,
"text": "Before beginning with the installation process, PyCharm needs to be downloaded. For that, PyCharm is available on jetbrains.com.Download the PyCharm and follow the further instructions for its Setup."
},
{
"code": null,
"e": 27953,
"s": 27927,
"text": "Begin setting up PyCharm:"
},
{
"code": null,
"e": 27991,
"s": 27953,
"text": "Download the tar.gz file for PyCharm:"
},
{
"code": null,
"e": 28018,
"s": 27991,
"text": "Extract Files to a Folder:"
},
{
"code": null,
"e": 28038,
"s": 28018,
"text": "Extraction Process:"
},
{
"code": null,
"e": 28066,
"s": 28038,
"text": "Extracted File for PyCharm:"
},
{
"code": null,
"e": 28190,
"s": 28066,
"text": "Open Terminal in bin Folder:Go to home -> nikhil -> Documents -> pycharm-community-2019.3.1 -> bin and open Terminal Window"
},
{
"code": null,
"e": 28296,
"s": 28190,
"text": "Command to Start PyCharm:In the terminal window, type the following command to start PyCharm../pycharm.sh"
},
{
"code": null,
"e": 28309,
"s": 28296,
"text": "./pycharm.sh"
},
{
"code": null,
"e": 28325,
"s": 28309,
"text": "Finished Setup:"
},
{
"code": null,
"e": 28340,
"s": 28325,
"text": "how-to-install"
},
{
"code": null,
"e": 28354,
"s": 28340,
"text": "python-basics"
},
{
"code": null,
"e": 28361,
"s": 28354,
"text": "How To"
},
{
"code": null,
"e": 28380,
"s": 28361,
"text": "Installation Guide"
},
{
"code": null,
"e": 28387,
"s": 28380,
"text": "Python"
},
{
"code": null,
"e": 28485,
"s": 28387,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28519,
"s": 28485,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28577,
"s": 28519,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 28626,
"s": 28577,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 28673,
"s": 28626,
"text": "How to create a nested RecyclerView in Android"
},
{
"code": null,
"e": 28733,
"s": 28673,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 28766,
"s": 28733,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28800,
"s": 28766,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28835,
"s": 28800,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 28893,
"s": 28835,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
]
|
Add hover color to a table with Bootstrap | To add hover color to table, use the table-hover class. You can try to run the following code to implement the table-hover class:
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Table</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<table class = "table table-hover table-bordered table-striped">
<caption>Footballer Rank</caption>
<thead>
<tr>
<th>Footballer</th>
<th>Rank</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>Messi</td>
<td>1</td>
<td>Argentina</td>
</tr>
<tr>
<td>Neymar</td>
<td>2</td>
<td>Brazil</td>
</tr>
<tr>
<td>Ronaldo</td>
<td>3</td>
<td>Portugal</td>
</tr>
</tbody>
</table>
</body>
</html> | [
{
"code": null,
"e": 1192,
"s": 1062,
"text": "To add hover color to table, use the table-hover class. You can try to run the following code to implement the table-hover class:"
},
{
"code": null,
"e": 1202,
"s": 1192,
"text": "Live Demo"
},
{
"code": null,
"e": 2414,
"s": 1202,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Table</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/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://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <table class = \"table table-hover table-bordered table-striped\">\n <caption>Footballer Rank</caption>\n <thead>\n <tr>\n <th>Footballer</th>\n <th>Rank</th>\n <th>Country</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Messi</td>\n <td>1</td>\n <td>Argentina</td>\n </tr>\n <tr>\n <td>Neymar</td>\n <td>2</td>\n <td>Brazil</td>\n </tr>\n <tr>\n <td>Ronaldo</td>\n <td>3</td>\n <td>Portugal</td>\n </tr>\n </tbody>\n </table>\n </body>\n</html>"
}
]
|
How to pass multiple JSON Objects as data using jQuery's $.ajax() ? - GeeksforGeeks | 30 Apr, 2021
The purpose of this article is to pass multiple JSON objects as data using the jQuery $ajax() method in an HTML document.
Approach: Create a button in an HTML document to send JSON objects to a PHP server. In the JavaScript file, add a click event listener to the button. On clicking of the button, a request is made to PHP file using jQuery $ajax() method by which multiple JSON objects are passed to the server.
HTML Code: The following code demonstrates the design or structure of the user interface. On click of the HTML button, it gives the response by the PHP server in the resultID HTML div.
index.html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- CSS file --> <link rel="stylesheet" href="style.css"> <!-- jQuery Ajax CDN --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script> <!-- JavaScript file --> <script src="script.js"></script></head> <body> <center> <h2 style="color:green">GeeksforGeeks</h2> <div class="container"> <b>Pass multiple JSON objects</b> <br/><br/> <!-- Button to multiple JSON objects --> <button type="button" id="btn"> Click on me! </button> <div style="height:10px"></div> <div id="resultID"></div> </div> </center></body> </html>
CSS Code: The following code is the content for the file “style.css” used in the above HTML code.
Style,css
.container { border: 1px solid rgb(73, 72, 72); border-radius: 10px; margin: auto; padding: 10px; text-align: center;} button { border-radius: 5px; padding: 10px; color: #fff; background-color: #167deb; border-color: #0062cc; font-weight: bolder; cursor: pointer;} button:hover { text-decoration: none; background-color: #0069d9; border-color: #0062cc;}
JavaScript Code: The following code is the content for the file “script.js” used in the above HTML code. It handles the click() event for the button by using jQuery ajax() method and passing the data to a PHP server file i.e action.php
script.js
$(document).ready(() => { // Adding 'click' event listener to button $("#btn").click(() => { // Two JSON objects are passed to server let obj1 = {"name": "John Doe"}; let obj2 = {"name": "Duke"}; // jQuery Ajax Post Request using $.ajax() $.ajax({ url: 'action.php', type: 'POST', // passing JSON objects as comma(,) separated values data: { obj1, obj2 }, success: (response) => { // response from PHP back-end PHP server $("#resultID").show().html(response); } }) });});
Note: You can pass as many JSON objects by using comma(,) separated values i.e. obj1, obj2, obj3,..
PHP code: The following is the code for the file “action.php” used in the above JavaScript code.
PHP
<?php // Check if JSON Objects are set by user if (isset($_POST['obj1']) && $_POST['obj2']){ // Get JSON objects in variables $obj1 = $_POST['obj1']; $obj2 = $_POST['obj2']; // Sending response to script file echo "Success";}?>
Output :
multiple data passing and getting response
jQuery-AJAX
jQuery-Questions
JSON
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
How to prevent Body from scrolling when a modal is opened using jQuery ?
How to redirect to a particular section of a page using HTML or jQuery?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26962,
"s": 26934,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 27084,
"s": 26962,
"text": "The purpose of this article is to pass multiple JSON objects as data using the jQuery $ajax() method in an HTML document."
},
{
"code": null,
"e": 27377,
"s": 27084,
"text": "Approach: Create a button in an HTML document to send JSON objects to a PHP server. In the JavaScript file, add a click event listener to the button. On clicking of the button, a request is made to PHP file using jQuery $ajax() method by which multiple JSON objects are passed to the server. "
},
{
"code": null,
"e": 27562,
"s": 27377,
"text": "HTML Code: The following code demonstrates the design or structure of the user interface. On click of the HTML button, it gives the response by the PHP server in the resultID HTML div."
},
{
"code": null,
"e": 27573,
"s": 27562,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <!-- CSS file --> <link rel=\"stylesheet\" href=\"style.css\"> <!-- jQuery Ajax CDN --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js\"> </script> <!-- JavaScript file --> <script src=\"script.js\"></script></head> <body> <center> <h2 style=\"color:green\">GeeksforGeeks</h2> <div class=\"container\"> <b>Pass multiple JSON objects</b> <br/><br/> <!-- Button to multiple JSON objects --> <button type=\"button\" id=\"btn\"> Click on me! </button> <div style=\"height:10px\"></div> <div id=\"resultID\"></div> </div> </center></body> </html>",
"e": 28389,
"s": 27573,
"text": null
},
{
"code": null,
"e": 28487,
"s": 28389,
"text": "CSS Code: The following code is the content for the file “style.css” used in the above HTML code."
},
{
"code": null,
"e": 28497,
"s": 28487,
"text": "Style,css"
},
{
"code": ".container { border: 1px solid rgb(73, 72, 72); border-radius: 10px; margin: auto; padding: 10px; text-align: center;} button { border-radius: 5px; padding: 10px; color: #fff; background-color: #167deb; border-color: #0062cc; font-weight: bolder; cursor: pointer;} button:hover { text-decoration: none; background-color: #0069d9; border-color: #0062cc;}",
"e": 28868,
"s": 28497,
"text": null
},
{
"code": null,
"e": 29104,
"s": 28868,
"text": "JavaScript Code: The following code is the content for the file “script.js” used in the above HTML code. It handles the click() event for the button by using jQuery ajax() method and passing the data to a PHP server file i.e action.php"
},
{
"code": null,
"e": 29114,
"s": 29104,
"text": "script.js"
},
{
"code": "$(document).ready(() => { // Adding 'click' event listener to button $(\"#btn\").click(() => { // Two JSON objects are passed to server let obj1 = {\"name\": \"John Doe\"}; let obj2 = {\"name\": \"Duke\"}; // jQuery Ajax Post Request using $.ajax() $.ajax({ url: 'action.php', type: 'POST', // passing JSON objects as comma(,) separated values data: { obj1, obj2 }, success: (response) => { // response from PHP back-end PHP server $(\"#resultID\").show().html(response); } }) });});",
"e": 29729,
"s": 29114,
"text": null
},
{
"code": null,
"e": 29829,
"s": 29729,
"text": "Note: You can pass as many JSON objects by using comma(,) separated values i.e. obj1, obj2, obj3,.."
},
{
"code": null,
"e": 29926,
"s": 29829,
"text": "PHP code: The following is the code for the file “action.php” used in the above JavaScript code."
},
{
"code": null,
"e": 29930,
"s": 29926,
"text": "PHP"
},
{
"code": "<?php // Check if JSON Objects are set by user if (isset($_POST['obj1']) && $_POST['obj2']){ // Get JSON objects in variables $obj1 = $_POST['obj1']; $obj2 = $_POST['obj2']; // Sending response to script file echo \"Success\";}?>",
"e": 30173,
"s": 29930,
"text": null
},
{
"code": null,
"e": 30182,
"s": 30173,
"text": "Output :"
},
{
"code": null,
"e": 30225,
"s": 30182,
"text": "multiple data passing and getting response"
},
{
"code": null,
"e": 30237,
"s": 30225,
"text": "jQuery-AJAX"
},
{
"code": null,
"e": 30254,
"s": 30237,
"text": "jQuery-Questions"
},
{
"code": null,
"e": 30259,
"s": 30254,
"text": "JSON"
},
{
"code": null,
"e": 30266,
"s": 30259,
"text": "Picked"
},
{
"code": null,
"e": 30273,
"s": 30266,
"text": "JQuery"
},
{
"code": null,
"e": 30290,
"s": 30273,
"text": "Web Technologies"
},
{
"code": null,
"e": 30388,
"s": 30290,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30443,
"s": 30388,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 30497,
"s": 30443,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 30531,
"s": 30497,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 30604,
"s": 30531,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 30676,
"s": 30604,
"text": "How to redirect to a particular section of a page using HTML or jQuery?"
},
{
"code": null,
"e": 30716,
"s": 30676,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30749,
"s": 30716,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30794,
"s": 30749,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30837,
"s": 30794,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Python | Numpy np.fft() method - GeeksforGeeks | 21 Nov, 2019
With the help of np.fft() method, we can get the 1-D Fourier Transform by using np.fft() method.
Syntax : np.fft(Array)Return : Return a series of fourier transformation.
Example #1 :In this example we can see that by using np.fft() method, we are able to get the series of fourier transformation by using this method.
# import numpyimport numpy as np a = np.array([5, 4, 6, 3, 7])# using np.fft() methodgfg = np.fft.fft(a) print(gfg)
Output :
[25. + 0.j 1.11803399 + 1.08981379j -1.11803399 + 4.61652531j-1.11803399 – 4.61652531j 1.11803399 – 1.08981379j]
Example #2 :
# import numpyimport numpy as np a = np.array([-5.5, 4.4, -6.6, 3.3, -7.7])# using np.fft() methodgfg = np.fft.fft(a) print(gfg)
Output :
[-12.1 + 0.j -3.85 – 5.68870985j -3.85 – 16.52766106j-3.85 + 16.52766106j -3.85 + 5.68870985j]
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 26304,
"s": 26276,
"text": "\n21 Nov, 2019"
},
{
"code": null,
"e": 26401,
"s": 26304,
"text": "With the help of np.fft() method, we can get the 1-D Fourier Transform by using np.fft() method."
},
{
"code": null,
"e": 26475,
"s": 26401,
"text": "Syntax : np.fft(Array)Return : Return a series of fourier transformation."
},
{
"code": null,
"e": 26623,
"s": 26475,
"text": "Example #1 :In this example we can see that by using np.fft() method, we are able to get the series of fourier transformation by using this method."
},
{
"code": "# import numpyimport numpy as np a = np.array([5, 4, 6, 3, 7])# using np.fft() methodgfg = np.fft.fft(a) print(gfg)",
"e": 26741,
"s": 26623,
"text": null
},
{
"code": null,
"e": 26750,
"s": 26741,
"text": "Output :"
},
{
"code": null,
"e": 26863,
"s": 26750,
"text": "[25. + 0.j 1.11803399 + 1.08981379j -1.11803399 + 4.61652531j-1.11803399 – 4.61652531j 1.11803399 – 1.08981379j]"
},
{
"code": null,
"e": 26876,
"s": 26863,
"text": "Example #2 :"
},
{
"code": "# import numpyimport numpy as np a = np.array([-5.5, 4.4, -6.6, 3.3, -7.7])# using np.fft() methodgfg = np.fft.fft(a) print(gfg)",
"e": 27007,
"s": 26876,
"text": null
},
{
"code": null,
"e": 27016,
"s": 27007,
"text": "Output :"
},
{
"code": null,
"e": 27111,
"s": 27016,
"text": "[-12.1 + 0.j -3.85 – 5.68870985j -3.85 – 16.52766106j-3.85 + 16.52766106j -3.85 + 5.68870985j]"
},
{
"code": null,
"e": 27140,
"s": 27111,
"text": "Python numpy-Matrix Function"
},
{
"code": null,
"e": 27153,
"s": 27140,
"text": "Python-numpy"
},
{
"code": null,
"e": 27160,
"s": 27153,
"text": "Python"
},
{
"code": null,
"e": 27258,
"s": 27160,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27276,
"s": 27258,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27311,
"s": 27276,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27343,
"s": 27311,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27365,
"s": 27343,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27407,
"s": 27365,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27437,
"s": 27407,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27463,
"s": 27437,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27507,
"s": 27463,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27536,
"s": 27507,
"text": "*args and **kwargs in Python"
}
]
|
How to create popup message using Alerter Library in android - GeeksforGeeks | 12 Jun, 2020
In this article, we learn about how to create a popup message with the help of Alerter Library. It is better to use Alerter than using Toast or Snackbar in cases if some alert messages are to be displayed to the user. We can add various onClickListners to our alerter message which makes it better and it also has nice appealing UI.
Approach:
Add the support Library in build.gradle file and add dependency in the dependencies section. This library facilitates easy integration of Alert View in the app. The alert view is customizable and it is displayed over the ongoing activity in the app. This library is also compatible with AndroidX.dependencies { implementation 'com.tapadoo.android:alerter:2.0.4'}Now add the following code in the activity_main.xml file. This codes add a button in the MainActivity and if the button is clicked then showAlerter function is invoked.activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="showAlerter" android:text="Show Alerter" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>Now add the following code in the MainActivity.java file. It defines the showAlerter function. This function creates the Alerter. Various methods are called to initialize different properties of the Alerter. setTitle sets the title, setText sets the text shown below the title, setIcon sets the icon, etc. Various onClickListeners are also attached so that you can do something in response of the users action.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgAlerter; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import com.tapadoo.alerter.Alerter;import com.tapadoo.alerter.OnHideAlertListener;import com.tapadoo.alerter.OnShowAlertListener; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); } public void showAlerter(View v) { Alerter.create(this) .setTitle("Alert Title") .setText("Alert Text") .setIcon( R.drawable.ic_android_black_24dp) .setBackgroundColorRes( R.color.colorAccent) .setDuration(3000) .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // do something when // Alerter message was clicked } }) .setOnShowListener( new OnShowAlertListener() { @Override public void onShow() { // do something when // Alerter message shows } }) .setOnHideListener( new OnHideAlertListener() { @Override public void onHide() { // do something when // Alerter message hides } }) .show(); }}
Add the support Library in build.gradle file and add dependency in the dependencies section. This library facilitates easy integration of Alert View in the app. The alert view is customizable and it is displayed over the ongoing activity in the app. This library is also compatible with AndroidX.dependencies { implementation 'com.tapadoo.android:alerter:2.0.4'}
dependencies { implementation 'com.tapadoo.android:alerter:2.0.4'}
Now add the following code in the activity_main.xml file. This codes add a button in the MainActivity and if the button is clicked then showAlerter function is invoked.activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="showAlerter" android:text="Show Alerter" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="showAlerter" android:text="Show Alerter" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>
Now add the following code in the MainActivity.java file. It defines the showAlerter function. This function creates the Alerter. Various methods are called to initialize different properties of the Alerter. setTitle sets the title, setText sets the text shown below the title, setIcon sets the icon, etc. Various onClickListeners are also attached so that you can do something in response of the users action.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgAlerter; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import com.tapadoo.alerter.Alerter;import com.tapadoo.alerter.OnHideAlertListener;import com.tapadoo.alerter.OnShowAlertListener; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); } public void showAlerter(View v) { Alerter.create(this) .setTitle("Alert Title") .setText("Alert Text") .setIcon( R.drawable.ic_android_black_24dp) .setBackgroundColorRes( R.color.colorAccent) .setDuration(3000) .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // do something when // Alerter message was clicked } }) .setOnShowListener( new OnShowAlertListener() { @Override public void onShow() { // do something when // Alerter message shows } }) .setOnHideListener( new OnHideAlertListener() { @Override public void onHide() { // do something when // Alerter message hides } }) .show(); }}
MainActivity.java
package org.geeksforgeeks.gfgAlerter; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import com.tapadoo.alerter.Alerter;import com.tapadoo.alerter.OnHideAlertListener;import com.tapadoo.alerter.OnShowAlertListener; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); } public void showAlerter(View v) { Alerter.create(this) .setTitle("Alert Title") .setText("Alert Text") .setIcon( R.drawable.ic_android_black_24dp) .setBackgroundColorRes( R.color.colorAccent) .setDuration(3000) .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // do something when // Alerter message was clicked } }) .setOnShowListener( new OnShowAlertListener() { @Override public void onShow() { // do something when // Alerter message shows } }) .setOnHideListener( new OnHideAlertListener() { @Override public void onHide() { // do something when // Alerter message hides } }) .show(); }}
Output:
Akanksha_Rai
android
How To
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
How to Install FFmpeg on Windows?
Java Tutorial
How to filter object array based on attributes?
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
HashMap in Java with Examples | [
{
"code": null,
"e": 25246,
"s": 25218,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 25579,
"s": 25246,
"text": "In this article, we learn about how to create a popup message with the help of Alerter Library. It is better to use Alerter than using Toast or Snackbar in cases if some alert messages are to be displayed to the user. We can add various onClickListners to our alerter message which makes it better and it also has nice appealing UI."
},
{
"code": null,
"e": 25589,
"s": 25579,
"text": "Approach:"
},
{
"code": null,
"e": 29267,
"s": 25589,
"text": "Add the support Library in build.gradle file and add dependency in the dependencies section. This library facilitates easy integration of Alert View in the app. The alert view is customizable and it is displayed over the ongoing activity in the app. This library is also compatible with AndroidX.dependencies { implementation 'com.tapadoo.android:alerter:2.0.4'}Now add the following code in the activity_main.xml file. This codes add a button in the MainActivity and if the button is clicked then showAlerter function is invoked.activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:onClick=\"showAlerter\" android:text=\"Show Alerter\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /></androidx.constraintlayout.widget.ConstraintLayout>Now add the following code in the MainActivity.java file. It defines the showAlerter function. This function creates the Alerter. Various methods are called to initialize different properties of the Alerter. setTitle sets the title, setText sets the text shown below the title, setIcon sets the icon, etc. Various onClickListeners are also attached so that you can do something in response of the users action.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgAlerter; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import com.tapadoo.alerter.Alerter;import com.tapadoo.alerter.OnHideAlertListener;import com.tapadoo.alerter.OnShowAlertListener; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); } public void showAlerter(View v) { Alerter.create(this) .setTitle(\"Alert Title\") .setText(\"Alert Text\") .setIcon( R.drawable.ic_android_black_24dp) .setBackgroundColorRes( R.color.colorAccent) .setDuration(3000) .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // do something when // Alerter message was clicked } }) .setOnShowListener( new OnShowAlertListener() { @Override public void onShow() { // do something when // Alerter message shows } }) .setOnHideListener( new OnHideAlertListener() { @Override public void onHide() { // do something when // Alerter message hides } }) .show(); }}"
},
{
"code": null,
"e": 29633,
"s": 29267,
"text": "Add the support Library in build.gradle file and add dependency in the dependencies section. This library facilitates easy integration of Alert View in the app. The alert view is customizable and it is displayed over the ongoing activity in the app. This library is also compatible with AndroidX.dependencies { implementation 'com.tapadoo.android:alerter:2.0.4'}"
},
{
"code": "dependencies { implementation 'com.tapadoo.android:alerter:2.0.4'}",
"e": 29703,
"s": 29633,
"text": null
},
{
"code": null,
"e": 30743,
"s": 29703,
"text": "Now add the following code in the activity_main.xml file. This codes add a button in the MainActivity and if the button is clicked then showAlerter function is invoked.activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:onClick=\"showAlerter\" android:text=\"Show Alerter\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /></androidx.constraintlayout.widget.ConstraintLayout>"
},
{
"code": null,
"e": 30761,
"s": 30743,
"text": "activity_main.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:onClick=\"showAlerter\" android:text=\"Show Alerter\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /></androidx.constraintlayout.widget.ConstraintLayout>",
"e": 31599,
"s": 30761,
"text": null
},
{
"code": null,
"e": 33873,
"s": 31599,
"text": "Now add the following code in the MainActivity.java file. It defines the showAlerter function. This function creates the Alerter. Various methods are called to initialize different properties of the Alerter. setTitle sets the title, setText sets the text shown below the title, setIcon sets the icon, etc. Various onClickListeners are also attached so that you can do something in response of the users action.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgAlerter; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import com.tapadoo.alerter.Alerter;import com.tapadoo.alerter.OnHideAlertListener;import com.tapadoo.alerter.OnShowAlertListener; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); } public void showAlerter(View v) { Alerter.create(this) .setTitle(\"Alert Title\") .setText(\"Alert Text\") .setIcon( R.drawable.ic_android_black_24dp) .setBackgroundColorRes( R.color.colorAccent) .setDuration(3000) .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // do something when // Alerter message was clicked } }) .setOnShowListener( new OnShowAlertListener() { @Override public void onShow() { // do something when // Alerter message shows } }) .setOnHideListener( new OnHideAlertListener() { @Override public void onHide() { // do something when // Alerter message hides } }) .show(); }}"
},
{
"code": null,
"e": 33891,
"s": 33873,
"text": "MainActivity.java"
},
{
"code": "package org.geeksforgeeks.gfgAlerter; import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import com.tapadoo.alerter.Alerter;import com.tapadoo.alerter.OnHideAlertListener;import com.tapadoo.alerter.OnShowAlertListener; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); } public void showAlerter(View v) { Alerter.create(this) .setTitle(\"Alert Title\") .setText(\"Alert Text\") .setIcon( R.drawable.ic_android_black_24dp) .setBackgroundColorRes( R.color.colorAccent) .setDuration(3000) .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // do something when // Alerter message was clicked } }) .setOnShowListener( new OnShowAlertListener() { @Override public void onShow() { // do something when // Alerter message shows } }) .setOnHideListener( new OnHideAlertListener() { @Override public void onHide() { // do something when // Alerter message hides } }) .show(); }}",
"e": 35721,
"s": 33891,
"text": null
},
{
"code": null,
"e": 35729,
"s": 35721,
"text": "Output:"
},
{
"code": null,
"e": 35742,
"s": 35729,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35750,
"s": 35742,
"text": "android"
},
{
"code": null,
"e": 35757,
"s": 35750,
"text": "How To"
},
{
"code": null,
"e": 35762,
"s": 35757,
"text": "Java"
},
{
"code": null,
"e": 35767,
"s": 35762,
"text": "Java"
},
{
"code": null,
"e": 35865,
"s": 35767,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35874,
"s": 35865,
"text": "Comments"
},
{
"code": null,
"e": 35887,
"s": 35874,
"text": "Old Comments"
},
{
"code": null,
"e": 35914,
"s": 35887,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 35959,
"s": 35914,
"text": "How to Install OpenCV for Python on Windows?"
},
{
"code": null,
"e": 35993,
"s": 35959,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 36007,
"s": 35993,
"text": "Java Tutorial"
},
{
"code": null,
"e": 36055,
"s": 36007,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 36077,
"s": 36055,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 36113,
"s": 36077,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 36138,
"s": 36113,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 36170,
"s": 36138,
"text": "Initialize an ArrayList in Java"
}
]
|
C# Average Method | To find the average of integers in C#, use the Queryable Average() method.
Let’s say the following is our integer array.
var arr = new int[] { 10, 17, 25, 30, 40, 55, 60, 70 };
Now, use the Average() method to get the average of the elements.
double avg = Queryable.Average(arr.AsQueryable());
Live Demo
using System;
using System.Linq;
class Demo {
static void Main() {
var arr = new int[] { 10, 17, 25, 30, 40, 55, 60, 70 };
double avg = Queryable.Average(arr.AsQueryable());
Console.WriteLine("Average = "+avg);
}
}
Average = 38.375 | [
{
"code": null,
"e": 1137,
"s": 1062,
"text": "To find the average of integers in C#, use the Queryable Average() method."
},
{
"code": null,
"e": 1183,
"s": 1137,
"text": "Let’s say the following is our integer array."
},
{
"code": null,
"e": 1239,
"s": 1183,
"text": "var arr = new int[] { 10, 17, 25, 30, 40, 55, 60, 70 };"
},
{
"code": null,
"e": 1305,
"s": 1239,
"text": "Now, use the Average() method to get the average of the elements."
},
{
"code": null,
"e": 1356,
"s": 1305,
"text": "double avg = Queryable.Average(arr.AsQueryable());"
},
{
"code": null,
"e": 1367,
"s": 1356,
"text": " Live Demo"
},
{
"code": null,
"e": 1606,
"s": 1367,
"text": "using System;\nusing System.Linq;\nclass Demo {\n static void Main() {\n var arr = new int[] { 10, 17, 25, 30, 40, 55, 60, 70 };\n double avg = Queryable.Average(arr.AsQueryable());\n Console.WriteLine(\"Average = \"+avg);\n }\n}"
},
{
"code": null,
"e": 1623,
"s": 1606,
"text": "Average = 38.375"
}
]
|
R – NonLinear Least Square | 22 Apr, 2020
In non-linear function, the points plotted on the graph are not linear and thus, do not give a curve or line on the graph. So, non-linear regression analysis is used to alter the parameters of the function to obtain a curve or regression line that is closed to your data.To perform this, Non-Linear Least Square approach is used to minimize the total sum of squares of residual values or error values i.e., the difference between vertical points on the graph from regression line and will fit the non-linear function accordingly.
Mathematical Formula:
where,
r is residual or error value between 2 points.
Above mathematical function to find minimum residual function can be performed in R using resid() function.
Regression analysis is widely used in all types of business issues to perform a smart decision or predicting the future by altering a factor of their business.In R language, Non-linear Least Square function is represented as –Syntax:
nls(formula, start)
where,
formula indicates the model formula i.e., non-linear functionstart is a list of starting estimates
Note: To know about more optional parameters of nls(), use below command in R console –
help("nls")
Example 1 :In this example, a non-linear function is taken and plotted on the graph as points.
# defining x and y coordinatesx <- seq(0, 10, 0.1)y <- rnorm(101, 5, 1) # output to be present as PNG filepng(file ="nls.png") # Taking the model to get fittedm <- nls(y~a * x ^ 3 + b * x + c, start = list(a = 1, b = 2, c = 1)) # plot the graphplot(x, y, col.lab ="darkgreen", col.axis ="darkgreen") # plot the graph with new fitting line# or regression linelines(x, predict(m)) # saving the filedev.off() # print minimum residual or error valueprint(sum(resid(m)^2))
Output :
[1] 106.4507
Example 2 :In this example, below code is accepting a non-linear function as shown:
Further plotting the points and regression line and also, finding out the goodness of fit also by using cor() method.
# creating sequence of 101 values from 0 to 100x <- seq(0, 100, 1) y<-((runif(1, 10, 20)*x)/(runif(1, 0, 10) + x)) + rnorm(101, 0, 1) # output to be present as PNG filepng(file ="nls2.png") # using starting values in nls() function# to not get a warningm<-nls(y~a * x/(b + x), start = list(a = 1, b = 2)) # goodness of fitcor(y, predict(m)) # minimized residual valuesum(resid(m)^2) # plotting points on graphplot(x, y) # finding regression linelines(x, predict(m)) # saving the filedev.off()
Output :
[1] 0.9622681
[1] 108.1481
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 558,
"s": 28,
"text": "In non-linear function, the points plotted on the graph are not linear and thus, do not give a curve or line on the graph. So, non-linear regression analysis is used to alter the parameters of the function to obtain a curve or regression line that is closed to your data.To perform this, Non-Linear Least Square approach is used to minimize the total sum of squares of residual values or error values i.e., the difference between vertical points on the graph from regression line and will fit the non-linear function accordingly."
},
{
"code": null,
"e": 580,
"s": 558,
"text": "Mathematical Formula:"
},
{
"code": null,
"e": 587,
"s": 580,
"text": "where,"
},
{
"code": null,
"e": 634,
"s": 587,
"text": "r is residual or error value between 2 points."
},
{
"code": null,
"e": 742,
"s": 634,
"text": "Above mathematical function to find minimum residual function can be performed in R using resid() function."
},
{
"code": null,
"e": 976,
"s": 742,
"text": "Regression analysis is widely used in all types of business issues to perform a smart decision or predicting the future by altering a factor of their business.In R language, Non-linear Least Square function is represented as –Syntax:"
},
{
"code": null,
"e": 997,
"s": 976,
"text": "nls(formula, start)\n"
},
{
"code": null,
"e": 1004,
"s": 997,
"text": "where,"
},
{
"code": null,
"e": 1103,
"s": 1004,
"text": "formula indicates the model formula i.e., non-linear functionstart is a list of starting estimates"
},
{
"code": null,
"e": 1191,
"s": 1103,
"text": "Note: To know about more optional parameters of nls(), use below command in R console –"
},
{
"code": null,
"e": 1204,
"s": 1191,
"text": "help(\"nls\")\n"
},
{
"code": null,
"e": 1299,
"s": 1204,
"text": "Example 1 :In this example, a non-linear function is taken and plotted on the graph as points."
},
{
"code": "# defining x and y coordinatesx <- seq(0, 10, 0.1)y <- rnorm(101, 5, 1) # output to be present as PNG filepng(file =\"nls.png\") # Taking the model to get fittedm <- nls(y~a * x ^ 3 + b * x + c, start = list(a = 1, b = 2, c = 1)) # plot the graphplot(x, y, col.lab =\"darkgreen\", col.axis =\"darkgreen\") # plot the graph with new fitting line# or regression linelines(x, predict(m)) # saving the filedev.off() # print minimum residual or error valueprint(sum(resid(m)^2))",
"e": 1799,
"s": 1299,
"text": null
},
{
"code": null,
"e": 1808,
"s": 1799,
"text": "Output :"
},
{
"code": null,
"e": 1821,
"s": 1808,
"text": "[1] 106.4507"
},
{
"code": null,
"e": 1905,
"s": 1821,
"text": "Example 2 :In this example, below code is accepting a non-linear function as shown:"
},
{
"code": null,
"e": 2023,
"s": 1905,
"text": "Further plotting the points and regression line and also, finding out the goodness of fit also by using cor() method."
},
{
"code": "# creating sequence of 101 values from 0 to 100x <- seq(0, 100, 1) y<-((runif(1, 10, 20)*x)/(runif(1, 0, 10) + x)) + rnorm(101, 0, 1) # output to be present as PNG filepng(file =\"nls2.png\") # using starting values in nls() function# to not get a warningm<-nls(y~a * x/(b + x), start = list(a = 1, b = 2)) # goodness of fitcor(y, predict(m)) # minimized residual valuesum(resid(m)^2) # plotting points on graphplot(x, y) # finding regression linelines(x, predict(m)) # saving the filedev.off()",
"e": 2558,
"s": 2023,
"text": null
},
{
"code": null,
"e": 2567,
"s": 2558,
"text": "Output :"
},
{
"code": null,
"e": 2595,
"s": 2567,
"text": "[1] 0.9622681\n[1] 108.1481\n"
},
{
"code": null,
"e": 2602,
"s": 2595,
"text": "Picked"
},
{
"code": null,
"e": 2613,
"s": 2602,
"text": "R Language"
}
]
|
HTML | thead bgcolor Attribute | 31 Dec, 2019
The HTML thead bgcolor Attribute is used to specify the background color of a table head. It is not supported by HTML 5.
Syntax:
<thead bgcolor= "color_name | hex_number | rgb_number">
Attribute Values:
color_name: It sets the text color by using the color name. For example “red”.
hex_number: It sets the text color by using the color hex code. For example “#0000ff”.
rgb_number: It sets the text color by using the rgb code. For example: “RGB(0, 153, 0)”.
Example:
<!DOCTYPE html> <html> <head> <title> HTML thead bgcolor Attribute </title> </head> <body> <h1>GeeksforGeeks</h1> <h2>HTML thead bgcolor Attribute</h2> <table border="1" width="500"> <thead bgcolor="red"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> </thead> <tbody align="center" > <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </tbody> </table> </body> </html>
Output :
Supported Browsers: The browser supported by HTML <thead> bgcolor attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Make a div horizontally scrollable using CSS
DOM (Document Object Model)
How to get values from html input array using JavaScript ?
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
How do you run JavaScript script through the Terminal?
Node.js fs.readFileSync() Method
How to set space between the flexbox ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Dec, 2019"
},
{
"code": null,
"e": 149,
"s": 28,
"text": "The HTML thead bgcolor Attribute is used to specify the background color of a table head. It is not supported by HTML 5."
},
{
"code": null,
"e": 157,
"s": 149,
"text": "Syntax:"
},
{
"code": null,
"e": 213,
"s": 157,
"text": "<thead bgcolor= \"color_name | hex_number | rgb_number\">"
},
{
"code": null,
"e": 231,
"s": 213,
"text": "Attribute Values:"
},
{
"code": null,
"e": 310,
"s": 231,
"text": "color_name: It sets the text color by using the color name. For example “red”."
},
{
"code": null,
"e": 397,
"s": 310,
"text": "hex_number: It sets the text color by using the color hex code. For example “#0000ff”."
},
{
"code": null,
"e": 486,
"s": 397,
"text": "rgb_number: It sets the text color by using the rgb code. For example: “RGB(0, 153, 0)”."
},
{
"code": null,
"e": 495,
"s": 486,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> HTML thead bgcolor Attribute </title> </head> <body> <h1>GeeksforGeeks</h1> <h2>HTML thead bgcolor Attribute</h2> <table border=\"1\" width=\"500\"> <thead bgcolor=\"red\"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> </thead> <tbody align=\"center\" > <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </tbody> </table> </body> </html> ",
"e": 1100,
"s": 495,
"text": null
},
{
"code": null,
"e": 1109,
"s": 1100,
"text": "Output :"
},
{
"code": null,
"e": 1203,
"s": 1109,
"text": "Supported Browsers: The browser supported by HTML <thead> bgcolor attribute are listed below:"
},
{
"code": null,
"e": 1217,
"s": 1203,
"text": "Google Chrome"
},
{
"code": null,
"e": 1235,
"s": 1217,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1243,
"s": 1235,
"text": "Firefox"
},
{
"code": null,
"e": 1250,
"s": 1243,
"text": "Safari"
},
{
"code": null,
"e": 1256,
"s": 1250,
"text": "Opera"
},
{
"code": null,
"e": 1272,
"s": 1256,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1277,
"s": 1272,
"text": "HTML"
},
{
"code": null,
"e": 1294,
"s": 1277,
"text": "Web Technologies"
},
{
"code": null,
"e": 1299,
"s": 1294,
"text": "HTML"
},
{
"code": null,
"e": 1397,
"s": 1299,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1421,
"s": 1397,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1460,
"s": 1421,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1505,
"s": 1460,
"text": "Make a div horizontally scrollable using CSS"
},
{
"code": null,
"e": 1533,
"s": 1505,
"text": "DOM (Document Object Model)"
},
{
"code": null,
"e": 1592,
"s": 1533,
"text": "How to get values from html input array using JavaScript ?"
},
{
"code": null,
"e": 1625,
"s": 1592,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1683,
"s": 1625,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 1738,
"s": 1683,
"text": "How do you run JavaScript script through the Terminal?"
},
{
"code": null,
"e": 1771,
"s": 1738,
"text": "Node.js fs.readFileSync() Method"
}
]
|
Change Legend Size in Base R Plot | 30 May, 2021
In this article, we will be looking at the approach to change the size of the legend in the plot in the R programming language.
To change the legend size of the plot, the user needs to use the cex argument of the legend function and specify its value with the user requirement, the values of cex greater than 1 will increase the legend size in the plot and the value of cex less than 1 will decrease the size of the legend in the plot.
Syntax: legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg)
Parameters:
x and y: These are co-ordinates to be used to position the legend
legend: Text of the legend
fill: Colors to use for filling the boxes with legend text
col: Colors of lines
bg: It defines background color for the legend box
cex: Used for scaling
title: Legend title (optional)
text.font: An integer specifying the font style of the legend (optional)
Returns: Legend plot
cex is a number indicating the amount by which plotting text and symbols should be scaled relative to the default. 1=default, 1.5 is 50% larger, 0.5 is 50% smaller, etc.
Example 1:
R
x1 <- c(1,8,5,3,8,7) y1 <- c(4,6,3,8,2,7)plot(x1,y1,cex=.8,pch=1,col="red") x2<-c(4,5,8,6,4)y2<-c(9,8,2,3,1) x3<-c(2,1,6,7,4)y3<-c(7,9,1,5,2) points(x2,y2,cex=.8,pch=2,col="blue")points(x3,y3,cex=.8,pch=3,col="green") legend("topright",c("gfg1","gfg2","gfg3"), cex=0.5,col=c("red","blue","green"), pch=c(1,2,3))
Output:
Example 2:
R
gfg_data <- matrix(c(1,2,3,4,5,6,7,8,9,10), ncol = 5) colnames(gfg_data) <- paste0("Gfg", 1:5)rownames(gfg_data) <- c('A','B') gfg_data barplot(gfg_data, col = 1:nrow(gfg_data)) legend("topright", legend = rownames(gfg_data), pch = 15, col = 1:nrow(gfg_data),cex=2.5)
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 156,
"s": 28,
"text": "In this article, we will be looking at the approach to change the size of the legend in the plot in the R programming language."
},
{
"code": null,
"e": 464,
"s": 156,
"text": "To change the legend size of the plot, the user needs to use the cex argument of the legend function and specify its value with the user requirement, the values of cex greater than 1 will increase the legend size in the plot and the value of cex less than 1 will decrease the size of the legend in the plot."
},
{
"code": null,
"e": 540,
"s": 464,
"text": "Syntax: legend(x, y, legend, fill, col, bg, lty, cex, title, text.font, bg)"
},
{
"code": null,
"e": 552,
"s": 540,
"text": "Parameters:"
},
{
"code": null,
"e": 618,
"s": 552,
"text": "x and y: These are co-ordinates to be used to position the legend"
},
{
"code": null,
"e": 645,
"s": 618,
"text": "legend: Text of the legend"
},
{
"code": null,
"e": 704,
"s": 645,
"text": "fill: Colors to use for filling the boxes with legend text"
},
{
"code": null,
"e": 725,
"s": 704,
"text": "col: Colors of lines"
},
{
"code": null,
"e": 776,
"s": 725,
"text": "bg: It defines background color for the legend box"
},
{
"code": null,
"e": 798,
"s": 776,
"text": "cex: Used for scaling"
},
{
"code": null,
"e": 836,
"s": 798,
"text": "title: Legend title (optional)"
},
{
"code": null,
"e": 909,
"s": 836,
"text": "text.font: An integer specifying the font style of the legend (optional)"
},
{
"code": null,
"e": 930,
"s": 909,
"text": "Returns: Legend plot"
},
{
"code": null,
"e": 1101,
"s": 930,
"text": "cex is a number indicating the amount by which plotting text and symbols should be scaled relative to the default. 1=default, 1.5 is 50% larger, 0.5 is 50% smaller, etc. "
},
{
"code": null,
"e": 1112,
"s": 1101,
"text": "Example 1:"
},
{
"code": null,
"e": 1114,
"s": 1112,
"text": "R"
},
{
"code": "x1 <- c(1,8,5,3,8,7) y1 <- c(4,6,3,8,2,7)plot(x1,y1,cex=.8,pch=1,col=\"red\") x2<-c(4,5,8,6,4)y2<-c(9,8,2,3,1) x3<-c(2,1,6,7,4)y3<-c(7,9,1,5,2) points(x2,y2,cex=.8,pch=2,col=\"blue\")points(x3,y3,cex=.8,pch=3,col=\"green\") legend(\"topright\",c(\"gfg1\",\"gfg2\",\"gfg3\"), cex=0.5,col=c(\"red\",\"blue\",\"green\"), pch=c(1,2,3))",
"e": 1457,
"s": 1114,
"text": null
},
{
"code": null,
"e": 1465,
"s": 1457,
"text": "Output:"
},
{
"code": null,
"e": 1476,
"s": 1465,
"text": "Example 2:"
},
{
"code": null,
"e": 1478,
"s": 1476,
"text": "R"
},
{
"code": "gfg_data <- matrix(c(1,2,3,4,5,6,7,8,9,10), ncol = 5) colnames(gfg_data) <- paste0(\"Gfg\", 1:5)rownames(gfg_data) <- c('A','B') gfg_data barplot(gfg_data, col = 1:nrow(gfg_data)) legend(\"topright\", legend = rownames(gfg_data), pch = 15, col = 1:nrow(gfg_data),cex=2.5)",
"e": 1800,
"s": 1478,
"text": null
},
{
"code": null,
"e": 1808,
"s": 1800,
"text": "Output:"
},
{
"code": null,
"e": 1815,
"s": 1808,
"text": "Picked"
},
{
"code": null,
"e": 1824,
"s": 1815,
"text": "R-Charts"
},
{
"code": null,
"e": 1833,
"s": 1824,
"text": "R-Graphs"
},
{
"code": null,
"e": 1841,
"s": 1833,
"text": "R-plots"
},
{
"code": null,
"e": 1852,
"s": 1841,
"text": "R Language"
},
{
"code": null,
"e": 1950,
"s": 1852,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2002,
"s": 1950,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2060,
"s": 2002,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2095,
"s": 2060,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2133,
"s": 2095,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2182,
"s": 2133,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2199,
"s": 2182,
"text": "R - if statement"
},
{
"code": null,
"e": 2236,
"s": 2199,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 2279,
"s": 2236,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2316,
"s": 2279,
"text": "How to import an Excel File into R ?"
}
]
|
JavaScript String fromCharCode() Method | 05 Oct, 2021
Below is the example of the String.fromCharCode() Method.
Example:<script> function func() { var str = String.fromCharCode(71, 70, 71); document.write(str); } func(); </script>
<script> function func() { var str = String.fromCharCode(71, 70, 71); document.write(str); } func(); </script>
Output:GFG
GFG
String.fromCharCode() method is used to create a string from the given sequence of UTF-16 code units.
Syntax:
String.fromCharCode(n1, n2, ..., nX)
Arguments:The method takes the UTF-16 Unicode sequences as its argument. The number of arguments to this method depends upon the number of characters to be joined as a string. The range of the numbers is between 0 and 65535
Return value:The return value of this method is a string containing the characters whose UTF-16 codes were passed to the method as arguments.
Examples for the above method are provided below:
Example 1:
print(String.fromCharCode(65, 66, 67));
Output:
ABC
In this example the method fromCharCode() converts the UTF-16 codes into their equivalent characters and returns the string containing them as the answer. In this case the answer is ABC.
Example 2:
String.fromCharCode(0x12014);
Output:
—
In this example the method fromCharCode() converts the UTF-16 code into its equivalent character and returns the string containing it as the answer. In this case the answer is —.
Codes for the above method are provided below:
Program 1:
<script>// JavaScript to illustrate fromCharCode() methodfunction func() { // UTF-16 codes to be converted into characters var str = String.fromCharCode(65, 66, 67); document.write(str);} func();</script>
Output:
ABC
Program 2:
<script>// JavaScript to illustrate fromCharCode() methodfunction func() { // UTF-16 code to be converted into character var str = String.fromCharCode(0x12014); document.write(str); } func();</script>
Output:
—
Supported Browsers:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 4 and above
Opera 4 and above
Safari 1 and above
ysachin2314
JavaScript-Methods
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 86,
"s": 28,
"text": "Below is the example of the String.fromCharCode() Method."
},
{
"code": null,
"e": 214,
"s": 86,
"text": "Example:<script> function func() { var str = String.fromCharCode(71, 70, 71); document.write(str); } func(); </script> "
},
{
"code": "<script> function func() { var str = String.fromCharCode(71, 70, 71); document.write(str); } func(); </script> ",
"e": 334,
"s": 214,
"text": null
},
{
"code": null,
"e": 346,
"s": 334,
"text": "Output:GFG\n"
},
{
"code": null,
"e": 351,
"s": 346,
"text": "GFG\n"
},
{
"code": null,
"e": 453,
"s": 351,
"text": "String.fromCharCode() method is used to create a string from the given sequence of UTF-16 code units."
},
{
"code": null,
"e": 461,
"s": 453,
"text": "Syntax:"
},
{
"code": null,
"e": 499,
"s": 461,
"text": "String.fromCharCode(n1, n2, ..., nX)\n"
},
{
"code": null,
"e": 723,
"s": 499,
"text": "Arguments:The method takes the UTF-16 Unicode sequences as its argument. The number of arguments to this method depends upon the number of characters to be joined as a string. The range of the numbers is between 0 and 65535"
},
{
"code": null,
"e": 865,
"s": 723,
"text": "Return value:The return value of this method is a string containing the characters whose UTF-16 codes were passed to the method as arguments."
},
{
"code": null,
"e": 915,
"s": 865,
"text": "Examples for the above method are provided below:"
},
{
"code": null,
"e": 926,
"s": 915,
"text": "Example 1:"
},
{
"code": null,
"e": 969,
"s": 926,
"text": "print(String.fromCharCode(65, 66, 67)); \n"
},
{
"code": null,
"e": 977,
"s": 969,
"text": "Output:"
},
{
"code": null,
"e": 982,
"s": 977,
"text": "ABC\n"
},
{
"code": null,
"e": 1169,
"s": 982,
"text": "In this example the method fromCharCode() converts the UTF-16 codes into their equivalent characters and returns the string containing them as the answer. In this case the answer is ABC."
},
{
"code": null,
"e": 1180,
"s": 1169,
"text": "Example 2:"
},
{
"code": null,
"e": 1211,
"s": 1180,
"text": "String.fromCharCode(0x12014);\n"
},
{
"code": null,
"e": 1219,
"s": 1211,
"text": "Output:"
},
{
"code": null,
"e": 1222,
"s": 1219,
"text": "—\n"
},
{
"code": null,
"e": 1401,
"s": 1222,
"text": "In this example the method fromCharCode() converts the UTF-16 code into its equivalent character and returns the string containing it as the answer. In this case the answer is —."
},
{
"code": null,
"e": 1448,
"s": 1401,
"text": "Codes for the above method are provided below:"
},
{
"code": null,
"e": 1459,
"s": 1448,
"text": "Program 1:"
},
{
"code": "<script>// JavaScript to illustrate fromCharCode() methodfunction func() { // UTF-16 codes to be converted into characters var str = String.fromCharCode(65, 66, 67); document.write(str);} func();</script>",
"e": 1676,
"s": 1459,
"text": null
},
{
"code": null,
"e": 1684,
"s": 1676,
"text": "Output:"
},
{
"code": null,
"e": 1689,
"s": 1684,
"text": "ABC\n"
},
{
"code": null,
"e": 1700,
"s": 1689,
"text": "Program 2:"
},
{
"code": "<script>// JavaScript to illustrate fromCharCode() methodfunction func() { // UTF-16 code to be converted into character var str = String.fromCharCode(0x12014); document.write(str); } func();</script>",
"e": 1913,
"s": 1700,
"text": null
},
{
"code": null,
"e": 1921,
"s": 1913,
"text": "Output:"
},
{
"code": null,
"e": 1924,
"s": 1921,
"text": "—\n"
},
{
"code": null,
"e": 1944,
"s": 1924,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 1963,
"s": 1944,
"text": "Chrome 1 and above"
},
{
"code": null,
"e": 1981,
"s": 1963,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 2001,
"s": 1981,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 2031,
"s": 2001,
"text": "Internet Explorer 4 and above"
},
{
"code": null,
"e": 2049,
"s": 2031,
"text": "Opera 4 and above"
},
{
"code": null,
"e": 2068,
"s": 2049,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 2080,
"s": 2068,
"text": "ysachin2314"
},
{
"code": null,
"e": 2099,
"s": 2080,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 2117,
"s": 2099,
"text": "javascript-string"
},
{
"code": null,
"e": 2128,
"s": 2117,
"text": "JavaScript"
},
{
"code": null,
"e": 2145,
"s": 2128,
"text": "Web Technologies"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.