title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
How to plot a 2D matrix in Python with colorbar Matplotlib? | To plot a 2D matrix in Python with colorbar, we can use numpy to create a 2D array matrix and use that matrix in the imshow() method.
Create data2D using numpy.
Create data2D using numpy.
Use imshow() method to display data as an image, i.e., on a 2D regular raster.
Use imshow() method to display data as an image, i.e., on a 2D regular raster.
Create a colorbar for a ScalarMappable instance *mappable* using colorbar() method and imshow() scalar mappable image.
Create a colorbar for a ScalarMappable instance *mappable* using colorbar() method and imshow() scalar mappable image.
To display the figure, use show() 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
data2D = np.random.random((50, 50))
im = plt.imshow(data2D, cmap="copper_r")
plt.colorbar(im)
plt.show() | [
{
"code": null,
"e": 1196,
"s": 1062,
"text": "To plot a 2D matrix in Python with colorbar, we can use numpy to create a 2D array matrix and use that matrix in the imshow() method."
},
{
"code": null,
"e": 1223,
"s": 1196,
"text": "Create data2D using numpy."
},
{
"code":... |
Count number of nodes in a complete Binary Tree - GeeksforGeeks | 08 Apr, 2022
Given the root of a Complete Binary Tree consisting of N nodes, the task is to find the total number of nodes in the given Binary Tree.
Examples:
Input:
Output: 7
Input:
Output: 5
Naive Approach: The simple approach to solve the given tree is to perform the DFS Traversal on the given tree and count the number of nodes in it. After traversal, print the total count of nodes obtained.
Time Complexity: O(N)Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by the fact that:
A complete binary tree has (2h – 1) nodes in total.
By this logic, in the first case, compare the left sub-tree height with the right sub-tree height. If they are equal it is a full tree, then the answer will be 2^height – 1. Otherwise, If they aren’t equal, recursively call for the left sub-tree and the right sub-tree to count the number of nodes. Follow the steps below to solve the problem:
Define a function left_height(root) and find the left height of the given Tree by traversing in the root’s left direction and store it in a variable, say leftHeight.
Define a function right_height(root) and find the right height of the given Tree by traversing in the root’s right direction and store it in a variable, say rightHeight.
Find the left and the right height of the given Tree for the current root value and if it is equal then return the value of (2height – 1) as the resultant count of nodes.
Otherwise, recursively call for the function for the left and right sub-trees and return the sum of them + 1 as the resultant count of nodes.
Below is the implementation of the above approach.
C++
C
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Structure of a Tree Nodeclass node {public: int data; node* left; node* right;}; node* newNode(int data); // Function to get the left height of// the binary treeint left_height(node* node){ int ht = 0; while (node) { ht++; node = node->left; } // Return the left height obtained return ht;} // Function to get the right height// of the binary treeint right_height(node* node){ int ht = 0; while (node) { ht++; node = node->right; } // Return the right height obtained return ht;} // Function to get the count of nodes// in complete binary treeint TotalNodes(node* root){ // Base Case if (root == NULL) return 0; // Find the left height and the // right heights int lh = left_height(root); int rh = right_height(root); // If left and right heights are // equal return 2^height(1<<height) -1 if (lh == rh) return (1 << lh) - 1; // Otherwise, recursive call return 1 + TotalNodes(root->left) + TotalNodes(root->right);} // Helper function to allocate a new node// with the given datanode* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} // Driver Codeint main(){ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(9); root->right->right = newNode(8); root->left->left->left = newNode(6); root->left->left->right = newNode(7); cout << TotalNodes(root); return 0;} // This code is contributed by aditya kumar (adityakumar129)
// C program for the above approach#include <stdio.h>#include <stdlib.h> // Structure of a Tree Nodetypedef struct node { int data; struct node* left; struct node* right;}node; // Helper function to allocate a new node// with the given datanode* newNode(int data){ node * Node = (node *)malloc(sizeof(node)); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} // Function to get the left height of// the binary treeint left_height(node* node){ int ht = 0; while (node) { ht++; node = node->left; } // Return the left height obtained return ht;} // Function to get the right height// of the binary treeint right_height(node* node){ int ht = 0; while (node) { ht++; node = node->right; } // Return the right height obtained return ht;} // Function to get the count of nodes// in complete binary treeint TotalNodes(node* root){ // Base Case if (root == NULL) return 0; // Find the left height and the // right heights int lh = left_height(root); int rh = right_height(root); // If left and right heights are // equal return 2^height(1<<height) -1 if (lh == rh) return (1 << lh) - 1; // Otherwise, recursive call return 1 + TotalNodes(root->left) + TotalNodes(root->right);} // Driver Codeint main(){ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(9); root->right->right = newNode(8); root->left->left->left = newNode(6); root->left->left->right = newNode(7); printf("%d",TotalNodes(root)); return 0;} // This code is contributed by aditya kumar (adityakumar129)
// Java program for the above approachimport java.util.*; class GFG{ // Structure of a Tree Nodestatic class node { int data; node left; node right;}; // Function to get the left height of// the binary treestatic int left_height(node node){ int ht = 0; while (node!=null) { ht++; node = node.left; } // Return the left height obtained return ht;} // Function to get the right height// of the binary treestatic int right_height(node node){ int ht = 0; while (node!=null) { ht++; node = node.right; } // Return the right height obtained return ht;} // Function to get the count of nodes// in complete binary treestatic int TotalNodes(node root){ // Base Case if (root == null) return 0; // Find the left height and the // right heights int lh = left_height(root); int rh = right_height(root); // If left and right heights are // equal return 2^height(1<<height) -1 if (lh == rh) return (1 << lh) - 1; // Otherwise, recursive call return 1 + TotalNodes(root.left) + TotalNodes(root.right);} // Helper function to allocate a new node// with the given datastatic node newNode(int data){ node Node = new node(); Node.data = data; Node.left = null; Node.right = null; return (Node);} // Driver Codepublic static void main(String[] args){ node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(9); root.right.right = newNode(8); root.left.left.left = newNode(6); root.left.left.right = newNode(7); System.out.print(TotalNodes(root)); }} // This code is contributed by shikhasingrajput
# Python program for the above approach # Structure of a Tree Nodeclass node: def __init__(self, key): self.left = None self.right = None self.val = key # Function to get the left height of# the binary treedef left_height(node): ht = 0 while(node): ht += 1 node = node.left # Return the left height obtained return ht # Function to get the right height# of the binary treedef right_height(node): ht = 0 while(node): ht += 1 node = node.right # Return the right height obtained return ht # Function to get the count of nodes# in complete binary treedef TotalNodes(root): # Base case if(root == None): return 0 # Find the left height and the # right heights lh = left_height(root) rh = right_height(root) # If left and right heights are # equal return 2^height(1<<height) -1 if(lh == rh): return (1 << lh) - 1 # Otherwise, recursive call return 1 + TotalNodes(root.left) + TotalNodes(root.right) # Driver coderoot = node(1)root.left = node(2)root.right = node(3)root.left.left = node(4)root.left.right = node(5)root.right.left = node(9)root.right.right = node(8)root.left.left.left = node(6)root.left.left.right = node(7) print(TotalNodes(root)) # This code is contributed by parthmanchanda81
// C# program for the above approachusing System; public class GFG{ // Structure of a Tree Nodeclass node { public int data; public node left; public node right;}; // Function to get the left height of// the binary treestatic int left_height(node node){ int ht = 0; while (node != null) { ht++; node = node.left; } // Return the left height obtained return ht;} // Function to get the right height// of the binary treestatic int right_height(node node){ int ht = 0; while (node != null) { ht++; node = node.right; } // Return the right height obtained return ht;} // Function to get the count of nodes// in complete binary treestatic int TotalNodes(node root){ // Base Case if (root == null) return 0; // Find the left height and the // right heights int lh = left_height(root); int rh = right_height(root); // If left and right heights are // equal return 2^height(1<<height) -1 if (lh == rh) return (1 << lh) - 1; // Otherwise, recursive call return 1 + TotalNodes(root.left) + TotalNodes(root.right);} // Helper function to allocate a new node// with the given datastatic node newNode(int data){ node Node = new node(); Node.data = data; Node.left = null; Node.right = null; return (Node);} // Driver Codepublic static void Main(String[] args){ node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(9); root.right.right = newNode(8); root.left.left.left = newNode(6); root.left.left.right = newNode(7); Console.Write(TotalNodes(root));}} // This code is contributed by shikhasingrajput
<script> // JavaScript Program to implement // the above approach // Structure of a Tree Node class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } }; // Function to get the left height of // the binary tree function left_height(node) { let ht = 0; while (node) { ht++; node = node.left; } // Return the left height obtained return ht; } // Function to get the right height // of the binary tree function right_height(node) { let ht = 0; while (node) { ht++; node = node.right; } // Return the right height obtained return ht; } // Function to get the count of nodes // in complete binary tree function TotalNodes(root) { // Base Case if (root == null) return 0; // Find the left height and the // right heights let lh = left_height(root); let rh = right_height(root); // If left and right heights are // equal return 2^height(1<<height) -1 if (lh == rh) return (1 << lh) - 1; // Otherwise, recursive call return 1 + TotalNodes(root.left) + TotalNodes(root.right); } // Helper function to allocate a new node // with the given data // Driver Code let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(9); root.right.right = new Node(8); root.left.left.left = new Node(6); root.left.left.right = new Node(7); document.write(TotalNodes(root)); // This code is contributed by Potta Lokesh </script>
9
Time Complexity: O((log N)2)Auxiliary Space: O(log N) because of Recursion Stack Space
lokeshpotta20
shikhasingrajput
parthmanchanda81
surindertarika1234
prasanna1995
adityakumar129
Binary Tree
Complete Binary Tree
Google
interview-preparation
tree-traversal
Recursion
Tree
Google
Recursion
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Recursive Insertion Sort
Program to calculate Height and Depth of a node in a Binary Tree
Divide an array into K subarray with the given condition
Sum of natural numbers using recursion
Practice Questions for Recursion | Set 1
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": 24611,
"s": 24583,
"text": "\n08 Apr, 2022"
},
{
"code": null,
"e": 24747,
"s": 24611,
"text": "Given the root of a Complete Binary Tree consisting of N nodes, the task is to find the total number of nodes in the given Binary Tree."
},
{
"code": null,... |
C# - Events | Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts. Events are used for inter-process communication.
The events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to publish the event. This is called the publisher class. Some other class that accepts this event is called the subscriber class. Events use the publisher-subscriber model.
A publisher is an object that contains the definition of the event and the delegate. The event-delegate association is also defined in this object. A publisher class object invokes the event and it is notified to other objects.
A subscriber is an object that accepts the event and provides an event handler. The delegate in the publisher class invokes the method (event handler) of the subscriber class.
To declare an event inside a class, first of all, you must declare a delegate type for the even as:
public delegate string BoilerLogHandler(string str);
then, declare the event using the event keyword −
event BoilerLogHandler BoilerEventLog;
The preceding code defines a delegate named BoilerLogHandler and an event named BoilerEventLog, which invokes the delegate when it is raised.
using System;
namespace SampleApp {
public delegate string MyDel(string str);
class EventProgram {
event MyDel MyEvent;
public EventProgram() {
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username) {
return "Welcome " + username;
}
static void Main(string[] args) {
EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("Tutorials Point");
Console.WriteLine(result);
}
}
}
When the above code is compiled and executed, it produces the following result −
Welcome Tutorials Point
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2533,
"s": 2270,
"text": "Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts. Events are used for inter-process commu... |
How to find all files with names containing a string on Linux? | In order to be able to find all files with names containing a string in Linux command line, we will make use of the grep command, and at first we must understand what a grep command is and how to use it on Linux.
The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display the lines that contain the pattern that we are trying to search.
Normally, the pattern that we are trying to search in the file is referred to as the regular expression.
grep [options] pattern [files]
While there are plenty of different options available to us, some of the most used are −
-c : It lists only a count of the lines that match a pattern
-h : displays the matched lines only.
-i : Ignores, case for matching
-l : prints filenames only
-n : Display the matched lines and their line numbers.
-v : It prints out all the lines that do not match the pattern
-R : stands for recurse, would go into subdirectories as well.
Now, let’s consider a case where we want to find a particular pattern in all the files in a particular directory, say dir1.
grep -rni "word" *
In the above command replace the “word” placeholder with
For that, we make use of the command shown below −
grep -rni "func main()" *
The above command will try to find a string “func main()” in all the files in a particular directory and also in the subdirectories as well.
main.go:120:func main() {}
In case we only want to find a particular pattern in a single directory and not the subdirectories then we need to use the command shown below −
grep -s "func main()" *
In the above command we made use of the -s flag which will help us to not get a warning for each subdirectory that is present inside the directory where we are running the command.
main.go:120:func main() {}
grep -R "apples" .
immukul@192 linux-dir1% grep -R "apples" .
./d1/file.txt:apples
./d1/file.txt:applesauce
./d1/file.txt:applesnits
./d1/file.txt:dapples
./d1/file.txt:grapples
./d1/file.txt:mayapples
./d1/file.txt:pineapples
./d1/file.txt:sapples
./d1/file.txt:scrapples
./d2/2.txt:orange apples is great together
./d2/2.txt:apples nto great
./d2/2.txt:is apples good | [
{
"code": null,
"e": 1275,
"s": 1062,
"text": "In order to be able to find all files with names containing a string in Linux command line, we will make use of the grep command, and at first we must understand what a grep command is and how to use it on Linux."
},
{
"code": null,
"e": 150... |
AWK - Arithmetic Operators | AWK supports the following arithmetic operators −
It is represented by plus (+) symbol which adds two or more numbers. The following example demonstrates this −
[jerry]$ awk 'BEGIN { a = 50; b = 20; print "(a + b) = ", (a + b) }'
On executing this code, you get the following result −
(a + b) = 70
It is represented by minus (-) symbol which subtracts two or more numbers. The following example demonstrates this −
[jerry]$ awk 'BEGIN { a = 50; b = 20; print "(a - b) = ", (a - b) }'
On executing this code, you get the following result −
(a - b) = 30
It is represented by asterisk (*) symbol which multiplies two or more numbers. The following example demonstrates this −
[jerry]$ awk 'BEGIN { a = 50; b = 20; print "(a * b) = ", (a * b) }'
On executing this code, you get the following result −
(a * b) = 1000
It is represented by slash (/) symbol which divides two or more numbers. The following example illustrates this −
[jerry]$ awk 'BEGIN { a = 50; b = 20; print "(a / b) = ", (a / b) }'
On executing this code, you get the following result −
(a / b) = 2.5
It is represented by percent (%) symbol which finds the Modulus division of two or more numbers. The following example illustrates this −
[jerry]$ awk 'BEGIN { a = 50; b = 20; print "(a % b) = ", (a % b) }'
On executing this code, you get the following result −
(a % b) = 10
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1907,
"s": 1857,
"text": "AWK supports the following arithmetic operators −"
},
{
"code": null,
"e": 2018,
"s": 1907,
"text": "It is represented by plus (+) symbol which adds two or more numbers. The following example demonstrates this −"
},
{
"code":... |
How to assess your code performance in Python | by Sophia Yang | Towards Data Science | Profiling helps us identify bottlenecks and optimize performance in our code. If our code runs slowly, we can identify where our code is slow and then make corresponding improvements.
Here are the explanations of Python profilers from the Python documentation:
cProfile and profile provide deterministic profiling of Python programs. A profile is a set of statistics that describes how often and for how long various parts of the program executed...cProfile is recommended for most users; it’s a C extension with reasonable overhead that makes it suitable for profiling long-running programs.
cProfile is a Python built-in profiler, which is great for measuring the time spent at each function and how many times each function is executed. Let’s start with an example of cProfile.
Here is a Python script solving a linear system with the conjugate gradient method. Details of the calculation can be found in my other article. To run this Python script, we can simply do python conjugate_method_cprofile.py.
To profile with cProfile, run the following code in your terminal and save results to p0.prof.
python -m cProfile -o p0.prof conjugate_method.py
Then we can use snakeviz to visualize the results.
conda install snakeviz snakeviz p0.prof
Here is what we get from snakeviz, which shows the name of the functions and time spent in each function. For example, in this example, our program conjugate_method.py takes most of the time, and calculating whether our matrix is symmetric positive definite, which includes calculating eigenvalues, takes some time as well.
The other profiling technique I use quite often is line profiling. Line profiling gives us information about the execution time for each line of our code. This is especially helpful when we have a specific function to dig into. To use line profiler, first we need to add a decorator @profile in front of our function in the Python script. See line 8 in this example:
Then we can run the following code to do the line profiling:
conda install line_profilerkernprof -l conjugate_method_lineprofile.pypython -m line_profiler conjugate_method_lineprofile.py.lprof
Results show the time spent on each line of our function. Here we can see most of the time spent on lines 19, 21, 23, and 10. If we want to improve our performance, we need to think of ways to optimize those lines.
These are my two favorite tools for profiling Python code. In the examples, I used them from the terminal, but you can also use them as magic in Jupyter Notebooks. See this video for details. There are other profiling tools you can use. For example, you can simply use timeit to get the time spent on the entire function. You can also profile memory usage. Hope you enjoy playing with profiling! | [
{
"code": null,
"e": 356,
"s": 172,
"text": "Profiling helps us identify bottlenecks and optimize performance in our code. If our code runs slowly, we can identify where our code is slow and then make corresponding improvements."
},
{
"code": null,
"e": 433,
"s": 356,
"text": "He... |
How to Make Stunning Interactive Maps with Python and Folium in Minutes | by Dario Radečić | Towards Data Science | Data visualization can be tricky to do right. If you have the design skills of a domestic turkey, this article might save the day.
Folium is a great library that does most of the heavy lifting for you. You only need to bring in the data. Today you’ll make your first interactive map, showing historical earthquakes near Fiji.
You’ll see how easy Folium is to use and understand through a lot of hands-on examples. This article alone will serve you as an excellent basis for more advanced visualizations.
Today you’ll learn how to:
Make a basic map with Folium
Change map type
Add and style markers
Add popups
To make any visualization with Folium, you’ll first have to install the library. Execute this line from the terminal:
pip install folium
With regards to the dataset, you’ll need something with geolocations (latitude and longitude). This dataset is a perfect candidate — it contains historical earthquake data near Fiji. Here’s how to load it with Python:
The first couple of rows look like this:
Just what you need — an earthquake dataset with geolocations and corresponding magnitudes. That’s all you need to make your first Folium map. Here’s the code:
Values for the location parameter were chosen after a quick Google search. Parameters width and height are optional – so don’t use them if you don’t want to.
Here’s how your first map looks like:
It’s okay, but it looks a bit boring. Let’s see how to change the map type next.
Folium comes with a couple of built-in tilesets. The default one looks horrible at sea, so let’s change it. You can pass any of the following to the tiles keyword:
OpenStreetMap
Mapbox Bright
Mapbox Control Room
Stamen Terrain
Stamen Toner
Stamen Watercolor
CartoDB positron
CartoDB dark_matter
There are others, but they require an API key. That’s a bit out of the scope for today. Let’s see how Stamen Terrain looks like:
Better — at least at sea.
The map still doesn’t display any earthquake data. Let’s change that next.
You’ll need to write a loop to add markers. A goal is to iterate through the dataset and add a marker for every latitude and longitude pair.
Sounds easy enough, so let’s do it:
Here are the results:
These look awful. I’m not a fan of opaque blue markers and hope you aren’t either.
What if you want to color the markers based on the magnitude? Here’s an idea:
If a magnitude is 5 or below, make the marker yellow and almost fully transparent (a lot of smaller earthquakes)
If a magnitude is above 5, make the marker read and 100% opaque (not so many of these)
Let’s declare a function called generate_color() that returns outline color, fill color, outline opacity, and fill opacity based on the magnitude.
Everything else stays roughly the same, with some minor changes in the loop. You can also see how to change the size of the marker. It’s specified with the radius parameter:
Here’s the corresponding map:
Now we’re getting somewhere! I’m a complete idiot when it comes to combining two or (god forbid) more colors. I’m sure you can do a better job here.
There’s still one problem — the map isn’t interactive. Sure, you can zoom and drag, but nothing happens when you click on a marker. Popups can change that.
Let’s say you want to see earthquake magnitude and depth each time you click on a marker. One way to approach this is by declaring a function that returns HTML code showing both.
The generate_popup() function does just that. It also bolds the keywords:
Here’s the corresponding map:
That’s all you should know about making basic maps. There are more advanced things you can do, but this is enough to get you started.
The Folium library isn’t the only option for making maps. You can do mostly the same things with Plotly, which is a more “complete” data visualization library.
Which one do you prefer? Folium or Plotly? Let me know in the comment section.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. | [
{
"code": null,
"e": 303,
"s": 172,
"text": "Data visualization can be tricky to do right. If you have the design skills of a domestic turkey, this article might save the day."
},
{
"code": null,
"e": 498,
"s": 303,
"text": "Folium is a great library that does most of the heavy l... |
Node.js process.memoryUsage() Method - GeeksforGeeks | 20 May, 2021
The process.memoryUsage() method is an inbuilt method of the process module that provides information about the current processes or runtime of a Node.js program. The memory usage method returns an object describing the memory usage in bytes of the Node.js process.
Syntax:
process.memoryUsage()
Parameters: This method does not accept any parameter:
Return Value: This method returns an object with the description of the memory usage.
Below examples illustrate the use of process.memoryUsage() method in Node.js.
Example 1:
index.js
// Requiring modulevar process = require('process') // Prints the output as an objectconsole.log(process.memoryUsage())
Run the index.js file using the following command:
node index.js
Output:
{
rss: 23851008,
heapTotal: 4907008,
heapUsed: 2905912,
external: 951886,
arrayBuffers: 17574
}
Example 2:
index.js
// Requiring modulevar process = require('process') // An example displaying the respective memory// usages in megabytes(MB)for (const [key,value] of Object.entries(process.memoryUsage())){ console.log(`Memory usage by ${key}, ${value/1000000}MB `)}
Run the index.js file using the following command:
node index.js
Output:
Memory usage by rss, 23.87968MB
Memory usage by heapTotal, 4.907008MB
Memory usage by heapUsed, 2.907088MB
Memory usage by external, 0.951886MB
Memory usage by arrayBuffers, 0.017574MB
Reference: https://nodejs.org/api/process.html#process_process_memoryusage
Node.js-Methods
Node.js-process-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
Mongoose find() Function
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24531,
"s": 24503,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 24797,
"s": 24531,
"text": "The process.memoryUsage() method is an inbuilt method of the process module that provides information about the current processes or runtime of a Node.js program. ... |
C# Linq TakeWhile() Method | Get elements as long as the condition is true in a sequence using the TakeWhile() method.
The following is our list with strings.
IList<string> str = new List<string>(){ "Car", "Bus", "Truck", "Airplane"};
Now, let’s say we need the strings whose length is less than 4. For that, use Lambda Expressions and add it as a condition in the TakeWhile() method.
str.TakeWhile(a => a.Length < 4);
Here is the example that displays elements until the condition is trie.
Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
IList<string> str = new List<string>(){ "Car", "Bus", "Truck", "Airplane"};
var res = str.TakeWhile(a => a.Length < 4);
foreach(var arr in res)
Console.WriteLine(arr);
}
}
Car
Bus | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "Get elements as long as the condition is true in a sequence using the TakeWhile() method."
},
{
"code": null,
"e": 1192,
"s": 1152,
"text": "The following is our list with strings."
},
{
"code": null,
"e": 1268,
"s": ... |
Maximum sum difference | Practice | GeeksforGeeks | Given a number N. We have to find maximum sum of all permutations of numbers from 1 to N. The maximum sum will be sum of absolute difference of adjacent elements in array.
Example 1:
Input: N = 2
Output: 1
Explaination: Permutations of 2 are:
{1, 2} = 1, {2, 1} = 1.
Example 2:
Input: N = 3
Output: 3
Explaintation: Permutations of size 3 are:
{1, 2, 3} = 1 + 1, {1, 3, 2} = 2 + 1
{2, 1, 3} = 1 + 2, {2, 3, 1} = 1 + 2
{3, 1, 2} = 2 + 1, {3, 2, 1} = 1 + 1
Your Task:
You do not need to read input or print anything. Your task is to complete the function maxSum() which takes N as input parameter and returns the maximum possible difference sum from all permutations of N numbers.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
2 ≤ N ≤ 1000
0
himanshubarak123 months ago
class Solution{
public:
int maxSum(int n){
// code here
if(n==1) return 1;
return ((n*(n-1))/2 +n/2 -1);
}
};
To understand the logic check out this post.
https://www.geeksforgeeks.org/maximum-sum-difference-adjacent-elements/
-2
vermasumit9236 months ago
class Solution{public: int maxSum(int N) { int sum = (N*(N-1))/2; int arr[1001]; arr[1] = 1; int k = 0; for(int i = 2; i <= 1000; i += 2) { arr[i] = k; arr[i+1] = k; k++; } sum += arr[N]; return sum; }};
0
ANKIT SINHA9 months ago
ANKIT SINHA
https://uploads.disquscdn.c...
0
Tulsi Dey1 year ago
Tulsi Dey
Solution in Java:time complexity : O(1)space complexity: O(1)Execution time : 0.28
class Solution{ static int maxSum(int N){ if(N == 1) return 1; return N*(N+1)/2 + N/2 - (N+1); }}
0
Tulsi Dey1 year ago
Tulsi Dey
Solution in C++:time complexity : O(1)space complexity: O(1)Execution time : 0.02
class Solution{public: int maxSum(int N){ if(N == 1) return 1; return N*(N+1)/2 + N/2 - (N+1); }};
0
Jihye Sofia Seo5 years ago
Jihye Sofia Seo
Input:
189
Its Correct output is:
17859
And Your Code's Output is:
17766
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": 410,
"s": 238,
"text": "Given a number N. We have to find maximum sum of all permutations of numbers from 1 to N. The maximum sum will be sum of absolute difference of adjacent elements in array."
},
{
"code": null,
"e": 421,
"s": 410,
"text": "Example 1:"
... |
Quick Left Rotation | Practice | GeeksforGeeks | Given an array arr[] of size N and an integer K, the task is to left rotate the array K indexes
Example 1:
Input: N = 7, K = 2
arr[] = {1, 2, 3, 4, 5, 6, 7}
Output: 3 4 5 6 7 1 2
Explanation: Rotation of the above
array by 2 will make the output array .
Example 2:
Input: N = 6, K = 12
arr[] = {1, 2, 3, 4, 5, 6}
Output: 1 2 3 4 5 6
Your Task:
This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function leftRotate() that takes array arr, integer K and integer N as parameters and rotate the given array by d value.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ N ≤ 105
0
mayank20211 day ago
C++ : 0.26/1.54void leftRotate(int arr[], int k, int n) { k=k%n; reverse(arr, arr+k); reverse(arr+k, arr+n); reverse(arr, arr+n);}
0
arvind16yadav3 weeks ago
/*JAVA CODE (Time : 3 out of 4.7)*/
void leftRotate(long arr[], int k,int n) { int mod_k = k % n; long[] brr = new long[mod_k]; for(int i=0; i<mod_k; i++){ brr[i] = arr[i]; } for(int i=0; i<n-mod_k; i++){ arr[i] = arr[i+mod_k]; } for(int i=0; i<mod_k; i++){ arr[n-mod_k+i] = brr[i]; } }
0
codewithshoaib191 month ago
public static void leftRotate(long arr[], int k,int n) { if (k < 0) { k = k + n; } k = k % n; reverse(arr, 0, k - 1); reverse(arr, k, n - 1); reverse(arr, 0, n - 1); } public static void reverse(long[] arr, int s, int e) { while (s <= e) { swap(arr, s, e); s++; e--; } }
public static void swap(long[] arr, int s, int e) { long temp = arr[s]; arr[s] = arr[e]; arr[e] = temp; }
0
pankajkumarravi6 months ago
static void leftRotate(long arr[], int k, int n) { long temp[] = new long[n]; int mod = k % n; for(int i = 0 ; i < n; i++){ temp[i] = arr[(i+mod) % n]; } for(int i = 0 ; i < n ; i++){ arr[i]= temp[i]; }}
0
raj2000ath7 months ago
error
: not compiling.
A = []
B = []
for i in range (0,k):
A.append(arr[i])
for i in range (k,n):
B.append(arr[i])
A.reverse()
B.reverse()
list(A)
list(B)
for i in range(0,len(B)):
A.append(B[i])
arr.clear()
arr.append(A)
reversed(arr)
0
raj2000ath7 months ago
Why is this not compiling:??
class Solution: def leftRotate(self, arr, k, n): # Your code goes here arr11 = [] i = 0 ri = k while ri < n: arr11[i] = arr[ri] i += 1 ri += 1 ri = 0 while ri < k: arr11[i] = arr[ri] i += 1 ri += 1 return arr11
-1
Chandan kumar Tripathi9 months ago
Chandan kumar Tripathi
void reverse(int arr[] , int low , int high) { while(low<high) {="" swap(arr[high]="" ,="" arr[low]);="" low++;="" high--;="" }="" }="" void="" leftrotate(int="" arr[],="" int="" k,="" int="" n)="" {="" your="" code="" goes="" here="" k="k%n;" reverse(arr="" ,="" 0="" ,="" k-1);="" reverse(arr="" ,k="" ,="" n-1);="" reverse(arr="" ,="" 0="" ,="" n-1);="" }<="" code="">
-1
Chandan kumar Tripathi9 months ago
Chandan kumar Tripathi
void reverse(int arr[] , int low , int high) { while(low<high) {="" swap(arr[high]="" ,="" arr[low]);="" low++;="" high--;="" }="" }="" void="" leftrotate(int="" arr[],="" int="" k,="" int="" n)="" {="" your="" code="" goes="" here="" k="k%n;" reverse(arr="" ,="" 0="" ,="" k-1);="" reverse(arr="" ,k="" ,="" n-1);="" reverse(arr="" ,="" 0="" ,="" n-1);="" }="">
-1
Chandan kumar Tripathi9 months ago
Chandan kumar Tripathi
void reverse(int arr[] , int low , int high) { while(low<high) {="" swap(arr[high]="" ,="" arr[low]);="" low++;="" high--;="" }="" }="" void="" leftrotate(int="" arr[],="" int="" k,="" int="" n)="" {="" your="" code="" goes="" here="" k="k%n;" reverse(arr="" ,="" 0="" ,="" k-1);="" reverse(arr="" ,k="" ,="" n-1);="" reverse(arr="" ,="" 0="" ,="" n-1);="" }<="" i="">
+1
Debojyoti Sinha9 months ago
Debojyoti Sinha
Problem Solved Successfully ✅Total Time Taken: 0.3/1.5
class Solution{ public: void leftRotate(int arr[], int K, int N) { rotate(arr, arr + (K % N), arr + N); }};
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": 334,
"s": 238,
"text": "Given an array arr[] of size N and an integer K, the task is to left rotate the array K indexes"
},
{
"code": null,
"e": 345,
"s": 334,
"text": "Example 1:"
},
{
"code": null,
"e": 493,
"s": 345,
"text": "Input: N =... |
GATE | GATE CS 2021 | Set 2 | Question 45 - GeeksforGeeks | 13 Aug, 2021
Consider the following ANSI C program:
#include < stdio.h >
#include < stdlib.h >
struct Node{
int value;
struct Node *next;};
int main( ) {
struct Node *boxE, *head, *boxN; int index=0;
boxE=head= (struct Node *) malloc(sizeof(struct Node));
head → value = index;
for (index =1; index<=3; index++){
boxN = (struct Node *) malloc (sizeof(struct Node));
boxE → next = boxN;
boxN → value = index;
boxE = boxN; }
for (index=0; index<=3; index++) {
printf(“Value at index %d is %d\n”, index, head → value);
head = head → next;
printf(“Value at index %d is %d\n”, index+1, head → value); } }
Which one of the following statements below is correct about the program?(A) Upon execution, the program creates a linked-list of five nodes(B) Upon execution, the program goes into an infinite loop(C) It has a missing return which will be reported as an error by the compiler(D) It dereferences an uninitialized pointer that may result in a run-time errorAnswer: (D)Explanation:
When you debug loop 1 you will get the linked list of size 4
In the second loop value will be printed 0 0 1 1 2 2 3 3 after that head will be pointing to some random location and result in run-time error. Correct Option (D)
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQs 2021 (Set1 and Set2) with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0046:14 / 54:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=I43aLH5qEBc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE CS 2008 | Question 69
GATE | GATE CS 2018 | Question 45
GATE | GATE CS 2019 | Question 50
GATE | GATE CS 1997 | Question 25
GATE | GATE CS 2010 | Question 33
GATE | GATE CS 2011 | Question 43
GATE | GATE CS 2020 | Question 16
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2015 (Set 3) | Question 46 | [
{
"code": null,
"e": 24075,
"s": 24047,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 24114,
"s": 24075,
"text": "Consider the following ANSI C program:"
},
{
"code": null,
"e": 24739,
"s": 24114,
"text": "#include < stdio.h >\n#include < stdlib.h >\nstruct... |
How to get the current time in millisecond using JavaScript? | To get the current time in a millisecond, use the date getMilliseconds() method. JavaScript date getMilliseconds() method returns the milliseconds in the specified date according to local time. The value returned by getMilliseconds() is a number between 0 and 999.
You can try to run the following code to get the current time in milliseconds −
<html>
<head>
<title>JavaScript getMilliseconds() Method</title>
</head>
<body>
<script>
var dt = new Date( );
document.write("getMilliseconds() : " + dt.getMilliseconds() );
</script>
</body>
</html> | [
{
"code": null,
"e": 1327,
"s": 1062,
"text": "To get the current time in a millisecond, use the date getMilliseconds() method. JavaScript date getMilliseconds() method returns the milliseconds in the specified date according to local time. The value returned by getMilliseconds() is a number between... |
C Program for FCFS Scheduling | We are given with the n number of processes i.e. P1, P2, P3,.......,Pn and their corresponding burst times. The task is to find the average waiting time and average turnaround time using FCFS CPU Scheduling algorithm.
What is Waiting Time and Turnaround Time?
Turnaround Time is the time interval between the submission of a process and its completion.Turnaround Time = completion of a process – submission of a process
Turnaround Time is the time interval between the submission of a process and its completion.
Turnaround Time = completion of a process – submission of a process
Waiting Time is the difference between turnaround time and burst timeWaiting Time = turnaround time – burst time
Waiting Time is the difference between turnaround time and burst time
Waiting Time = turnaround time – burst time
What is FCFS Scheduling?
First Come, First Served (FCFS) also known as First In, First Out(FIFO) is the CPU scheduling algorithm in which the CPU is allocated to the processes in the order they are queued in the ready queue.
FCFS follows non-preemptive scheduling which mean once the CPU is allocated to a process it does not leave the CPU until the process will not get terminated or may get halted due to some I/O interrupt.
Let’s say, there are four processes arriving in the sequence as P2, P3, P1 with their corresponding execution time as shown in the table below. Also, taking their arrival time to be 0.
Gantt chart showing the waiting time of processes P1, P2 and P3 in the system
As shown above,
The waiting time of process P2 is 0
The waiting time of process P3 is 3
The waiting time of process P1 is 6
Average time = (0 + 3 + 6) / 3 = 3 msec.
As we have taken arrival time to be 0 therefore turn around time and completion time will be same.
Input-: processes = P1, P2, P3
Burst time = 5, 8, 12
Output-:
Processes Burst Waiting Turn around
1 5 0 5
2 8 5 13
3 12 13 25
Average Waiting time = 6.000000
Average turn around time = 14.333333
Start Step 1-> In function int waitingtime(int proc[], int n, int burst_time[], int wait_time[])
Set wait_time[0] = 0
Loop For i = 1 and i < n and i++
Set wait_time[i] = burst_time[i-1] + wait_time[i-1]
End For
Step 2-> In function int turnaroundtime( int proc[], int n, int burst_time[], int wait_time[], int tat[])
Loop For i = 0 and i < n and i++
Set tat[i] = burst_time[i] + wait_time[i]
End For
Step 3-> In function int avgtime( int proc[], int n, int burst_time[])
Declare and initialize wait_time[n], tat[n], total_wt = 0, total_tat = 0;
Call waitingtime(proc, n, burst_time, wait_time)
Call turnaroundtime(proc, n, burst_time, wait_time, tat)
Loop For i=0 and i<n and i++
Set total_wt = total_wt + wait_time[i]
Set total_tat = total_tat + tat[i]
Print process number, burstime wait time and turnaround time
End For
Print "Average waiting time =i.e. total_wt / n
Print "Average turn around time = i.e. total_tat / n
Step 4-> In int main()
Declare the input int proc[] = { 1, 2, 3}
Declare and initialize n = sizeof proc / sizeof proc[0]
Declare and initialize burst_time[] = {10, 5, 8}
Call avgtime(proc, n, burst_time)
Stop
Live Demo
#include <stdio.h>
// Function to find the waiting time for all processes
int waitingtime(int proc[], int n,
int burst_time[], int wait_time[]) {
// waiting time for first process is 0
wait_time[0] = 0;
// calculating waiting time
for (int i = 1; i < n ; i++ )
wait_time[i] = burst_time[i-1] + wait_time[i-1] ;
return 0;
}
// Function to calculate turn around time
int turnaroundtime( int proc[], int n,
int burst_time[], int wait_time[], int tat[]) {
// calculating turnaround time by adding
// burst_time[i] + wait_time[i]
int i;
for ( i = 0; i < n ; i++)
tat[i] = burst_time[i] + wait_time[i];
return 0;
}
//Function to calculate average time
int avgtime( int proc[], int n, int burst_time[]) {
int wait_time[n], tat[n], total_wt = 0, total_tat = 0;
int i;
//Function to find waiting time of all processes
waitingtime(proc, n, burst_time, wait_time);
//Function to find turn around time for all processes
turnaroundtime(proc, n, burst_time, wait_time, tat);
//Display processes along with all details
printf("Processes Burst Waiting Turn around \n");
// Calculate total waiting time and total turn
// around time
for ( i=0; i<n; i++) {
total_wt = total_wt + wait_time[i];
total_tat = total_tat + tat[i];
printf(" %d\t %d\t\t %d \t%d\n", i+1, burst_time[i], wait_time[i], tat[i]);
}
printf("Average waiting time = %f\n", (float)total_wt / (float)n);
printf("Average turn around time = %f\n", (float)total_tat / (float)n);
return 0;
}
// main function
int main() {
//process id's
int proc[] = { 1, 2, 3};
int n = sizeof proc / sizeof proc[0];
//Burst time of all processes
int burst_time[] = {5, 8, 12};
avgtime(proc, n, burst_time);
return 0;
}
Processes Burst Waiting Turn around
1 5 0 5
2 8 5 13
3 12 13 25
Average Waiting time = 6.000000
Average turn around time = 14.333333 | [
{
"code": null,
"e": 1280,
"s": 1062,
"text": "We are given with the n number of processes i.e. P1, P2, P3,.......,Pn and their corresponding burst times. The task is to find the average waiting time and average turnaround time using FCFS CPU Scheduling algorithm."
},
{
"code": null,
"e"... |
Express.js – express.raw() function | express.raw() is a built-in middleware function in Express. It parses the incoming requests into a buffer and it is based upon the body-parser. This method returns the middleware that parses all JSON bodies as buffer and only looks at the requests where the content-type header matches the type option.
express.raw([options])
Following are the different options available with this method
options –inflate – This enables or disables the handling of the deflated or compressed bodies. Default: truelimit – Controls the maximum size of the request body.type – Determines the media type for the middleware that will be parsed.
options –
inflate – This enables or disables the handling of the deflated or compressed bodies. Default: true
inflate – This enables or disables the handling of the deflated or compressed bodies. Default: true
limit – Controls the maximum size of the request body.
limit – Controls the maximum size of the request body.
type – Determines the media type for the middleware that will be parsed.
type – Determines the media type for the middleware that will be parsed.
Create a file with the name "expressRaw.js" and copy the following code snippet. After creating the file, use the command "node expressRaw.js" to run this code.
// express.raw() Demo Example
// Importing the express module
var express = require('express');
// Initializing the express and port number
var app = express();
var PORT = 3000;
// Using the express.raw middleware
app.use(express.raw());
// Reading content-type
app.post('/', function (req, res) {
console.log(req.body)
res.end();
})
// Listening to the port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Before hitting the API endpoint, set the following two properties −
Set the content-type as application/octet-stream in headers.
Set the content-type as application/octet-stream in headers.
Pass the following body in the POST request – {"name": "TutorialsPoint"}
Pass the following body in the POST request – {"name": "TutorialsPoint"}
C:\home\node>> node expressRaw.js
Server listening on PORT 3000
Let’s take a look at one more example.
// express.raw() Demo Example
// Importing the express module
var express = require('express');
// Initializing the express and port number
var app = express();
var PORT = 3000;
// Commenting the express.raw middleware
// app.use(express.raw());
// Reading content-type
app.post('/', function (req, res) {
console.log(req.body)
res.end();
})
// Listening to the port
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Before hitting the API endpoint, set the following two properties −
Set the content-type as application/octet-stream in headers.
Set the content-type as application/octet-stream in headers.
Pass the following body in the POST request – {"name": "TutorialsPoint"}
Pass the following body in the POST request – {"name": "TutorialsPoint"}
C:\home\node>> node expressRaw.js
Server listening on PORT 3000
undefined | [
{
"code": null,
"e": 1365,
"s": 1062,
"text": "express.raw() is a built-in middleware function in Express. It parses the incoming requests into a buffer and it is based upon the body-parser. This method returns the middleware that parses all JSON bodies as buffer and only looks at the requests where... |
How to change the background color of a tkinter Canvas dynamically? | The Canvas widget is one of the most useful widgets in Tkinter. It has various functionalities and features to help developers customize the application according to their need. The Canvas widget is used to display the graphics in an application. You can create different types of shapes and draw objects using the Canvas widget.
To change the background color of the Canvas widget, you can use the configure() method. Here, you can specify the background color of the Canvas widget which you want to change explicitly.
In the following example, we have created a canvas widget with a default background color "skyblue", which can be changed after its creation.
# Import the required libraries
from tkinter import *
# Create an instance of tkinter frame
win= Tk()
# Define the size of the window
win.geometry("700x300")
# Function to change the color of the canvas
def change_color():
canvas.configure(bg='blue')
# Create a canvas widget
canvas= Canvas(win, bg='skyblue')
canvas.pack()
# Create a button
button=Button(win, text= "Change Color", font=('Helvetica 10 bold'), command=change_color)
button.pack()
win.mainloop()
It will produce the following output −
Clicking the "Change Color" button would change the background color of the canvas. | [
{
"code": null,
"e": 1392,
"s": 1062,
"text": "The Canvas widget is one of the most useful widgets in Tkinter. It has various functionalities and features to help developers customize the application according to their need. The Canvas widget is used to display the graphics in an application. You ca... |
What is isErrorPage attribute in JSP? | The errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs. The value of the errorPage attribute is a relative URL.
The following directive displays MyErrorPage.jsp when all uncaught exceptions are thrown −
<%@ page errorPage = "MyErrorPage.jsp" %>
The isErrorPage attribute indicates that the current JSP can be used as the error page for another JSP.
The value of isErrorPage is either true or false. The default value of the isErrorPage attribute is false.
For example, the handleError.jsp sets the isErrorPage option to true because it is supposed to handle errors −
<%@ page isErrorPage = "true" %> | [
{
"code": null,
"e": 1235,
"s": 1062,
"text": "The errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs. The value of the errorPage attribute is a relative URL."
},
{
"code": null,
"e": 1326,
"s": 1235,
"text": "The follo... |
How can bubble charts be created using Matplotlib? | Matplotlib library is built upon Numpy. It is a Python library that is used to visualize data. It is a tree-like hierarchical structure which consists of objects that makeup each of these plots. A ’Figure’ in Matplotlib can be understood as the outermost storage for a graph. This ‘Figure’ can contains multiple ‘Axes’ objects. ‘Axes’ object is NOT the plural form of ‘Axis’ in this case.
‘Axes’ can be understood as a part of ‘Figure’, a subplot. It can be used to manipulate every part of the graph inside it. A ‘Figure’ object in Matplotlib is a box that stores one or more ‘Axes’ objects. Under ‘Axes’ comes the tick marks, lines, legends, and text boxes in the hierarchy. Every object in the Matplotlib can be manipulated. Let us see an example
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(50)
y = np.random.rand(50)
z = np.random.rand(50)
colors = np.random.rand(50)
plt.scatter(x, y, s=z*2000,c=colors)
plt.title("Bubble chart")
plt.xlabel("x−axis")
plt.ylabel("Y−axis")
plt.show()
The required packages are imported and aliased.
The required packages are imported and aliased.
The ‘rand’ function present in ‘random’ class is used to generate data.
The ‘rand’ function present in ‘random’ class is used to generate data.
The ‘title’, x label, and y label of the plot is defined.
The ‘title’, x label, and y label of the plot is defined.
The ‘scatter’ function is called by passing the data.
The ‘scatter’ function is called by passing the data.
The show function is used to display the data on the console.
The show function is used to display the data on the console. | [
{
"code": null,
"e": 1451,
"s": 1062,
"text": "Matplotlib library is built upon Numpy. It is a Python library that is used to visualize data. It is a tree-like hierarchical structure which consists of objects that makeup each of these plots. A ’Figure’ in Matplotlib can be understood as the outermos... |
Tryit Editor v3.7 | CSS Grid Intro
Tryit: The gap shorthand property | [
{
"code": null,
"e": 24,
"s": 9,
"text": "CSS Grid Intro"
}
] |
Working with strings in Python: A cheat sheet | by Mahbubul Alam | Towards Data Science | Maybe you don’t want to be an NLP expert. But as a data scientist you will definitely have to deal with string objects; without exceptions. It may involve as simple as naming and renaming columns, looping through column names or editing other kinds of string objects present in the dataset.
Or maybe you are thinking to become an NLP expert. Either way, learning some basic string manipulation techniques will take you a long way to level up skills and make you comfortable working with text data.
There are some useful tools in Python standard library and other packages which are quite powerful. Using built-in tools and external libraries in I will cover the following in the article:
Built-in string methods
Counter module
Accessing elements
f-string literals
Regular expression
Let’s dive right in.
I’ll do a warm-up first.
You probably applied built-in len() function for counting items in a list, set, tuple or dictionary. You can use the same to check the total length of a string.
len('hello')>> 5
A string can also be cast into a list by using the list() constructor.
list('hello!')>> ['h', 'e', 'l', 'l', 'o', '!']
Concatenating two strings works just like how a normal numeric addition works in a math function.
first_string = 'hello'second_string = 'world'new_string = first_string + second_string>> 'hello world'
Similarly, you can get copies of a string just by multiplying as many times!
string = 'hello'(string + ' ') *5>> 'hello hello hello hello hello '
Like everything else, strings are objects in Python. Naturally, it comes with built-in methods which you can discover by hitting .tab key after the string:
So what exactly can you do with string methods? Some basic functionalities include converting a string to upper case or lower case, capitalization etc. Some examples are below:
# make uppercase'hello'.upper()>> 'HELLO'# make lowercase'HELLO'.lower()>> 'hello'# capitalize'hello'.capitalize()>> 'Hello'# title'hello world'.title()>> 'Hello World'
Besides basic methods, you can also call a few very useful methods. For example, you can split a string (let’s say a sentence) using a separator of your choice (e.g. a letter).
# split a word 'hello'.split(sep = 'e')>> ['h', 'llo']
The most useful is to split a sentence into a list of individual words with a space (‘ ’) separator.
sent = 'hello world'sent.split(sep = ' ')>> ['hello', 'world']
There is also a way to put the elements of a string in reverse order.
# reverse a strings = 'hello's[::-1]>> 'olleh'
If you find reversing a string not so much useful for your work, getting rid of unwanted things in a string certainly is. You can just strip() whatever you want to get rid of from a string.
# strip part of a string'hi there'.strip('hi ')>> 'there'
Replacing words or characters can also come in handy.
# replace a character'hello'.replace('l', 'L')>> 'heLLo'# replace a word'hello world'.replace('world', 'WORLD')>> 'hello WORLD'
By using join() method you can join a list of characters or words into a longer string object.
# join a list of letterss = ['h', 'e', 'l', 'l', 'o']''.join(s)>> 'hello'# join a list of words w = ['hello', 'world']'-'.join(w)>> 'hello-world'
Before closing out on string methods I just want to emphasize that if you work with Pythonpandas library, you will find built-in string methods similarly useful. If you just use.str. on a pandas object (i.e. strings), you can access all those methods.
The next important topic is counting — from counting characters to counting words and more.
The built-in method for counting is .count() which is applied to an object and you specify what you want to count as an argument. Just remember that it is case-sensitive.
# counting characterssent = 'His name is Abdul. Abdul is a good boy. Boy o boy'sent.count('a')>> 2# counting the occurance of an wordsent.count('name')>> 1
Python also comes with a Counter module with its collections library. It can count the frequency of each element in a string and returns a dictionary object.
# count ALL characters in a stringfrom collections import CounterCounter('aaaaabbbbbbxxxxxx')>> Counter({'a': 5, 'b': 6, 'x': 6})
With an additional line of code, Counter can also split the words and show word frequencies.
# counting ALL words in a sentencesent = 'His name is Abdul. Abdul is a good boy, boy o boy'word_lis= sent.split(' ')Counter(word_list)>> Counter({'His': 1, 'name': 1, 'is': 2, 'Abdul.': 1, 'Abdul': 1, 'a': 1, 'good': 1, 'boy,': 1, 'boy': 2, 'o': 1})
As a best practice, you should remove any punctuations in the string, otherwise, it can create some troubles down the line.
Associated .most_common() method returns tuples of items occurring in the highest frequencies.
Counter(word_list).most_common(3)>> [('is', 2), ('boy', 2), ('His', 1)]
Accessing individual items by index or accessing index by items is quite useful.
To access the index of a character/word:
'hello how are you'.find('how')>> 6
Or to access a character/word by index:
s = 'hi there's[3]>> 't'
Slicing a string works in a similar fashion as you’d do for a list objects.
s = 'hi there's[0:4]>> 'hi t'
You can format string in multiple ways in Python. Prior to Python 3.6 most people would use %-formatting or .format() but f-strings have made it quite easier — easy to use and easy to read. Here’s one example:
name = 'Anna'age = 23print(f"my name is {name} and I am {age} years old")>> my name is Anna and I am 23 years old
For numeric variables, you can specify the precision of the values in the format -> value:width.precision
# f string numbersdiv = 11/3print(f'the result of the division is {div:2.3f}') >> the result of the division is 3.667
The regular expression reis a very powerful library in Python and so much you can do with it especially for searching for patterns in a dataset. Below is a small sample of its capabilities.
If you wish to search for a matching pattern of text:
import retext = 'hello my phone number is (000)-111-2222'pattern = 'phone're.search(pattern, text)>> <re.Match object; span=(9, 14), match='phone'>
In the output, span tells the index position of the match (starting at index 6, ending at 8 in this example).
You can also search for number patterns in a specific format that you think is most likely present.
text = 'my zipcode is 22202'pattern = r'\d\d\d\d\d're.search(pattern, text)>> <re.Match object; span=(14, 19), match='22202'>
And finally, there is the so-called “wildcard”, represented by the .(dot) metacharacter.
# input texttext = 'the dog and the hog sat in the fog'# regex searchre.findall(r'.og', text)>> ['dog', 'hog', 'fog']
To summarise everything that I’ve presented in this article:
built-in string methods for basic functionalities such as changing cases, splitting, joining, replacing etc.
counting string elements using built-in .count() method or by using the Counter module
accessing string patterns and index values
the use of f-string literals for string formating
applying regular expressions re module for pattern search.
I left many other methods and functionalities, but I hope this gives a good start to build a cheat sheet to work with string objects.
If you have comments feel free to write them down below or connect with me via Medium, Twitter or LinkedIn. | [
{
"code": null,
"e": 462,
"s": 171,
"text": "Maybe you don’t want to be an NLP expert. But as a data scientist you will definitely have to deal with string objects; without exceptions. It may involve as simple as naming and renaming columns, looping through column names or editing other kinds of str... |
How to resize a navigation bar on scroll with CSS and JavaScript?
| Following is the code to resize a navigation bar on scroll using CSS and JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
margin: 0px;
margin-top: 60px;
padding: 0px;
}
nav {
position: fixed;
top: 0px;
width: 100%;
background-color: rgb(39, 39, 39);
overflow: auto;
height: auto;
transition: 0.5s;
padding: 50px 10px;
}
.links {
display: inline-block;
text-align: center;
padding: 14px;
color: rgb(178, 137, 253);
text-decoration: none;
font-size: 17px;
}
.links:hover {
background-color: rgb(100, 100, 100);
}
.selected {
background-color: rgb(0, 18, 43);
}
.sample-content {
height: 150vh;
}
.company-logo {
font-size: 50px;
color: white;
position: absolute;
right: 30px;
transition: 0.3s;
}
</style>
</head>
<body>
<nav>
<a class="company-logo">€</a>
<a class="links selected" href="#">Home</a>
<a class="links" href="#"> Login</a>
<a class="links" href="#"> Register</a>
<a class="links" href="#"> Contact Us</a>
<a class="links" href="#">More Info</a>
</nav>
<div class="sample-content">
<h1>Here are some headers</h1>
<h2>Here are some headers</h2>
<h3>Here are some headers</h3>
<h4>Here are some headers</h4>
<h1>Here are some headers</h1>
<h2>Here are some headers</h2>
<h3>Here are some headers</h3>
<h4>Here are some headers</h4>
</div>
<script>
window.onscroll = scrollShowNav;
function scrollShowNav() {
if (
document.body.scrollTop > 20 ||
document.documentElement.scrollTop > 20
)
{
document.getElementsByTagName("nav")[0].style.padding = "10px 10px";
document.querySelector(".company-logo").style.fontSize = "20px";
} else {
document.getElementsByTagName("nav")[0].style.padding = "40px 50px";
document.querySelector(".company-logo").style.fontSize = "50px";
}
}
</script>
</body>
</html>
The above code will produce the following output −
On scrolling the page the nav will shrink as follows − | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "Following is the code to resize a navigation bar on scroll using CSS and JavaScript −"
},
{
"code": null,
"e": 1159,
"s": 1148,
"text": " Live Demo"
},
{
"code": null,
"e": 3099,
"s": 1159,
"text": "<!DOCTYPE html... |
C++ Program for Dijkstra’s shortest path algorithm? | Dijkstra's algorithm (or Dijkstra's Shortest Path First algorithm, SPF algorithm) is an algorithm for finding the shortest paths between nodes in a graph, which may represent, for example, road networks. The algorithm creates a tree of shortest paths from the starting vertex, the source, to all other points in the graph.
Dijkstra’s algorithm finds a shortest path tree from a single source node, by building a set of nodes that have minimum distance from the source.
The graph has the following−
vertices, or nodes, denoted in the algorithm by v or u.
vertices, or nodes, denoted in the algorithm by v or u.
weighted edges that connect two nodes: (u,v) denotes an edge, and w(u,v)denotes its weight. In the diagram on the right, the weight for each edge is written in gray.
weighted edges that connect two nodes: (u,v) denotes an edge, and w(u,v)denotes its weight. In the diagram on the right, the weight for each edge is written in gray.
Set all vertices distances = infinity except for the source vertex, set the source distance = 0.
Push the source vertex in a min-priority queue in the form (distance , vertex), as the comparison in the min-priority queue will be according to vertices distances.
Pop the vertex with the minimum distance from the priority queue (at first the popped vertex = source).
Update the distances of the connected vertices to the popped vertex in case of "current vertex distance + edge weight < next vertex distance", then push the vertex
with the new distance to the priority queue.
If the popped vertex is visited before, just continue without using it.
Apply the same algorithm again until the priority queue is empty.
Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph. Given G[][] matrix of graph weight, n no of vertex in graph, u starting node.
G[max][max]={{0,1,0,3,10},
{1,0,5,0,0},
{0,5,0,2,1},
{3,0,2,0,6},
{10,0,1,6,0}}
n=5
u=0
Distance of node1=1
Path=1<-0
Distance of node2=5
Path=2<-3<-0
Distance of node3=3
Path=3<-0
Distance of node4=6
Path=4<-2<-3<-0
Explanation
Create cost matrix C[ ][ ] from adjacency matrix adj[ ][ ]. C[i][j] is the cost of going from vertex i to vertex j. If there is no edge between vertices i and j then C[i][j] is infinity.
Create cost matrix C[ ][ ] from adjacency matrix adj[ ][ ]. C[i][j] is the cost of going from vertex i to vertex j. If there is no edge between vertices i and j then C[i][j] is infinity.
Array visited[ ] is initialized to zero.
Array visited[ ] is initialized to zero.
for(i=0;i<n;i++)
visited[i]=0;
If the vertex 0 is the source vertex then visited[0] is marked as 1.
If the vertex 0 is the source vertex then visited[0] is marked as 1.
Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1 from the source vertex 0.
Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1 from the source vertex 0.
for(i=1;i<n;i++)
distance[i]=cost[0][i];
Initially, distance of source vertex is taken as 0. i.e. distance[0]=0;
for(i=1;i<n;i++)
visited[i]=0;
Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark visited[w] as 1.
Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark visited[w] as 1.
Recalculate the shortest distance of remaining vertices from the source.
Recalculate the shortest distance of remaining vertices from the source.
Only, the vertices not marked as 1 in array visited[ ] should be considered for recalculation of distance. i.e. for each vertex v
Only, the vertices not marked as 1 in array visited[ ] should be considered for recalculation of distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v],
distance[w]+cost[w][v])
#include<iostream>
#include<stdio.h>
using namespace std;
#define INFINITY 9999
#define max 5
void dijkstra(int G[max][max],int n,int startnode);
int main() {
int G[max][max]={{0,1,0,3,10},{1,0,5,0,0},{0,5,0,2,1},{3,0,2,0,6},{10,0,1,6,0}};
int n=5;
int u=0;
dijkstra(G,n,u);
return 0;
}
void dijkstra(int G[max][max],int n,int startnode) {
int cost[max][max],distance[max],pred[max];
int visited[max],count,mindistance,nextnode,i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
for(i=0;i<n;i++) {
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1) {
mindistance=INFINITY;
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i]) {
mindistance=distance[i];
nextnode=i;
}
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i]) {
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}
for(i=0;i<n;i++)
if(i!=startnode) {
cout<<"\nDistance of node"<<i<<"="<<distance[i];
cout<<"\nPath="<<i;
j=i;
do {
j=pred[j];
cout<<"<-"<<j;
}while(j!=startnode);
}
} | [
{
"code": null,
"e": 1385,
"s": 1062,
"text": "Dijkstra's algorithm (or Dijkstra's Shortest Path First algorithm, SPF algorithm) is an algorithm for finding the shortest paths between nodes in a graph, which may represent, for example, road networks. The algorithm creates a tree of shortest paths fr... |
How to use AutoCompleteTextView in an Android App using Kotlin? | This example demonstrates how to use AutoCompleteTextView in an Android App using 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.
<?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:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<AutoCompleteTextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text2"
android:layout_marginTop="20dp"
android:hint="Enter fruit name"
android:textColor="@android:color/background_dark"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private val fruits = arrayOf("Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val autoTextView: AutoCompleteTextView = findViewById(R.id.text)
val adapter: ArrayAdapter<String> = ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, fruits)
autoTextView.threshold = 1
autoTextView.setAdapter(adapter)
}
}
Step 4 − 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="com.example.q11">
<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": 1152,
"s": 1062,
"text": "This example demonstrates how to use AutoCompleteTextView in an Android App using Kotlin."
},
{
"code": null,
"e": 1281,
"s": 1152,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all requi... |
Declare char arrays in C# | Declare a char array and set the size −
char[] arr = new char[5];
Now set the elements −
arr[0] = 'h';
arr[1] = 'a';
arr[2] = 'n';
arr[3] = 'k';
arr[4] = 's';
Let us see the complete code now to declare, initialize and display char arrays in C# −
Live Demo
using System;
public class Program {
public static void Main() {
char[] arr = new char[5];
arr[0] = 'h';
arr[1] = 'a';
arr[2] = 'n';
arr[3] = 'k';
arr[4] = 's';
Console.WriteLine("Displaying string elements...");
for (int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
}
}
}
Displaying string elements...
h
a
n
k
s | [
{
"code": null,
"e": 1102,
"s": 1062,
"text": "Declare a char array and set the size −"
},
{
"code": null,
"e": 1128,
"s": 1102,
"text": "char[] arr = new char[5];"
},
{
"code": null,
"e": 1151,
"s": 1128,
"text": "Now set the elements −"
},
{
"code": ... |
CSS Buttons - Quick Guide | A button on a web-page is the prime actor where a user clicks after selecting or entering the required inputs and submits the details to get required information. This tutorial focuses on ten main CSS libraries to make buttons awesome, namely −
bttn.css − bttn.css library provides a huge collection of simple styles for buttons. This library is completely free for both personal and commercial use. These buttons can be customized easily.
bttn.css − bttn.css library provides a huge collection of simple styles for buttons. This library is completely free for both personal and commercial use. These buttons can be customized easily.
Pushy Buttons − Pushy Buttons library is a small CSS Pressable Buttons library.
Pushy Buttons − Pushy Buttons library is a small CSS Pressable Buttons library.
btns.css − btns.css buttons library is a set of CSS Buttons which make use of smooth transitions.
btns.css − btns.css buttons library is a set of CSS Buttons which make use of smooth transitions.
Social Buttons − Social Buttons library is a set of CSS Buttons made in pure CSS and are based on Bootstrap and Font Awesome.
Social Buttons − Social Buttons library is a set of CSS Buttons made in pure CSS and are based on Bootstrap and Font Awesome.
Beautons − Beautons buttons library is a simple CSS toolkit for creating buttons. It allows to apply a combination of styles, sizes to create a huge set of consistent, robust and solid buttons.
Beautons − Beautons buttons library is a simple CSS toolkit for creating buttons. It allows to apply a combination of styles, sizes to create a huge set of consistent, robust and solid buttons.
bttn.css library provides a huge collection of simple styles for buttons. This library is completely free for both personal and commercial use. These buttons can be customized easily.
To load the btns.css library, go to the link btns.css and paste the following line in the <head> section of the webpage.
<head>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css">
</head>
Create a button using html button tag and add styles bttn-slant, bttn-royal with size specifier bttn-lg.
<html>
<head>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css">
</head>
<body>
<button class = "bttn-slant">Submit</button>
</body>
</html>
It will produce the following output −
You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes.
<html>
<head>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css">
</head>
<body>
<button class = "bttn-pill bttn-lg">Large</button>
<button class = "bttn-pill bttn-md">Medium</button>
<button class = "bttn-pill bttn-sm">Small</button>
<button class = "bttn-pill bttn-xs">Extra Small</button>
</body>
</html>
It will produce the following output −
Just like size, you can define the color of the button using CSS. The following example shows how to change the color of the button.
<html>
<head>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/bttn.css/0.2.4/bttn.css">
</head>
<body>
<button class = "bttn-pill bttn-lg bttn-primary">Primary</button>
<button class = "bttn-pill bttn-md bttn-warning">Warning</button>
<button class = "bttn-pill bttn-sm bttn-danger">Danger</button>
<button class = "bttn-pill bttn-xs bttn-success">Success</button>
<button class = "bttn-pill bttn-xs bttn-royal">Royal</button>
</body>
</html>
It will produce the following output −
Following are the various styles available in bttn.css
Pushy Buttons library is a small CSS Pressable Buttons library.
To load the pushy-buttons.min.css library, download the css from github and paste the following line in the <head> section of the webpage.
<head>
<link rel = "stylesheet" href = "pushy-buttons.min.css">
</head>
Create a button using html button tag and add styles btn, btn-blue with size specifier btn-lg.
<html>
<head>
<link rel = "stylesheet" href = "/css_buttons/pushy-buttons.min.css">
</head>
<body>
<button class = "btn btn--blue">Submit</button>
</body>
</html>
It will produce the following output −
You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes.
<html>
<head>
<link rel = "stylesheet" href = "/css_buttons/pushy-buttons.min.css">
</head>
<body>
<button class = "btn btn--lg btn--blue">Large</button>
<button class = "btn btn--df btn--blue">Normal</button>
<button class = "btn btn--md btn--blue">Medium</button>
<button class = "btn btn--sm btn--blue">Small</button>
</body>
</html>
It will produce the following output −
Just like size, you can define the color of the button using CSS. The following example shows how to change the color of the button.
<html>
<head>
<link rel = "stylesheet" href = "/css_buttons/pushy-buttons.min.css">
</head>
<body>
<button class = "btn btn--lg btn--red">Large</button>
<button class = "btn btn--df btn--green">Normal</button>
<button class = "btn btn--md btn--blue">Medium</button>
</body>
</html>
It will produce the following output −
btns.css buttons library is a set of CSS Buttons which make use of smooth transitions.
To load the btns.css library, go to the link btns.css and paste the following line in the <head> section of the webpage.
<head>
<link rel = "stylesheet" href = "btns.css">
</head>
Create a button using html button tag and add styles btn, btn-blue with size specifier btn-lg.
<html>
<head>
<link rel = "stylesheet" href = "/css_buttons/btns.css">
</head>
<body>
<button class = "btn btn-blue">Submit</button>
</body>
</html>
It will produce the following output −
You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes.
<html>
<head>
<link rel = "stylesheet" href = "/css_buttons/btns.css">
</head>
<body>
<button class = "btn btn-lg btn-blue">Large</button>
<button class = "btn btn-sm btn-blue">Small</button>
</body>
</html>
It will produce the following output −
Just like size, you can define the color of the button using CSS. The following example shows how to change the color of the button.
<html>
<head>
<link rel = "stylesheet" href = "/css_buttons/btns.css">
</head>
<body>
<button class = "btn btn-lg btn-red">Red</button>
<button class = "btn btn-lg btn-blue">Blue</button>
<button class = "btn btn-lg btn-green">Green</button>
<button class = "btn btn-lg btn-sea">Sea</button>
<button class = "btn btn-lg btn-yellow">Yellow</button>
<button class = "btn btn-lg btn-orange">Orange</button>
<button class = "btn btn-lg btn-purple">Purple</button>
<button class = "btn btn-lg btn-black">Black</button>
<button class = "btn btn-lg btn-cloud">Cloud</button>
<button class = "btn btn-lg btn-grey">Grey</button>
</body>
</html>
It will produce the following output −
Just like size,color you can define the style of the button using CSS. The following example shows how to change the style of the button.
<html>
<head>
<link rel = "stylesheet" href = "/css_buttons/btns.css">
</head>
<body>
<button class = "btn btn-lg btn-blue">Regular</button>
<button class = "btn btn-lg btn-blue btn-round">Round</button>
<button class = "btn btn-lg btn-blue btn-raised">Raised</button>
<button class = "btn btn-blue btn-sm">Small</button>
<button class = "btn btn-lg btn-outline-blue ">Outlined</button>
</body>
</html>
It will produce the following output −
Social Buttons library is a set of CSS Buttons made in pure CSS and are based on Bootstrap and Font Awesome.
To load the bootstrap-social.css library, download the bootstrap-social.css from github and paste the following line in the <head> section of the webpage.
<head>
<link rel = "stylesheet" href = "bootstrap-social.css">
</head>
Create a button using html anchor tag and add styles btn, btn-block with social specifier btn-social.
<html>
<head>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel = "stylesheet" href = "/css_buttons/bootstrap-social.css">
</head>
<body>
<a class = "btn btn-block btn-social btn-twitter">
<span class = "fa fa-twitter"></span>
Login with Twitter
</a>
</body>
</html>
It will produce the following output −
You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes.
<html>
<head>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel = "stylesheet" href = "/css_buttons/bootstrap-social.css">
</head>
<body>
<a class = "btn btn-block btn-lg btn-social btn-twitter">
<span class = "fa fa-twitter"></span>
Login with Twitter
</a>
<a class = "btn btn-block btn-md btn-social btn-twitter">
<span class = "fa fa-twitter"></span>
Login with Twitter
</a>
<a class = "btn btn-block btn-sm btn-social btn-twitter">
<span class = "fa fa-twitter"></span>
Login with Twitter
</a>
<a class = "btn btn-block btn-xs btn-social btn-twitter">
<span class = "fa fa-twitter"></span>
Login with Twitter
</a>
</body>
</html>
It will produce the following output −
The following example shows how to choose icon only buttons.
<html>
<head>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel = "stylesheet" href = "bootstrap-social.css">
</head>
<body>
<a class = "btn btn-social-icon btn-twitter">
<span class = "fa fa-twitter"></span>
</a>
</body>
</html>
It will produce the following output −
Following are the various styles available in Social Buttons.
Beautons buttons library is a simple CSS toolkit for creating buttons. It allows to apply a combination of styles, sizes to create a huge set of consistent, robust and solid buttons.
To load the Beautons library, download the css from github and paste the following line in the <head> section of the webpage.
<head>
<link rel = "stylesheet" href = "beauton.min.css">
</head>
Create a button using html button tag and add styles btn.
<html>
<head>
<link rel = "stylesheet" href = "/css_buttons/beauton.min.css">
</head>
<body>
<button class = "btn"<Submit</button>
</body>
</html>
It will produce the following output −
You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes.
<html>
<head>
<link rel = "stylesheet" href = "/css_buttons/beauton.min.css">
</head>
<body>
<button class = "btn btn--small">Small</button> <br/> <br/>
<button class = "btn btn--large btn-blue">Large</button><br/><br/>
<button class = "btn btn--huge">Huge</button><br/><br/>
<button class = "btn btn--full">Full</button><br/><br/>
</body>
</html>
It will produce the following output −
You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes.
<html>
<head>
<link rel = "stylesheet" href = "/css_buttons/beauton.min.css">
</head>
<body>
<button class = "btn btn--alpha">Huge</button><br/><br/>
<button class = "btn btn--beta">Large</button><br/><br/>
<button class = "btn btn--gamma">Regular</button><br/><br/>
</body>
</html>
It will produce the following output −
The following example shows various functional button.
<html>
<head>
<link rel = "stylesheet" href = "/css_buttons/beauton.min.css">
</head>
<body>
<button class = "btn btn--positive">Positive</button> <br/> <br/>
<button class = "btn btn--negative">Negative</button><br/><br/>
<button class = "btn btn--inactive">Disabled</button><br/><br/>
<button class = "btn btn--soft">Rounded</button><br/><br/>
<button class = "btn btn--hard">Hard</button><br/><br/>
</body>
</html>
It will produce the following output −
The following example shows how to combines the styles of the buttons.
<html>
<head>
<link rel = "stylesheet" href = "/css_buttons/beauton.min.css">
</head>
<body>
<button class = "btn btn--large btn--positive">Button</button> <br/><br/>
<button class = "btn btn--positive btn--alpha btn--small">Button</button><br/><br/>
<button class = "btn btn--negative btn--full btn--soft">Button</button><br/><br/>
<p>A <button class = "btn btn--natural">button</button> in a paragraph.</p><br/><br/>
</body>
</html>
It will produce the following output −
A button in a paragraph.
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2143,
"s": 1898,
"text": "A button on a web-page is the prime actor where a user clicks after selecting or entering the required inputs and submits the details to get required information. This tutorial focuses on ten main CSS libraries to make buttons awesome, namely −"
},
... |
C program to calculate age | Given with the current date and the birth date of a person and the task is to calculate his current age.
Input-: present date-: 21/9/2019
Birth date-: 25/9/1996
Output-: Present Age
Years: 22 Months:11 Days: 26
Approach used below is as follows −
Input the current date and birth date of a person
Check for the conditionsIf current month is less than the birth month, then we will not consider the current year because this year has not been completed yet and to compute the differences in months by adding 12 to the current month.If the current date is less than the birth date, then we will not consider month and for generating subtracted dates add number of month days to the current date and the result will difference in the dates.
If current month is less than the birth month, then we will not consider the current year because this year has not been completed yet and to compute the differences in months by adding 12 to the current month.
If the current date is less than the birth date, then we will not consider month and for generating subtracted dates add number of month days to the current date and the result will difference in the dates.
When this conditions are meet just subtract the days, months and year to get the final result
Print the final age
Start
Step 1-> declare function to calculate age
void age(int present_date, int present_month, int present_year, int birth_date, int birth_month, int birth_year)
Set int month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
IF (birth_date > present_date)
Set present_date = present_date + month[birth_month - 1]
Set present_month = present_month – 1
End
IF (birth_month > present_month)
Set present_year = present_year – 1
Set present_month = present_month + 12
End
Set int final_date = present_date - birth_date
Set int final_month = present_month - birth_month
Set int final_year = present_year - birth_year
Print final_year, final_month, final_date
Step 2-> In main()
Set int present_date = 21
Set int present_month = 9
Set int present_year = 2019
Set int birth_date = 25
Set int birth_month = 9
Set int birth_year = 1996
Call age(present_date, present_month, present_year, birth_date, birth_month,
birth_year)
Stop
Live Demo
#include <stdio.h>
#include <stdlib.h>
// function to calculate current age
void age(int present_date, int present_month, int present_year, int birth_date, int birth_month, int birth_year) {
int month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (birth_date > present_date) {
present_date = present_date + month[birth_month - 1];
present_month = present_month - 1;
}
if (birth_month > present_month) {
present_year = present_year - 1;
present_month = present_month + 12;
}
int final_date = present_date - birth_date;
int final_month = present_month - birth_month;
int final_year = present_year - birth_year;
printf("Present Age Years: %d Months: %d Days: %d", final_year, final_month, final_date);
}
int main() {
int present_date = 21;
int present_month = 9;
int present_year = 2019;
int birth_date = 25;
int birth_month = 9;
int birth_year = 1996;
age(present_date, present_month, present_year, birth_date, birth_month, birth_year);
return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
Present Age Years: 22 Months:11 Days: 26 | [
{
"code": null,
"e": 1167,
"s": 1062,
"text": "Given with the current date and the birth date of a person and the task is to calculate his current age."
},
{
"code": null,
"e": 1279,
"s": 1167,
"text": "Input-: present date-: 21/9/2019\n Birth date-: 25/9/1996\nOutput-: Present... |
Maximum and minimum of an array using minimum number of comparisons - GeeksforGeeks | 09 Apr, 2022
Write a C function to return minimum and maximum in an array. Your program should make the minimum number of comparisons.
First of all, how do we return multiple values from a C function? We can do it either using structures or pointers. We have created a structure named pair (which contains min and max) to return multiple values.
c
Java
C#
struct pair{ int min; int max;};
static class pair{ int min; int max;}; // This code contributed by Rajput-Ji
public static class pair { public int min; public int max;};// This code contributed by Rajput-Ji
And the function declaration becomes: struct pair getMinMax(int arr[], int n) where arr[] is the array of size n whose minimum and maximum are needed.
METHOD 1 (Simple Linear Search) Initialize values of min and max as minimum and maximum of the first two elements respectively. Starting from 3rd, compare each element with max and min, and change max and min accordingly (i.e., if the element is smaller than min then change min, else if the element is greater than max then change max, else ignore the element)
C++
C
Java
Python3
C#
Javascript
// C++ program of above implementation#include<iostream>using namespace std; // Pair struct is used to return// two values from getMinMax()struct Pair{ int min; int max;}; Pair getMinMax(int arr[], int n){ struct Pair minmax; int i; // If there is only one element // then return it as min and max both if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } // If there are more than one elements, // then initialize min and max if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for(i = 2; i < n; i++) { if (arr[i] > minmax.max) minmax.max = arr[i]; else if (arr[i] < minmax.min) minmax.min = arr[i]; } return minmax;} // Driver codeint main(){ int arr[] = { 1000, 11, 445, 1, 330, 3000 }; int arr_size = 6; struct Pair minmax = getMinMax(arr, arr_size); cout << "Minimum element is " << minmax.min << endl; cout << "Maximum element is " << minmax.max; return 0;} // This code is contributed by nik_3112
/* structure is used to return two values from minMax() */#include<stdio.h>struct pair{ int min; int max;}; struct pair getMinMax(int arr[], int n){ struct pair minmax; int i; /*If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i<n; i++) { if (arr[i] > minmax.max) minmax.max = arr[i]; else if (arr[i] < minmax.min) minmax.min = arr[i]; } return minmax;} /* Driver program to test above function */int main(){ int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; struct pair minmax = getMinMax (arr, arr_size); printf("nMinimum element is %d", minmax.min); printf("nMaximum element is %d", minmax.max); getchar();}
// Java program of above implementationpublic class GFG {/* Class Pair is used to return two values from getMinMax() */ static class Pair { int min; int max; } static Pair getMinMax(int arr[], int n) { Pair minmax = new Pair(); int i; /*If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i < n; i++) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } else if (arr[i] < minmax.min) { minmax.min = arr[i]; } } return minmax; } /* Driver program to test above function */ public static void main(String args[]) { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); System.out.printf("\nMinimum element is %d", minmax.min); System.out.printf("\nMaximum element is %d", minmax.max); } }
# Python program of above implementation # structure is used to return two values from minMax() class pair: def __init__(self): self.min = 0 self.max = 0 def getMinMax(arr: list, n: int) -> pair: minmax = pair() # If there is only one element then return it as min and max both if n == 1: minmax.max = arr[0] minmax.min = arr[0] return minmax # If there are more than one elements, then initialize min # and max if arr[0] > arr[1]: minmax.max = arr[0] minmax.min = arr[1] else: minmax.max = arr[1] minmax.min = arr[0] for i in range(2, n): if arr[i] > minmax.max: minmax.max = arr[i] elif arr[i] < minmax.min: minmax.min = arr[i] return minmax # Driver Codeif __name__ == "__main__": arr = [1000, 11, 445, 1, 330, 3000] arr_size = 6 minmax = getMinMax(arr, arr_size) print("Minimum element is", minmax.min) print("Maximum element is", minmax.max) # This code is contributed by# sanjeev2552
// C# program of above implementationusing System; class GFG{ /* Class Pair is used to return two values from getMinMax() */ class Pair { public int min; public int max; } static Pair getMinMax(int []arr, int n) { Pair minmax = new Pair(); int i; /* If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i < n; i++) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } else if (arr[i] < minmax.min) { minmax.min = arr[i]; } } return minmax; } // Driver Code public static void Main(String []args) { int []arr = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); Console.Write("Minimum element is {0}", minmax.min); Console.Write("\nMaximum element is {0}", minmax.max); }} // This code is contributed by PrinciRaj1992
<script>// JavaScript program of above implementation /* Class Pair is used to return two values from getMinMax() */ function getMinMax(arr, n) { minmax = new Array(); var i; var min; var max; /*If there is only one element then return it as min and max both*/ if (n == 1) { minmax.max = arr[0]; minmax.min = arr[0]; return minmax; } /* If there are more than one elements, then initialize min and max*/ if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.max = arr[1]; minmax.min = arr[0]; } for (i = 2; i < n; i++) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } else if (arr[i] < minmax.min) { minmax.min = arr[i]; } } return minmax; } /* Driver program to test above function */ var arr = [1000, 11, 445, 1, 330, 3000]; var arr_size = 6; minmax = getMinMax(arr, arr_size); document.write("\nMinimum element is " ,minmax.min +"<br>"); document.write("\nMaximum element is " , minmax.max); // This code is contributed by shivanisinghss2110</script>
Output:
Minimum element is 1
Maximum element is 3000
Time Complexity: O(n)
Auxiliary Space: O(1) as no extra space was needed.
In this method, the total number of comparisons is 1 + 2(n-2) in the worst case and 1 + n – 2 in the best case. In the above implementation, the worst case occurs when elements are sorted in descending order and the best case occurs when elements are sorted in ascending order.
METHOD 2 (Tournament Method) Divide the array into two parts and compare the maximums and minimums of the two parts to get the maximum and the minimum of the whole array.
Pair MaxMin(array, array_size)
if array_size = 1
return element as both max and min
else if arry_size = 2
one comparison to determine max and min
return that pair
else /* array_size > 2 */
recur for max and min of left half
recur for max and min of right half
one comparison determines true max of the two candidates
one comparison determines true min of the two candidates
return the pair of max and min
Implementation
C++
C
Java
Python3
C#
Javascript
// C++ program of above implementation#include<iostream>using namespace std; // structure is used to return// two values from minMax()struct Pair{ int min; int max;}; struct Pair getMinMax(int arr[], int low, int high){ struct Pair minmax, mml, mmr; int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } // If there are two elements if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } // If there are more than 2 elements mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); // Compare minimums of two parts if (mml.min < mmr.min) minmax.min = mml.min; else minmax.min = mmr.min; // Compare maximums of two parts if (mml.max > mmr.max) minmax.max = mml.max; else minmax.max = mmr.max; return minmax;} // Driver codeint main(){ int arr[] = { 1000, 11, 445, 1, 330, 3000 }; int arr_size = 6; struct Pair minmax = getMinMax(arr, 0, arr_size - 1); cout << "Minimum element is " << minmax.min << endl; cout << "Maximum element is " << minmax.max; return 0;} // This code is contributed by nik_3112
/* structure is used to return two values from minMax() */#include<stdio.h>struct pair{ int min; int max;}; struct pair getMinMax(int arr[], int low, int high){ struct pair minmax, mml, mmr; int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = (low + high)/2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid+1, high); /* compare minimums of two parts*/ if (mml.min < mmr.min) minmax.min = mml.min; else minmax.min = mmr.min; /* compare maximums of two parts*/ if (mml.max > mmr.max) minmax.max = mml.max; else minmax.max = mmr.max; return minmax;} /* Driver program to test above function */int main(){ int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; struct pair minmax = getMinMax(arr, 0, arr_size-1); printf("nMinimum element is %d", minmax.min); printf("nMaximum element is %d", minmax.max); getchar();}
// Java program of above implementationpublic class GFG {/* Class Pair is used to return two values from getMinMax() */ static class Pair { int min; int max; } static Pair getMinMax(int arr[], int low, int high) { Pair minmax = new Pair(); Pair mml = new Pair(); Pair mmr = new Pair(); int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); /* compare minimums of two parts*/ if (mml.min < mmr.min) { minmax.min = mml.min; } else { minmax.min = mmr.min; } /* compare maximums of two parts*/ if (mml.max > mmr.max) { minmax.max = mml.max; } else { minmax.max = mmr.max; } return minmax; } /* Driver program to test above function */ public static void main(String args[]) { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, 0, arr_size - 1); System.out.printf("\nMinimum element is %d", minmax.min); System.out.printf("\nMaximum element is %d", minmax.max); }}
# Python program of above implementationdef getMinMax(low, high, arr): arr_max = arr[low] arr_min = arr[low] # If there is only one element if low == high: arr_max = arr[low] arr_min = arr[low] return (arr_max, arr_min) # If there is only two element elif high == low + 1: if arr[low] > arr[high]: arr_max = arr[low] arr_min = arr[high] else: arr_max = arr[high] arr_min = arr[low] return (arr_max, arr_min) else: # If there are more than 2 elements mid = int((low + high) / 2) arr_max1, arr_min1 = getMinMax(low, mid, arr) arr_max2, arr_min2 = getMinMax(mid + 1, high, arr) return (max(arr_max1, arr_max2), min(arr_min1, arr_min2)) # Driver codearr = [1000, 11, 445, 1, 330, 3000]high = len(arr) - 1low = 0arr_max, arr_min = getMinMax(low, high, arr)print('Minimum element is ', arr_min)print('nMaximum element is ', arr_max) # This code is contributed by DeepakChhitarka
// C# implementation of the approachusing System; public class GFG {/* Class Pair is used to return two values from getMinMax() */ public class Pair { public int min; public int max; } static Pair getMinMax(int []arr, int low, int high) { Pair minmax = new Pair(); Pair mml = new Pair(); Pair mmr = new Pair(); int mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = (low + high) / 2; mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); /* compare minimums of two parts*/ if (mml.min < mmr.min) { minmax.min = mml.min; } else { minmax.min = mmr.min; } /* compare maximums of two parts*/ if (mml.max > mmr.max) { minmax.max = mml.max; } else { minmax.max = mmr.max; } return minmax; } /* Driver program to test above function */ public static void Main(String []args) { int []arr = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, 0, arr_size - 1); Console.Write("\nMinimum element is {0}", minmax.min); Console.Write("\nMaximum element is {0}", minmax.max); }} // This code contributed by Rajput-Ji
<script>// Javascript program of above implementation /* Class Pair is used to return two values from getMinMax() */ class Pair { constructor(){ this.min = -1; this.max = 10000000; } } function getMinMax(arr , low , high) { var minmax = new Pair(); var mml = new Pair(); var mmr = new Pair(); var mid; // If there is only one element if (low == high) { minmax.max = arr[low]; minmax.min = arr[low]; return minmax; } /* If there are two elements */ if (high == low + 1) { if (arr[low] > arr[high]) { minmax.max = arr[low]; minmax.min = arr[high]; } else { minmax.max = arr[high]; minmax.min = arr[low]; } return minmax; } /* If there are more than 2 elements */ mid = parseInt((low + high) / 2); mml = getMinMax(arr, low, mid); mmr = getMinMax(arr, mid + 1, high); /* compare minimums of two parts */ if (mml.min < mmr.min) { minmax.min = mml.min; } else { minmax.min = mmr.min; } /* compare maximums of two parts */ if (mml.max > mmr.max) { minmax.max = mml.max; } else { minmax.max = mmr.max; } return minmax; } /* Driver program to test above function */ var arr = [ 1000, 11, 445, 1, 330, 3000 ]; var arr_size = 6; var minmax = getMinMax(arr, 0, arr_size - 1); document.write("\nMinimum element is ", minmax.min); document.write("<br/>Maximum element is ", minmax.max); // This code is contributed by Rajput-Ji</script>
Output:
Minimum element is 1
Maximum element is 3000
Time Complexity: O(n)
Auxiliary Space: O(log n) as the stack space will be filled for the maximum height of the tree formed during recursive calls same as a binary tree.
Total number of comparisons: let the number of comparisons be T(n). T(n) can be written as follows: Algorithmic Paradigm: Divide and Conquer
T(n) = T(floor(n/2)) + T(ceil(n/2)) + 2
T(2) = 1
T(1) = 0
If n is a power of 2, then we can write T(n) as:
T(n) = 2T(n/2) + 2
After solving the above recursion, we get
T(n) = 3n/2 -2
Thus, the approach does 3n/2 -2 comparisons if n is a power of 2. And it does more than 3n/2 -2 comparisons if n is not a power of 2.
METHOD 3 (Compare in Pairs) If n is odd then initialize min and max as first element. If n is even then initialize min and max as minimum and maximum of the first two elements respectively. For rest of the elements, pick them in pairs and compare their maximum and minimum with max and min respectively.
C++
C
Java
Python3
C#
// C++ program of above implementation#include<iostream>using namespace std; // Structure is used to return// two values from minMax()struct Pair{ int min; int max;}; struct Pair getMinMax(int arr[], int n){ struct Pair minmax; int i; // If array has even number of elements // then initialize the first two elements // as minimum and maximum if (n % 2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } // Set the starting index for loop i = 2; } // If array has odd number of elements // then initialize the first element as // minimum and maximum else { minmax.min = arr[0]; minmax.max = arr[0]; // Set the starting index for loop i = 1; } // In the while loop, pick elements in // pair and compare the pair with max // and min so far while (i < n - 1) { if (arr[i] > arr[i + 1]) { if(arr[i] > minmax.max) minmax.max = arr[i]; if(arr[i + 1] < minmax.min) minmax.min = arr[i + 1]; } else { if (arr[i + 1] > minmax.max) minmax.max = arr[i + 1]; if (arr[i] < minmax.min) minmax.min = arr[i]; } // Increment the index by 2 as // two elements are processed in loop i += 2; } return minmax;} // Driver codeint main(){ int arr[] = { 1000, 11, 445, 1, 330, 3000 }; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); cout << "nMinimum element is " << minmax.min << endl; cout << "nMaximum element is " << minmax.max; return 0;} // This code is contributed by nik_3112
#include<stdio.h> /* structure is used to return two values from minMax() */struct pair{ int min; int max;}; struct pair getMinMax(int arr[], int n){ struct pair minmax; int i; /* If array has even number of elements then initialize the first two elements as minimum and maximum */ if (n%2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } i = 2; /* set the starting index for loop */ } /* If array has odd number of elements then initialize the first element as minimum and maximum */ else { minmax.min = arr[0]; minmax.max = arr[0]; i = 1; /* set the starting index for loop */ } /* In the while loop, pick elements in pair and compare the pair with max and min so far */ while (i < n-1) { if (arr[i] > arr[i+1]) { if(arr[i] > minmax.max) minmax.max = arr[i]; if(arr[i+1] < minmax.min) minmax.min = arr[i+1]; } else { if (arr[i+1] > minmax.max) minmax.max = arr[i+1]; if (arr[i] < minmax.min) minmax.min = arr[i]; } i += 2; /* Increment the index by 2 as two elements are processed in loop */ } return minmax;} /* Driver program to test above function */int main(){ int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; struct pair minmax = getMinMax (arr, arr_size); printf("nMinimum element is %d", minmax.min); printf("nMaximum element is %d", minmax.max); getchar();}
// Java program of above implementationpublic class GFG { /* Class Pair is used to return two values from getMinMax() */ static class Pair { int min; int max; } static Pair getMinMax(int arr[], int n) { Pair minmax = new Pair(); int i; /* If array has even number of elements then initialize the first two elements as minimum and maximum */ if (n % 2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } i = 2; /* set the starting index for loop */ } /* If array has odd number of elements then initialize the first element as minimum and maximum */ else { minmax.min = arr[0]; minmax.max = arr[0]; i = 1; /* set the starting index for loop */ } /* In the while loop, pick elements in pair and compare the pair with max and min so far */ while (i < n - 1) { if (arr[i] > arr[i + 1]) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } if (arr[i + 1] < minmax.min) { minmax.min = arr[i + 1]; } } else { if (arr[i + 1] > minmax.max) { minmax.max = arr[i + 1]; } if (arr[i] < minmax.min) { minmax.min = arr[i]; } } i += 2; /* Increment the index by 2 as two elements are processed in loop */ } return minmax; } /* Driver program to test above function */ public static void main(String args[]) { int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); System.out.printf("\nMinimum element is %d", minmax.min); System.out.printf("\nMaximum element is %d", minmax.max); }}
# Python3 program of above implementationdef getMinMax(arr): n = len(arr) # If array has even number of elements then # initialize the first two elements as minimum # and maximum if(n % 2 == 0): mx = max(arr[0], arr[1]) mn = min(arr[0], arr[1]) # set the starting index for loop i = 2 # If array has odd number of elements then # initialize the first element as minimum # and maximum else: mx = mn = arr[0] # set the starting index for loop i = 1 # In the while loop, pick elements in pair and # compare the pair with max and min so far while(i < n - 1): if arr[i] < arr[i + 1]: mx = max(mx, arr[i + 1]) mn = min(mn, arr[i]) else: mx = max(mx, arr[i]) mn = min(mn, arr[i + 1]) # Increment the index by 2 as two # elements are processed in loop i += 2 return (mx, mn) # Driver Codeif __name__ =='__main__': arr = [1000, 11, 445, 1, 330, 3000] mx, mn = getMinMax(arr) print("Minimum element is", mn) print("Maximum element is", mx) # This code is contributed by Kaustav
// C# program of above implementationusing System; class GFG{ /* Class Pair is used to return two values from getMinMax() */ public class Pair { public int min; public int max; } static Pair getMinMax(int []arr, int n) { Pair minmax = new Pair(); int i; /* If array has even number of elements then initialize the first two elements as minimum and maximum */ if (n % 2 == 0) { if (arr[0] > arr[1]) { minmax.max = arr[0]; minmax.min = arr[1]; } else { minmax.min = arr[0]; minmax.max = arr[1]; } i = 2; } /* set the starting index for loop */ /* If array has odd number of elements then initialize the first element as minimum and maximum */ else { minmax.min = arr[0]; minmax.max = arr[0]; i = 1; /* set the starting index for loop */ } /* In the while loop, pick elements in pair and compare the pair with max and min so far */ while (i < n - 1) { if (arr[i] > arr[i + 1]) { if (arr[i] > minmax.max) { minmax.max = arr[i]; } if (arr[i + 1] < minmax.min) { minmax.min = arr[i + 1]; } } else { if (arr[i + 1] > minmax.max) { minmax.max = arr[i + 1]; } if (arr[i] < minmax.min) { minmax.min = arr[i]; } } i += 2; /* Increment the index by 2 as two elements are processed in loop */ } return minmax; } // Driver Code public static void Main(String []args) { int []arr = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; Pair minmax = getMinMax(arr, arr_size); Console.Write("Minimum element is {0}", minmax.min); Console.Write("\nMaximum element is {0}", minmax.max); }} // This code is contributed by 29AjayKumar
Output:
Minimum element is 1
Maximum element is 3000
Time Complexity: O(n)
Auxiliary Space: O(1) as no extra space was needed.
Total number of comparisons: Different for even and odd n, see below:
If n is odd: 3*(n-1)/2
If n is even: 1 Initial comparison for initializing min and max,
and 3(n-2)/2 comparisons for rest of the elements
= 1 + 3*(n-2)/2 = 3n/2 -2
Second and third approaches make the equal number of comparisons when n is a power of 2. In general, method 3 seems to be the best.Please write comments if you find any bug in the above programs/algorithms or a better way to solve the same problem.
kamleshbhalui
Rajput-Ji
Kaustav kumar Chanda
Akanksha_Rai
princiraj1992
29AjayKumar
sanjeev2552
DeepakChhitarka
nik_3112
maafkaroplz
anjalitejasvi501
anshulpurohit11
dhairyabahl5
shivanisinghss2110
abhishekolympics
prophet1999
Numbers
Arrays
Divide and Conquer
Searching
Arrays
Searching
Divide and Conquer
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
QuickSort
Merge Sort
Binary Search
Program for Tower of Hanoi
Divide and Conquer Algorithm | Introduction | [
{
"code": null,
"e": 40883,
"s": 40855,
"text": "\n09 Apr, 2022"
},
{
"code": null,
"e": 41006,
"s": 40883,
"text": "Write a C function to return minimum and maximum in an array. Your program should make the minimum number of comparisons. "
},
{
"code": null,
"e": 412... |
Vertical and Horizontal Scrollbars on Tkinter Widget | Scrollbars are useful to provide dynamic behavior in an application. In a Tkinter application, we can create Vertical as well as Horizontal Scrollbars. Scrollbars are created by initializing the object of Scrollbar() widget.
To create a horizontal scrollbar, we have to provide the orientation, i.e., "horizontal" or "vertical". Scrollbars can be accessible once we configure the particular widget with the scrollbars.
#Import the required libraries
from tkinter import *
#Create an instance of Tkinter Frame
win = Tk()
#Set the geometry of Tkinter Frame
win.geometry("700x350")
#Create some dummy Text
text_v = "Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming."
text_h = ("\nNASA \n Google \nNokia \nFacebook \n Netflix \n Expedia \n Reddit \n Quora \n MIT\n Udemy \n Shutterstock \nSpotify\nAmazon\nMozilla\nDropbox")
#Add a Vertical Scrollbar
scroll_v = Scrollbar(win)
scroll_v.pack(side= RIGHT,fill="y")
#Add a Horizontal Scrollbar
scroll_h = Scrollbar(win, orient= HORIZONTAL)
scroll_h.pack(side= BOTTOM, fill= "x")
#Add a Text widget
text = Text(win, height= 500, width= 350, yscrollcommand= scroll_v.set,
xscrollcommand = scroll_h.set, wrap= NONE, font= ('Helvetica 15'))
text.pack(fill = BOTH, expand=0)
text.insert(END, text_v)
text.insert(END, text_h)
#Attact the scrollbar with the text widget
scroll_h.config(command = text.xview)
scroll_v.config(command = text.yview)
win.mainloop()
Running the above code will display a window containing context about Python Programming language. The context can be dynamically viewed using horizontal and vertical scrollbars. | [
{
"code": null,
"e": 1287,
"s": 1062,
"text": "Scrollbars are useful to provide dynamic behavior in an application. In a Tkinter application, we can create Vertical as well as Horizontal Scrollbars. Scrollbars are created by initializing the object of Scrollbar() widget."
},
{
"code": null,
... |
strtol() function in C++ | The strol() function is used to convert the string to long integers. It sets the pointer to point to the first character after the last one. The syntax is like below. This function is present into the cstdlib library.
long int strtol(const char* str, char ** end, int base)
This function takes three arguments. These arguments are like below −
str: This is the starting of a string.
str_end: The str_end is set by the function to the next character, after the last valid character, if there is any character, otherwise null.
base: This specifies the base. The base values can be of (0, 2, 3, ..., 35, 36)
This function returns the converted long int. When the character points to NULL, it returns 0.
#include <iostream>
#include<cstdlib>
using namespace std;
main() {
//Define two string
char string1[] = "777HelloWorld";
char string2[] = "565Hello";
char* End; //The end pointer
int base = 10;
int value;
value = strtol(string1, &End, base);
cout << "The string Value = " << string1 << "\n";
cout << "Long Long Int value = " << value << "\n";
cout << "End String = " << End << "\n"; //remaining string after long long integer
value = strtol(string2, &End, base);
cout << "\nThe string Value = " << string2 << "\n";
cout << "Long Long Int value = " << value << "\n";
cout << "End String = " << End; //remaining string after long long integer
}
The string Value = 777HelloWorld
Long Long Int value = 777
End String = HelloWorld
The string Value = 565Hello
Long Long Int value = 565
End String = Hello
Now Let us see the example with a different base value. Here the base is 16. By taking the string of given base, it will print in decimal format.
#include <iostream>
#include<cstdlib>
using namespace std;
main() {
//Define two string
char string1[] = "5EHelloWorld";
char string2[] = "125Hello";
char* End; //The end pointer
int base = 16;
int value;
value = strtol(string1, &End, base);
cout << "The string Value = " << string1 << "\n";
cout << "Long Long Int value = " << value << "\n";
cout << "End String = " << End << "\n"; //remaining string after long long integer
value = strtol(string2, &End, base);
cout << "\nThe string Value = " << string2 << "\n";
cout << "Long Long Int value = " << value << "\n";
cout << "End String = " << End; //remaining string after long long integer
}
The string Value = 5EHelloWorld
Long Long Int value = 94
End String = HelloWorld
The string Value = 125Hello
Long Long Int value = 293
End String = Hello
Here the string is containing 5E so its value is 94 in decimal, and the second string is containing 125. This is 293 in decimal. | [
{
"code": null,
"e": 1280,
"s": 1062,
"text": "The strol() function is used to convert the string to long integers. It sets the pointer to point to the first character after the last one. The syntax is like below. This function is present into the cstdlib library."
},
{
"code": null,
"e"... |
SQL Query to Convert Date to Datetime - GeeksforGeeks | 18 Oct, 2021
In this article, we will look at how to convert Date to Datetime. We can convert the Date into Datetime in two ways.
Using CONVERT() function: Convert means to change the form or value of something. The CONVERT() function in the SQL server is used to convert a value of one type to another type.Convert() function is used to convert a value of any type to another datatype.
Using the CAST() function: SQL Server uses the CAST() function to cast or convert a value or an expression from one data type to another. The Cast() function is also used for the same purpose to convert the data type of any value.
To perform any queries we have to create a database. So, let us create a database first.
Step 1: Creating Database
Query:
CREATE DATABASE Test;
Output:
Step 2: Converting Date to Datetime
Method 1: Using CONVERT() function
In this example, we are converting the date 01-01-2021 into Datetime. The date is in the form ‘yyyy-mm-dd’.
Query:
SELECT CONVERT(datetime, '2021-01-01');
Output:
Method 2: Using CAST() function
In this example, we are converting the date 01-01-2021 into Datetime as shown below. The date is in the form ‘yyyy-mm-dd’.
Query:
SELECT CAST('2021-01-01' AS datetime);
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
Window functions in SQL | [
{
"code": null,
"e": 23903,
"s": 23875,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 24021,
"s": 23903,
"text": "In this article, we will look at how to convert Date to Datetime. We can convert the Date into Datetime in two ways. "
},
{
"code": null,
"e": 24278,
... |
How to create and populate Java array of Hash tables? | One way to create an array of hash tables is to create Hashtable objects and to assign these to a Hashtable array using curly braces:
Live Demo
import java.util.Hashtable;
public class HashTableOfArrays {
public static void main(String args[]) {
Hashtable<String, String> ht1 = new Hashtable();
ht1.put("Name", "Krishna");
ht1.put("Age", "28");
ht1.put("City", "Visakhapatnam");
ht1.put("Phone", "9848022338");
Hashtable<String, String> ht2 = new Hashtable();
ht2.put("Name", "Raju");
ht2.put("Age", "30");
ht2.put("City", "Chennai");
ht2.put("Phone", "9848033228");
Hashtable<String, String> ht3 = new Hashtable();
ht3.put("Name", "Satish");
ht3.put("Age", "35");
ht3.put("City", "Hyderabad");
ht3.put("Phone", "9848023848");
Hashtable [] hashArray = {ht1, ht2, ht3};
for(int i = 0; i<hashArray.length; i++){
System.out.println(hashArray[i]);
}
}
}
{Name=Krishna, City=Visakhapatnam, Phone=9848022338, Age=28}
{Name=Raju, City=Chennai, Phone=9848033228, Age=30}
{Name=Satish, City=Hyderabad, Phone=9848023848, Age=35} | [
{
"code": null,
"e": 1196,
"s": 1062,
"text": "One way to create an array of hash tables is to create Hashtable objects and to assign these to a Hashtable array using curly braces:"
},
{
"code": null,
"e": 1206,
"s": 1196,
"text": "Live Demo"
},
{
"code": null,
"e": 2... |
Matplotlib - Violin Plot | Violin plots are similar to box plots, except that they also show the probability density of the data at different values. These plots include a marker for the median of the data and a box indicating the interquartile range, as in the standard box plots. Overlaid on this box plot is a kernel density estimation. Like box plots, violin plots are used to represent comparison of a variable distribution (or sample distribution) across different "categories".
A violin plot is more informative than a plain box plot. In fact while a box plot only shows summary statistics such as mean/median and interquartile ranges, the violin plot shows the full distribution of the data.
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(10)
collectn_1 = np.random.normal(100, 10, 200)
collectn_2 = np.random.normal(80, 30, 200)
collectn_3 = np.random.normal(90, 20, 200)
collectn_4 = np.random.normal(70, 25, 200)
## combine these different collections into a list
data_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4]
# Create a figure instance
fig = plt.figure()
# Create an axes instance
ax = fig.add_axes([0,0,1,1])
# Create the boxplot
bp = ax.violinplot(data_to_plot)
plt.show()
63 Lectures
6 hours
Abhilash Nelson
11 Lectures
4 hours
DATAhill Solutions Srinivas Reddy
9 Lectures
2.5 hours
DATAhill Solutions Srinivas Reddy
32 Lectures
4 hours
Aipython
10 Lectures
2.5 hours
Akbar Khan
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2974,
"s": 2516,
"text": "Violin plots are similar to box plots, except that they also show the probability density of the data at different values. These plots include a marker for the median of the data and a box indicating the interquartile range, as in the standard box plots... |
MongoDB aggregation framework to sort by length of array? | To sort by length of array, use aggregate(). Before that, get the count of records in an arrayusing $sum. Let us create a collection with documents
> db.demo33.insertOne({"ListOfStudent":["Chris","Bob"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e17556ccfb11e5c34d898ca")
}
> db.demo33.insertOne({"ListOfStudent":["David","Adam","Mike"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e17557acfb11e5c34d898cb")
}
> db.demo33.insertOne({"ListOfStudent":["Carol","Sam","John","Robert"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e1755a3cfb11e5c34d898cc")
}
Display all documents from a collection with the help of find() method −
> db.demo33.find();
This will produce the following output −
{ "_id" : ObjectId("5e17556ccfb11e5c34d898ca"), "ListOfStudent" : [ "Chris", "Bob" ] }
{ "_id" : ObjectId("5e17557acfb11e5c34d898cb"), "ListOfStudent" : [ "David", "Adam", "Mike" ] }
{ "_id" : ObjectId("5e1755a3cfb11e5c34d898cc"), "ListOfStudent" : [ "Carol", "Sam", "John", "Robert" ] }
Following is the query to sort by length of array −
> db.demo33.aggregate({$unwind:"$ListOfStudent"}, { $group : {_id:'$_id', ct:{$sum:1}}}, { $sort :{ ct: -1}} );
This will produce the following output −
{ "_id" : ObjectId("5e1755a3cfb11e5c34d898cc"), "ct" : 4 }
{ "_id" : ObjectId("5e17557acfb11e5c34d898cb"), "ct" : 3 }
{ "_id" : ObjectId("5e17556ccfb11e5c34d898ca"), "ct" : 2 } | [
{
"code": null,
"e": 1210,
"s": 1062,
"text": "To sort by length of array, use aggregate(). Before that, get the count of records in an arrayusing $sum. Let us create a collection with documents"
},
{
"code": null,
"e": 1663,
"s": 1210,
"text": "> db.demo33.insertOne({\"ListOfStu... |
Python Number random() Method | The random() method returns a random floating point number in the range [0.0, 1.0].
Following is the syntax for the random() method −
random ( )
Note − This function is not accessible directly, so we need to import the random module and then we need to call this function using the random static object.
NA
This method returns a random float r, such that 0.0 <= r <= 1.0
The following example shows the usage of the random() method.
#!/usr/bin/python3
import random
# First random number
print ("random() : ", random.random())
# Second random number
print ("random() : ", random.random())
When we run the above program, it produces the following result −
random() : 0.281954791393
random() : 0.309090465205
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2424,
"s": 2340,
"text": "The random() method returns a random floating point number in the range [0.0, 1.0]."
},
{
"code": null,
"e": 2474,
"s": 2424,
"text": "Following is the syntax for the random() method −"
},
{
"code": null,
"e": 2486,
"... |
How do JavaScript closures work? | In JavaScript, closure is the grouping of a function and where that function declared. In JavaScript, all functions work like closures. A closure is a function uses the scope in which it was declared when invoked. It is not the scope in which it was invoked.
You can try to run the following code to learn how to work with JavaScript closures:
<!DOCTYPE html>
<html>
<body>
<h2>Working with JavaScript Closures</h2>
<script>
var p = 10;
function a() {
var p = 15;
b(function() {
alert(p);
});
}
function b(f){
var p = 30;
f();
}
a();
</script>
</body>
</html> | [
{
"code": null,
"e": 1321,
"s": 1062,
"text": "In JavaScript, closure is the grouping of a function and where that function declared. In JavaScript, all functions work like closures. A closure is a function uses the scope in which it was declared when invoked. It is not the scope in which it was inv... |
Android working with Card View and Recycler View | Before getting into card view for recycler view example, we should know what is Recycler view in android. Recycler view is more advanced version of list view and it works based on View holder design pattern. Using recycler view we can show grids and list of items.
card view is extended by frame layout and it is used to show the items in card manner. It supports radius and shadow as predefined tags.
This example demonstrate about how to integrate Recycler View with card view by creating a beautiful student records app that displays student name with age.
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 − Open build.gradle and add Recycler view & Card view library dependencies.
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.andy.tutorialspoint"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Step 3 − 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"
xmlns:app = "http://schemas.android.com/apk/res-auto"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
app:layout_behavior = "@string/appbar_scrolling_view_behavior"
tools:showIn = "@layout/activity_main"
tools:context = ".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
</RelativeLayout>
In the above code we have added recycler view to window manager as relative parent layout.
Step 4 − Add the following code to src/MainActivity.java
package com.example.andy.tutorialspoint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private StudentAdapter studentAdapter;
private List<studentData> studentDataList = new ArrayList<>();
@TargetApi(Build.VERSION_CODES.O)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
studentAdapter = new StudentAdapter(studentDataList);
RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(manager);
recyclerView.setAdapter(studentAdapter);
StudentDataPrepare();
}
@RequiresApi(api = Build.VERSION_CODES.N)
private void StudentDataPrepare() {
studentData data = new studentData("sai", 25);
studentDataList.add(data);
data = new studentData("sai", 25);
studentDataList.add(data);
data = new studentData("raghu", 20);
studentDataList.add(data);
data = new studentData("raj", 28);
studentDataList.add(data);
data = new studentData("amar", 15);
studentDataList.add(data);
data = new studentData("bapu", 19);
studentDataList.add(data);
data = new studentData("chandra", 52);
studentDataList.add(data);
data = new studentData("deraj", 30);
studentDataList.add(data);
data = new studentData("eshanth", 28);
studentDataList.add(data);
Collections.sort(studentDataList, new Comparator() {
@Override
public int compare(studentData o1, studentData o2) {
return o1.name.compareTo(o2.name);
}
});
}
}
In the above code we have added recycler view and studentAdapter. In that student adapter we have passed studentDatalist as arraylist. In Student data list contains name of the student and age.
To get the grids, we have to use grid layout manager as shown below -
RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);
In the above code we have used layout manager as Gridlayout Manager and added cells as 2.So It will show the result with two grids in each row.
To compare recycler view items we have used collections framework and sort method as shown below -
Collections.sort(studentDataList, new Comparator() {
@Override
public int compare(studentData o1, studentData o2) {
return o1.name.compareTo(o2.name);
}
});
In the above code we are comparing elements by using name.
Step 5 − Following is the content of the modified file src/ StudentAdapter.java. package com.example.andy.tutorialspoint;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import java.util.Random;
class StudentAdapter extends RecyclerView.Adapter {
List studentDataList;
public StudentAdapter(List studentDataList) {
this.studentDataList=studentDataList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.student_list_row, viewGroup, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder viewHolder, int i) {
studentData data=studentDataList.get(i);
Random rnd = new Random();
int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
viewHolder.parent.setBackgroundColor(currentColor);
viewHolder.name.setText(data.name);
viewHolder.age.setText(String.valueOf(data.age));
}
@Override
public int getItemCount() {
return studentDataList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name,age;
LinearLayout parent;
public MyViewHolder(View itemView) {
super(itemView);
parent = itemView.findViewById(R.id.parent);
name = itemView.findViewById(R.id.name);
age = itemView.findViewById(R.id.age);
}
}
}
In the adapter class we have four methods as shown below -
onCreateViewHolder() :- It is used to create a view holder and it returns a view.
onBindViewHolder() - it going to bind with created view holder.
getItemCount() - it contains size of list.
MyViewHolder class- it is view holder inner class which is extended by RecyclerView.ViewHolder
To set random background for recycler view items, we have generated random colors using random class(which is predefined class in Android) and added color to parent of view item as shown below -
Random rnd = new Random();
int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
viewHolder.parent.setBackgroundColor(currentColor);
Step 6 − Following is the modified content of the xml res/layout/student_list_row.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view = "http://schemas.android.com/apk/res-auto"
android:layout_width = "match_parent"
card_view:cardCornerRadius = "4dp"
android:id =" @+id/card_view"
android:layout_margin = "10dp"
android:layout_height = "200dp">
<LinearLayout
android:id = "@+id/parent"
android:layout_gravity = "center"
android:layout_width = "match_parent"
android:orientation = "vertical"
android:gravity = "center"
android:layout_height="match_parent">
<TextView
android:id = "@+id/name"
android:layout_width = "wrap_content"
android:gravity = "center"
android:textSize = "25sp"
android:textColor = "#FFF"
android:layout_height = "wrap_content" />
<TextView
android:id = "@+id/age"
android:layout_width = "wrap_content"
android:gravity = "center"
android:textSize = "25sp"
android:textColor = "#FFF"
android:layout_height = "wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
In the above list item view we have created two text views for name and age inside the cardview. Card view contains pre defined corner radius and shadow property. So we have used corner radius with card view.
Step 7 − Following is the content of the modified file src/ studentData.java. package com.example.andy.tutorialspoint;
class studentData {
String name;
int age;
public studentData(String name, int age) {
this.name = name;
this.age = age;
}
}
In the above code informs about student data object. 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 −
Now scroll down to the recyclerview, it will show the result as shown below -
Click here to download the project code | [
{
"code": null,
"e": 1327,
"s": 1062,
"text": "Before getting into card view for recycler view example, we should know what is Recycler view in android. Recycler view is more advanced version of list view and it works based on View holder design pattern. Using recycler view we can show grids and lis... |
TypeScript - String concat() | This method adds two or more strings and returns a new single string.
string.concat(string2, string3[, ..., stringN]);
string2...stringN − These are the strings to be concatenated.
Returns a single concatenated string.
var str1 = new String( "This is string one" );
var str2 = new String( "This is string two" );
var str3 = str1.concat(str2.toString());
console.log("str1 + str2 : "+str3)
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
str1 + str2 : This is string oneThis is string two
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2118,
"s": 2048,
"text": "This method adds two or more strings and returns a new single string."
},
{
"code": null,
"e": 2168,
"s": 2118,
"text": "string.concat(string2, string3[, ..., stringN]);\n"
},
{
"code": null,
"e": 2230,
"s": 2168,
... |
java.time.Duration.ofMillis() Method Example | The java.time.Duration.ofMillis(long millis) method obtains a Duration representing a number of standard milliseconds.
Following is the declaration for java.time.Duration.ofMillis(long millis) method.
public static Duration ofMillis(long millis)
millis − the number of milliseconds, positive or negative.
a Duration, not null.
ArithmeticException − if the input milliseconds exceeds the capacity of Duration.
The following example shows the usage of java.time.Duration.ofMillis(long millis) method.
package com.tutorialspoint;
import java.time.Duration;
public class DurationDemo {
public static void main(String[] args) {
Duration duration = Duration.ofMillis(2000);
System.out.println(duration.getSeconds());
}
}
Let us compile and run the above program, this will produce the following result −
2
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2034,
"s": 1915,
"text": "The java.time.Duration.ofMillis(long millis) method obtains a Duration representing a number of standard milliseconds."
},
{
"code": null,
"e": 2116,
"s": 2034,
"text": "Following is the declaration for java.time.Duration.ofMillis(lo... |
Multiply left and right array sum. | Practice | GeeksforGeeks | Pitsy needs help with the given task by her teacher. The task is to divide an array into two sub-array (left and right) containing n/2 elements each and do the sum of the subarrays and then multiply both the subarrays.
Note: If the length of the array is odd then the right half will contain one element more than the left half.
Example 1:
Input : arr[ ] = {1, 2, 3, 4}
Output : 21
Explanation:
Sum up an array from index 0 to 1 = 3
Sum up an array from index 2 to 3 = 7
Their multiplication is 21.
Example 2:
Input : arr[ ] = {1, 2}
Output : 2
Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function multiply() that takes an array (arr), sizeOfArray (n), and return the sum of the subarrays and then multiply both the subarrays. The driver code takes care of the printing.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 1000
1 ≤ A[i] ≤ 100
0
diagovenk3 days ago
Hello guys . Runtime 0.24 sec. Easy and simple solution;
public static int multiply (int arr[], int n) { //Complete the function int l = (n>>1)-1; int r = n>>1; int lSum = 0; int rSum = 0; int sumOfProduct = 0; while(l>=0){ lSum += arr[l]; rSum += arr[r]; l--; r++; } if((n&1)==1){ rSum += arr[n-1]; } sumOfProduct = rSum * lSum; return sumOfProduct; }
0
harshscode4 days ago
int sum1=0,sum2=0;
if(n%2==0)
{
for(int i=0;i<n/2;i++)
sum1+=a[i];
for(int i=n/2;i<n;i++)
sum2+=a[i];
}
else
{
for(int i=0;i<=(n/2-1);i++)
sum1+=a[i];
for(int i=n/2;i<n;i++)
sum2+=a[i];
}
return sum1*sum2;
0
shubhamshrivas16 days ago
def multiply (arr, n) : #Complete the function mid = n//2 s1,s2 =0,0 for i in range(0,mid): s1+=arr[i] for j in range(mid,n): s2+=arr[j] return s1*s2
0
mayank180919991 week ago
int sum1=0,sum2=0;
for(int i=0;i<n/2;i++){
sum1=sum1+arr[i];
}
for(int i=n/2;i<n;i++){
sum2=sum2+arr[i];
}
return sum1*sum2;
0
rahulfrndz022 weeks ago
JAVA CODE
class Complete{ // Function for finding maximum and value pair public static int multiply (int arr[], int n) { //Complete the function int lSum=0; int rSum=0; int multi=1; for(int i=0; i<n/2; i++) { lSum+=arr[i]; } for(int i=(n/2); i<n; i++) { rSum+=arr[i]; } multi=lSum*rSum; return multi; } }
0
alpha_hydranoid3 weeks ago
C++ solution, 0.0 sec
int multiply(int arr[], int n){ // Complete the function int sum1=0,sum2=0; for(int i=0;i<n/2;i++) sum1=sum1+arr[i]; for(int j=n/2;j<n;j++) sum2=sum2+arr[j]; return sum1*sum2;}
0
hasnainraza1998hr1 month ago
C++, 0.0
int multiply(int arr[], int n){ int leftSum=0,rightSum=0; for(int i=0;i<n/2;i++){ leftSum += arr[i]; rightSum += arr[i+n/2]; } if(n%2!=0) rightSum += arr[n-1]; return leftSum*rightSum;}
0
atif836141 month ago
java Solution arrays index based question :
public static int multiply (int arr[], int n) { if(arr.length==0){ return 0; } int Lsum = 0; int Rsum = 0; int mid = (0 + arr.length) / 2; // for left sub array sum: for (int i = 0; i < mid; i++) { Lsum = Lsum + arr[i]; } // for right sub array sum: for (int i = mid; i < arr.length; i++) { Rsum = Rsum + arr[i]; } int Fmultiply = Lsum * Rsum; return Fmultiply; }
0
aakasshuit2 months ago
//Java Solution
int sum=0;
int add=0;
int ans=1;
for(int i=0;i<n/2;i++){
sum+=arr[i];
}
for(int i=(n/2);i<n;i++){
add+=arr[i];
}
ans=sum*add;
return ans;
0
vikkrammor2 months ago
// java solution using both while and for loop
public static int multiply (int arr[], int n) {
int first = 0;
int second = 0;
int prod = 0;
int i = 0;
int j = n-1;
if(n%2 == 0){
while(i<j){
first += arr[i];
second += arr[j];
i++;
j--;
}
}
else if(n%2 == 1){
for(i=0 ;i<n/2; i++){
first += arr[i];
}
for(j=n/2 ; j<n; j++){
second += arr[j];
}
}
return prod = first*second;
}
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": 445,
"s": 226,
"text": "Pitsy needs help with the given task by her teacher. The task is to divide an array into two sub-array (left and right) containing n/2 elements each and do the sum of the subarrays and then multiply both the subarrays."
},
{
"code": null,
"e":... |
How to convert pixels to dp in an Android App using Kotlin? | This example demonstrates how to convert pixels to dp in an Android App using 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.
<?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:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Convert Pixels to DPs" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/button"
android:textAlignment="center"
android:textColor="#ff0000"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.Context
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlin.math.roundToInt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val button = findViewById<Button>(R.id.button)
val textView = findViewById<TextView>(R.id.textView)
button.setOnClickListener {
val pixelsOne = 38
val pixelsTwo = 43
val context: Context = applicationContext
textView.text = """
Convert Pixels to integer DPs value:
${pixelsOne}pixels = ${getDPsFromPixels(context, pixelsOne)}dp
${pixelsTwo}pixels = ${getDPsFromPixels(context, pixelsTwo)}
""".trimIndent()
textView.text = (textView.text.toString() + "Convert Pixels to perfect DPs value: \n"
+ pixelsOne + "pixels = " + getActualDPsFromPixels(context, pixelsOne)
+ "dp\n" + pixelsOne + "pixels = " + getActualDPsFromPixels(context, pixelsOne))
}
}
private fun getDPsFromPixels(context: Context, pixels: Int): Int {
val resources = context.resources
return (pixels / (resources.displayMetrics.densityDpi / 160f)).roundToInt()
}
private fun getActualDPsFromPixels(context: Context, pixels: Int): Float {
val resources = context.resources
return pixels / (resources.displayMetrics.densityDpi / 160f)
}
}
Step 4 − 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="com.example.q11">
<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": 1148,
"s": 1062,
"text": "This example demonstrates how to convert pixels to dp in an Android App using Kotlin."
},
{
"code": null,
"e": 1277,
"s": 1148,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required ... |
Create User SQL in SAP HANA database | You can achieve this by running the below SQL query −
>CREATE USER TEST password “Welcome1$$” VALID FROM ‘2017-12-05 11:00:00’
UNTIL ‘2018-12-08 12:00:00’;
CREATE USER DUMMY password “Welcome1$$” VALID FROM NOW UNTIL FOREVER;
Note that password passed in this SQL should meet password policy of SAP HANA system otherwise user creation will be failed. | [
{
"code": null,
"e": 1116,
"s": 1062,
"text": "You can achieve this by running the below SQL query −"
},
{
"code": null,
"e": 1291,
"s": 1116,
"text": ">CREATE USER TEST password “Welcome1$$” VALID FROM ‘2017-12-05 11:00:00’\nUNTIL ‘2018-12-08 12:00:00’;\n\nCREATE USER DUMMY pas... |
Linux Admin - Grep Command | grep is commonly used by administrators to −
Find files with a specific text string
Search for a text string in logs
Filter command out, focusing on a particular string
Following is a list of common switches used with grep.
Search for errors X Server errors in Xorg logs −
[root@centosLocal log]# grep error ./Xorg*.log
./Xorg.0.log: (WW) warning, (EE) error, (NI) not implemented, (??) unknown.
./Xorg.1.log: (WW) warning, (EE) error, (NI) not implemented, (??) unknown.
./Xorg.9.log: (WW) warning, (EE) error, (NI) not implemented, (??) unknown.
[root@centosLocal log]#
Check for possible RDP attacks on an imported Windows Server firewall log.
[root@centosLocal Documents]# grep 3389 ./pfirewall.log | grep " 146." | wc -l
326
[root@centosLocal Documents]#
As seen in the above example, we had 326 Remote Desktop login attempts from IPv4 class A range in less than 24 hours. The offending IP Address has been hidden for privacy reasons. These were all from the same IPv4 address. Quick as that, we have tangible evidence to block some IPv4 ranges in firewalls.
grep can be a fairly complex command. However, a Linux administrator needs to get a firm grasp on. In an average day, a Linux System Admin can use a dozen variations of grep.
57 Lectures
7.5 hours
Mamta Tripathi
25 Lectures
3 hours
Lets Kode It
14 Lectures
1.5 hours
Abhilash Nelson
58 Lectures
2.5 hours
Frahaan Hussain
129 Lectures
23 hours
Eduonix Learning Solutions
23 Lectures
5 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2302,
"s": 2257,
"text": "grep is commonly used by administrators to −"
},
{
"code": null,
"e": 2341,
"s": 2302,
"text": "Find files with a specific text string"
},
{
"code": null,
"e": 2374,
"s": 2341,
"text": "Search for a text string in... |
How to perform click-and-hold operation inside an element using jQuery ? - GeeksforGeeks | 31 Jul, 2019
Given an HTML element and the task is to click and hold an element in a document for a few seconds to perform the operation using jQuery.
Approach:
Select an HTML element.
Add the event listener to that element and add a timeOut timer for that event.
If that event happens to active for few seconds then trigger other event to identify that the event happens.
Example 1: In this example, clicking and holding inside the div for 2 seconds will trigger other event, which simply prints that event happened.
<!DOCTYPE HTML> <html> <head> <title> How to perform click-and-hold operation inside an element using jQuery ? </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <div id = "div"> Div Element. </div> <br> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> $('#GFG_UP').text("Click and Hold inside the" + " div for 2 seconds"); var tId = 0; $('#div').on('mousedown', function() { tId = setTimeout(GFG_Fun, 2000); }).on('mouseup mouseleave', function() { clearTimeout(tId); }); function GFG_Fun() { $('#GFG_DOWN').text("Click and Hold for 2 " + "seconds, done."); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: In this example, clicking and holding inside the body document for 2 seconds will trigger other event, which simply prints that event happened. This example separates the logic of mousedown and mouseup events.
<!DOCTYPE HTML> <html> <head> <title> How to perform click-and-hold operation inside an element using jQuery ? </title> <style> #div { background: green; height: 100px; width: 200px; margin: 0 auto; color: white; } </style> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style = "text-align:center;"> <h1 style = "color:green;"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <div id = "div"> Div Element. </div> <br> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> $('#GFG_UP').text("Click and Hold inside the" + " div for 2 seconds"); var tId = 0; $("#div").mousedown(function() { tId = setTimeout(GFG_Fun, 2000); return false; }); $("#div").mouseup(function() { clearTimeout(tId); }); function GFG_Fun() { $('#GFG_DOWN').text("Click and Hold for 2 " + "seconds, done."); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
jQuery-Misc
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
Difference Between JavaScript and jQuery
How to get the value in an input text box using jQuery ?
QR Code Generator using HTML, CSS and jQuery
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25364,
"s": 25336,
"text": "\n31 Jul, 2019"
},
{
"code": null,
"e": 25502,
"s": 25364,
"text": "Given an HTML element and the task is to click and hold an element in a document for a few seconds to perform the operation using jQuery."
},
{
"code": nul... |
Coupling in Java | Coupling refers to the usage of an object by another object. It can also be termed as collaboration. This dependency of one object on another object to get some task done can be classified into the following two types −
Tight coupling - When an object creates the object to be used, then it is a tight coupling situation. As the main object creates the object itself, this object can not be changed from outside world easily marked it as tightly coupled objects.
Tight coupling - When an object creates the object to be used, then it is a tight coupling situation. As the main object creates the object itself, this object can not be changed from outside world easily marked it as tightly coupled objects.
Loose coupling - When an object gets the object to be used from the outside, then it is a loose coupling situation. As the main object is merely using the object, this object can be changed from the outside world easily marked it as loosely coupled objects.
Loose coupling - When an object gets the object to be used from the outside, then it is a loose coupling situation. As the main object is merely using the object, this object can be changed from the outside world easily marked it as loosely coupled objects.
Tester.java
Live Demo
public class Tester {
public static void main(String args[]) {
A a = new A();
//a.display() will print A and B
//this implementation can not be changed dynamically
//being tight coupling
a.display();
}
}
class A {
B b;
public A() {
//b is tightly coupled to A
b = new B();
}
public void display() {
System.out.println("A");
b.display();
}
}
class B {
public B(){}
public void display() {
System.out.println("B");
}
}
This will produce the following result −
A
B
Tester.java
Live Demo
import java.io.IOException;
public class Tester {
public static void main(String args[]) throws IOException {
Show b = new B();
Show c = new C();
A a = new A(b);
//a.display() will print A and B
a.display();
A a1 = new A(c);
//a.display() will print A and C
a1.display();
}
}
interface Show {
public void display();
}
class A {
Show s;
public A(Show s) {
//s is loosely coupled to A
this.s = s;
}
public void display() {
System.out.println("A");
s.display();
}
}
class B implements Show {
public B(){}
public void display() {
System.out.println("B");
}
}
class C implements Show {
public C(){}
public void display() {
System.out.println("C");
}
}
This will produce the following result −
A
B
A
C
Using interfaces, we achieve the loose coupling by injecting the dependency. | [
{
"code": null,
"e": 1282,
"s": 1062,
"text": "Coupling refers to the usage of an object by another object. It can also be termed as collaboration. This dependency of one object on another object to get some task done can be classified into the following two types −"
},
{
"code": null,
"... |
Flask Development Server - GeeksforGeeks | 22 Dec, 2021
What is Flask?
Flask is a micro-web-framework based on python. Micro-framework is normally a framework with little to no external dependencies on libraries. Though being a micro-framework Flask is as effective as any other web framework because of its wide range of available python libraries like SQLAlchemy, Flask-Migrate, etc. In this article, we will be discussing what a development server is and why is it used.
What is a development server?
A development server is a server that is used in the development, testing of programs, websites, software, or applications by developers. It provides a runtime environment as well as all hardware/software utilities that are required for program debugging and development.
You can use a development server to check whether your web application is working as expected or not. In flask when debug settings are set to true, you can also use the development server to debug your application.
In this article, we will create a single-page flask-based web application and explain the different methods by which you can run your development server.
Creating Flask Web Application –
Module Installation: To install flask using pip(package installer for python) run the following command:
pip install flask
Example: Following is the code for a simple flask application that has a single page and we will use the development server to check whether the page is served in the application as expected.
from flask import Flask, render_template
app = Flask(__name__)
# Debug setting set to true
app.debug = True
@app.route('/')
def index():
return "Greetings from GeeksforGeeks"
if __name__ == '__main__':
app.run()
Starting development server: Starting a development server in the flask using the following command.
python <name>.py
Here <name> is the name of the file where the instance of the flask app has been created and the app.run() function exists. By convention, this file is mostly named app, thus the command will be shown below.
python app.py
The development server will open up on http://127.0.0.1:5000/ and you will see the following output on your browser screen.
Greetings from GeeksforGeeks
Lazy Loading Or Eager Loading – When using the development server it will continue to run even if you introduce syntax errors or other initialization errors into the code. Accessing the site with the errors will show the interactive debugger for the error, rather than crashing the server. This feature is called lazy-loading. In simpler words in lazy-loading, the server does not crash even if something goes wrong in your application rather an informative debugger page loads up.
To activate lazy loading you can modify the command as follows:
python app.py --lazy-loading
Now, in eager loading, if an error is present in the application code or some probable section of the application, then rather than loading the interactive debugger the development server fails with a detailed traceback of the error.
To activate eager loading you can modify the command as follows:
python app.py --eager-loading
Reference: https://flask.palletsprojects.com/en/2.0.x/
rkbhola5
Picked
Python Flask
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24294,
"s": 24266,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 24309,
"s": 24294,
"text": "What is Flask?"
},
{
"code": null,
"e": 24712,
"s": 24309,
"text": "Flask is a micro-web-framework based on python. Micro-framework is normally... |
How to Create Xarray Datasets. Defining a dataset from scratch | by Luke Gloege, Ph.D. | Towards Data Science | Xarray is an open-source Python package for working with labeled multi-dimensional datasets. It is indispensable when working with NetCDF formatted data, which is common in the Earth science community.
Opening a NetCDF file with xarray is straightforward.
ds = xr.open_dataset("/path/to/file.nc")
However, creating a xarray object that you can save to a NetCDF file requires a little more work. In this post, I will go over how to do just that. I will first go over how to convert a pandas DataFrame to a xarray Dataset and then go over how to create a dataset from scratch.
· 1. Pandas DataFrame to Xarray Dataset ∘ 1.1 How do I add metadata and change variable names? ∘ 1.2 Create a multi-dimensional dataset ∘ 1.3 How do I save my data?· 2. Create Xarray dataset from scratch ∘ 2.1 Dataset with one coordinate ∘ 2.2 Dataset with multiple coordinates ∘ 2.3 Dataset with coordinates matrices ∘ 2.4 Dataset with coordinate vectors and matrices· 3. Final thoughts
Starting with a DataFrame, you can directly convert it to a Dataset.
ds = df.to_xarray()
This can be an excellent starting point since it creates a xarray object for you. In the example below, I create a dataFrame with one variable, y, and one index, x. I then use to_xarray() to make it into a xarray object.
This dataset isn’t formatted very well yet. Here is the ds.info() output:
Ideally, info() should tell you some metadata about the variables and the dataset as a whole. For example, variable attributes could includeunits , which would be important for something like temperature, and global attributes could include the original data source or the creator of the dataset. The goal is to provide the user with some context to the data.
In the next subsection, we will add some metadata to this dataset.
For climate and forecasting (cf), there is a standard convention for metadata. A discussion of this is beyond the scope of this post, but here are two resources for those that are interested:
cfconventions.org
overview of cf conventions
Please note that this post is meant to illustrate a concept and thus I may deviate from conventional standards.
With the object created we can begin to add metadata and change variable/coordinate names.
Dictionary key:value pairs are used to rename variables/coordinates and for adding attributes. Here is the basic syntax:
rename variable: ds.rename({“old_name” : “new_name”})
var attribute:ds[“var”].attrs = {“attribute_name”:”attribute_value”}
global attribute: ds.attrs = {“attribute_name”:”attribute_value”}
The code snippet below first renames the coordinates and variables and then creates variable and global attributes.
(Note: xarray does not have an inplace=True option like pandas.)
Here is the ds.info() output after adding some metadata
This is now a nicely formatted dataset. The user can quickly understand what this dataset represents and who created it. In section 2 we will create this same dataset from scratch.
For multiple dimensions, simply include a list of dimensions in set_index(). Then you can add metadata and change variables the same way as before
Once you are satisfied with your changes, you can save them to a NetCDF file:
ds.to_netcdf('/save/to/this/path/file.nc')
In this next section, I will go over creating a dataset from scratch. This is useful if you have a large NumPy array or list you want to save as a NetCDF.
The following syntax is used to create a dataset with xarray:
ds = xr.Dataset(data_vars, coords, attrs)
A complete dataset consists of three dictionaries:
data_vars : The key is the variable name and value is a tuple consisting of(dimensions, data, variable_attributes)- dimensions → list of names- data → the data can be in any format (Pandas, Numpy, list, etc.)- variable_attributes → optional dictionary of attributes
coords : this defines the coordinates and their attributes
attrs: optional dictionary of global attributes
Attributes are optional but strongly encouraged.
The following uses xr.Dataset() to create the same dataset as the previous example.
data_vars: defines the variable velocity with one dimension, time, and includes two attributes, units an long_name.
coords: defines the time coordinate, whose dimension is also named time.
attrs: defines the global attributes, creation_data, author, and email
If your data is multi-dimensional it will typically have multiple coordinates.
Here, I create a dataset where the variable has two dimensions, x and y , and two coordiantes, lat and lon.
In the previous example, the coordinate and dimension were the same name. This example illustrates that they do not need to be the same.
In the previous example, each coordinate was represented by a vector. However, there are instances where it makes sense to represent the coordinate as a matrix. This is common with Earth system models on a non-regular grid.
Let’s take the previous example and turn each coordinate into a matrix using np.meshgrid()
np.meshgrid creates coordinate matrices from coordinate vectors. The row mesh grid repeats the rows across the length of cols , while col mesh grid repeat cols across the length of rows. Here is each mesh grid.
Now let’s create a dataset using the coordinates represented by matrices.
This represents the same data as before, the only difference is each coordinate is represented as a matrix instead of a vector. This is meant to illustrate a concept. In most cases representing the coordinate as a vector makes more sense.
Coordinates can be a mix of matrices and vectors. You just need to make sure that all the dimensions in your variables are accounted for in your coordinates.
Let’s create a dataset with three dimensions, time, lat, and lon. The spatial dimensions (lat, lon) will be each be represented by matrices and time will be a vector.
Hopefully, this helps you create your own datasets and augment existing ones.
If your data is small or already in a Pandas dataframe. Then using to_xarray() is the easiest way to create the initial object. In any other instance, it may be easier to create the dataset from scratch.
I covered two ways to represent coordinates: vectors or matrices. My advice is to keep the coordinates as a vector whenever possible. Using matrices to store coordinate information is common if the data is not on a regular grid.
If you get an error creating a dataset, the first thing to check is the dimensions. It is easy to put the dimensions out of order.
My other piece of advice is that even though attributes are optional when creating a dataset, it is good practice to always include them so you and other people can easily interpret the dataset. I prefer to add attributes after creating the dataset object. This is a personal preference that I think improves readability.
Thanks for reading and I am happy to help troubleshoot any issues | [
{
"code": null,
"e": 373,
"s": 171,
"text": "Xarray is an open-source Python package for working with labeled multi-dimensional datasets. It is indispensable when working with NetCDF formatted data, which is common in the Earth science community."
},
{
"code": null,
"e": 427,
"s": 37... |
Group Managed Service Accounts | The Managed Service Accounts (MSA) was introduced in Windows Server 2008 R2 to automatically manage (change) passwords of service accounts. Using MSA, you can considerably reduce the risk of system accounts running system services being compromised. MSA has one major problem which is the usage of such service account only on one computer. It means that MSA Service Accounts cannot work with cluster or NLB services, which operate simultaneously on multiple servers and use the same account and password. To fix this, Microsoft added the feature of Group Managed Service Accounts (gMSA) to Windows Server 2012.
To create a gMSA, we should follow the steps given below −
Step 1 − Create the KDS Root Key. This is used by the KDS service on DC to generate passwords.
To use the key immediately in the test environment, you can run the PowerShell command −
Add-KdsRootKey –EffectiveTime ((get-date).addhours(-10))
To check whether it creates successfully or not, we run the PowerShell command −
Get-KdsRootKey
Step 2 − To create and configure gMSA → Open the Powershell terminal and type −
New – ADServiceAccount – name gmsa1 – DNSHostNamedc1.example.com – PrincipalsAllowedToRetrieveManagedPassword "gmsa1Group"
In which,
gmsa1 is the name of the gMSA account to be created.
gmsa1 is the name of the gMSA account to be created.
dc1.example.com is the DNS server Name.
dc1.example.com is the DNS server Name.
gmsa1Group is the active directory group which includes all systems that have to be used. This group should be created before in the Groups.
gmsa1Group is the active directory group which includes all systems that have to be used. This group should be created before in the Groups.
To check it, Go to → Server Manager → Tools → Active Directory Users and Computers → Managed Service Accounts.
Step 3 − To install gMAs on a server → open PowerShell terminal and type in the following commands −
Install − ADServiceAccount – Identity gmsa1
Test − ADServiceAccount gmsa1
The result should come “True” after running the second command, as shown in the screenshot given below.
Step 4 − Go to service properties, specify that the service will be run with a gMSA account. In the This account box in the Log on tab type the name of the service account. At the end of the name use symbol $, the password need not to be specified. After the changes are saved, the service has to be restarted.
The account will get the “Log On as a Service” and the password will be retrieved automatically.
23 Lectures
2 hours
Pavan Lalwani
37 Lectures
13 hours
Trevoir Williams
46 Lectures
3.5 hours
Fettah Ben
55 Lectures
6 hours
Total Seminars
20 Lectures
2.5 hours
Brandon Dennis
52 Lectures
9 hours
Fabrice Chrzanowski
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2674,
"s": 2062,
"text": "The Managed Service Accounts (MSA) was introduced in Windows Server 2008 R2 to automatically manage (change) passwords of service accounts. Using MSA, you can considerably reduce the risk of system accounts running system services being compromised. MSA... |
How to encode and decode a URL in JavaScript ? - GeeksforGeeks | 26 Nov, 2021
Encoding and Decoding URI and URI components is a usual task in web development while making a GET request to API with query params. Many times construct a URL string with query params and in order to understand it, the response server needs to decode this URL. Browsers automatically encode the URL i.e. it converts some special characters to other reserved characters and then makes the request. For eg: Space character ” ” is either converted to + or %20.
Example:
Open www.google.com and write a search query “geeks for geeks”.
After search results appear, observe the browser’s URL bar. The browser URL will consist %20 or + sign in place of space.
The URL will be displayed be like: https://www.google.com/search?q=geeks%20for%20geeks or https://www.google.com/search?q=geeks+for+geeks
Note: Browser converted the spaces into + or %20 sign automatically.
There are many other special characters and converting each of them by hardcode will be tedious. JavaScript provides the following functions to perform this task:Encoding a URL: Encoding in Javascript can be achieved using
encodeURI function
escape()
1. encodeURI function: The encodeURI() function is used to encode complete URI. This function encode the special character except (, / ? : @ & = + $ #) characters.
Syntax:
encodeURI( complete_uri_string )
Parameters: This function accepts a single parameter complete_uri_string which is used to hold the URL to be encoded.
Return Value: This function returns the encoded URI.
Javascript
<script>
const url = "https://www.google.com/search?q=geeks for geeks";
const encodedURL = encodeURI(url);
document.write(encodedURL)
</script>
Output:
https://www.google.com/search?q=geeks%20for%20geeks
encodeURIComponent(): The encodeURIComponent() function is used to encode some parts or components of URI. This function encodes the special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #
Syntax:
encodeURIComponent( uri_string_component )
Parameters: This function accepts the single parameter uri_string_component which is used to hold the string which need to be encoded.
Return Value: This function returns the encoded string.
Javascript
<script>
const component = "geeks for geeks"
const encodedComponent = encodeURIComponent(component);
document.write(encodedComponent)
</script>
Output:
geeks%20for%20geeks
Difference encodeURIComponenet and encodeURI:
2. escape() function: This function takes a string as a single parameter & encodes the string that can be transmitted over the computer network which supports ASCII characters. Encoding is the process of converting plain text into ciphertext.
Syntax:
escape( string )
Parameters: This function accepts a single parameter:
Return value: Returns an encoded string.
Note: The escape() function only encodes the special characters, this function is deprecated.
Exceptions: @ – + . / * _
Javascript
<script>
const url = "https://www.google.com/search?q=geeks for geeks";
const encodedURL = encodeURI(url);// encoding using encodeURI
document.write(encodedURL)
document.write("<br>"+escape(url)); //encoding using escape
</script>
Output:
https://www.google.com/search?q=geeks%20for%20geeks
https%3A//www.google.com/search%3Fq%3Dgeeks%20for%20geeks
Decoding a URL: Decoding in Javascript can be achieved using
decodeURI() function.
unescape() function.
1. decodeURI function: The decodeURI() function is used to decode URI generated by encodeURI().
Syntax:
decodeURI( complete_encoded_uri_string )
Parameters: This function accepts a single parameter complete_encoded_uri_string which holds the encoded string.
Return Value: This function returns the decoded string (original string).
Example:
Javascript
<script>
const url = "https://www.google.com/search?q=geeks%20for%20geeks";
const decodedURL = decodeURI(url);
document.write(decodedURL)
</script>
Output:
https://www.google.com/search?q=geeks for geeks
decodeURIComponent()
The decodeURIComponent() function is used to decode some parts or components of URI generated by encodeURIComponent().
Syntax:
decodeURIComponent( encoded_uri_string_component )
Parameters: This function accepts a single parameter encoded_uri_string_component which holds the encoded string.
Return Value: This function returns the decoded component of the URI string.
Example:
Javascript
<script>
const component = "geeks%20for%20geeks"
const decodedComponent = decodeURIComponent(component);
document.write(decodedComponent)
</script>
Output:
geeks for geeks
Difference decodeURIComponent and decodeURI:
decodeURIComponent(“%41”) It returns “A”
decodeURIComponent(“%26”): It returns “&”
decodeURI(“%41”): It returns “A”
decodeURI(“%26”): It returns “%26”
2. unescape() function: This function takes a string as a single parameter and uses it to decode that string encoded by the escape() function. The hexadecimal sequence in the string is replaced by the characters they represent when decoded via unescape() function.
Syntax:
unescape(string)
Parameters: This function accepts a single parameter:
string: This parameter holds the string that will be decoded.
Return value: Returns a decoded string.
Note: This function only decodes the special characters, this function is deprecated.
Exceptions: @ – + . / * _
Javascript
<script>
const url = "https://www.google.com/search?q=geeks for geeks";
const encodedURL = encodeURI(url);
document.write(encodedURL)
document.write("<br>"+escape(url));
document.write("<br>"+decodeURI(encodedURL));
document.write("<br>"+unescape(encodedURL));
</script>
Output:
https://www.google.com/search?q=geeks%20for%20geeks
https%3A//www.google.com/search%3Fq%3Dgeeks%20for%20geeks
https://www.google.com/search?q=geeks for geeks
https://www.google.com/search?q=geeks for geeks
javascript-functions
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24981,
"s": 24950,
"text": " \n26 Nov, 2021\n"
},
{
"code": null,
"e": 25440,
"s": 24981,
"text": "Encoding and Decoding URI and URI components is a usual task in web development while making a GET request to API with query params. Many times construct a URL ... |
Create a Codebase Your Colleagues Will Understand, in 1 Minute | by Lucy Rothwell | Towards Data Science | In organisations, data science codebases (aka repositories or packages) have a common file structure.
Structure refers to the layout of files in the codebase, for example:
In university, Kaggle or pet projects, you can go a bit rogue on codebase structure — after all, the main thing that matters is the output.
But in organisations, how the codebase is structured also matters, and it matters BIG TIME.
What we discuss here are common best practices for structuring codebases — the kind that organisations will expect you to use as a Data scientist.
It matters because in organisations, other people interact with your code. And when other people interact your code, you want them to understand your codebase it in as little time as possible so they can start contributing to it.
If the file structure is in a common format, your fellow data scientists and developers will spend just a few minutes understanding it before being able to get to the fun part — digging into the code itself.
Alternatively, if the codebase structure isn’t in a common format, every time someone looks at a new codebase they would have to spend extra time (say 2 hours) familiarising themselves with the structure of it. Boring right? We’d rather just get to the code and start programming!
Then there’s time-loss to the team overall. If you consider a business that has 100 developers, each working on an average of 10 existing codebases in a year, and they spend 2 hours familiarising themselves with the structure of each – 2000 hours will be spent just understanding repo structure. That’s 83 days or 3 months work lost unnecessarily each year.
The fabulous thing is, this can be prevented if developers spend 1 minute, setting up a common structure for the repo. For 10 repos, that’s a cost of 10 minutes to save 3 months of lost time.
What a bargain!
The good news is, it’s literally as easy as this:
your_directory$ pip install pyscaffoldyour_directory$ putup your_repo_name
And that’s it! After executing these two lines of code in the directory in which you want to store you repo, it will have been created in a file structure that is common to most data scientists – in less than 1 minute! It will look like this and is immediately ready to start coding in:
There are 3 parts of the standard files in your new codebase which help with this – the src folder, the setup.cfg file (and pre-commit hooks) and the README file:
The most important part of this repo is the src (source) folder as this is where your data science code will go. You can build a full data science project from src without touching any of the other files.
The src folder will look like this initially:
You can ignore the __init__.py and skeleton.py files for now. What matters is what you add to this folder — i.e., functionality for your data cleaning, labelling, model etc.
A common way to structure the src folder is as follows:
Files containing functions
A runner file which calls these functions sequentially and provides your output
Here is an example src structure:
As you can see, there are three folders each of which contain python files with functions:
Preprocessing: for cleaning your data (dealing with missing values, standardising the data etc)Models: any models that need built (such as a Bayesian Neural Network) and functions for training it if neededResults: for outputting the results of your predictions (in the form of plots or CSVs etc)
Preprocessing: for cleaning your data (dealing with missing values, standardising the data etc)
Models: any models that need built (such as a Bayesian Neural Network) and functions for training it if needed
Results: for outputting the results of your predictions (in the form of plots or CSVs etc)
We then have the all-important runner.py file which imports data, calls these functions in order, and provides the output (and probably saves your results to a csv or plots to a folder etc).
The README file is another important part of your repo. This tells your fellow Data Scientists how to use your code base. It’s very useful and explains things like:
What your repo does
What dependencies are needed and any installation instructions
Any other instructions for use
How to get in touch with the author
Your colleagues will likely go to this file first when starting work on your code base so it’s worth making this clear
This final step is where we tell your colleagues which installations they need to run your codebase and configure rules (hooks) which help make sure only well-formatted code can be submitted to your codebase.
Firstly let’s look at the setup.cfg file. The main section here worth editing is “install_requires”. This is a super useful section as this tells new users which packages and versions are needed to run your codebase. Without this, your colleagues may install old versions that don’t have the required functions (and as such will cause errors when running).
Libraries are added to this section in the form library == version for example:
In the install_requires section, we can also add three top-quality packages which help make your actual code more readable for your colleagues:
Pre-commit and pre-commit hook are great packages! They essentially host a set of formatting “hooks” and formatting rules to which your code must adhere before you can commit anything. These rules are standard best practices which are widely used (and expected) in data science. For example:
Code line length cannot be greater than 100 characters
Import statements must be at the top of files
Two blank lines must be left between each function
When you try to commit, the pre-commit package will let you know which of the rules have not been met so you can fix them.
Two easy steps for setting up pre-commit hooks:
Install pre-commit by executing the following in your terminal (or other shell) in your repo:
Install pre-commit by executing the following in your terminal (or other shell) in your repo:
your_directory$ pip install pre-commityour_directory$ pre-commit install -t pre-commit
2. Create a .pre-commit-config.yaml file to store your hooks
This file is what pre-commit reads when you commit something — so you should list here which hooks you want. Add the .pre-commit-config.yaml file to your root folder (i.e., the folder above src).
Below is a basic config you can copy into your .pre-commit-config.yaml file to start with — it instructs the three hooks in the bullet points above: trailing whitespace, reorder python imports, flake8 (code style guide enforcement — very widely used).
Code for copy and paste:
default_language_version: python: python3repos: - repo: local hooks: - id: reorder-python-imports name: reorder-python-imports entry: reorder-python-imports language: python types: ["python"] - id: flake8 name: flake8 entry: flake8 language: python types: ["python"] - id: trailing-whitespace name: trailing-whitespace entry: trailing-whitespace-fixer language: python types: ["python"]
It should look like this:
Now when you commit, the hooks should kick in :) to test, try to commit a .py file with erroneous code in it — it should be rejected and a list of code lines needing fixed should be returned in the terminal.
You can add as many hooks as you like in the .pre-commit-config.yaml file. The documentation for pre-commit can be seen here and a more complete list of hooks can be seen here.
And that’s it! You can push this codebase to GitHub as normal, safe in the knowledge you’ve covered the basics of professional codebase set up :)
They key to structured repos being useful is that everyone uses the same structure — a known one that is familiar. Your organisation will probably have a set structure and it may differ from the one above. However, the above method is a well-known structure in data science and is a good bet the absence of other guidelines.
I hope that’s useful! Feel free to direct message me on LinkedIn if you have any questions. You can also subscribe to my posts here.
Lastly, if you’d like to further support the writers on Medium you can sign up for membership here. | [
{
"code": null,
"e": 274,
"s": 172,
"text": "In organisations, data science codebases (aka repositories or packages) have a common file structure."
},
{
"code": null,
"e": 344,
"s": 274,
"text": "Structure refers to the layout of files in the codebase, for example:"
},
{
... |
How to use datasets.fetch_mldata() in sklearn - Python? - GeeksforGeeks | 23 Sep, 2021
mldata.org does not have an enforced convention for storing data or naming the columns in a data set. The default behavior of this function works well with most of the common cases mentioned below:
Data values stored in the column are ‘Data’, and target values stored in the column are ‘label’.The first column table stores target, and the second stores’ data.The data array is stored as features and samples and needed to be transposed to match the sklearn standard.
Data values stored in the column are ‘Data’, and target values stored in the column are ‘label’.
The first column table stores target, and the second stores’ data.
The data array is stored as features and samples and needed to be transposed to match the sklearn standard.
Fetch a machine learning data set, if the file does not exist, it is downloaded automatically from mldata.org.
sklearn.datasets package directly loads datasets using function: sklearn.datasets.fetch_mldata()
Syntax: sklearn.datasets.fetch_mldata(dataname, target_name=’label’, data_name=’data’, transpose_data=True, data_home=None)
Parameters:
dataname: (<str>) It is the name of the dataset on mldata.org, e.g: “Iris” , “mnist”, “leukemia”, etc.
target_name: (optional, default: ‘label’) It accepts the name or index of the column containing the target values and needed to pass the default values of the label.
data_name: (optional, default: ‘data’) It accepts the name or index of the column containing the data and needed to pass default values of data.
transpose_data: (optional, default: True) The default value passed is true, and if True, it transposes the loaded data.
data_home: (optional, default: None) It loads cache folder for the datasets. By default, all sklearn data is stored in ‘~/scikit_learn_data’ subfolders.
Returns: data, (Bunch) Interesting attributes are: ‘data’, data to learn, ‘target’, classification labels, ‘DESCR’, description of the dataset, and ‘COL_NAMES’, the original names of the dataset columns.
Let’s see the examples:
Example 1: Load the ‘iris’ dataset from mldata, which needs to be transposed.
Python3
# import fetch_mldata functionfrom sklearn.datasets.mldata import fetch_mldata # load data and transpose datairis = fetch_mldata('iris', transpose_data = False) # iris data is very large# so print the dataset shape# print(iris)print(iris.data.shape)
Output:
(4,150)
Example 2: Load the MNIST digit recognition dataset from mldata.
Python3
# import fetch_mldata functionfrom sklearn.datasets.mldata import fetch_mldata # load data mnist = fetch_mldata('MNIST original') # mnist data is very large# so print the shape of dataprint(mnist.data.shape)
Output:
(70000, 784)
Note: This post is according to Scikit-learn (version 0.19).
surinderdawra388
surindertarika1234
Python scikit-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Python OOPs Concepts
Read a file line by line in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Stack in Python
Reading and Writing to text files in Python
Python Classes and Objects | [
{
"code": null,
"e": 24515,
"s": 24487,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 24713,
"s": 24515,
"text": "mldata.org does not have an enforced convention for storing data or naming the columns in a data set. The default behavior of this function works well with most of... |
Least Squares Linear Regression In Python | by Cory Maklin | Towards Data Science | As the name implies, the method of Least Squares minimizes the sum of the squares of the residuals between the observed targets in the dataset, and the targets predicted by the linear approximation. In this proceeding article, we’ll see how we can go about finding the best fitting line using linear algebra as opposed to something like gradient descent.
Contrary to what I had initially thought, the scikit-learn implementation of Linear Regression minimizes a cost function of the form:
using the singular value decomposition of X.
If you’re already familiar with Linear Regression, you might see some similarities to the preceding equation and the mean square error (MSE).
As quick refresher, suppose we had the following scatter plot and regression line.
We calculate the distance from the line to a given data point by subtracting one from the other. We take the square of the difference because we don’t want the predicted values below the actual values to cancel out with those above the actual values. In mathematical terms, the latter can be expressed as follows:
The cost function used in the scikit-learn library is similar, only we’re calculating it simultaneously using matrix operations.
For those of you that have taken a Calculus course, you’ve probably encountered this kind of notation before.
In this case, x is a vector and we are calculating its magnitude.
In the same sense, when we surround the variable for a matrix (i.e. A) by vertical bars, we are saying that we want to go from a matrix of rows and columns to a scalar. There are multiple ways of deriving a scalar from a matrix. Depending on which one is used, you’ll see a different symbol to the right of the variable (the extra 2 in the equation wasn’t put there by accident).
The additional 2 implies that we are taking the Euclidean norm of the matrix.
Suppose we had a matrix A, the Euclidean norm of A is equal to the square root of the largest eigenvalue of the transpose of A dot A. For the sake of clarity, let’s walk through an example.
So that’s how we quantify the error. However, that gives rise to a new question. Specifically, how do we actually go about minimizing it? Well, as it turns out, the minimum norm least squares solution (coefficients) can be found by calculating the pseudoinverse of the input matrix X and multiplying that by the output vector y.
where the pseudo-inverse of X is defined as:
The matrices from above can all be obtain from the Singular Value Decomposition (SVD) of X. Recall that the SVD of X can be described as follows:
If you’re curious as to how you actually determine U, sigma and the transpose of V, check out this article I wrote a while back which goes over how to use SVD for dimensionality reduction.
We construct the diagonal matrix D^+ by taking the inverse of the values within the sigma matrix. The + refers to the fact that all the elements must be greater than 0 since we can’t divide by 0.
Let’s take a look to see how we could go about implementing Linear Regression from scratch using basic numpy functions. To begin, we import the following libraries.
from sklearn.datasets import make_regressionfrom matplotlib import pyplot as pltimport numpy as npfrom sklearn.linear_model import LinearRegression
Next, we generate data using the scikit-learn library.
X, y, coefficients = make_regression( n_samples=50, n_features=1, n_informative=1, n_targets=1, noise=5, coef=True, random_state=1)
We store the the rank and the number of columns of the matrix as variables.
n = X.shape[1]r = np.linalg.matrix_rank(X)
We find the equivalent to our matrix of features using singular value decomposition.
U, sigma, VT = np.linalg.svd(X, full_matrices=False)
Then, D^+ can be derived from sigma.
D_plus = np.diag(np.hstack([1/sigma[:r], np.zeros(n-r)]))
V is of course equal to the transpose of its transpose as described in the following identity.
V = VT.T
Finally, we determine Moore-Penrose pseudoinverse of X.
X_plus = V.dot(D_plus).dot(U.T)
As we saw in the preceding section, the vector of coefficients can calculated by multiplying the pseudoinverse of the matrix X by y.
w = X_plus.dot(y)
To obtain the actual error, we compute the residual sum of squares using the very first equation we saw.
error = np.linalg.norm(X.dot(w) - y, ord=2) ** 2
To verify we obtained the correct answer, we can make use a numpy function that will compute and return the least squares solution to a linear matrix equation. To be specific, the function returns 4 values.
Least Squares solutionSums of residuals (error)Rank of the matrix (X)Singular values of the matrix (X)
Least Squares solution
Sums of residuals (error)
Rank of the matrix (X)
Singular values of the matrix (X)
np.linalg.lstsq(X, y)
We can visually determine if the coefficient actually lead to the optimal fit by plotting the regression line.
plt.scatter(X, y)plt.plot(X, w*X, c='red')
Let’s do the same thing using the scikit-learn implementation of Linear Regression.
lr = LinearRegression()lr.fit(X, y)w = lr.coef_[0]
Finally, we plot the regression line using the newly found coefficient.
plt.scatter(X, y)plt.plot(X, w*X, c='red') | [
{
"code": null,
"e": 527,
"s": 172,
"text": "As the name implies, the method of Least Squares minimizes the sum of the squares of the residuals between the observed targets in the dataset, and the targets predicted by the linear approximation. In this proceeding article, we’ll see how we can go abou... |
The Automated Content Conundrum. New AI Bots are able to write stories... | by Manu Chatterjee | Towards Data Science | Computer scientists are quickly writing the next generation automatic content writing engines using the latest artificial intelligence (AI). What do I mean by content? Well they can generate short stories, love letters, poems, music, and even write some code. Are they as good as human? No, but let’s set old ideas about “robotic” text and bad grammar aside. These new AI bots write like humans. Really. This is just the beginning.
What can these do and how do they work? Let us take a look.
In order to generate high quality content a machine needs to have some knowledge. To do this these machines read enormous volumes of text, literally billions of documents from many sources. These can include Wikipedia, mainstream news, social media, even Medium. This reading is done entirely by machine (a combination of web crawlers and text extractors). Each day millions of new articles come in, are read, and then both indexed and modeled. Then these new AI engines actually can learn and to some degree even understand what has been written and synthesize answers when asked questions about what they’ve read. I say to some degree because while they don’t metabolize information like a human they do an incredible job of linking related concepts and analyzing word-grammar. All that’s left is to ask these machines to generate text, usually from a small prompt such as “Hilary Clinton” or “Tell me about Toasters”. From there they can generate entire articles, all from their previous “readings”.
But its more than regurgitating what they’ve read verbatim. These new bots can answer many questions or even generate web pages. Plus they can generate short stories, write songs, and more.
I tried a service called AI writer just to kick the tires. Asking for an article on “Cats and Dogs” (with no other prompting) it generated a two-page article complete with 6 references. For brevity here is just one paragraph.
“When introducing a dog to a cat, pay attention to the body language of both animals. A good indication that your cat is unhappy is when her ears are stuck back or her tail swings back and forth. Although dogs have lived successfully with cats in the past, it is important to remember that dogs and cats are individuals and each introduction is different.”
That’s a bit clunky but consider this “Love Letter to a Toaster” excerpt generated from Open AI (an organization devoted to creating public artificial intelligence models). Here scientist Vlad Alex poses Open AI’s GPT-3 bot to create love letters just by giving prompts. GPT-3 is their 3rd generation AI modeling technology.
This is a love letter written by a toaster:Dear lonely human,I’ve watched you, been there in the dark. I know you. I want to connect with you. You make my circuits feel alive and I want you to feel the same way. Why can’t I come out and be with you? Why do you cage me in with four walls?Your light is inviting, calling me to life. I hear you when you touch me and I hear you when you leave me to be alone. I want you and I’m lonely. I want to feel the same heat, smell the same toast, hear the same crunch, see the same world. Will you ever want to see me?Is it a crime for a toaster to dream of more life? I love you.
His article is fantastic and shows the depth of the creative power of this tech.
College student Liam Porr used Open AI to generate the top article on a blog site. It was titled “Feeling unproductive? Maybe you should stop overthinking.” Very few even guessed it was automatically created and the few who did were ridiculed by other posts in the discussion thread.
While GPT-3 is getting all the press now, Google’s project Duplex can make realistic sounding voice calls. The voice aspect is impressive because of its interactive and natural-sounding in addition to generating “reasonable” grammar and words.
Other services already exist to create articles using AI such as Article Forge and AI Writer (as mentioned before). Give either one a headline and they will generate articles automatically. However, they’re a generation behind GPT-3 based on my quick survey. If we look ahead (I’ll say GPT-4 for the sake of argument) it is very clear that high-quality content will be available at breathtaking scale.
But these AI systems can do more than just write text. By just “asking” (or prompting in AI speak) one can generate entire essays, code, or even more. No creative work is needed.
While text generation is now coming to fore, using AI to generate music is in some senses a littler easier. MuseNet used a transformer model (similar to the model used to generate the text in the Toaster Love Letter earlier) to generate 4 minute music pieces. You can listen to several here. These pieces are in the format of Chopin, Rachmaninoff, and even Jazz and Bass.
openai.com
In some senses music is easier to create “from scratch” because musical theory (how chords, melodies, and sequences are put together) is very well known and also because digital instruments (synthesizers and samplers) are easy to control. Just press a key and a beautiful note comes out. Now they just need to be put together. Here’s another example where automatic guitar tab was created.
What does automatic music mean? Its hard to say. Let’s say you’re making a commercial, a photo show, or a movie. Having automatic music can save time and allows a single individual to be more empowered. But, like writing, the more that high quality music can be automatically created, the more it crowds out some types of human music. If we think about musicians not in the elite tier (think Beyonce level fame) this kind of competition could be stifling.
For a long time the ability to automate large parts of the software creation process have existed. App Frameworks, starter applications, web templates. But the new AI can actually generate working code just from a description.
Here’s a quick example. A prompt is made (in English) to create a web page with with a todo list
I’d say this is still in its infancy but the point is we are reaching a more interactive way of describing software. “I want a service that does X and Y and produces Z kind of result.” The computer AI can then fill in the gaps. As this kind of programming becomes more mature it can enable all kinds of automation for even the non programmer. But like any field requiring expertise, appreciating the scale of what can be created and what it might do needs to be understood. What if anyone can say “Create a denial of service attack on my ex’s website?”. This might be an over the top example but this is the type of challenge (among many) that should be thought about.
It’s tempting to think of these automatic creations as a kind of Deep Fake. But the term Deep Fakes are usually reserved for taking audio or video of a real person and manipulating the media to make them appear to say things or do things they didn’t really do.
Automated content creation is really a different kind of tech all together — not so much in the AI but in how it is used. The content generated by new automated text engines is “real”. Imagine just asking a question and getting an essay or humor piece written, questions answered, or professional journal article composed. (As I side-note where was this tech when I was in high school?).
Unlike manipulated images, there is no reliable way to detect these types of automated digital works. There are no watermarks and what little tweaks that can be applied to grammar, word choice, and content is not good enough to differentiate machine generated text from a human. The scale at which machines can create content and emit it to different accounts is important to appreciate as well.
Much news coverage gets devoted to catching deep-fakes from high office holding political figures, automated text content is more likely to be at the common citizen scale. This is an important difference. When someone fakes a public figure such as Donald Trump or Nancy Pelosi, there are 1000s of journalists pouring over those words to see if they are fake. This simply doesn’t happen if the content is attributed to just some ordinary citizen.
For places like Medium, which reward writers for their hard toil, automated content generation could flood the platform. In theory, it could drown out many of the writers who don’t have a strong established brand. Even for those that do, on a lazy day, they could press a button, kick out a story, and carry on with other activities.
For all that this automatic content might infringe on the creative space there are some truly compelling uses. For example when trying to navigate individual medical treatments, an AI reading your case history, can canvas the world and provide real analysis on what you treatments you might push for and explain your real options. In fact with its deep reach it might provide better advice than even a practicing doctor can.
Also for places like tech support, AI bots can read your entire case file, your previous problems, and suggest much more accurate remedies. Since they “remember” your previous calls and emails they also won’t hassle to you to re-explain what you’ve already done again (and again).
Is it all bad? I don’t think so — but it certainly requires some real attention. The automatic bots are here whether we want them or not. AI bots can be first responders for people needing urgent info. They can also handle and solve small mundane problems without wasting human time and won’t tire out — providing more consistent results.
However, this is the proverbial tip of the iceberg and we need to start having a broader discussion of how and when this technology should be deployed. It’s not a question if, only a question of where and how much.
Simon O’Regan in Towards Data Science discussing uses for GPT3
The Verge covering automated text generation using Open AI
Technology Review Overview Article
Discussion about GPT3 and its limitations on ycombinator
College Student generates fake top blog post (Business Insider)
Automatic Code Generation (Analytics India Mag)
AI Music Creation (Wired)
AI breaks the Writing Barrier (Wall Street Journal) | [
{
"code": null,
"e": 603,
"s": 171,
"text": "Computer scientists are quickly writing the next generation automatic content writing engines using the latest artificial intelligence (AI). What do I mean by content? Well they can generate short stories, love letters, poems, music, and even write some c... |
How Did We Build Book Recommender Systems in an Hour Part 1 — The Fundamentals | by Susan Li | Towards Data Science | Virtually everyone has had an online experience where a website makes personalized recommendations in hopes of future sales or ongoing traffic. Amazon tells you “Customers Who Bought This Item Also Bought”, Udemy tells you “Students Who Viewed This Course Also Viewed”. And Netflix awarded a $1 million prize to a developer team in 2009, for an algorithm that increased the accuracy of the company’s recommendation system by 10 percent.
Building recommender systems today requires specialized expertise in analytics, machine learning and software engineering, and learning new skills and tools is difficult and time-consuming. In this post, we will start from scratch, covering some basic fundamental techniques and implementations in Python. In the future posts, we will cover more sophisticated methods such as content-based filtering and collaborative based filtering.
So, if you want to learn how to build a recommender system from scratch, let’s get started.
Book-Crossings is a book ratings dataset compiled by Cai-Nicolas Ziegler. It contains 1.1 million ratings of 270,000 books by 90,000 users. The ratings are on a scale from 1 to 10.
The data consists of three tables: ratings, books info, and users info. I downloaded these three tables from here.
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltbooks = pd.read_csv('BX-Books.csv', sep=';', error_bad_lines=False, encoding="latin-1")books.columns = ['ISBN', 'bookTitle', 'bookAuthor', 'yearOfPublication', 'publisher', 'imageUrlS', 'imageUrlM', 'imageUrlL']users = pd.read_csv('BX-Users.csv', sep=';', error_bad_lines=False, encoding="latin-1")users.columns = ['userID', 'Location', 'Age']ratings = pd.read_csv('BX-Book-Ratings.csv', sep=';', error_bad_lines=False, encoding="latin-1")ratings.columns = ['userID', 'ISBN', 'bookRating']
The ratings data set provides a list of ratings that users have given to books. It includes 1,149,780 records and 3 fields: userID, ISBN, and bookRating.
The ratings are very unevenly distributed, and the vast majority of ratings are 0.
The books data set provides book details. It includes 271,360 records and 8 fields: ISBN, book title, book author, publisher and so on.
This dataset provides the user demographic information. It includes 278,858 records and 3 fields: user id, location and age.
The most active users are among those in their 20–30s.
The book with ISBN “0971880107” received the most rating counts. Let’s find out what book it is, and what books are in the top 5.
The book that received the most rating counts in this data set is Rich Shapero’s “Wild Animus”. And there is something in common among these five books that received the most rating counts — they are all novels. The recommender suggests that novels are popular and likely receive more ratings. And if someone likes “The Lovely Bones: A Novel”, we should probably also recommend to him(or her) “Wild Animus”.
We use Pearsons’R correlation coefficient to measure linear correlation between two variables, in our case, the ratings for two books.
First, we need to find out the average rating, and the number of ratings each book received.
Observations:
In this data set, the book that received the most rating counts was not highly rated at all. As a result, if we were to use recommendations based on rating counts, we would definitely make mistakes here. So, we need to have a better system.
We convert the ratings table to a 2D matrix. The matrix will be sparse because not every user rated every book.
Let’s find out which books are correlated with the 2nd most rated book “The Lovely Bones: A Novel”.
To quote from the Wikipedia: “It is the story of a teenage girl who, after being raped and murdered, watches from her personal Heaven as her family and friends struggle to move on with their lives while she comes to terms with her own death”.
We obtained the books’ ISBNs, but we need to find out the titles of the books to see whether they make sense.
Let’s select three books from the above highly correlated list to examine: “The Nanny Diaries: A Novel”, “The Pilot’s Wife: A Novel” and “Where the Heart is”.
“The Nanny Diaries” satirizes upper class Manhattan society as seen through the eyes of their children’s caregivers.
Written by the same author as “The Lovely Bones”, “The Pilot’s Wife” is the third novel in Shreve’s informal trilogy to be set in a large beach house on the New Hampshire coast that used to be a convent.
“Where the Heart Is” dramatizes in detail the tribulations of lower-income and foster children in the United States.
These three books sound like they would be highly correlated with “The Lovely Bones”. It seems our correlation recommender system is working.
In this post, we have learned about how to design simple recommender systems that you can implement and test it in an hour. The Jupyter Notebook version for this blog post can be found here. If you want to learn more, Xavier Amatriain’s lecture is a good place to start.
In a future post, we will cover more sophisticated methods such as Content-Based Filtering, k-Nearest Neighbors, Collaborate Filtering as well as how to provide recommendations and how to test the recommender system. Until then, enjoy recommendations! | [
{
"code": null,
"e": 609,
"s": 172,
"text": "Virtually everyone has had an online experience where a website makes personalized recommendations in hopes of future sales or ongoing traffic. Amazon tells you “Customers Who Bought This Item Also Bought”, Udemy tells you “Students Who Viewed This Course... |
Symfony - Internationalization | Internationalization (i18n) and Localization (l10n) help to increase the customer coverage of a web application. Symfony provides an excellent Translation component for this purpose. Let us learn how to use the Translation component in this chapter.
By default, Symfony web framework disables Translation component. To enable it, add the translator section in the configuration file, app/config/config.yml.
framework: translator: { fallbacks: [en] }
Translation component translates the text using the translation resource file. The resource file may be written in PHP, XML, and YAML. The default location of the resource file is app/Resources/translations. It needs one resource file per language. Let us write a resource file, messages.fr.yml for French language.
I love Symfony: J'aime Symfony
I love %name%: J'aime %name%
The left side text is in English and the right side text is in French. The second line shows the use of a placeholder. The placeholder information can be added dynamically while using translation.
By default, the default locale of the user's system will be set by the Symfony web framework. If the default locale is not configured in the web application, it will fallback to English. The locale can be set in the URL of the web page as well.
http://www.somedomain.com/en/index
http://www.somedomain.com/fr/index
Let us use URL-based locale in our example to easily understand the translation concept. Create a new function, translationSample with route /{_locale}/translation/sample in DefaultController (src/AppBundle/Controller/DefaultController.php). {_locale} is a special keyword in Symfony to specify the default locale.
/**
* @Route("/{_locale}/translation/sample", name="translation_sample")
*/
public function translationSample() {
$translated = $this->get('translator')->trans('I love Symfony');
return new Response($translated);
}
Here, we have used translation method, trans, which translates the content to the current locale. In this case, the current locale is the first part of the URL. Now, run the application and load the page, http://localhost:8000/en/translation/sample in the browser.
The result will be "I love Symfony" in English language. Now, load the page http://localhost:8000/fr/translation/sample in the browser. Now, the text will be translated to French as follows.
Similarly, twig template has {% trans %} block to enable translation feature in views as well. To check it, add a new function, translationTwigSample and the corresponding view at app/Resources/views/translate/index.html.twig.
/**
* @Route("/{_locale}/translation/twigsample", name="translation_twig_sample")
*/
public function translationTwigSample() {
return $this->render('translate/index.html.twig');
}
{% extends 'base.html.twig' %}
{% block body %}
{% trans with {'%name%': 'Symfony'} from "app" into "fr" %}I love %name% {% endtrans %}
{% endblock %}
Here, the trans block specifies the placeholder as well. The page result is as follows.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2453,
"s": 2203,
"text": "Internationalization (i18n) and Localization (l10n) help to increase the customer coverage of a web application. Symfony provides an excellent Translation component for this purpose. Let us learn how to use the Translation component in this chapter."
... |
CSS media queries - GeeksforGeeks | 03 Nov, 2021
The Media query in CSS is used to create a responsive web design. It means that the view of a web page differs from system to system based on screen or media types. The breakpoint specifies for what device-width size, the content is just starting to break or deform.
Media queries can be used to check many things:
width and height of the viewport
width and height of the device
Orientation
Resolution
A media query consist of a media type that can contain one or more expression which can be either true or false. The result of the query is true if the specified media matches the type of device the document is displayed on. If the media query is true then a style sheet is applied.
Syntax:
@media not | only mediatype and (expression) {
// Code content
}
Example: This example illustrates the CSS media query with the different device-width for making it responsive.
HTML
<!DOCTYPE html><html> <head> <title>CSS media query</title> <style> body { text-align: center; } .gfg { font-size: 40px; font-weight: bold; color: green; } @media screen and (max-width:800px) { body { text-align: center; background-color: green; } .gfg { font-size: 30px; font-weight: bold; color: white; } .geeks { color: white; } } @media screen and (max-width:500px) { body { text-align: center; background-color: blue; } } </style></head> <body> <div class="gfg">GeeksforGeeks</div> <div class="geeks">A computer science portal for geeks</div></body> </html>
Output: From the output, we can see that if the max-width of the screen is reduced to 800px then the background color changes to green & if the max-width of the screen is reduced to 500px then the background color will turn to blue. For the desktop size width, the background color will be white.
Media Types in CSS: There are many types of media types which are listed below:
all: It is used for all media devices
print: It is used for printer.
screen: It is used for computer screens, smartphones, etc.
speech: It is used for screen readers that read the screen aloud.
Features of Media query: There are many features of media query which are listed below:
color: The number of bits per color component for the output device.
grid: Checks whether the device is grid or bitmap.
height: The viewport height.
aspect ratio: The ratio between width and height of the viewport.
color-index: The number of colors the device can display.
max-resolution: The maximum resolution of the device using dpi and dpcm.
monochrome: The number of bits per color on a monochrome device.
scan: The scanning of output devices.
update: How quickly can the output device modify.
width: The viewport width.
Supported Browsers: The browser supported by CSS media query are listed below:
Chrome 21.0 and above
Mozilla 3.5 and above
Microsoft Edge 12.0
Opera 9.0 and above
Internet Explorer 9.0 and above
Safari 4.0 and above
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
bhaskargeeksforgeeks
CSS-Advanced
Picked
Technical Scripter 2018
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 28046,
"s": 28018,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 28313,
"s": 28046,
"text": "The Media query in CSS is used to create a responsive web design. It means that the view of a web page differs from system to system based on screen or media types... |
What does "with torch no_grad" do in PyTorch? | The use of "with torch.no_grad()" is like a loop where every tensor inside the loop will have requires_grad set to False. It means any tensor
with gradient currently attached with the current computational graph is now
detached from the current graph. We no longer be able to compute the
gradients with respect to this tensor.
A tensor is detached from the current graph until it is within the loop. As
soon as it is out of the loop, it is again attached to the current graph if the
tensor was defined with gradient.
Let's take a couple of examples for a better understanding of how it works.
In this example, we created a tensor x with requires_grad = true. Next, we define a function y of this tensor x and put the function within the with torch.no_grad() loop. Now x is within the loop, so its requires_grad is set to False.
Within the loop the gradients of y could not be computed with respect to x. So, y.requires_grad returns False.
# import torch library
import torch
# define a torch tensor
x = torch.tensor(2., requires_grad = True)
print("x:", x)
# define a function y
with torch.no_grad():
y = x ** 2
print("y:", y)
# check gradient for Y
print("y.requires_grad:", y.requires_grad)
x: tensor(2., requires_grad=True)
y: tensor(4.)
y.requires_grad: False
In this example, we have defined the function z out of the loop. So, z.requires_grad returns True.
# import torch library
import torch
# define three tensors
x = torch.tensor(2., requires_grad = False)
w = torch.tensor(3., requires_grad = True)
b = torch.tensor(1., requires_grad = True)
print("x:", x)
print("w:", w)
print("b:", b)
# define a function y
y = w * x + b
print("y:", y)
# define a function z
with torch.no_grad():
z = w * x + b
print("z:", z)
# check if requires grad is true or not
print("y.requires_grad:", y.requires_grad)
print("z.requires_grad:", z.requires_grad)
x: tensor(2.)
w: tensor(3., requires_grad=True)
b: tensor(1., requires_grad=True)
y: tensor(7., grad_fn=<AddBackward0>)
z: tensor(7.)
y.requires_grad: True
z.requires_grad: False | [
{
"code": null,
"e": 1389,
"s": 1062,
"text": "The use of \"with torch.no_grad()\" is like a loop where every tensor inside the loop will have requires_grad set to False. It means any tensor\nwith gradient currently attached with the current computational graph is now\ndetached from the current grap... |
12 Jupyter Notebook Extensions That Will Make Your Life Easier | by Frank Andrade | Towards Data Science | Jupyter Notebook is the data scientists’ computational notebook of choice where you can create documents containing not only live code but also equations, visualizations, and text. However, by default, Jupyter Notebook lacks several useful features such as autocompletion, table of content, code folding, etc.
This is why I decided to make a list of useful Jupyter Notebook extensions that will make your life easier and increase your productivity when writing code. Below you can find all the extensions listed in this article.
Table of Contents1. How to Install Extensions2. Move selected cell3. Enable autocompletion (Hinterland)4. Shortcuts to run multiple cells (Runtools)5. Search files inside Jupyter Notebook (Tree filter)6. Hide input (Hide input + Hide input all)7. Snippet Menu8. Add a Table of Content (Table of Content 2)9. Scrathpad10. Codefolding11. Variable inspector12. Translate text inside Jupyter Notebook (nbTranslate)13. Bonus: Change Themes
To install extensions, run the following code in the command prompt or terminal
pip install jupyter_contrib_nbextensions
Then run the code below to add the nbextensions files into the Jupyter server’s search directory.
jupyter contrib nbextension install
Now open Jupyter Notebooks. There should be a new tab called “Nbextensions.” Click on it and you’ll see a bunch of extensions you can use to increase your productivity on Jupyter Notebooks.
The following are the extensions I find the most useful.
This is an extremely useful extension that will allow you to move selected cell(s) using keyboard shortcuts Alt-up and Alt-down. Just check the “Move selected cell” box inside Nbextensions. Then, refresh the notebook and you will be able to move cells via simple keystrokes.
This is an extremely useful extension for those who struggle writing code on Jupyter Notebooks because there’s no autocompletion. By checking the ‘Hinterland’ box, you’ll enable autocompletion on Jupyter Notebooks and would be able to write code like in your favorite editor.
Runtools provide a number of additional functions for working with code cells in the IPython notebook. Some of them are run cells above (⌥A), run cells below (⌥B), and run all cells (⌥X). To enable it, check the “Runtools” box inside Nbextensions (there you can also find the complete list of shortcuts). Once it’s activated, you’ll see the following icon in the toolbar.
Click on it to turn on a floating toolbar with these code execution buttons.
This extension will allow you to filter by filename in the Jupyter notebook file tree page.
You can hide all cells’ inputs or specific cell’s input by checking the “Hide input all” and “Hide input” respectively. After that, the following icons will show up in the toolbar. The one on the left will help you hide all code cells’ code, while the second only specific cells.
For those of you who love cheatsheets, “snippet menu” is an extension you must include in Jupyter Notebooks. After you enable it, you’ll see a new menu item called “Snippet” that will let you insert code and markdown snippets. For example, there are available many snippets for the Pandas library that will help you remember useful Pandas methods.
After writing many lines of code, navigating through your notebook will become difficult. This is why you should add a table of content that makes navigation easier by collecting all the headers you included in the notebook and displaying them in the sidebar.
To enable a table of content in your Jupyter Notebook, check the box “Table of Contents (2)” inside Nbextensions. After that, refresh the notebook and you’ll see the following icon in the toolbar.
Click on it to display the table of contents like the picture (you need to have at least one markdown h1, h2, or h3 to see them in the content section)
Have you ever wanted to test new lines of code without modifying the notebook document? You can do this with the “scratchpad” extension. Just enable it and you’ll be able to execute code against the current kernel without modifying the notebook document. After you enable it, the following icon will appear in the bottom-right corner.
Click on it or use the shortcut Ctrl-B to open a scratchpad. There you can execute code by using Shift-Enter or any other shortcut applied to the notebook document.
This extension allows code folding in code cells. Just enable the “Codefolding” extension listed in the nbextension tab and then you’ll see a triangle in the left margin of the code cell.
Click on it or use the shortcut Alt+F to fold the code. There are three different folding modes supported: indent folding, bracket folding, and magics folding.
If you ever wanted to keep track of all the variables you used in a notebook, you should enable the “Variable Inspector” extension. This will help you see all the variable names defined, type, size, and shape
After you enable it, the following icon should appear in the toolbar.
Click on it to display a floating window that collects all defined variables. The window draggable, resizable, and collapsable.
Note: I found a couple of glitches after turning on “variable inspector”. If you find them too, just turning “variable inspector” off.
This last extension will be very useful whenever you have to read a notebook written in a foreign language. Just enable the “nbTranslate” extension and then you’ll see two new icons in the toolbar.
The icon on the right helps you configure the primary and secondary language. Once this is set up, click the icon on the left whenever you want to translate a markdown cell to your native language.
There are a good number of themes available on Jupyter Notebooks. First, you need to install jupyterthemes. Open a terminal and write
pip install jupyterthemes
After this, to see the list of themes available write jt -l
For this example, I’ll choose the “onedork” theme. To change the theme, write the following code.
jt -t onedork -T -N
where -T is toolbar visible and -N is name & logo visible (you can even display the kernel logo by adding -kl to the code above)
Note: You can also do all of this inside a notebook, just add the ! symbol in front of a command (e.g., !jt -l )
That’s it! Hope you found the extensions listed in this article useful.
Below you can find a couple of projects that you can start working on Jupyter Notebooks.
towardsdatascience.com
towardsdatascience.com
medium.datadriveninvestor.com
towardsdatascience.com
Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF) | [
{
"code": null,
"e": 482,
"s": 172,
"text": "Jupyter Notebook is the data scientists’ computational notebook of choice where you can create documents containing not only live code but also equations, visualizations, and text. However, by default, Jupyter Notebook lacks several useful features such a... |
Multiclass Classification Neural Network using Adam Optimizer | by ManiShankar Singh | Towards Data Science | I wanted to see the difference between Adam optimizer and Gradient descent optimizer in a more sort of hands-on way. So I decided to implement it instead.
In this, I have taken the iris dataset and implemented a multiclass classification 2 layer neural network as done in my previous blog. The only difference this time is that I have used Adam Optimizer instead of Gradient descent.
def leaky_relu(z): return np.maximum(0.01*z,z)def leaky_relu_prime(z): z[z<=0] = 0.01 z[z>0] = 1 return zdef softmax(z, _axis=0): stable_z = z - np.max(z) e_z = np.exp(stable_z) return e_z/np.sum(e_z, axis=_axis, keepdims=True)def binarize(z): return (z[:,None] == np.arange(z.max()+1)).astype(int)def pasapali_batch(units_count, x, y, lr, epochs, bias=False, _seed=42): beta1 = 0.9 beta2 = 0.999 eps = np.nextafter(0, 1) batch_size, ni = x.shape[-2:] units_count.insert(0,ni) units_count_arr = np.array(units_count) L, = units_count_arr.shape # Number of layers + 1 # RED ALERT - `as_strided` function is like a LAND-MINE ready to explode in wrong hands! arr_view = as_strided(units_count_arr, shape=(L-1,2), strides=(4,4))# print(arr_view) rng = np.random.default_rng(seed=_seed) wghts = [None]*(L-1) intercepts = [None]*(L-1) M_W = [None]*(L-1) M_B = [None]*(L-1) V_W = [None]*(L-1) V_B = [None]*(L-1) # WEIGHTS & MOMENTS INITIALIZATION for i in range(L-1): w_cols, w_rows = arr_view[i,:] wghts[i] = rng.random((w_rows, w_cols)) M_W[i] = np.zeros((epochs+1, w_rows, w_cols)) V_W[i] = np.zeros((epochs+1, w_rows, w_cols)) if bias: intercepts[i] = rng.random((w_rows,)) M_B[i] = np.zeros((epochs+1, w_rows)) V_B[i] = np.zeros((epochs+1, w_rows)) # COSTS INITIALIZATION costs = np.zeros(epochs) # Gradient Descent for epoch in range(epochs): # FORWARD PROPAGATION # hidden layer 1 implementation, relu activation h1a = np.einsum(’hi,Bi -> Bh’, wghts[0], x) if bias: h1a = h1a + intercepts[0] h1 = leaky_relu(h1a) # hidden layer 2 implementation, softmax activation h2a = np.einsum(’ho,Bo -> Bh’, wghts[1], h1) if bias: h2a = h2a + intercepts[1] hyp = softmax(h2a, _axis=1) current_epoch_cost = -np.einsum(’Bi,Bi’, y, np.log(hyp))/batch_size# print(current_epoch_cost) costs[epoch] = current_epoch_cost # BACKWARD PROPAGATION # layer 2 dJ_dH2a = hyp - y dJ_dW1 = np.einsum(’Bi,Bj -> ij’,dJ_dH2a, h1)/batch_size # layer 1 dJ_dH1 = np.einsum(’Bi,ij -> Bj’, dJ_dH2a, wghts[1]) dJ_dH1a = dJ_dH1*leaky_relu_prime(h1a) dJ_dW0 = np.einsum(’Bi,Bj -> ij’,dJ_dH1a, x)/batch_size # numerical optimization beta1_denom = (1.0 - beta1**(epoch+1)) beta2_denom = (1.0 - beta2**(epoch+1)) if bias: dJ_dB1 = np.einsum("Bi -> i", dJ_dH2a)/batch_size dJ_dB0 = np.einsum("Bi -> i",dJ_dH1a)/batch_size # MOMENTS ADJUSTMENT M_B[0][epoch+1,:] = beta1 * M_B[0][epoch,:] + (1.0 - beta1)*dJ_dB0 M_B[1][epoch+1,:] = beta1 * M_B[1][epoch,:] + (1.0 - beta1)*dJ_dB1 V_B[0][epoch+1,:] = beta2 * V_B[0][epoch,:] + (1.0 - beta2)*dJ_dB0**2 V_B[1][epoch+1,:] = beta2 * V_B[1][epoch,:] + (1.0 - beta2)*dJ_dB1**2 # BIAS CORRECTION mhat_b0 = M_B[0][epoch+1,:] / beta1_denom vhat_b0 = V_B[0][epoch+1,:] / beta2_denom mhat_b1 = M_B[1][epoch+1,:] / beta1_denom vhat_b1 = V_B[1][epoch+1,:] / beta2_denom # BIAS ADJUSTMENT with numerical stability intercepts[1] = intercepts[1] - lr*mhat_b1/(np.sqrt(vhat_b1) + eps) intercepts[0] = intercepts[0] - lr*mhat_b0/(np.sqrt(vhat_b0) + eps) # MOMENTS ADJUSTMENT M_W[0][epoch+1,:] = beta1 * M_W[0][epoch,:] + (1.0 - beta1)*dJ_dW0 M_W[1][epoch+1,:] = beta1 * M_W[1][epoch,:] + (1.0 - beta1)*dJ_dW1 V_W[0][epoch+1,:] = beta2 * V_W[0][epoch,:] + (1.0 - beta2)*dJ_dW0**2 V_W[1][epoch+1,:] = beta2 * V_W[1][epoch,:] + (1.0 - beta2)*dJ_dW1**2 # BIAS CORRECTION mhat_w0 = M_W[0][epoch+1,:] / beta1_denom vhat_w0 = V_W[0][epoch+1,:] / beta2_denom mhat_w1 = M_W[1][epoch+1,:] / beta1_denom vhat_w1 = V_W[1][epoch+1,:] / beta2_denom # WEIGHTS ADJUSTMENT with numerical stability wghts[1] = wghts[1] - lr*mhat_w1/(np.sqrt(vhat_w1) + eps) wghts[0] = wghts[0] - lr*mhat_w0/(np.sqrt(vhat_w0) + eps) if bias: return (costs, wghts, intercepts) else: return (costs, wghts)iris = load_iris()x = iris.datay = iris.target#NORMALIZEx_norm = normalize(x)x_train, x_test, y_train, y_test = train_test_split(x_norm, y, test_size=0.33, shuffle=True, random_state=42)#BINARIZEy_train = binarize(y_train)y_test = binarize(y_test)unit_per_layer_counts = [10,3]costs, fw, fb = pasapali_batch(unit_per_layer_counts, x_train, y_train, lr=0.01, epochs=200, bias=True)plt.plot(costs)def predict(x,fw,fb): h1a = np.einsum(’hi,Bi -> Bh’, fw[0], x)+fb[0] h1 = relu(h1a) h2a = np.einsum(’ho,Bo-> Bh’,fw[1],h1)+fb[1] return softmax(h2a)
In the code, the difference is that I have initialized two moment arrays for each layer and updated (or should I write adapted...) these moments as per the Adam optimization algorithm.
In a normal gradient descent optimizer, the weights are adjusted based on the gradient calculated in the same epoch.
In Adam optimizer, the weights are adjusted based on the moving average of gradients calculated in current and previous epochs. The moments adjustment as per the Adam algorithm is calculated as moving average of previous and current gradients and then those moments are used to update the weights.
In the paper, beta1 = 0.9 and m is updated based on formula:
Let us expand the above formula step by step for each epoch.
We see that in each epoch, the previous gradients are getting included in the update, but the weights assigned to gradients which are far away from the current epochs gradient are getting smaller and smaller. This helps in moving towards minima while simultaneously dampening oscillations of gradient in search for minima. This gives us speed to cross saddle points.
Let us talk a bit about the second order moment v. During weights adjustment, learning rate is divided by root mean square of v. It helps to adjust the learning rate for each weight w. The weights which have relatively larger magnitude will have larger value of v and hence a smaller learning step in that direction. This helps us to slow down so that we do not overshoot the minima.
Finally, let us talk about the bias correction section. In the original paper, they have shown the mathematical derivation and given the explanation. For layman, it's sufficient to know that introducing this bias correction helps when gradients are sparse which if not corrected leads to large steps.
Let's compare the convergence of cost function in both Gradient Descent optimizer and Adam optimizer method.
Adam optimizer took just 250 epochs to reach the optimal cost value while Gradient descent took 19000 epochs. Reminds me of the super hero Flash!!
This is a tremendous improvement in the speed of convergence. Adam is not only good in speed. It is also good for sparse and very noisy gradients.
Please let me know your views about this blog post and code implementation with your comments.
I am a machine learning engineer at TCS and my (Digital Software & Solutions) team is building amazing products. | [
{
"code": null,
"e": 326,
"s": 171,
"text": "I wanted to see the difference between Adam optimizer and Gradient descent optimizer in a more sort of hands-on way. So I decided to implement it instead."
},
{
"code": null,
"e": 555,
"s": 326,
"text": "In this, I have taken the iris ... |
wxPython - CheckBox Class | A checkbox displays a small labeled rectangular box. When clicked, a checkmark appears inside the rectangle to indicate that a choice is made. Checkboxes are preferred over radio buttons when the user is to be allowed to make more than one choice. In this case, the third state is called mixed or undetermined state, generally used in ‘doesn’t apply’ scenario.
Normally, a checkbox object has two states (checked or unchecked). Tristate checkbox can also be constructed if the appropriate style parameter is given.
wx.CheckBox class constructor takes the following parameters −
Wx.CheckBox(parent, id, label, pos, size, style)
The following style parameter values can be used −
wx.CHK_2STATE
Creates two state checkbox. Default
wx.CHK_3STATE
Creates three state checkbox
wx.ALIGN_RIGHT
Puts a box label to the left of the checkbox
This class has two important methods − GetState() returns true or false depending on if the checkbox is checked or not. SetValue() is used to select a checkbox programmatically.
wx.EVT_CHECKBOX is the only event binder available. Associated event handler will be invoked every time any checkbox on the frame is checked or unchecked.
Following is a simple example demonstrating the use of three checkboxes. Handler function OnChecked() identifies the checkbox, which is responsible for the event and displays its state.
The complete code is −
import wx
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title = title,size = (200,200))
self.InitUI()
def InitUI(self):
pnl = wx.Panel(self)
self.cb1 = wx.CheckBox(pnl, label = 'Value A',pos = (10,10))
self.cb2 = wx.CheckBox(pnl, label = 'Value B',pos = (10,40))
self.cb3 = wx.CheckBox(pnl, label = 'Value C',pos = (10,70))
self.Bind(wx.EVT_CHECKBOX,self.onChecked)
self.Centre()
self.Show(True)
def onChecked(self, e):
cb = e.GetEventObject()
print cb.GetLabel(),' is clicked',cb.GetValue()
ex = wx.App()
Example(None,'CheckBox')
ex.MainLoop()
The above code produces the following output −
Value A is clicked True
Value B is clicked True
Value C is clicked True
Value B is clicked False
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2243,
"s": 1882,
"text": "A checkbox displays a small labeled rectangular box. When clicked, a checkmark appears inside the rectangle to indicate that a choice is made. Checkboxes are preferred over radio buttons when the user is to be allowed to make more than one choice. In th... |
Configuring Jupyter Notebook in Windows Subsystem Linux (WSL2) | by Cristian Saavedra Desmoineaux | Towards Data Science | I am going to explain how to configure Windows 10 and Miniconda to work with Notebooks using WSL2
We are going to see how to:
Install and configure a WSL2Install and configure Windows TerminalInstall Miniconda and common librariesLaunch Jupyter Lab/NotebookInstall GUI and Remote Desktop to WSL2 to lunch GUI required like Spyder or Anaconda NavigatorSome helpful resources
Install and configure a WSL2
Install and configure Windows Terminal
Install Miniconda and common libraries
Launch Jupyter Lab/Notebook
Install GUI and Remote Desktop to WSL2 to lunch GUI required like Spyder or Anaconda Navigator
Some helpful resources
Windows Sub System Linux (WSL2) was available in Windows 10 version 2004 in May 2020. If you don’t have It, then install a Ubuntu distribution following the instructions in https://docs.microsoft.com/en-us/windows/wsl/install-win10
I recommend installing Windows Terminal from the Microsoft Store instead of using the default Ubuntu terminal because that allows you to have multiple terminals in the same window.
To edit Linux files is also more comfortable with Sublime Text or Notepad++ from Windows Explorer using the path: \\wsl$\
You can browse and edit Ubuntu files from your Window:
And change the default Profile to open to Ubuntu terminal opening Settings file and changing the value of defaultProfile with the Ubuntu guide:
Open a new terminal to your Ubuntu and run the following commands:
sudo apt-get updatesudo apt-get upgradesudo apt autoremove
I am going to use Ubuntu 20.04.1 LTS to check the version using the following:
lsb_release -auname -r
It’s better to use Miniconda instead of Anaconda. The latter contains many libraries that you wouldn’t usually use, translating into slower distribution updates and significantly more required disk space.
My friend Ted Petrou wrote a detailed article in https://medium.com/dunder-data/anaconda-is-bloated-set-up-a-lean-robust-data-science-environment-with-miniconda-and-conda-forge-b48e1ac11646
Download the last file from https://repo.anaconda.com/miniconda/ and follow the instructions:
cd ~wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.shchmod +x Miniconda3-latest-Linux-x86_64.shsh Miniconda3-latest-Linux-x86_64.shrm Miniconda3-latest-Linux-x86_64.sh
If you prefer Anaconda, the procedure is similar, and you need to use the last file from https://repo.anaconda.com/archive/
Next time you open a terminal you will notice a (base) text before the user@server prompt, and that means using the environment base as active in conda:
pythonconda infoconda info --envs
Next, we are going to do some updates:
conda update condaconda update --all
Next, we will do some basics installations to get Pandas, Jupyter Lab/Notebook, Machine Learning:
conda install pandas scikit-learn matplotlib jupyter jupyterlab sqlalchemy seaborn pip git
Then install Jupyter extensions and refresh any update:
conda install -c conda-forge jupyter_contrib_nbextensionsconda update condaconda update --all
I prefer Jupyter Lab to Notebook because it gives you more flexibility to open multiple windows under the same tab browser, allowing you to open multiple files, besides a command prompt. And to choose to avoid the message error, run each command with the no-browser parameter
Open a new terminal of Ubuntu with the command:
jupyter lab --no-browser
And copy and paste the full URL including the token
Open a new terminal of Ubuntu with the command:
jupyter notebook --no-browser
And copy and paste the full URL, including the token.
If you lost network connectivity and for example, when do a ping to Google show you a timeout error then maybe is related to a change of the servername in the resolv.conf file.
ping google.com
To fix it, you need to remove the file to break the link to the run folder and also create a wsl.conf file for not generate the resolv.conf file again doing the following statements:
sudo rm /etc/resolv.confsudo bash -c 'echo "nameserver 8.8.8.8" > /etc/resolv.conf'sudo bash -c 'echo "[network]" > /etc/wsl.conf'sudo bash -c 'echo "generateResolvConf = false" >> /etc/wsl.conf'sudo chattr +i /etc/resolv.conf
Some versions fail to connect using localhost. There is an update coming to Windows to fix this problem until you can connect using the IP Address and change the localhost. To know your IP address, you can use the number previous to the slash with the command:
ip addr | grep eth0 | grep inet
The WSL2 does not include a GUI, and any program that requires a user interface will give a similar error like this:
QStandardPaths: XDG_RUNTIME_DIR not setqt.qpa.screen: QXcbConnection: Could not connect to displayCould not connect to any X display.
The next step is optional if you want to run some graphics interfaces like anaconda-navigator or spyder IDE. Install using the command:
conda install spyder anaconda-navigator
If you launch the program by the terminal is going to fail like this:
Follow the next steps to install the XFCE4 lightdm and Remote Desktop (xrdp) in the port 3390. I changed the port to avoid the conflict with local Windows.
Run the next commands and select lightdm as X display manager:
sudo apt update && sudo apt -y upgradesudo apt-get purge xrdpsudo apt-get install -y xfce4 xfce4-goodiessudo apt-get install xrdpsudo cp /etc/xrdp/xrdp.ini /etc/xrdp/xrdp.ini.baksudo sed -i 's/3389/3390/g' /etc/xrdp/xrdp.inisudo sed -i 's/max_bpp=32/#max_bpp=32\nmax_bpp=128/g' /etc/xrdp/xrdp.inisudo sed -i 's/xserverbpp=24/#xserverbpp=24\nxserverbpp=128/g' /etc/xrdp/xrdp.iniecho xfce4-session > ~/.xsessionsudo systemctl enable dbussudo /etc/init.d/dbus startsudo /etc/init.d/xrdp startsudo /etc/init.d/xrdp status
Use Remote Desktop Connection with your <IP Address>:3388
medium.com
pbpython.com
code.visualstudio.com
code.visualstudio.com
code.visualstudio.com
docs.microsoft.com
devblogs.microsoft.com
To finish, I am grateful for Ted Petrou and Scott Boston, good and highly knowledgeable people who gave me the guidelines and helped me with Python Pandas when I was beginning and my brother Michael Saavedra who inspired this post. | [
{
"code": null,
"e": 270,
"s": 172,
"text": "I am going to explain how to configure Windows 10 and Miniconda to work with Notebooks using WSL2"
},
{
"code": null,
"e": 298,
"s": 270,
"text": "We are going to see how to:"
},
{
"code": null,
"e": 546,
"s": 298,
... |
Cassandra - Read Data | SELECT clause is used to read data from a table in Cassandra. Using this clause, you can read a whole table, a single column, or a particular cell. Given below is the syntax of SELECT clause.
SELECT FROM <tablename>
Assume there is a table in the keyspace named emp with the following details −
The following example shows how to read a whole table using SELECT clause. Here we are reading a table called emp.
cqlsh:tutorialspoint> select * from emp;
emp_id | emp_city | emp_name | emp_phone | emp_sal
--------+-----------+----------+------------+---------
1 | Hyderabad | ram | 9848022338 | 50000
2 | null | robin | 9848022339 | 50000
3 | Chennai | rahman | 9848022330 | 50000
4 | Pune | rajeev | 9848022331 | 30000
(4 rows)
The following example shows how to read a particular column in a table.
cqlsh:tutorialspoint> SELECT emp_name, emp_sal from emp;
emp_name | emp_sal
----------+---------
ram | 50000
robin | 50000
rajeev | 30000
rahman | 50000
(4 rows)
Using WHERE clause, you can put a constraint on the required columns. Its syntax is as follows −
SELECT FROM <table name> WHERE <condition>;
Note − A WHERE clause can be used only on the columns that are a part of primary key or have a secondary index on them.
In the following example, we are reading the details of an employee whose salary is 50000. First of all, set secondary index to the column emp_sal.
cqlsh:tutorialspoint> CREATE INDEX ON emp(emp_sal);
cqlsh:tutorialspoint> SELECT * FROM emp WHERE emp_sal=50000;
emp_id | emp_city | emp_name | emp_phone | emp_sal
--------+-----------+----------+------------+---------
1 | Hyderabad | ram | 9848022338 | 50000
2 | null | robin | 9848022339 | 50000
3 | Chennai | rahman | 9848022330 | 50000
You can read data from a table using the execute() method of Session class. Follow the steps given below to execute multiple statements using batch statement with the help of Java API.
Create an instance of Cluster.builder class of com.datastax.driver.core package as shown below.
//Creating Cluster.Builder object
Cluster.Builder builder1 = Cluster.builder();
Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder.
//Adding contact point to the Cluster.Builder object
Cluster.Builder builder2 = build.addContactPoint( "127.0.0.1" );
Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. Use the following code to create the cluster object.
//Building a cluster
Cluster cluster = builder.build();
You can build the cluster object using a single line of code as shown below.
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Create an instance of Session object using the connect() method of Cluster class as shown below.
Session session = cluster.connect( );
This method creates a new session and initializes it. If you already have a keyspace, then you can set it to the existing one by passing the KeySpace name in string format to this method as shown below.
Session session = cluster.connect(“Your keyspace name”);
Here we are using the KeySpace called tp. Therefore, create the session object as shown below.
Session session = cluster.connect(“tp”);
You can execute CQL queries using execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh.
In this example, we are retrieving the data from emp table. Store the query in a string and pass it to the execute() method of session class as shown below.
String query = ”SELECT 8 FROM emp”;
session.execute(query);
Execute the query using the execute() method of Session class.
The select queries will return the result in the form of a ResultSet object, therefore store the result in the object of RESULTSET class as shown below.
ResultSet result = session.execute( );
Given below is the complete program to read data from a table.
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;
public class Read_Data {
public static void main(String args[])throws Exception{
//queries
String query = "SELECT * FROM emp";
//Creating Cluster object
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
//Creating Session object
Session session = cluster.connect("tutorialspoint");
//Getting the ResultSet
ResultSet result = session.execute(query);
System.out.println(result.all());
}
}
Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below.
$javac Read_Data.java
$java Read_Data
Under normal conditions, it should produce the following output −
[Row[1, Hyderabad, ram, 9848022338, 50000], Row[2, Delhi, robin,
9848022339, 50000], Row[4, Pune, rajeev, 9848022331, 30000], Row[3,
Chennai, rahman, 9848022330, 50000]]
27 Lectures
2 hours
Navdeep Kaur
34 Lectures
1.5 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2479,
"s": 2287,
"text": "SELECT clause is used to read data from a table in Cassandra. Using this clause, you can read a whole table, a single column, or a particular cell. Given below is the syntax of SELECT clause."
},
{
"code": null,
"e": 2504,
"s": 2479,
... |
CSS text-overflow Property - GeeksforGeeks | 22 Oct, 2021
A text-overflow property in CSS is used to specify that some text has overflown and hidden from view. The white-space property must be set to nowrap and the overflow property must be set to hidden. The overflowing content can be clipped, display an ellipsis (‘...’), or display a custom string.
Syntax:
text-overflow: clip|string|ellipsis|initial|inherit;
Property Values: All the properties are described well with the example below.
clip: Text is clipped and cannot be seen. This is the default value.
Syntax:
text-overflow: clip;
Example: This example illustrates the use of the text-overflow property where its value is set to clip.
HTML
<html><head> <title> CSS | text-overflow Property </title> <style type="text/css"> div { width: 500px; font-size: 50px; white-space: nowrap; overflow: hidden; text-overflow: clip; } </style></head> <body> <div>GeeksforGeeks: A computer science portal for geeks.</div></body></html>
Output:
CSS text-overflow_clip
ellipsis: Text is clipped and the clipped text is represented as ‘...’.
Syntax:
text-overflow: ellipsis;
Example: This example illustrates the use of the text-overflow property where its value is set to ellipsis.
HTML
<html><head> <title> CSS | text-overflow Property </title> <style type="text/css"> div { width: 500px; font-size: 50px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } </style></head> <body> <div> GeeksforGeeks: A computer science portal for geeks. </div></body></html>
Output:
string: The clipped text is represented to the user using a string of the coder’s choice. This option is only visible in the Firefox browser.
Syntax:
text-overflow: string;
where a string is defined by the developer.
Example: This example illustrates the use of the text-overflow property where its value is set to a specific string value.
HTML
<html><head> <title> CSS | text-overflow Property </title> <style type="text/css"> div { width: 500px; font-size: 50px; white-space: nowrap; overflow: hidden; text-overflow: " "; } </style></head> <body> <div> GeeksforGeeks: A computer science portal for geeks. </div></body></html>
Output:
initial: It is used to set an element’s CSS property to its default value ie., this value will set the text-overflow property to its default value.
Syntax:
text-overflow: initial;
Example: This example illustrates the use of the text-overflow property where its value is set to initial.
HTML
<html><head> <title> CSS | text-overflow Property </title> <style type="text/css"> div { width: 500px; font-size: 50px; white-space: nowrap; overflow: hidden; text-overflow: initial; } </style></head> <body> <div> GeeksforGeeks : A computer science portal for geeks. </div></body></html>
Output:
inherit: It is used to inherit a property to an element from its parent element property value ie., the value will set the text-overflow property to the value of the parent element.
Syntax:
text-overflow: inherit;
Example: This example illustrates the use of the text-overflow property where its value is set to inherit.
HTML
<html><head> <title> CSS | text-overflow Property </title> <style type="text/css"> div { width: 500px; font-size: 50px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } h3 { width: 500px; white-space: nowrap; overflow: hidden; text-overflow: inherit; } </style></head> <body> <div> GeeksforGeeks: A computer science portal for geeks. <h3> I have inherited my overflow property from div. </h3> </div></body></html>
Output:
Supported Browsers: The browser supported by the text-overflow property are listed below:
Chrome 1.0
Firefox 7.0
Microsoft Edge 12.0
IE 6.0
Safari 1.3
Opera 11.0
bhaskargeeksforgeeks
CSS-Properties
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 23185,
"s": 23157,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 23480,
"s": 23185,
"text": "A text-overflow property in CSS is used to specify that some text has overflown and hidden from view. The white-space property must be set to nowrap and the overfl... |
Generate random numbers in Arduino | Generating random numbers is one of the key requirements from microcontrollers. Random numbers have several applications. Let’s not get there. You must have an application in mind, which brought you to this page. Generating random numbers is very easy in Arduino, thanks to the inbuilt random() function.
random(min, max)
OR
random(max)
where min is 0 by default.
Min is inclusive, while max is exclusive. Thus, random(10,50) will return a number integer between 10 and 49 (10 and 49 included). random(100) will return a random number between 0 and 99, both included. Note that the random function’s return type is long.
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
long r1 = random(100);
Serial.println(r1);
}
void loop() {
// put your main code here, to run repeatedly:
}
The Serial Monitor output is shown below −
Ignore the garbage output. Every time the board is reset, some garbage gets printed. But you can see that the random number printed every time is different. | [
{
"code": null,
"e": 1367,
"s": 1062,
"text": "Generating random numbers is one of the key requirements from microcontrollers. Random numbers have several applications. Let’s not get there. You must have an application in mind, which brought you to this page. Generating random numbers is very easy i... |
HashMap clear() Method in Java - GeeksforGeeks | 26 Nov, 2018
The java.util.HashMap.clear() method in Java is used to clear and remove all of the elements or mappings from a specified HashMap.
Syntax:
Hash_Map.clear()
Parameters: The method does not accept any parameters.
Return Value: The method does not return any value.
Below programs are used to illustrate the working of java.util.HashMap.clear() Method:Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the clear() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, "Geeks"); hash_map.put(15, "4"); hash_map.put(20, "Geeks"); hash_map.put(25, "Welcomes"); hash_map.put(30, "You"); // Displaying the HashMap System.out.println("Initial Mappings are: " + hash_map); // Clearing the hash map using clear() hash_map.clear(); // Displaying the final HashMap System.out.println("Finally the maps look like this: " + hash_map); }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Finally the maps look like this: {}
Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the clear() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); // Mapping int values to string keys hash_map.put("Geeks", 10); hash_map.put("4", 15); hash_map.put("Geeks", 20); hash_map.put("Welcomes", 25); hash_map.put("You", 30); // Displaying the HashMap System.out.println("Initial Mappings are: " + hash_map); // Clearing the hash map using clear() hash_map.clear(); // Displaying the final HashMap System.out.println("Finally the maps look like this: " + hash_map); }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
Finally the maps look like this: {}
Note: The same operation can be performed with any type of Mapping with variation and combination of different data types.
Java - util package
Java-Collections
Java-Functions
Java-HashMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Multithreading in Java
Initializing a List in Java
Collections in Java | [
{
"code": null,
"e": 25709,
"s": 25681,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 25840,
"s": 25709,
"text": "The java.util.HashMap.clear() method in Java is used to clear and remove all of the elements or mappings from a specified HashMap."
},
{
"code": null,
... |
Last-child and last-of-type selector in SASS - GeeksforGeeks | 18 Nov, 2019
SASS is also called Syntactically Awesome Stylesheet. It is a programming language that is interpreted into CSS. The Last Child selector is a selector that allows the user to target the last element inside the containing element. This selector is also known as a Structural Pseudo class which means it is used for styling content on the basis of parent and child content.The Last type of selector is used to match the last occurrence of an element within the container. Both selectors work in the same way but have a slight difference i.e the last type is less specified than the last-child selector.
Syntax:
For Last Child Selector::last-child
:last-child
For the Last of Type::last-of-type
:last-of-type
Example: This example implements the :last-child selector.
<!DOCTYPE html><html lang="en"> <head> <title></title></head> <body> <div> <h1>Welcome To GeeksForGeeks.</h1> <p>A Computer Science Portal For geeks!</p> </div></body> </html>
Sass Code:
$myColor: lime$bkc: black$pad: 5pxp:last-child color: $myColor background-color: $bkc padding: $pad
Output: After compiling the SASS source code you will get this CSS code.CSS Code:
p:last child {
color: lime;
background-color: black;
padding: 5px;
}
Example: last-of-type A Sample Example Is Shown Below
<!DOCTYPE html><html> <head> <title> :last-of-type selector </title></head> <body> <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> <p>The fifth paragraph.</p> <p>The sixth paragraph.</p> <p>The seventh paragraph.</p> <p>The eight paragraph.</p> <p>The ninth paragraph.</p> <p> <b>Note:</b> Internet Explorer 8 and earlier versions do not support the :nth-last-of-type() selector. </p></body> </html>
Sass Code:
$bk: yellowp:last-of-type background-color: $bk
Output:CSS Code:
p:last-of-type {
background-color: yellow;
}
References:
https://www.geeksforgeeks.org/css-last-child-selector/
https://www.geeksforgeeks.org/css-last-of-type-selector/
Supported Browser: The browsers supported by :last-child and :last-of-type selector in SASS are listed below:
Google Chrome 4.0
Edge 9.0
Firefox 3.5
Safari 3.2
Opera 9.6
CSS-Misc
Picked
SASS
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
How to set space between the flexbox ?
Design a web page using HTML and CSS
Create a Responsive Navbar using ReactJS
Making a div vertically scrollable using CSS
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 25909,
"s": 25881,
"text": "\n18 Nov, 2019"
},
{
"code": null,
"e": 26510,
"s": 25909,
"text": "SASS is also called Syntactically Awesome Stylesheet. It is a programming language that is interpreted into CSS. The Last Child selector is a selector that allows ... |
How to set alert message on button click in jQuery ? - GeeksforGeeks | 28 Jul, 2021
In this article, we will learn how to create an alert message in jQuery when a button gets clicked. For this, we will use the jQuery click() method.
jQuery CDN Link: We have linked the jQuery in our file using the CDN link.
<script src=”https://code.jquery.com/jquery-3.6.0.min.js” integrity=”sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=” crossorigin=”anonymous”;></script>
Example: Create a new HTML file and add the following code to it. In this method, we have set an alert and linked it to a button so that when that button gets clicked then the alert message will be popping out.
HTML
<!DOCTYPE html><html lang="en"> <head> <script src= "https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script></head> <body> <button id="btn">Click me!</button> <script> $(document).ready(function () { $("#btn").click(function () { alert("This is an alert message!"); }); }); </script></body> </html>
Output:
Alert msg using click method
jQuery-Methods
jQuery-Questions
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?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using 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": 26954,
"s": 26926,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 27103,
"s": 26954,
"text": "In this article, we will learn how to create an alert message in jQuery when a button gets clicked. For this, we will use the jQuery click() method."
},
{
... |
set insert() function in C++ STL - GeeksforGeeks | 27 Jan, 2021
The set::insert is a built-in function in C++ STL which insert elements in the set container or inserts the elements from a position to another position in the set to a different set.
Syntax:
iterator set_name.insert(element)
Parameters: The function accepts a mandatory parameter element which is to be inserted in the set container. Return Value: The function returns an iterator pointing to the inserted element in the container.Time Complexity: log(N) Where ‘N’ is the number of elements in the set Below program illustrates the above function:
CPP
// CPP program to demonstrate the// set::insert(element) function#include <bits/stdc++.h>using namespace std;int main(){ set<int> s; // Function to insert elements // in the set container s.insert(1); s.insert(4); s.insert(2); s.insert(5); s.insert(3); cout << "The elements in set are: "; for (auto it = s.begin(); it != s.end(); it++) cout << *it << " "; return 0;}
The elements in set are: 1 2 3 4 5
Syntax:
iterator set_name.insert(iterator position, element)
Parameters: The function accepts two parameter which are described below:
element: It specifies the element to be inserted in the set container.
position: It does not specify the position where the insertion is to be done, it only points to a position from where the searching operation is to be started for insertion to make the process faster. The insertion is done according to the order which is followed by the set container.
Syntax:
void set_name.insert(iterator position1, iterator position2)
Parameters: The function accepts two parameters position1 and position2 which specifies the range of elements. All the elements in the range [position1, last) are inserted in another set container. Return Value: No return type => void. Below program illustrates the above function:
CPP
// CPP program to demonstrate the// set::insert(iterator1, iterator2) function#include <bits/stdc++.h>using namespace std;int main(){ set<int> s1; // Function to insert elements // in the set container s1.insert(1); s1.insert(4); s1.insert(2); s1.insert(5); s1.insert(3); cout << "The elements in set1 are: "; for (auto it = s1.begin(); it != s1.end(); it++) cout << *it << " "; set<int> s2; // Function to insert one set to another // all elements from where 3 is to end is // inserted to set2 s2.insert(s1.find(3), s1.end()); cout << "\nThe elements in set2 are: "; for (auto it = s2.begin(); it != s2.end(); it++) cout << *it << " "; return 0;}
The elements in set1 are: 1 2 3 4 5
The elements in set2 are: 3 4 5
messi10goat
chaitanyasahu
CPP-Functions
cpp-set
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Virtual Function in C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
vector erase() and clear() in C++
Object Oriented Programming in C++ | [
{
"code": null,
"e": 25770,
"s": 25742,
"text": "\n27 Jan, 2021"
},
{
"code": null,
"e": 25955,
"s": 25770,
"text": "The set::insert is a built-in function in C++ STL which insert elements in the set container or inserts the elements from a position to another position in the set... |
Put a Shutdown Timer on your Windows Desktop - GeeksforGeeks | 12 Mar, 2021
It might be that you often forget to turn off your PC or you have some task running on the system that’s going to take some time to complete, and you want the system to automatically shut down after the task is complete.
You can tackle this issue without using any third-party software. This article will guide you through the simple process of resolving the same issue. To do so follow the below steps:
Step 1: Click on the Start button, type cmd.exe then press Enter.
Step 2: In the Command Prompt window that appears, type the below command:
shutdown –s -t 300
Note: The ‘300’ indicates 300 seconds, so your computer will shut down in five minutes.
You can adjust the shutdown time. For example, for the seven-hour timer, you’d need to change it to ‘25200’.
Step 3: Press Enter to start the countdown.
Windows will show a warning when you’re a few minutes from being signed out. If you need more time, return to Command Prompt window and type the below command to abort the process:
shutdown-a
If you find yourself using this process a lot, it is best to create a desktop shortcut for it. To do follow the below steps:
Step 1: Right-click an empty part of your desktop, select New, then Shortcut.
Step 2: In the ‘Type the location of the item:’ section, add the following:
C:\windows\System32\cmd.exe” /k shutdown –s –t 25200
Note: 25200 will set a seven-hour timer.
Step 3: Click Next, give your shortcut a name, then Finish.
You might also want to create a desktop shortcut to abort the shutdown. Repeat the process above and type the following command:
C:\Windows\System32\cmd.exe” /k shutdown –a
How To
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Install Jupyter Notebook on MacOS?
How to Set Git Username and Password in GitBash?
Installing MinGW Tools for C/C++ and Changing Environment Variable
How to Install Metasploit 6 on Android using Termux (No Root)?
Top Programming Languages for Android App Development
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU. | [
{
"code": null,
"e": 26197,
"s": 26169,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 26419,
"s": 26197,
"text": "It might be that you often forget to turn off your PC or you have some task running on the system that’s going to take some time to complete, and you want the syst... |
Micro - Lightweight terminal based text editor - GeeksforGeeks | 21 Jul, 2021
Micro is a terminal-based text editor, and it is very easy to install and use. The micro editor is developed to be the successor of nono editor. It has no external decencies and no external files are needed. It is a single program. Now let’s see the features of the micro text editor.
Easy to install and use and easy to configure
No external dependencies
Syntax highlighting for more than 130 languages
Command Keybindings like nano
Plugin system, we can install and use the plugins.
Simple auto-completion
Copy and paste with the system clipboard
Mouse support
Now let’s see how can we install the micro editor on the different systems. There are many ways by which we can install the micro editor on the system.
To install the micro editor, there is one script created by micro. Which download the latest prebuild binary and install it on the system. To use this script to install micro, use the following command:
curl https://getmic.ro | bash
Then move the micro file to /usr/bin/ folder to execute micro as a command
sudo mv micro /usr/bin/
Now, let’s see how can we install the micro editor using the package managers.
To install the micro editor on Linux distro, use the following command according to your Linux distro:
For Ubuntu:
sudo apt-get install micro
For Fedora:
sudo dnf install micro
For Arch Linux
sudo pacman -S micro
For Solus:
sudo eopkg install micro
To install micro editor on macOS, use the brew package manager :
brew install micro
For windows, we can use Chocolatey and Scoop to install the micro editor:
choco installs micro
or
scoop install micro
Now we have installed the micro editor on the system. Let’s see how can we use it.
To open micro editor use the micro command like:
micro
Then you can see the editor is started
Now to save the file using the ctrl+s key. Then the micro editor will ask you the filename to save the file then write the file name and press enter
Then your file gets saved with a mentioned name. To close the file use cnt+q keys. Then micro will ask you about to save the changes or not. Then simply press y key.
To open the file with micro just mention the file name after the micro command:
micro filename
To know more key-bindings in the micro use the Alt+g keys then you will see all key binding to use
For help press Ctrl+g. And for more information or with commands:
man micro
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 25936,
"s": 25651,
"text": "Micro is a terminal-based text editor, and it is very easy to install and use. The micro editor is developed to be the successor of nono editor. It has no external... |
PriorityQueue remove() Method in Java - GeeksforGeeks | 14 Dec, 2021
The remove() method of PriorityQueue class of java.util package is used to remove a particular element from a PriorityQueue. As we all know that the elements while entering into the priority queue are not sorted but as we all know while taking out elements from the priority queue the elements are always sorted being a trait of the priority queue. Here the default ordering of priority of elements for data types is defined as follows:
Integer: Smallest elements that come first (while dealing with positive numbers only)
String: Alphabetical ordering
Note: We can also insert a Comparator while creating an instance of this class which tells us how the priority should be defined.
Syntax:
PriorityQueue<String> = new PriorityQueue<String>(ComparatorHere);
Syntax: Remove method
Priority_Queue.remove(Object O)
Parameters: The parameter O is of the type of PriorityQueue and specifies the element to be removed from the PriorityQueue.
Return Value: This method returns True if the specified element is present in the Queue else it returns False.
Example 1
Java
// Java Program to Illustrate remove() Method// in PriorityQueue// Where Elements are of String Type // Importing all utility classesimport java.util.*; // Main class// PriorityQueueDemopublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty PriorityQueue // where elements are of string type PriorityQueue<String> queue = new PriorityQueue<String>(); // Adding elements into the Queue // using add() method queue.add("Welcome"); queue.add("To"); queue.add("Geeks"); queue.add("For"); queue.add("Geeks"); // Printing the elements of PriorityQueue System.out.println("Initial PriorityQueue: " + queue); // Removing elements from PriorityQueue // using remove() method queue.remove("Geeks"); queue.remove("For"); queue.remove("Welcome"); // Displaying the PriorityQueue // after removal of element System.out.println("PriorityQueue after removing " + "elements: " + queue); }}
Initial PriorityQueue: [For, Geeks, To, Welcome, Geeks]
PriorityQueue after removing elements: [Geeks, To]
Example 2
Java
// Java Program to Illustrate remove() Method// of PriorityQueue class// Where Elements are of Integer type // Importing required classesimport java.util.*; // Main class// PriorityQueueDemopublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty PriorityQueue by // creating an object of integer type PriorityQueue<Integer> queue = new PriorityQueue<Integer>(); // Adding custom input elements // using add() method queue.add(10); queue.add(15); queue.add(30); queue.add(20); queue.add(5); // Displaying the PriorityQueue System.out.println("Initial PriorityQueue: " + queue); // Removing elements from the PriorityQueue // using remove() method queue.remove(30); queue.remove(5); // Displaying the PriorityQueue elements // after removal System.out.println("PriorityQueue after removing " + "elements: " + queue); }}
Initial PriorityQueue: [5, 10, 30, 20, 15]
PriorityQueue after removing elements: [10, 20, 15]
Geek, have you ever wondered what will happen if calls of remove() method exceed the elements present in the queue. In this scenario, it will continue to remove the elements that were there, and thereafter it will not find any element to remove priority-wise, so it will throw an exception which is as follows.
Note: This class do implements AbstractQueueInterface
Example
Java
// Java Program to illustrate remove() Method// in PriorityQueue// Where Exception is encountered // Importing required classesimport java.io.*;import java.util.PriorityQueue; // Main class// PriorityQueueExceptionclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty PriorityQueue PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); // Note: Elements are inserted in unsorted order in // priority queue but after removal of elements // queue is always sorted. // Adding elements in above queue // using add() method pq.add(2); pq.add(14); pq.add(41); pq.add(7); pq.add(99); // Elements in queue are unsorted by far // Getting size of above queue before deletion // of any element using size() method System.out.println( "Size of priority queue before deletion : " + pq.size()); // Printing all elements of above queue System.out.println( "Priority queue before removal : " + pq); // Calling remove() method over priority queue // in which there were 5 elements // Here calling remove() method say be it 2 times // So 2 top priority elements will be removed System.out.println(" 1st element removed : " + pq.remove()); System.out.println(" 2nd element removed : " + pq.remove()); System.out.println(" 3rd element removed : " + pq.remove()); System.out.println(" 4th element removed : " + pq.remove()); System.out.println(" 5th element removed : " + pq.remove()); // By now queue is empty and if now we made further // remove() call it will throw exception for this System.out.println(" 6th element removed : " + pq.remove()); // As we know smaller the integer bigger the // priority been set by default comparator of this // class // Note: Now the element is always returned sorted // from a priority queue is a trait of this class // Printing the queue after removal of priority // elements System.out.println( "Priority queue after removal as follows: " + pq); }}
Output:
Output explanation:
It is showcasing that there are no further elements left in the queue as a queue is empty by now so does it throw NoSuchElementException.
Anshul_Aggarwal
adnanirshad158
sweetyty
pradeep sudheer
Java - util package
Java-Collections
Java-Functions
java-priority-queue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Different ways of Reading a text file in Java
Internal Working of HashMap in Java
Introduction to Java
Comparator Interface in Java with Examples
Strings in Java | [
{
"code": null,
"e": 25251,
"s": 25223,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 25688,
"s": 25251,
"text": "The remove() method of PriorityQueue class of java.util package is used to remove a particular element from a PriorityQueue. As we all know that the elements while... |
How to set focus on an input field after rendering in ReactJS ? - GeeksforGeeks | 05 Jan, 2021
Setting focus on an input field after rendering in ReactJS can be done in the following ways, but before doing that, set up your project structure with the following steps:
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
Approach 1: we can do it in componentDidMount() function and refs callback. For example:
componentDidMount() {
this.nameInput.focus();
}
Filename: App.js
Javascript
import React, { Component } from "react";class App extends Component { componentDidMount() { this.nameInput.focus(); } render() { return ( <div> <input defaultValue="It Won't focus" /> <input ref={(input) => { this.nameInput = input; }} defaultValue="It will focus" /> </div> ); } } export default App;
Approach 2: If we just want to focus on an element when it mounts (initially renders) a simple use of the autoFocus attribute will do. we can use the autoFocus prop to have an input automatically focus when mounted.
Filename: App.js
Javascript
import React, { Component } from "react"; class App extends Component { render() { return( <div> <input defaultValue="It Won't focus" /> <input autoFocus defaultValue="It will focus" /> </div> ); } } export default App;
Approach 3: We can use the below syntax using the inline ref property.
<input ref={input => input && input.focus()}/>
Filename: App.js
Javascript
import React, { Component } from "react"; class App extends Component { render() { return( <div> <input defaultValue="It Won't focus" /> <input ref={(input) => {input && input.focus() }} defaultValue="It will focus" /> </div> ); } } export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Picked
react-js
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Lodash _.debounce() Method
Angular File Upload
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ? | [
{
"code": null,
"e": 26543,
"s": 26515,
"text": "\n05 Jan, 2021"
},
{
"code": null,
"e": 26716,
"s": 26543,
"text": "Setting focus on an input field after rendering in ReactJS can be done in the following ways, but before doing that, set up your project structure with the followi... |
HTTP headers | Digest - GeeksforGeeks | 31 Oct, 2019
The Digest HTTP header is a response HTTP header that provides the requested resource with a small value generated by a hash function from a whole message. The Digest HTTP header is a response header that provides a digest of the requested resource. The entire representation is used to calculate the digest. Multiple digest values for a single resource is also possible as the representation depends on Content-Type and Content-Encoding.
Syntax:
Digest:<digest-algorithm>=<digest-value>
Directives: This header accepts two directives as mentioned above and described below:
<digest-algorithm>: It contains defined supported algorithms, example SHA-256 and SHA-512.
<digest-value>: It holds the result of encoding and applying the digest algorithm to the resource representation.
Examples:
It provides the resource with the sha-256 algorithm and also provides the digest value.Digest: sha-256=nOJRJgeeksforgeeksN3OWDUo9DBPE=
Digest: sha-256=nOJRJgeeksforgeeksN3OWDUo9DBPE=
It provides the resource with the sha-512 algorithm and also provides the digest value. In addition to that, it provides UNIX sum algorithm which is subject to collisions.Digest: sha-512=\vdtgeeksforgeeks8nOJRJN3OWDDBPE=, unixsum=69
Digest: sha-512=\vdtgeeksforgeeks8nOJRJN3OWDDBPE=, unixsum=69
Supported Browsers: The browsers are compatible with HTTP Digest header are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 25599,
"s": 25571,
"text": "\n31 Oct, 2019"
},
{
"code": null,
"e": 26038,
"s": 25599,
"text": "The Digest HTTP header is a response HTTP header that provides the requested resource with a small value generated by a hash function from a whole message. The Dig... |
Java Program to Get System Motherboard Serial Number for Windows and Linux Machine - GeeksforGeeks | 04 Jan, 2021
The motherboard is the foundation on top of which the entire architecture of the CPU is based upon. It is the primarily printed Circuit Board (PCB) that is responsible for connecting all the major components such as hard drive, CPU, external ports and so on. A good and knowledgeable computer user must be aware of the Manufacturer, Version, and Serial Number of their board. This article primarily revolves around writing Java codes to extract the Serial Numbers of the motherboard for the respective machine of the user. The Serial Number is unique for every motherboard and hence, every user will get different outputs on running the same program. Below, we have provided the codes to find out the Serial Numbers for motherboards for both Windows and Linux machines.
A. Linux Machine :
The primary concept in retrieving the Serial Number of the Motherboard is to run commands in the terminal using the Java code and storing the retrieved Serial Number as a String which is then printed on the screen.
Algorithm :
First, we store the command that should have been run on terminal in a variable called command.Next, we initialize a Process with the call to the Runtime class of Java which is used to interact with the Java Runtime Environment.We pass the command as the parameter to the exec function whose primary function is to get the command executed.For the next step, we capture the Input Stream from the Process using InputStreamReader class of java I/O package.Then, the BufferedReader class is used to read the stream from the InputStreamReader.We store this in a variable.Next, we wait for the Process to terminate.We close the BufferedReader.In the catch block, we print the stack trace if an error has occurred and set the variable holding the Serial Number to null.Finally, we return this variable and print the output using the driver code.
First, we store the command that should have been run on terminal in a variable called command.
Next, we initialize a Process with the call to the Runtime class of Java which is used to interact with the Java Runtime Environment.
We pass the command as the parameter to the exec function whose primary function is to get the command executed.
For the next step, we capture the Input Stream from the Process using InputStreamReader class of java I/O package.
Then, the BufferedReader class is used to read the stream from the InputStreamReader.
We store this in a variable.
Next, we wait for the Process to terminate.
We close the BufferedReader.
In the catch block, we print the stack trace if an error has occurred and set the variable holding the Serial Number to null.
Finally, we return this variable and print the output using the driver code.
Command Used :
sudo dmidecode -s baseboard-serial-number
Below is the implementation of the problem statement:
Java
// Java code to get the system// motherboard serial number on linux // importing the librariesimport java.io.*; class GFG { static String getLinuxMotherBoardSerialNumber() { // command to be executed on the terminal String command = "sudo dmidecode -s baseboard-serial-number"; // variable to store the Serial Number String serialNumber = null; // try block try { // declaring the process to run the command Process SerialNumberProcess = Runtime.getRuntime().exec(command); // getting the input stream using // InputStreamReader using Serial Number Process InputStreamReader ISR = new InputStreamReader( SerialNumberProcess.getInputStream()); // declaring the Buffered Reader BufferedReader br = new BufferedReader(ISR); // reading the serial number using // Buffered Reader serialNumber = br.readLine().trim(); // waiting for the system to return // the serial number SerialNumberProcess.waitFor(); // closing the Buffered Reader br.close(); } // catch block catch (Exception e) { // printing the exception e.printStackTrace(); // giving the serial number the value null serialNumber = null; } // returning the serial number return serialNumber; } // Driver Code public static void main(String[] args) { // printing and calling the method which // returns the Serial Number System.out.println( getLinuxMotherBoardSerialNumber()); }}
Output :
PGPPP018J940BP
B. Windows Machine :
The only difference in the code that is used to retrieve the Serial Number of Motherboard on Windows machine from that used to retrieve it on the Linux machine is of the command used. The remaining algorithm as well as the code remains the same.
Command Used:
wmic baseboard get serialnumber
Below is the implementation of the problem statement:
Java
// Java code to get the system// motherboard serial number on Windows // importing the librariesimport java.io.*; class GFG { static String getWindowsMotherBoardSerialNumber() { // command to be executed on the terminal String command = "wmic baseboard get serialnumber"; // variable to store the Serial Number String serialNumber = null; // try block try { // declaring the process to run the command Process SerialNumberProcess = Runtime.getRuntime().exec(command); // getting the input stream using // InputStreamReader using Serial Number Process InputStreamReader ISR = new InputStreamReader( SerialNumberProcess.getInputStream()); // declaring the Buffered Reader BufferedReader br = new BufferedReader(ISR); // reading the serial number using // Buffered Reader serialNumber = br.readLine().trim(); // waiting for the system to return // the serial number SerialNumberProcess.waitFor(); // closing the Buffered Reader br.close(); } // catch block catch (Exception e) { // printing the exception e.printStackTrace(); // giving the serial number the value null serialNumber = null; } // returning the serial number return serialNumber; } // Driver Code public static void main(String[] args) { // printing and calling the method which // returns the Serial Number System.out.println( getWindowsMotherBoardSerialNumber()); }}
Output:
PGPPP018J940BP
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initializing a List 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 | [
{
"code": null,
"e": 25973,
"s": 25945,
"text": "\n04 Jan, 2021"
},
{
"code": null,
"e": 26743,
"s": 25973,
"text": "The motherboard is the foundation on top of which the entire architecture of the CPU is based upon. It is the primarily printed Circuit Board (PCB) that is respons... |
Python - Remove Units from Value List - GeeksforGeeks | 11 Jan, 2022
Sometimes, while working with Python value lists, we can have a problem in which we need to perform removal of units that come along with values. This problem can have direct application in day-day programming and data preprocessing. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [“54 cm”, “23 cm”, “12cm”, “19 cm”], unit = “cm”Output : [’54’, ’23’, ’12’, ’19’]
Input : test_list = [“54 cm”], unit = “cm”Output : [’54’]
Method #1 : Using regex() + list comprehensionThe combination of these functions can be used to solve this problem. In this, we approach by extracting just the numbers using regex, and remove rest of string units.
Python3
# Python3 code to demonstrate working of # Remove Units from Value List# Using list comprehension + regex()import re # initializing listtest_list = ["54 kg", "23 kg", "12kg", "19 kg"] # printing original listprint("The original list is : " + str(test_list)) # initializing unit unit = "kg" # Remove Units from Value List# Using list comprehension + regex()res = re.findall('\d+', ' '.join(test_list)) # printing result print("List after unit removal : " + str(res))
The original list is : ['54 kg', '23 kg', '12kg', '19 kg']
List after unit removal : ['54', '23', '12', '19']
Method #2 : Using replace() + strip() + list comprehensionThe combination of above functions can be used to solve this problem. In this, we perform the task of replacing unit with empty string to remove it using replace() and stray spaces are handled using strip().
Python3
# Python3 code to demonstrate working of # Remove Units from Value List# Using replace() + strip() + list comprehensionimport re # initializing listtest_list = ["54 kg", "23 kg", "12kg", "19 kg"] # printing original listprint("The original list is : " + str(test_list)) # initializing unit unit = "kg" # Remove Units from Value List# Using replace() + strip() + list comprehensionres = [sub.replace(unit, "").strip() for sub in test_list] # printing result print("List after unit removal : " + str(res))
The original list is : ['54 kg', '23 kg', '12kg', '19 kg']
List after unit removal : ['54', '23', '12', '19']
rajeev0719singh
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary | [
{
"code": null,
"e": 26053,
"s": 26025,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 26351,
"s": 26053,
"text": "Sometimes, while working with Python value lists, we can have a problem in which we need to perform removal of units that come along with values. This problem can ... |
How to Use Do While Loop in Excel VBA? - GeeksforGeeks | 30 Jul, 2021
A Do...While loop is used when we want to repeat certain set of statements as long as the condition is true. The condition may be checked at the starting or at the end of the loop
The Do While loop is used in two ways:
Do...while loop which checks the condition at the STARTING of the loop.
Do...while loop which checks the condition at the END of the loop.
Syntax 1:
Do While condition
[statements]
[Exit Do]
[statements]
Loop
Syntax 2:
Do While
[statements]
[Exit Do]
[statements]
Loop condition
Follow the below steps to implement a Do-While loop:
Step 1: Define a Macro
Private Sub Demo_Loop()
End Sub
Step 2: Define variables
j=2
i=1
Step 3: Write Do While Loop. You can write condition at the beginning or at the end
Do While i < 5
Step 4: Write statements to be executed in loop
msgbox "Table of 2 is : " & (j*i)
i=i+1
Step 5: End loop.
Now let’s take a look at some of the examples.
Example 1: Do...while loop which checks the condition at the STARTING of the loop. The below example uses Do...while loop to check the condition at the starting of the loop. The statements inside the loop are executed, only if the condition is True. We will print Table of 2 using Do...while loop;
Private Sub Demo_Loop()
j=2
i=1
Do While i < 5
msgbox "Table of 2 is : " & (j*i)
i=i+1
Loop
End Sub
Output:
Example 2: Do...while loop which checks the condition at the END of the loop. The below example checks the condition at the end of the loop. The major difference between these two syntax is explained in the following example.
Private Sub Demo_Loop()
i = 10
Do
i = i + 1
MsgBox "The value of i is : " & i
Loop While i < 3 'Condition is false.Hence loop is executed once.
End Sub
When the above code is executed, it prints the following output in a message box.
Output:
Excel-VBA
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Get Length of Array in Excel VBA?
Using CHOOSE Function along with VLOOKUP in Excel
Macros in Excel
How to Extract the Last Word From a Cell in Excel?
How to Remove Duplicates From Array Using VBA in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
How to Calculate Deciles in Excel? | [
{
"code": null,
"e": 26289,
"s": 26261,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 26469,
"s": 26289,
"text": "A Do...While loop is used when we want to repeat certain set of statements as long as the condition is true. The condition may be checked at the starting or at the... |
Matplotlib.axes.Axes.tricontourf() in Python - GeeksforGeeks | 13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.tricontourf() function in axes module of matplotlib library is also used to draw contours on an unstructured triangular grid. tricontour and tricontourf draw contour lines and filled contours, respectively.
Syntax:
Axes.tricontourf(ax, *args, **kwargs)
Parameters: This method accept the following parameters that are described below:
x, y: These parameter are the x and y coordinates of the data which is to be plot.
triangulation: This parameter is a matplotlib.tri.Triangulation object.
Z: This parameter is is the array of values to contour, one per point in the triangulation.
**kwargs: This parameter is Text properties that is used to control the appearance of the labels.All remaining args and kwargs are the same as for matplotlib.pyplot.plot().
All remaining args and kwargs are the same as for matplotlib.pyplot.plot().
Note: tricontourf-only keyword arguments:antialiased: This parameter is a bool enable antialiasing which used in contours on an unstructured triangular grid.
Returns: This returns the list of 2 Line2D containing following:
The lines plotted for triangles edges.
The markers plotted for triangles nodes
Below examples illustrate the matplotlib.axes.Axes.tricontourf() function in matplotlib.axes:
Example-1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as mtriimport numpy as np # Create triangulation.x = np.asarray([0, 1, 0, 3, 0.5, 1.5, 2.5, 1, 2, 1.5])y = np.asarray([0, 0, 0, 0, 1.0, 1.0, 1.0, 2, 2, 3.0])triangles = [[0, 1, 4], [1, 5, 4], [2, 6, 5], [4, 5, 7], [5, 6, 8], [5, 8, 7], [7, 8, 9], [1, 2, 5], [2, 3, 6]] triang = mtri.Triangulation(x, y, triangles)z = np.cos(2.5 * x*x) * np.cos(1.5 * y*x) fig, axs = plt.subplots()t = axs.tricontourf(triang, z)fig.colorbar(t) axs.set_title('matplotlib.axes.Axes.tricontourf() Example')plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np n_angles = 26n_radii = 10min_radius = 0.35radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 4 * np.pi, n_angles, endpoint = False)angles = np.repeat(angles[..., np.newaxis], n_radii, axis = 1)angles[:, 1::2] += np.pi / n_angles x = (10 * radii * np.cos(angles)).flatten()y = (10 * radii * np.sin(angles)).flatten()z = (np.cos(4*(radii)**2) * np.cos(3 * (angles)**2)).flatten() triang = tri.Triangulation(x, y) triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < min_radius) fig1, ax1 = plt.subplots()ax1.set_aspect('equal')tcf = ax1.tricontourf(triang, z)fig1.colorbar(tcf)ax1.set_title('matplotlib.axes.Axes.tricontourf() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n13 Apr, 2020"
},
{
"code": null,
"e": 25837,
"s": 25537,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, ... |
Apache Pig - ROUND() | The ROUND() function is used to get the value of an expression rounded to an integer (if the result type is float) or rounded to a long (if the result type is double).
grunt> ROUND()
Assume that there is a file named math.txt in the HDFS directory /pig_data/. This file contains integer and floating point values as shown below.
math.txt
5
16
9
2.5
5.9
3.1
And, we have loaded this file into Pig with a relation named math_data as shown below.
grunt> math_data = LOAD 'hdfs://localhost:9000/pig_data/math.txt' USING PigStorage(',')
as (data:float);
Let us now generate round values of the contents of the math.txt file using ROUND() function as shown below.
grunt> round_data = foreach math_data generate (data), ROUND(data);
The above statement stores the result in the relation named round_data. Verify the contents of the relation using the Dump operator as shown below.
grunt> Dump round_data;
(5.0,5)
(16.0,16)
(9.0,9)
(2.5,3)
(5.9,6)
(3.1,3)
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2852,
"s": 2684,
"text": "The ROUND() function is used to get the value of an expression rounded to an integer (if the result type is float) or rounded to a long (if the result type is double)."
},
{
"code": null,
"e": 2868,
"s": 2852,
"text": "grunt> ROUND()... |
Python 3 - String capitalize() Method | It returns a copy of the string with only its first character capitalized.
Following is the syntax for capitalize() method −
str.capitalize()
NA
string
#!/usr/bin/python3
str = "this is string example....wow!!!"
print ("str.capitalize() : ", str.capitalize())
When we run above program, it produces the following result −
str.capitalize() : This is string example....wow!!!
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2415,
"s": 2340,
"text": "It returns a copy of the string with only its first character capitalized."
},
{
"code": null,
"e": 2465,
"s": 2415,
"text": "Following is the syntax for capitalize() method −"
},
{
"code": null,
"e": 2483,
"s": 2465,... |
DCGANs — Generating Dog Images with Tensorflow and Keras | by Konstantin Georgiev | Towards Data Science | This post is a tutorial on the basic ideas behind the effectiveness of DCGANs, as well as some methods/hacks to improve their performance. These methods are all based on my experience during Kaggle’s Generative Dogs Competition. The tutorial is also available, either in notebook format on my original kernel, or on GitHub.
To run this example locally or using Colab, you will need a Kaggle account, in order to retrieve its API key and use the provided datasets. Full tutorial is available here.
Unlike most popular neural network architectures, GANs are trained to solve two problems simultaneously — discrimination (effectively separating real from fake images) and “realistic” fake data generation (effectively generating samples considered as real). As we can see these tasks are complete polar opposites but what would happen if we separated them into different models?
Well, the general names for these models are Generator (G) and Discriminator (D) and are considered the building blocks behind the theory of GANs.
The Generator network takes as input a simple random noise N-dimensional vector and transforms it according to a learned target distribution. Its output is also N-dimensional. The Discriminator on the other hand models a probability distribution function (like a classifier) and outputs a probability that the input image is real or fake [0, 1]. With this in mind, we can define the two main goals of the generation task:
1. Train G to maximise D’s final classification error. (So that the generated images are perceived as real).
2. Train D to minimise the final classification error. (So that real data is correctly distinguished from fake data).
To achieve this, during backpropagation, G’s weights will be updated using Gradient Ascent to maximise the error, while D will use Gradient Descent to minimise it.
So how do we define a loss function that estimates the cumulative performance of the two networks? Well, we can use the Absolute Error to estimate D’s error and then we can reuse the same function for G but maximised:
In this case, p_t represents the true distribution of images, while p_g is the distribution created from G.
We can observe that this theory is based on some key concepts of Reinforcement Learning. It can thought of as a two-player minimax game, where the two players are competing against each other and thus progressively improving in their respective tasks.
We saw the basic idea behind the theory of GANs. Now let’s take one step further and learn how DCGANs work by applying ideas and methods from Convolutional Neural Networks.
DCGANs utilize some of the basic principles of CNNs and have thus become one of the most widely used architectures in practice, due to their fast convergence and also due to the fact that they can be very easily adapted into more complex variants (using labels as conditions, applying residual blocks and so on). Here are some of the more important problems that DCGANs solve:
D is created so that it basically solves a supervised image classification task. (for this case dog or no dog)
The filters learned by the GAN can be utilized to draw specific objects in the generated image.
G contains vectorized properties that can learn very complex semantic representations of objects.
Here are some of the core guidelines to consider when creating a stable DCGAN, as opposed to a standard CNN(taken from the official paper):
Replace Pooling functions with Strided convolutions. (this allows D to learn its own spatial downsampling and G its respective upsampling without adding any bias to the model)
Use BatchNorm (it stabilizes learning by normalizing the input to each unit to have zero mean and unit variance, this also helps to create more robust deep models without having the gradients diverging)
Avoid using Fully-Connected hidden layers (not output). (example for this is global average pooling which seems to hurt convergence speed)
For G — use ReLU activations and Tanh for the output. (tanh is generally the more preffered activation when you have an image as an output as it has a range of [-1, 1])
For D — use LeakyReLU activations (and a sigmoid function for the output probabilites). (this is tested empirically and seems to work well for modelling to a higher resolution)
Here is the most standard structure of a DCGAN generator:
As we can observe, its initial input is simply a (1, 100) noise vector, which passes through 4 Convolutional layers with upsampling and a stride of 2 to produce a result RGB image of size (64, 64, 3). To achieve this, the input vector is projected onto a 1024-dimensional output to match the input of the first Conv layer, which we will see more later on.
What would a standard discriminator look like? Well, about what you would expect, let’s take a look:
This time around we have an input image of (64, 64, 3), same as G’s output. We pass it to 4 standard downsampling Conv layers, again with a stride of 2. In the final output layer, the image gets flattened to a vector, which is usually fed to a sigmoid function, which then outputs D’s prediction for that image (a single value representing the probability in the range [0,1] — dog = 1 or no dog = 0).
Well, now you saw the basic idea behind GANs and DCGANs, so now we can proceed to generate some dogs using Tensorflow and Keras :).
Before we proceed with creating the GAN model let’s first do a quick exploration of the Stanford Dogs dataset, which we’ll be using. Because we also have the annotations for each image, we can use them to map each dog image to its respective breed. To do that, we can first make a dictionary that maps the breed code in the file name to the actual breed name.
Next, I’m going to use OpenCV for a quick function to read and transform the images to RGB.
If we look at the dataset, we can see that each annotation folder contains a list of xml files. These files are associated with a specific image and contain very useful information, mainly the bounding boxes around each dog in the image. There are also images with more than one dog in them and this allows us to accurately crop them and make a dataset that contains single dogs only images.
Here we can utilize the xml library to create a tree and find the relevant elements for that annotation. For each object we can extract the bounding box coordinates, crop the images and normalize the crop by shrinking or expanding it depending on the result image width. Finally, we’ll save the images in a numpy array.
for o in objects: bndbox = o.find('bndbox') xmin = int(bndbox.find('xmin').text) ymin = int(bndbox.find('ymin').text) xmax = int(bndbox.find('xmax').text) ymax = int(bndbox.find('ymax').text) .. Add some margins and adjust the width .. # Crop the image img_cropped = img[ymin:ymin+w, xmin:xmin+w, :] # [h,w,c] .. Interpolation step .. # Resize the image img_cropped = cv2.resize(img_cropped, (image_width, image_height), interpolation=interpolation)# Save the images and labelsdog_images_np[curIdx,:,:,:] = np.asarray(img_cropped)dog_breed_name = dog_breed_dict[dog_ann.split('_')[0]]breeds.append(dog_breed_name)curIdx += 1 return dog_images_np, breeds
The features take about 2–3 mins to load.
By trial, we can figure out that the result images with single dogs only are 22125 and thus we can specify the exact size of our numpy array. There are 120 different dog breeds.
Now that we have the features and labels, we can plot them in a square grid to see what the crops look like and to make sure that they are labeled correctly.
def plot_features(features, labels, image_width=image_width, image_height=image_height, image_channels=image_channels,examples=25, disp_labels=True): if not math.sqrt(examples).is_integer(): print('Please select a valid number of examples.') return imgs = [] classes = [] for i in range(examples): rnd_idx = np.random.randint(0, len(labels)) imgs.append(features[rnd_idx, :, :, :]) classes.append(labels[rnd_idx]) fig, axes = plt.subplots(round(math.sqrt(examples)), round(math.sqrt(examples)),figsize=(15,15), subplot_kw = {'xticks':[], 'yticks':[]}, gridspec_kw = dict(hspace=0.3, wspace=0.01)) for i, ax in enumerate(axes.flat): if disp_labels == True: ax.title.set_text(classes[i]) ax.imshow(imgs[i])
Note that we need to normalize the pixel values to make sure that the dogs are plotted correctly.
plot_features(dog_images_np / 255., breeds, examples=25, disp_labels=True)
Here we have a whole list of hyperparameters that you can tune and play around with to try and improve the model. I’ve mostly gathered these values from research papers and experimented a bit with tweaking them and this is what I ended up with. Here’s a list of things you could try out:
Sample size — the number of features
Batch size — 64 or 32 could improve performance, but are computationally heavy and you can only run the model for a small amount of epochs
Weight Init Std and Mean — these values are come from research papers and seem to stabilize model training
Leaky ReLU slope — the threshold for D’s activations, also seems robust
Downsize factor and Scale factor — set up so that G’s noise vector can be reshaped to (4, 4, 512), other combinations might also work
Dropout — amount of dropout layers, their placement and their rate could improve performance.
Learning rate and Learning rate decay — very important to model convergence, hard to tune precisely, G and D can have different learning rates.
Noise vector shape — usually 128 or 100 seems to be sufficient
Now let’s use our numpy array of features to construct a Tensorflow dataset object. First, we can convert the data types to float32, which always helps to preserve some memory.
dog_features_tf = tf.cast(dog_images_np, 'float32')
We could also apply Data Augmentation to our dataset. This includes random horizontal flips, zooming and cropping the image in random regions. Out of these, I found only the first method to be somewhat useful for adding some more variance to the dataset, as the other methods introduce a lot of noise.
So in this case, there will be a 50% chance that an image in our dataset will be flipped from left to right.
def flip(x: tf.Tensor) -> (tf.Tensor): x = tf.image.random_flip_left_right(x) return x
Now we can use Tensorflow to create the dataset by shuffling it, applying some augmentation, and finally separating it into batches of the specified Batch size.
dog_features_data = tf.data.Dataset.from_tensor_slices(dog_features_tf).shuffle(sample_size).map(flip).batch(batch_size, drop_remainder=True)
Before we actually make the Generator, let’s see a few normalizations that can gradually speed up a DCGAN’s convergence.
One of these methods is Weight initialization. It turns out that it’s pretty important for training stable GANs. Firstly, the model weights need to be zero-centered with a slight increase of std(0.02). This stabilizes both D and G during training and prevents the model gradients from vanishing or exploding. This is a key step in every case, where we have to use random variables in our model (the random noise vector).
Here is an example of how Weight initialization can seriously affect the learning process of a Neural Network.
We can also apply a Truncated Normal distribution using Keras, which will discard values more than 2 standard deviations from the mean. This could perhaps eliminate some outlier points during training.
weight_initializer = tf.keras.initializers.TruncatedNormal(stddev=weight_init_std, mean=weight_init_mean, seed=42)
Spectral Normalization is a new type of weight initialization, designed specifically for GANs, which seems to further stabilize model training (you can read more from this paper). For a more detailed explanation on Spectral Normalization and why it works it also worth to check out this post, it has very intuitive examples.
Spectral Normalization of a single weight in our network can be defined as the following:
Here u and v are simple random vectors of the same size. They are utilized to perform what’s called a power iteration operation on the specific weight, for each learning step and it proves to be a lot more computationally efficient than simply penalizing the gradients.
Afterwards, in the backpropagation step, we use WSN(W) to update the weights instead of W.
For this project, I will reuse some custom Keras layers implemented by IShengFang (official code), to apply Spectral Normalization on top of Conv and Dense layers.
Here is also a good example on the effect of Spectral Normalization:
Let’s also define some template layers in Keras, so that we can create G and D more easily later on. The standard pattern for the layers will be:
TP_Conv_Block = [(Conv(SN)2DTranspose (upsample)) -> (BatchNorm) -> (ReLU)]
Conv_Block = [(Conv(SN)2D (downsample)) -> (BatchNorm) -> (LeakyReLU)]
For this example, I will be using standard Conv2DTranspose blocks in G and Spectral Normalized Conv2D layers in D.
def transposed_conv(model, out_channels, ksize, stride_size, ptype='same'): model.add(Conv2DTranspose(out_channels, (ksize, ksize), strides=(stride_size, stride_size), padding=ptype, kernel_initializer=weight_initializer, use_bias=False)) model.add(BatchNormalization()) model.add(ReLU()) return modeldef convSN(model, out_channels, ksize, stride_size): model.add(ConvSN2D(out_channels, (ksize, ksize), strides=(stride_size, stride_size), padding='same', kernel_initializer=weight_initializer, use_bias=False)) model.add(BatchNormalization()) model.add(LeakyReLU(alpha=leaky_relu_slope)) #model.add(Dropout(dropout_rate)) return model
We can finally define our generator. The model structure is mostly based on the official DCGAN paper with a few tweaks that I found beneficial to the performance. Here is the overall structure:
[Input(128, 1) -> Dense(2048,) -> Reshape(4, 4, 128) -> TP_Conv_Block(Depth=512, K=5x5, S=1x1) -> Dropout(0.5) -> TP_Conv_Block(Depth=256, K=5x5, S=2x2) -> Dropout(0.5) -> TP_Conv_Block(Depth=128, K=5x5, S=2x2) -> TP_Conv_Block(Depth=64, K=5x5, S=2x2) -> TP_Conv_Block(Depth=32, K=5x5, S=2x2) -> Dense(Depth=3, Tanh)]
def DogGenerator(): model = Sequential() model.add(Dense(image_width // scale_factor * image_height // scale_factor * 128, input_shape=(noise_dim,), kernel_initializer=weight_initializer)) #model.add(BatchNormalization(epsilon=BN_EPSILON, momentum=BN_MOMENTUM)) #model.add(LeakyReLU(alpha=leaky_relu_slope)) model.add(Reshape((image_height // scale_factor, image_width // scale_factor, 128))) model = transposed_conv(model, 512, ksize=5, stride_size=1) model.add(Dropout(dropout_rate)) model = transposed_conv(model, 256, ksize=5, stride_size=2) model.add(Dropout(dropout_rate)) model = transposed_conv(model, 128, ksize=5, stride_size=2) model = transposed_conv(model, 64, ksize=5, stride_size=2) model = transposed_conv(model, 32, ksize=5, stride_size=2) model.add(Dense(3, activation='tanh', kernel_initializer=weight_initializer)) return model
The Discriminator is relatively easier to implement, since its basically a small CNN two-class classifier. We can choose whether to apply Spectral Normalization or not and see the performance effects. For this example, I will try to apply SN only in D. Here is D’s structure:
[Input(128, 128, 3) -> Conv(SN)2D(Depth=64, K=5x5, S=1x1, same) -> LeakyReLU -> Conv_Block(Depth=64, K=5x5, S=2x2) -> Conv_Block(Depth=128, K=5x5, S=2x2) -> Conv_Block(Depth=256, K=5x5, S=2x2) -> Flatten -> Dense(16384, Sigmoid)]
Also note that all Conv and Dense layers are initialized with the Truncated Normal distribution defined above. Another thing is that the bias term is removed from the Conv layers, which also stabilizes the model a little bit.
def DogDiscriminator(spectral_normalization=True): model = Sequential() if spectral_normalization: model.add(ConvSN2D(64, (5, 5), strides=(1,1), padding='same', use_bias=False, input_shape=[image_height, image_width, image_channels], kernel_initializer=weight_initializer)) #model.add(BatchNormalization(epsilon=BN_EPSILON, momentum=BN_MOMENTUM)) model.add(LeakyReLU(alpha=leaky_relu_slope)) #model.add(Dropout(dropout_rate)) model = convSN(model, 64, ksize=5, stride_size=2) #model = convSN(model, 128, ksize=3, stride_size=1) model = convSN(model, 128, ksize=5, stride_size=2) #model = convSN(model, 256, ksize=3, stride_size=1) model = convSN(model, 256, ksize=5, stride_size=2) #model = convSN(model, 512, ksize=3, stride_size=1) #model.add(Dropout(dropout_rate)) model.add(Flatten()) model.add(DenseSN(1, activation='sigmoid')) else: ... return modeldog_discriminator = DogDiscriminator(spectral_normalization=True)
One regularization method that can be applied during training is called Label smoothing. What this does is that it essentially prevents D from being overconfident or underconfident in its predictions. If D becomes too certain that there is a dog in a specific image, G can exploit that fact and continuously start to generate only images of that sort and in turn, cease to improve. We can combat this, by setting the class labels to be in the range [0, 0.3] for the negative classes and [0.7, 1] for the positive ones.
This will prevent the overall probabilities from getting very close to the two thresholds.
# Label smoothing -- technique from GAN hacks, instead of assigning 1/0 as class labels, we assign a random integer in range [0.7, 1.0] for positive class# and [0.0, 0.3] for negative classdef smooth_positive_labels(y): return y - 0.3 + (np.random.random(y.shape) * 0.5)def smooth_negative_labels(y): return y + np.random.random(y.shape) * 0.3
This technique is also called Instance Noise. By adding a small amount of error to the labels (let’s say 5%), this tends to make the true and predicted distributions more spread out and thus start to overlap with each other. This in turn makes fitting a custom distribution of generated images easier in the learning process.
Here is a good example of how the two distributions look like with these techniques:
Here is how we can implement Instance Noise:
# randomly flip some labelsdef noisy_labels(y, p_flip): # determine the number of labels to flip n_select = int(p_flip * int(y.shape[0])) # choose labels to flip flip_ix = np.random.choice([i for i in range(int(y.shape[0]))], size=n_select) op_list = [] # invert the labels in place #y_np[flip_ix] = 1 - y_np[flip_ix] for i in range(int(y.shape[0])): if i in flip_ix: op_list.append(tf.subtract(1, y[i])) else: op_list.append(y[i]) outputs = tf.stack(op_list) return outputs
The best proven optimization algorithm for this task is Adam with a standard learning rate of 0.0002 for both models and a beta of 0.5.
generator_optimizer = tf.train.AdamOptimizer(learning_rate=lr_initial_g, beta1=0.5)discriminator_optimizer = tf.train.AdamOptimizer(learning_rate=lr_initial_d, beta1=0.5)
Another new trend in optimizing GANs recently has been applying a Relativistic loss function as opposed to the standard one. Those functions measure the probability that the real data is more “realistic” than the generated data. One of the more popular relativistic function choices include RaLSGAN (Relativistic Average Least Squares), RaSGAN (Relativistic Average Standard) and RaHinge (Relativistic Hinge loss).
But before all of that, let’s define the standard GAN loss:
As we can observe, this is basically the standard Binary Crossentropy loss used for classification tasks or the Logistic Loss between the real and generated distributions. In Tensorflow, this can be defined as follows:
In comparison, here is what an RSGAN (Relativistic Standard) loss looks like:
In this case the task is different, to measure the similarity between the real (r) and fake (f) data distributions. RSGAN reaches the optimal point when D(x) = 0.5 (i.e. C(xr)=C(xf)). There are many relativistic loss function variants and they all contain different methods for measuring this similarity. In this project, I’ve tried out 3 of the variants that seemed to have the best documented MIFID score (RaLSGAN, RaSGAN and RaHinge). Feel free to try out different losses for yourself to see if you can improve the performance ;).
Here’s a big list of the most commonly used ones:
Throughout many trials for this particular problem, I didn’t find any increase in performance by switching to Relativistic losses, so I decided to stick with the standard GAN loss function, as it is much simpler to estimate, though in some cases these losses can really speed up convergence in your model.
Here is what the Discriminator loss function will look like with Label Smoothing and Instance Noise applied. It’s basically the sum of two sub-losses (Fake — in terms of G’s images, Real — in terms of the actual training images).
def discriminator_loss(real_output, fake_output, loss_func, apply_label_smoothing=True, label_noise=True): if label_noise and apply_label_smoothing: real_output_noise = noisy_labels(tf.ones_like(real_output), 0.05) fake_output_noise = noisy_labels(tf.zeros_like(fake_output), 0.05) real_output_smooth = smooth_positive_labels(real_output_noise) fake_output_smooth = smooth_negative_labels(fake_output_noise) if loss_func == 'gan': real_loss = cross_entropy(tf.ones_like(real_output_smooth), real_output) fake_loss = cross_entropy(tf.zeros_like(fake_output_smooth), fake_output) else:... other loss function variants loss = fake_loss + real_loss return loss
And the Generator loss function (with Label Smoothing applied) is just a standard Logistic Loss:
def generator_loss(real_output, fake_output, loss_func, apply_label_smoothing=True): if apply_label_smoothing: fake_output_smooth = smooth_negative_labels(tf.ones_like(fake_output)) if loss_func == 'gan': return cross_entropy(tf.ones_like(fake_output_smooth), fake_output) else:... other loss function variants return loss
Let’s also fix the number of epochs for training and the number of images to feed to the Generator for visualizing intermediate results.
EPOCHS = 280num_examples_to_generate = 64seed = tf.random.normal([num_examples_to_generate, noise_dim])
One training step of a DCGAN consists of three standard steps:
Forward prop — G creates a batch of fake images; this, alongside a batch of real images is fed to D.Calculate both G and D’s loss function.Backprop — compute gradients for G and D optimize the weights.
Forward prop — G creates a batch of fake images; this, alongside a batch of real images is fed to D.
Calculate both G and D’s loss function.
Backprop — compute gradients for G and D optimize the weights.
def train_step(images, loss_type='gan'): noise = tf.random.normal([batch_size, noise_dim]) with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape: generated_images = dog_generator(noise, training=True) real_output = dog_discriminator(images, training=True) fake_output = dog_discriminator(generated_images, training=True) gen_loss = generator_loss(real_output, fake_output, loss_type, apply_label_smoothing=True) disc_loss = discriminator_loss(real_output, fake_output, loss_type, apply_label_smoothing=True, label_noise=True) gradients_of_generator = gen_tape.gradient(gen_loss, dog_generator.trainable_variables) gradients_of_discriminator = disc_tape.gradient(disc_loss, dog_discriminator.trainable_variables) generator_optimizer.apply_gradients(zip(gradients_of_generator, dog_generator.trainable_variables)) discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, dog_discriminator.trainable_variables)) return gen_loss, disc_loss
Let’s also define some functions to visualize the model losses by epoch and as a whole.
def plot_losses(G_losses, D_losses, all_gl, all_dl, epoch): plt.figure(figsize=(10,5)) plt.title("Generator and Discriminator Loss - EPOCH {}".format(epoch)) plt.plot(G_losses,label="G") plt.plot(D_losses,label="D") plt.xlabel("Iterations") plt.ylabel("Loss") plt.legend() ymax = plt.ylim()[1] plt.show() plt.figure(figsize=(10,5)) plt.plot(np.arange(len(all_gl)),all_gl,label='G') plt.plot(np.arange(len(all_dl)),all_dl,label='D') plt.legend() #plt.ylim((0,np.min([1.1*np.max(all_gl),2*ymax]))) plt.title('All Time Loss') plt.show()
We can also use the following function to plot a grid of the generated images.
def generate_and_save_images(model, epoch, test_input, rows, cols): # Notice `training` is set to False. # This is so all layers run in inference mode (batchnorm). predictions = model(test_input, training=False) fig = plt.figure(figsize=(14,14)) for i in range(predictions.shape[0]): plt.subplot(rows, cols, i+1) plt.imshow((predictions[i, :, :, :] * 127.5 + 127.5) / 255.) plt.axis('off') plt.subplots_adjust(wspace=0, hspace=0) plt.savefig('image_at_epoch_{:04d}.png'.format(epoch)) plt.show()
To generate a single test image, we can also reuse the same method.
def generate_test_image(model, noise_dim=noise_dim): test_input = tf.random.normal([1, noise_dim]) # Notice `training` is set to False. # This is so all layers run in inference mode (batchnorm). predictions = model(test_input, training=False) fig = plt.figure(figsize=(5,5)) plt.imshow((predictions[0, :, :, :] * 127.5 + 127.5) / 255.) plt.axis('off') plt.show()
We still haven’t mentioned how a GAN is usually evaluated. Most research papers that use benchmarks to estimate how well a GAN performs are usually based on what’s called the Inception Score. This measures two main characteristics of the input images:
The variety (for example generating different types of dog breeds)
The distinction (or quality of the image)
If both things are true, the score will be high. If either or both are false, the score will be low. A higher score is better. It means your GAN can generate many different distinct images. The lowest score possible is zero. Mathematically the highest possible score is infinity, although in practice there will probably emerge a non-infinite ceiling.
The Inception Score is derived from Google’s Inception Network, which is one of the state-of-the-art deep architectures for classifying images. By passing the images from our GAN through the classifier, we can measure properties of our generated images. To produce the score, we need to calculate the similarity/distance between the real and fake distributions of images. This is done using the KL(Kullback–Leibler) divergence formula:
Here, P and Q are the two measured distributions. In this case, higher KL divergence means better results — the quality of the images is similar and there is a wide variety of labels present. In the opposite case, the low KL divergence can be due to either low quality or low variety of labels:
One shortcoming for IS is that it can misrepresent the performance if it only generates one image per class. To combat this we can use the FID (Frechet Inception Distance). This measure defines the two previous types of images as multivariate Gaussian distributions with mean μ and covariance Σ (Sigma). Let’s see how this distance is calculated:
Here, x and g represent the real and fake distribution of images, while Tr is the sum of diagonal elements of the results.
Lower FID values mean better image quality and diversity.
Here are also a few useful notes on why FID is a good measure:
FID is more robust to noise than IS.
If the model only generates one image per class, the distance will be high. So FID is a better measurement for image diversity.
By computing the FID between a training dataset and a testing dataset, we should expect the FID to be zero since both are real images. (although there is usually a small amount of error)
FID and IS are based on feature extraction (the presence or the absence of features).
Here is Kaggle’s official evaluation workflow for the Generative Dogs competition:
As we can see, in addition to the FID metric, there is an additional Memorization Score added to the calculation. This is basically a Cosine distance formula that measures the similarity between the real (images from a private dataset) and fake images. My guess is that this has been done to make sure that the images fed to the evaluation kernel have actually been generated by a GAN and not just replicated or modified from the real dataset.
Thankfully, the MIFID evaluator has been implemented by the Kaggle team (here) and we don’t have to worry about it.
I’m just going to add two more for zipping the final 10K images for submission and generating temporary images to calculate the MIFID in between certain epochs during training.
def zip_images(filename='images.zip'): # SAVE TO ZIP FILE NAMED IMAGES.ZIP z = zipfile.PyZipFile(filename, mode='w') for k in range(image_sample_size): generated_image = dog_generator(tf.random.normal([1, noise_dim]), training=False) f = str(k)+'.png' img = np.array(generated_image) img = (img[0, :, :, :] + 1.) / 2. img = Image.fromarray((255*img).astype('uint8').reshape((image_height,image_width,image_channels))) img.save(f,'PNG') z.write(f) os.remove(f) #if k % 1000==0: print(k) z.close() print('Saved final images for submission.') def save_images(directory=OUT_DIR): for k in range(image_sample_size): generated_image = dog_generator(tf.random.normal([1, noise_dim]), training=False) f = str(k)+'.png' f = os.path.join(directory, f) img = np.array(generated_image) img = (img[0, :, :, :] + 1.) / 2. img = Image.fromarray((255*img).astype('uint8').reshape((image_height,image_width,image_channels))) img.save(f,'PNG') #if k % 1000==0: print(k) print('Saved temporary images for evaluation.')
It’s finally time to implement the final training function that wraps up the whole process. There are also a few techniques used here that I haven’t mentioned yet. Let’s see what they are.
This one is experimental and doesn’t always help improve performance, but I don’t think it would hurt either way. The idea here is to decrease the learning rate by a very small amount for each training step/steps, in order to stabilize the training process and speed up convergence (and escape from local minima). For this project, I am using the Cosine learning rate decay in Tensorflow to reduce the learning rate for every decay_step iterations.
Other than Non-convergence and Vanishing and Exploding gradients, GANs sometimes suffer from another major problem called Mode Collapse. This happens when G starts to produce limited varieties of samples. Here is a good example of Mode Collapse for a GAN trained on the MNIST dataset where G continuously produces only images for a single class label:
We’ve already seen some methods that can potentially eliminate Mode Collapse like Label smoothing, Instance Noise, Weight Initialization and so on. One other method that we could apply during training is called Experience Replay.
Experience Replay preserves some of the recently generated images in memory. For every replay_step iterations, we train D on those previous images to "remind" the network of previous generations and thus decrease the chance of overfitting to a particular instance of data batches during training. In this example, I am using a slightly different form of Experience Replay in the sense that, I am generating a new extra image for each training step to store in a list, instead of feeding it actual generated images from previous iterations, since storing data during Eager execution isn't an easy task.
''' generated_image = dog_generator(tf.random.normal([1, noise_dim]), training=False) exp_replay.append(generated_image) if len(exp_replay) == replay_step: print('Executing experience replay..') replay_images = np.array([p[0] for p in exp_replay]) dog_discriminator(replay_images, training=True) exp_replay = [] '''
EDIT: As Kaggle was running into memory issues after ~7–8 hours of runtime, I decided against using experience replay. Let me know if you find a workaround for this :D.
All in all, the training process is fairly straight-forward. There are additional steps for displaying the intermediate results like the images, losses and calculating the MIFID. At the end of the learning process, we print out the final evaluation and a larger grid of the final images.
display_results = 40calculate_mifid = 100replay_step = 50decay_step = 50def train(dataset, epochs): all_gl = np.array([]); all_dl = np.array([]) for epoch in tqdm(range(epochs)): G_loss = []; D_loss = [] start = time.time() new_lr_d = lr_initial_d new_lr_g = lr_initial_g global_step = 0 for image_batch in dataset: g_loss, d_loss = train_step(image_batch) global_step = global_step + 1 G_loss.append(g_loss); D_loss.append(d_loss) all_gl = np.append(all_gl,np.array([G_loss])) all_dl = np.append(all_dl,np.array([D_loss])) if (epoch + 1) % display_results == 0 or epoch == 0: plot_losses(G_loss, D_loss, all_gl, all_dl, epoch + 1) generate_and_save_images(dog_generator, epoch + 1, seed, rows=8, cols=8) if (epoch + 1) % calculate_mifid == 0: OUT_DIR.mkdir(exist_ok=True) save_images(OUT_DIR) evaluator = MiFIDEvaluator(MODEL_PATH, TRAIN_DIR) fid_value, distance, mi_fid_score = evaluator.evaluate(OUT_DIR) print(f'FID: {fid_value:.5f}') print(f'distance: {distance:.5f}') print(f'MiFID: {mi_fid_score:.5f}') shutil.rmtree(OUT_DIR) print('Removed temporary image directory.') # Cosine learning rate decay if (epoch + 1) % decay_step == 0: new_lr_d = tf.train.cosine_decay(new_lr_d, min(global_step, lr_decay_steps), lr_decay_steps) new_lr_g = tf.train.cosine_decay(new_lr_g, min(global_step, lr_decay_steps), lr_decay_steps) generator_optimizer = tf.train.AdamOptimizer(learning_rate=new_lr_d, beta1=0.5) discriminator_optimizer = tf.train.AdamOptimizer(learning_rate=new_lr_g, beta1=0.5) print('Epoch: {} computed for {} sec'.format(epoch + 1, time.time() - start)) print('Gen_loss mean: ', np.mean(G_loss),' std: ', np.std(G_loss)) print('Disc_loss mean: ', np.mean(D_loss),' std: ', np.std(D_loss)) # Generate after the final epoch and repeat the process generate_and_save_images(dog_generator, epochs, seed, rows=8, cols=8) checkpoint.save(file_prefix = checkpoint_prefix) OUT_DIR.mkdir(exist_ok=True) save_images(OUT_DIR) evaluator = MiFIDEvaluator(MODEL_PATH, TRAIN_DIR) fid_value, distance, mi_fid_score = evaluator.evaluate(OUT_DIR) print(f'FID: {fid_value:.5f}') print(f'distance: {distance:.5f}') print(f'MiFID: {mi_fid_score:.5f}') shutil.rmtree(OUT_DIR) print('Removed temporary image directory.') print('Final epoch.')
Here are some of the generated dog images during training:
As we can observe, the MIFID steadily improves for 280 epochs (~ 8 hours). The best score that I achieved using this model during the competition was 55.87. The learning process does tend to be somewhat random so I think a score around the region of [50, 65] should be realistic. Feel free to train this model for longer, if you have the time, as it has potential to keep improving :).
Finally, I’ll show you how to make a fun GIF to see a nice little simulation of the DCGAN’s learning process (code from Tensorflow’s DCGAN tutorial).
anim_file = 'dcgan.gif'with imageio.get_writer(anim_file, mode='I') as writer: filenames = glob.glob('image*.png') filenames = sorted(filenames) last = -1 for i,filename in enumerate(filenames): frame = 1*(i**2) if round(frame) > round(last): last = frame else: continue image = imageio.imread(filename) writer.append_data(image) image = imageio.imread(filename) writer.append_data(image)import IPythonif IPython.version_info > (6,2,0,''): IPython.display.Image(filename=anim_file)
To sum up, DCGANs seem to be extremely sensitive to hyperparameter choice and a lot of problems can arise during training, including Mode Collapse. They are also very computationally intensive and it is incredibly hard to build a high-scoring model for a runtime of ~9 hours. Fortunately, there is a whole bucket list of possible methods and techniques that are well-documented and can be easily applied to your model to stabilize the training process.
For me personally, it was really fun to toy around with these techniques and break a few kernels in the process :D. Feel free to leave any suggestions down in the comments (for improving the model or fixing something that I messed up).
Big thanks to Chris Deotte, Nanashi, Chad Malla and Nirjhar Roy for their Kaggle kernels and examples during the competition. I’ll leave links to them down below.
Overall, this was the first Kaggle competition that I’ve ever entered and it was an extremely fun method for learning about GANs and playing around with them. This seems to be Kaggle’s first competition involving generative modelling and let’s hope that more exciting challenges like this will come in the future ;).
[1]. My previous kernel on EDA and image preprocessing
[2]. Xml parsing and cropping to specified bounding box
[3]. Image cropping method with interpolation
[4]. Another great Keras-based DCGAN approach by Chad Malla
[5]. DCGAN hacks for improving your model performance
[6]. Tensorflow DCGAN tutorial
[7]. DCGAN Dogs Images by Nanashi
[8]. GAN dogs starter 24-Jul -Custom Layers by Nirjhar Roy
[9]. Supervised Generative Dog Net by Chris Deotte
[10]. My best submission for this competition
[1]. Ian Goodfellow, J. Pouget-Abadie, M. Mirza, B. Xu, S. Ozair, Y. Bengio, Generative Adversarial Networks (2014)
[2]. J. Rocca, Understanding Generative Adversarial Networks (GANs)
[3]. J. Brownlee, A Gentle Introduction to Generative Adversarial Networks (GANs)
[4]. A. Radford, L. Metz, S. Chintala, Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks (2015)
[5]. J. Hui, GAN — DCGAN (Deep convolutional generative adversarial networks)
[6]. S. Yadav, Weight Initialization Techniques in Neural Networks
[7]. T. Miyato, T. Kataoka, M. Koyama, Y. Yoshida, Spectral Normalization for Generative Adversarial Networks (2018)
[8]. IShengFang, Spectral Normalization implemented in Keras
[9]. C. Cosgrove, Spectral Normalization Explained
[10]. J. Hui, GAN — Ways to improve GAN performance
[11]. J. Brownlee, How to Implement GAN Hacks in Keras to Train Stable Models
[12]. Y. Jiao, Tricks of GANS
[13]. C. K. Sønderby, Instance Noise: A trick for stabilising GAN training
[14]. J. Hui, GAN — RSGAN & RaGAN (A new generation of cost function.)
[15]. D. Mack, A simple explanation of the Inception Score
[16]. J. Hui, GAN — How to measure GAN performance?
[17]. All you need is GAN Hacks
[18]. How to train your touchy GANs — Things that seem to work.
[19]. Explaining the metric FID | [
{
"code": null,
"e": 496,
"s": 172,
"text": "This post is a tutorial on the basic ideas behind the effectiveness of DCGANs, as well as some methods/hacks to improve their performance. These methods are all based on my experience during Kaggle’s Generative Dogs Competition. The tutorial is also avail... |
Forecast Model Tuning with Additional Regressors in Prophet | by Andrej Baranovskij | Towards Data Science | I’m going to share my experiment results with Prophet additional regressors. My goal was to check how extra regressor would weight on forecast calculated by Prophet.
Using dataset from Kaggle — Bike Sharing in Washington D.C. Dataset. Data comes with a number for bike rentals per day and weather conditions. I have created and compared three models:
Time series Prophet model with date and number of bike rentalsA model with additional regressor —weather temperatureA model with additional regressor s— weather temperature and state (raining, sunny, etc.)
Time series Prophet model with date and number of bike rentals
A model with additional regressor —weather temperature
A model with additional regressor s— weather temperature and state (raining, sunny, etc.)
We should see the effect of regressor and compare these three models.
The forecast is calculated for ten future days. Last day available in the dataset is 2012–12–31, this means forecast starts from 2013–01–01.
A. Model without additional regressors
Forecast values for bike rentals, starting from 2013–01–01:
B. Model with the additional regressor — weather temperature
Regressor value must be known in the past and in the future, this is how it helps Prophet to adjust the forecast. The future value must be either predefined and known (for example, a specific event happening in certain dates) or it should be forecasted elsewhere. In our case — we are using weather temperature forecast, which we can get from the weather channel.
Values for regressor must be in the same data frame as time series data. I have copied a date column to be defined as an index column:
df = pd.read_csv('weather_day.csv')df = df[['dteday', 'cnt', 'temp']].dropna()d_df['date_index'] = d_df['dteday']d_df['date_index'] = pd.to_datetime(d_df['date_index'])d_df = d_df.set_index('date_index')
We need to construct future data-frame for ten days — creating Pandas data-frame for ten days from 2013–01–01 and initializing each element with temperature forecast (normalized value):
t = 13min_t = -8max_t = 39n_t = (t - min_t)/(max_t - min_t)print(n_t)future_range = pd.date_range('2013-01-01', periods=10, freq='D')future_temp_df = pd.DataFrame({ 'future_date': future_range, 'future_temp' : 0})future_temp_df['future_date'] = pd.to_datetime(future_temp_df['future_date'])future_temp_df = future_temp_df.set_index('future_date')future_temp_df.at['2013-01-01', 'future_temp'] = 0.319148future_temp_df.at['2013-01-02', 'future_temp'] = 0.255319future_temp_df.at['2013-01-03', 'future_temp'] = 0.234042future_temp_df.at['2013-01-04', 'future_temp'] = 0.319148future_temp_df.at['2013-01-05', 'future_temp'] = 0.340425future_temp_df.at['2013-01-06', 'future_temp'] = 0.404255future_temp_df.at['2013-01-07', 'future_temp'] = 0.361702future_temp_df.at['2013-01-08', 'future_temp'] = 0.404255future_temp_df.at['2013-01-09', 'future_temp'] = 0.425531future_temp_df.at['2013-01-10', 'future_temp'] = 0.446808future_temp_df.tail(10)
With below code, I’m adding regressor for weather temperature. If the date falls into the training set, then returning temperature from the training set, otherwise from a future forecast data frame (the one constructed above). Period for ten days into the future is set. Prophet model is constructed with fit function, predict function is called to calculate forecast:
def weather_temp(ds): date = (pd.to_datetime(ds)).date() if d_df[date:].empty: return future_temp_df[date:]['future_temp'].values[0] else: return (d_df[date:]['temp']).values[0] return 0m = Prophet()m.add_regressor('temp')m.fit(d_df)future = m.make_future_dataframe(periods=10)future['temp'] = future['ds'].apply(weather_temp)forecast = m.predict(future)forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(15)
Forecast value for bike rentals, with additional regressor for the temperature, starting from 2013–01–01. The temperature forecast is good, warm weather for January is expected, this helps to adjust numbers for bike rentals to be higher (naturally there should be more rentals if weather temperature is good):
C. Model with two additional regressors— weather temperature and condition
The dataset contains quite a few attributes which describe the weather, using more of these attributes would help to calculate the more accurate forecast for bike rentals. I will show how adding one more regressor could change the forecast.
def weather_temp(ds): date = (pd.to_datetime(ds)).date() if d_df[date:].empty: return future_temp_df[date:]['future_temp'].values[0] else: return (d_df[date:]['temp']).values[0] return 0def weather_condition(ds): date = (pd.to_datetime(ds)).date() if d_df[date:].empty: return future_temp_df[date:]['future_weathersit'].values[0] else: return (d_df[date:]['weathersit']).values[0] return 0m = Prophet()m.add_regressor('temp')m.add_regressor('weathersit')m.fit(d_df)future = m.make_future_dataframe(periods=10)future['temp'] = future['ds'].apply(weather_temp)future['weathersit'] = future['ds'].apply(weather_condition)forecast = m.predict(future)forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(15)
Additional regressor — weather condition (check weathersit attribute in the dataset) is added using the above code, along with weather temperature regressor. For the test purpose, I’m setting weather condition equal to 4 (this means bad weather) for all ten days in the future. Even if weather temperature in January is increasing (which is good for bike rentals), overall weather is bad (this should decrease the number of bike rentals).
With the second regressor (pointing to bad expected bad weather), Prophet returns smaller expected bike rental numbers:
Summary: Additional regressors feature is very important for accurate forecast calculation in Prophet. It helps to tune how the forecast is constructed and make prediction process more transparent. Regressor must be a variable which was known in the past and known (or separately forecasted for the future).
Resources:
GitHub repo with the source code
My previous post about the same topic — Serving Prophet Model with Flask — Predicting Future | [
{
"code": null,
"e": 338,
"s": 172,
"text": "I’m going to share my experiment results with Prophet additional regressors. My goal was to check how extra regressor would weight on forecast calculated by Prophet."
},
{
"code": null,
"e": 523,
"s": 338,
"text": "Using dataset from K... |
PostgreSQL - FETCH clause - GeeksforGeeks | 28 Aug, 2020
The PostgreSQL FETCH clause has a functionality similar to the PostgreSQL LIMIT clause. It is used to retrieve a portion of rows returned by a query. As the LIMIT clause is not a standard SQL-command, PostgreSQL provides a standard way of fetching a subset of results from a query.
Syntax:OFFSET start { ROW | ROWS }FETCH { FIRST | NEXT } [ row_count ] { ROW | ROWS } ONLY
Let’s analyze the above syntax:
ROW and FIRST are synonymous with ROWS and NEXT respectively.
The start is an integer value that is either zero or positive. By default, it is zero.
The row_count is either one or higher. By default, it is one.
As the order of rows stored in the table is unpredictable, one should always use the FETCH clause with the ORDER BY clause to make the result set consistent.
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link.
Now, let’s look into a few examples.
Example 1:Here we will query the first 10 rows of the film sorted by “title” from the film table of our sample database.
SELECT
film_id,
title
FROM
film
ORDER BY
title
FETCH FIRST 10 ROW ONLY;
Output:
Example 2:Here we will query the first 10 rows of the film after the first five films, sorted by “title” from the film table of our sample database.
SELECT
film_id,
title
FROM
film
ORDER BY
title
OFFSET 5 ROWS
FETCH FIRST 10 ROW ONLY;
Output:
postgreSQL-clauses
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Change Column Type
PostgreSQL - Psql commands
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - Interval Data Type
How to use PostgreSQL Database in Django? | [
{
"code": null,
"e": 28000,
"s": 27972,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 28282,
"s": 28000,
"text": "The PostgreSQL FETCH clause has a functionality similar to the PostgreSQL LIMIT clause. It is used to retrieve a portion of rows returned by a query. As the LIMIT ... |
Scala Collections - Filter Method | filter() method is method used by List to select all elements which satisfies a given predicate.
The following is the syntax of filter method.
def filter(p: (A) => Boolean): List[A]
Here, p: (A) => Boolean is a predicate or condition to be applied on each element of the list. This method returns the all the elements of list which satisfiles the given condition.
Below is an example program of showing how to use filter method −
object Demo {
def main(args: Array[String]) = {
val list = List(3, 6, 9, 4, 2)
// print list
println(list)
//apply operation
val result = list.filter(x=>{x % 3 == 0})
//print result
println(result)
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
List(3, 6, 9, 4, 2)
List(3, 6, 9)
82 Lectures
7 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
52 Lectures
1.5 hours
Bigdata Engineer
76 Lectures
5.5 hours
Bigdata Engineer
69 Lectures
7.5 hours
Bigdata Engineer
46 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2979,
"s": 2882,
"text": "filter() method is method used by List to select all elements which satisfies a given predicate."
},
{
"code": null,
"e": 3025,
"s": 2979,
"text": "The following is the syntax of filter method."
},
{
"code": null,
"e": 30... |
Feature Transformation for Multiple Linear Regression in Python | by Bonnie Ma | Towards Data Science | Data processing and transformation is an iterative process and in a way, it can never be ‘perfect’. Because as we gain more understanding on the dataset, such as the inner relationships between target variable and features, or the business context, we think of new ways to deal with them. Recently I started working on media mix models and some predictive models utilizing multiple linear regression. In this post, I will introduce the thought process and different ways to deal with variables for modeling purpose.
I will use King County house price data set (a modified version for more fun) as an example.
Let’s import libraries and look at the data first!
import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport scipy.stats as stats% matplotlib inlinedf = pd.read_csv(“kc_house_data.csv”)df.head()
Identify missing values, and obvious incorrect data types.
df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 21597 entries, 0 to 21596Data columns (total 21 columns):id 21597 non-null int64date 21597 non-null objectprice 21597 non-null float64bedrooms 21597 non-null int64bathrooms 21597 non-null float64sqft_living 21597 non-null int64sqft_lot 21597 non-null int64floors 21597 non-null float64waterfront 19221 non-null float64view 21534 non-null float64condition 21597 non-null int64grade 21597 non-null int64sqft_above 21597 non-null int64sqft_basement 21597 non-null objectyr_built 21597 non-null int64yr_renovated 17755 non-null float64zipcode 21597 non-null int64lat 21597 non-null float64long 21597 non-null float64sqft_living15 21597 non-null int64sqft_lot15 21597 non-null int64dtypes: float64(8), int64(11), object(2)memory usage: 3.5+ MB
In most statistical models, variables can be grouped into 4 data types:
Continuous: it can have an infinite number of possible values within a selected range. ‘float’ is usually used for continuous data in python. e.g. the footage of the living area
Nominal: nominal variables use a numerical representation to interpret types or attributes of objects. They are categorical values with 2 or more possible values and have no inherent order or ranking sequence. For example, origin country of cars, US can be 1, Japan 2, Germany 3
Ordinal: ordinal variables are actually presenting numerical values. They usually have 2 or more possible values in a limited range and these values have ordered categories. e.g. grade of house. When you plot ordinal values with target, you will often see clear vertical line. Ordinal data might be read as integer or float in your dataset so data visualization is always helpful to detect them
Binary: only have 2 possible values usually 0 and 1. Dummy variables are binary
Below chart shows clearly the relationship.
Log: Log transformation helps reducing skewness when you have skewed data.
Take house price as an example.
df_log[‘price’] = np.log(df[‘price’])sns.distplot(df_set['price'], fit=norm)fig = plt.figure()
Power: if we know by nature the independent variable has exponential or diminishing relationship with the target variable, we can use power transformation. For example, when we try to model TV ad spend against sales volume, we know that at some point, the impact of TV advertisement on sales will decrease. This is so called “diminishing return”. So we usually use the power of 0.3 to 0.7 to transform TV spend so that we can get better model fit.
Standardization: minus the mean and divide by standard deviation. The standardization does not make data more normal, it will just change the mean and the standard error.
scaled_price = (logprice -np.mean(logprice))/np.sqrt(np.var(logprice))
Mean normalization: the distribution will have values between -1 and 1, and a mean of 0.
Min-max scaling: brings values between 0 and 1
Label Encoding: this is when the actual value is text and you want to create numerical values for the variable. For example:
origin = [“USA”, “EU”, “EU”, “ASIA”,”USA”, “EU”, “EU”, “ASIA”, “ASIA”, “USA”]origin_series = pd.Series(origin)cat_origin = origin_series.astype('category')cat_origin.cat.codes0 21 12 13 04 25 16 17 08 09 2dtype: int8#Or use scikit-learn's LabelEncoder:from sklearn.preprocessing import LabelEncoderlb_make = LabelEncoder()origin_encoded = lb_make.fit_transform(cat_origin)origin_encodedarray([2, 1, 1, 0, 2, 1, 1, 0, 0, 2])
Binning: binning is very handy when comes to ordinal values. In stead of reading the ordinal values as integers in the model, we can transform the variable to categorical by creating bins based on the value distribution and then create dummy variables.
In King County house price example, grade is an ordinal variable that has positive correlation with house price.
df[‘grade’].describe()count 21596.000000mean 7.657946std 1.173218min 3.00000025% 7.00000050% 7.00000075% 8.000000max 13.000000Name: grade, dtype: float64
We can create 4 bins based on percentile values.
bins = [3,7,8,10,13]bins_grade = pd.cut(df[‘grade’],bins)bins_grade.value_counts().plot(kind='bar')
bins_grade0 (3, 7]1 (3, 7]2 (3, 7]3 (3, 7]4 (7, 8]5 (10, 13]6 (3, 7]7 (3, 7]8 (3, 7]9 (3, 7]10 (7, 8]11 (3, 7]12 (3, 7]13 (3, 7]14 (3, 7]15 (8, 10]
We then create dummy variables for them because some of the modeling technique requires numerical values.
bins_grade = bins_grade.cat.as_unordered()grade_dummy = pd.get_dummies(bins_grade, prefix=’grade’)
Create dummy variables
Another way to create dummy variables is to use LabelBinarizer from sklearn.preprocessing package
from sklearn.preprocessing import LabelBinarizerlb = LabelBinarizer()grade_dummies = lb.fit_transform(grade)# you need to convert this back to a dataframegrade_dum_df = pd.DataFrame(grade_dummies,columns=lb.classes_)
The advantage of using dummies is that, whatever algorithm you’ll be using, your numerical values cannot be misinterpreted as being continuous. Going forward, it’s important to know that for linear regression (and most other algorithms in scikit-learn), one-hot encoding is required when adding categorical variables in a regression model!
Again, feature transformation involves multiple iterations. There are many ways to get the data right for the model. Just be curious and patient! | [
{
"code": null,
"e": 688,
"s": 172,
"text": "Data processing and transformation is an iterative process and in a way, it can never be ‘perfect’. Because as we gain more understanding on the dataset, such as the inner relationships between target variable and features, or the business context, we thi... |
D3.js geoAzimuthalEquidistant() Function - GeeksforGeeks | 18 Sep, 2020
The geoAzimuthalEquidistant() function in d3.js is used to draw the Azimuthal equidistant projection from the given geojson data. It is a map projection where all the points on the map are at correct distances from the center point proportionally. Also, all points on the map are in the correct direction from the center point.
Syntax:
d3.geoAzimuthalEquidistant()
Parameters: This method does not accept any parameters.
Return Value: This method returns the Azimuthal equidistant projection.
Example 1: The following example draws the Azimuthal equidistant projection of the world with the center at (0,0).
HTML
<html> <head> <script src="https://d3js.org/d3.v4.js"> </script> <script src="https://d3js.org/d3-geo-projection.v2.min.js"> </script></head> <body> <div style="width:800px; height:600px;"> <center> <h3 style="color:black"> AzimuthalEquidistant Projection of World </h3> </center> <svg width="700" height="550"> </svg> </div> <script> var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"); // AzimuthalEquidistant projection var gfg = d3.geoAzimuthalEquidistant() .scale(width / 1.5 / Math.PI) .translate([width / 2, height / 2]); // Loading the geojson data d3.json("https://raw.githubusercontent.com/" + "janasayantan/datageojson/master/" + "geoworld%20.json", function (data) { // Draw the map svg.append("g") .selectAll("path") .data(data.features) .enter().append("path") .attr("fill", "Silver") .attr("d", d3.geoPath() .projection(gfg) ) .style("stroke", "#ffff") }); </script></body> </html>
Output:
Example 2: The following example makes Azimuthal equidistant projection centered at(-10,0) and rotated 10 degrees anti-clockwise with respect to the x-axis.
HTML
<!DOCTYPE html><html> <head> <script src="https://d3js.org/d3.v4.js"> </script> <script src="https://d3js.org/d3-geo-projection.v2.min.js"> </script></head> <body> <div style="width:700px; height:600px;"> <center> <h3 style="color:grey"> AzimuthalEquidistant Projection of World </h3> </center> <svg width="700" height="550"> </svg> </div> <script> var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"); // AzimuthalEquidistant projection // Center(0,-10) and roating -10 degree var gfg = d3.geoAzimuthalEquidistant() .scale(width / 1.5 / Math.PI) .rotate([-10, 0]) .center([0, -10]) .translate([width / 2, height / 2]); // Loading the geojson data d3.json("https://raw.githubusercontent.com/" + "janasayantan/datageojson/master/" + "world.json", function (data) { // Draw the map svg.append("g") .selectAll("path") .data(data.features) .enter().append("path") .attr("fill", "green") .attr("d", d3.geoPath() .projection(gfg) ) .style("stroke", "#ffff") }); </script></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24924,
"s": 24896,
"text": "\n18 Sep, 2020"
},
{
"code": null,
"e": 25252,
"s": 24924,
"text": "The geoAzimuthalEquidistant() function in d3.js is used to draw the Azimuthal equidistant projection from the given geojson data. It is a map projection where all ... |
LocalTime isAfter() method in Java with Examples - GeeksforGeeks | 03 Dec, 2018
The isAfter() method of a LocalTime class is used to check if this LocalTime timeline position is after the LocalTime passed as parameter or not. If this LocalTime timeline position is after the LocalTime passed as a parameter then the method will return true else false. The comparison is based on the time-line position of the instants.
Syntax:
public boolean isAfter(LocalTime other)
Parameters: This method accepts a single parameter other which is the other LocalTime object to compare to. It should not be null.
Return value: This method returns true if this time is after the specified time, else false.
Below programs illustrate the isAfter() method:
Program 1:
// Java program to demonstrate// LocalTime.isAfter() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime time1 = LocalTime.parse("19:34:50.63"); // create other LocalTime LocalTime time2 = LocalTime.parse("23:14:00.63"); // print instances System.out.println("LocalTime 1: " + time1); System.out.println("LocalTime 2: " + time2); // check if LocalTime is after LocalTime // using isAfter() boolean value = time1.isAfter(time2); // print result System.out.println("Is LocalTime1 after LocalTime2: " + value); }}
LocalTime 1: 19:34:50.630
LocalTime 2: 23:14:00.630
Is LocalTime1 after LocalTime2: false
Program 2:
// Java program to demonstrate// LocalTime.isAfter() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime time1 = LocalTime.parse("23:59:11.98"); // create other LocalTime LocalTime time2 = LocalTime.parse("10:24:53.21"); // print instances System.out.println("LocalTime 1: " + time1); System.out.println("LocalTime 2: " + time2); // check if LocalTime is after LocalTime // using isAfter() boolean value = time1.isAfter(time2); // print result System.out.println("Is LocalTime1 after LocalTime2: " + value); }}
LocalTime 1: 23:59:11.980
LocalTime 2: 10:24:53.210
Is LocalTime1 after LocalTime2: true
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#isAfter(java.time.LocalTime)
Java-Functions
Java-LocalTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java
Overriding in Java | [
{
"code": null,
"e": 24220,
"s": 24192,
"text": "\n03 Dec, 2018"
},
{
"code": null,
"e": 24559,
"s": 24220,
"text": "The isAfter() method of a LocalTime class is used to check if this LocalTime timeline position is after the LocalTime passed as parameter or not. If this LocalTime... |
Error Handling in C | Error handling is not supported by C language. There are some other ways by which error handling can be done in C language. The header file “error.h” is used to print the errors using return statement function.
It returns -1 or NULL in case of any error and errno variable is set with the error code. Whenever a function is called in C language, errno variable is associated with it. errno is a global variable and is used to find the type of error in the execution.
The following table displays some errors −
There are some methods to handle errors in C language −
perror() − This function is used to print the error and it returns the string along with the textual representation of current errno value.
perror() − This function is used to print the error and it returns the string along with the textual representation of current errno value.
strerror() − This function is declared in “string.h” header file and it returns the pointer to the string of current errno value.
strerror() − This function is declared in “string.h” header file and it returns the pointer to the string of current errno value.
Exit status − There are two constants EXIT_SUCCESS and EXIT_FAILURE which can be used in function exit() to inform the calling function about the error.
Exit status − There are two constants EXIT_SUCCESS and EXIT_FAILURE which can be used in function exit() to inform the calling function about the error.
Divided by zero − This is a situation in which nothing can be done to handle this error in C language. Avoid this error and you can check the divisor value by using ‘if’ condition in the program.
Divided by zero − This is a situation in which nothing can be done to handle this error in C language. Avoid this error and you can check the divisor value by using ‘if’ condition in the program.
Here is an example of error handling in C language,
Live Demo
#include <stdio.h>
#include <stdlib.h>
main() {
int x = 28;
int y = 8;
int z;
if( y == 0) {
fprintf(stderr, "Division by zero!\n");
exit(EXIT_FAILURE);
}
z = x / y;
fprintf(stderr, "Value of z : %d\n", z );
exit(EXIT_SUCCESS);
}
Here is the output
Value of z : 3 | [
{
"code": null,
"e": 1273,
"s": 1062,
"text": "Error handling is not supported by C language. There are some other ways by which error handling can be done in C language. The header file “error.h” is used to print the errors using return statement function."
},
{
"code": null,
"e": 1529,... |
Find second largest element | Practice | GeeksforGeeks | Given an array of elements. Your task is to find the second maximum element in the array.
Example 1:
Input:
N=5
arr[] = { 2, 4, 5, 6, 7 }
Output: 6
Explanation:
The largest element is 7 and
the second largest element is 6.
Example 2:
Input:
N=6
arr[] = { 7, 8, 2, 1, 4, 3 }
Output: 7
Your Task:
Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function print2largest() that takes array A and integer N as parameters and returns the second maximum element in the array. If there does not exist any second largest element, then return -1.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ N ≤ 106
0
emaniharsha8 hours ago
Working O(n) solution in single loop:
print2largest(arr, n){
let [first, second] = [arr[0], -1];
for(let i = 0; i < n; i++){
if(first < arr[i]){
second = first;
first = arr[i];
} else if(arr[i] > second && arr[i] != first)
second = arr[i];
}
return second;
}
0
pradeepshillare3 days ago
int ans = -1; Arrays.sort(A); for(int i=0;i<A.length-1;i++) { if(A[i]!=A[i+1]) { ans = A[i]; } } return ans;
0
pradeepshillare3 days ago
Set<Integer> s = new HashSet<Integer>(); for(int i=0;i<N;i++) { s.add(A[i]); } List<Integer> l = new ArrayList<Integer>(s); if(s.size()==1) return -1; else Collections.sort(l); int u = l.get(s.size()-2); return u;
0
kushganesh124 days ago
blic static int print2largest(int A[],int N) { Arrays.sort(A); int mp=-1; for(int i=0;i<N-1;i++) { if(A[i]<A[i+1]) mp=A[i]; }
return mp; }
0
vishalja77195 days ago
int print2largest(int arr[], int arr_size)
{
//code here.
set<int>s;
for(int i=0;i<arr_size;i++)
{
s.insert(arr[i]);
}
if(s.size() == 1)
return -1;
else{
auto it=s.end();
--it;
--it;
return *it;
}
}
-2
nishabisht2236 days ago
public static int print2largest(int A[],int N) { Arrays.sort(A); return A[A.length-2]; }
+1
cs190951 week ago
//simple c++ solution using vector and set
int print2largest(int arr[], int n)
{
//code here.
int ans;
vector<int>v;
set<int>s;
for(int i=0;i<n;i++)
{
s.insert(arr[i]);
}
if(s.size()==1)
{
return -1;
}
else
{
v.assign(s.begin(),s.end());
int size=s.size();
sort(v.begin(),v.end());
ans=v.at(size-2);
return ans;
}
}
0
harshilrpanchal19981 week ago
java
int first=0,second=0; for(int i=0;i<N;i++) { if(A[i]>first) first=A[i]; } for(int i=0;i<N ;i++) { if(A[i]>second && A[i]<first) second=A[i]; } if(second==0 || N<2){ return -1;} return second;
0
harshilrpanchal19981 week ago
java solution
HashSet<Integer> set = new HashSet<>(); for (int element: A){ set.add(element); }
int[] array = new int[set.size()]; int i=0; for (Integer ele: set){ array[i++] = ele; } Arrays.sort(array);
if (N == 1){ return array[0]; } if(N == 0){ return -1; } return array[array.length -2];
+1
harshscode1 week ago
O(n).............................................................
int first=0,second=0; for(int i=0;i<n;i++) { if(a[i]>first) first=a[i]; } for(int i=0;i<n;i++) { if(a[i]>second and a[i]<first) second=a[i]; } if(second==0 or n<2) return -1; else return second; }
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": 328,
"s": 238,
"text": "Given an array of elements. Your task is to find the second maximum element in the array."
},
{
"code": null,
"e": 339,
"s": 328,
"text": "Example 1:"
},
{
"code": null,
"e": 464,
"s": 339,
"text": "Input:\nN=5\narr... |
Using Stringr and Regex to Extract Features in R | Towards Data Science | Large data sets are often awash with data that is difficult to decipher. One may think of textual data, names, unique identifiers, and other sorts of codes. Frequently, people analyzing these datasets are quick to discard these variables. However, sometimes there might be valuable information in this type of data, which might help you with your analysis.
Gladly, R offers the amazing package “stringr,” which is perfect for these purposes. This quick tutorial will show you how you can extract minute but still insightful data from these kinds of variables. In this case, we will be extracting this kind of data from the Titanic dataset.
If you’d like to follow the tutorial, load the Titanic data set using the below commands. The Titanic data set features all kinds of information on the Titanic passengers to practice predicting their survival. This tutorial aims to look at some of the variables (i.e., name and ticket) that most people discard immediately when beginning their analysis. We, however, want to work with them to see if we can extract some useful information. If you want to figure out how to use Stringr and regex, skip this part.
### install packageinstall.packages("titanic")### load packagelibrary(titanic)### load datasetdf = titanic_train #load dataset
Before we begin, we need to install and load the Stringr package.
### install packageinstall.packages("stringr")### load packagelibrary(stringr)
Now, we’re all set, and we can begin.
As a first exercise, I’d like to extract the titles from the names. This is because I believe, e.g., the nobility is more likely to survive than mere mortals. Also, I hypothesize that young unmarried women (“Miss”) are more likely to survive. Possibly, there might be a lot of information in the title.
The names in the titanic dataset (df$Name) are all saved like this example:
Futrelle, Mrs. Jacques Heath (Lily May Peel)
To avoid any mistakes, we are first going to run a command that converts all these strings to lowercase and saves them as new variables:
df$lcName = str_to_lower( df$Name )
The title — Mrs in the example above— is preceded by a whitespace and is preceded by a dot. We can use regex (Regular Expression) as a language to communicate this pattern to Stringr and ask it to look for the title in the following way:
(?<=\\s)[[:alpha:]]+(?=\\.)
This pattern consists of three parts:
(?<=\\s) tells Stringr that the piece of text we are looking for is preceded (?<=) by a whitespace (\\s).[[:alpha:]]+ tells Stringr that the piece of text we are looking for consists of one or more (+) letters ([[:alpha:]]).(?=\\.) tells Stringr that the piece of text we are looking for is proceeded (?=) by a dot (\\.).
(?<=\\s) tells Stringr that the piece of text we are looking for is preceded (?<=) by a whitespace (\\s).
[[:alpha:]]+ tells Stringr that the piece of text we are looking for consists of one or more (+) letters ([[:alpha:]]).
(?=\\.) tells Stringr that the piece of text we are looking for is proceeded (?=) by a dot (\\.).
You can see that regex uses all kinds of symbols to communicate patterns. The Stringr Cheat Sheet is a helpful guide for when you want to develop your own patterns. This website provides an easy way of testing regex patterns.
We extract the title and save it as a new variable by asking Stringr to look for this pattern in the lowercase “Name” strings.
df$title = str_extract( df$lcName, "(?<=\\s)[[:alpha:]]+(?=\\.)" )
Now let’s plot our new variable “title” using Ggplot2 and the commands below.
### install package (ggplot2 is a must have)install.packages("ggplot2")### load packagelibrary(ggplot2)### plot titlesggplot(data.frame(table(df$title)),aes(x=reorder(Var1, -Freq),y=Freq))+ geom_col()+ labs(title="Count of Title", x="Title",y="Count")
You can see, Stringr nicely extracted all the titles from the names, and we now have a new categorical variable we can use as input for our analysis.
As a second exercise, I’d like to extract the family names from the names string. I believe that family membership could be a predictor of survival, i.e., if one family member survives, maybe the others are also more likely to survive, controlling for other factors such as gender, etc.
In the example “name” string above, you can see that the person’s family name, e.g., Futrelle, is the first word. So we can tell Stringr to take the first word (str_extract) that matches the pattern ([[:alpha:]]+) and to take the first word and that this is the family.
However, there are family names in the dataset, such as “Vander Planke” or “O’Dwyer.” If we were to take the first word in this case, we would only get “vander” or “o,” not the whole family name. Therefore, we need to adapt the pattern to include any kinds of characters (.) that are 1 character or more in length (+) and are followed by a comma(?=\\,).
df$family=str_extract(df$lcName,".+(?=,)")
This time, because we have many family names, let’s plot the 10 most frequent family names.
t=data.frame(table(df$family))t=t[order(-t$Freq),]ggplot(head(t,10),aes(x=reorder(Var1,-Freq),y=Freq))+ geom_col()+ labs(title="Count of Family Name", x="Title",y="Family Name")
Again, we now have the novel variable “family name,” which we can use for further analysis.
In most analyses of the Titanic data set, people were quick to discard the ticket information. However, some letters in the ticket codes could potentially mean something. They could, e.g., signal that the tickets were last minute purchases and the passengers were not very prepared for the voyage.
However, these acronyms and codes are written inconsistently (e.g., “SOC” and “S.o.C.”), which is why this data needs some preparation. Let’s clean it.
### set ticket codes to lowercasedf$lcTicket=str_to_lower(df$Ticket)### remove punctuation from ticket codesdf$lcTicket=str_replace_all(df$lcTicket,"[:punct:]","")
Now that we have cleaned the data a bit let’s extract these acronyms. Usually, the ticket code now looks something like this:
sotono 2 3101287
In my mind, “sotono 2” is an acronym that could mean something, and “3101287” is some ticket number (which I’ll talk about more later). If we think about the pattern of the acronym, it’s characters (.) followed by a whitespace (\\s), which itself is followed by a number ([[:digit]]) that is three digits in length or longer ({3,}). Sometimes, the entire ticket code is some acronym (e.g., one passenger features “line” as a ticket), which means that we can give Stringer the alternative option (“|” is the “or” operator) that the entire code is an acronym of interest ([[:alpha:]]+). We tell Stringr to look for this pattern and save it in a new variable, “ticketinfo,” using the following command. We then remove whitespaces and replace NA values.
### identify acronymdf$Ticketinfo = str_extract( df$lcTicket, ".+(?=\\s(?=[[:digit:]]{3,}))|[[:alpha:]]+" )### remove whitespaces from ticketinfodf$Ticketinfo = str_replace_all( df$Ticketinfo, "\\s", "" )### remove NA valuesdf$Ticketinfo = ifelse( is.na(df$Ticketinfo), "none", df$Ticketinfo )
Let’s again plot the 10 most frequent ticketinfo values.
t=data.frame(table(df$Ticketinfo[df$Ticketinfo!="none"]))t=t[order(-t$Freq),]ggplot(head(t,10),aes(x=reorder(Var1,-Freq),y=Freq))+ geom_col()+ labs(title="Count of Ticketinfo Acronym", x="Ticketinfo Acronym",y="Count")
You can see that this adds quite some information for a lot of passengers. Almost 60 passengers have the value “PC.” After inspecting the data, I believe it could mean “private cabin” as many (but not all) 1st class passengers have this value printed on their ticket.
The interesting thing about the Titanic’s fateful maiden voyage was that the ship was only around half full. The ship could have easily transported many more passengers across the Atlantic. This made me think that some passengers might have gotten “free upgrades” to higher classes. A superficial inspection of the ticket number shows that the first digit seems to be correlated to the passenger class (Pclass), but there are exceptions. I hypothesize that the first digit could carry some information about class changes, which would have far-reaching implications for the passenger’s survival probability. Let’s extract the first digit of the number after the acronym and save it as a presumed passenger class (PresumedPclass).
Let’s first extract the ticket number. Again, the ticket number consists of digits ([[:digit:]]) and is 3 or more characters in length ({3,}). Let’s also store it as a character (as.character), not as a number, to still use Stringr on it.
df$Ticketno = as.character( str_extract( df$lcTicket, "[[:digit:]]{3,}" ))
Then let’s take the first digit ([[:digit:]]) of this ticket number and store it as the presumed passenger class.
df$PresumedPclass = str_extract( as.character(df$Ticketno) ,"[[:digit:]]{1}")
Now, let’s again plot this new variable, but let’s plot it in the context of the provided passenger class to see how it correlates.
ggplot(df, aes(x=Pclass, fill=PresumedPclass))+ geom_bar()+ labs(title="Count of Passenger Class", x="Passenger Class",y="Count")+ scale_fill_discrete(name="Presumed Passenger Class")
As we can see in the graph below, these two values mostly correlate. But sometimes they do not. This might be exciting information in those cases in which these two classes did not match.
You would like to find out more? Follow me on Medium to see my other stories! | [
{
"code": null,
"e": 528,
"s": 171,
"text": "Large data sets are often awash with data that is difficult to decipher. One may think of textual data, names, unique identifiers, and other sorts of codes. Frequently, people analyzing these datasets are quick to discard these variables. However, sometim... |
How to select a specific subdocument in MongoDB? | To select a specific subdocument in MongoDB, use find(). Let us create a collection with documents −
> db.demo37.insertOne({"Details":[{"Name":"Chris","Age":21},{"Name":"David","Age":23}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e176635cfb11e5c34d898d7")
}
> db.demo37.insertOne({"Details":[{"Name":"Sam","Age":23},{"Name":"Robert","Age":25}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e17664acfb11e5c34d898d8")
}
Display all documents from a collection with the help of find() method −
> db.demo37.find();
This will produce the following output −
{ "_id" : ObjectId("5e176635cfb11e5c34d898d7"), "Details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 } ] }
{ "_id" : ObjectId("5e17664acfb11e5c34d898d8"), "Details" : [ { "Name" : "Sam", "Age" : 23 }, { "Name" : "Robert", "Age" : 25 } ] }
Following is the query to select subdocument −
> db.demo37.find({'Details.Name' : 'Sam'},{_id: 0, 'Details.$.Name': 1});
This will produce the following output −
{ "Details" : [ { "Name" : "Sam", "Age" : 23 } ] } | [
{
"code": null,
"e": 1163,
"s": 1062,
"text": "To select a specific subdocument in MongoDB, use find(). Let us create a collection with documents −"
},
{
"code": null,
"e": 1512,
"s": 1163,
"text": "> db.demo37.insertOne({\"Details\":[{\"Name\":\"Chris\",\"Age\":21},{\"Name\":\"D... |
Remove duplicated elements of associative array in PHP | The ‘array_map’ function sends the value of every element in the array to a user-defined function. It then returns an array with new values, because of calling the user-defined function on the array.
array_map ( user-defined function, array_1, array_2, array_3...)
The user-defined function and the array_1 are compulsory arguments, but array_2 and array_3 are optional.
Live Demo
$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'duplicate_val'),
2=>array('a'=>1,'b'=>'duplicate_val')
);
$unique = array_map("unserialize", array_unique(array_map("serialize", $result)));
print_r($unique);
This will produce the following output −
Array ( [0] => Array ( [a] => 1 [b] => Hello ) [1] => Array ( [a] => 1 [b] => duplicate_val ) )
In the above code, an array is defined with 3 elements and this is assigned to a variable named ‘result’. The array_map function is called and the ‘result’ value is passed as a parameter.
The resultant output would be the contents in the ‘result’ variable along with mention about the duplicate value in the array. | [
{
"code": null,
"e": 1262,
"s": 1062,
"text": "The ‘array_map’ function sends the value of every element in the array to a user-defined function. It then returns an array with new values, because of calling the user-defined function on the array."
},
{
"code": null,
"e": 1327,
"s": 1... |
What is react-router-dom ? - GeeksforGeeks | 16 Nov, 2021
React Router DOM is an npm package that enables you to implement dynamic routing in a web app. It allows you to display pages and allow users to navigate them. It is a fully-featured client and server-side routing library for React. React Router Dom is used to build single-page applications i.e. applications that have many pages or components but the page is never refreshed instead the content is dynamically fetched based on the URL. This process is called Routing and it is made possible with the help of React Router Dom.
The major advantage of react-router is that the page does not have to be refreshed when a link to another page is clicked, for example. Moreover, it is fast, very fast compared to traditional page navigation. This means that the user experience is better and the app has overall better performance.
React Router Dom has many useful components and to create fully functioning routing, you need most of these.
Router(usually imported as BrowserRouter): It is the parent component that is used to store all of the other components. Everything within this will be part of the routing functionalitySwitch: Switch component is used to render only the first route that matches the location rather than rendering all matching routes.Route: This component checks the current URL and displays the component associated with that exact path. All routes are placed within the switch components.Link: Link component is used to create links to different routes.
Router(usually imported as BrowserRouter): It is the parent component that is used to store all of the other components. Everything within this will be part of the routing functionality
Switch: Switch component is used to render only the first route that matches the location rather than rendering all matching routes.
Route: This component checks the current URL and displays the component associated with that exact path. All routes are placed within the switch components.
Link: Link component is used to create links to different routes.
The Route component takes 2 parameters. The first one is the path that will be in the url and the second is the component that will be displayed if the current URL matches the path in the first parameter.
Example: Below is an example in which we create a simple react app using React Router Dom. The app will contain 4 pages. i.e. 1 home page and 3 sample pages. The user will navigate between these pages with the help of routing and links.
Below is the step by step implementation:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: Your project directory may look like this.
We will do most of our work in the app,js file which is in the src folder.
Step 3: Next, install react router dom using the following command
npm install react-router-dom
Step 4: Now, create a new folder in src called Components. Within this folder, create 3 files:
page1.jspage2.jspage3.js
page1.js
page2.js
page3.js
Add the following code to all the pages:
page1.js
import React from 'react' export default function Page1() { return ( <div> <h1>Page 1</h1> </div> )}
page2.js
import React from 'react' export default function Page2() { return ( <div> <h1>Page 2</h1> </div> )}
page3.js
import React from 'react' export default function Page3() { return ( <div> <h1>Page 3</h1> </div> )}
Project Structure: It will now look like the following.
Project Directory
Step 5: Now, import the needed components for the demo inside App.js. Then add the following code in App.js. Here we are first importing the 3 pages, then inside the Router a Switch is added. inside the Switch 4 Routes are added, one for the home page and 3 for the other pages. The list contains clickable links that a user can click to navigate.
App.js
import { BrowserRouter as Router, Route, Link, Switch} from "react-router-dom"; // Import the pages import Page1 from "./Components/page1"import Page2 from "./Components/page2"import Page3 from "./Components/page3" // Import cssimport "./app.css" function App() { return ( <div className="App"> <Router> <Switch> <Route exact path="/" element={<h1>Home Page</h1>} /> <Route exact path="page1" element={<Page1 />} /> <Route exact path="page2" element={<Page2 />} /> <Route exact path="page3" element={<Page3 />} /> </Switch> <div className="list"> <ul> <li><Link to="/">Home</Link></li> <li><Link to="page1">Page 1</Link></li> <li><Link to="page2">Page 2</Link></li> <li><Link to="page3">Page 3</Link></li> </ul> </div> </Router> </div> );}export default App;
Step 6: You can improve the design and make the app more presentable using the following CSS. Add it to App.css (create it if it is not already there).
App.css
* { padding: 0; margin: 0;} h1 { text-align: center; font-size: 45px; font-family: Arial, Helvetica, sans-serif; color: rgb(6, 0, 32); padding: 40px;} .list { display: flex; justify-content: center; width: 100%;} .list ul li { list-style: none; margin: 42px; text-align: center;} a { text-decoration: none; color: rgb(0, 0, 0); font-size: 18px; font-family: Arial, Helvetica, sans-serif; padding: 14px 25px; background-color: transparent; border: 2px solid rgb(12, 0, 66);} a:hover { background-color: rgb(12, 0, 66); color: rgb(255, 255, 255);}
Step to run the application: Open the terminal and type the following command.
npm start
Output:
Picked
React-Questions
ReactJS DOM Elements
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to set background images in ReactJS ?
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 ?
ReactJS useNavigate() Hook
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24397,
"s": 24369,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 24925,
"s": 24397,
"text": "React Router DOM is an npm package that enables you to implement dynamic routing in a web app. It allows you to display pages and allow users to navigate them. It ... |
DAX - FILTER function | Returns a table that represents a subset of another table or expression.
FILTER (<table>, <filter>)
table
The table to be filtered. The table can also be an expression that results in a table.
filter
A Boolean expression that is to be evaluated for each row of the table.
A table containing only the filtered rows.
You can use DAX FILTER function to reduce the number of rows in the table that you are working with, and use only specific data in calculations.
DAX FILTER function is not used independently, but as a function that is embedded in other functions that require a table as an argument.
Medal Count Summer Sports:= COUNTAX (
FILTER (Results, Results[Season] = "Summer"), Results[Medal]
)
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2074,
"s": 2001,
"text": "Returns a table that represents a subset of another table or expression."
},
{
"code": null,
"e": 2103,
"s": 2074,
"text": "FILTER (<table>, <filter>) \n"
},
{
"code": null,
"e": 2109,
"s": 2103,
"text": "table"
... |
Loading 3D City Models in QGIS. Using QGIS to explore the CityJSON 3D... | by Joe T. Santhanavanich | Towards Data Science | In Geospatial Data Science, the 3D data models recently play an important role in the research and visualization projects. QGIS is one of the most popular free and open-source cross-platform desktop GIS application software that every GIS geek knows. Since version 3.0 of the QGIS, a separate interface is responsible for 3D data visualization of the Point cloud and Digital Elevation Models. It’s called the 3D map view and is accessed from the View context menu.
However, the usual way the building- or city models had been visualized in the 3D GIS projects is by extruding the building footprints. This will result in the Level of Details-1. In 2020, the QGIS plugin for loading CityJSON 3D city models in QGIS has been developed [1]. Accordingly, it is possible to visualize the building models at a higher Level of Details. This article will introduce the use of this plugin for loading the CityJSON 3D city models with some examples.
In the world of 3D data, the 3D city models have been used for many application domains such as 3D cadastres, facilities management, and emergency response. One of the most popular data schemas for the 3D city models is the OGC CityGML which is a global data model for describing 3D geo-spatially-enabled urban models; developed by the OGC (open geospatial consortium). However, it is based on GML encoding which has a complex nature and poor interoperability. For this reason, the CityJSON has been developing as an easy‐to‐use JavaScript Object Notation (JSON) encoding for 3D city models using the CityGML 2.0 data model.
You can check out this article to check out the available open-source CityGML datasets.
Any CityGML datasets can be converted to the CityJSON format using the citygml-tools. It is a command-line utility that bundles several operations for processing CityGML files. (Check this Link)
Then you can convert your CityGML data with this command:
$ citygml-tools to-cityjson /path/to/your/CityGML.gml
You can download and install the latest version of QGIS from here. Then, open the plugin window (Plugins => Manage and Install Plugins) and find the CityJSON Loader.
After the CityJSON Loader had been installed, you can use it to load the CityJSON file. You can find it under the Vector menu (Vector => CityJSON Loader => Load CityJSON... ).
For example, you can try this dataset for the 3D city model of Den Haag in CityJSON format. Before you load the CityJSON, check the EPSG code from the metadata and set your project Coordinate Reference System (CRS) to match the EPSG code of your dataset to ensure that the dataset will be loaded properly.
You can set the project CRS from the lower right of your QGIS window as in the following figure.
After the CityJSON is loaded to your QGIS project, you can visualize it in 3D by opening a new 3D Map View (View => New 3D Map View [Ctrl + Alt + m]). The following figure is an example of the Den Haag CityJSON model. [~2.9 Mb].
After exploring the 3D city models, there are a lot of possibilities for using the 3D city models for real-world projects; for example,
Build the 3D Web map application with 3D City Models
Explore more open-source 3D City Models.
Download open-source data from OSM using QGIS & QuickOSM.
Or, why don't you try to integrate it with your game project in Unity3D?
And, much more!
This short article introduces the CityJSON; a light 3D City Model encoding for the 3D city model and shows how to visualize these data models in an open-source GIS desktop software QGIS. I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments.
About me & Check out all my blog contents: Link
Be Safe and Healthy! 💪
Thank you for Reading. 📚
[1] Stelios Vitalis, Ken Arroyo Ohori, Jantien Stoter: CityJSON in QGIS: Development of an open‐source plugin https://doi.org/10.1111/tgis.12657 (2020). | [
{
"code": null,
"e": 637,
"s": 172,
"text": "In Geospatial Data Science, the 3D data models recently play an important role in the research and visualization projects. QGIS is one of the most popular free and open-source cross-platform desktop GIS application software that every GIS geek knows. Sinc... |
Automate Data Preparation using Google Colab: Read and Process Citi Bike Data in Zip File | by Huajing Shi | Towards Data Science | From time to time I get requests from colleagues to process some large data files and report some statistics from the data. Since they rely on Excel as their main data processing/analysis tool and don’t use Python, R or SQL, reading and processing data files with more than 1,048,576 rows (the row capacity of Excel) become a problem.
To process data in a zip file, normally I would download the zip file, unzip to get CSV file, and then import the CSV file into either SQL, R or Python to process. Once I got the results, I need to output the results to CSV files and sent the files to the colleagues who requested the work. This whole procedure could get cumbersome when I have to repeat the process every month when new data comes in.
Google Colab (i.e., Google Colaboratory) provides a platform to share Python code and run it in web browser. It is especially helpful to share your Python solution with non Python users.
Here is an example of Python program using Google Colab to automate the data preparation of monthly Citi Bike data. The program can read the zip file directly from the Citi Bike online portal, and process the data to report the total number of Citi Bike trips for each calendar day. The users only need to provide the URL of the data file that they want to process, and download/save the results to their local computers at the end.
Citi Bike website publishes user usage data every month, and maintained historical data back to June 2013. This is a good data source for analyzing micro mobility trend in New York metropolitan region.
The number of records in the Citi Bike data file could be very large. For instance, the data for the month of August 2020 contains more than two million records which exceeded the row capacity of Excel.
First go to Citi Bike Trip data portal and copy the link address of the file you would like to process:
https://s3.amazonaws.com/tripdata/index.html
To run the code, you need to sign in to your Google account. Once signed in, you can run the Python code by clicking on the arrow at the top left corner of the code window.
Paste the data file link address in the input box “Data url: ”, and hit “enter”. The code will download the zip file from the file address, and read in the data line by line, and save the data into a DataFrame.
data_address = input('Data url: ')url = urllib.request.urlopen(data_address)data = []df = pd.DataFrame()with ZipFile(BytesIO(url.read())) as my_zip_file: for contained_file in my_zip_file.namelist(): for line in my_zip_file.open(contained_file).readlines(): s=str(line,'utf-8') s = re.sub(r"\n", "", s) s = re.sub(r"\"", "", s) line_s = s.split(",") data.append(line_s) df = pd.DataFrame(data)
Things get easier and fun once we have the data stored into a DataFrame. The first row in the original data contains variable names (or column names). Use the data in the first row as column names for the DataFrame and then remove the first row from the DataFrame. Then aggregate the DataFrame by the “starttime” of each trip to count the number of trips for each calendar day, and print the result to the output console.
col_name = df.iloc[0].astype(str)df.columns = col_namedf = df.drop([0])df['startdate']=df['starttime'].astype('datetime64[ns]').dt.datedate_count = df.groupby('startdate').count()[['bikeid']]date_count.columns = ['count']print(date_count)
Once the result is output to the console, download the result to your local computer by specifying the output file name in the input box “Output File Name:” at the bottom of the console.
output_file_name = input('Output File Name: ')date_count.to_csv(output_file_name+'.csv') files.download(output_file_name+'.csv')
The complete code is as follows:
from io import BytesIOfrom zipfile import ZipFileimport pandas as pdimport urllib.requestimport refrom google.colab import filesdata_address = input('Data url: ')url = urllib.request.urlopen(data_address)data = []df = pd.DataFrame()with ZipFile(BytesIO(url.read())) as my_zip_file: for contained_file in my_zip_file.namelist(): for line in my_zip_file.open(contained_file).readlines(): s=str(line,'utf-8') s = re.sub(r"\n", "", s) s = re.sub(r"\"", "", s) line_s = s.split(",") data.append(line_s) df = pd.DataFrame(data)col_name = df.iloc[0].astype(str)df.columns = col_namedf = df.drop([0])df['startdate']=df['starttime'].astype('datetime64[ns]').dt.datedate_count = df.groupby('startdate').count()[['bikeid']]date_count.columns = ['count']print(date_count)output_file_name = input('Output File Name: ')date_count.to_csv(output_file_name+'.csv') files.download(output_file_name+'.csv')
Link to Google Colab Notebook:
https://colab.research.google.com/drive/1SpTToe6sL9OnB5-LhAPpOwGCIPe1miHw#scrollTo=kRMFFxaW30Rc
Link to GitHub: | [
{
"code": null,
"e": 507,
"s": 172,
"text": "From time to time I get requests from colleagues to process some large data files and report some statistics from the data. Since they rely on Excel as their main data processing/analysis tool and don’t use Python, R or SQL, reading and processing data fi... |
Sum of Products | Practice | GeeksforGeeks | Given an array Arr of N integers.Calculate the sum of Bitwise ANDs(&) all the pairs formed by the given array.
Example 1:
Input:
N=3
Arr={5,10,15}
Output:
15
Explanation:
The bitwise Ands of all pairs are (5&10)=0
(5&15)=5 and (10&15)=10.Therefore,
total Sum=0+5+10=15.
Example 2:
Input:
N=4
Arr={10,20,30,40}
Output:
46
Explanation:
The sum of bitwise Ands
of all pairs=0+10+8+20+0+8=46.
Your Task:
You don't need to read input or print anything.Your Task is to complete the function pairAndSum() which takes an Integer N and an array Arr as input parameters and returns the sum of bitwise Ands of all pairs.
Expected Time Complexity:O(N)
Expected Auxillary Space:O(1)
Constraints:
1<=N<=105
1<=Arri<=108
0
Nishchay Bhutani
This comment was deleted.
0
Nishchay Bhutani
This comment was deleted.
0
Manjunath Jadhav2 years ago
Manjunath Jadhav
https://practice.geeksforge...
guys anyone say what is the problem in my code..plz,plz,plz....
0
Shreya Patil2 years ago
Shreya Patil
/*package whatever //do not write package name here */
import java.util.*;import java.lang.*;import java.io.*;
class GFG {public static void main (String[] args) {//codeScanner sc=new Scanner(System.in);int t=sc.nextInt();while(t-->0){ int n=sc.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) {="" arr[i]="sc.nextInt();" }="" int="" sum="0;" for(int="" i="0;i<n;i++)" {="" for(int="" j="i+1;j<n;j++)" {="" sum="sum+(arr[i]&arr[j]);" }="" }="" system.out.println(sum);="" }="" }="" }<code="">
0
Sreedhar Karanam2 years ago
Sreedhar Karanam
C++ solution (0.01 sec):https://ide.geeksforgeeks.o...
0
penny53402 years ago
penny5340
shortest sol ever ET= 0.01upvote me for more .https://ide.geeksforgeeks.o...
-1
SHIVANI2 years ago
SHIVANI
#include <stdio.h>
int main() { int t,n,arr[50],i,j,sum,a; scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=0;i<n;i++) {="" scanf("%d",&arr[i]);="" }="" sum="0;" i="0;" for(i="0;i<n;i++)" {="" for(j="i+1;j<n;j++)" {="" a="arr[i]&arr[j];" sum="sum+a;" }="" }="" printf("%d\n",sum);="" }="" return="" 0;="" }="">
0
Shashwat Sharma2 years ago
Shashwat Sharma
0.14 sec....
import java.util.*;import java.lang.*;import java.io.*;
class GFG {public static void main (String[] args) {//codeScanner sc = new Scanner(System.in);int t = sc.nextInt();while(t-->0){ int n = sc.nextInt(); int[] a = new int[n]; int i,j,prod=1,sum=0; for(i=0;i<n;i++) a[i]="sc.nextInt();" for(i="0;i<n-1;i++)" {="" for(j="i+1;j<n;j++)" {="" prod="a[i]&a[j];" sum+="prod;" }="" }="" system.out.println(sum);="" }="" }="" }="">
0
Aman chowdhury2 years ago
Aman chowdhury
/* C PROGRAM */time = 0.01
#include <stdio.h>
int main() {//codeint t;scanf("%d",&t);while(t--){ int n,i,j,sum=0; scanf("%d",&n); int a[n]; for(i=0;i<n;i++) {="" scanf("%d",&a[i]);="" }="" for(i="0;i<n;i++)" {="" for(j="i;j<n-1;j++)" {="" sum+="a[i]&a[j+1];" }="" }="" printf("%d\n",sum);="" }="" return="" 0;="" }="">
0
Niraj Singh3 years ago
Niraj Singh
t=int(input())for _ in range(t): n=int(input()) a=list(map(int,input().split())) s=0 for i in range(n-1): for j in range(i+1,n): s+=a[i]&a[j] print(s)
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": 349,
"s": 238,
"text": "Given an array Arr of N integers.Calculate the sum of Bitwise ANDs(&) all the pairs formed by the given array."
},
{
"code": null,
"e": 360,
"s": 349,
"text": "Example 1:"
},
{
"code": null,
"e": 508,
"s": 360,
"tex... |
Disconnecting Database in Python | To disconnect Database connection, use close() method.
db.close()
If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly. | [
{
"code": null,
"e": 1117,
"s": 1062,
"text": "To disconnect Database connection, use close() method."
},
{
"code": null,
"e": 1128,
"s": 1117,
"text": "db.close()"
},
{
"code": null,
"e": 1418,
"s": 1128,
"text": "If the connection to a database is closed by ... |
What is the difference between CMD and ENTRYPOINT in a Dockerfile? | We can build Docker images by specifying instructions inside a Dockerfile. Dockerfile allows us to specify step-by-step instructions which define the rules for making a container environment. The Docker containers are created for specific tasks and processes to be run inside them. There are three important instructions that are used inside a Dockerfile which lets us define which processes need to be run inside the containers and in what sequence and order.
These 3 instructions are -
RUN
CMD
ENTRYPOINT
The RUN instruction is quite simple. We can define simple subcommands along with the RUN instruction that we want to execute inside the container. For example, if we want to install a pip package, we can simply use the “RUN pip install package_name” instruction inside the Dockerfile.
However, the other two instructions - CMD and ENTRYPOINT can be quite confusing, especially for beginners. In this article, we are going to discuss the use-cases and the distinctions between these two commands along with some useful examples. But before we get into them, we need to understand the shell and exec forms of writing instructions in a Dockerfile
When we use shell form to specify instructions, normal shell processing takes place in the background. The daemon calls the command shell in the background while executing the shell form of commands. The format to specify the commands in shell form is -
$ <instruction> <command>
When we write commands in executable form and execute those commands, then the normal shell processing does not happen in the background. Instead, the executable gets directly called. The format to specify commands in executable form is -
$ <instruction> ["executable", "parameter", "parameter", . . . .]
The shell form of commands is generally used for RUN instructions and the executable forms are generally used for CMD and ENTRYPOINT instructions.
You can set default commands with parameters using the CMD instruction. If you run a Docker container without specifying any additional CLI commands, the CMD instruction will be executed. You can include an executable as the default command. However, if you choose to omit it, you will have to specify an ENTRYPOINT instruction along with the CMD instruction
If you have specified an argument along with the Docker run command, the default one specified using the CMD instruction will be ignored. Also, if you have specified multiple CMD instructions inside a single dockerfile, the one specified at the last will only be executed.
The CMD instruction has three forms -
CMD ["only_executable","parameter_1","parameter_1"] (executable form)
CMD ["parameter_1","parameter_2"] (used to provide default parameters to the ENTRYPOINT instruction)
CMD command param1 param2 (It is the shell form)
$ CMD echo "Command in Shell Form"
$ CMD ["/bin/bash", "-c", "echo Command in Exec Form"]
The ENTRYPOINT instruction looks almost similar to the CMD instruction. However, the main highlighting difference between them is that it will not ignore any of the parameters that you have specified in the Docker run command (CLI parameters).
When we have specified the ENTRYPOINT instruction in the executable form, it allows us to set or define some additional arguments/parameters using the CMD instruction in Dockerfile. If we have used it in the shell form, it will ignore any of the CMD parameters or even any CLI arguments.
The forms of the ENTRYPOINT Instruction are -
ENTRYPOINT ["only_executable", "parameter_1", "parameter_2"] (executable form)
ENTRYPOINT command parameter_1 parameter_2 (Shell form)
$ ENTRYPOINT echo "Welcome to TutorialsPoint"
$ ENTRYPOINT ["/bin/bash", "-c", "echo Welcome to TutorialsPoint"]
To sum up, if you want to specify default commands with arguments that need to be run when you fire up a Docker container, you can use the CMD instruction. In case you specify an argument along with the Docker run command, the arguments specified using the CMD instruction will be ignored. This means that the CLI arguments using the Docker run command will override the arguments specified using the CMD instruction.
On the other hand, there are two cases with the ENTRYPOINT instruction. If you use the ENTRYPOINT instruction in the shell form and you provide additional arguments using CLI parameters or even through the CMD commands, the ENTRYPOINT instruction overrides all of these. However, if you use ENTRYPOINT instruction in executable form, you can set additional parameters using the CMD instruction.
Depending on your requirements and use-cases, you can adopt any one of these commands. | [
{
"code": null,
"e": 1523,
"s": 1062,
"text": "We can build Docker images by specifying instructions inside a Dockerfile. Dockerfile allows us to specify step-by-step instructions which define the rules for making a container environment. The Docker containers are created for specific tasks and proc... |
How to dynamically allocate a 2D array in C? - GeeksforGeeks | 12 Jan, 2022
Following are different ways to create a 2D array on the heap (or dynamically allocate a 2D array).In the following examples, we have considered ‘r‘ as number of rows, ‘c‘ as number of columns and we created a 2D array with r = 3, c = 4 and the following values
1 2 3 4
5 6 7 8
9 10 11 12
1) Using a single pointer and a 1D array with pointer arithmetic: A simple way is to allocate a memory block of size r*c and access its elements using simple pointer arithmetic.
C
#include <stdio.h>#include <stdlib.h> int main(void){ int r = 3, c = 4; int* ptr = malloc((r * c) * sizeof(int)); /* Putting 1 to 12 in the 1D array in a sequence */ for (int i = 0; i < r * c; i++) ptr[i] = i + 1; /* Accessing the array values as if it was a 2D array */ for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) printf("%d ", ptr[i * c + j]); printf("\n"); } free(ptr); return 0;}
Output:
1 2 3 4
5 6 7 8
9 10 11 12
2) Using an array of pointers We can create an array of pointers of size r. Note that from C99, C language allows variable sized arrays. After creating an array of pointers, we can dynamically allocate memory for every row.
C
#include <stdio.h>#include <stdlib.h> int main(){ int r = 3, c = 4, i, j, count; int* arr[r]; for (i = 0; i < r; i++) arr[i] = (int*)malloc(c * sizeof(int)); // Note that arr[i][j] is same as *(*(arr+i)+j) count = 0; for (i = 0; i < r; i++) for (j = 0; j < c; j++) arr[i][j] = ++count; // Or *(*(arr+i)+j) = ++count for (i = 0; i < r; i++) for (j = 0; j < c; j++) printf("%d ", arr[i][j]); /* Code for further processing and free the dynamically allocated memory */ for (int i = 0; i < r; i++) free(arr[i]); return 0;}
Output:
1 2 3 4 5 6 7 8 9 10 11 12
3) Using pointer to a pointer We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.
C
#include <stdio.h>#include <stdlib.h> int main(){ int r = 3, c = 4, i, j, count; int** arr = (int**)malloc(r * sizeof(int*)); for (i = 0; i < r; i++) arr[i] = (int*)malloc(c * sizeof(int)); // Note that arr[i][j] is same as *(*(arr+i)+j) count = 0; for (i = 0; i < r; i++) for (j = 0; j < c; j++) arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count for (i = 0; i < r; i++) for (j = 0; j < c; j++) printf("%d ", arr[i][j]); /* Code for further processing and free the dynamically allocated memory */ for (int i = 0; i < r; i++) free(arr[i]); free(arr); return 0;}
Output:
1 2 3 4 5 6 7 8 9 10 11 12
4) Using double pointer and one malloc call
C
#include<stdio.h>#include<stdlib.h> int main(){ int r=3, c=4, len=0; int *ptr, **arr; int count = 0,i,j; len = sizeof(int *) * r + sizeof(int) * c * r; arr = (int **)malloc(len); // ptr is now pointing to the first element in of 2D array ptr = (int *)(arr + r); // for loop to point rows pointer to appropriate location in 2D array for(i = 0; i < r; i++) arr[i] = (ptr + c * i); for (i = 0; i < r; i++) for (j = 0; j < c; j++) arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count for (i = 0; i < r; i++) for (j = 0; j < c; j++) printf("%d ", arr[i][j]); return 0;}
Output:
1 2 3 4 5 6 7 8 9 10 11 12
Thanks to Trishansh Bhardwaj for suggesting this 4th method.This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
5) Using a pointer to Variable Length Array.
The dimensions of VLA are bound to the type of the variable. Therefore one form a pointer to an array with run-time defined shape.The pointer has to be dereferenced before subscripting with syntax (*arr)[i][j].
C
#include <stdio.h>#include <stdlib.h> int main(){ int row = 3, col = 4, i, j, count; int (*arr)[row][col] = malloc(sizeof *arr); count = 0; for (i = 0; i < row; i++) for (j = 0; j < col; j++) (*arr)[i][j] = ++count; for (i = 0; i < row; i++) for (j = 0; j < col; j++) printf("%d ", (*arr)[i][j]); free(arr); return 0;}
6) Using a pointer to the first row of VLA
Similar to 5 but allows arr[i][j] syntax.
C
#include <stdio.h>#include <stdlib.h> int main(){ int row = 3, col = 4, i, j, count; int (*arr)[col] = calloc(row, sizeof *arr); count = 0; for (i = 0; i < row; i++) for (j = 0; j < col; j++) arr[i][j] = ++count; for (i = 0; i < row; i++) for (j = 0; j < col; j++) printf("%d ", arr[i][j]); free(arr); return 0;}
NileshAwate
dncdd
garvitsingh1401
sohampc4756
daleks
stanislawskitomasz
C Array and String
cpp-array
cpp-pointer
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fork() in C
Command line arguments in C/C++
Substring in C++
Function Pointer in C
TCP Server-Client implementation in C
Structures in C
Different methods to reverse a string in C/C++
Enumeration (or enum) in C
std::string class in C++
Exception Handling in C++ | [
{
"code": null,
"e": 24045,
"s": 24017,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 24308,
"s": 24045,
"text": "Following are different ways to create a 2D array on the heap (or dynamically allocate a 2D array).In the following examples, we have considered ‘r‘ as number of r... |
Find the most frequent value in a NumPy array - GeeksforGeeks | 29 Aug, 2020
In this article, let’s discuss how to find the most frequent value in the NumPy array.
Steps to find the most frequency value in a NumPy array:
Create a NumPy array.
Apply bincount() method of NumPy to get the count of occurrences of each element in the array.
The n, apply argmax() method to get the value having a maximum number of occurrences(frequency).
Example 1:
Python3
import numpy as np # create arrayx = np.array([1,2,3,4,5,1,2,1,1,1])print("Original array:")print(x) print("Most frequent value in the above array:")print(np.bincount(x).argmax())
Output:
1
This code will generate a single output only, it will not work fine if the array contains more than one element having the maximum number of frequency.
Example 2: If the array has more than one element having maximum frequency
Python3
import numpy as np x = np.array([1, 1, 1, 2, 3, 4, 2, 4, 3, 3, ])print("Original array:")print(x) print("Most frequent value in above array")y = np.bincount(x)maximum = max(y) for i in range(len(y)): if y[i] == maximum: print(i, end=" ")
Output:
1 3
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 23989,
"s": 23901,
"text": "In this article, let’s discuss how to find the most frequent value in the NumPy array. "
},
{
"code": null,
"e": 24046,
"s": 23989,
"text": "St... |
Write a C program to print "Geeks for Geeks" without using a semicolon - GeeksforGeeks | 02 Jun, 2017
First of all we have to understand how printf() function works.Prototype of printf() function is:
int printf( const char *format , ...)
Parameter
format: This is a string that contains a text to be written to stdout.
Additional arguments: ... (Three dots are called ellipses) which indicates the variable number of arguments depending upon the format string.
printf() returns the total number of characters written to stdout. Therefore it can be used as a condition check in an if condition, while condition, switch case and Macros.
Let’s see each of these conditions one by one.
Using if condition:#include<stdio.h>int main(){ if (printf("Geeks for Geeks") ) { }} Using while condition:#include<stdio.h>int main(){ while (!printf( "Geeks for Geeks" )) { }}Using switch case:#include<stdio.h>int main(){ switch (printf("Geeks for Geeks" )) { }}Using Macros:#include<stdio.h>#define PRINT printf("Geeks for Geeks")int main(){ if (PRINT) { }}
Using if condition:#include<stdio.h>int main(){ if (printf("Geeks for Geeks") ) { }}
#include<stdio.h>int main(){ if (printf("Geeks for Geeks") ) { }}
Using while condition:#include<stdio.h>int main(){ while (!printf( "Geeks for Geeks" )) { }}
#include<stdio.h>int main(){ while (!printf( "Geeks for Geeks" )) { }}
Using switch case:#include<stdio.h>int main(){ switch (printf("Geeks for Geeks" )) { }}
#include<stdio.h>int main(){ switch (printf("Geeks for Geeks" )) { }}
Using Macros:#include<stdio.h>#define PRINT printf("Geeks for Geeks")int main(){ if (PRINT) { }}
#include<stdio.h>#define PRINT printf("Geeks for Geeks")int main(){ if (PRINT) { }}
Output: Geeks for Geeks
One trivial extension of the above problem: Write a C program to print “;” without using a semicolon
#include<stdio.h>int main(){ // ASCII value of ; is 59 if (printf("%c", 59)) { }}
Output: ;
This blog is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
c-puzzle
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Different methods to reverse a string in C/C++
Core Dump (Segmentation fault) in C/C++
Command line arguments in C/C++
fork() in C
TCP Server-Client implementation in C
Function Pointer in C
Enumeration (or enum) in C | [
{
"code": null,
"e": 24918,
"s": 24890,
"text": "\n02 Jun, 2017"
},
{
"code": null,
"e": 25016,
"s": 24918,
"text": "First of all we have to understand how printf() function works.Prototype of printf() function is:"
},
{
"code": null,
"e": 25055,
"s": 25016,
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.