title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
GATE | GATE CS 2013 | Question 11 - GeeksforGeeks | 28 Jun, 2021
Match the problem domains in GROUP I with the solution technologies in GROUP II
GROUP I GROUP II
(P) Service oriented computing (1) Interoperability
(Q) Heterogeneous communicating systems (2) BPMN
(R) Information representation (3) Publish-find-bind
(S) Process description (4) XML
(A) P-1, Q-2, R-3, S-4(B) P-3, Q-4, R-2, S-1(C) P-3, Q-1, R-4, S-2(D) P-4, Q-3, R-2, S-1Answer: (C)Explanation: The answer can be easily guessed with XML. XML is used for information representation.Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
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 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2012 | Question 65 | [
{
"code": null,
"e": 24075,
"s": 24047,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24155,
"s": 24075,
"text": "Match the problem domains in GROUP I with the solution technologies in GROUP II"
},
{
"code": null,
"e": 24461,
"s": 24155,
"text": "GROUP I GROUP II\n(P) Service oriented computing (1) Interoperability\n(Q) Heterogeneous communicating systems (2) BPMN\n(R) Information representation (3) Publish-find-bind\n(S) Process description (4) XML "
},
{
"code": null,
"e": 24681,
"s": 24461,
"text": "(A) P-1, Q-2, R-3, S-4(B) P-3, Q-4, R-2, S-1(C) P-3, Q-1, R-4, S-2(D) P-4, Q-3, R-2, S-1Answer: (C)Explanation: The answer can be easily guessed with XML. XML is used for information representation.Quiz of this Question"
},
{
"code": null,
"e": 24694,
"s": 24681,
"text": "GATE-CS-2013"
},
{
"code": null,
"e": 24712,
"s": 24694,
"text": "GATE-GATE CS 2013"
},
{
"code": null,
"e": 24717,
"s": 24712,
"text": "GATE"
},
{
"code": null,
"e": 24815,
"s": 24717,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24824,
"s": 24815,
"text": "Comments"
},
{
"code": null,
"e": 24837,
"s": 24824,
"text": "Old Comments"
},
{
"code": null,
"e": 24879,
"s": 24837,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 24921,
"s": 24879,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 24955,
"s": 24921,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 24997,
"s": 24955,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25051,
"s": 24997,
"text": "C++ Program to count Vowels in a string using Pointer"
},
{
"code": null,
"e": 25084,
"s": 25051,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25126,
"s": 25084,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 42"
},
{
"code": null,
"e": 25168,
"s": 25126,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25202,
"s": 25168,
"text": "GATE | GATE CS 2011 | Question 65"
}
] |
How to create user defined exceptions in C#? | Like any other programming language, in C#, you can easily create user-defined exception. User-defined exception classes are derived from the Exception class.
In the below example, the exception created is not a built-in exception.
TempIsZeroException
You can try to run the following code to learn how to create user defined exception in C#.
Live Demo
using System;
namespace Demo {
class TestTemperature {
static void Main(string[] args) {
Temperature temp = new Temperature();
try {
temp.showTemp();
} catch(TempIsZeroException e) {
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException: Exception {
public TempIsZeroException(string message): base(message) {
}
}
public class Temperature {
int temperature = 0;
public void showTemp() {
if(temperature == 0) {
throw (new TempIsZeroException("Zero Temperature found"));
} else {
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
TempIsZeroException: Zero Temperature found | [
{
"code": null,
"e": 1221,
"s": 1062,
"text": "Like any other programming language, in C#, you can easily create user-defined exception. User-defined exception classes are derived from the Exception class."
},
{
"code": null,
"e": 1294,
"s": 1221,
"text": "In the below example, the exception created is not a built-in exception."
},
{
"code": null,
"e": 1314,
"s": 1294,
"text": "TempIsZeroException"
},
{
"code": null,
"e": 1405,
"s": 1314,
"text": "You can try to run the following code to learn how to create user defined exception in C#."
},
{
"code": null,
"e": 1416,
"s": 1405,
"text": " Live Demo"
},
{
"code": null,
"e": 2154,
"s": 1416,
"text": "using System;\nnamespace Demo {\n class TestTemperature {\n static void Main(string[] args) {\n Temperature temp = new Temperature();\n try {\n temp.showTemp();\n } catch(TempIsZeroException e) {\n Console.WriteLine(\"TempIsZeroException: {0}\", e.Message);\n }\n Console.ReadKey();\n }\n }\n}\npublic class TempIsZeroException: Exception {\n public TempIsZeroException(string message): base(message) {\n }\n}\npublic class Temperature {\n int temperature = 0;\n public void showTemp() {\n if(temperature == 0) {\n throw (new TempIsZeroException(\"Zero Temperature found\"));\n } else {\n Console.WriteLine(\"Temperature: {0}\", temperature);\n }\n }\n}"
},
{
"code": null,
"e": 2198,
"s": 2154,
"text": "TempIsZeroException: Zero Temperature found"
}
] |
How to find the first and last character of a string in Java - GeeksforGeeks | 23 Jul, 2020
Given a string str, the task is to print the first and the last character of the string.
Examples:
Input: str = “GeeksForGeeks”
Output:
First: G
Last: s
Explanation: The first character of the given string is ‘G’ and the last character of given string is ‘s’.
Input: str = “Java”
Output:
First: J
Last: a
Explanation: The first character of given string is ‘J’ and the last character of given string is ‘a’.
The idea is to use charAt() method of String class to find the first and last character in a string.
The charAt() method accepts a parameter as an index of the character to be returned.
The first character in a string is present at index zero and the last character in a string is present at index length of string-1 .
Now, print the first and the last character of the string.
Below is the implementation of the above approach:
Java
// Java program to find first// and last character of a string class GFG { // Function to print first and last // character of a string public static void firstAndLastCharacter(String str) { // Finding string length int n = str.length(); // First character of a string char first = str.charAt(0); // Last character of a string char last = str.charAt(n - 1); // Printing first and last // character of a string System.out.println("First: " + first); System.out.println("Last: " + last); } // Driver Code public static void main(String args[]) { // Given string str String str = "GeeksForGeeks"; // Function Call firstAndLastCharacter(str); }}
First: G
Last: s
The idea is to first convert the given string into a character array using toCharArray() method of String class, then find the first and last character of a string and print it.
Below is the implementation of the above approach:
Java
// Java program to find first// and last character of a string class GFG { // Function to print first and last // character of a string public static void firstAndLastCharacter(String str) { // Converting a string into // a character array char[] charArray = str.toCharArray(); // Finding the length of // character array int n = charArray.length; // First character of a string char first = charArray[0]; // Last character of a string char last = charArray[n - 1]; // Printing first and last // character of a string System.out.println("First: " + first); System.out.println("Last: " + last); } // Driver Code public static void main(String args[]) { // Given string str String str = "GeeksForGeeks"; // Function Call firstAndLastCharacter(str); }}
First: G
Last: s
Java-String-Programs
Java Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Iterate HashMap in Java?
Factory method design pattern in Java
Iterate through List in Java
Java Program to Remove Duplicate Elements From the Array
Iterate Over the Characters of a String in Java
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types | [
{
"code": null,
"e": 24262,
"s": 24234,
"text": "\n23 Jul, 2020"
},
{
"code": null,
"e": 24351,
"s": 24262,
"text": "Given a string str, the task is to print the first and the last character of the string."
},
{
"code": null,
"e": 24361,
"s": 24351,
"text": "Examples:"
},
{
"code": null,
"e": 24390,
"s": 24361,
"text": "Input: str = “GeeksForGeeks”"
},
{
"code": null,
"e": 24398,
"s": 24390,
"text": "Output:"
},
{
"code": null,
"e": 24407,
"s": 24398,
"text": "First: G"
},
{
"code": null,
"e": 24415,
"s": 24407,
"text": "Last: s"
},
{
"code": null,
"e": 24522,
"s": 24415,
"text": "Explanation: The first character of the given string is ‘G’ and the last character of given string is ‘s’."
},
{
"code": null,
"e": 24542,
"s": 24522,
"text": "Input: str = “Java”"
},
{
"code": null,
"e": 24551,
"s": 24542,
"text": "Output: "
},
{
"code": null,
"e": 24560,
"s": 24551,
"text": "First: J"
},
{
"code": null,
"e": 24568,
"s": 24560,
"text": "Last: a"
},
{
"code": null,
"e": 24671,
"s": 24568,
"text": "Explanation: The first character of given string is ‘J’ and the last character of given string is ‘a’."
},
{
"code": null,
"e": 24773,
"s": 24671,
"text": "The idea is to use charAt() method of String class to find the first and last character in a string. "
},
{
"code": null,
"e": 24858,
"s": 24773,
"text": "The charAt() method accepts a parameter as an index of the character to be returned."
},
{
"code": null,
"e": 24991,
"s": 24858,
"text": "The first character in a string is present at index zero and the last character in a string is present at index length of string-1 ."
},
{
"code": null,
"e": 25050,
"s": 24991,
"text": "Now, print the first and the last character of the string."
},
{
"code": null,
"e": 25101,
"s": 25050,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25106,
"s": 25101,
"text": "Java"
},
{
"code": "// Java program to find first// and last character of a string class GFG { // Function to print first and last // character of a string public static void firstAndLastCharacter(String str) { // Finding string length int n = str.length(); // First character of a string char first = str.charAt(0); // Last character of a string char last = str.charAt(n - 1); // Printing first and last // character of a string System.out.println(\"First: \" + first); System.out.println(\"Last: \" + last); } // Driver Code public static void main(String args[]) { // Given string str String str = \"GeeksForGeeks\"; // Function Call firstAndLastCharacter(str); }}",
"e": 25891,
"s": 25106,
"text": null
},
{
"code": null,
"e": 25909,
"s": 25891,
"text": "First: G\nLast: s\n"
},
{
"code": null,
"e": 26087,
"s": 25909,
"text": "The idea is to first convert the given string into a character array using toCharArray() method of String class, then find the first and last character of a string and print it."
},
{
"code": null,
"e": 26138,
"s": 26087,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26143,
"s": 26138,
"text": "Java"
},
{
"code": "// Java program to find first// and last character of a string class GFG { // Function to print first and last // character of a string public static void firstAndLastCharacter(String str) { // Converting a string into // a character array char[] charArray = str.toCharArray(); // Finding the length of // character array int n = charArray.length; // First character of a string char first = charArray[0]; // Last character of a string char last = charArray[n - 1]; // Printing first and last // character of a string System.out.println(\"First: \" + first); System.out.println(\"Last: \" + last); } // Driver Code public static void main(String args[]) { // Given string str String str = \"GeeksForGeeks\"; // Function Call firstAndLastCharacter(str); }}",
"e": 27064,
"s": 26143,
"text": null
},
{
"code": null,
"e": 27082,
"s": 27064,
"text": "First: G\nLast: s\n"
},
{
"code": null,
"e": 27103,
"s": 27082,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 27117,
"s": 27103,
"text": "Java Programs"
},
{
"code": null,
"e": 27125,
"s": 27117,
"text": "Strings"
},
{
"code": null,
"e": 27133,
"s": 27125,
"text": "Strings"
},
{
"code": null,
"e": 27231,
"s": 27133,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27240,
"s": 27231,
"text": "Comments"
},
{
"code": null,
"e": 27253,
"s": 27240,
"text": "Old Comments"
},
{
"code": null,
"e": 27285,
"s": 27253,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 27323,
"s": 27285,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 27352,
"s": 27323,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 27409,
"s": 27352,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 27457,
"s": 27409,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 27482,
"s": 27457,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27528,
"s": 27482,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 27562,
"s": 27528,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 27622,
"s": 27562,
"text": "Write a program to print all permutations of a given string"
}
] |
Displaying 3D images in Python - GeeksforGeeks | 06 Jul, 2021
In this article, we will discuss how to display 3D images using different methods, (i.e 3d projection, view_init() method, and using a loop) in Python.
Matplotlib: It is a plotting library for Python programming it serves as a visualization utility library, Matplotlib is built on NumPy arrays, and designed to work with the broader SciPy stack.
Numpy: It is a general-purpose array-processing package. It provides a high-performance multidimensional array and matrices along with a large collection of high-level mathematical functions.
mpl_toolkits: It provides some basic 3d plotting (scatter, surf, line, mesh) tools.
Example 1:
In this example, we created a 3d image of a scatter sin wave. Here we have created an array of points using ‘np.arrange’ and ‘np.sin’.NumPy.sin: This mathematical function helps the user to calculate trigonometric sine for all x(being the array elements), and another function is the scatter() method which is the matplotlib library used to draw a scatter plot.
Syntax: np.arrange(start, stop, step) : It returns an array with evenly spaced elements as per the interval.
Parameters:
start: start of interval range.
stop: end of interval range.
step: step size of the interval.
Python3
# Import librariesimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D # Change the Size of Graph using# Figsizefig = plt.figure(figsize=(10, 10)) # Generating a 3D sine waveax = plt.axes(projection='3d') # Creating array points using# numpyx = np.arange(0, 20, 0.1)y = np.sin(x)z = y*np.sin(x)c = x + y # To create a scatter graphax.scatter(x, y, z, c=c) # trun off/on axisplt.axis('off') # show the graphplt.show()
Output:
Example 2:
In this example, we are selecting the 3D axis of the dimension X =5, Y=5, Z=5, and in np.ones() we are passing the dimensions of the cube. The np.ones () function returns a new array of given shape and type, with ones.
Syntax: numpy.ones (shape, dtype = None)
After the above step, we are selecting color opacity as alpha = 0.9 ( vary from 0.0 – 1.0 ). In the next step, we are passing the dimension of axes( i.e 5, 5, 5) + number of faces for the cube ( i.e 0-4 ) in np.empty() function after that we are passing color combination and opacity for each face of the cube and in last Voxels is used to customizations of the sizes, positions, and colors. The np.empty () function return a new array of given shape and type, without initializing entries.
Syntax: numpy.empty(shape)
Python3
# Import librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # Change the Size of Graph using# Figsizefig = plt.figure(figsize=(10, 10)) # Generating a 3D sine waveax = plt.axes(projection='3d') # Create axisaxes = [5, 5, 5] # Create Datadata = np.ones(axes) # Controll Tranperencyalpha = 0.9 # Control colourcolors = np.empty(axes + [4]) colors[0] = [1, 0, 0, alpha] # redcolors[1] = [0, 1, 0, alpha] # greencolors[2] = [0, 0, 1, alpha] # bluecolors[3] = [1, 1, 0, alpha] # yellowcolors[4] = [1, 1, 1, alpha] # grey # trun off/on axisplt.axis('off') # Voxels is used to customizations of# the sizes, positions and colors.ax.voxels(data, facecolors=colors, edgecolors='grey')
Output:
Example 3:
In this example, we use numpy.linspace() that creates an array of 10 linearly placed elements between -1 and 5, both inclusive after that the mesh grid function returns two 2-dimensional arrays, After that in order to visualize an image of 3D wireframe we require passing coordinates of X, Y, Z, color(optional).
Python3
#Import librariesimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D #Change the Size of Graph using Figsizefig = plt.figure(figsize=(10,10)) #Generating a 3D sine waveax = plt.axes(projection='3d') # assigning coordinatesx = np.linspace(-1, 5, 10)y = np.linspace(-1, 5, 10)X, Y = np.meshgrid(x, y)Z = np.sin(np.sqrt(X ** 2 + Y ** 2)) # creating the visualizationax.plot_wireframe(X, Y, Z, color ='green') # trun off/on axisplt.axis('off')
Output:
Example 4:
In this example, we plot a spiral graph, and we will see its 360-degree view using a loop. Here, view_init(elev=, azim=)This can be used to rotate the axes programmatically.‘elev’ stores the elevation angle in the z plane. ‘azim’ stores the azimuth angle in the x,y plane.D constructor. The draw() function in pyplot module of the matplotlib library is used to redraw the current figure with a pause of 0.001-time interval.
Python3
from numpy import linspaceimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3d # Creating 3D figurefig = plt.figure(figsize=(8, 8))ax = plt.axes(projection='3d') # Creating Datasetz = np.linspace(0, 15, 1000)x = np.sin(z)y = np.cos(z)ax.plot3D(x, y, z, 'green') # 360 Degree viewfor angle in range(0, 360): ax.view_init(angle, 30) plt.draw() plt.pause(.001) plt.show()
Output:
as5853535
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 24444,
"s": 24292,
"text": "In this article, we will discuss how to display 3D images using different methods, (i.e 3d projection, view_init() method, and using a loop) in Python."
},
{
"code": null,
"e": 24638,
"s": 24444,
"text": "Matplotlib: It is a plotting library for Python programming it serves as a visualization utility library, Matplotlib is built on NumPy arrays, and designed to work with the broader SciPy stack."
},
{
"code": null,
"e": 24830,
"s": 24638,
"text": "Numpy: It is a general-purpose array-processing package. It provides a high-performance multidimensional array and matrices along with a large collection of high-level mathematical functions."
},
{
"code": null,
"e": 24914,
"s": 24830,
"text": "mpl_toolkits: It provides some basic 3d plotting (scatter, surf, line, mesh) tools."
},
{
"code": null,
"e": 24925,
"s": 24914,
"text": "Example 1:"
},
{
"code": null,
"e": 25287,
"s": 24925,
"text": "In this example, we created a 3d image of a scatter sin wave. Here we have created an array of points using ‘np.arrange’ and ‘np.sin’.NumPy.sin: This mathematical function helps the user to calculate trigonometric sine for all x(being the array elements), and another function is the scatter() method which is the matplotlib library used to draw a scatter plot."
},
{
"code": null,
"e": 25396,
"s": 25287,
"text": "Syntax: np.arrange(start, stop, step) : It returns an array with evenly spaced elements as per the interval."
},
{
"code": null,
"e": 25408,
"s": 25396,
"text": "Parameters:"
},
{
"code": null,
"e": 25440,
"s": 25408,
"text": "start: start of interval range."
},
{
"code": null,
"e": 25469,
"s": 25440,
"text": "stop: end of interval range."
},
{
"code": null,
"e": 25502,
"s": 25469,
"text": "step: step size of the interval."
},
{
"code": null,
"e": 25510,
"s": 25502,
"text": "Python3"
},
{
"code": "# Import librariesimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D # Change the Size of Graph using# Figsizefig = plt.figure(figsize=(10, 10)) # Generating a 3D sine waveax = plt.axes(projection='3d') # Creating array points using# numpyx = np.arange(0, 20, 0.1)y = np.sin(x)z = y*np.sin(x)c = x + y # To create a scatter graphax.scatter(x, y, z, c=c) # trun off/on axisplt.axis('off') # show the graphplt.show()",
"e": 25963,
"s": 25510,
"text": null
},
{
"code": null,
"e": 25971,
"s": 25963,
"text": "Output:"
},
{
"code": null,
"e": 25982,
"s": 25971,
"text": "Example 2:"
},
{
"code": null,
"e": 26201,
"s": 25982,
"text": "In this example, we are selecting the 3D axis of the dimension X =5, Y=5, Z=5, and in np.ones() we are passing the dimensions of the cube. The np.ones () function returns a new array of given shape and type, with ones."
},
{
"code": null,
"e": 26242,
"s": 26201,
"text": "Syntax: numpy.ones (shape, dtype = None)"
},
{
"code": null,
"e": 26733,
"s": 26242,
"text": "After the above step, we are selecting color opacity as alpha = 0.9 ( vary from 0.0 – 1.0 ). In the next step, we are passing the dimension of axes( i.e 5, 5, 5) + number of faces for the cube ( i.e 0-4 ) in np.empty() function after that we are passing color combination and opacity for each face of the cube and in last Voxels is used to customizations of the sizes, positions, and colors. The np.empty () function return a new array of given shape and type, without initializing entries."
},
{
"code": null,
"e": 26761,
"s": 26733,
"text": "Syntax: numpy.empty(shape) "
},
{
"code": null,
"e": 26769,
"s": 26761,
"text": "Python3"
},
{
"code": "# Import librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # Change the Size of Graph using# Figsizefig = plt.figure(figsize=(10, 10)) # Generating a 3D sine waveax = plt.axes(projection='3d') # Create axisaxes = [5, 5, 5] # Create Datadata = np.ones(axes) # Controll Tranperencyalpha = 0.9 # Control colourcolors = np.empty(axes + [4]) colors[0] = [1, 0, 0, alpha] # redcolors[1] = [0, 1, 0, alpha] # greencolors[2] = [0, 0, 1, alpha] # bluecolors[3] = [1, 1, 0, alpha] # yellowcolors[4] = [1, 1, 1, alpha] # grey # trun off/on axisplt.axis('off') # Voxels is used to customizations of# the sizes, positions and colors.ax.voxels(data, facecolors=colors, edgecolors='grey')",
"e": 27496,
"s": 26769,
"text": null
},
{
"code": null,
"e": 27504,
"s": 27496,
"text": "Output:"
},
{
"code": null,
"e": 27515,
"s": 27504,
"text": "Example 3:"
},
{
"code": null,
"e": 27828,
"s": 27515,
"text": "In this example, we use numpy.linspace() that creates an array of 10 linearly placed elements between -1 and 5, both inclusive after that the mesh grid function returns two 2-dimensional arrays, After that in order to visualize an image of 3D wireframe we require passing coordinates of X, Y, Z, color(optional)."
},
{
"code": null,
"e": 27836,
"s": 27828,
"text": "Python3"
},
{
"code": "#Import librariesimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D #Change the Size of Graph using Figsizefig = plt.figure(figsize=(10,10)) #Generating a 3D sine waveax = plt.axes(projection='3d') # assigning coordinatesx = np.linspace(-1, 5, 10)y = np.linspace(-1, 5, 10)X, Y = np.meshgrid(x, y)Z = np.sin(np.sqrt(X ** 2 + Y ** 2)) # creating the visualizationax.plot_wireframe(X, Y, Z, color ='green') # trun off/on axisplt.axis('off')",
"e": 28314,
"s": 27836,
"text": null
},
{
"code": null,
"e": 28322,
"s": 28314,
"text": "Output:"
},
{
"code": null,
"e": 28333,
"s": 28322,
"text": "Example 4:"
},
{
"code": null,
"e": 28757,
"s": 28333,
"text": "In this example, we plot a spiral graph, and we will see its 360-degree view using a loop. Here, view_init(elev=, azim=)This can be used to rotate the axes programmatically.‘elev’ stores the elevation angle in the z plane. ‘azim’ stores the azimuth angle in the x,y plane.D constructor. The draw() function in pyplot module of the matplotlib library is used to redraw the current figure with a pause of 0.001-time interval."
},
{
"code": null,
"e": 28765,
"s": 28757,
"text": "Python3"
},
{
"code": "from numpy import linspaceimport numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits import mplot3d # Creating 3D figurefig = plt.figure(figsize=(8, 8))ax = plt.axes(projection='3d') # Creating Datasetz = np.linspace(0, 15, 1000)x = np.sin(z)y = np.cos(z)ax.plot3D(x, y, z, 'green') # 360 Degree viewfor angle in range(0, 360): ax.view_init(angle, 30) plt.draw() plt.pause(.001) plt.show()",
"e": 29173,
"s": 28765,
"text": null
},
{
"code": null,
"e": 29181,
"s": 29173,
"text": "Output:"
},
{
"code": null,
"e": 29191,
"s": 29181,
"text": "as5853535"
},
{
"code": null,
"e": 29198,
"s": 29191,
"text": "Picked"
},
{
"code": null,
"e": 29216,
"s": 29198,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 29223,
"s": 29216,
"text": "Python"
},
{
"code": null,
"e": 29321,
"s": 29223,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29353,
"s": 29321,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29409,
"s": 29353,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29451,
"s": 29409,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29493,
"s": 29451,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29515,
"s": 29493,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29554,
"s": 29515,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29585,
"s": 29554,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29640,
"s": 29585,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29669,
"s": 29640,
"text": "Create a directory in Python"
}
] |
Neo4j - With Clause | You can chain the query arts together using the WITH clause.
Following is the syntax of the WITH clause.
MATCH (n)
WITH n
ORDER BY n.property
RETURN collect(n.property)
Following is a sample Cypher Query which demonstrates the usage of the WITH clause.
MATCH (n)
WITH n
ORDER BY n.name DESC LIMIT 3
RETURN collect(n.name)
To execute the above query, carry out the following steps −
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2400,
"s": 2339,
"text": "You can chain the query arts together using the WITH clause."
},
{
"code": null,
"e": 2444,
"s": 2400,
"text": "Following is the syntax of the WITH clause."
},
{
"code": null,
"e": 2513,
"s": 2444,
"text": "MATCH (n) \nWITH n \nORDER BY n.property \nRETURN collect(n.property) \n"
},
{
"code": null,
"e": 2597,
"s": 2513,
"text": "Following is a sample Cypher Query which demonstrates the usage of the WITH clause."
},
{
"code": null,
"e": 2670,
"s": 2597,
"text": "MATCH (n) \nWITH n \nORDER BY n.name DESC LIMIT 3 \nRETURN collect(n.name) "
},
{
"code": null,
"e": 2730,
"s": 2670,
"text": "To execute the above query, carry out the following steps −"
},
{
"code": null,
"e": 2908,
"s": 2730,
"text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot."
},
{
"code": null,
"e": 3061,
"s": 2908,
"text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot."
},
{
"code": null,
"e": 3110,
"s": 3061,
"text": "On executing, you will get the following result."
},
{
"code": null,
"e": 3117,
"s": 3110,
"text": " Print"
},
{
"code": null,
"e": 3128,
"s": 3117,
"text": " Add Notes"
}
] |
How to create an empty tuple in Python? | You can create empty tuple object by giving no elements in parentheses in assignment statement. Empty tuple object is also created by tuple() built-in function without any arguments
>>> T1 = ()
>>> T1
()
>>> T1 = tuple()
>>> T1
() | [
{
"code": null,
"e": 1244,
"s": 1062,
"text": "You can create empty tuple object by giving no elements in parentheses in assignment statement. Empty tuple object is also created by tuple() built-in function without any arguments"
},
{
"code": null,
"e": 1293,
"s": 1244,
"text": ">>> T1 = ()\n>>> T1\n()\n>>> T1 = tuple()\n>>> T1\n()"
}
] |
ggplot: Grammar of Graphics in Python with Plotnine | by Alan Jones | Towards Data Science | Do you wish that Python could emulate the superb visualizations that ggplot gives you in the R language? Well, it can.
We are going to explore the capabilities of Plotnine, a visualization library for Python that is based on ggplot2.
Being able to visualize your data gives you the ability to better understand it. It gives you the opportunity to gain insights into the relationships between elements of that data and to spot correlations and dependencies. ggplot, in R, and Plotnine in Python gives you the ability to do this in a logical way.
You don’t need to be an expert in Python to be able to do this, although some exposure to programming in Python would be useful, as would be a basic understanding of DataFrames in Pandas.
It would be helpful if you are familiar with Jupyter Notebooks, too.
ggplot2 is a powerful graphics library for R and is described in the book “ggplot2: Elegant Graphics for Data Analysis” by Hadley Wickham (affiliate link). Wickham, in turn, based his work on “The Grammar of Graphics”, a book by Leland Wilkinson. Wilkinson’s book gives the theoretical basis for a grammar of graphics and Wickham’s book shows how such a grammar can be implemented (in ggplot2).
ggplot2 implements a layered approach to constructing graphics and allows the possibility of either using standard routines for the construction of popular graphs and charts, or the construction of custom graphics to suit your own purposes.
Plotnine is based on ggplot2 and implemented in Python.
Depending on your Python installation, you can install it with pip:
pip install plotnine
or Conda:
conda install -c conda-forge plotnine
This article will focus on how to construct and customize standard graphs — lines, bars and so on — use layers to modify those plots and hopefully give an inkling as to how you could produce customized plots of your own.
Then, in your program, your first line should be
from plotnine import *
There are three basic elements to a ggplot command, data, aesthetics and layers. The role of data is clear and we should provide it in the form of a Pandas DataFrame. Aesthetics are where variables in the data are mapped onto visual properties and layers describe how to render the data, for example, as a bar chart. There can be several layers that define different charts or parts of the chart, such as labels on the axes.
In R commands in ggplot2 look something like:
ggplot(data, aesthetics) + layer1() + layer2()
Plotnine uses the same pattern but this doesn’t fit with Python syntax very well. You could write:
ggplot(data,aesthetics) + layer1() + layer2()
but you can end up with very long lines. The solution is simple, though. Just enclose the whole thing in braces. So we end up with:
(ggplot(data,aesthetics) + layer1() + layer2())
So this is the style that I will use in this article.
If you’ve followed my introductions to visualization for Pandas Plot or Julia, you will be familiar with the weather data that I use. It is public data derived from the UK Meteorological Office and charts weather data for London over the last few decades.
The data tracks the maximum and minimum temperatures, the number of hours of sunshine and the rainfall for each month. There are two tables, one is the complete set of data from 1957 and a shorter one records the data for 2018, only.
We’ll get the 2018 data first.
import pandas as pdweather=pd.read_csv(‘https://raw.githubusercontent.com/alanjones2/dataviz/master/london2018.csv')weather
And this is what it looks like:
The Year column is fairly redundant but is consistent with the larger data file. The other columns are self-explanatory. Months are numbered from 1 to 12, temperatures are in Celsius, rainfall is millimeters and sunshine is in hours.
So, to get started with ggplot, we are going to draw a line graph of the maximum temperatures for each month. We will then add some layers to enhance the graph.
The anatomy of the call to ggplot is as described above. The first parameter is the data that we are going to graph, weather, the next parameter is a call to aes. aes maps the data onto various ‘aesthetics’ — here we have just two. By default, the first two parameters are the x and y axes. So here Month will be on the x axis and Tmax on the y axis.
This by itself is a legitimate call to ggplot but it won’t draw anything. To do that we need to add a layer to tell ggplot what sort of graph we want. Graph types are called geoms and the one we use here is geom_line, which is, of course, a line graph.
(ggplot(weather,aes('Month', 'Tmax')) + geom_line())
That’s a good start but we can do better with a couple of modifications. For example, you’ll notice that the months are numeric values rather than actual dates, so the line plot has interpreted them as real numbers. This means that we end up with the months ranging from 2.5 to 12.5 — not ideal.
We can easily fix this by adding another layer to the graph function. ggplot allows us to specify the ticks each axis, so we’ll add a layer to do that. We want the ticks to be the numbers 1 through 12, which is exactly what is in the Month column. So we’ll use that data to tell ggplot what the ticks should be.
For convenience, I am going to use a variable months. Like this:
months = weather['Month']
Here is the complete code
months=weather['Month'](ggplot(weather,aes('Month','Tmax')) + geom_line() + scale_x_continuous(breaks=months))
That’s better but what if we wanted to label the months with strings, ‘Jan’, ‘Feb’, etc. Well, of course, we could change the data in the table but this article is about ggplot, so we’ll use that, instead.
Also, I’m not keen on the default color scheme. ggplot comes with a number of themes that we can use, so I’ll add another layer to specify that I want to use the Light theme and add a parameter to geom_line to tell it to draw a red line instead of the default black one.
month_labels=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")(ggplot(weather,aes('Month','Tmax')) + geom_line(color='red') + scale_x_continuous(breaks=months,labels=month_labels) + theme_light())
That’s an improvement, I think.
Let’s do the same sort of plot but with a column chart.
To draw a column chart we simply swap the geom. Instead of geom_line, we use geom_col. Simple. The only thing to watch out for is that if we want to change the color of the bars, we need to specify a ‘fill’. There is a parameter ‘color’ but this only changes the outline of the columns.
(ggplot(weather,aes('Month','Tmax')) + geom_col(fill='red') + scale_x_continuous(breaks=months, labels=month_labels) + theme_light())
And here is the same sort of thing for Rain — with a suitably rainy color change.
(ggplot(weather,aes('Month','Rain')) + geom_col(fill='green') + scale_x_continuous(breaks=months, labels=month_labels) + theme_light())
I want to draw Tmax and Tmin on the same graph — how do I do that?
The best way is to transform the data so that the two temperatures are in the same column and labelled as either Tmax or Tmin in a separate column. This is easily done with the Pandas melt function. Here I have created a new dataframe temps with the required columns.
temps = pd.melt(weather, id_vars=['Month'], value_vars=['Tmax','Tmin'], var_name='Temp', value_name='DegC' )temps
And now I plot them with a column geom. There are a couple of things to note here. First, I’ve taken the fill out of the geom and put it in the call to aes and assigned it to Temps (which will either be Tmax or Tmin).
Specifying a color in the geom fixes that color in that geom, whereas by putting it in aes I can tell the geom to color the columns differently for each Temp value. So the column geom will now color two separate bars one for Tmax and the other for Tmin. By default these bars would be stacked but here we want them to be side by side.
So the second thing is that in the column geom I’ve specified the position to be ‘dodge’ which gives us the side by side configuration.
(ggplot(temps,aes('Month','DegC',fill='Temp')) + geom_col(position='dodge') + scale_x_continuous(breaks=months) + theme_light())
Here is the same thing but with lines. Note that I specify color not fill for the lines and that I don’t need to worry about the position.
(ggplot(temps,aes(‘Month’,’DegC’,color=’Temp’)) + geom_line() + scale_x_continuous(breaks=months) + theme_light())
As you have seen, to add more to the plot, we add more layers. To modify the labels on our chart we can do the same. In the next piece of code, I’ve added layers to specify the captions on the x and y axes, and have given the whole chart a title.
(ggplot(temps,aes('Month','DegC',color='Temp')) + geom_line() + scale_x_continuous(breaks=months) + theme_light() + xlab('2018') + ylab('Temperature in degrees C') + ggtitle('Monthly Maximum and Minimum Temperatures'))
Let’s think about drawing a single figure that summarizes the entire table of data. Column charts for the two temperatures, for rainfall and sunshine.
First, we melt the dataframe again but this time we put all of the data in a single column. Each value will be labelled as Tmax, Tmin, Rain or Sun.
data = pd.melt(weather, id_vars=['Month'], value_vars=['Tmax','Tmin','Rain','Sun'], var_name='Measure', value_name='Value' )
To create the faceted graph we add a facet_wrap layer and we pass the Measure to it meaning that we will get facets for each of Tmax, tmin, Rain and Sun. By default, the facets will all use the same scale, which would be fine for Tmax and Tmin. But Rain and Sun are both different from each and the temperatures. So we need to tell facet_wrap that the scales are ‘free’, that is, each facet will have its own scale.
The trouble is that doing this means that the labels for the y axes tend to overlap the charts, so we need to adjust the layout with another layer. The last layer is a modification of the theme (theme_light) to add extra spacing between the facets and to set the overall size of the figure. Note that this must come after the theme_light layer, otherwise theme_light will reset the layout to it default settings.
(ggplot(data, aes('Month','Value', fill='Measure')) + geom_col(show_legend=False) + scale_x_continuous(breaks=months,labels=month_labels) + facet_wrap('Measure', scales='free') + xlab('') + ylab('') + ggtitle('Weather Data for London, 2018') + theme_light() + theme(panel_spacing=0.5, figure_size=(10,5)))
This has been a fairly random walkthrough of some of the aspects and features of ggplot as implemented in Python by Plotnine. I hope that you can see the power of this approach and encourage you to read Hadley Wickham’s book on ggplot2 and see the Plotnine documentation.
If you would like to be informed about future articles please subscribe to my free (occasional) newsletter. | [
{
"code": null,
"e": 290,
"s": 171,
"text": "Do you wish that Python could emulate the superb visualizations that ggplot gives you in the R language? Well, it can."
},
{
"code": null,
"e": 405,
"s": 290,
"text": "We are going to explore the capabilities of Plotnine, a visualization library for Python that is based on ggplot2."
},
{
"code": null,
"e": 716,
"s": 405,
"text": "Being able to visualize your data gives you the ability to better understand it. It gives you the opportunity to gain insights into the relationships between elements of that data and to spot correlations and dependencies. ggplot, in R, and Plotnine in Python gives you the ability to do this in a logical way."
},
{
"code": null,
"e": 904,
"s": 716,
"text": "You don’t need to be an expert in Python to be able to do this, although some exposure to programming in Python would be useful, as would be a basic understanding of DataFrames in Pandas."
},
{
"code": null,
"e": 973,
"s": 904,
"text": "It would be helpful if you are familiar with Jupyter Notebooks, too."
},
{
"code": null,
"e": 1368,
"s": 973,
"text": "ggplot2 is a powerful graphics library for R and is described in the book “ggplot2: Elegant Graphics for Data Analysis” by Hadley Wickham (affiliate link). Wickham, in turn, based his work on “The Grammar of Graphics”, a book by Leland Wilkinson. Wilkinson’s book gives the theoretical basis for a grammar of graphics and Wickham’s book shows how such a grammar can be implemented (in ggplot2)."
},
{
"code": null,
"e": 1609,
"s": 1368,
"text": "ggplot2 implements a layered approach to constructing graphics and allows the possibility of either using standard routines for the construction of popular graphs and charts, or the construction of custom graphics to suit your own purposes."
},
{
"code": null,
"e": 1665,
"s": 1609,
"text": "Plotnine is based on ggplot2 and implemented in Python."
},
{
"code": null,
"e": 1733,
"s": 1665,
"text": "Depending on your Python installation, you can install it with pip:"
},
{
"code": null,
"e": 1754,
"s": 1733,
"text": "pip install plotnine"
},
{
"code": null,
"e": 1764,
"s": 1754,
"text": "or Conda:"
},
{
"code": null,
"e": 1802,
"s": 1764,
"text": "conda install -c conda-forge plotnine"
},
{
"code": null,
"e": 2023,
"s": 1802,
"text": "This article will focus on how to construct and customize standard graphs — lines, bars and so on — use layers to modify those plots and hopefully give an inkling as to how you could produce customized plots of your own."
},
{
"code": null,
"e": 2072,
"s": 2023,
"text": "Then, in your program, your first line should be"
},
{
"code": null,
"e": 2095,
"s": 2072,
"text": "from plotnine import *"
},
{
"code": null,
"e": 2520,
"s": 2095,
"text": "There are three basic elements to a ggplot command, data, aesthetics and layers. The role of data is clear and we should provide it in the form of a Pandas DataFrame. Aesthetics are where variables in the data are mapped onto visual properties and layers describe how to render the data, for example, as a bar chart. There can be several layers that define different charts or parts of the chart, such as labels on the axes."
},
{
"code": null,
"e": 2566,
"s": 2520,
"text": "In R commands in ggplot2 look something like:"
},
{
"code": null,
"e": 2614,
"s": 2566,
"text": "ggplot(data, aesthetics) + layer1() + layer2()"
},
{
"code": null,
"e": 2713,
"s": 2614,
"text": "Plotnine uses the same pattern but this doesn’t fit with Python syntax very well. You could write:"
},
{
"code": null,
"e": 2759,
"s": 2713,
"text": "ggplot(data,aesthetics) + layer1() + layer2()"
},
{
"code": null,
"e": 2891,
"s": 2759,
"text": "but you can end up with very long lines. The solution is simple, though. Just enclose the whole thing in braces. So we end up with:"
},
{
"code": null,
"e": 2939,
"s": 2891,
"text": "(ggplot(data,aesthetics) + layer1() + layer2())"
},
{
"code": null,
"e": 2993,
"s": 2939,
"text": "So this is the style that I will use in this article."
},
{
"code": null,
"e": 3249,
"s": 2993,
"text": "If you’ve followed my introductions to visualization for Pandas Plot or Julia, you will be familiar with the weather data that I use. It is public data derived from the UK Meteorological Office and charts weather data for London over the last few decades."
},
{
"code": null,
"e": 3483,
"s": 3249,
"text": "The data tracks the maximum and minimum temperatures, the number of hours of sunshine and the rainfall for each month. There are two tables, one is the complete set of data from 1957 and a shorter one records the data for 2018, only."
},
{
"code": null,
"e": 3514,
"s": 3483,
"text": "We’ll get the 2018 data first."
},
{
"code": null,
"e": 3638,
"s": 3514,
"text": "import pandas as pdweather=pd.read_csv(‘https://raw.githubusercontent.com/alanjones2/dataviz/master/london2018.csv')weather"
},
{
"code": null,
"e": 3670,
"s": 3638,
"text": "And this is what it looks like:"
},
{
"code": null,
"e": 3904,
"s": 3670,
"text": "The Year column is fairly redundant but is consistent with the larger data file. The other columns are self-explanatory. Months are numbered from 1 to 12, temperatures are in Celsius, rainfall is millimeters and sunshine is in hours."
},
{
"code": null,
"e": 4065,
"s": 3904,
"text": "So, to get started with ggplot, we are going to draw a line graph of the maximum temperatures for each month. We will then add some layers to enhance the graph."
},
{
"code": null,
"e": 4416,
"s": 4065,
"text": "The anatomy of the call to ggplot is as described above. The first parameter is the data that we are going to graph, weather, the next parameter is a call to aes. aes maps the data onto various ‘aesthetics’ — here we have just two. By default, the first two parameters are the x and y axes. So here Month will be on the x axis and Tmax on the y axis."
},
{
"code": null,
"e": 4669,
"s": 4416,
"text": "This by itself is a legitimate call to ggplot but it won’t draw anything. To do that we need to add a layer to tell ggplot what sort of graph we want. Graph types are called geoms and the one we use here is geom_line, which is, of course, a line graph."
},
{
"code": null,
"e": 4723,
"s": 4669,
"text": "(ggplot(weather,aes('Month', 'Tmax')) + geom_line())"
},
{
"code": null,
"e": 5019,
"s": 4723,
"text": "That’s a good start but we can do better with a couple of modifications. For example, you’ll notice that the months are numeric values rather than actual dates, so the line plot has interpreted them as real numbers. This means that we end up with the months ranging from 2.5 to 12.5 — not ideal."
},
{
"code": null,
"e": 5331,
"s": 5019,
"text": "We can easily fix this by adding another layer to the graph function. ggplot allows us to specify the ticks each axis, so we’ll add a layer to do that. We want the ticks to be the numbers 1 through 12, which is exactly what is in the Month column. So we’ll use that data to tell ggplot what the ticks should be."
},
{
"code": null,
"e": 5396,
"s": 5331,
"text": "For convenience, I am going to use a variable months. Like this:"
},
{
"code": null,
"e": 5422,
"s": 5396,
"text": "months = weather['Month']"
},
{
"code": null,
"e": 5448,
"s": 5422,
"text": "Here is the complete code"
},
{
"code": null,
"e": 5562,
"s": 5448,
"text": "months=weather['Month'](ggplot(weather,aes('Month','Tmax')) + geom_line() + scale_x_continuous(breaks=months))"
},
{
"code": null,
"e": 5768,
"s": 5562,
"text": "That’s better but what if we wanted to label the months with strings, ‘Jan’, ‘Feb’, etc. Well, of course, we could change the data in the table but this article is about ggplot, so we’ll use that, instead."
},
{
"code": null,
"e": 6039,
"s": 5768,
"text": "Also, I’m not keen on the default color scheme. ggplot comes with a number of themes that we can use, so I’ll add another layer to specify that I want to use the Light theme and add a parameter to geom_line to tell it to draw a red line instead of the default black one."
},
{
"code": null,
"e": 6266,
"s": 6039,
"text": "month_labels=(\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\")(ggplot(weather,aes('Month','Tmax')) + geom_line(color='red') + scale_x_continuous(breaks=months,labels=month_labels) + theme_light())"
},
{
"code": null,
"e": 6298,
"s": 6266,
"text": "That’s an improvement, I think."
},
{
"code": null,
"e": 6354,
"s": 6298,
"text": "Let’s do the same sort of plot but with a column chart."
},
{
"code": null,
"e": 6641,
"s": 6354,
"text": "To draw a column chart we simply swap the geom. Instead of geom_line, we use geom_col. Simple. The only thing to watch out for is that if we want to change the color of the bars, we need to specify a ‘fill’. There is a parameter ‘color’ but this only changes the outline of the columns."
},
{
"code": null,
"e": 6778,
"s": 6641,
"text": "(ggplot(weather,aes('Month','Tmax')) + geom_col(fill='red') + scale_x_continuous(breaks=months, labels=month_labels) + theme_light())"
},
{
"code": null,
"e": 6860,
"s": 6778,
"text": "And here is the same sort of thing for Rain — with a suitably rainy color change."
},
{
"code": null,
"e": 6999,
"s": 6860,
"text": "(ggplot(weather,aes('Month','Rain')) + geom_col(fill='green') + scale_x_continuous(breaks=months, labels=month_labels) + theme_light())"
},
{
"code": null,
"e": 7066,
"s": 6999,
"text": "I want to draw Tmax and Tmin on the same graph — how do I do that?"
},
{
"code": null,
"e": 7334,
"s": 7066,
"text": "The best way is to transform the data so that the two temperatures are in the same column and labelled as either Tmax or Tmin in a separate column. This is easily done with the Pandas melt function. Here I have created a new dataframe temps with the required columns."
},
{
"code": null,
"e": 7480,
"s": 7334,
"text": "temps = pd.melt(weather, id_vars=['Month'], value_vars=['Tmax','Tmin'], var_name='Temp', value_name='DegC' )temps"
},
{
"code": null,
"e": 7698,
"s": 7480,
"text": "And now I plot them with a column geom. There are a couple of things to note here. First, I’ve taken the fill out of the geom and put it in the call to aes and assigned it to Temps (which will either be Tmax or Tmin)."
},
{
"code": null,
"e": 8033,
"s": 7698,
"text": "Specifying a color in the geom fixes that color in that geom, whereas by putting it in aes I can tell the geom to color the columns differently for each Temp value. So the column geom will now color two separate bars one for Tmax and the other for Tmin. By default these bars would be stacked but here we want them to be side by side."
},
{
"code": null,
"e": 8169,
"s": 8033,
"text": "So the second thing is that in the column geom I’ve specified the position to be ‘dodge’ which gives us the side by side configuration."
},
{
"code": null,
"e": 8301,
"s": 8169,
"text": "(ggplot(temps,aes('Month','DegC',fill='Temp')) + geom_col(position='dodge') + scale_x_continuous(breaks=months) + theme_light())"
},
{
"code": null,
"e": 8440,
"s": 8301,
"text": "Here is the same thing but with lines. Note that I specify color not fill for the lines and that I don’t need to worry about the position."
},
{
"code": null,
"e": 8558,
"s": 8440,
"text": "(ggplot(temps,aes(‘Month’,’DegC’,color=’Temp’)) + geom_line() + scale_x_continuous(breaks=months) + theme_light())"
},
{
"code": null,
"e": 8805,
"s": 8558,
"text": "As you have seen, to add more to the plot, we add more layers. To modify the labels on our chart we can do the same. In the next piece of code, I’ve added layers to specify the captions on the x and y axes, and have given the whole chart a title."
},
{
"code": null,
"e": 9030,
"s": 8805,
"text": "(ggplot(temps,aes('Month','DegC',color='Temp')) + geom_line() + scale_x_continuous(breaks=months) + theme_light() + xlab('2018') + ylab('Temperature in degrees C') + ggtitle('Monthly Maximum and Minimum Temperatures'))"
},
{
"code": null,
"e": 9181,
"s": 9030,
"text": "Let’s think about drawing a single figure that summarizes the entire table of data. Column charts for the two temperatures, for rainfall and sunshine."
},
{
"code": null,
"e": 9329,
"s": 9181,
"text": "First, we melt the dataframe again but this time we put all of the data in a single column. Each value will be labelled as Tmax, Tmin, Rain or Sun."
},
{
"code": null,
"e": 9484,
"s": 9329,
"text": "data = pd.melt(weather, id_vars=['Month'], value_vars=['Tmax','Tmin','Rain','Sun'], var_name='Measure', value_name='Value' )"
},
{
"code": null,
"e": 9900,
"s": 9484,
"text": "To create the faceted graph we add a facet_wrap layer and we pass the Measure to it meaning that we will get facets for each of Tmax, tmin, Rain and Sun. By default, the facets will all use the same scale, which would be fine for Tmax and Tmin. But Rain and Sun are both different from each and the temperatures. So we need to tell facet_wrap that the scales are ‘free’, that is, each facet will have its own scale."
},
{
"code": null,
"e": 10313,
"s": 9900,
"text": "The trouble is that doing this means that the labels for the y axes tend to overlap the charts, so we need to adjust the layout with another layer. The last layer is a modification of the theme (theme_light) to add extra spacing between the facets and to set the overall size of the figure. Note that this must come after the theme_light layer, otherwise theme_light will reset the layout to it default settings."
},
{
"code": null,
"e": 10627,
"s": 10313,
"text": "(ggplot(data, aes('Month','Value', fill='Measure')) + geom_col(show_legend=False) + scale_x_continuous(breaks=months,labels=month_labels) + facet_wrap('Measure', scales='free') + xlab('') + ylab('') + ggtitle('Weather Data for London, 2018') + theme_light() + theme(panel_spacing=0.5, figure_size=(10,5)))"
},
{
"code": null,
"e": 10899,
"s": 10627,
"text": "This has been a fairly random walkthrough of some of the aspects and features of ggplot as implemented in Python by Plotnine. I hope that you can see the power of this approach and encourage you to read Hadley Wickham’s book on ggplot2 and see the Plotnine documentation."
}
] |
How to Tune the Hyperparameters for Better Performance | by Soner Yıldırım | Towards Data Science | There are various ready-to-use machine learning algorithms. They all have their pros and cons. For a given task, it is the job of the machine learning engineer or data scientist to select the optimal algorithm and make the most out of it.
A critical part of making the most out of a model is hyperparameter tuning. The performance of a model is greatly influenced by the selected hyperparameter values.
In this post, we will focus on how to tune hyperparameters to obtain a more robust and generalized mode.
In some sense, we design our own implementation of an algorithm by finding the optimal hyperparameter values for a given task and dataset.
As the model complexity increases, the number of hyperparameters also increase. Tree based ensemble learners such as xgboost and lightgbm have lots of hyperparameters.
The hyperparameters need to be tuned very well in order to get accurate, and robust results. Our focus should not be getting the best accuracy or lowest lost. The ultimate goal is to have a robust, accurate, and not-overfit model.
The tuning process cannot be just trying random combinations of hyperparameters. We need to understand what they mean and how they change the model.
The outline of the post is as follows:
Create a classification dataset
LightGBM classifier
Tune hyperparameters to improve the model
The make_classification function of scikit-learn allows creating customized classification datasets. You can customize the dataset by choosing the number of samples, informative and redundant features. It is also possible to adjust the difficulty of classification task by using the class_sep and flip_y parameters.
import numpy as npimport pandas as pdfrom sklearn.datasets import make_classificationX, y = make_classification( n_samples=50000, n_features=20, n_informative=17, n_redundant=3, n_classes=5, n_clusters_per_class=2, flip_y=0.001, class_sep=1)X.shape, y.shape((50000, 20), (50000,))
The dataset contains 50000 samples and 20 features.
The next step is to split the dataset into train and test subsets.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
It is very important the evaluate the performance of a model on the samples it has not trained on. This is the most accurate way of detecting overfitting.
We have the train and test sets now. The next step is to create, train, and evaluate a classifier.
LightGBM is an implementation of gradient boosted decision trees. It is super fast and efficient. If you’d like to learn more about LightGBM, please read this post that I have written how LightGBM works and what makes it super fast.
I will be using the scikit-learn API of LightGBM. Let’s first import it and create the initial model.
from lightgbm import LGBMClassifierparams = {'boosting_type': 'gbdt','objective': 'multiclass','metric': 'multi_logloss','num_class':5,'max_depth':8,'num_leaves':200,'learning_rate': 0.05,'n_estimators':500}clf = LGBMClassifier(**params)
We have a classifier whose hyperparameters are described in the params dictionary. We will not change the first four parameters. Although different boosting types are available, we stick with the gradient boosted decision trees (gbdt). The objective and num_class parameters defined by the task so they cannot be changed. We have options for the metric but log loss is a commonly used one for classification tasks.
Max_depth: The maximum depth of an individual tree in the ensemble. Increasing the depth blatantly will result in overfitting.
Num_leaves: The number of leaves a tree can have. This is especially important for LightGBM because it adapts a leaf-wise growth strategy. Num_leaves and max_depth should be adjusted together.
Learning_rate: The rate at which weights are updated. As the learning rate increases, the model learns faster but it comes at a cost. There is a risk of missing the global minima. Very low learning rates may prevent a model from converging.
N_estimators: The number of trees used in the ensemble.
These are the basic parameters. We will adjust these after the initial evaluation and also introduce new parameters that will help us reduce overfitting.
Let’s first train the model and evalute its performance.
clf.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_test, y_test)],early_stopping_rounds=10)
The fit method will train the model with the train set and evaluate the performance on both train and test according to the given metric.
The early stopping parameter is used to control the training process. If there is no improvement on the loss in ten consecutive rounds, the model will stop training.
Here are the results of the last 2 iterations.
[499] training's multi_logloss: 0.0195056 valid_1's multi_logloss: 0.195734[500] training's multi_logloss: 0.0193433 valid_1's multi_logloss: 0.19556
The log loss is 0.019 on train set and 0.196 on test set which is definitely not acceptable. There is a significant overfitting issue that needs to be solved. Please note that the loss on the test set is not realistic and it will increase as the degree of overfitting reduces.
We will add new hyperparameters as well as adjusting the existing ones in order to reduce overfitting.
The first one is the min_data_in_leaf parameter.
Min_data_in_leaf: The least number of data points a leaf must have.
It puts a constraint on splitting the nodes in a tree so the model will not capture the details or noise in the train set.
'min_data_in_leaf':200 #added to the params dictionary
Here is the result after setting the min_data_in_leaf parameter as 100.
[500] training's multi_logloss: 0.099274 valid_1's multi_logloss: 0.239233
The loss on the test set increased but the difference between train and test loss decreased. The loss or accuracy of test set is not reliable when there is a huge difference between train and test set.
The next hyperparameters that can be used to reduce overfitting are colsample_bytree and subsample.
Colsample_bytree: LightGBM randomly selects part of features on each iteration (tree). The ratio is controlled by this parameter.
Subsample: Similar to colsample_bytree but for samples (i.e. rows)
#added to the params dictionary'colsample_bytree': 0.5'subsample': 0.5 'subsample_freq':1 #frequency for subsampling
Here is the new result.
[500] training's multi_logloss: 0.149361 valid_1's multi_logloss: 0.257776
We can also use regularization to reduce overfitting. LightGBM supports both L1 and L2 regularization.
#added to the params dictionary'reg_alpha': 5
Reg_alpha: L1 regularization hyperparameter.
Rep_lambda: L2 regularization hyperparameter.
Adding L1 regularization has further decreased overfitting.
[500] training's multi_logloss: 0.203253 valid_1's multi_logloss: 0.296209
The max_bin parameter helps preventing a model from overfitting as well.
Max_bin: The maximum number of bins that feature values will be bucketed in
Small number of bins may reduce training accuracy but may increase the generalization performance of a model.
#added to the params dictionary'max_bin': 10[500] training's multi_logloss: 0.259076 valid_1's multi_logloss: 0.326792
Finally, we can adjust the max_depth and num_leaves parameter to reduce overfitting.
The current parameter dictionary is as below:
params = {'boosting_type': 'gbdt','objective': 'multiclass','metric': 'multi_logloss','num_class':5,'max_depth':7,'num_leaves':50,'learning_rate': 0.05,'n_estimators':500,'min_data_in_leaf':200,'colsample_bytree': 0.5,'subsample': 0.5,'subsample_freq':1,'reg_alpha': 5,'max_bin': 10}
The performance of the model with these parameters:
[500] training's multi_logloss: 0.271047 valid_1's multi_logloss: 0.33548
We have reduced the overfitting by a significant amount but there is still room for improvement. Getting more data will definitely help in making the model more generalized so overfitting will be reduced. We can also keep trying different values of these hyperparameters or use other available ones.
I do not claim that these values are the optimal value for these hyperparameters. In fact, you might well get a better result by trying different combinations.
I wanted to show how these hyperparameters adjust a model and therefore its performance. Instead of trying random combinations, it is always better to have an idea who a particular hyperparameter can be used for.
LightGBM or other complex models such as xgboost have many more hyperparameters than the ones we have discussed. Here is the entire hyperparamer list of the LightGBM.
There are also tools and packages that help optimize hyperparameter tuning such as optuna. The GridSearchCV and RandomizedSearchCV functions of scikit-learn also help in finding the optimal hyperparameter values.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 411,
"s": 172,
"text": "There are various ready-to-use machine learning algorithms. They all have their pros and cons. For a given task, it is the job of the machine learning engineer or data scientist to select the optimal algorithm and make the most out of it."
},
{
"code": null,
"e": 575,
"s": 411,
"text": "A critical part of making the most out of a model is hyperparameter tuning. The performance of a model is greatly influenced by the selected hyperparameter values."
},
{
"code": null,
"e": 680,
"s": 575,
"text": "In this post, we will focus on how to tune hyperparameters to obtain a more robust and generalized mode."
},
{
"code": null,
"e": 819,
"s": 680,
"text": "In some sense, we design our own implementation of an algorithm by finding the optimal hyperparameter values for a given task and dataset."
},
{
"code": null,
"e": 987,
"s": 819,
"text": "As the model complexity increases, the number of hyperparameters also increase. Tree based ensemble learners such as xgboost and lightgbm have lots of hyperparameters."
},
{
"code": null,
"e": 1218,
"s": 987,
"text": "The hyperparameters need to be tuned very well in order to get accurate, and robust results. Our focus should not be getting the best accuracy or lowest lost. The ultimate goal is to have a robust, accurate, and not-overfit model."
},
{
"code": null,
"e": 1367,
"s": 1218,
"text": "The tuning process cannot be just trying random combinations of hyperparameters. We need to understand what they mean and how they change the model."
},
{
"code": null,
"e": 1406,
"s": 1367,
"text": "The outline of the post is as follows:"
},
{
"code": null,
"e": 1438,
"s": 1406,
"text": "Create a classification dataset"
},
{
"code": null,
"e": 1458,
"s": 1438,
"text": "LightGBM classifier"
},
{
"code": null,
"e": 1500,
"s": 1458,
"text": "Tune hyperparameters to improve the model"
},
{
"code": null,
"e": 1816,
"s": 1500,
"text": "The make_classification function of scikit-learn allows creating customized classification datasets. You can customize the dataset by choosing the number of samples, informative and redundant features. It is also possible to adjust the difficulty of classification task by using the class_sep and flip_y parameters."
},
{
"code": null,
"e": 2109,
"s": 1816,
"text": "import numpy as npimport pandas as pdfrom sklearn.datasets import make_classificationX, y = make_classification( n_samples=50000, n_features=20, n_informative=17, n_redundant=3, n_classes=5, n_clusters_per_class=2, flip_y=0.001, class_sep=1)X.shape, y.shape((50000, 20), (50000,))"
},
{
"code": null,
"e": 2161,
"s": 2109,
"text": "The dataset contains 50000 samples and 20 features."
},
{
"code": null,
"e": 2228,
"s": 2161,
"text": "The next step is to split the dataset into train and test subsets."
},
{
"code": null,
"e": 2370,
"s": 2228,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)"
},
{
"code": null,
"e": 2525,
"s": 2370,
"text": "It is very important the evaluate the performance of a model on the samples it has not trained on. This is the most accurate way of detecting overfitting."
},
{
"code": null,
"e": 2624,
"s": 2525,
"text": "We have the train and test sets now. The next step is to create, train, and evaluate a classifier."
},
{
"code": null,
"e": 2857,
"s": 2624,
"text": "LightGBM is an implementation of gradient boosted decision trees. It is super fast and efficient. If you’d like to learn more about LightGBM, please read this post that I have written how LightGBM works and what makes it super fast."
},
{
"code": null,
"e": 2959,
"s": 2857,
"text": "I will be using the scikit-learn API of LightGBM. Let’s first import it and create the initial model."
},
{
"code": null,
"e": 3197,
"s": 2959,
"text": "from lightgbm import LGBMClassifierparams = {'boosting_type': 'gbdt','objective': 'multiclass','metric': 'multi_logloss','num_class':5,'max_depth':8,'num_leaves':200,'learning_rate': 0.05,'n_estimators':500}clf = LGBMClassifier(**params)"
},
{
"code": null,
"e": 3612,
"s": 3197,
"text": "We have a classifier whose hyperparameters are described in the params dictionary. We will not change the first four parameters. Although different boosting types are available, we stick with the gradient boosted decision trees (gbdt). The objective and num_class parameters defined by the task so they cannot be changed. We have options for the metric but log loss is a commonly used one for classification tasks."
},
{
"code": null,
"e": 3739,
"s": 3612,
"text": "Max_depth: The maximum depth of an individual tree in the ensemble. Increasing the depth blatantly will result in overfitting."
},
{
"code": null,
"e": 3932,
"s": 3739,
"text": "Num_leaves: The number of leaves a tree can have. This is especially important for LightGBM because it adapts a leaf-wise growth strategy. Num_leaves and max_depth should be adjusted together."
},
{
"code": null,
"e": 4173,
"s": 3932,
"text": "Learning_rate: The rate at which weights are updated. As the learning rate increases, the model learns faster but it comes at a cost. There is a risk of missing the global minima. Very low learning rates may prevent a model from converging."
},
{
"code": null,
"e": 4229,
"s": 4173,
"text": "N_estimators: The number of trees used in the ensemble."
},
{
"code": null,
"e": 4383,
"s": 4229,
"text": "These are the basic parameters. We will adjust these after the initial evaluation and also introduce new parameters that will help us reduce overfitting."
},
{
"code": null,
"e": 4440,
"s": 4383,
"text": "Let’s first train the model and evalute its performance."
},
{
"code": null,
"e": 4540,
"s": 4440,
"text": "clf.fit(X_train, y_train, eval_set=[(X_train, y_train), (X_test, y_test)],early_stopping_rounds=10)"
},
{
"code": null,
"e": 4678,
"s": 4540,
"text": "The fit method will train the model with the train set and evaluate the performance on both train and test according to the given metric."
},
{
"code": null,
"e": 4844,
"s": 4678,
"text": "The early stopping parameter is used to control the training process. If there is no improvement on the loss in ten consecutive rounds, the model will stop training."
},
{
"code": null,
"e": 4891,
"s": 4844,
"text": "Here are the results of the last 2 iterations."
},
{
"code": null,
"e": 5057,
"s": 4891,
"text": "[499]\ttraining's multi_logloss: 0.0195056\t valid_1's multi_logloss: 0.195734[500]\ttraining's multi_logloss: 0.0193433\t valid_1's multi_logloss: 0.19556"
},
{
"code": null,
"e": 5334,
"s": 5057,
"text": "The log loss is 0.019 on train set and 0.196 on test set which is definitely not acceptable. There is a significant overfitting issue that needs to be solved. Please note that the loss on the test set is not realistic and it will increase as the degree of overfitting reduces."
},
{
"code": null,
"e": 5437,
"s": 5334,
"text": "We will add new hyperparameters as well as adjusting the existing ones in order to reduce overfitting."
},
{
"code": null,
"e": 5486,
"s": 5437,
"text": "The first one is the min_data_in_leaf parameter."
},
{
"code": null,
"e": 5554,
"s": 5486,
"text": "Min_data_in_leaf: The least number of data points a leaf must have."
},
{
"code": null,
"e": 5677,
"s": 5554,
"text": "It puts a constraint on splitting the nodes in a tree so the model will not capture the details or noise in the train set."
},
{
"code": null,
"e": 5732,
"s": 5677,
"text": "'min_data_in_leaf':200 #added to the params dictionary"
},
{
"code": null,
"e": 5804,
"s": 5732,
"text": "Here is the result after setting the min_data_in_leaf parameter as 100."
},
{
"code": null,
"e": 5888,
"s": 5804,
"text": "[500]\ttraining's multi_logloss: 0.099274\t valid_1's multi_logloss: 0.239233"
},
{
"code": null,
"e": 6090,
"s": 5888,
"text": "The loss on the test set increased but the difference between train and test loss decreased. The loss or accuracy of test set is not reliable when there is a huge difference between train and test set."
},
{
"code": null,
"e": 6190,
"s": 6090,
"text": "The next hyperparameters that can be used to reduce overfitting are colsample_bytree and subsample."
},
{
"code": null,
"e": 6320,
"s": 6190,
"text": "Colsample_bytree: LightGBM randomly selects part of features on each iteration (tree). The ratio is controlled by this parameter."
},
{
"code": null,
"e": 6387,
"s": 6320,
"text": "Subsample: Similar to colsample_bytree but for samples (i.e. rows)"
},
{
"code": null,
"e": 6504,
"s": 6387,
"text": "#added to the params dictionary'colsample_bytree': 0.5'subsample': 0.5 'subsample_freq':1 #frequency for subsampling"
},
{
"code": null,
"e": 6528,
"s": 6504,
"text": "Here is the new result."
},
{
"code": null,
"e": 6611,
"s": 6528,
"text": "[500]\ttraining's multi_logloss: 0.149361 valid_1's multi_logloss: 0.257776"
},
{
"code": null,
"e": 6714,
"s": 6611,
"text": "We can also use regularization to reduce overfitting. LightGBM supports both L1 and L2 regularization."
},
{
"code": null,
"e": 6760,
"s": 6714,
"text": "#added to the params dictionary'reg_alpha': 5"
},
{
"code": null,
"e": 6805,
"s": 6760,
"text": "Reg_alpha: L1 regularization hyperparameter."
},
{
"code": null,
"e": 6851,
"s": 6805,
"text": "Rep_lambda: L2 regularization hyperparameter."
},
{
"code": null,
"e": 6911,
"s": 6851,
"text": "Adding L1 regularization has further decreased overfitting."
},
{
"code": null,
"e": 6994,
"s": 6911,
"text": "[500]\ttraining's multi_logloss: 0.203253 valid_1's multi_logloss: 0.296209"
},
{
"code": null,
"e": 7067,
"s": 6994,
"text": "The max_bin parameter helps preventing a model from overfitting as well."
},
{
"code": null,
"e": 7143,
"s": 7067,
"text": "Max_bin: The maximum number of bins that feature values will be bucketed in"
},
{
"code": null,
"e": 7253,
"s": 7143,
"text": "Small number of bins may reduce training accuracy but may increase the generalization performance of a model."
},
{
"code": null,
"e": 7380,
"s": 7253,
"text": "#added to the params dictionary'max_bin': 10[500]\ttraining's multi_logloss: 0.259076\t valid_1's multi_logloss: 0.326792"
},
{
"code": null,
"e": 7465,
"s": 7380,
"text": "Finally, we can adjust the max_depth and num_leaves parameter to reduce overfitting."
},
{
"code": null,
"e": 7511,
"s": 7465,
"text": "The current parameter dictionary is as below:"
},
{
"code": null,
"e": 7795,
"s": 7511,
"text": "params = {'boosting_type': 'gbdt','objective': 'multiclass','metric': 'multi_logloss','num_class':5,'max_depth':7,'num_leaves':50,'learning_rate': 0.05,'n_estimators':500,'min_data_in_leaf':200,'colsample_bytree': 0.5,'subsample': 0.5,'subsample_freq':1,'reg_alpha': 5,'max_bin': 10}"
},
{
"code": null,
"e": 7847,
"s": 7795,
"text": "The performance of the model with these parameters:"
},
{
"code": null,
"e": 7929,
"s": 7847,
"text": "[500]\ttraining's multi_logloss: 0.271047\t valid_1's multi_logloss: 0.33548"
},
{
"code": null,
"e": 8229,
"s": 7929,
"text": "We have reduced the overfitting by a significant amount but there is still room for improvement. Getting more data will definitely help in making the model more generalized so overfitting will be reduced. We can also keep trying different values of these hyperparameters or use other available ones."
},
{
"code": null,
"e": 8389,
"s": 8229,
"text": "I do not claim that these values are the optimal value for these hyperparameters. In fact, you might well get a better result by trying different combinations."
},
{
"code": null,
"e": 8602,
"s": 8389,
"text": "I wanted to show how these hyperparameters adjust a model and therefore its performance. Instead of trying random combinations, it is always better to have an idea who a particular hyperparameter can be used for."
},
{
"code": null,
"e": 8769,
"s": 8602,
"text": "LightGBM or other complex models such as xgboost have many more hyperparameters than the ones we have discussed. Here is the entire hyperparamer list of the LightGBM."
},
{
"code": null,
"e": 8982,
"s": 8769,
"text": "There are also tools and packages that help optimize hyperparameter tuning such as optuna. The GridSearchCV and RandomizedSearchCV functions of scikit-learn also help in finding the optimal hyperparameter values."
}
] |
C++ Relational Operators | Try the following example to understand all the relational operators available in C++.
Copy and paste the following C++ program in test.cpp file and compile and run this program.
#include <iostream>
using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
cout << "Line 1 - a is equal to b" << endl ;
} else {
cout << "Line 1 - a is not equal to b" << endl ;
}
if( a < b ) {
cout << "Line 2 - a is less than b" << endl ;
} else {
cout << "Line 2 - a is not less than b" << endl ;
}
if( a > b ) {
cout << "Line 3 - a is greater than b" << endl ;
} else {
cout << "Line 3 - a is not greater than b" << endl ;
}
/* Let's change the values of a and b */
a = 5;
b = 20;
if( a <= b ) {
cout << "Line 4 - a is either less than \ or equal to b" << endl ;
}
if( b >= a ) {
cout << "Line 5 - b is either greater than \ or equal to b" << endl ;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or euqal to b
Line 5 - b is either greater than or equal to b
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2405,
"s": 2318,
"text": "Try the following example to understand all the relational operators available in C++."
},
{
"code": null,
"e": 2497,
"s": 2405,
"text": "Copy and paste the following C++ program in test.cpp file and compile and run this program."
},
{
"code": null,
"e": 3317,
"s": 2497,
"text": "#include <iostream>\nusing namespace std;\n\nmain() {\n int a = 21;\n int b = 10;\n int c ;\n\n if( a == b ) {\n cout << \"Line 1 - a is equal to b\" << endl ;\n } else {\n cout << \"Line 1 - a is not equal to b\" << endl ;\n }\n \n if( a < b ) {\n cout << \"Line 2 - a is less than b\" << endl ;\n } else {\n cout << \"Line 2 - a is not less than b\" << endl ;\n }\n \n if( a > b ) {\n cout << \"Line 3 - a is greater than b\" << endl ;\n } else {\n cout << \"Line 3 - a is not greater than b\" << endl ;\n }\n \n /* Let's change the values of a and b */\n a = 5;\n b = 20;\n if( a <= b ) {\n cout << \"Line 4 - a is either less than \\ or equal to b\" << endl ;\n }\n \n if( b >= a ) {\n cout << \"Line 5 - b is either greater than \\ or equal to b\" << endl ;\n }\n \n return 0;\n}"
},
{
"code": null,
"e": 3398,
"s": 3317,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3581,
"s": 3398,
"text": "Line 1 - a is not equal to b\nLine 2 - a is not less than b\nLine 3 - a is greater than b\nLine 4 - a is either less than or euqal to b\nLine 5 - b is either greater than or equal to b\n"
},
{
"code": null,
"e": 3618,
"s": 3581,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 3637,
"s": 3618,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3669,
"s": 3637,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 3692,
"s": 3669,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 3728,
"s": 3692,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 3745,
"s": 3728,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3780,
"s": 3745,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3797,
"s": 3780,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3832,
"s": 3797,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3849,
"s": 3832,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3884,
"s": 3849,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3901,
"s": 3884,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3908,
"s": 3901,
"text": " Print"
},
{
"code": null,
"e": 3919,
"s": 3908,
"text": " Add Notes"
}
] |
Apply style to the parent if it has a child with CSS and HTML | Parent selectors are not present in CSS3. There is a proposed CSS4 selector, $, to do so, which could look like this (Selecting the li element) −
ul $li ul.sub { ... }
As an alternative, with jQuery, a one-liner you could make use of would be this. The: has() selector selects all elements that have one or more elements inside of them, that matches the specified selector. The <li> tag defines a list item. The <ul> tag defines an unordered (bulleted) list.
$('ul li:has(ul.sub)').addClass('has_sub');
You could then style the li.has_sub in your CSS. | [
{
"code": null,
"e": 1208,
"s": 1062,
"text": "Parent selectors are not present in CSS3. There is a proposed CSS4 selector, $, to do so, which could look like this (Selecting the li element) −"
},
{
"code": null,
"e": 1230,
"s": 1208,
"text": "ul $li ul.sub { ... }"
},
{
"code": null,
"e": 1521,
"s": 1230,
"text": "As an alternative, with jQuery, a one-liner you could make use of would be this. The: has() selector selects all elements that have one or more elements inside of them, that matches the specified selector. The <li> tag defines a list item. The <ul> tag defines an unordered (bulleted) list."
},
{
"code": null,
"e": 1565,
"s": 1521,
"text": "$('ul li:has(ul.sub)').addClass('has_sub');"
},
{
"code": null,
"e": 1614,
"s": 1565,
"text": "You could then style the li.has_sub in your CSS."
}
] |
Program for Mean and median of an unsorted array - GeeksforGeeks | 23 Aug, 2021
Given n size unsorted array, find it’s mean and median.
Mean of an array = (sum of all elements) / (number of elements)
Median of a sorted array of size n is defined as the middle element when n is odd and average of middle two elements when n is even.Since the array is not sorted here, we sort the array first, then apply above formula.
Examples:
Input : a[] = {1, 3, 4, 2, 6, 5, 8, 7}
Output : Mean = 4.5
Median = 4.5
Sum of the elements is 1 + 3 + 4 + 2 + 6 +
5 + 8 + 7 = 36
Mean = 36/8 = 4.5
Since number of elements are even, median
is average of 4th and 5th largest elements.
which means (4 + 5)/2 = 4.5
Input : a[] = {4, 4, 4, 4, 4}
Output : Mean = 4
Median = 4
Below is the code implementation:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find mean and median of// an array#include <bits/stdc++.h>using namespace std; // Function for calculating meandouble findMean(int a[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; return (double)sum / (double)n;} // Function for calculating mediandouble findMedian(int a[], int n){ // First we sort the array sort(a, a + n); // check for even case if (n % 2 != 0) return (double)a[n / 2]; return (double)(a[(n - 1) / 2] + a[n / 2]) / 2.0;} // Driver codeint main(){ int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 }; int n = sizeof(a) / sizeof(a[0]); // Function call cout << "Mean = " << findMean(a, n) << endl; cout << "Median = " << findMedian(a, n) << endl; return 0;}
// Java program to find mean// and median of an arrayimport java.util.*; class GFG{ // Function for calculating mean public static double findMean(int a[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; return (double)sum / (double)n; } // Function for calculating median public static double findMedian(int a[], int n) { // First we sort the array Arrays.sort(a); // check for even case if (n % 2 != 0) return (double)a[n / 2]; return (double)(a[(n - 1) / 2] + a[n / 2]) / 2.0; } // Driver code public static void main(String args[]) { int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 }; int n = a.length; // Function call System.out.println("Mean = " + findMean(a, n)); System.out.println("Median = " + findMedian(a, n)); }} // This article is contributed by Anshika Goyal.
# Python3 program to find mean# and median of an array # Function for calculating mean def findMean(a, n): sum = 0 for i in range(0, n): sum += a[i] return float(sum/n) # Function for calculating median def findMedian(a, n): # First we sort the array sorted(a) # check for even case if n % 2 != 0: return float(a[int(n/2)]) return float((a[int((n-1)/2)] + a[int(n/2)])/2.0) # Driver codea = [1, 3, 4, 2, 7, 5, 8, 6]n = len(a) # Function callprint("Mean =", findMean(a, n))print("Median =", findMedian(a, n)) # This code is contributed by Smitha Dinesh Semwal
// C# program to find mean// and median of an arrayusing System; class GFG{ // Function for // calculating mean public static double findMean(int[] a, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; return (double)sum / (double)n; } // Function for // calculating median public static double findMedian(int[] a, int n) { // First we sort // the array Array.Sort(a); // check for // even case if (n % 2 != 0) return (double)a[n / 2]; return (double)(a[(n - 1) / 2] + a[n / 2]) / 2.0; } // Driver Code public static void Main() { int[] a = { 1, 3, 4, 2, 7, 5, 8, 6 }; int n = a.Length; // Function call Console.Write("Mean = " + findMean(a, n) + "\n"); Console.Write("Median = " + findMedian(a, n) + "\n"); }} // This code is contributed by Smitha .
<?php// PHP program to find mean// and median of an array // Function for calculating meanfunction findMean(&$a, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $a[$i]; return (double)$sum / (double)$n;} // Function for// calculating medianfunction findMedian(&$a, $n){ // First we sort the array sort($a); // check for even case if ($n % 2 != 0) return (double)$a[$n / 2]; return (double)($a[($n - 1) / 2] + $a[$n / 2]) / 2.0;} // Driver Code$a = array(1, 3, 4, 2, 7, 5, 8, 6);$n = sizeof($a); // Function callecho "Mean = " . findMean($a, $n)."\n";echo "Median = " . findMedian($a, $n); // This code is contributed// by ChitraNayal?>
<script> // Javascript program to find mean// and median of an array // Function for// calculating meanfunction findMean(a,n){ let sum = 0; for (let i = 0; i < n; i++) sum += a[i]; return sum / n;} // Function for// calculating medianfunction findMedian(a,n){ // First we sort // the array a.sort(); // check for // even case if (n % 2 != 0) return a[n / 2]; return (a[Math.floor((n-1)/2)] + a[n / 2]) / 2;} // Driver Code let a = [1, 3, 4, 2, 7, 5, 8, 6]let n = a.length; // Function calldocument.write("Mean = " + findMean(a, n) + "<br>");document.write("Median = " + findMedian(a, n)); </script>
Mean = 4.5
Median = 4.5
Time Complexity to find mean = O(n) Time Complexity to find median = O(n Log n) as we need to sort the array first. Note that we can find median in O(n) time using methods discussed here and here.
This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Smitha Dinesh Semwal
ukasp
semank
mohit kumar 29
sweetyty
maths-mean
median-finding
Order-Statistics
statistical-algorithms
Arrays
School Programming
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Python Dictionary
Inheritance in C++
Reverse a string in Java
Interfaces in Java
C++ Classes and Objects | [
{
"code": null,
"e": 24865,
"s": 24837,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 24922,
"s": 24865,
"text": "Given n size unsorted array, find it’s mean and median. "
},
{
"code": null,
"e": 24986,
"s": 24922,
"text": "Mean of an array = (sum of all elements) / (number of elements)"
},
{
"code": null,
"e": 25205,
"s": 24986,
"text": "Median of a sorted array of size n is defined as the middle element when n is odd and average of middle two elements when n is even.Since the array is not sorted here, we sort the array first, then apply above formula."
},
{
"code": null,
"e": 25216,
"s": 25205,
"text": "Examples: "
},
{
"code": null,
"e": 25560,
"s": 25216,
"text": "Input : a[] = {1, 3, 4, 2, 6, 5, 8, 7}\nOutput : Mean = 4.5\n Median = 4.5\nSum of the elements is 1 + 3 + 4 + 2 + 6 + \n5 + 8 + 7 = 36\nMean = 36/8 = 4.5\nSince number of elements are even, median\nis average of 4th and 5th largest elements.\nwhich means (4 + 5)/2 = 4.5\n\nInput : a[] = {4, 4, 4, 4, 4}\nOutput : Mean = 4\n Median = 4 "
},
{
"code": null,
"e": 25595,
"s": 25560,
"text": "Below is the code implementation: "
},
{
"code": null,
"e": 25599,
"s": 25595,
"text": "C++"
},
{
"code": null,
"e": 25604,
"s": 25599,
"text": "Java"
},
{
"code": null,
"e": 25612,
"s": 25604,
"text": "Python3"
},
{
"code": null,
"e": 25615,
"s": 25612,
"text": "C#"
},
{
"code": null,
"e": 25619,
"s": 25615,
"text": "PHP"
},
{
"code": null,
"e": 25630,
"s": 25619,
"text": "Javascript"
},
{
"code": "// CPP program to find mean and median of// an array#include <bits/stdc++.h>using namespace std; // Function for calculating meandouble findMean(int a[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; return (double)sum / (double)n;} // Function for calculating mediandouble findMedian(int a[], int n){ // First we sort the array sort(a, a + n); // check for even case if (n % 2 != 0) return (double)a[n / 2]; return (double)(a[(n - 1) / 2] + a[n / 2]) / 2.0;} // Driver codeint main(){ int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 }; int n = sizeof(a) / sizeof(a[0]); // Function call cout << \"Mean = \" << findMean(a, n) << endl; cout << \"Median = \" << findMedian(a, n) << endl; return 0;}",
"e": 26388,
"s": 25630,
"text": null
},
{
"code": "// Java program to find mean// and median of an arrayimport java.util.*; class GFG{ // Function for calculating mean public static double findMean(int a[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; return (double)sum / (double)n; } // Function for calculating median public static double findMedian(int a[], int n) { // First we sort the array Arrays.sort(a); // check for even case if (n % 2 != 0) return (double)a[n / 2]; return (double)(a[(n - 1) / 2] + a[n / 2]) / 2.0; } // Driver code public static void main(String args[]) { int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 }; int n = a.length; // Function call System.out.println(\"Mean = \" + findMean(a, n)); System.out.println(\"Median = \" + findMedian(a, n)); }} // This article is contributed by Anshika Goyal.",
"e": 27327,
"s": 26388,
"text": null
},
{
"code": "# Python3 program to find mean# and median of an array # Function for calculating mean def findMean(a, n): sum = 0 for i in range(0, n): sum += a[i] return float(sum/n) # Function for calculating median def findMedian(a, n): # First we sort the array sorted(a) # check for even case if n % 2 != 0: return float(a[int(n/2)]) return float((a[int((n-1)/2)] + a[int(n/2)])/2.0) # Driver codea = [1, 3, 4, 2, 7, 5, 8, 6]n = len(a) # Function callprint(\"Mean =\", findMean(a, n))print(\"Median =\", findMedian(a, n)) # This code is contributed by Smitha Dinesh Semwal",
"e": 27949,
"s": 27327,
"text": null
},
{
"code": "// C# program to find mean// and median of an arrayusing System; class GFG{ // Function for // calculating mean public static double findMean(int[] a, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; return (double)sum / (double)n; } // Function for // calculating median public static double findMedian(int[] a, int n) { // First we sort // the array Array.Sort(a); // check for // even case if (n % 2 != 0) return (double)a[n / 2]; return (double)(a[(n - 1) / 2] + a[n / 2]) / 2.0; } // Driver Code public static void Main() { int[] a = { 1, 3, 4, 2, 7, 5, 8, 6 }; int n = a.Length; // Function call Console.Write(\"Mean = \" + findMean(a, n) + \"\\n\"); Console.Write(\"Median = \" + findMedian(a, n) + \"\\n\"); }} // This code is contributed by Smitha .",
"e": 28914,
"s": 27949,
"text": null
},
{
"code": "<?php// PHP program to find mean// and median of an array // Function for calculating meanfunction findMean(&$a, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $a[$i]; return (double)$sum / (double)$n;} // Function for// calculating medianfunction findMedian(&$a, $n){ // First we sort the array sort($a); // check for even case if ($n % 2 != 0) return (double)$a[$n / 2]; return (double)($a[($n - 1) / 2] + $a[$n / 2]) / 2.0;} // Driver Code$a = array(1, 3, 4, 2, 7, 5, 8, 6);$n = sizeof($a); // Function callecho \"Mean = \" . findMean($a, $n).\"\\n\";echo \"Median = \" . findMedian($a, $n); // This code is contributed// by ChitraNayal?>",
"e": 29647,
"s": 28914,
"text": null
},
{
"code": "<script> // Javascript program to find mean// and median of an array // Function for// calculating meanfunction findMean(a,n){ let sum = 0; for (let i = 0; i < n; i++) sum += a[i]; return sum / n;} // Function for// calculating medianfunction findMedian(a,n){ // First we sort // the array a.sort(); // check for // even case if (n % 2 != 0) return a[n / 2]; return (a[Math.floor((n-1)/2)] + a[n / 2]) / 2;} // Driver Code let a = [1, 3, 4, 2, 7, 5, 8, 6]let n = a.length; // Function calldocument.write(\"Mean = \" + findMean(a, n) + \"<br>\");document.write(\"Median = \" + findMedian(a, n)); </script>",
"e": 30305,
"s": 29647,
"text": null
},
{
"code": null,
"e": 30329,
"s": 30305,
"text": "Mean = 4.5\nMedian = 4.5"
},
{
"code": null,
"e": 30526,
"s": 30329,
"text": "Time Complexity to find mean = O(n) Time Complexity to find median = O(n Log n) as we need to sort the array first. Note that we can find median in O(n) time using methods discussed here and here."
},
{
"code": null,
"e": 30949,
"s": 30526,
"text": "This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30970,
"s": 30949,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 30976,
"s": 30970,
"text": "ukasp"
},
{
"code": null,
"e": 30983,
"s": 30976,
"text": "semank"
},
{
"code": null,
"e": 30998,
"s": 30983,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 31007,
"s": 30998,
"text": "sweetyty"
},
{
"code": null,
"e": 31018,
"s": 31007,
"text": "maths-mean"
},
{
"code": null,
"e": 31033,
"s": 31018,
"text": "median-finding"
},
{
"code": null,
"e": 31050,
"s": 31033,
"text": "Order-Statistics"
},
{
"code": null,
"e": 31073,
"s": 31050,
"text": "statistical-algorithms"
},
{
"code": null,
"e": 31080,
"s": 31073,
"text": "Arrays"
},
{
"code": null,
"e": 31099,
"s": 31080,
"text": "School Programming"
},
{
"code": null,
"e": 31106,
"s": 31099,
"text": "Arrays"
},
{
"code": null,
"e": 31204,
"s": 31106,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31213,
"s": 31204,
"text": "Comments"
},
{
"code": null,
"e": 31226,
"s": 31213,
"text": "Old Comments"
},
{
"code": null,
"e": 31270,
"s": 31226,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 31293,
"s": 31270,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 31325,
"s": 31293,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31339,
"s": 31325,
"text": "Linear Search"
},
{
"code": null,
"e": 31407,
"s": 31339,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 31425,
"s": 31407,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31444,
"s": 31425,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 31469,
"s": 31444,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 31488,
"s": 31469,
"text": "Interfaces in Java"
}
] |
Setting the position of TKinter labels | 12 Jan, 2021
Tkinter is the standard GUI library for Python. Tkinter in Python comes with a lot of good widgets. Widgets are standard GUI elements, and the Label will also come under these WidgetsNote: For more information, refer to Python GUI – tkinter
Tkinter Label is a widget that is used to implement display boxes where you can place text or images. The text displayed by this widget can be changed by the developer at any time you want. It is also used to perform tasks such as to underline the part of the text and span the text across multiple lines.
Example:
We can use place() method to set the position of the Tkinter labels.
Example 1: Placing label at the middle of the window
Python3
import tkinter as tk # Creating the root windowroot = tk.Tk() # creating the Label with# the text MiddleLabel_middle = tk.Label(root, text ='Middle') # Placing the Label at# the middle of the root window# relx and rely should be properly# set to position the label on# root windowLabel_middle.place(relx = 0.5, rely = 0.5, anchor = 'center')# Execute Tkinterroot.mainloop()
Output:
Example 2: Placing label at the lower left side of window
Python3
# Import Moduleimport tkinter as tk # Create Objectroot = tk.Tk() # Create Label and add some textLower_left = tk.Label(root,text ='Lower_left') # using place method we can set the position of labelLower_left.place(relx = 0.0, rely = 1.0, anchor ='sw') # Execute Tkinterroot.mainloop()
Output
Example 3: Placing label at the upper right side of window
Python3
# Import Moduleimport tkinter as tk # Create Objectroot = tk.Tk() # Create Label and add some textUpper_right = tk.Label(root,text ='Upper_right') # using place method we can set the position of labelUpper_right.place(relx = 1.0, rely = 0.0, anchor ='ne') # Execute Tkinterroot.mainloop()
Output
abhigoya
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jan, 2021"
},
{
"code": null,
"e": 270,
"s": 28,
"text": "Tkinter is the standard GUI library for Python. Tkinter in Python comes with a lot of good widgets. Widgets are standard GUI elements, and the Label will also come under these WidgetsNote: For more information, refer to Python GUI – tkinter "
},
{
"code": null,
"e": 576,
"s": 270,
"text": "Tkinter Label is a widget that is used to implement display boxes where you can place text or images. The text displayed by this widget can be changed by the developer at any time you want. It is also used to perform tasks such as to underline the part of the text and span the text across multiple lines."
},
{
"code": null,
"e": 587,
"s": 576,
"text": "Example: "
},
{
"code": null,
"e": 659,
"s": 589,
"text": "We can use place() method to set the position of the Tkinter labels. "
},
{
"code": null,
"e": 714,
"s": 659,
"text": "Example 1: Placing label at the middle of the window "
},
{
"code": null,
"e": 722,
"s": 714,
"text": "Python3"
},
{
"code": "import tkinter as tk # Creating the root windowroot = tk.Tk() # creating the Label with# the text MiddleLabel_middle = tk.Label(root, text ='Middle') # Placing the Label at# the middle of the root window# relx and rely should be properly# set to position the label on# root windowLabel_middle.place(relx = 0.5, rely = 0.5, anchor = 'center')# Execute Tkinterroot.mainloop()",
"e": 1156,
"s": 722,
"text": null
},
{
"code": null,
"e": 1165,
"s": 1156,
"text": "Output: "
},
{
"code": null,
"e": 1225,
"s": 1165,
"text": "Example 2: Placing label at the lower left side of window "
},
{
"code": null,
"e": 1233,
"s": 1225,
"text": "Python3"
},
{
"code": "# Import Moduleimport tkinter as tk # Create Objectroot = tk.Tk() # Create Label and add some textLower_left = tk.Label(root,text ='Lower_left') # using place method we can set the position of labelLower_left.place(relx = 0.0, rely = 1.0, anchor ='sw') # Execute Tkinterroot.mainloop()",
"e": 1551,
"s": 1233,
"text": null
},
{
"code": null,
"e": 1559,
"s": 1551,
"text": "Output "
},
{
"code": null,
"e": 1619,
"s": 1559,
"text": "Example 3: Placing label at the upper right side of window "
},
{
"code": null,
"e": 1627,
"s": 1619,
"text": "Python3"
},
{
"code": "# Import Moduleimport tkinter as tk # Create Objectroot = tk.Tk() # Create Label and add some textUpper_right = tk.Label(root,text ='Upper_right') # using place method we can set the position of labelUpper_right.place(relx = 1.0, rely = 0.0, anchor ='ne') # Execute Tkinterroot.mainloop()",
"e": 1950,
"s": 1627,
"text": null
},
{
"code": null,
"e": 1958,
"s": 1950,
"text": "Output "
},
{
"code": null,
"e": 1969,
"s": 1960,
"text": "abhigoya"
},
{
"code": null,
"e": 1984,
"s": 1969,
"text": "Python-tkinter"
},
{
"code": null,
"e": 1991,
"s": 1984,
"text": "Python"
},
{
"code": null,
"e": 2089,
"s": 1991,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2121,
"s": 2089,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2150,
"s": 2121,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2177,
"s": 2150,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2213,
"s": 2177,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2234,
"s": 2213,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2265,
"s": 2234,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2288,
"s": 2265,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2344,
"s": 2288,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2381,
"s": 2344,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Basis Path Testing | Basis path testing, a structured testing or white box testing technique used for designing test cases intended to examine all possible paths of execution at least once. Creating and executing tests for all possible paths results in 100% statement coverage and 100% branch coverage.
Function fn_delete_element (int value, int array_size, int array[])
{
1 int i;
location = array_size + 1;
2 for i = 1 to array_size
3 if ( array[i] == value )
4 location = i;
end if;
end for;
5 for i = location to array_size
6 array[i] = array[i+1];
end for;
7 array_size --;
}
Step 1 : Draw the Flow Graph of the Function/Program under consideration as shown below:
Step 2 : Determine the independent paths.
Path 1: 1 - 2 - 5 - 7
Path 2: 1 - 2 - 5 - 6 - 7
Path 3: 1 - 2 - 3 - 2 - 5 - 6 - 7
Path 4: 1 - 2 - 3 - 4 - 2 - 5 - 6 - 7 | [
{
"code": null,
"e": 6161,
"s": 5879,
"text": "Basis path testing, a structured testing or white box testing technique used for designing test cases intended to examine all possible paths of execution at least once. Creating and executing tests for all possible paths results in 100% statement coverage and 100% branch coverage."
},
{
"code": null,
"e": 6456,
"s": 6161,
"text": "Function fn_delete_element (int value, int array_size, int array[])\n{\n\t1 int i;\n\tlocation = array_size + 1; \n\n\t2 for i = 1 to array_size\n\t3 if ( array[i] == value )\n\t4 location = i;\n\t end if;\n\t end for;\n\n\t5 for i = location to array_size\n\t6 array[i] = array[i+1];\n\tend for;\n\t7 array_size --;\n} "
},
{
"code": null,
"e": 6545,
"s": 6456,
"text": "Step 1 : Draw the Flow Graph of the Function/Program under consideration as shown below:"
},
{
"code": null,
"e": 6587,
"s": 6545,
"text": "Step 2 : Determine the independent paths."
}
] |
Find the only repetitive element between 1 to n-1 | 27 Jun, 2022
We are given an array arr[] of size n. Numbers are from 1 to (n-1) in random order. The array has only one repetitive element. We need to find the repetitive element.
Examples:
Input : a[] = {1, 3, 2, 3, 4}
Output : 3
Input : a[] = {1, 5, 1, 2, 3, 4}
Output : 1
Method 1 (Simple) We use two nested loops. The outer loop traverses through all elements and the inner loop check if the element picked by the outer loop appears anywhere else.Below is the implementation of the above approach:
C++
Python3
C#
// CPP program to find the only repeating// element in an array where elements are// from 1 to n-1.#include <bits/stdc++.h>using namespace std; int findRepeating(int arr[], int n){ for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) return arr[i]; } }} // Driver codeint main(){ int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findRepeating(arr, n); return 0;}// This code is added by Arpit Jain
# Python3 program to find the only# repeating element in an array where# elements are from 1 to n-1.def findRepeating(arr, n): for i in range(n): for j in range(i + 1, n): if (arr[i] == arr[j]): return arr[i]; # Driver Codearr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]n = len(arr)print(findRepeating(arr, n)) # This code is contributed by Arpit Jain
// C# program to find the only repeating// element in an array where elements are// from 1 to n-1.using System; public class GFG { static int findRepeating(int[] arr) { for (int i = 0; i < arr.Length; i++) { for (int j = i + 1; j < arr.Length; j++) { if (arr[i] == arr[j]) return arr[i]; } } return -1; } // Driver code static public void Main() { // Code int[] arr = new int[] { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int repeatingNum = findRepeating(arr); Console.WriteLine(repeatingNum); }} // This code is contributed by Mohd Nizam
8
Time Complexity: O(n2)Auxiliary Space: O(1)
Method 2 (Using Sorting),
first sort the array and just compare the array element with its index
if arr[i] != i+1, it means that arr[i] is repetitive. So Just return arr[I]
So Just return arr[I]
Otherwise, array does not contain duplicates from 1 to n-1In this case return -1
In this case return -1
C++
// CPP program to find the only repeating// element in an array where elements are// from 1 to n-1.#include <bits/stdc++.h>using namespace std; int findRepeating(int arr[], int n){ sort(arr, arr + n); // sort array for (int i = 0; i <= n; i++) { // compare array element with its index if (arr[i] != i + 1) { return arr[i]; } } return -1;} // driver codeint main(){ int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findRepeating(arr, n); return 0;}// this code is contributed by devendra solunke
8
Time complexity: O(N*log N) compare every array element with its indexAuxiliary Space: O(1)
Method 3 (Using Sum Formula): We know sum of first n-1 natural numbers is (n – 1)*n/2. We compute sum of array elements and subtract natural number sum from it to find the only missing element.
C++
Java
Python3
C#
Javascript
// CPP program to find the only repeating// element in an array where elements are// from 1 to n-1.#include <bits/stdc++.h>using namespace std; int findRepeating(int arr[], int n){ // Find array sum and subtract sum // first n-1 natural numbers from it // to find the result. return accumulate(arr , arr+n , 0) - ((n - 1) * n/2);} // driver codeint main(){ int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findRepeating(arr, n); return 0;}
// Java program to find the only repeating// element in an array where elements are// from 1 to n-1.import java.io.*;import java.util.*; class GFG{ static int findRepeating(int[] arr, int n) { // Find array sum and subtract sum // first n-1 natural numbers from it // to find the result. int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum - (((n - 1) * n) / 2); } // Driver code public static void main(String args[]) { int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = arr.length; System.out.println(findRepeating(arr, n)); }} // This code is contributed by rachana soma
# Python3 program to find the only# repeating element in an array where# elements are from 1 to n-1. def findRepeating(arr, n): # Find array sum and subtract sum # first n-1 natural numbers from it # to find the result. return sum(arr) -(((n - 1) * n) // 2) # Driver Codearr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]n = len(arr)print(findRepeating(arr, n)) # This code is contributed# by mohit kumar
// C# program to find the only repeating// element in an array where elements are// from 1 to n-1.using System; class GFG{ static int findRepeating(int[] arr, int n) { // Find array sum and subtract sum // first n-1 natural numbers from it // to find the result. int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum - (((n - 1) * n) / 2); } // Driver code public static void Main(String []args) { int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = arr.Length; Console.WriteLine(findRepeating(arr, n)); }} /* This code contributed by PrinciRaj1992 */
<script>// javascript program to find the only repeating// element in an array where elements are// from 1 to n-1. function findRepeating(arr , n){ // Find array sum and subtract sum // first n-1 natural numbers from it // to find the result. var sum = 0; for (i = 0; i < n; i++) sum += arr[i]; return sum - (((n - 1) * n) / 2); } // Driver code var arr = [ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 ]; var n = arr.length; document.write(findRepeating(arr, n)); // This code is contributed by Rajput-Ji</script>
8
Time Complexity: O(n)Auxiliary Space: O(1)Causes overflow for large arrays.
Method 4 (Use Hashing): Use a hash table to store elements visited. If a seen element appears again, we return it.
C++
Java
Python3
C#
Javascript
// CPP program to find the only repeating// element in an array where elements are// from 1 to n-1.#include <bits/stdc++.h>using namespace std; int findRepeating(int arr[], int n){ unordered_set<int> s; for (int i=0; i<n; i++) { if (s.find(arr[i]) != s.end()) return arr[i]; s.insert(arr[i]); } // If input is correct, we should // never reach here return -1;} // driver codeint main(){ int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findRepeating(arr, n); return 0;}
import java.util.*;// Java program to find the only repeating// element in an array where elements are// from 1 to n-1. class GFG{ static int findRepeating(int arr[], int n){ HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < n; i++) { if (s.contains(arr[i])) return arr[i]; s.add(arr[i]); } // If input is correct, we should // never reach here return -1;} // Driver codepublic static void main(String[] args){ int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = arr.length; System.out.println(findRepeating(arr, n));;}} // This code is contributed by Rajput-Ji
# Python3 program to find the only# repeating element in an array# where elements are from 1 to n-1.def findRepeating(arr, n): s = set() for i in range(n): if arr[i] in s: return arr[i] s.add(arr[i]) # If input is correct, we should # never reach here return -1 # Driver codearr = [9, 8, 2, 6, 1, 8, 5, 3]n = len(arr)print(findRepeating(arr, n)) # This code is contributed# by Shrikant13
// C# program to find the only repeating// element in an array where elements are// from 1 to n-1.using System;using System.Collections.Generic; class GFG{ static int findRepeating(int []arr, int n){ HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { if (s.Contains(arr[i])) return arr[i]; s.Add(arr[i]); } // If input is correct, we should // never reach here return -1;} // Driver codepublic static void Main(String[] args){ int []arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = arr.Length; Console.WriteLine(findRepeating(arr, n));;}} // This code has been contributed by 29AjayKumar
<script> // JavaScript program to find the only repeating// element in an array where elements are// from 1 to n-1. function findRepeating(arr,n){ s = new Set(); for (let i = 0; i < n; i++) { if (s.has(arr[i])) return arr[i]; s.add(arr[i]); } // If input is correct, we should // never reach here return -1;} // driver codelet arr = [ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 ];let n = arr.length;document.write(findRepeating(arr, n)); // This code is contributed by shinjanpatra.</script>
8
Time Complexity: O(n)Auxiliary Space: O(n)
Method 5(Use XOR): The idea is based on the fact that x ^ x = 0 and x ^ y = y ^ x.1) Compute XOR of elements from 1 to n-1.2) Compute XOR of array elements.3) XOR of above two would be our result.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the only repeating// element in an array where elements are// from 1 to n-1.#include <bits/stdc++.h>using namespace std; int findRepeating(int arr[], int n){ // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^ // arr[1] ^ .... arr[n-1] int res = 0; for (int i=0; i<n-1; i++) res = res ^ (i+1) ^ arr[i]; res = res ^ arr[n-1]; return res;} // driver codeint main(){ int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findRepeating(arr, n); return 0;}
// Java program to find the only repeating// element in an array where elements are// from 1 to n-1.class GFG{ static int findRepeating(int arr[], int n) { // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^ // arr[1] ^ .... arr[n-1] int res = 0; for (int i = 0; i < n - 1; i++) res = res ^ (i + 1) ^ arr[i]; res = res ^ arr[n - 1]; return res; } // Driver code public static void main(String[] args) { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = arr.length; System.out.println(findRepeating(arr, n)); }} // This code is contributed by// Smitha Dinesh Semwal.
# Python3 program to find the only# repeating element in an array where# elements are from 1 to n-1. def findRepeating(arr, n): # res is going to store value of # 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^ # arr[1] ^ .... arr[n-1] res = 0 for i in range(0, n-1): res = res ^ (i+1) ^ arr[i] res = res ^ arr[n-1] return res # Driver codearr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]n = len(arr)print(findRepeating(arr, n)) # This code is contributed by Smitha Dinesh Semwal.
// C# program to find the only repeating// element in an array where elements are// from 1 to n-1.using System;public class GFG{ static int findRepeating(int []arr, int n) { // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^ // arr[1] ^ .... arr[n-1] int res = 0; for (int i = 0; i < n - 1; i++) res = res ^ (i + 1) ^ arr[i]; res = res ^ arr[n - 1]; return res; } // Driver code public static void Main(String[] args) { int []arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = arr.Length; Console.WriteLine(findRepeating(arr, n)); }} // This code is contributed by Rajput-Ji
<?php// PHP program to find the only repeating// element in an array where elements are// from 1 to n-1. function findRepeating($arr, $n){ // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^ // arr[1] ^ .... arr[n-1] $res = 0; for($i = 0; $i < $n - 1; $i++) $res = $res ^ ($i + 1) ^ $arr[$i]; $res = $res ^ $arr[$n - 1]; return $res;} // Driver Code $arr =array(9, 8, 2, 6, 1, 8, 5, 3, 4, 7); $n = sizeof($arr) ; echo findRepeating($arr, $n); // This code is contributed by ajit?>
<script> // JavaScript program to find the only repeating// element in an array where elements are// from 1 to n-1. function findRepeating(arr,n){ // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^ // arr[1] ^ .... arr[n-1] let res = 0; for (let i=0; i<n-1; i++) res = res ^ (i+1) ^ arr[i]; res = res ^ arr[n-1]; return res;} // driver code let arr = [ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 ];let n = arr.length;document.write(findRepeating(arr, n)); </script>
8
Time Complexity: O(n)Auxiliary Space: O(1)
Method 6: Using indexing.1. Iterate through the array.2. For every index visit a[index], if it is positive change the sign of element at a[index] index, else print the element.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the only// repeating element in an array// where elements are from 1 to n-1.#include <bits/stdc++.h>using namespace std; // Function to find repeated elementint findRepeating(int arr[], int n){ int missingElement = 0; // indexing based for (int i = 0; i < n; i++){ int element = arr[abs(arr[i])]; if(element < 0){ missingElement = arr[i]; break; } arr[abs(arr[i])] = -arr[abs(arr[i])];} return abs(missingElement); } // driver codeint main(){ int arr[] = { 5, 4, 3, 9, 8, 9, 1, 6, 2, 5}; int n = sizeof(arr) / sizeof(arr[0]); cout << findRepeating(arr, n); return 0;}
// Java program to find the only// repeating element in an array// where elements are from 1 to n-1.import java.lang.Math.*; class GFG{ // Function to find repeated element static int findRepeating(int arr[], int n) { int missingElement = 0; // indexing based for (int i = 0; i < n; i++){ int absVal = Math.abs(arr[i]); int element = arr[absVal]; if(element < 0){ missingElement = arr[i]; break; } int absVal = Math.abs(arr[i]); arr[absVal] = -arr[absVal]; } return Math.abs(missingElement); } // Driver code public static void main(String[] args) { int arr[] = { 5, 4, 3, 9, 8, 9, 1, 6, 2, 5}; int n = arr.length; System.out.println(findRepeating(arr, n)); }}// This code is contributed by// Smitha Dinesh Semwal.
# Python3 program to find the only# repeating element in an array# where elements are from 1 to n-1. # Function to find repeated elementdef findRepeating(arr, n): missingElement = 0 # indexing based for i in range(0, n): element = arr[abs(arr[i])] if(element < 0): missingElement = arr[i] break arr[abs(arr[i])] = -arr[abs(arr[i])] return abs(missingElement) # Driver codearr = [5, 4, 3, 9, 8, 9, 1, 6, 2, 5]n = len(arr)print(findRepeating(arr, n)) # This code is contributed by Smitha Dinesh Semwal.
// C# program to find the only// repeating element in an array// where elements are from 1 to n-1.using System; public class GFG{ // Function to find repeated element static int findRepeating(int[] arr, int n) { int missingElement = 0; // indexing based for (int i = 0; i < n; i++) { int absVal = Math.abs(arr[i]); int element = arr[absVal]; if (element < 0) { missingElement = arr[i]; break; } int absVal = Math.abs(arr[i]); arr[absVal] = -arr[absVal]; } return Math.Abs(missingElement); } // Driver Code public static void Main(string[] args) { int[] arr = { 5, 4, 3, 9, 8, 9, 1, 6, 2, 5 }; int n = arr.Length; Console.WriteLine(findRepeating(arr, n)); }} // this code is contributed by phasing17
<?php// PHP program to find the only// repeating element in an array// where elements are from 1 to n-1. // Function to find repeated elementsfunction findRepeating($arr, $n){ $missingElement = 0; // indexing based for ($i = 0; $i < $n; $i++) { $element = $arr[abs($arr[$i])]; if($element < 0) { $missingElement = $arr[$i]; break; } $arr[abs($arr[$i])] = -$arr[abs($arr[$i])];} return abs($missingElement); } // Driver Code$arr = array (5, 4, 3, 9, 8, 9, 1, 6, 2, 5); $n = sizeof($arr); echo findRepeating($arr, $n); // This code is contributed by ajit?>
<script> // JavaScript program for the above approach; // Function to find repeated element function findRepeating(arr, n) { let missingElement = 0; // indexing based for (let i = 0; i < n; i++) { let absVal = Math.abs(arr[i]); let element = arr[absVal]; if (element < 0) { missingElement = arr[i]; break; } let absVal = Math.abs(arr[i]); arr[absVal] = -arr[absVal]; } return Math.abs(missingElement); } // driver code let arr = [5, 4, 3, 9, 8, 9, 1, 6, 2, 5]; let n = arr.length; document.write(findRepeating(arr, n)); // This code is contributed by Potta Lokesh </script>
9
Time Complexity: O(n)Auxiliary Space: O(1)
jit_t
Smitha Dinesh Semwal
shrikanth13
mohit kumar 29
Rajput-Ji
rachana soma
princiraj1992
29AjayKumar
sumitgumber28
lokeshpotta20
arorakashish0911
surindertarika1234
shinjanpatra
phasing17
_shinchancode
111arpit1
alinizam72
devendrasalunke
Bitwise-XOR
cpp-unordered_set
limited-range-elements
Arrays
Hash
Searching
Arrays
Searching
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jun, 2022"
},
{
"code": null,
"e": 219,
"s": 52,
"text": "We are given an array arr[] of size n. Numbers are from 1 to (n-1) in random order. The array has only one repetitive element. We need to find the repetitive element."
},
{
"code": null,
"e": 229,
"s": 219,
"text": "Examples:"
},
{
"code": null,
"e": 317,
"s": 229,
"text": "Input : a[] = {1, 3, 2, 3, 4}\nOutput : 3\n\nInput : a[] = {1, 5, 1, 2, 3, 4}\nOutput : 1"
},
{
"code": null,
"e": 544,
"s": 317,
"text": "Method 1 (Simple) We use two nested loops. The outer loop traverses through all elements and the inner loop check if the element picked by the outer loop appears anywhere else.Below is the implementation of the above approach:"
},
{
"code": null,
"e": 548,
"s": 544,
"text": "C++"
},
{
"code": null,
"e": 556,
"s": 548,
"text": "Python3"
},
{
"code": null,
"e": 559,
"s": 556,
"text": "C#"
},
{
"code": "// CPP program to find the only repeating// element in an array where elements are// from 1 to n-1.#include <bits/stdc++.h>using namespace std; int findRepeating(int arr[], int n){ for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) return arr[i]; } }} // Driver codeint main(){ int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findRepeating(arr, n); return 0;}// This code is added by Arpit Jain",
"e": 1091,
"s": 559,
"text": null
},
{
"code": "# Python3 program to find the only# repeating element in an array where# elements are from 1 to n-1.def findRepeating(arr, n): for i in range(n): for j in range(i + 1, n): if (arr[i] == arr[j]): return arr[i]; # Driver Codearr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]n = len(arr)print(findRepeating(arr, n)) # This code is contributed by Arpit Jain",
"e": 1464,
"s": 1091,
"text": null
},
{
"code": "// C# program to find the only repeating// element in an array where elements are// from 1 to n-1.using System; public class GFG { static int findRepeating(int[] arr) { for (int i = 0; i < arr.Length; i++) { for (int j = i + 1; j < arr.Length; j++) { if (arr[i] == arr[j]) return arr[i]; } } return -1; } // Driver code static public void Main() { // Code int[] arr = new int[] { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int repeatingNum = findRepeating(arr); Console.WriteLine(repeatingNum); }} // This code is contributed by Mohd Nizam",
"e": 2121,
"s": 1464,
"text": null
},
{
"code": null,
"e": 2123,
"s": 2121,
"text": "8"
},
{
"code": null,
"e": 2167,
"s": 2123,
"text": "Time Complexity: O(n2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2194,
"s": 2167,
"text": "Method 2 (Using Sorting), "
},
{
"code": null,
"e": 2266,
"s": 2194,
"text": "first sort the array and just compare the array element with its index "
},
{
"code": null,
"e": 2343,
"s": 2266,
"text": "if arr[i] != i+1, it means that arr[i] is repetitive. So Just return arr[I] "
},
{
"code": null,
"e": 2366,
"s": 2343,
"text": "So Just return arr[I] "
},
{
"code": null,
"e": 2449,
"s": 2366,
"text": "Otherwise, array does not contain duplicates from 1 to n-1In this case return -1 "
},
{
"code": null,
"e": 2474,
"s": 2449,
"text": "In this case return -1 "
},
{
"code": null,
"e": 2478,
"s": 2474,
"text": "C++"
},
{
"code": "// CPP program to find the only repeating// element in an array where elements are// from 1 to n-1.#include <bits/stdc++.h>using namespace std; int findRepeating(int arr[], int n){ sort(arr, arr + n); // sort array for (int i = 0; i <= n; i++) { // compare array element with its index if (arr[i] != i + 1) { return arr[i]; } } return -1;} // driver codeint main(){ int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findRepeating(arr, n); return 0;}// this code is contributed by devendra solunke",
"e": 3073,
"s": 2478,
"text": null
},
{
"code": null,
"e": 3075,
"s": 3073,
"text": "8"
},
{
"code": null,
"e": 3168,
"s": 3075,
"text": "Time complexity: O(N*log N) compare every array element with its indexAuxiliary Space: O(1)"
},
{
"code": null,
"e": 3362,
"s": 3168,
"text": "Method 3 (Using Sum Formula): We know sum of first n-1 natural numbers is (n – 1)*n/2. We compute sum of array elements and subtract natural number sum from it to find the only missing element."
},
{
"code": null,
"e": 3366,
"s": 3362,
"text": "C++"
},
{
"code": null,
"e": 3371,
"s": 3366,
"text": "Java"
},
{
"code": null,
"e": 3379,
"s": 3371,
"text": "Python3"
},
{
"code": null,
"e": 3382,
"s": 3379,
"text": "C#"
},
{
"code": null,
"e": 3393,
"s": 3382,
"text": "Javascript"
},
{
"code": "// CPP program to find the only repeating// element in an array where elements are// from 1 to n-1.#include <bits/stdc++.h>using namespace std; int findRepeating(int arr[], int n){ // Find array sum and subtract sum // first n-1 natural numbers from it // to find the result. return accumulate(arr , arr+n , 0) - ((n - 1) * n/2);} // driver codeint main(){ int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findRepeating(arr, n); return 0;}",
"e": 3916,
"s": 3393,
"text": null
},
{
"code": "// Java program to find the only repeating// element in an array where elements are// from 1 to n-1.import java.io.*;import java.util.*; class GFG{ static int findRepeating(int[] arr, int n) { // Find array sum and subtract sum // first n-1 natural numbers from it // to find the result. int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum - (((n - 1) * n) / 2); } // Driver code public static void main(String args[]) { int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = arr.length; System.out.println(findRepeating(arr, n)); }} // This code is contributed by rachana soma",
"e": 4606,
"s": 3916,
"text": null
},
{
"code": "# Python3 program to find the only# repeating element in an array where# elements are from 1 to n-1. def findRepeating(arr, n): # Find array sum and subtract sum # first n-1 natural numbers from it # to find the result. return sum(arr) -(((n - 1) * n) // 2) # Driver Codearr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]n = len(arr)print(findRepeating(arr, n)) # This code is contributed# by mohit kumar",
"e": 5014,
"s": 4606,
"text": null
},
{
"code": "// C# program to find the only repeating// element in an array where elements are// from 1 to n-1.using System; class GFG{ static int findRepeating(int[] arr, int n) { // Find array sum and subtract sum // first n-1 natural numbers from it // to find the result. int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum - (((n - 1) * n) / 2); } // Driver code public static void Main(String []args) { int[] arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = arr.Length; Console.WriteLine(findRepeating(arr, n)); }} /* This code contributed by PrinciRaj1992 */",
"e": 5679,
"s": 5014,
"text": null
},
{
"code": "<script>// javascript program to find the only repeating// element in an array where elements are// from 1 to n-1. function findRepeating(arr , n){ // Find array sum and subtract sum // first n-1 natural numbers from it // to find the result. var sum = 0; for (i = 0; i < n; i++) sum += arr[i]; return sum - (((n - 1) * n) / 2); } // Driver code var arr = [ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 ]; var n = arr.length; document.write(findRepeating(arr, n)); // This code is contributed by Rajput-Ji</script>",
"e": 6262,
"s": 5679,
"text": null
},
{
"code": null,
"e": 6264,
"s": 6262,
"text": "8"
},
{
"code": null,
"e": 6340,
"s": 6264,
"text": "Time Complexity: O(n)Auxiliary Space: O(1)Causes overflow for large arrays."
},
{
"code": null,
"e": 6455,
"s": 6340,
"text": "Method 4 (Use Hashing): Use a hash table to store elements visited. If a seen element appears again, we return it."
},
{
"code": null,
"e": 6459,
"s": 6455,
"text": "C++"
},
{
"code": null,
"e": 6464,
"s": 6459,
"text": "Java"
},
{
"code": null,
"e": 6472,
"s": 6464,
"text": "Python3"
},
{
"code": null,
"e": 6475,
"s": 6472,
"text": "C#"
},
{
"code": null,
"e": 6486,
"s": 6475,
"text": "Javascript"
},
{
"code": "// CPP program to find the only repeating// element in an array where elements are// from 1 to n-1.#include <bits/stdc++.h>using namespace std; int findRepeating(int arr[], int n){ unordered_set<int> s; for (int i=0; i<n; i++) { if (s.find(arr[i]) != s.end()) return arr[i]; s.insert(arr[i]); } // If input is correct, we should // never reach here return -1;} // driver codeint main(){ int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findRepeating(arr, n); return 0;}",
"e": 7049,
"s": 6486,
"text": null
},
{
"code": "import java.util.*;// Java program to find the only repeating// element in an array where elements are// from 1 to n-1. class GFG{ static int findRepeating(int arr[], int n){ HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < n; i++) { if (s.contains(arr[i])) return arr[i]; s.add(arr[i]); } // If input is correct, we should // never reach here return -1;} // Driver codepublic static void main(String[] args){ int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = arr.length; System.out.println(findRepeating(arr, n));;}} // This code is contributed by Rajput-Ji",
"e": 7688,
"s": 7049,
"text": null
},
{
"code": "# Python3 program to find the only# repeating element in an array# where elements are from 1 to n-1.def findRepeating(arr, n): s = set() for i in range(n): if arr[i] in s: return arr[i] s.add(arr[i]) # If input is correct, we should # never reach here return -1 # Driver codearr = [9, 8, 2, 6, 1, 8, 5, 3]n = len(arr)print(findRepeating(arr, n)) # This code is contributed# by Shrikant13",
"e": 8121,
"s": 7688,
"text": null
},
{
"code": "// C# program to find the only repeating// element in an array where elements are// from 1 to n-1.using System;using System.Collections.Generic; class GFG{ static int findRepeating(int []arr, int n){ HashSet<int> s = new HashSet<int>(); for (int i = 0; i < n; i++) { if (s.Contains(arr[i])) return arr[i]; s.Add(arr[i]); } // If input is correct, we should // never reach here return -1;} // Driver codepublic static void Main(String[] args){ int []arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = arr.Length; Console.WriteLine(findRepeating(arr, n));;}} // This code has been contributed by 29AjayKumar",
"e": 8784,
"s": 8121,
"text": null
},
{
"code": "<script> // JavaScript program to find the only repeating// element in an array where elements are// from 1 to n-1. function findRepeating(arr,n){ s = new Set(); for (let i = 0; i < n; i++) { if (s.has(arr[i])) return arr[i]; s.add(arr[i]); } // If input is correct, we should // never reach here return -1;} // driver codelet arr = [ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 ];let n = arr.length;document.write(findRepeating(arr, n)); // This code is contributed by shinjanpatra.</script>",
"e": 9300,
"s": 8784,
"text": null
},
{
"code": null,
"e": 9302,
"s": 9300,
"text": "8"
},
{
"code": null,
"e": 9345,
"s": 9302,
"text": "Time Complexity: O(n)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 9542,
"s": 9345,
"text": "Method 5(Use XOR): The idea is based on the fact that x ^ x = 0 and x ^ y = y ^ x.1) Compute XOR of elements from 1 to n-1.2) Compute XOR of array elements.3) XOR of above two would be our result."
},
{
"code": null,
"e": 9546,
"s": 9542,
"text": "C++"
},
{
"code": null,
"e": 9551,
"s": 9546,
"text": "Java"
},
{
"code": null,
"e": 9559,
"s": 9551,
"text": "Python3"
},
{
"code": null,
"e": 9562,
"s": 9559,
"text": "C#"
},
{
"code": null,
"e": 9566,
"s": 9562,
"text": "PHP"
},
{
"code": null,
"e": 9577,
"s": 9566,
"text": "Javascript"
},
{
"code": "// CPP program to find the only repeating// element in an array where elements are// from 1 to n-1.#include <bits/stdc++.h>using namespace std; int findRepeating(int arr[], int n){ // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^ // arr[1] ^ .... arr[n-1] int res = 0; for (int i=0; i<n-1; i++) res = res ^ (i+1) ^ arr[i]; res = res ^ arr[n-1]; return res;} // driver codeint main(){ int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findRepeating(arr, n); return 0;}",
"e": 10124,
"s": 9577,
"text": null
},
{
"code": "// Java program to find the only repeating// element in an array where elements are// from 1 to n-1.class GFG{ static int findRepeating(int arr[], int n) { // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^ // arr[1] ^ .... arr[n-1] int res = 0; for (int i = 0; i < n - 1; i++) res = res ^ (i + 1) ^ arr[i]; res = res ^ arr[n - 1]; return res; } // Driver code public static void main(String[] args) { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = arr.length; System.out.println(findRepeating(arr, n)); }} // This code is contributed by// Smitha Dinesh Semwal.",
"e": 10841,
"s": 10124,
"text": null
},
{
"code": "# Python3 program to find the only# repeating element in an array where# elements are from 1 to n-1. def findRepeating(arr, n): # res is going to store value of # 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^ # arr[1] ^ .... arr[n-1] res = 0 for i in range(0, n-1): res = res ^ (i+1) ^ arr[i] res = res ^ arr[n-1] return res # Driver codearr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7]n = len(arr)print(findRepeating(arr, n)) # This code is contributed by Smitha Dinesh Semwal.",
"e": 11340,
"s": 10841,
"text": null
},
{
"code": "// C# program to find the only repeating// element in an array where elements are// from 1 to n-1.using System;public class GFG{ static int findRepeating(int []arr, int n) { // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^ // arr[1] ^ .... arr[n-1] int res = 0; for (int i = 0; i < n - 1; i++) res = res ^ (i + 1) ^ arr[i]; res = res ^ arr[n - 1]; return res; } // Driver code public static void Main(String[] args) { int []arr = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int n = arr.Length; Console.WriteLine(findRepeating(arr, n)); }} // This code is contributed by Rajput-Ji",
"e": 11976,
"s": 11340,
"text": null
},
{
"code": "<?php// PHP program to find the only repeating// element in an array where elements are// from 1 to n-1. function findRepeating($arr, $n){ // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^ // arr[1] ^ .... arr[n-1] $res = 0; for($i = 0; $i < $n - 1; $i++) $res = $res ^ ($i + 1) ^ $arr[$i]; $res = $res ^ $arr[$n - 1]; return $res;} // Driver Code $arr =array(9, 8, 2, 6, 1, 8, 5, 3, 4, 7); $n = sizeof($arr) ; echo findRepeating($arr, $n); // This code is contributed by ajit?>",
"e": 12529,
"s": 11976,
"text": null
},
{
"code": "<script> // JavaScript program to find the only repeating// element in an array where elements are// from 1 to n-1. function findRepeating(arr,n){ // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^ // arr[1] ^ .... arr[n-1] let res = 0; for (let i=0; i<n-1; i++) res = res ^ (i+1) ^ arr[i]; res = res ^ arr[n-1]; return res;} // driver code let arr = [ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 ];let n = arr.length;document.write(findRepeating(arr, n)); </script>",
"e": 13011,
"s": 12529,
"text": null
},
{
"code": null,
"e": 13013,
"s": 13011,
"text": "8"
},
{
"code": null,
"e": 13056,
"s": 13013,
"text": "Time Complexity: O(n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 13233,
"s": 13056,
"text": "Method 6: Using indexing.1. Iterate through the array.2. For every index visit a[index], if it is positive change the sign of element at a[index] index, else print the element."
},
{
"code": null,
"e": 13237,
"s": 13233,
"text": "C++"
},
{
"code": null,
"e": 13242,
"s": 13237,
"text": "Java"
},
{
"code": null,
"e": 13250,
"s": 13242,
"text": "Python3"
},
{
"code": null,
"e": 13253,
"s": 13250,
"text": "C#"
},
{
"code": null,
"e": 13257,
"s": 13253,
"text": "PHP"
},
{
"code": null,
"e": 13268,
"s": 13257,
"text": "Javascript"
},
{
"code": "// CPP program to find the only// repeating element in an array// where elements are from 1 to n-1.#include <bits/stdc++.h>using namespace std; // Function to find repeated elementint findRepeating(int arr[], int n){ int missingElement = 0; // indexing based for (int i = 0; i < n; i++){ int element = arr[abs(arr[i])]; if(element < 0){ missingElement = arr[i]; break; } arr[abs(arr[i])] = -arr[abs(arr[i])];} return abs(missingElement); } // driver codeint main(){ int arr[] = { 5, 4, 3, 9, 8, 9, 1, 6, 2, 5}; int n = sizeof(arr) / sizeof(arr[0]); cout << findRepeating(arr, n); return 0;}",
"e": 13954,
"s": 13268,
"text": null
},
{
"code": "// Java program to find the only// repeating element in an array// where elements are from 1 to n-1.import java.lang.Math.*; class GFG{ // Function to find repeated element static int findRepeating(int arr[], int n) { int missingElement = 0; // indexing based for (int i = 0; i < n; i++){ int absVal = Math.abs(arr[i]); int element = arr[absVal]; if(element < 0){ missingElement = arr[i]; break; } int absVal = Math.abs(arr[i]); arr[absVal] = -arr[absVal]; } return Math.abs(missingElement); } // Driver code public static void main(String[] args) { int arr[] = { 5, 4, 3, 9, 8, 9, 1, 6, 2, 5}; int n = arr.length; System.out.println(findRepeating(arr, n)); }}// This code is contributed by// Smitha Dinesh Semwal.",
"e": 14902,
"s": 13954,
"text": null
},
{
"code": "# Python3 program to find the only# repeating element in an array# where elements are from 1 to n-1. # Function to find repeated elementdef findRepeating(arr, n): missingElement = 0 # indexing based for i in range(0, n): element = arr[abs(arr[i])] if(element < 0): missingElement = arr[i] break arr[abs(arr[i])] = -arr[abs(arr[i])] return abs(missingElement) # Driver codearr = [5, 4, 3, 9, 8, 9, 1, 6, 2, 5]n = len(arr)print(findRepeating(arr, n)) # This code is contributed by Smitha Dinesh Semwal.",
"e": 15476,
"s": 14902,
"text": null
},
{
"code": "// C# program to find the only// repeating element in an array// where elements are from 1 to n-1.using System; public class GFG{ // Function to find repeated element static int findRepeating(int[] arr, int n) { int missingElement = 0; // indexing based for (int i = 0; i < n; i++) { int absVal = Math.abs(arr[i]); int element = arr[absVal]; if (element < 0) { missingElement = arr[i]; break; } int absVal = Math.abs(arr[i]); arr[absVal] = -arr[absVal]; } return Math.Abs(missingElement); } // Driver Code public static void Main(string[] args) { int[] arr = { 5, 4, 3, 9, 8, 9, 1, 6, 2, 5 }; int n = arr.Length; Console.WriteLine(findRepeating(arr, n)); }} // this code is contributed by phasing17",
"e": 16272,
"s": 15476,
"text": null
},
{
"code": "<?php// PHP program to find the only// repeating element in an array// where elements are from 1 to n-1. // Function to find repeated elementsfunction findRepeating($arr, $n){ $missingElement = 0; // indexing based for ($i = 0; $i < $n; $i++) { $element = $arr[abs($arr[$i])]; if($element < 0) { $missingElement = $arr[$i]; break; } $arr[abs($arr[$i])] = -$arr[abs($arr[$i])];} return abs($missingElement); } // Driver Code$arr = array (5, 4, 3, 9, 8, 9, 1, 6, 2, 5); $n = sizeof($arr); echo findRepeating($arr, $n); // This code is contributed by ajit?>",
"e": 16913,
"s": 16272,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach; // Function to find repeated element function findRepeating(arr, n) { let missingElement = 0; // indexing based for (let i = 0; i < n; i++) { let absVal = Math.abs(arr[i]); let element = arr[absVal]; if (element < 0) { missingElement = arr[i]; break; } let absVal = Math.abs(arr[i]); arr[absVal] = -arr[absVal]; } return Math.abs(missingElement); } // driver code let arr = [5, 4, 3, 9, 8, 9, 1, 6, 2, 5]; let n = arr.length; document.write(findRepeating(arr, n)); // This code is contributed by Potta Lokesh </script>",
"e": 17730,
"s": 16913,
"text": null
},
{
"code": null,
"e": 17732,
"s": 17730,
"text": "9"
},
{
"code": null,
"e": 17776,
"s": 17732,
"text": "Time Complexity: O(n)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 17782,
"s": 17776,
"text": "jit_t"
},
{
"code": null,
"e": 17803,
"s": 17782,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 17815,
"s": 17803,
"text": "shrikanth13"
},
{
"code": null,
"e": 17830,
"s": 17815,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 17840,
"s": 17830,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 17853,
"s": 17840,
"text": "rachana soma"
},
{
"code": null,
"e": 17867,
"s": 17853,
"text": "princiraj1992"
},
{
"code": null,
"e": 17879,
"s": 17867,
"text": "29AjayKumar"
},
{
"code": null,
"e": 17893,
"s": 17879,
"text": "sumitgumber28"
},
{
"code": null,
"e": 17907,
"s": 17893,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 17924,
"s": 17907,
"text": "arorakashish0911"
},
{
"code": null,
"e": 17943,
"s": 17924,
"text": "surindertarika1234"
},
{
"code": null,
"e": 17956,
"s": 17943,
"text": "shinjanpatra"
},
{
"code": null,
"e": 17966,
"s": 17956,
"text": "phasing17"
},
{
"code": null,
"e": 17980,
"s": 17966,
"text": "_shinchancode"
},
{
"code": null,
"e": 17990,
"s": 17980,
"text": "111arpit1"
},
{
"code": null,
"e": 18001,
"s": 17990,
"text": "alinizam72"
},
{
"code": null,
"e": 18017,
"s": 18001,
"text": "devendrasalunke"
},
{
"code": null,
"e": 18029,
"s": 18017,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 18047,
"s": 18029,
"text": "cpp-unordered_set"
},
{
"code": null,
"e": 18070,
"s": 18047,
"text": "limited-range-elements"
},
{
"code": null,
"e": 18077,
"s": 18070,
"text": "Arrays"
},
{
"code": null,
"e": 18082,
"s": 18077,
"text": "Hash"
},
{
"code": null,
"e": 18092,
"s": 18082,
"text": "Searching"
},
{
"code": null,
"e": 18099,
"s": 18092,
"text": "Arrays"
},
{
"code": null,
"e": 18109,
"s": 18099,
"text": "Searching"
},
{
"code": null,
"e": 18114,
"s": 18109,
"text": "Hash"
}
] |
Sorting a 2D Array according to values in any given column in Java | 11 Dec, 2018
We are given a 2D array of order N X M and a column number K ( 1<=K<=m). Our task is to sort the 2D array according to values in the Column K.
Examples:
Input : If our 2D array is given as (Order 4X4)
39 27 11 42
10 93 91 90
54 78 56 89
24 64 20 65
Sorting it by values in column 3
Output : 39 27 11 42
24 64 20 65
54 78 56 89
10 93 91 90
The Idea is to use Arrays.sort in Java.
// Java Code to sort 2D Matrix// according to any Columnimport java.util.*;class sort2DMatrixbycolumn { // Function to sort by column public static void sortbyColumn(int arr[][], int col) { // Using built-in sort function Arrays.sort Arrays.sort(arr, new Comparator<int[]>() { @Override // Compare values according to columns public int compare(final int[] entry1, final int[] entry2) { // To sort in descending order revert // the '>' Operator if (entry1[col] > entry2[col]) return 1; else return -1; } }); // End of function call sort(). } // Driver Code public static void main(String args[]) { int matrix[][] = { { 39, 27, 11, 42 }, { 10, 93, 91, 90 }, { 54, 78, 56, 89 }, { 24, 64, 20, 65 } }; // Sort this matrix by 3rd Column int col = 3; sortbyColumn(matrix, col - 1); // Display the sorted Matrix for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) System.out.print(matrix[i][j] + " "); System.out.println(); } }}
Output:
39 27 11 42
24 64 20 65
54 78 56 89
10 93 91 90
Time complexity : O(n Log n) where n is number of rows. Here assumption is that the sort() function uses a O(n Log n) sorting algorithm.
This article is contributed by DANISH KALEEM. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-Array-Programs
Java-Arrays
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 197,
"s": 54,
"text": "We are given a 2D array of order N X M and a column number K ( 1<=K<=m). Our task is to sort the 2D array according to values in the Column K."
},
{
"code": null,
"e": 207,
"s": 197,
"text": "Examples:"
},
{
"code": null,
"e": 470,
"s": 207,
"text": "Input : If our 2D array is given as (Order 4X4) \n 39 27 11 42 \n 10 93 91 90 \n 54 78 56 89 \n 24 64 20 65\n Sorting it by values in column 3 \nOutput : 39 27 11 42 \n 24 64 20 65 \n 54 78 56 89 \n 10 93 91 90 \n"
},
{
"code": null,
"e": 510,
"s": 470,
"text": "The Idea is to use Arrays.sort in Java."
},
{
"code": "// Java Code to sort 2D Matrix// according to any Columnimport java.util.*;class sort2DMatrixbycolumn { // Function to sort by column public static void sortbyColumn(int arr[][], int col) { // Using built-in sort function Arrays.sort Arrays.sort(arr, new Comparator<int[]>() { @Override // Compare values according to columns public int compare(final int[] entry1, final int[] entry2) { // To sort in descending order revert // the '>' Operator if (entry1[col] > entry2[col]) return 1; else return -1; } }); // End of function call sort(). } // Driver Code public static void main(String args[]) { int matrix[][] = { { 39, 27, 11, 42 }, { 10, 93, 91, 90 }, { 54, 78, 56, 89 }, { 24, 64, 20, 65 } }; // Sort this matrix by 3rd Column int col = 3; sortbyColumn(matrix, col - 1); // Display the sorted Matrix for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) System.out.print(matrix[i][j] + \" \"); System.out.println(); } }}",
"e": 1854,
"s": 510,
"text": null
},
{
"code": null,
"e": 1862,
"s": 1854,
"text": "Output:"
},
{
"code": null,
"e": 1916,
"s": 1862,
"text": " 39 27 11 42 \n24 64 20 65 \n54 78 56 89 \n10 93 91 90 \n"
},
{
"code": null,
"e": 2053,
"s": 1916,
"text": "Time complexity : O(n Log n) where n is number of rows. Here assumption is that the sort() function uses a O(n Log n) sorting algorithm."
},
{
"code": null,
"e": 2354,
"s": 2053,
"text": "This article is contributed by DANISH KALEEM. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2479,
"s": 2354,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2499,
"s": 2479,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 2511,
"s": 2499,
"text": "Java-Arrays"
},
{
"code": null,
"e": 2516,
"s": 2511,
"text": "Java"
},
{
"code": null,
"e": 2521,
"s": 2516,
"text": "Java"
},
{
"code": null,
"e": 2619,
"s": 2521,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2670,
"s": 2619,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2701,
"s": 2670,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2720,
"s": 2701,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2750,
"s": 2720,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2768,
"s": 2750,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2783,
"s": 2768,
"text": "Stream In Java"
},
{
"code": null,
"e": 2803,
"s": 2783,
"text": "Collections in Java"
},
{
"code": null,
"e": 2835,
"s": 2803,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2859,
"s": 2835,
"text": "Singleton Class in Java"
}
] |
Python PIL | ImageDraw.Draw.ellipse() | 02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
ImageDraw.Draw.ellipse() Draws an ellipse inside the given bounding box.
Syntax: PIL.ImageDraw.Draw.ellipse(xy, fill=None, outline=None)
Parameters:xy – Four points to define the bounding box. Sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].outline – Color to use for the outline.fill – Color to use for the fill.
Returns: An Image object in ellipse shape.
# importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new("RGB", (w, h)) # create ellipse imageimg1 = ImageDraw.Draw(img) img1.ellipse(shape, fill ="# ffff33", outline ="red")img.show()
Output:
Another Example: Here we use different colour for filling.
# importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new("RGB", (w, h)) # create ellipse imageimg1 = ImageDraw.Draw(img) img1.ellipse(shape, fill ="# 800080", outline ="green")img.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use."
},
{
"code": null,
"e": 405,
"s": 332,
"text": "ImageDraw.Draw.ellipse() Draws an ellipse inside the given bounding box."
},
{
"code": null,
"e": 469,
"s": 405,
"text": "Syntax: PIL.ImageDraw.Draw.ellipse(xy, fill=None, outline=None)"
},
{
"code": null,
"e": 658,
"s": 469,
"text": "Parameters:xy – Four points to define the bounding box. Sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1].outline – Color to use for the outline.fill – Color to use for the fill."
},
{
"code": null,
"e": 701,
"s": 658,
"text": "Returns: An Image object in ellipse shape."
},
{
"code": " # importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new(\"RGB\", (w, h)) # create ellipse imageimg1 = ImageDraw.Draw(img) img1.ellipse(shape, fill =\"# ffff33\", outline =\"red\")img.show()",
"e": 1010,
"s": 701,
"text": null
},
{
"code": null,
"e": 1018,
"s": 1010,
"text": "Output:"
},
{
"code": null,
"e": 1077,
"s": 1018,
"text": "Another Example: Here we use different colour for filling."
},
{
"code": " # importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new(\"RGB\", (w, h)) # create ellipse imageimg1 = ImageDraw.Draw(img) img1.ellipse(shape, fill =\"# 800080\", outline =\"green\")img.show()",
"e": 1388,
"s": 1077,
"text": null
},
{
"code": null,
"e": 1396,
"s": 1388,
"text": "Output:"
},
{
"code": null,
"e": 1407,
"s": 1396,
"text": "Python-pil"
},
{
"code": null,
"e": 1414,
"s": 1407,
"text": "Python"
},
{
"code": null,
"e": 1512,
"s": 1414,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1530,
"s": 1512,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1572,
"s": 1530,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1594,
"s": 1572,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1620,
"s": 1594,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1652,
"s": 1620,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1681,
"s": 1652,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1708,
"s": 1681,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1744,
"s": 1708,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 1775,
"s": 1744,
"text": "Python | os.path.join() method"
}
] |
PostgreSQL - UNIONS Clause | The PostgreSQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows.
To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same order but they do not have to be the same length.
The basic syntax of UNION is as follows −
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here, given condition could be any given expression based on your requirement.
Consider the following two tables, (a) COMPANY table is as follows −
testdb=# SELECT * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
(b) Another table is DEPARTMENT as follows −
testdb=# SELECT * from DEPARTMENT;
id | dept | emp_id
----+-------------+--------
1 | IT Billing | 1
2 | Engineering | 2
3 | Finance | 7
4 | Engineering | 3
5 | Finance | 4
6 | Engineering | 5
7 | Finance | 6
(7 rows)
Now let us join these two tables using SELECT statement along with UNION clause as follows −
testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
This would produce the following result −
emp_id | name | dept
--------+-------+--------------
5 | David | Engineering
6 | Kim | Finance
2 | Allen | Engineering
3 | Teddy | Engineering
4 | Mark | Finance
1 | Paul | IT Billing
7 | James | Finance
(7 rows)
The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows. The same rules that apply to UNION apply to the UNION ALL operator as well.
The basic syntax of UNION ALL is as follows −
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION ALL
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Here, given condition could be any given expression based on your requirement.
Now, let us join above-mentioned two tables in our SELECT statement as follows −
testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID
UNION ALL
SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
ON COMPANY.ID = DEPARTMENT.EMP_ID;
This would produce the following result −
emp_id | name | dept
--------+-------+--------------
1 | Paul | IT Billing
2 | Allen | Engineering
7 | James | Finance
3 | Teddy | Engineering
4 | Mark | Finance
5 | David | Engineering
6 | Kim | Finance
1 | Paul | IT Billing
2 | Allen | Engineering
7 | James | Finance
3 | Teddy | Engineering
4 | Mark | Finance
5 | David | Engineering
6 | Kim | Finance | [
{
"code": null,
"e": 3098,
"s": 2959,
"text": "The PostgreSQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows."
},
{
"code": null,
"e": 3306,
"s": 3098,
"text": "To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same order but they do not have to be the same length."
},
{
"code": null,
"e": 3348,
"s": 3306,
"text": "The basic syntax of UNION is as follows −"
},
{
"code": null,
"e": 3497,
"s": 3348,
"text": "SELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n\nUNION\n\nSELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n"
},
{
"code": null,
"e": 3576,
"s": 3497,
"text": "Here, given condition could be any given expression based on your requirement."
},
{
"code": null,
"e": 3645,
"s": 3576,
"text": "Consider the following two tables, (a) COMPANY table is as follows −"
},
{
"code": null,
"e": 4038,
"s": 3645,
"text": "testdb=# SELECT * from COMPANY;\n id | name | age | address | salary\n----+-------+-----+-----------+--------\n 1 | Paul | 32 | California| 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall| 45000\n 7 | James | 24 | Houston | 10000\n(7 rows)"
},
{
"code": null,
"e": 4083,
"s": 4038,
"text": "(b) Another table is DEPARTMENT as follows −"
},
{
"code": null,
"e": 4371,
"s": 4083,
"text": "testdb=# SELECT * from DEPARTMENT;\n id | dept | emp_id\n----+-------------+--------\n 1 | IT Billing | 1\n 2 | Engineering | 2\n 3 | Finance | 7\n 4 | Engineering | 3\n 5 | Finance | 4\n 6 | Engineering | 5\n 7 | Finance | 6\n(7 rows)"
},
{
"code": null,
"e": 4464,
"s": 4371,
"text": "Now let us join these two tables using SELECT statement along with UNION clause as follows −"
},
{
"code": null,
"e": 4696,
"s": 4464,
"text": "testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID\n UNION\n SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID;"
},
{
"code": null,
"e": 4738,
"s": 4696,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 5001,
"s": 4738,
"text": " emp_id | name | dept\n--------+-------+--------------\n 5 | David | Engineering\n 6 | Kim | Finance\n 2 | Allen | Engineering\n 3 | Teddy | Engineering\n 4 | Mark | Finance\n 1 | Paul | IT Billing\n 7 | James | Finance\n(7 rows)\n"
},
{
"code": null,
"e": 5182,
"s": 5001,
"text": "The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows. The same rules that apply to UNION apply to the UNION ALL operator as well."
},
{
"code": null,
"e": 5228,
"s": 5182,
"text": "The basic syntax of UNION ALL is as follows −"
},
{
"code": null,
"e": 5381,
"s": 5228,
"text": "SELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n\nUNION ALL\n\nSELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n"
},
{
"code": null,
"e": 5460,
"s": 5381,
"text": "Here, given condition could be any given expression based on your requirement."
},
{
"code": null,
"e": 5541,
"s": 5460,
"text": "Now, let us join above-mentioned two tables in our SELECT statement as follows −"
},
{
"code": null,
"e": 5777,
"s": 5541,
"text": "testdb=# SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID\n UNION ALL\n SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT\n ON COMPANY.ID = DEPARTMENT.EMP_ID;"
},
{
"code": null,
"e": 5819,
"s": 5777,
"text": "This would produce the following result −"
}
] |
Ruby | String gsub Method | 12 Dec, 2019
gsub is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument.
Syntax: str.gsub(pattern, replacement)
Parameters: Here, str is the given string. pattern may be specified regex or character set to be removed. replacement is the set of characters which is to be put.
Returns:A copy of the string with all occurrences of pattern substituted for the second argument.
Example 1:
# Ruby program to demonstrate # the gsub method # Taking a string and # using the methodputs "Sample".gsub(/[amuyt]/, '*') puts "Program".gsub(/([gmra])/, '<\1>')
Output:
S**ple
Po
Example 2:
# Ruby program to demonstrate # the gsub method # Taking a string and # using the methodputs "Ruby".gsub(/[tyru]/, '<\1>') puts "String".gsub(/([igtr])/, '*')
Output:
Rb
S***n*
Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Ruby | Array slice() function
Ruby | push() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Dec, 2019"
},
{
"code": null,
"e": 186,
"s": 28,
"text": "gsub is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument."
},
{
"code": null,
"e": 225,
"s": 186,
"text": "Syntax: str.gsub(pattern, replacement)"
},
{
"code": null,
"e": 388,
"s": 225,
"text": "Parameters: Here, str is the given string. pattern may be specified regex or character set to be removed. replacement is the set of characters which is to be put."
},
{
"code": null,
"e": 486,
"s": 388,
"text": "Returns:A copy of the string with all occurrences of pattern substituted for the second argument."
},
{
"code": null,
"e": 497,
"s": 486,
"text": "Example 1:"
},
{
"code": "# Ruby program to demonstrate # the gsub method # Taking a string and # using the methodputs \"Sample\".gsub(/[amuyt]/, '*') puts \"Program\".gsub(/([gmra])/, '<\\1>') ",
"e": 689,
"s": 497,
"text": null
},
{
"code": null,
"e": 697,
"s": 689,
"text": "Output:"
},
{
"code": null,
"e": 708,
"s": 697,
"text": "S**ple\nPo\n"
},
{
"code": null,
"e": 719,
"s": 708,
"text": "Example 2:"
},
{
"code": "# Ruby program to demonstrate # the gsub method # Taking a string and # using the methodputs \"Ruby\".gsub(/[tyru]/, '<\\1>') puts \"String\".gsub(/([igtr])/, '*') ",
"e": 907,
"s": 719,
"text": null
},
{
"code": null,
"e": 915,
"s": 907,
"text": "Output:"
},
{
"code": null,
"e": 926,
"s": 915,
"text": "Rb\nS***n*\n"
},
{
"code": null,
"e": 944,
"s": 926,
"text": "Ruby String-class"
},
{
"code": null,
"e": 957,
"s": 944,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 962,
"s": 957,
"text": "Ruby"
},
{
"code": null,
"e": 1060,
"s": 962,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1106,
"s": 1060,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 1137,
"s": 1106,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 1167,
"s": 1137,
"text": "Ruby | Array slice() function"
},
{
"code": null,
"e": 1190,
"s": 1167,
"text": "Ruby | push() function"
},
{
"code": null,
"e": 1217,
"s": 1190,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 1241,
"s": 1217,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 1272,
"s": 1241,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 1315,
"s": 1272,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 1337,
"s": 1315,
"text": "Ruby | Case Statement"
}
] |
Help function in Python | 17 Sep, 2021
The Python help function is used to display the documentation of modules, functions, classes, keywords, etc.
help([object])
object: Call help of the given object.
If the help function is passed without an argument, then the interactive help utility starts up on the console.
Let us check the documentation of the print function in the python console.
Python3
help(print)
Output:
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Help function output can also be defined for user-defined functions and classes. The docstring(documentation string) is used for documentation. It is nested inside triple quotes and is the first statement within a class or function or a module.
Let us define a class with functions:
Python3
class Helper: def __init__(self): '''The helper class is initialized''' def print_help(self): '''Returns the help description''' print('helper description') help(Helper)help(Helper.print_help)
On running the above program, we get the output of the first help function as shown below:
Help on class Helper in module __main__:
class Helper(builtins.object)
| Methods defined here:
|
| __init__(self)
| The helper class is initialized
|
| print_help(self)
| Returns the help description
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
Help on function print_help in module __main__:
print_help(self)
Returns the help description
The docstrings are declared using ”’triple single quotes”’ or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.
Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function.
Python3
def my_function(): '''Demonstrates triple double quotes docstrings and does nothing really.''' return None print("Using __doc__:")print(my_function.__doc__) print("Using help:")help(my_function)
Output:
Using __doc__:
Demonstrates triple double quotes
docstrings and does nothing really.
Using help:
Help on function my_function in module __main__:
my_function()
Demonstrates triple double quotes
docstrings and does nothing really.
kumar_satyam
Python-Built-in-functions
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace() | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Sep, 2021"
},
{
"code": null,
"e": 163,
"s": 53,
"text": "The Python help function is used to display the documentation of modules, functions, classes, keywords, etc. "
},
{
"code": null,
"e": 178,
"s": 163,
"text": "help([object])"
},
{
"code": null,
"e": 217,
"s": 178,
"text": "object: Call help of the given object."
},
{
"code": null,
"e": 329,
"s": 217,
"text": "If the help function is passed without an argument, then the interactive help utility starts up on the console."
},
{
"code": null,
"e": 406,
"s": 329,
"text": "Let us check the documentation of the print function in the python console. "
},
{
"code": null,
"e": 414,
"s": 406,
"text": "Python3"
},
{
"code": "help(print)",
"e": 426,
"s": 414,
"text": null
},
{
"code": null,
"e": 434,
"s": 426,
"text": "Output:"
},
{
"code": null,
"e": 919,
"s": 434,
"text": "Help on built-in function print in module builtins:\n\nprint(...)\n print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\n Prints the values to a stream, or to sys.stdout by default.\n Optional keyword arguments:\n file: a file-like object (stream); defaults to the current sys.stdout.\n sep: string inserted between values, default a space.\n end: string appended after the last value, default a newline.\n flush: whether to forcibly flush the stream."
},
{
"code": null,
"e": 1164,
"s": 919,
"text": "Help function output can also be defined for user-defined functions and classes. The docstring(documentation string) is used for documentation. It is nested inside triple quotes and is the first statement within a class or function or a module."
},
{
"code": null,
"e": 1203,
"s": 1164,
"text": "Let us define a class with functions: "
},
{
"code": null,
"e": 1211,
"s": 1203,
"text": "Python3"
},
{
"code": "class Helper: def __init__(self): '''The helper class is initialized''' def print_help(self): '''Returns the help description''' print('helper description') help(Helper)help(Helper.print_help)",
"e": 1433,
"s": 1211,
"text": null
},
{
"code": null,
"e": 1526,
"s": 1433,
"text": "On running the above program, we get the output of the first help function as shown below: "
},
{
"code": null,
"e": 2119,
"s": 1526,
"text": "Help on class Helper in module __main__:\n\nclass Helper(builtins.object)\n | Methods defined here:\n | \n | __init__(self)\n | The helper class is initialized\n | \n | print_help(self)\n | Returns the help description\n | \n | ----------------------------------------------------------------------\n | Data descriptors defined here:\n | \n | __dict__\n | dictionary for instance variables (if defined)\n | \n | __weakref__\n | list of weak references to the object (if defined)\n\nHelp on function print_help in module __main__:\n\nprint_help(self)\n Returns the help description"
},
{
"code": null,
"e": 2301,
"s": 2119,
"text": "The docstrings are declared using ”’triple single quotes”’ or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring."
},
{
"code": null,
"e": 2421,
"s": 2301,
"text": "Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function."
},
{
"code": null,
"e": 2429,
"s": 2421,
"text": "Python3"
},
{
"code": "def my_function(): '''Demonstrates triple double quotes docstrings and does nothing really.''' return None print(\"Using __doc__:\")print(my_function.__doc__) print(\"Using help:\")help(my_function)",
"e": 2634,
"s": 2429,
"text": null
},
{
"code": null,
"e": 2642,
"s": 2634,
"text": "Output:"
},
{
"code": null,
"e": 2885,
"s": 2642,
"text": "Using __doc__:\nDemonstrates triple double quotes\n docstrings and does nothing really.\nUsing help:\nHelp on function my_function in module __main__:\n\nmy_function()\n Demonstrates triple double quotes\n docstrings and does nothing really."
},
{
"code": null,
"e": 2898,
"s": 2885,
"text": "kumar_satyam"
},
{
"code": null,
"e": 2924,
"s": 2898,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 2941,
"s": 2924,
"text": "Python-Functions"
},
{
"code": null,
"e": 2948,
"s": 2941,
"text": "Python"
},
{
"code": null,
"e": 3046,
"s": 2948,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3074,
"s": 3046,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3124,
"s": 3074,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3146,
"s": 3124,
"text": "Python map() function"
},
{
"code": null,
"e": 3190,
"s": 3146,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 3208,
"s": 3190,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3250,
"s": 3208,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3273,
"s": 3250,
"text": "Taking input in Python"
},
{
"code": null,
"e": 3295,
"s": 3273,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3330,
"s": 3295,
"text": "Read a file line by line in Python"
}
] |
Java program to find IP address of your computer | 09 Nov, 2021
An IP(Internet Protocol) address is an identifier assigned to each computer and another device (e.g., router, mobile, etc) connected to a TCP/IP network that is used to locate and identify the node in communication with other nodes on the network. IP addresses are usually written and displayed in human-readable notation such as 192.168.1.35 in IPv4(32-bit IP address).
An IP address serves two principal functions: host or network interface identification and local addressing. Its role has been characterized as follows: “A name indicates what we seek. An address indicates where it is. A route indicates how to get there.”
Prerequisites : Networking in Java | Set 1 (InetAddress class), trim() in Java.InetAddress.getLocalHost() is used to find the private IP addresses used in LAN or any other local network.
To find public IP, we use http://bot.whatismyipaddress.com (An online utility to find your public IP), we open the URL, read a line and print the line.
Below is the Java implementation of the above steps.
Java
// Java program to find IP address of your computer// java.net.InetAddress class provides method to get// IP of any host nameimport java.net.*;import java.io.*;import java.util.*;import java.net.InetAddress; public class JavaProgram{ public static void main(String args[]) throws Exception { // Returns the instance of InetAddress containing // local host name and address InetAddress localhost = InetAddress.getLocalHost(); System.out.println("System IP Address : " + (localhost.getHostAddress()).trim()); // Find public IP address String systemipaddress = ""; try { URL url_name = new URL("http://bot.whatismyipaddress.com"); BufferedReader sc = new BufferedReader(new InputStreamReader(url_name.openStream())); // reads system IPAddress systemipaddress = sc.readLine().trim(); } catch (Exception e) { systemipaddress = "Cannot Execute Properly"; } System.out.println("Public IP Address: " + systemipaddress +"\n"); }}
Output:
System IP Address : 10.0.8.204
Public IP Address : 35.166.48.97
Note: The above output is for a machine that is used by GeeksforGeeks online compiler, ide.geeksforgeeks.org
This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
marcosarcticseal
Computer Networks
Java
Java
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Types of Network Topology
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Socket Programming in Python
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 423,
"s": 52,
"text": "An IP(Internet Protocol) address is an identifier assigned to each computer and another device (e.g., router, mobile, etc) connected to a TCP/IP network that is used to locate and identify the node in communication with other nodes on the network. IP addresses are usually written and displayed in human-readable notation such as 192.168.1.35 in IPv4(32-bit IP address)."
},
{
"code": null,
"e": 679,
"s": 423,
"text": "An IP address serves two principal functions: host or network interface identification and local addressing. Its role has been characterized as follows: “A name indicates what we seek. An address indicates where it is. A route indicates how to get there.”"
},
{
"code": null,
"e": 866,
"s": 679,
"text": "Prerequisites : Networking in Java | Set 1 (InetAddress class), trim() in Java.InetAddress.getLocalHost() is used to find the private IP addresses used in LAN or any other local network."
},
{
"code": null,
"e": 1018,
"s": 866,
"text": "To find public IP, we use http://bot.whatismyipaddress.com (An online utility to find your public IP), we open the URL, read a line and print the line."
},
{
"code": null,
"e": 1072,
"s": 1018,
"text": "Below is the Java implementation of the above steps. "
},
{
"code": null,
"e": 1077,
"s": 1072,
"text": "Java"
},
{
"code": "// Java program to find IP address of your computer// java.net.InetAddress class provides method to get// IP of any host nameimport java.net.*;import java.io.*;import java.util.*;import java.net.InetAddress; public class JavaProgram{ public static void main(String args[]) throws Exception { // Returns the instance of InetAddress containing // local host name and address InetAddress localhost = InetAddress.getLocalHost(); System.out.println(\"System IP Address : \" + (localhost.getHostAddress()).trim()); // Find public IP address String systemipaddress = \"\"; try { URL url_name = new URL(\"http://bot.whatismyipaddress.com\"); BufferedReader sc = new BufferedReader(new InputStreamReader(url_name.openStream())); // reads system IPAddress systemipaddress = sc.readLine().trim(); } catch (Exception e) { systemipaddress = \"Cannot Execute Properly\"; } System.out.println(\"Public IP Address: \" + systemipaddress +\"\\n\"); }}",
"e": 2188,
"s": 1077,
"text": null
},
{
"code": null,
"e": 2197,
"s": 2188,
"text": "Output: "
},
{
"code": null,
"e": 2263,
"s": 2197,
"text": " System IP Address : 10.0.8.204\n Public IP Address : 35.166.48.97"
},
{
"code": null,
"e": 2372,
"s": 2263,
"text": "Note: The above output is for a machine that is used by GeeksforGeeks online compiler, ide.geeksforgeeks.org"
},
{
"code": null,
"e": 2793,
"s": 2372,
"text": "This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 2810,
"s": 2793,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 2828,
"s": 2810,
"text": "Computer Networks"
},
{
"code": null,
"e": 2833,
"s": 2828,
"text": "Java"
},
{
"code": null,
"e": 2838,
"s": 2833,
"text": "Java"
},
{
"code": null,
"e": 2856,
"s": 2838,
"text": "Computer Networks"
},
{
"code": null,
"e": 2954,
"s": 2856,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2986,
"s": 2954,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 3012,
"s": 2986,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 3042,
"s": 3012,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 3080,
"s": 3042,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 3109,
"s": 3080,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 3124,
"s": 3109,
"text": "Arrays in Java"
},
{
"code": null,
"e": 3160,
"s": 3124,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 3204,
"s": 3160,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 3229,
"s": 3204,
"text": "Reverse a string in Java"
}
] |
Modify a binary tree to get preorder traversal using right pointers only | 27 May, 2022
Given a binary tree. Modify it in such a way that after modification you can have a preorder traversal of it using only the right pointers. During modification, you can use right as well as left pointers. Examples:
Input : 10
/ \
8 2
/ \
3 5
Output : 10
\
8
\
3
\
5
\
2
Explanation : The preorder traversal
of given binary tree is 10 8 3 5 2.
Method 1 (Recursive) One needs to make the right pointer of root point to the left subtree. If the node has just left child, then just moving the child to right will complete the processing for that node. If there is a right child too, then it should be made right child of the right-most of the original left subtree. The above function used in the code process a node and then returns the rightmost node of the transformed subtree.
C++
Java
Python3
C#
Javascript
// C code to modify binary tree for// traversal using only right pointer#include <bits/stdc++.h> using namespace std; // A binary tree node has data,// left child and right childstruct Node { int data; struct Node* left; struct Node* right;}; // function that allocates a new node// with the given data and NULL left// and right pointers.struct Node* newNode(int data){ struct Node* node = new struct Node; node->data = data; node->left = NULL; node->right = NULL; return (node);} // Function to modify treestruct Node* modifytree(struct Node* root){ struct Node* right = root->right; struct Node* rightMost = root; // if the left tree exists if (root->left) { // get the right-most of the // original left subtree rightMost = modifytree(root->left); // set root right to left subtree root->right = root->left; root->left = NULL; } // if the right subtree does // not exists we are done! if (!right) return rightMost; // set right pointer of right-most // of the original left subtree rightMost->right = right; // modify the rightsubtree rightMost = modifytree(right); return rightMost;} // printing using right pointer onlyvoid printpre(struct Node* root){ while (root != NULL) { cout << root->data << " "; root = root->right; }} // Driver program to test above functionsint main(){ /* Constructed binary tree is 10 / \ 8 2 / \ 3 5 */ struct Node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); modifytree(root); printpre(root); return 0;}
// Java code to modify binary tree for// traversal using only right pointerclass GFG{ // A binary tree node has data,// left child and right childstatic class Node{ int data; Node left; Node right;}; // function that allocates a new node// with the given data and null left// and right pointers.static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // Function to modify treestatic Node modifytree( Node root){ Node right = root.right; Node rightMost = root; // if the left tree exists if (root.left != null) { // get the right-most of the // original left subtree rightMost = modifytree(root.left); // set root right to left subtree root.right = root.left; root.left = null; } // if the right subtree does // not exists we are done! if (right == null) return rightMost; // set right pointer of right-most // of the original left subtree rightMost.right = right; // modify the rightsubtree rightMost = modifytree(right); return rightMost;} // printing using right pointer onlystatic void printpre( Node root){ while (root != null) { System.out.print( root.data + " "); root = root.right; }} // Driver cdepublic static void main(String args[]){ /* Constructed binary tree is 10 / \ 8 2 / \ 3 5 */ Node root = newNode(10); root.left = newNode(8); root.right = newNode(2); root.left.left = newNode(3); root.left.right = newNode(5); modifytree(root); printpre(root);}} // This code is contributed by Arnab Kundu
# Python code to modify binary tree for# traversal using only right pointer class newNode(): def __init__(self, data): self.data = data self.left = None self.right = None # Function to modify treedef modifytree(root): right = root.right rightMost = root # if the left tree exists if (root.left): # get the right-most of the # original left subtree rightMost = modifytree(root.left) # set root right to left subtree root.right = root.left root.left = None # if the right subtree does # not exists we are done! if (not right): return rightMost # set right pointer of right-most # of the original left subtree rightMost.right = right # modify the rightsubtree rightMost = modifytree(right) return rightMost # printing using right pointer onlydef printpre(root): while (root != None): print(root.data,end=" ") root = root.right # Driver codeif __name__ == '__main__': """ Constructed binary tree is 10 / \ 8 2 / \ 3 5 """ root = newNode(10) root.left = newNode(8) root.right = newNode(2) root.left.left = newNode(3) root.left.right = newNode(5) modifytree(root) printpre(root) # This code is contributed by SHUBHAMSINGH10
// C# code to modify binary tree for// traversal using only right pointerusing System; class GFG{ // A binary tree node has data,// left child and right childpublic class Node{ public int data; public Node left; public Node right;}; // function that allocates a new node// with the given data and null left// and right pointers.static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // Function to modify treestatic Node modifytree( Node root){ Node right = root.right; Node rightMost = root; // if the left tree exists if (root.left != null) { // get the right-most of the // original left subtree rightMost = modifytree(root.left); // set root right to left subtree root.right = root.left; root.left = null; } // if the right subtree does // not exists we are done! if (right == null) return rightMost; // set right pointer of right-most // of the original left subtree rightMost.right = right; // modify the rightsubtree rightMost = modifytree(right); return rightMost;} // printing using right pointer onlystatic void printpre( Node root){ while (root != null) { Console.Write( root.data + " "); root = root.right; }} // Driver cdepublic static void Main(String []args){ /* Constructed binary tree is 10 / \ 8 2 / \ 3 5 */ Node root = newNode(10); root.left = newNode(8); root.right = newNode(2); root.left.left = newNode(3); root.left.right = newNode(5); modifytree(root); printpre(root);}} // This code is contributed by 29AjayKumar
<script> // JavaScript code to modify binary tree for // traversal using only right pointer // A binary tree node has data, // left child and right child class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // function that allocates a new node // with the given data and null left // and right pointers. function newNode(data) { let node = new Node(data); return (node); } // Function to modify tree function modifytree(root) { let right = root.right; let rightMost = root; // if the left tree exists if (root.left != null) { // get the right-most of the // original left subtree rightMost = modifytree(root.left); // set root right to left subtree root.right = root.left; root.left = null; } // if the right subtree does // not exists we are done! if (right == null) return rightMost; // set right pointer of right-most // of the original left subtree rightMost.right = right; // modify the rightsubtree rightMost = modifytree(right); return rightMost; } // printing using right pointer only function printpre(root) { while (root != null) { document.write( root.data + " "); root = root.right; } } /* Constructed binary tree is 10 / \ 8 2 / \ 3 5 */ let root = newNode(10); root.left = newNode(8); root.right = newNode(2); root.left.left = newNode(3); root.left.right = newNode(5); modifytree(root); printpre(root); </script>
10 8 3 5 2
Time Complexity : O(n)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Auxiliary Space : O(n)
Method 2 (Iterative) This can be easily done using iterative preorder traversal. See here. Iterative preorder traversal The idea is to maintain a variable prev which maintains the previous node of the preorder traversal. Every-time a new node is encountered, the node set its right to previous one and prev is made equal to the current node. In the end we will have a sort of linked list whose first element is root then left child then right, so on and so forth.
C++
Java
Python
C#
Javascript
// C++ code to modify binary tree for// traversal using only right pointer#include <iostream>#include <stack>#include <stdio.h>#include <stdlib.h> using namespace std; // A binary tree node has data,// left child and right childstruct Node { int data; struct Node* left; struct Node* right;}; // Helper function that allocates a new// node with the given data and NULL// left and right pointers.struct Node* newNode(int data){ struct Node* node = new struct Node; node->data = data; node->left = NULL; node->right = NULL; return (node);} // An iterative process to set the right// pointer of Binary treevoid modifytree(struct Node* root){ // Base Case if (root == NULL) return; // Create an empty stack and push root to it stack<Node*> nodeStack; nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ struct Node* pre = NULL; while (nodeStack.empty() == false) { // Pop the top item from stack struct Node* node = nodeStack.top(); nodeStack.pop(); // Push right and left children of // the popped node to stack if (node->right) nodeStack.push(node->right); if (node->left) nodeStack.push(node->left); // check if some previous node exists if (pre != NULL) { // set the right pointer of // previous node to current pre->right = node; } // set previous node as current node pre = node; }} // printing using right pointer onlyvoid printpre(struct Node* root){ while (root != NULL) { cout << root->data << " "; root = root->right; }} // Driver codeint main(){ /* Constructed binary tree is 10 / \ 8 2 / \ 3 5 */ struct Node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); modifytree(root); printpre(root); return 0;}
// Java code to modify binary tree for// traversal using only right pointerimport java.util.*;class GfG { // A binary tree node has data,// left child and right childstatic class Node { int data; Node left; Node right;} // Helper function that allocates a new// node with the given data and NULL// left and right pointers.static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // An iterative process to set the right// pointer of Binary treestatic void modifytree(Node root){ // Base Case if (root == null) return; // Create an empty stack and push root to it Stack<Node> nodeStack = new Stack<Node> (); nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ Node pre = null; while (nodeStack.isEmpty() == false) { // Pop the top item from stack Node node = nodeStack.peek(); nodeStack.pop(); // Push right and left children of // the popped node to stack if (node.right != null) nodeStack.push(node.right); if (node.left != null) nodeStack.push(node.left); // check if some previous node exists if (pre != null) { // set the right pointer of // previous node to current pre.right = node; } // set previous node as current node pre = node; }} // printing using right pointer onlystatic void printpre(Node root){ while (root != null) { System.out.print(root.data + " "); root = root.right; }} // Driver codepublic static void main(String[] args){ /* Constructed binary tree is 10 / \ 8 2 / \ 3 5*/ Node root = newNode(10); root.left = newNode(8); root.right = newNode(2); root.left.left = newNode(3); root.left.right = newNode(5); modifytree(root); printpre(root); }}
# Python code to modify binary tree for# traversal using only right pointer # A binary tree node has data,# left child and right childclass newNode(): def __init__(self, data): self.data = data self.left = None self.right = None # An iterative process to set the right# pointer of Binary treedef modifytree( root): # Base Case if (root == None): return # Create an empty stack and append root to it nodeStack = [] nodeStack.append(root) ''' Pop all items one by one. Do following for every popped item a) print b) append its right child c) append its left child Note that right child is appended first so that left is processed first ''' pre = None while (len(nodeStack)): # Pop the top item from stack node = nodeStack[-1] nodeStack.pop() # append right and left children of # the popped node to stack if (node.right): nodeStack.append(node.right) if (node.left): nodeStack.append(node.left) # check if some previous node exists if (pre != None): # set the right pointer of # previous node to current pre.right = node # set previous node as current node pre = node # printing using right pointer onlydef printpre( root): while (root != None): print(root.data, end = " ") root = root.right # Driver code ''' Constructed binary tree is 10 / \ 8 2/ \ 3 5'''root = newNode(10)root.left = newNode(8)root.right = newNode(2)root.left.left = newNode(3)root.left.right = newNode(5) modifytree(root)printpre(root) # This code is contributed by SHUBHAMSINGH10
// C# code to modify binary tree for// traversal using only right pointerusing System;using System.Collections; class GfG{ // A binary tree node has data,// left child and right childpublic class Node{ public int data; public Node left; public Node right;} // Helper function that allocates a new// node with the given data and NULL// left and right pointers.static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // An iterative process to set the right// pointer of Binary treestatic void modifytree(Node root){ // Base Case if (root == null) return; // Create an empty stack and Push root to it Stack nodeStack = new Stack(); nodeStack.Push(root); /* Pop all items one by one. Do following for every Popped item a) print it b) Push its right child c) Push its left child Note that right child is Pushed first so that left is processed first */ Node pre = null; while (nodeStack.Count !=0) { // Pop the top item from stack Node node = (Node)nodeStack.Peek(); nodeStack.Pop(); // Push right and left children of // the Popped node to stack if (node.right != null) nodeStack.Push(node.right); if (node.left != null) nodeStack.Push(node.left); // check if some previous node exists if (pre != null) { // set the right pointer of // previous node to current pre.right = node; } // set previous node as current node pre = node; }} // printing using right pointer onlystatic void printpre(Node root){ while (root != null) { Console.Write(root.data + " "); root = root.right; }} // Driver codepublic static void Main(String []args){ /* Constructed binary tree is 10 / \ 8 2 / \ 3 5*/ Node root = newNode(10); root.left = newNode(8); root.right = newNode(2); root.left.left = newNode(3); root.left.right = newNode(5); modifytree(root); printpre(root);}} // This code is contributed by// Arnab Kundu
<script> // JavaScript code to modify binary tree for // traversal using only right pointer class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Helper function that allocates a new // node with the given data and NULL // left and right pointers. function newNode(data) { let node = new Node(data); return (node); } // An iterative process to set the right // pointer of Binary tree function modifytree(root) { // Base Case if (root == null) return; // Create an empty stack and push root to it let nodeStack = []; nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ let pre = null; while (nodeStack.length > 0) { // Pop the top item from stack let node = nodeStack[nodeStack.length - 1]; nodeStack.pop(); // Push right and left children of // the popped node to stack if (node.right != null) nodeStack.push(node.right); if (node.left != null) nodeStack.push(node.left); // check if some previous node exists if (pre != null) { // set the right pointer of // previous node to current pre.right = node; } // set previous node as current node pre = node; } } // printing using right pointer only function printpre(root) { while (root != null) { document.write(root.data + " "); root = root.right; } } /* Constructed binary tree is 10 / \ 8 2 / \ 3 5 */ let root = newNode(10); root.left = newNode(8); root.right = newNode(2); root.left.left = newNode(3); root.left.right = newNode(5); modifytree(root); printpre(root); </script>
10 8 3 5 2
Time Complexity : O(n)
Auxiliary Space : O(n)
Modify a binary tree to get preorder traversal using right pointers only | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersModify a binary tree to get preorder traversal using right pointers only | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:41•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=zgmdmqNePio" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
02DCE
prerna saini
andrew1234
SHUBHAMSINGH10
29AjayKumar
Akanksha_Rai
sooda367
decode2207
vaibhavrabadiya117
sweetyty
ranjanrohit840
Stack
Tree
Stack
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Next Greater Element
Program for Tower of Hanoi
Merge Overlapping Intervals
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
Introduction to Tree Data Structure
What is Data Structure: Types, Classifications and Applications | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 271,
"s": 54,
"text": "Given a binary tree. Modify it in such a way that after modification you can have a preorder traversal of it using only the right pointers. During modification, you can use right as well as left pointers. Examples: "
},
{
"code": null,
"e": 592,
"s": 271,
"text": "Input : 10\n / \\\n 8 2\n / \\ \n 3 5 \nOutput : 10\n \\\n 8\n \\ \n 3\n \\\n 5\n \\\n 2\nExplanation : The preorder traversal\nof given binary tree is 10 8 3 5 2."
},
{
"code": null,
"e": 1029,
"s": 594,
"text": "Method 1 (Recursive) One needs to make the right pointer of root point to the left subtree. If the node has just left child, then just moving the child to right will complete the processing for that node. If there is a right child too, then it should be made right child of the right-most of the original left subtree. The above function used in the code process a node and then returns the rightmost node of the transformed subtree. "
},
{
"code": null,
"e": 1033,
"s": 1029,
"text": "C++"
},
{
"code": null,
"e": 1038,
"s": 1033,
"text": "Java"
},
{
"code": null,
"e": 1046,
"s": 1038,
"text": "Python3"
},
{
"code": null,
"e": 1049,
"s": 1046,
"text": "C#"
},
{
"code": null,
"e": 1060,
"s": 1049,
"text": "Javascript"
},
{
"code": "// C code to modify binary tree for// traversal using only right pointer#include <bits/stdc++.h> using namespace std; // A binary tree node has data,// left child and right childstruct Node { int data; struct Node* left; struct Node* right;}; // function that allocates a new node// with the given data and NULL left// and right pointers.struct Node* newNode(int data){ struct Node* node = new struct Node; node->data = data; node->left = NULL; node->right = NULL; return (node);} // Function to modify treestruct Node* modifytree(struct Node* root){ struct Node* right = root->right; struct Node* rightMost = root; // if the left tree exists if (root->left) { // get the right-most of the // original left subtree rightMost = modifytree(root->left); // set root right to left subtree root->right = root->left; root->left = NULL; } // if the right subtree does // not exists we are done! if (!right) return rightMost; // set right pointer of right-most // of the original left subtree rightMost->right = right; // modify the rightsubtree rightMost = modifytree(right); return rightMost;} // printing using right pointer onlyvoid printpre(struct Node* root){ while (root != NULL) { cout << root->data << \" \"; root = root->right; }} // Driver program to test above functionsint main(){ /* Constructed binary tree is 10 / \\ 8 2 / \\ 3 5 */ struct Node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); modifytree(root); printpre(root); return 0;}",
"e": 2797,
"s": 1060,
"text": null
},
{
"code": "// Java code to modify binary tree for// traversal using only right pointerclass GFG{ // A binary tree node has data,// left child and right childstatic class Node{ int data; Node left; Node right;}; // function that allocates a new node// with the given data and null left// and right pointers.static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // Function to modify treestatic Node modifytree( Node root){ Node right = root.right; Node rightMost = root; // if the left tree exists if (root.left != null) { // get the right-most of the // original left subtree rightMost = modifytree(root.left); // set root right to left subtree root.right = root.left; root.left = null; } // if the right subtree does // not exists we are done! if (right == null) return rightMost; // set right pointer of right-most // of the original left subtree rightMost.right = right; // modify the rightsubtree rightMost = modifytree(right); return rightMost;} // printing using right pointer onlystatic void printpre( Node root){ while (root != null) { System.out.print( root.data + \" \"); root = root.right; }} // Driver cdepublic static void main(String args[]){ /* Constructed binary tree is 10 / \\ 8 2 / \\ 3 5 */ Node root = newNode(10); root.left = newNode(8); root.right = newNode(2); root.left.left = newNode(3); root.left.right = newNode(5); modifytree(root); printpre(root);}} // This code is contributed by Arnab Kundu",
"e": 4472,
"s": 2797,
"text": null
},
{
"code": "# Python code to modify binary tree for# traversal using only right pointer class newNode(): def __init__(self, data): self.data = data self.left = None self.right = None # Function to modify treedef modifytree(root): right = root.right rightMost = root # if the left tree exists if (root.left): # get the right-most of the # original left subtree rightMost = modifytree(root.left) # set root right to left subtree root.right = root.left root.left = None # if the right subtree does # not exists we are done! if (not right): return rightMost # set right pointer of right-most # of the original left subtree rightMost.right = right # modify the rightsubtree rightMost = modifytree(right) return rightMost # printing using right pointer onlydef printpre(root): while (root != None): print(root.data,end=\" \") root = root.right # Driver codeif __name__ == '__main__': \"\"\" Constructed binary tree is 10 / \\ 8 2 / \\ 3 5 \"\"\" root = newNode(10) root.left = newNode(8) root.right = newNode(2) root.left.left = newNode(3) root.left.right = newNode(5) modifytree(root) printpre(root) # This code is contributed by SHUBHAMSINGH10",
"e": 5807,
"s": 4472,
"text": null
},
{
"code": "// C# code to modify binary tree for// traversal using only right pointerusing System; class GFG{ // A binary tree node has data,// left child and right childpublic class Node{ public int data; public Node left; public Node right;}; // function that allocates a new node// with the given data and null left// and right pointers.static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // Function to modify treestatic Node modifytree( Node root){ Node right = root.right; Node rightMost = root; // if the left tree exists if (root.left != null) { // get the right-most of the // original left subtree rightMost = modifytree(root.left); // set root right to left subtree root.right = root.left; root.left = null; } // if the right subtree does // not exists we are done! if (right == null) return rightMost; // set right pointer of right-most // of the original left subtree rightMost.right = right; // modify the rightsubtree rightMost = modifytree(right); return rightMost;} // printing using right pointer onlystatic void printpre( Node root){ while (root != null) { Console.Write( root.data + \" \"); root = root.right; }} // Driver cdepublic static void Main(String []args){ /* Constructed binary tree is 10 / \\ 8 2 / \\ 3 5 */ Node root = newNode(10); root.left = newNode(8); root.right = newNode(2); root.left.left = newNode(3); root.left.right = newNode(5); modifytree(root); printpre(root);}} // This code is contributed by 29AjayKumar",
"e": 7516,
"s": 5807,
"text": null
},
{
"code": "<script> // JavaScript code to modify binary tree for // traversal using only right pointer // A binary tree node has data, // left child and right child class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // function that allocates a new node // with the given data and null left // and right pointers. function newNode(data) { let node = new Node(data); return (node); } // Function to modify tree function modifytree(root) { let right = root.right; let rightMost = root; // if the left tree exists if (root.left != null) { // get the right-most of the // original left subtree rightMost = modifytree(root.left); // set root right to left subtree root.right = root.left; root.left = null; } // if the right subtree does // not exists we are done! if (right == null) return rightMost; // set right pointer of right-most // of the original left subtree rightMost.right = right; // modify the rightsubtree rightMost = modifytree(right); return rightMost; } // printing using right pointer only function printpre(root) { while (root != null) { document.write( root.data + \" \"); root = root.right; } } /* Constructed binary tree is 10 / \\ 8 2 / \\ 3 5 */ let root = newNode(10); root.left = newNode(8); root.right = newNode(2); root.left.left = newNode(3); root.left.right = newNode(5); modifytree(root); printpre(root); </script>",
"e": 9314,
"s": 7516,
"text": null
},
{
"code": null,
"e": 9326,
"s": 9314,
"text": "10 8 3 5 2 "
},
{
"code": null,
"e": 9351,
"s": 9328,
"text": "Time Complexity : O(n)"
},
{
"code": null,
"e": 9360,
"s": 9351,
"text": "Chapters"
},
{
"code": null,
"e": 9387,
"s": 9360,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 9437,
"s": 9387,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 9460,
"s": 9437,
"text": "captions off, selected"
},
{
"code": null,
"e": 9468,
"s": 9460,
"text": "English"
},
{
"code": null,
"e": 9492,
"s": 9468,
"text": "This is a modal window."
},
{
"code": null,
"e": 9561,
"s": 9492,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 9583,
"s": 9561,
"text": "End of dialog window."
},
{
"code": null,
"e": 9606,
"s": 9583,
"text": "Auxiliary Space : O(n)"
},
{
"code": null,
"e": 10071,
"s": 9606,
"text": "Method 2 (Iterative) This can be easily done using iterative preorder traversal. See here. Iterative preorder traversal The idea is to maintain a variable prev which maintains the previous node of the preorder traversal. Every-time a new node is encountered, the node set its right to previous one and prev is made equal to the current node. In the end we will have a sort of linked list whose first element is root then left child then right, so on and so forth. "
},
{
"code": null,
"e": 10075,
"s": 10071,
"text": "C++"
},
{
"code": null,
"e": 10080,
"s": 10075,
"text": "Java"
},
{
"code": null,
"e": 10087,
"s": 10080,
"text": "Python"
},
{
"code": null,
"e": 10090,
"s": 10087,
"text": "C#"
},
{
"code": null,
"e": 10101,
"s": 10090,
"text": "Javascript"
},
{
"code": "// C++ code to modify binary tree for// traversal using only right pointer#include <iostream>#include <stack>#include <stdio.h>#include <stdlib.h> using namespace std; // A binary tree node has data,// left child and right childstruct Node { int data; struct Node* left; struct Node* right;}; // Helper function that allocates a new// node with the given data and NULL// left and right pointers.struct Node* newNode(int data){ struct Node* node = new struct Node; node->data = data; node->left = NULL; node->right = NULL; return (node);} // An iterative process to set the right// pointer of Binary treevoid modifytree(struct Node* root){ // Base Case if (root == NULL) return; // Create an empty stack and push root to it stack<Node*> nodeStack; nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ struct Node* pre = NULL; while (nodeStack.empty() == false) { // Pop the top item from stack struct Node* node = nodeStack.top(); nodeStack.pop(); // Push right and left children of // the popped node to stack if (node->right) nodeStack.push(node->right); if (node->left) nodeStack.push(node->left); // check if some previous node exists if (pre != NULL) { // set the right pointer of // previous node to current pre->right = node; } // set previous node as current node pre = node; }} // printing using right pointer onlyvoid printpre(struct Node* root){ while (root != NULL) { cout << root->data << \" \"; root = root->right; }} // Driver codeint main(){ /* Constructed binary tree is 10 / \\ 8 2 / \\ 3 5 */ struct Node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); modifytree(root); printpre(root); return 0;}",
"e": 12303,
"s": 10101,
"text": null
},
{
"code": "// Java code to modify binary tree for// traversal using only right pointerimport java.util.*;class GfG { // A binary tree node has data,// left child and right childstatic class Node { int data; Node left; Node right;} // Helper function that allocates a new// node with the given data and NULL// left and right pointers.static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // An iterative process to set the right// pointer of Binary treestatic void modifytree(Node root){ // Base Case if (root == null) return; // Create an empty stack and push root to it Stack<Node> nodeStack = new Stack<Node> (); nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ Node pre = null; while (nodeStack.isEmpty() == false) { // Pop the top item from stack Node node = nodeStack.peek(); nodeStack.pop(); // Push right and left children of // the popped node to stack if (node.right != null) nodeStack.push(node.right); if (node.left != null) nodeStack.push(node.left); // check if some previous node exists if (pre != null) { // set the right pointer of // previous node to current pre.right = node; } // set previous node as current node pre = node; }} // printing using right pointer onlystatic void printpre(Node root){ while (root != null) { System.out.print(root.data + \" \"); root = root.right; }} // Driver codepublic static void main(String[] args){ /* Constructed binary tree is 10 / \\ 8 2 / \\ 3 5*/ Node root = newNode(10); root.left = newNode(8); root.right = newNode(2); root.left.left = newNode(3); root.left.right = newNode(5); modifytree(root); printpre(root); }}",
"e": 14420,
"s": 12303,
"text": null
},
{
"code": "# Python code to modify binary tree for# traversal using only right pointer # A binary tree node has data,# left child and right childclass newNode(): def __init__(self, data): self.data = data self.left = None self.right = None # An iterative process to set the right# pointer of Binary treedef modifytree( root): # Base Case if (root == None): return # Create an empty stack and append root to it nodeStack = [] nodeStack.append(root) ''' Pop all items one by one. Do following for every popped item a) print b) append its right child c) append its left child Note that right child is appended first so that left is processed first ''' pre = None while (len(nodeStack)): # Pop the top item from stack node = nodeStack[-1] nodeStack.pop() # append right and left children of # the popped node to stack if (node.right): nodeStack.append(node.right) if (node.left): nodeStack.append(node.left) # check if some previous node exists if (pre != None): # set the right pointer of # previous node to current pre.right = node # set previous node as current node pre = node # printing using right pointer onlydef printpre( root): while (root != None): print(root.data, end = \" \") root = root.right # Driver code ''' Constructed binary tree is 10 / \\ 8 2/ \\ 3 5'''root = newNode(10)root.left = newNode(8)root.right = newNode(2)root.left.left = newNode(3)root.left.right = newNode(5) modifytree(root)printpre(root) # This code is contributed by SHUBHAMSINGH10",
"e": 16205,
"s": 14420,
"text": null
},
{
"code": "// C# code to modify binary tree for// traversal using only right pointerusing System;using System.Collections; class GfG{ // A binary tree node has data,// left child and right childpublic class Node{ public int data; public Node left; public Node right;} // Helper function that allocates a new// node with the given data and NULL// left and right pointers.static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // An iterative process to set the right// pointer of Binary treestatic void modifytree(Node root){ // Base Case if (root == null) return; // Create an empty stack and Push root to it Stack nodeStack = new Stack(); nodeStack.Push(root); /* Pop all items one by one. Do following for every Popped item a) print it b) Push its right child c) Push its left child Note that right child is Pushed first so that left is processed first */ Node pre = null; while (nodeStack.Count !=0) { // Pop the top item from stack Node node = (Node)nodeStack.Peek(); nodeStack.Pop(); // Push right and left children of // the Popped node to stack if (node.right != null) nodeStack.Push(node.right); if (node.left != null) nodeStack.Push(node.left); // check if some previous node exists if (pre != null) { // set the right pointer of // previous node to current pre.right = node; } // set previous node as current node pre = node; }} // printing using right pointer onlystatic void printpre(Node root){ while (root != null) { Console.Write(root.data + \" \"); root = root.right; }} // Driver codepublic static void Main(String []args){ /* Constructed binary tree is 10 / \\ 8 2 / \\ 3 5*/ Node root = newNode(10); root.left = newNode(8); root.right = newNode(2); root.left.left = newNode(3); root.left.right = newNode(5); modifytree(root); printpre(root);}} // This code is contributed by// Arnab Kundu",
"e": 18397,
"s": 16205,
"text": null
},
{
"code": "<script> // JavaScript code to modify binary tree for // traversal using only right pointer class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Helper function that allocates a new // node with the given data and NULL // left and right pointers. function newNode(data) { let node = new Node(data); return (node); } // An iterative process to set the right // pointer of Binary tree function modifytree(root) { // Base Case if (root == null) return; // Create an empty stack and push root to it let nodeStack = []; nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ let pre = null; while (nodeStack.length > 0) { // Pop the top item from stack let node = nodeStack[nodeStack.length - 1]; nodeStack.pop(); // Push right and left children of // the popped node to stack if (node.right != null) nodeStack.push(node.right); if (node.left != null) nodeStack.push(node.left); // check if some previous node exists if (pre != null) { // set the right pointer of // previous node to current pre.right = node; } // set previous node as current node pre = node; } } // printing using right pointer only function printpre(root) { while (root != null) { document.write(root.data + \" \"); root = root.right; } } /* Constructed binary tree is 10 / \\ 8 2 / \\ 3 5 */ let root = newNode(10); root.left = newNode(8); root.right = newNode(2); root.left.left = newNode(3); root.left.right = newNode(5); modifytree(root); printpre(root); </script>",
"e": 20622,
"s": 18397,
"text": null
},
{
"code": null,
"e": 20634,
"s": 20622,
"text": "10 8 3 5 2 "
},
{
"code": null,
"e": 20659,
"s": 20636,
"text": "Time Complexity : O(n)"
},
{
"code": null,
"e": 20682,
"s": 20659,
"text": "Auxiliary Space : O(n)"
},
{
"code": null,
"e": 21644,
"s": 20682,
"text": "Modify a binary tree to get preorder traversal using right pointers only | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersModify a binary tree to get preorder traversal using right pointers only | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:41•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=zgmdmqNePio\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 21650,
"s": 21644,
"text": "02DCE"
},
{
"code": null,
"e": 21663,
"s": 21650,
"text": "prerna saini"
},
{
"code": null,
"e": 21674,
"s": 21663,
"text": "andrew1234"
},
{
"code": null,
"e": 21689,
"s": 21674,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 21701,
"s": 21689,
"text": "29AjayKumar"
},
{
"code": null,
"e": 21714,
"s": 21701,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 21723,
"s": 21714,
"text": "sooda367"
},
{
"code": null,
"e": 21734,
"s": 21723,
"text": "decode2207"
},
{
"code": null,
"e": 21753,
"s": 21734,
"text": "vaibhavrabadiya117"
},
{
"code": null,
"e": 21762,
"s": 21753,
"text": "sweetyty"
},
{
"code": null,
"e": 21777,
"s": 21762,
"text": "ranjanrohit840"
},
{
"code": null,
"e": 21783,
"s": 21777,
"text": "Stack"
},
{
"code": null,
"e": 21788,
"s": 21783,
"text": "Tree"
},
{
"code": null,
"e": 21794,
"s": 21788,
"text": "Stack"
},
{
"code": null,
"e": 21799,
"s": 21794,
"text": "Tree"
},
{
"code": null,
"e": 21897,
"s": 21799,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 21929,
"s": 21897,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 21993,
"s": 21929,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 22014,
"s": 21993,
"text": "Next Greater Element"
},
{
"code": null,
"e": 22041,
"s": 22014,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 22069,
"s": 22041,
"text": "Merge Overlapping Intervals"
},
{
"code": null,
"e": 22104,
"s": 22069,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 22133,
"s": 22104,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 22165,
"s": 22133,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 22201,
"s": 22165,
"text": "Introduction to Tree Data Structure"
}
] |
Class getName() method in Java with Examples | 27 Jan, 2022
The getName() method of java.lang.Class class is used to get the name of this entity. This entity can be a class, an array, an interface, etc. The method returns the name of the entity as a String.Syntax:
public String getName()
Parameter: This method does not accept any parameter.Return Value: This method returns the name of the entity as a String.Below programs demonstrate the getName() method.Example 1:
Java
// Java program to demonstrate getName() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the name of myClass // using getName() method System.out.println("Name of myClass: " + myClass.getName()); }}
Class represented by myClass: class Test
Name of myClass: Test
Example 2:
Java
// Java program to demonstrate getName() method public class Test { class Arr { } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for A Class arrClass = Arr.class; // Get the name of arrClass // using getName() method System.out.println("Name of arrClass: " + arrClass.getName()); }}
Name of arrClass: Test$Arr
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getName–
adnanirshad158
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Set in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 235,
"s": 28,
"text": "The getName() method of java.lang.Class class is used to get the name of this entity. This entity can be a class, an array, an interface, etc. The method returns the name of the entity as a String.Syntax: "
},
{
"code": null,
"e": 259,
"s": 235,
"text": "public String getName()"
},
{
"code": null,
"e": 441,
"s": 259,
"text": "Parameter: This method does not accept any parameter.Return Value: This method returns the name of the entity as a String.Below programs demonstrate the getName() method.Example 1: "
},
{
"code": null,
"e": 446,
"s": 441,
"text": "Java"
},
{
"code": "// Java program to demonstrate getName() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the name of myClass // using getName() method System.out.println(\"Name of myClass: \" + myClass.getName()); }}",
"e": 972,
"s": 446,
"text": null
},
{
"code": null,
"e": 1035,
"s": 972,
"text": "Class represented by myClass: class Test\nName of myClass: Test"
},
{
"code": null,
"e": 1049,
"s": 1037,
"text": "Example 2: "
},
{
"code": null,
"e": 1054,
"s": 1049,
"text": "Java"
},
{
"code": "// Java program to demonstrate getName() method public class Test { class Arr { } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for A Class arrClass = Arr.class; // Get the name of arrClass // using getName() method System.out.println(\"Name of arrClass: \" + arrClass.getName()); }}",
"e": 1476,
"s": 1054,
"text": null
},
{
"code": null,
"e": 1503,
"s": 1476,
"text": "Name of arrClass: Test$Arr"
},
{
"code": null,
"e": 1589,
"s": 1505,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getName– "
},
{
"code": null,
"e": 1604,
"s": 1589,
"text": "adnanirshad158"
},
{
"code": null,
"e": 1619,
"s": 1604,
"text": "Java-Functions"
},
{
"code": null,
"e": 1637,
"s": 1619,
"text": "Java-lang package"
},
{
"code": null,
"e": 1653,
"s": 1637,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 1658,
"s": 1653,
"text": "Java"
},
{
"code": null,
"e": 1663,
"s": 1658,
"text": "Java"
},
{
"code": null,
"e": 1761,
"s": 1663,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1812,
"s": 1761,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 1843,
"s": 1812,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 1873,
"s": 1843,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 1891,
"s": 1873,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 1906,
"s": 1891,
"text": "Stream In Java"
},
{
"code": null,
"e": 1926,
"s": 1906,
"text": "Collections in Java"
},
{
"code": null,
"e": 1958,
"s": 1926,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 1982,
"s": 1958,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2002,
"s": 1982,
"text": "Stack Class in Java"
}
] |
\pmatrix - Tex Command | \pmatrix - Used to create matrix enclosed in parentheses.
{ \pmatrix { <math> & <math> ... \cr <repeat as needed> }}
\pmatrix command is used to create matrix enclosed in parentheses; alignment occurs at the ampersands; a double-backslash can be used in place of the \cr; the final \\ or \cr is optional
A = \pmatrix{
a_{11} & a_{12} & \ldots & a_{1n} \cr
a_{21} & a_{22} & \ldots & a_{2n} \cr
\vdots & \vdots & \ddots & \vdots \cr
a_{m1} & a_{m2} & \ldots & a_{mn} \cr
}
A=(a11a12...a1na21a22...a2n⋮⋮⋱⋮am1am2...amn)
A = \pmatrix{
a_{11} & a_{12} & \ldots & a_{1n} \cr
a_{21} & a_{22} & \ldots & a_{2n} \cr
\vdots & \vdots & \ddots & \vdots \cr
a_{m1} & a_{m2} & \ldots & a_{mn} \cr
}
A=(a11a12...a1na21a22...a2n⋮⋮⋱⋮am1am2...amn)
A = \pmatrix{
a_{11} & a_{12} & \ldots & a_{1n} \cr
a_{21} & a_{22} & \ldots & a_{2n} \cr
\vdots & \vdots & \ddots & \vdots \cr
a_{m1} & a_{m2} & \ldots & a_{mn} \cr | [
{
"code": null,
"e": 8178,
"s": 8120,
"text": "\\pmatrix - Used to create matrix enclosed in parentheses."
},
{
"code": null,
"e": 8237,
"s": 8178,
"text": "{ \\pmatrix { <math> & <math> ... \\cr <repeat as needed> }}"
},
{
"code": null,
"e": 8424,
"s": 8237,
"text": "\\pmatrix command is used to create matrix enclosed in parentheses; alignment occurs at the ampersands; a double-backslash can be used in place of the \\cr; the final \\\\ or \\cr is optional"
},
{
"code": null,
"e": 8643,
"s": 8424,
"text": "\nA = \\pmatrix{\na_{11} & a_{12} & \\ldots & a_{1n} \\cr\na_{21} & a_{22} & \\ldots & a_{2n} \\cr\n\\vdots & \\vdots & \\ddots & \\vdots \\cr\na_{m1} & a_{m2} & \\ldots & a_{mn} \\cr\n}\n\n\nA=(a11a12...a1na21a22...a2n⋮⋮⋱⋮am1am2...amn)\n\n\n"
},
{
"code": null,
"e": 8860,
"s": 8643,
"text": "A = \\pmatrix{\na_{11} & a_{12} & \\ldots & a_{1n} \\cr\na_{21} & a_{22} & \\ldots & a_{2n} \\cr\n\\vdots & \\vdots & \\ddots & \\vdots \\cr\na_{m1} & a_{m2} & \\ldots & a_{mn} \\cr\n}\n\n\nA=(a11a12...a1na21a22...a2n⋮⋮⋱⋮am1am2...amn)\n\n"
}
] |
Why Java Interfaces Cannot Have Constructor But Abstract Classes Can Have? | 29 Aug, 2021
Prerequisite: Interface and Abstract class in Java.
A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created.
Why interfaces can not have the constructor?
An Interface is a complete abstraction of class. All data members present in the interface are by default public, static, and final. All the static final fields should be assigned values at the time of declaration, otherwise it will throw compilation error saying “variable variable_Name not initialized in default constructor”.
The methods inside the interface are by default public abstract which means the method implementation cannot be provided by the interface itself, it has to be provided by the implementing class. Therefore, no need of having a constructor inside the interface.
A constructor is used to initializing non-static data members and as there are no non-static data members in the interface, there is no need of constructor
Methods present in the interface are only declared not defined, As there is no implementation of methods, there is no need of making objects for calling methods in the interface and thus no point of having constructor in it.
If we try to create a constructor inside the interface, the compiler will give a compile-time error.
Java
// Java program that demonstrates why// interface can not have a constructor // Creating an interfaceinterface Subtraction { // Creating a method, by default // this is a abstract method int subtract(int a, int b);} // Creating a class that implements// the Subtraction interfaceclass GFG implements Subtraction { // Defining subtract method public int subtract(int a, int b) { int k = a - b; return k; } // Driver Code public static void main(String[] args) { // Creating an instance of // GFG class GFG g = new GFG(); System.out.println(g.subtract(20, 5)); }}
15
In the above program, we have created an interface Subtraction which defines a method subtract(), whose implementation is provided by the class GFG. In order to call a method, we need to create an object, since the methods inside the interface by default public abstract which means the method inside the interface doesn’t have the body. Therefore, there is no need for calling the method in the interface. Since we cannot call the methods in the interface, there is no need for creating the object for interface and there is no need of having a constructor in it.
Why abstract classes have a constructor?
The main purpose of the constructor is to initialize the newly created object. In abstract class, we have an instance variable, abstract methods, and non-abstract methods. We need to initialize the non-abstract methods and instance variables, therefore abstract classes have a constructor.
Also, even if we don’t provide any constructor the compiler will add default constructor in an abstract class.
An abstract class can be inherited by any number of sub-classes, thus functionality of constructor present in abstract class can be used by them.
The constructor inside the abstract class can only be called during constructor chaining i.e. when we create an instance of sub-classes. This is also one of the reasons abstract class can have a constructor.
Java
// A Java program to demonstrates// an abstract class with constructors // Creating an abstract class Carabstract class Car { // Creating a constructor in // the abstract class Car() { System.out.println("car is created"); }} // A class that extends the// abstract class Carclass Maruti extends Car { // Method defining inside // the Maruti class void run() { System.out.println("Maruti is running"); }} class GFG { public static void main(String[] args) { Maruti c = new Maruti(); c.run(); }}
car is created
Maruti is running
simmytarika5
sweetyty
Java-Abstract Class and Interface
java-interfaces
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Set in Java
Introduction to Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Aug, 2021"
},
{
"code": null,
"e": 104,
"s": 52,
"text": "Prerequisite: Interface and Abstract class in Java."
},
{
"code": null,
"e": 257,
"s": 104,
"text": "A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created."
},
{
"code": null,
"e": 302,
"s": 257,
"text": "Why interfaces can not have the constructor?"
},
{
"code": null,
"e": 631,
"s": 302,
"text": "An Interface is a complete abstraction of class. All data members present in the interface are by default public, static, and final. All the static final fields should be assigned values at the time of declaration, otherwise it will throw compilation error saying “variable variable_Name not initialized in default constructor”."
},
{
"code": null,
"e": 891,
"s": 631,
"text": "The methods inside the interface are by default public abstract which means the method implementation cannot be provided by the interface itself, it has to be provided by the implementing class. Therefore, no need of having a constructor inside the interface."
},
{
"code": null,
"e": 1047,
"s": 891,
"text": "A constructor is used to initializing non-static data members and as there are no non-static data members in the interface, there is no need of constructor"
},
{
"code": null,
"e": 1272,
"s": 1047,
"text": "Methods present in the interface are only declared not defined, As there is no implementation of methods, there is no need of making objects for calling methods in the interface and thus no point of having constructor in it."
},
{
"code": null,
"e": 1373,
"s": 1272,
"text": "If we try to create a constructor inside the interface, the compiler will give a compile-time error."
},
{
"code": null,
"e": 1378,
"s": 1373,
"text": "Java"
},
{
"code": "// Java program that demonstrates why// interface can not have a constructor // Creating an interfaceinterface Subtraction { // Creating a method, by default // this is a abstract method int subtract(int a, int b);} // Creating a class that implements// the Subtraction interfaceclass GFG implements Subtraction { // Defining subtract method public int subtract(int a, int b) { int k = a - b; return k; } // Driver Code public static void main(String[] args) { // Creating an instance of // GFG class GFG g = new GFG(); System.out.println(g.subtract(20, 5)); }}",
"e": 2019,
"s": 1378,
"text": null
},
{
"code": null,
"e": 2022,
"s": 2019,
"text": "15"
},
{
"code": null,
"e": 2587,
"s": 2022,
"text": "In the above program, we have created an interface Subtraction which defines a method subtract(), whose implementation is provided by the class GFG. In order to call a method, we need to create an object, since the methods inside the interface by default public abstract which means the method inside the interface doesn’t have the body. Therefore, there is no need for calling the method in the interface. Since we cannot call the methods in the interface, there is no need for creating the object for interface and there is no need of having a constructor in it."
},
{
"code": null,
"e": 2629,
"s": 2587,
"text": "Why abstract classes have a constructor? "
},
{
"code": null,
"e": 2919,
"s": 2629,
"text": "The main purpose of the constructor is to initialize the newly created object. In abstract class, we have an instance variable, abstract methods, and non-abstract methods. We need to initialize the non-abstract methods and instance variables, therefore abstract classes have a constructor."
},
{
"code": null,
"e": 3030,
"s": 2919,
"text": "Also, even if we don’t provide any constructor the compiler will add default constructor in an abstract class."
},
{
"code": null,
"e": 3176,
"s": 3030,
"text": "An abstract class can be inherited by any number of sub-classes, thus functionality of constructor present in abstract class can be used by them."
},
{
"code": null,
"e": 3384,
"s": 3176,
"text": "The constructor inside the abstract class can only be called during constructor chaining i.e. when we create an instance of sub-classes. This is also one of the reasons abstract class can have a constructor."
},
{
"code": null,
"e": 3389,
"s": 3384,
"text": "Java"
},
{
"code": "// A Java program to demonstrates// an abstract class with constructors // Creating an abstract class Carabstract class Car { // Creating a constructor in // the abstract class Car() { System.out.println(\"car is created\"); }} // A class that extends the// abstract class Carclass Maruti extends Car { // Method defining inside // the Maruti class void run() { System.out.println(\"Maruti is running\"); }} class GFG { public static void main(String[] args) { Maruti c = new Maruti(); c.run(); }}",
"e": 3935,
"s": 3389,
"text": null
},
{
"code": null,
"e": 3968,
"s": 3935,
"text": "car is created\nMaruti is running"
},
{
"code": null,
"e": 3983,
"s": 3970,
"text": "simmytarika5"
},
{
"code": null,
"e": 3992,
"s": 3983,
"text": "sweetyty"
},
{
"code": null,
"e": 4026,
"s": 3992,
"text": "Java-Abstract Class and Interface"
},
{
"code": null,
"e": 4042,
"s": 4026,
"text": "java-interfaces"
},
{
"code": null,
"e": 4047,
"s": 4042,
"text": "Java"
},
{
"code": null,
"e": 4052,
"s": 4047,
"text": "Java"
},
{
"code": null,
"e": 4150,
"s": 4052,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4181,
"s": 4150,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 4211,
"s": 4181,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 4229,
"s": 4211,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 4244,
"s": 4229,
"text": "Stream In Java"
},
{
"code": null,
"e": 4264,
"s": 4244,
"text": "Collections in Java"
},
{
"code": null,
"e": 4296,
"s": 4264,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 4320,
"s": 4296,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 4340,
"s": 4320,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 4352,
"s": 4340,
"text": "Set in Java"
}
] |
How to Sort data by Column in a CSV File in Python ? | 06 Jun, 2021
In this article, we will discuss how to sort CSV by column(s) using Python.
Method 1: Using sort_values()
We can take the header name as per our requirement, the axis can be either 0 or 1, where 0 means ‘rows’ and ‘1’ means ‘column’. Ascending can be either True/False and if True, it gets arranged in ascending order, if False, it gets arranged in descending order.
Syntax: DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)
CSV File Used:
Below are various which depict various ways to sort a CSV dataset.
Example 1: Sorting the dataset in descending order on the basis of salary
Python3
# importing pandas packageimport pandas as pandasForSortingCSV # assign datasetcsvData = pandasForSortingCSV.read_csv("sample.csv") # displaying unsorted data frameprint("\nBefore sorting:")print(csvData) # sort data framecsvData.sort_values(["Salary"], axis=0, ascending=[False], inplace=True) # displaying sorted data frameprint("\nAfter sorting:")print(csvData)
Output:
Example 2: Sorting the dataset in default (ascending) order on the basis of salary.
Python3
# importing pandas packageimport pandas as pandasForSortingCSV # assign datasetcsvData = pandasForSortingCSV.read_csv("sample.csv") # displaying unsorted data frameprint("\nBefore sorting:")print(csvData) # sort data framecsvData.sort_values(csvData.columns[4], axis=0, inplace=True) # displaying sorted data frameprint("\nAfter sorting:")print(csvData)
Output:
Example 3: Sorting the dataset on the basis of Name, Age and, Height in ascending order.
Python3
# importing pandas packageimport pandas as pandasForSortingCSV # assign datasetcsvData = pandasForSortingCSV.read_csv("sample.csv") # displaying unsorted data frameprint("\nBefore sorting:")print(csvData) # sort data framecsvData.sort_values(["Name", "Age", "Height"], axis=0, ascending=[True, True, True], inplace=True) # displaying sorted data frameprint("\nAfter sorting:")print(csvData)
Output:
Example 4: Sorting the dataset on the basis of Salary in descending order and Age in ascending order.
Python3
# importing pandas packageimport pandas as pandasForSortingCSV # assign datasetcsvData = pandasForSortingCSV.read_csv("sample.csv") # displaying unsorted data frameprint("\nBefore sorting:")print(csvData) # sort data framecsvData.sort_values([csvData.columns[4], csvData.columns[2]], axis=0, ascending=[False, True], inplace=True) # displaying sorted data frameprint("\nAfter sorting:")print(csvData)
Output:
Method 2: Using sorted()
Another way of sorting CSV files is by using the sorted() method on the CSV module object. However, it can only sort CSV files based on only one column.
Syntax:
sorted(iterable, key, reverse)
Below are various which depict various ways to sort a CSV dataset.
Example 1: Sorting the dataset in ascending order on the basis of Age.
Python3
# import modules import csv ,operator # load csv filedata = csv.reader(open('sample.csv'),delimiter=',') # sort data on the basis of agedata = sorted(data, key=operator.itemgetter(2)) # displaying sorted data print('After sorting:')display(data)
Output:
Example 2: Sorting the dataset in descending order on the basis of Age.
Python3
# import modules import csv ,operator # load csv filedata = csv.reader(open('sample.csv'),delimiter=',') # sort data on the basis of agedata = sorted(data, key=operator.itemgetter(2), reverse=True) # displaying sorted data print('After sorting:')display(data)
Output:
Picked
python-csv
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 104,
"s": 28,
"text": "In this article, we will discuss how to sort CSV by column(s) using Python."
},
{
"code": null,
"e": 134,
"s": 104,
"text": "Method 1: Using sort_values()"
},
{
"code": null,
"e": 395,
"s": 134,
"text": "We can take the header name as per our requirement, the axis can be either 0 or 1, where 0 means ‘rows’ and ‘1’ means ‘column’. Ascending can be either True/False and if True, it gets arranged in ascending order, if False, it gets arranged in descending order."
},
{
"code": null,
"e": 506,
"s": 395,
"text": "Syntax: DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)"
},
{
"code": null,
"e": 521,
"s": 506,
"text": "CSV File Used:"
},
{
"code": null,
"e": 588,
"s": 521,
"text": "Below are various which depict various ways to sort a CSV dataset."
},
{
"code": null,
"e": 662,
"s": 588,
"text": "Example 1: Sorting the dataset in descending order on the basis of salary"
},
{
"code": null,
"e": 670,
"s": 662,
"text": "Python3"
},
{
"code": "# importing pandas packageimport pandas as pandasForSortingCSV # assign datasetcsvData = pandasForSortingCSV.read_csv(\"sample.csv\") # displaying unsorted data frameprint(\"\\nBefore sorting:\")print(csvData) # sort data framecsvData.sort_values([\"Salary\"], axis=0, ascending=[False], inplace=True) # displaying sorted data frameprint(\"\\nAfter sorting:\")print(csvData)",
"e": 1137,
"s": 670,
"text": null
},
{
"code": null,
"e": 1145,
"s": 1137,
"text": "Output:"
},
{
"code": null,
"e": 1229,
"s": 1145,
"text": "Example 2: Sorting the dataset in default (ascending) order on the basis of salary."
},
{
"code": null,
"e": 1237,
"s": 1229,
"text": "Python3"
},
{
"code": "# importing pandas packageimport pandas as pandasForSortingCSV # assign datasetcsvData = pandasForSortingCSV.read_csv(\"sample.csv\") # displaying unsorted data frameprint(\"\\nBefore sorting:\")print(csvData) # sort data framecsvData.sort_values(csvData.columns[4], axis=0, inplace=True) # displaying sorted data frameprint(\"\\nAfter sorting:\")print(csvData)",
"e": 1673,
"s": 1237,
"text": null
},
{
"code": null,
"e": 1681,
"s": 1673,
"text": "Output:"
},
{
"code": null,
"e": 1770,
"s": 1681,
"text": "Example 3: Sorting the dataset on the basis of Name, Age and, Height in ascending order."
},
{
"code": null,
"e": 1778,
"s": 1770,
"text": "Python3"
},
{
"code": "# importing pandas packageimport pandas as pandasForSortingCSV # assign datasetcsvData = pandasForSortingCSV.read_csv(\"sample.csv\") # displaying unsorted data frameprint(\"\\nBefore sorting:\")print(csvData) # sort data framecsvData.sort_values([\"Name\", \"Age\", \"Height\"], axis=0, ascending=[True, True, True], inplace=True) # displaying sorted data frameprint(\"\\nAfter sorting:\")print(csvData)",
"e": 2271,
"s": 1778,
"text": null
},
{
"code": null,
"e": 2279,
"s": 2271,
"text": "Output:"
},
{
"code": null,
"e": 2381,
"s": 2279,
"text": "Example 4: Sorting the dataset on the basis of Salary in descending order and Age in ascending order."
},
{
"code": null,
"e": 2389,
"s": 2381,
"text": "Python3"
},
{
"code": "# importing pandas packageimport pandas as pandasForSortingCSV # assign datasetcsvData = pandasForSortingCSV.read_csv(\"sample.csv\") # displaying unsorted data frameprint(\"\\nBefore sorting:\")print(csvData) # sort data framecsvData.sort_values([csvData.columns[4], csvData.columns[2]], axis=0, ascending=[False, True], inplace=True) # displaying sorted data frameprint(\"\\nAfter sorting:\")print(csvData)",
"e": 2851,
"s": 2389,
"text": null
},
{
"code": null,
"e": 2859,
"s": 2851,
"text": "Output:"
},
{
"code": null,
"e": 2884,
"s": 2859,
"text": "Method 2: Using sorted()"
},
{
"code": null,
"e": 3037,
"s": 2884,
"text": "Another way of sorting CSV files is by using the sorted() method on the CSV module object. However, it can only sort CSV files based on only one column."
},
{
"code": null,
"e": 3046,
"s": 3037,
"text": "Syntax: "
},
{
"code": null,
"e": 3077,
"s": 3046,
"text": "sorted(iterable, key, reverse)"
},
{
"code": null,
"e": 3144,
"s": 3077,
"text": "Below are various which depict various ways to sort a CSV dataset."
},
{
"code": null,
"e": 3215,
"s": 3144,
"text": "Example 1: Sorting the dataset in ascending order on the basis of Age."
},
{
"code": null,
"e": 3223,
"s": 3215,
"text": "Python3"
},
{
"code": "# import modules import csv ,operator # load csv filedata = csv.reader(open('sample.csv'),delimiter=',') # sort data on the basis of agedata = sorted(data, key=operator.itemgetter(2)) # displaying sorted data print('After sorting:')display(data)",
"e": 3476,
"s": 3223,
"text": null
},
{
"code": null,
"e": 3484,
"s": 3476,
"text": "Output:"
},
{
"code": null,
"e": 3556,
"s": 3484,
"text": "Example 2: Sorting the dataset in descending order on the basis of Age."
},
{
"code": null,
"e": 3564,
"s": 3556,
"text": "Python3"
},
{
"code": "# import modules import csv ,operator # load csv filedata = csv.reader(open('sample.csv'),delimiter=',') # sort data on the basis of agedata = sorted(data, key=operator.itemgetter(2), reverse=True) # displaying sorted data print('After sorting:')display(data)",
"e": 3831,
"s": 3564,
"text": null
},
{
"code": null,
"e": 3839,
"s": 3831,
"text": "Output:"
},
{
"code": null,
"e": 3846,
"s": 3839,
"text": "Picked"
},
{
"code": null,
"e": 3857,
"s": 3846,
"text": "python-csv"
},
{
"code": null,
"e": 3864,
"s": 3857,
"text": "Python"
}
] |
Pascal - Basic Syntax | You have seen a basic structure of pascal program, so it will be easy to understand other basic building blocks of the pascal programming language.
A variable definition is put in a block beginning with a var keyword, followed by definitions of the variables as follows:
var
A_Variable, B_Variable ... : Variable_Type;
Pascal variables are declared outside the code-body of the function which means they are not declared within the begin and end pairs, but they are declared after the definition of the procedure/function and before the begin keyword. For global variables, they are defined after the program header.
In Pascal, a procedure is set of instructions to be executed, with no return value and a function is a procedure with a return value. The definition of function/procedures will be as follows −
Function Func_Name(params...) : Return_Value;
Procedure Proc_Name(params...);
The multiline comments are enclosed within curly brackets and asterisks as (* ... *). Pascal allows single-line comment enclosed within curly brackets { ... }.
(* This is a multi-line comments
and it will span multiple lines. *)
{ This is a single line comment in pascal }
Pascal is a case non-sensitive language, which means you can write your variables, functions and procedure in either case. Like variables A_Variable, a_variable and A_VARIABLE have same meaning in Pascal.
Pascal programs are made of statements. Each statement specifies a definite job of the program. These jobs could be declaration, assignment, reading data, writing data, taking logical decisions, transferring program flow control, etc.
For example −
readln (a, b, c);
s := (a + b + c)/2.0;
area := sqrt(s * (s - a)*(s-b)*(s-c));
writeln(area);
The statements in Pascal are designed with some specific Pascal words, which are called the reserved words. For example, the words, program, input, output, var, real, begin, readline, writeline and end are all reserved words.
Following is a list of reserved words available in Pascal.
The Pascal character set consists of −
All upper case letters (A-Z)
All upper case letters (A-Z)
All lower case letters (a-z)
All lower case letters (a-z)
All digits (0-9)
All digits (0-9)
Special symbols - + * / := , . ;. () [] = {} ` white space
Special symbols - + * / := , . ;. () [] = {} ` white space
The entities in a Pascal program like variables and constants, types, functions, procedures and records, etc., have a name or identifier. An identifier is a sequence of letters and digits, beginning with a letter. Special symbols and blanks must not be used in an identifier.
94 Lectures
8.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2231,
"s": 2083,
"text": "You have seen a basic structure of pascal program, so it will be easy to understand other basic building blocks of the pascal programming language."
},
{
"code": null,
"e": 2354,
"s": 2231,
"text": "A variable definition is put in a block beginning with a var keyword, followed by definitions of the variables as follows:"
},
{
"code": null,
"e": 2402,
"s": 2354,
"text": "var\nA_Variable, B_Variable ... : Variable_Type;"
},
{
"code": null,
"e": 2700,
"s": 2402,
"text": "Pascal variables are declared outside the code-body of the function which means they are not declared within the begin and end pairs, but they are declared after the definition of the procedure/function and before the begin keyword. For global variables, they are defined after the program header."
},
{
"code": null,
"e": 2893,
"s": 2700,
"text": "In Pascal, a procedure is set of instructions to be executed, with no return value and a function is a procedure with a return value. The definition of function/procedures will be as follows −"
},
{
"code": null,
"e": 2971,
"s": 2893,
"text": "Function Func_Name(params...) : Return_Value;\nProcedure Proc_Name(params...);"
},
{
"code": null,
"e": 3132,
"s": 2971,
"text": "The multiline comments are enclosed within curly brackets and asterisks as (* ... *). Pascal allows single-line comment enclosed within curly brackets { ... }. "
},
{
"code": null,
"e": 3249,
"s": 3132,
"text": "(* This is a multi-line comments\n and it will span multiple lines. *)\n\n{ This is a single line comment in pascal }"
},
{
"code": null,
"e": 3454,
"s": 3249,
"text": "Pascal is a case non-sensitive language, which means you can write your variables, functions and procedure in either case. Like variables A_Variable, a_variable and A_VARIABLE have same meaning in Pascal."
},
{
"code": null,
"e": 3689,
"s": 3454,
"text": "Pascal programs are made of statements. Each statement specifies a definite job of the program. These jobs could be declaration, assignment, reading data, writing data, taking logical decisions, transferring program flow control, etc."
},
{
"code": null,
"e": 3703,
"s": 3689,
"text": "For example −"
},
{
"code": null,
"e": 3805,
"s": 3703,
"text": "readln (a, b, c);\ns := (a + b + c)/2.0;\narea := sqrt(s * (s - a)*(s-b)*(s-c));\nwriteln(area); "
},
{
"code": null,
"e": 4031,
"s": 3805,
"text": "The statements in Pascal are designed with some specific Pascal words, which are called the reserved words. For example, the words, program, input, output, var, real, begin, readline, writeline and end are all reserved words."
},
{
"code": null,
"e": 4090,
"s": 4031,
"text": "Following is a list of reserved words available in Pascal."
},
{
"code": null,
"e": 4129,
"s": 4090,
"text": "The Pascal character set consists of −"
},
{
"code": null,
"e": 4158,
"s": 4129,
"text": "All upper case letters (A-Z)"
},
{
"code": null,
"e": 4187,
"s": 4158,
"text": "All upper case letters (A-Z)"
},
{
"code": null,
"e": 4216,
"s": 4187,
"text": "All lower case letters (a-z)"
},
{
"code": null,
"e": 4245,
"s": 4216,
"text": "All lower case letters (a-z)"
},
{
"code": null,
"e": 4262,
"s": 4245,
"text": "All digits (0-9)"
},
{
"code": null,
"e": 4279,
"s": 4262,
"text": "All digits (0-9)"
},
{
"code": null,
"e": 4340,
"s": 4279,
"text": "Special symbols - + * / := , . ;. () [] = {} ` white space"
},
{
"code": null,
"e": 4401,
"s": 4340,
"text": "Special symbols - + * / := , . ;. () [] = {} ` white space"
},
{
"code": null,
"e": 4678,
"s": 4401,
"text": "The entities in a Pascal program like variables and constants, types, functions, procedures and records, etc., have a name or identifier. An identifier is a sequence of letters and digits, beginning with a letter. Special symbols and blanks must not be used in an identifier."
},
{
"code": null,
"e": 4713,
"s": 4678,
"text": "\n 94 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4736,
"s": 4713,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 4743,
"s": 4736,
"text": " Print"
},
{
"code": null,
"e": 4754,
"s": 4743,
"text": " Add Notes"
}
] |
Explain else-if ladder statement in C language | This is the most general way of writing a multi-way decision.
Refer the syntax given below −
if (condition1)
stmt1;
else if (condition2)
stmt2;
- - - - -
- - - - -
else if (condition n)
stmtn;
else
stmt x;
Refer the algorithm given below −
START
Step 1: Declare int variables.
Step 2: Read a,b,c,d values at runtime
Step 3: i. if(a>b && a>c && a>d)
Print a is largest
ii.else if(b>c && b>a && b>d)
Print b is largest
iii. else if(c>d && c>a && c>b)
Print c is largest
iv. else
print d is largest
STOP
Following is the C program to execute Else If Ladder conditional operators −
Live Demo
#include<stdio.h>
void main (){
int a,b,c,d;
printf("Enter the values of a,b,c,d: ");
scanf("%d%d%d%d",&a,&b,&c,&d);
if(a>b && a>c && a>d){
printf("%d is the largest",a);
}else if(b>c && b>a && b>d){
printf("%d is the largest",b);
}else if(c>d && c>a && c>b){
printf("%d is the largest",c);
}else{
printf("%d is the largest",d);
}
}
You will see the following output −
Run 1:Enter the values of a,b,c,d: 2 4 6 8
8 is the largest
Run 2: Enter the values of a,b,c,d: 23 12 56 23
56 is the largest
Consider another C program which display the grade of student using else if ladder −
Live Demo
#include<stdio.h>
int main(){
int marks;
printf("Enter the marks of a student:\n");
scanf("%d",&marks);
if(marks <=100 && marks >= 90)
printf("Grade=A");
else if(marks < 90 && marks>= 80)
printf("Grade=B");
else if(marks < 80 && marks >= 70)
printf("Grade=C");
else if(marks < 70 && marks >= 60)
printf("Grade=D");
else if(marks < 60 && marks > 50)
printf("Grade=E");
else if(marks == 50)
printf("Grade=F");
else if(marks < 50 && marks >= 0)
printf("Fail");
else
printf("Enter a valid score between 0 and 100");
return 0;
}
You will see the following output −
Run 1:
Enter the marks of a student:78
Grade=C
Run 2:
Enter the marks of a student:98
Grade=A | [
{
"code": null,
"e": 1124,
"s": 1062,
"text": "This is the most general way of writing a multi-way decision."
},
{
"code": null,
"e": 1155,
"s": 1124,
"text": "Refer the syntax given below −"
},
{
"code": null,
"e": 1268,
"s": 1155,
"text": "if (condition1)\nstmt1;\nelse if (condition2)\nstmt2;\n- - - - -\n- - - - -\nelse if (condition n)\nstmtn;\nelse\nstmt x;"
},
{
"code": null,
"e": 1302,
"s": 1268,
"text": "Refer the algorithm given below −"
},
{
"code": null,
"e": 1563,
"s": 1302,
"text": "START\nStep 1: Declare int variables.\nStep 2: Read a,b,c,d values at runtime\nStep 3: i. if(a>b && a>c && a>d)\nPrint a is largest\nii.else if(b>c && b>a && b>d)\nPrint b is largest\niii. else if(c>d && c>a && c>b)\nPrint c is largest\niv. else\nprint d is largest\nSTOP"
},
{
"code": null,
"e": 1640,
"s": 1563,
"text": "Following is the C program to execute Else If Ladder conditional operators −"
},
{
"code": null,
"e": 1651,
"s": 1640,
"text": " Live Demo"
},
{
"code": null,
"e": 2032,
"s": 1651,
"text": "#include<stdio.h>\nvoid main (){\n int a,b,c,d;\n printf(\"Enter the values of a,b,c,d: \");\n scanf(\"%d%d%d%d\",&a,&b,&c,&d);\n if(a>b && a>c && a>d){\n printf(\"%d is the largest\",a);\n }else if(b>c && b>a && b>d){\n printf(\"%d is the largest\",b);\n }else if(c>d && c>a && c>b){\n printf(\"%d is the largest\",c);\n }else{\n printf(\"%d is the largest\",d);\n }\n}"
},
{
"code": null,
"e": 2068,
"s": 2032,
"text": "You will see the following output −"
},
{
"code": null,
"e": 2194,
"s": 2068,
"text": "Run 1:Enter the values of a,b,c,d: 2 4 6 8\n8 is the largest\nRun 2: Enter the values of a,b,c,d: 23 12 56 23\n56 is the largest"
},
{
"code": null,
"e": 2279,
"s": 2194,
"text": "Consider another C program which display the grade of student using else if ladder −"
},
{
"code": null,
"e": 2290,
"s": 2279,
"text": " Live Demo"
},
{
"code": null,
"e": 2898,
"s": 2290,
"text": "#include<stdio.h>\nint main(){\n int marks;\n printf(\"Enter the marks of a student:\\n\");\n scanf(\"%d\",&marks);\n if(marks <=100 && marks >= 90)\n printf(\"Grade=A\");\n else if(marks < 90 && marks>= 80)\n printf(\"Grade=B\");\n else if(marks < 80 && marks >= 70)\n printf(\"Grade=C\");\n else if(marks < 70 && marks >= 60)\n printf(\"Grade=D\");\n else if(marks < 60 && marks > 50)\n printf(\"Grade=E\");\n else if(marks == 50)\n printf(\"Grade=F\");\n else if(marks < 50 && marks >= 0)\n printf(\"Fail\");\n else\n printf(\"Enter a valid score between 0 and 100\");\n return 0;\n}"
},
{
"code": null,
"e": 2934,
"s": 2898,
"text": "You will see the following output −"
},
{
"code": null,
"e": 3028,
"s": 2934,
"text": "Run 1:\nEnter the marks of a student:78\nGrade=C\nRun 2:\nEnter the marks of a student:98\nGrade=A"
}
] |
Can we extend interfaces in Java? Explain? | An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.
Just like classes you can extend one interface from another using the extends keyword as shown below −
interface ArithmeticCalculations{
public abstract int addition(int a, int b);
public abstract int subtraction(int a, int b);
}
interface MathCalculations extends ArithmeticCalculations{
public abstract double squareRoot(int a);
public abstract double powerOf(int a, int b);
}
But, when you implement the sub-class you need to provide body for the abstract methods in both interfaces.
In the following example we have created two interfaces − ArithmeticCalculations with two abstract methods (addition and subtraction) and, MathCalculations where,
Live Demo
import java.util.Scanner;
interface ArithmeticCalculations{
public abstract int addition(int a, int b);
public abstract int subtraction(int a, int b);
}
interface MathCalculations extends ArithmeticCalculations{
public abstract double squareRoot(int a);
public abstract double powerOf(int a, int b);
}
public class ExtendingInterfaceExample implements MathCalculations{
public int addition(int a, int b) {
return a+b;
}
public int subtraction(int a, int b) {
return a-b;
}
public double squareRoot(int a) {
return Math.sqrt(a);
}
public double powerOf(int a, int b) {
return Math.pow(a, b);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of a: ");
int a = sc.nextInt();
System.out.println("Enter the value of b: ");
int b = sc.nextInt();
ExtendingInterfaceExample obj = new ExtendingInterfaceExample();
System.out.println("Result of addition: "+obj.addition(a, b));
System.out.println("Result of subtraction: "+obj.subtraction(a, b));
System.out.println("Square root of "+a+" is: "+obj.squareRoot(a));
System.out.println(a+"^"+b+" value is: "+obj.powerOf(a, b));
}
}
Enter the value of a:
4
Enter the value of b:
3
Result of addition: 7
Result of subtraction: 1
Square root of 4 is: 2.0
4^3 value is: 64.0
In the same way you can extend multiple interfaces from an interface using the extends keyword, by separating the interfaces using comma (,) as −
interface MyInterface extends ArithmeticCalculations, MathCalculations{
Following is the Java program demonstrating, how to extend multiple interfaces from a single interface.
interface ArithmeticCalculations{
public abstract int addition(int a, int b);
public abstract int subtraction(int a, int b);
}
interface MathCalculations {
public abstract double squareRoot(int a);
public abstract double powerOf(int a, int b);
}
interface MyInterface extends MathCalculations, ArithmeticCalculations {
public void displayResults();
}
public class ExtendingInterfaceExample implements MyInterface {
public int addition(int a, int b) {
return a+b;
}
public int subtraction(int a, int b) {
return a-b;
}
public double squareRoot(int a) {
return Math.sqrt(a);
}
public double powerOf(int a, int b) {
return Math.pow(a, b);
}
public void displayResults(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of a: ");
int a = sc.nextInt();
System.out.println("Enter the value of b: ");
int b = sc.nextInt();
ExtendingInterfaceExample obj = new ExtendingInterfaceExample();
System.out.println("Result of addition: "+obj.addition(a, b));
System.out.println("Result of subtraction: "+obj.subtraction(a, b));
System.out.println("Square root of "+a+" is: "+obj.squareRoot(a));
System.out.println(a+"^"+b+" value is: "+obj.powerOf(a, b));
}
public static void main(String args[]){
new ExtendingInterfaceExample().displayResults();
}
}
Enter the value of a:
4
Enter the value of b:
3
Result of addition: 7
Result of subtraction: 1
Square root of 4 is: 2.0
4^3 value is: 64.0 | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static."
},
{
"code": null,
"e": 1284,
"s": 1181,
"text": "Just like classes you can extend one interface from another using the extends keyword as shown below −"
},
{
"code": null,
"e": 1572,
"s": 1284,
"text": "interface ArithmeticCalculations{\n public abstract int addition(int a, int b);\n public abstract int subtraction(int a, int b);\n}\ninterface MathCalculations extends ArithmeticCalculations{\n public abstract double squareRoot(int a);\n public abstract double powerOf(int a, int b);\n}"
},
{
"code": null,
"e": 1680,
"s": 1572,
"text": "But, when you implement the sub-class you need to provide body for the abstract methods in both interfaces."
},
{
"code": null,
"e": 1843,
"s": 1680,
"text": "In the following example we have created two interfaces − ArithmeticCalculations with two abstract methods (addition and subtraction) and, MathCalculations where,"
},
{
"code": null,
"e": 1854,
"s": 1843,
"text": " Live Demo"
},
{
"code": null,
"e": 3115,
"s": 1854,
"text": "import java.util.Scanner;\ninterface ArithmeticCalculations{\n public abstract int addition(int a, int b);\n public abstract int subtraction(int a, int b);\n}\ninterface MathCalculations extends ArithmeticCalculations{\n public abstract double squareRoot(int a);\n public abstract double powerOf(int a, int b);\n}\npublic class ExtendingInterfaceExample implements MathCalculations{\n public int addition(int a, int b) {\n return a+b;\n }\n public int subtraction(int a, int b) {\n return a-b;\n }\n public double squareRoot(int a) {\n return Math.sqrt(a);\n }\n public double powerOf(int a, int b) {\n return Math.pow(a, b);\n }\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the value of a: \");\n int a = sc.nextInt();\n System.out.println(\"Enter the value of b: \");\n int b = sc.nextInt();\n ExtendingInterfaceExample obj = new ExtendingInterfaceExample();\n System.out.println(\"Result of addition: \"+obj.addition(a, b));\n System.out.println(\"Result of subtraction: \"+obj.subtraction(a, b));\n System.out.println(\"Square root of \"+a+\" is: \"+obj.squareRoot(a));\n System.out.println(a+\"^\"+b+\" value is: \"+obj.powerOf(a, b));\n }\n}"
},
{
"code": null,
"e": 3254,
"s": 3115,
"text": "Enter the value of a:\n4\nEnter the value of b:\n3\nResult of addition: 7\nResult of subtraction: 1\nSquare root of 4 is: 2.0\n4^3 value is: 64.0"
},
{
"code": null,
"e": 3400,
"s": 3254,
"text": "In the same way you can extend multiple interfaces from an interface using the extends keyword, by separating the interfaces using comma (,) as −"
},
{
"code": null,
"e": 3472,
"s": 3400,
"text": "interface MyInterface extends ArithmeticCalculations, MathCalculations{"
},
{
"code": null,
"e": 3576,
"s": 3472,
"text": "Following is the Java program demonstrating, how to extend multiple interfaces from a single interface."
},
{
"code": null,
"e": 4979,
"s": 3576,
"text": "interface ArithmeticCalculations{\n public abstract int addition(int a, int b);\n public abstract int subtraction(int a, int b);\n}\ninterface MathCalculations {\n public abstract double squareRoot(int a);\n public abstract double powerOf(int a, int b);\n}\ninterface MyInterface extends MathCalculations, ArithmeticCalculations {\n public void displayResults();\n}\npublic class ExtendingInterfaceExample implements MyInterface {\n public int addition(int a, int b) {\n return a+b;\n }\n public int subtraction(int a, int b) {\n return a-b;\n }\n public double squareRoot(int a) {\n return Math.sqrt(a);\n }\n public double powerOf(int a, int b) {\n return Math.pow(a, b);\n }\n public void displayResults(){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the value of a: \");\n int a = sc.nextInt();\n System.out.println(\"Enter the value of b: \");\n int b = sc.nextInt();\n ExtendingInterfaceExample obj = new ExtendingInterfaceExample();\n System.out.println(\"Result of addition: \"+obj.addition(a, b));\n System.out.println(\"Result of subtraction: \"+obj.subtraction(a, b));\n System.out.println(\"Square root of \"+a+\" is: \"+obj.squareRoot(a));\n System.out.println(a+\"^\"+b+\" value is: \"+obj.powerOf(a, b));\n }\n public static void main(String args[]){\n new ExtendingInterfaceExample().displayResults();\n }\n}"
},
{
"code": null,
"e": 5118,
"s": 4979,
"text": "Enter the value of a:\n4\nEnter the value of b:\n3\nResult of addition: 7\nResult of subtraction: 1\nSquare root of 4 is: 2.0\n4^3 value is: 64.0"
}
] |
Python | Pandas Timestamp.to_datetime64 - GeeksforGeeks | 17 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.to_datetime64() function return a numpy.datetime64 object with ‘ns’ precision for the given Timestamp object.
Syntax :Timestamp.to_datetime64()
Parameters : None
Return : numpy.datetime64 object
Example #1: Use Timestamp.to_datetime64() function to return a numpy.datetime64 object for the given Timestamp object.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.to_datetime64() function to return a numpy.datetime64 object for the given Timestamp.
# return numpy.datetime64 objectts.to_datetime64()
Output :As we can see in the output, the Timestamp.to_datetime64() function has returned a numpy.datetime64 object for the given Timestamp object with ‘ns’ precision. Example #2: Use Timestamp.to_datetime64() function to return a numpy.datetime64 object for the given Timestamp object.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.to_datetime64() function to return a numpy.datetime64 object for the given Timestamp.
# return numpy.datetime64 objectts.to_datetime64()
Output :
As we can see in the output, the Timestamp.to_datetime64() function has returned a numpy.datetime64 object for the given Timestamp object with ‘ns’ precision.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24649,
"s": 24621,
"text": "\n17 Jan, 2019"
},
{
"code": null,
"e": 24863,
"s": 24649,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 24990,
"s": 24863,
"text": "Pandas Timestamp.to_datetime64() function return a numpy.datetime64 object with ‘ns’ precision for the given Timestamp object."
},
{
"code": null,
"e": 25024,
"s": 24990,
"text": "Syntax :Timestamp.to_datetime64()"
},
{
"code": null,
"e": 25042,
"s": 25024,
"text": "Parameters : None"
},
{
"code": null,
"e": 25075,
"s": 25042,
"text": "Return : numpy.datetime64 object"
},
{
"code": null,
"e": 25194,
"s": 25075,
"text": "Example #1: Use Timestamp.to_datetime64() function to return a numpy.datetime64 object for the given Timestamp object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)",
"e": 25423,
"s": 25194,
"text": null
},
{
"code": null,
"e": 25432,
"s": 25423,
"text": "Output :"
},
{
"code": null,
"e": 25548,
"s": 25432,
"text": "Now we will use the Timestamp.to_datetime64() function to return a numpy.datetime64 object for the given Timestamp."
},
{
"code": "# return numpy.datetime64 objectts.to_datetime64()",
"e": 25599,
"s": 25548,
"text": null
},
{
"code": null,
"e": 25885,
"s": 25599,
"text": "Output :As we can see in the output, the Timestamp.to_datetime64() function has returned a numpy.datetime64 object for the given Timestamp object with ‘ns’ precision. Example #2: Use Timestamp.to_datetime64() function to return a numpy.datetime64 object for the given Timestamp object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)",
"e": 26113,
"s": 25885,
"text": null
},
{
"code": null,
"e": 26122,
"s": 26113,
"text": "Output :"
},
{
"code": null,
"e": 26238,
"s": 26122,
"text": "Now we will use the Timestamp.to_datetime64() function to return a numpy.datetime64 object for the given Timestamp."
},
{
"code": "# return numpy.datetime64 objectts.to_datetime64()",
"e": 26289,
"s": 26238,
"text": null
},
{
"code": null,
"e": 26298,
"s": 26289,
"text": "Output :"
},
{
"code": null,
"e": 26457,
"s": 26298,
"text": "As we can see in the output, the Timestamp.to_datetime64() function has returned a numpy.datetime64 object for the given Timestamp object with ‘ns’ precision."
},
{
"code": null,
"e": 26481,
"s": 26457,
"text": "Python Pandas-Timestamp"
},
{
"code": null,
"e": 26495,
"s": 26481,
"text": "Python-pandas"
},
{
"code": null,
"e": 26502,
"s": 26495,
"text": "Python"
},
{
"code": null,
"e": 26600,
"s": 26502,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26609,
"s": 26600,
"text": "Comments"
},
{
"code": null,
"e": 26622,
"s": 26609,
"text": "Old Comments"
},
{
"code": null,
"e": 26640,
"s": 26622,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26675,
"s": 26640,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26697,
"s": 26675,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26729,
"s": 26697,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26759,
"s": 26729,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26801,
"s": 26759,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26827,
"s": 26801,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26870,
"s": 26827,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26914,
"s": 26870,
"text": "Reading and Writing to text files in Python"
}
] |
Canonical Huffman Coding - GeeksforGeeks | 19 Aug, 2021
Huffman Coding is a lossless data compression algorithm where each character in the data is assigned a variable length prefix code. The least frequent character gets the largest code and the most frequent one gets the smallest code. Encoding the data using this technique is very easy and efficient. However, decoding the bitstream generated using this technique is inefficient.Decoders(or Decompressors)require the knowledge of the encoding mechanism used in order to decode the encoded data back to the original characters. Hence information about the encoding process needs to be passed to the decoder along with the encoded data as a table of characters and their corresponding codes. In regular Huffman coding of a large data, this table takes up a lot of memory space and also if a large no. of unique characters are present in the data then the compressed(or encoded) data size increases because of the presence of the codebook. Therefore to make the decoding process computationally efficient and still maintain a good compression ratio, Canonical Huffman codes were introduced.
In Canonical Huffman coding, the bit lengths of the standard Huffman codes generated for each symbol is used. The symbols are sorted first according to their bit lengths in non-decreasing order and then for each bit length, they are sorted lexicographically. The first symbol gets a code containing all zeros and of the same length as that of the original bit length. For the subsequent symbols, if the symbol has a bit length equal to that of the previous symbol, then the code of the previous symbol is incremented by one and assigned to the present symbol. Otherwise, if the symbol has a bit length greater than that of the previous symbol, after incrementing the code of the previous symbol is zeros are appended until the length becomes equal to the bit length of the current symbol and the code is then assigned to the current symbol. This process continues for the rest of the symbols.
The following example illustrates the process:
Consider the following data:
Standard Huffman Codes Generated with bit lengths:
Step 1: Sort the data according to bit lengths and then for each bit length sort the symbols lexicographically.
Step 2: Assign the code of the first symbol with the same number of ‘0’s as the bit length. Code for ‘c’:0Next symbol ‘a’ has bit length 2 > bit length of the previous symbol ‘c’ which is 1.Increment the code of the previous symbol by 1 and append (2-1)=1 zeros and assign the code to ‘a’. Code for ‘a’:10Next symbol ‘b’ has bit length 3 > bit length of the previous symbol ‘a’ which is 2.Increment the code of the previous symbol by 1 and append (3-2)=1 zeros and assign the code to ‘b’. Code for ‘b’:110Next symbol ‘d’ has bit length 3 = bit length of the previous symbol ‘b’ which is 3.Increment the code of the previous symbol by 1 and assign it to ‘d’. Code for ‘d’:111
Step 3: Final result.
The basic advantage of this method is that the encoding information passed to the decoder can be made more compact and memory efficient. For example, one can simply pass the bit lengths of the characters or symbols to the decoder. The canonical codes can be generated easily from the lengths as they are sequential. For generating Huffman codes using Huffman Tree refer here.
Approach: A simple and efficient approach is to generate a Huffman tree for the data and use a data structure similar to TreeMap in java to store the symbols and bit lengths such that the information always remains sorted. The canonical codes can then be obtained using incrementation and bitwise left shift operations.
Java
// Java Program for Canonical Huffman Encoding import java.io.*;import java.util.*; // Nodes of Huffman treeclass Node { int data; char c; Node left; Node right;} // comparator class helps to compare the node// on the basis of one of its attribute.// Here we will be compared// on the basis of data values of the nodes.class Pq_compare implements Comparator<Node> { public int compare(Node a, Node b) { return a.data - b.data; }} class Canonical_Huffman { // Treemap to store the // code lengths(sorted) as keys // and corresponding(sorted) // set of characters as values static TreeMap<Integer, TreeSet<Character> > data; // Constructor to initialize the Treemap public Canonical_Huffman() { data = new TreeMap<Integer, TreeSet<Character> >(); } // Recursive function // to generate code lengths // from regular Huffman codes static void code_gen(Node root, int code_length) { if (root == null) return; // base case; if the left and right are null // then its a leaf node. if (root.left == null && root.right == null) { // check if key is present or not. // If not present add a new treeset // as value along with the key data.putIfAbsent(code_length, new TreeSet<Character>()); // c is the character in the node data.get(code_length).add(root.c); return; } // Add 1 when on going left or right. code_gen(root.left, code_length + 1); code_gen(root.right, code_length + 1); } static void testCanonicalHC(int n, char chararr[], int freq[]) { // min-priority queue(min-heap). PriorityQueue<Node> q = new PriorityQueue<Node>(n, new Pq_compare()); for (int i = 0; i < n; i++) { // creating a node object // and adding it to the priority-queue. Node node = new Node(); node.c = chararr[i]; node.data = freq[i]; node.left = null; node.right = null; // add functions adds // the node to the queue. q.add(node); } // create a root node Node root = null; // extract the two minimum value // from the heap each time until // its size reduces to 1, extract until // all the nodes are extracted. while (q.size() > 1) { // first min extract. Node x = q.peek(); q.poll(); // second min extract. Node y = q.peek(); q.poll(); // new node f which is equal Node nodeobj = new Node(); // to the sum of the frequency of the two nodes // assigning values to the f node. nodeobj.data = x.data + y.data; nodeobj.c = '-'; // first extracted node as left child. nodeobj.left = x; // second extracted node as the right child. nodeobj.right = y; // marking the f node as the root node. root = nodeobj; // add this node to the priority-queue. q.add(nodeobj); } // Creating a canonical Huffman object Canonical_Huffman obj = new Canonical_Huffman(); // generate code lengths by traversing the tree code_gen(root, 0); // Object array to store the keys Object[] arr = data.keySet().toArray(); // Set initial canonical code=0 int c_code = 0, curr_len = 0, next_len = 0; for (int i = 0; i < arr.length; i++) { Iterator it = data.get(arr[i]).iterator(); // code length of current character curr_len = (int)arr[i]; while (it.hasNext()) { // Display the canonical codes System.out.println(it.next() + ":" + Integer.toBinaryString(c_code)); // if values set is not // completed or if it is // the last set set code length // of next character as current // code length if (it.hasNext() || i == arr.length - 1) next_len = curr_len; else next_len = (int)arr[i + 1]; // Generate canonical code // for next character using // regular code length of next // character c_code = (c_code + 1) << (next_len - curr_len); } } } // Driver code public static void main(String args[]) throws IOException { int n = 4; char[] chararr = { 'a', 'b', 'c', 'd' }; int[] freq = { 10, 1, 15, 7 }; testCanonicalHC(n, chararr, freq); }}
c:0
a:10
b:110
d:111
gabaa406
sumitgumber28
anikakapoor
Huffman Coding
Heap
Java Programs
Queue
Queue
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Min Heap and Max Heap
Fibonacci Heap | Set 1 (Introduction)
Find k numbers with most occurrences in the given array
Applications of Priority Queue
Complexity analysis of various operations of Binary Min Heap
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": 25841,
"s": 25813,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 26930,
"s": 25841,
"text": "Huffman Coding is a lossless data compression algorithm where each character in the data is assigned a variable length prefix code. The least frequent character gets the largest code and the most frequent one gets the smallest code. Encoding the data using this technique is very easy and efficient. However, decoding the bitstream generated using this technique is inefficient.Decoders(or Decompressors)require the knowledge of the encoding mechanism used in order to decode the encoded data back to the original characters. Hence information about the encoding process needs to be passed to the decoder along with the encoded data as a table of characters and their corresponding codes. In regular Huffman coding of a large data, this table takes up a lot of memory space and also if a large no. of unique characters are present in the data then the compressed(or encoded) data size increases because of the presence of the codebook. Therefore to make the decoding process computationally efficient and still maintain a good compression ratio, Canonical Huffman codes were introduced. "
},
{
"code": null,
"e": 27825,
"s": 26930,
"text": "In Canonical Huffman coding, the bit lengths of the standard Huffman codes generated for each symbol is used. The symbols are sorted first according to their bit lengths in non-decreasing order and then for each bit length, they are sorted lexicographically. The first symbol gets a code containing all zeros and of the same length as that of the original bit length. For the subsequent symbols, if the symbol has a bit length equal to that of the previous symbol, then the code of the previous symbol is incremented by one and assigned to the present symbol. Otherwise, if the symbol has a bit length greater than that of the previous symbol, after incrementing the code of the previous symbol is zeros are appended until the length becomes equal to the bit length of the current symbol and the code is then assigned to the current symbol. This process continues for the rest of the symbols. "
},
{
"code": null,
"e": 27872,
"s": 27825,
"text": "The following example illustrates the process:"
},
{
"code": null,
"e": 27902,
"s": 27872,
"text": "Consider the following data: "
},
{
"code": null,
"e": 27954,
"s": 27902,
"text": "Standard Huffman Codes Generated with bit lengths: "
},
{
"code": null,
"e": 28067,
"s": 27954,
"text": "Step 1: Sort the data according to bit lengths and then for each bit length sort the symbols lexicographically. "
},
{
"code": null,
"e": 28742,
"s": 28067,
"text": "Step 2: Assign the code of the first symbol with the same number of ‘0’s as the bit length. Code for ‘c’:0Next symbol ‘a’ has bit length 2 > bit length of the previous symbol ‘c’ which is 1.Increment the code of the previous symbol by 1 and append (2-1)=1 zeros and assign the code to ‘a’. Code for ‘a’:10Next symbol ‘b’ has bit length 3 > bit length of the previous symbol ‘a’ which is 2.Increment the code of the previous symbol by 1 and append (3-2)=1 zeros and assign the code to ‘b’. Code for ‘b’:110Next symbol ‘d’ has bit length 3 = bit length of the previous symbol ‘b’ which is 3.Increment the code of the previous symbol by 1 and assign it to ‘d’. Code for ‘d’:111"
},
{
"code": null,
"e": 28766,
"s": 28742,
"text": "Step 3: Final result. "
},
{
"code": null,
"e": 29142,
"s": 28766,
"text": "The basic advantage of this method is that the encoding information passed to the decoder can be made more compact and memory efficient. For example, one can simply pass the bit lengths of the characters or symbols to the decoder. The canonical codes can be generated easily from the lengths as they are sequential. For generating Huffman codes using Huffman Tree refer here."
},
{
"code": null,
"e": 29463,
"s": 29142,
"text": "Approach: A simple and efficient approach is to generate a Huffman tree for the data and use a data structure similar to TreeMap in java to store the symbols and bit lengths such that the information always remains sorted. The canonical codes can then be obtained using incrementation and bitwise left shift operations. "
},
{
"code": null,
"e": 29468,
"s": 29463,
"text": "Java"
},
{
"code": "// Java Program for Canonical Huffman Encoding import java.io.*;import java.util.*; // Nodes of Huffman treeclass Node { int data; char c; Node left; Node right;} // comparator class helps to compare the node// on the basis of one of its attribute.// Here we will be compared// on the basis of data values of the nodes.class Pq_compare implements Comparator<Node> { public int compare(Node a, Node b) { return a.data - b.data; }} class Canonical_Huffman { // Treemap to store the // code lengths(sorted) as keys // and corresponding(sorted) // set of characters as values static TreeMap<Integer, TreeSet<Character> > data; // Constructor to initialize the Treemap public Canonical_Huffman() { data = new TreeMap<Integer, TreeSet<Character> >(); } // Recursive function // to generate code lengths // from regular Huffman codes static void code_gen(Node root, int code_length) { if (root == null) return; // base case; if the left and right are null // then its a leaf node. if (root.left == null && root.right == null) { // check if key is present or not. // If not present add a new treeset // as value along with the key data.putIfAbsent(code_length, new TreeSet<Character>()); // c is the character in the node data.get(code_length).add(root.c); return; } // Add 1 when on going left or right. code_gen(root.left, code_length + 1); code_gen(root.right, code_length + 1); } static void testCanonicalHC(int n, char chararr[], int freq[]) { // min-priority queue(min-heap). PriorityQueue<Node> q = new PriorityQueue<Node>(n, new Pq_compare()); for (int i = 0; i < n; i++) { // creating a node object // and adding it to the priority-queue. Node node = new Node(); node.c = chararr[i]; node.data = freq[i]; node.left = null; node.right = null; // add functions adds // the node to the queue. q.add(node); } // create a root node Node root = null; // extract the two minimum value // from the heap each time until // its size reduces to 1, extract until // all the nodes are extracted. while (q.size() > 1) { // first min extract. Node x = q.peek(); q.poll(); // second min extract. Node y = q.peek(); q.poll(); // new node f which is equal Node nodeobj = new Node(); // to the sum of the frequency of the two nodes // assigning values to the f node. nodeobj.data = x.data + y.data; nodeobj.c = '-'; // first extracted node as left child. nodeobj.left = x; // second extracted node as the right child. nodeobj.right = y; // marking the f node as the root node. root = nodeobj; // add this node to the priority-queue. q.add(nodeobj); } // Creating a canonical Huffman object Canonical_Huffman obj = new Canonical_Huffman(); // generate code lengths by traversing the tree code_gen(root, 0); // Object array to store the keys Object[] arr = data.keySet().toArray(); // Set initial canonical code=0 int c_code = 0, curr_len = 0, next_len = 0; for (int i = 0; i < arr.length; i++) { Iterator it = data.get(arr[i]).iterator(); // code length of current character curr_len = (int)arr[i]; while (it.hasNext()) { // Display the canonical codes System.out.println(it.next() + \":\" + Integer.toBinaryString(c_code)); // if values set is not // completed or if it is // the last set set code length // of next character as current // code length if (it.hasNext() || i == arr.length - 1) next_len = curr_len; else next_len = (int)arr[i + 1]; // Generate canonical code // for next character using // regular code length of next // character c_code = (c_code + 1) << (next_len - curr_len); } } } // Driver code public static void main(String args[]) throws IOException { int n = 4; char[] chararr = { 'a', 'b', 'c', 'd' }; int[] freq = { 10, 1, 15, 7 }; testCanonicalHC(n, chararr, freq); }}",
"e": 34287,
"s": 29468,
"text": null
},
{
"code": null,
"e": 34308,
"s": 34287,
"text": "c:0\na:10\nb:110\nd:111"
},
{
"code": null,
"e": 34319,
"s": 34310,
"text": "gabaa406"
},
{
"code": null,
"e": 34333,
"s": 34319,
"text": "sumitgumber28"
},
{
"code": null,
"e": 34345,
"s": 34333,
"text": "anikakapoor"
},
{
"code": null,
"e": 34360,
"s": 34345,
"text": "Huffman Coding"
},
{
"code": null,
"e": 34365,
"s": 34360,
"text": "Heap"
},
{
"code": null,
"e": 34379,
"s": 34365,
"text": "Java Programs"
},
{
"code": null,
"e": 34385,
"s": 34379,
"text": "Queue"
},
{
"code": null,
"e": 34391,
"s": 34385,
"text": "Queue"
},
{
"code": null,
"e": 34396,
"s": 34391,
"text": "Heap"
},
{
"code": null,
"e": 34494,
"s": 34396,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34535,
"s": 34494,
"text": "Difference between Min Heap and Max Heap"
},
{
"code": null,
"e": 34573,
"s": 34535,
"text": "Fibonacci Heap | Set 1 (Introduction)"
},
{
"code": null,
"e": 34629,
"s": 34573,
"text": "Find k numbers with most occurrences in the given array"
},
{
"code": null,
"e": 34660,
"s": 34629,
"text": "Applications of Priority Queue"
},
{
"code": null,
"e": 34721,
"s": 34660,
"text": "Complexity analysis of various operations of Binary Min Heap"
},
{
"code": null,
"e": 34749,
"s": 34721,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 34793,
"s": 34749,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 34819,
"s": 34793,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 34853,
"s": 34819,
"text": "Convert Double to Integer in Java"
}
] |
Size of ROM for n-bit Adder/Subtractor - GeeksforGeeks | 15 Feb, 2021
ROM is a read-only memory which is used to store the data. The memory in the ROM is organized as a two-dimensional array of memory cells. The memory will read or write the contents of one of the rows of the array. This row is specified by an Address which are bits. The value read or written is called Data.
Figure a) shows a memory array with two address bits and three data bits. The two address bits specify one of the four rows (data words) in the array. Each data word is three bits wide. Figure b) shows some possible contents of the memory array.
An array of memory cells with n-bit addresses and m-bit data will have rows and m columns as shown in the figure. Each row of data is called a word. Thus, the array contains a word x m -bit array.
In the case of figure, the array of memory cells with 2-bit addresses and 3-bit Data will have rows which are 4 and 3 columns, so thus the array contains x m = x 3 = 4-word x 3 -bit array.
To get clear understanding let’s take 10 address bits and 32 Data bits then the size of the ROM would be –
2^(10) x 32 = 1024 x 32 = 32 Kb
Now to find the size of the ROM we need to find the number of inputs and output bits –
Number of inputs = n(A) + n(B) + 1(Cin) = 2n+1 address bits
Number of outputs = n(sum/diff) + 1(Cout) = n+1
Thus, this would require a 2^(2n+1) x (n+1) -bit ROM.
Here, n(A) means the number of inputs for A and n(B) means the number of inputs for B.
Example-1 : Size of the ROM you could use to program for 16-bit adder/subtractor with Cin and Cout is ____?
Solution :
Number of inputs = 16 (A) + 16 (B) + 1(Cin) = 2(16)+1 = 33 address bits.
Number of outputs = 16 (sum/diff) + 1(Cout) = 16+1 = 17
Thus, this would require a 2^(2n+1)x(n+1) = 2^(33)x17 bit ROM.
Example-2 : Size of the ROM you could use to program for 8-bit adder/subtractor with Cin and Cout is ____?
Solution :
Number of inputs = 8 (A) + 8 (B) + 1(Cin) = 2(8)+1 = 17 address bits.
Number of outputs = 8 (sum/diff) + 1(Cout) = 8+1 = 9
Thus, this would require a 2^(2n+1)x(n+1) = 2^(17)x9 bit ROM.
Technical Scripter 2020
Computer Organization & Architecture
DIgital Logic & Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Architecture of 8085 microprocessor
Pin diagram of 8086 microprocessor
I2C Communication Protocol
Basic Conversion of Logic Gates
Advantages and Disadvantages of Embedded System
Introduction of Algorithmic State Machines (ASMs)
Different ways to represent Signed Integer
How to Install Logisim on Windows? | [
{
"code": null,
"e": 26049,
"s": 26021,
"text": "\n15 Feb, 2021"
},
{
"code": null,
"e": 26358,
"s": 26049,
"text": "ROM is a read-only memory which is used to store the data. The memory in the ROM is organized as a two-dimensional array of memory cells. The memory will read or write the contents of one of the rows of the array. This row is specified by an Address which are bits. The value read or written is called Data. "
},
{
"code": null,
"e": 26604,
"s": 26358,
"text": "Figure a) shows a memory array with two address bits and three data bits. The two address bits specify one of the four rows (data words) in the array. Each data word is three bits wide. Figure b) shows some possible contents of the memory array."
},
{
"code": null,
"e": 26801,
"s": 26604,
"text": "An array of memory cells with n-bit addresses and m-bit data will have rows and m columns as shown in the figure. Each row of data is called a word. Thus, the array contains a word x m -bit array."
},
{
"code": null,
"e": 26990,
"s": 26801,
"text": "In the case of figure, the array of memory cells with 2-bit addresses and 3-bit Data will have rows which are 4 and 3 columns, so thus the array contains x m = x 3 = 4-word x 3 -bit array."
},
{
"code": null,
"e": 27097,
"s": 26990,
"text": "To get clear understanding let’s take 10 address bits and 32 Data bits then the size of the ROM would be –"
},
{
"code": null,
"e": 27129,
"s": 27097,
"text": "2^(10) x 32 = 1024 x 32 = 32 Kb"
},
{
"code": null,
"e": 27216,
"s": 27129,
"text": "Now to find the size of the ROM we need to find the number of inputs and output bits –"
},
{
"code": null,
"e": 27276,
"s": 27216,
"text": "Number of inputs = n(A) + n(B) + 1(Cin) = 2n+1 address bits"
},
{
"code": null,
"e": 27326,
"s": 27276,
"text": "Number of outputs = n(sum/diff) + 1(Cout) = n+1 "
},
{
"code": null,
"e": 27380,
"s": 27326,
"text": "Thus, this would require a 2^(2n+1) x (n+1) -bit ROM."
},
{
"code": null,
"e": 27467,
"s": 27380,
"text": "Here, n(A) means the number of inputs for A and n(B) means the number of inputs for B."
},
{
"code": null,
"e": 27575,
"s": 27467,
"text": "Example-1 : Size of the ROM you could use to program for 16-bit adder/subtractor with Cin and Cout is ____?"
},
{
"code": null,
"e": 27587,
"s": 27575,
"text": "Solution : "
},
{
"code": null,
"e": 27660,
"s": 27587,
"text": "Number of inputs = 16 (A) + 16 (B) + 1(Cin) = 2(16)+1 = 33 address bits."
},
{
"code": null,
"e": 27716,
"s": 27660,
"text": "Number of outputs = 16 (sum/diff) + 1(Cout) = 16+1 = 17"
},
{
"code": null,
"e": 27779,
"s": 27716,
"text": "Thus, this would require a 2^(2n+1)x(n+1) = 2^(33)x17 bit ROM."
},
{
"code": null,
"e": 27886,
"s": 27779,
"text": "Example-2 : Size of the ROM you could use to program for 8-bit adder/subtractor with Cin and Cout is ____?"
},
{
"code": null,
"e": 27897,
"s": 27886,
"text": "Solution :"
},
{
"code": null,
"e": 27967,
"s": 27897,
"text": "Number of inputs = 8 (A) + 8 (B) + 1(Cin) = 2(8)+1 = 17 address bits."
},
{
"code": null,
"e": 28020,
"s": 27967,
"text": "Number of outputs = 8 (sum/diff) + 1(Cout) = 8+1 = 9"
},
{
"code": null,
"e": 28082,
"s": 28020,
"text": "Thus, this would require a 2^(2n+1)x(n+1) = 2^(17)x9 bit ROM."
},
{
"code": null,
"e": 28106,
"s": 28082,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28143,
"s": 28106,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 28166,
"s": 28143,
"text": "DIgital Logic & Design"
},
{
"code": null,
"e": 28264,
"s": 28166,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28326,
"s": 28264,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 28417,
"s": 28326,
"text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)"
},
{
"code": null,
"e": 28453,
"s": 28417,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 28488,
"s": 28453,
"text": "Pin diagram of 8086 microprocessor"
},
{
"code": null,
"e": 28515,
"s": 28488,
"text": "I2C Communication Protocol"
},
{
"code": null,
"e": 28547,
"s": 28515,
"text": "Basic Conversion of Logic Gates"
},
{
"code": null,
"e": 28595,
"s": 28547,
"text": "Advantages and Disadvantages of Embedded System"
},
{
"code": null,
"e": 28645,
"s": 28595,
"text": "Introduction of Algorithmic State Machines (ASMs)"
},
{
"code": null,
"e": 28688,
"s": 28645,
"text": "Different ways to represent Signed Integer"
}
] |
Put spaces between words starting with capital letters - GeeksforGeeks | 25 Jun, 2021
You are given an array of characters which is basically a sentence. However, there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after following amendments: (i) Put a single space between these words. (ii) Convert the uppercase letters to lowercase.
Examples:
Input : BruceWayneIsBatman
Output : bruce wayne is batman
Input : You
Output : you
We check if the current character is in uppercase then print ” “(space) and convert it into lowercase.
C++
Java
Python3
C#
Javascript
// C++ program to put spaces between words starting// with capital letters.#include <iostream>using namespace std; // Function to amend the sentencevoid amendSentence(string str){ // Traverse the string for(int i=0; i < str.length(); i++) { // Convert to lowercase if its // an uppercase character if (str[i]>='A' && str[i]<='Z') { str[i]=str[i]+32; // Print space before it // if its an uppercase character if (i != 0) cout << " "; // Print the character cout << str[i]; } // if lowercase character // then just print else cout << str[i]; }} // Driver codeint main(){ string str ="BruceWayneIsBatman"; amendSentence(str); return 0;}
// Java program to put spaces between words starting// with capital letters. import java.util.*;import java.lang.*;import java.io.*; class AddSpaceinSentence{ // Function to amend the sentence public static void amendSentence(String sstr) { char[] str=sstr.toCharArray(); // Traverse the string for (int i=0; i < str.length; i++) { // Convert to lowercase if its // an uppercase character if (str[i]>='A' && str[i]<='Z') { str[i] = (char)(str[i]+32); // Print space before it // if its an uppercase character if (i != 0) System.out.print(" "); // Print the character System.out.print(str[i]); } // if lowercase character // then just print else System.out.print(str[i]); } } // Driver Code public static void main (String[] args) { String str ="BruceWayneIsBatman"; amendSentence(str); }}
# Python3 program to put spaces between words# starting with capital letters. # Function to amend the sentencedef amendSentence(string): string = list(string) # Traverse the string for i in range(len(string)): # Convert to lowercase if its # an uppercase character if string[i] >= 'A' and string[i] <= 'Z': string[i] = chr(ord(string[i]) + 32) # Print space before it # if its an uppercase character if i != 0: print(" ", end = "") # Print the character print(string[i], end = "") # if lowercase character # then just print else: print(string[i], end = "") # Driver Codeif __name__ == "__main__": string = "BruceWayneIsBatman" amendSentence(string) # This code is contributed by# sanjeev2552
// C# program to put spaces between words// starting with capital letters.using System; public class GFG { // Function to amend the sentence public static void amendSentence(string sstr) { char[] str = sstr.ToCharArray(); // Traverse the string for (int i = 0; i < str.Length; i++) { // Convert to lowercase if its // an uppercase character if (str[i] >= 'A' && str[i] <= 'Z') { str[i] = (char)(str[i] + 32); // Print space before it // if its an uppercase // character if (i != 0) Console.Write(" "); // Print the character Console.Write(str[i]); } // if lowercase character // then just print else Console.Write(str[i]); } } // Driver Code public static void Main () { string str ="BruceWayneIsBatman"; amendSentence(str); } } // This code is contributed by Sam007.
<script> // JavaScript program to put spaces between words // starting with capital letters. // Function to amend the sentence function amendSentence(sstr) { let str = sstr.split(''); // Traverse the string for (let i = 0; i < str.length; i++) { // Convert to lowercase if its // an uppercase character if (str[i].charCodeAt() >= 'A'.charCodeAt() && str[i].charCodeAt() <= 'Z'.charCodeAt()) { str[i] = String.fromCharCode(str[i].charCodeAt() + 32); // Print space before it // if its an uppercase // character if (i != 0) document.write(" "); // Print the character document.write(str[i]); } // if lowercase character // then just print else document.write(str[i]); } } let str ="BruceWayneIsBatman"; amendSentence(str); </script>
Output:
bruce wayne is batman
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
sanjeev2552
divyeshrabadiya07
surindertarika1234
Adobe
Strings
Adobe
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews | [
{
"code": null,
"e": 26037,
"s": 26009,
"text": "\n25 Jun, 2021"
},
{
"code": null,
"e": 26361,
"s": 26037,
"text": "You are given an array of characters which is basically a sentence. However, there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after following amendments: (i) Put a single space between these words. (ii) Convert the uppercase letters to lowercase."
},
{
"code": null,
"e": 26372,
"s": 26361,
"text": "Examples: "
},
{
"code": null,
"e": 26458,
"s": 26372,
"text": "Input : BruceWayneIsBatman\nOutput : bruce wayne is batman\n\nInput : You\nOutput : you"
},
{
"code": null,
"e": 26562,
"s": 26458,
"text": "We check if the current character is in uppercase then print ” “(space) and convert it into lowercase. "
},
{
"code": null,
"e": 26566,
"s": 26562,
"text": "C++"
},
{
"code": null,
"e": 26571,
"s": 26566,
"text": "Java"
},
{
"code": null,
"e": 26579,
"s": 26571,
"text": "Python3"
},
{
"code": null,
"e": 26582,
"s": 26579,
"text": "C#"
},
{
"code": null,
"e": 26593,
"s": 26582,
"text": "Javascript"
},
{
"code": "// C++ program to put spaces between words starting// with capital letters.#include <iostream>using namespace std; // Function to amend the sentencevoid amendSentence(string str){ // Traverse the string for(int i=0; i < str.length(); i++) { // Convert to lowercase if its // an uppercase character if (str[i]>='A' && str[i]<='Z') { str[i]=str[i]+32; // Print space before it // if its an uppercase character if (i != 0) cout << \" \"; // Print the character cout << str[i]; } // if lowercase character // then just print else cout << str[i]; }} // Driver codeint main(){ string str =\"BruceWayneIsBatman\"; amendSentence(str); return 0;}",
"e": 27399,
"s": 26593,
"text": null
},
{
"code": "// Java program to put spaces between words starting// with capital letters. import java.util.*;import java.lang.*;import java.io.*; class AddSpaceinSentence{ // Function to amend the sentence public static void amendSentence(String sstr) { char[] str=sstr.toCharArray(); // Traverse the string for (int i=0; i < str.length; i++) { // Convert to lowercase if its // an uppercase character if (str[i]>='A' && str[i]<='Z') { str[i] = (char)(str[i]+32); // Print space before it // if its an uppercase character if (i != 0) System.out.print(\" \"); // Print the character System.out.print(str[i]); } // if lowercase character // then just print else System.out.print(str[i]); } } // Driver Code public static void main (String[] args) { String str =\"BruceWayneIsBatman\"; amendSentence(str); }}",
"e": 28514,
"s": 27399,
"text": null
},
{
"code": "# Python3 program to put spaces between words# starting with capital letters. # Function to amend the sentencedef amendSentence(string): string = list(string) # Traverse the string for i in range(len(string)): # Convert to lowercase if its # an uppercase character if string[i] >= 'A' and string[i] <= 'Z': string[i] = chr(ord(string[i]) + 32) # Print space before it # if its an uppercase character if i != 0: print(\" \", end = \"\") # Print the character print(string[i], end = \"\") # if lowercase character # then just print else: print(string[i], end = \"\") # Driver Codeif __name__ == \"__main__\": string = \"BruceWayneIsBatman\" amendSentence(string) # This code is contributed by# sanjeev2552",
"e": 29360,
"s": 28514,
"text": null
},
{
"code": "// C# program to put spaces between words// starting with capital letters.using System; public class GFG { // Function to amend the sentence public static void amendSentence(string sstr) { char[] str = sstr.ToCharArray(); // Traverse the string for (int i = 0; i < str.Length; i++) { // Convert to lowercase if its // an uppercase character if (str[i] >= 'A' && str[i] <= 'Z') { str[i] = (char)(str[i] + 32); // Print space before it // if its an uppercase // character if (i != 0) Console.Write(\" \"); // Print the character Console.Write(str[i]); } // if lowercase character // then just print else Console.Write(str[i]); } } // Driver Code public static void Main () { string str =\"BruceWayneIsBatman\"; amendSentence(str); } } // This code is contributed by Sam007.",
"e": 30512,
"s": 29360,
"text": null
},
{
"code": "<script> // JavaScript program to put spaces between words // starting with capital letters. // Function to amend the sentence function amendSentence(sstr) { let str = sstr.split(''); // Traverse the string for (let i = 0; i < str.length; i++) { // Convert to lowercase if its // an uppercase character if (str[i].charCodeAt() >= 'A'.charCodeAt() && str[i].charCodeAt() <= 'Z'.charCodeAt()) { str[i] = String.fromCharCode(str[i].charCodeAt() + 32); // Print space before it // if its an uppercase // character if (i != 0) document.write(\" \"); // Print the character document.write(str[i]); } // if lowercase character // then just print else document.write(str[i]); } } let str =\"BruceWayneIsBatman\"; amendSentence(str); </script>",
"e": 31638,
"s": 30512,
"text": null
},
{
"code": null,
"e": 31648,
"s": 31638,
"text": "Output: "
},
{
"code": null,
"e": 31670,
"s": 31648,
"text": "bruce wayne is batman"
},
{
"code": null,
"e": 32092,
"s": 31670,
"text": "This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 32099,
"s": 32092,
"text": "Sam007"
},
{
"code": null,
"e": 32111,
"s": 32099,
"text": "sanjeev2552"
},
{
"code": null,
"e": 32129,
"s": 32111,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 32148,
"s": 32129,
"text": "surindertarika1234"
},
{
"code": null,
"e": 32154,
"s": 32148,
"text": "Adobe"
},
{
"code": null,
"e": 32162,
"s": 32154,
"text": "Strings"
},
{
"code": null,
"e": 32168,
"s": 32162,
"text": "Adobe"
},
{
"code": null,
"e": 32176,
"s": 32168,
"text": "Strings"
},
{
"code": null,
"e": 32274,
"s": 32176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32349,
"s": 32274,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 32406,
"s": 32349,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 32442,
"s": 32406,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 32489,
"s": 32442,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 32542,
"s": 32489,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 32578,
"s": 32542,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 32616,
"s": 32578,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 32646,
"s": 32616,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 32698,
"s": 32646,
"text": "Check whether two strings are anagram of each other"
}
] |
PHP | date_sub() Function - GeeksforGeeks | 28 Nov, 2019
The date_sub() is an inbuilt function in PHP which is used to subtract some days, months, years, hours, minutes, and seconds from given date. The function returns a DateTime object on success and returns FALSE on failure.
Syntax:
date_sub($object, $interval)
Parameters: The date_sub() function accepts two parameters as described below:
$object: It is a mandatory parameter which specifies the DateTime object returned by date_create()
$interval: It is a mandatory parameter which specifies the DateInterval object which we want to subtract.
Return Value: It returns a DateTime object after subtracting interval.
Below programs illustrate the date_sub() function:Program 1:
<?php// PHP program to illustrate date_sub() function // Subtract 5 years from the 25th of June, 2018$date = date_create('2018-06-25');date_sub($date, date_interval_create_from_date_string('5 years')); echo date_format($date, 'Y-m-d') . "\n"; // Subtract 5 month from the 25th of June, 2018$date = date_create('2018-06-25');date_sub($date, date_interval_create_from_date_string('5 month')); echo date_format($date, 'Y-m-d'). "\n"; // // Subtract 5 days from the 25th of June, 2018$date = date_create('2018-06-25');date_sub($date, date_interval_create_from_date_string('5 days')); echo date_format($date, 'Y-m-d'); ?>
Output:
2013-06-25
2013-01-25
2013-01-20
Program 2: When invalid date is passed the date_sub function gives warnings:
<?php// PHP program to illustrate date_sub function // date_sub function gives warning when// we passing invalid date$date = date_create('2018-25-25'); date_sub($date, date_interval_create_from_date_string('5 years')); echo date_format($date, 'Y-m-d') . "\n";?>
Output:
PHP Warning: date_sub() expects parameter 1 to be DateTime, boolean given in/home/2662efc623a406b7cb06a7320e7abf50.php on line 8
PHP Warning: date_format() expects parameter 1 to be DateTimeInterface, booleangiven in/home/2662efc623a406b7cb06a7320e7abf50.php on line 9
Reference: http://php.net/manual/en/function.date-sub.php
ManasChhabra2
PHP-date-time
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 42139,
"s": 42111,
"text": "\n28 Nov, 2019"
},
{
"code": null,
"e": 42361,
"s": 42139,
"text": "The date_sub() is an inbuilt function in PHP which is used to subtract some days, months, years, hours, minutes, and seconds from given date. The function returns a DateTime object on success and returns FALSE on failure."
},
{
"code": null,
"e": 42369,
"s": 42361,
"text": "Syntax:"
},
{
"code": null,
"e": 42398,
"s": 42369,
"text": "date_sub($object, $interval)"
},
{
"code": null,
"e": 42477,
"s": 42398,
"text": "Parameters: The date_sub() function accepts two parameters as described below:"
},
{
"code": null,
"e": 42576,
"s": 42477,
"text": "$object: It is a mandatory parameter which specifies the DateTime object returned by date_create()"
},
{
"code": null,
"e": 42682,
"s": 42576,
"text": "$interval: It is a mandatory parameter which specifies the DateInterval object which we want to subtract."
},
{
"code": null,
"e": 42753,
"s": 42682,
"text": "Return Value: It returns a DateTime object after subtracting interval."
},
{
"code": null,
"e": 42814,
"s": 42753,
"text": "Below programs illustrate the date_sub() function:Program 1:"
},
{
"code": "<?php// PHP program to illustrate date_sub() function // Subtract 5 years from the 25th of June, 2018$date = date_create('2018-06-25');date_sub($date, date_interval_create_from_date_string('5 years')); echo date_format($date, 'Y-m-d') . \"\\n\"; // Subtract 5 month from the 25th of June, 2018$date = date_create('2018-06-25');date_sub($date, date_interval_create_from_date_string('5 month')); echo date_format($date, 'Y-m-d'). \"\\n\"; // // Subtract 5 days from the 25th of June, 2018$date = date_create('2018-06-25');date_sub($date, date_interval_create_from_date_string('5 days')); echo date_format($date, 'Y-m-d'); ?>",
"e": 43440,
"s": 42814,
"text": null
},
{
"code": null,
"e": 43448,
"s": 43440,
"text": "Output:"
},
{
"code": null,
"e": 43482,
"s": 43448,
"text": "2013-06-25\n2013-01-25\n2013-01-20\n"
},
{
"code": null,
"e": 43559,
"s": 43482,
"text": "Program 2: When invalid date is passed the date_sub function gives warnings:"
},
{
"code": "<?php// PHP program to illustrate date_sub function // date_sub function gives warning when// we passing invalid date$date = date_create('2018-25-25'); date_sub($date, date_interval_create_from_date_string('5 years')); echo date_format($date, 'Y-m-d') . \"\\n\";?>",
"e": 43824,
"s": 43559,
"text": null
},
{
"code": null,
"e": 43832,
"s": 43824,
"text": "Output:"
},
{
"code": null,
"e": 44102,
"s": 43832,
"text": "PHP Warning: date_sub() expects parameter 1 to be DateTime, boolean given in/home/2662efc623a406b7cb06a7320e7abf50.php on line 8\nPHP Warning: date_format() expects parameter 1 to be DateTimeInterface, booleangiven in/home/2662efc623a406b7cb06a7320e7abf50.php on line 9\n"
},
{
"code": null,
"e": 44160,
"s": 44102,
"text": "Reference: http://php.net/manual/en/function.date-sub.php"
},
{
"code": null,
"e": 44174,
"s": 44160,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 44188,
"s": 44174,
"text": "PHP-date-time"
},
{
"code": null,
"e": 44201,
"s": 44188,
"text": "PHP-function"
},
{
"code": null,
"e": 44205,
"s": 44201,
"text": "PHP"
},
{
"code": null,
"e": 44222,
"s": 44205,
"text": "Web Technologies"
},
{
"code": null,
"e": 44226,
"s": 44222,
"text": "PHP"
},
{
"code": null,
"e": 44324,
"s": 44226,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44369,
"s": 44324,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 44419,
"s": 44369,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 44459,
"s": 44419,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 44483,
"s": 44459,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 44527,
"s": 44483,
"text": "How to pop an alert message box using PHP ?"
},
{
"code": null,
"e": 44567,
"s": 44527,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 44600,
"s": 44567,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 44645,
"s": 44600,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 44688,
"s": 44645,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python | sympy.atan() method - GeeksforGeeks | 17 Jan, 2022
In simpy, atan() method is an inverse tangent function. Using the atan(x) method in simpy module, we can compute the inverse tangent or arctangent of x.
Syntax : sympy.atan(x)
Return : Returns the arc tangent of x
Code #1:Below is the example using atan() method to find inverse tangent function.
Python3
# importing sympy libraryfrom sympy import * # calling atan() method on expressiongeek1 = atan(-1)geek2 = atan(1) print(geek1)print(geek2)
-pi/4
pi/4
Code #2:
Python3
# importing sympy libraryfrom sympy import atan # calling atan() method on expressiongeek = atan(1)print(geek)
pi/4
surindertarika1234
SymPy
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": "\n17 Jan, 2022"
},
{
"code": null,
"e": 25690,
"s": 25537,
"text": "In simpy, atan() method is an inverse tangent function. Using the atan(x) method in simpy module, we can compute the inverse tangent or arctangent of x."
},
{
"code": null,
"e": 25753,
"s": 25690,
"text": "Syntax : sympy.atan(x)\n\nReturn : Returns the arc tangent of x "
},
{
"code": null,
"e": 25836,
"s": 25753,
"text": "Code #1:Below is the example using atan() method to find inverse tangent function."
},
{
"code": null,
"e": 25844,
"s": 25836,
"text": "Python3"
},
{
"code": "# importing sympy libraryfrom sympy import * # calling atan() method on expressiongeek1 = atan(-1)geek2 = atan(1) print(geek1)print(geek2)",
"e": 25985,
"s": 25844,
"text": null
},
{
"code": null,
"e": 25997,
"s": 25985,
"text": "-pi/4\npi/4\n"
},
{
"code": null,
"e": 26007,
"s": 25997,
"text": " Code #2:"
},
{
"code": null,
"e": 26015,
"s": 26007,
"text": "Python3"
},
{
"code": "# importing sympy libraryfrom sympy import atan # calling atan() method on expressiongeek = atan(1)print(geek)",
"e": 26129,
"s": 26015,
"text": null
},
{
"code": null,
"e": 26134,
"s": 26129,
"text": "pi/4"
},
{
"code": null,
"e": 26153,
"s": 26134,
"text": "surindertarika1234"
},
{
"code": null,
"e": 26159,
"s": 26153,
"text": "SymPy"
},
{
"code": null,
"e": 26166,
"s": 26159,
"text": "Python"
},
{
"code": null,
"e": 26264,
"s": 26166,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26296,
"s": 26264,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26338,
"s": 26296,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26380,
"s": 26338,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26407,
"s": 26380,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26463,
"s": 26407,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26485,
"s": 26463,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26524,
"s": 26485,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26555,
"s": 26524,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26584,
"s": 26555,
"text": "Create a directory in Python"
}
] |
Find the size of a Dictionary in Python - GeeksforGeeks | 17 May, 2020
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized. The size of a Dictionary means the amount of memory (in bytes) occupied by a Dictionary object. In this article, we will learn various ways to get the size of a python Dictionary.
1.Using getsizeof() function:
The getsizeof() function belongs to the python’s sys module. It has been implemented in the below example.
Example 1:
import sys # sample Dictionariesdic1 = {"A": 1, "B": 2, "C": 3} dic2 = {"Geek1": "Raju", "Geek2": "Nikhil", "Geek3": "Deepanshu"}dic3 = {1: "Lion", 2: "Tiger", 3: "Fox", 4: "Wolf"} # print the sizes of sample Dictionariesprint("Size of dic1: " + str(sys.getsizeof(dic1)) + "bytes")print("Size of dic2: " + str(sys.getsizeof(dic2)) + "bytes")print("Size of dic3: " + str(sys.getsizeof(dic3)) + "bytes")
Output:
Size of dic1: 216bytes
Size of dic2: 216bytes
Size of dic3: 216bytes
1.Using inbuilt __sizeof__() method:
Python also has an inbuilt __sizeof__() method to determine the space allocation of an object without any additional garbage value. It has been implemented in the below example.Example 2:
# sample Dictionariesdic1 = {"A": 1, "B": 2, "C": 3} dic2 = {"Geek1": "Raju", "Geek2": "Nikhil", "Geek3": "Deepanshu"}dic3 = {1: "Lion", 2: "Tiger", 3: "Fox", 4: "Wolf"} # print the sizes of sample Dictionariesprint("Size of dic1: " + str(dic1.__sizeof__()) + "bytes")print("Size of dic2: " + str(dic2.__sizeof__()) + "bytes")print("Size of dic3: " + str(dic3.__sizeof__()) + "bytes")
Output:
Size of dic1: 216bytes
Size of dic2: 216bytes
Size of dic3: 216bytes
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
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": 26033,
"s": 26005,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 26488,
"s": 26033,
"text": "Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized. The size of a Dictionary means the amount of memory (in bytes) occupied by a Dictionary object. In this article, we will learn various ways to get the size of a python Dictionary."
},
{
"code": null,
"e": 26518,
"s": 26488,
"text": "1.Using getsizeof() function:"
},
{
"code": null,
"e": 26625,
"s": 26518,
"text": "The getsizeof() function belongs to the python’s sys module. It has been implemented in the below example."
},
{
"code": null,
"e": 26636,
"s": 26625,
"text": "Example 1:"
},
{
"code": "import sys # sample Dictionariesdic1 = {\"A\": 1, \"B\": 2, \"C\": 3} dic2 = {\"Geek1\": \"Raju\", \"Geek2\": \"Nikhil\", \"Geek3\": \"Deepanshu\"}dic3 = {1: \"Lion\", 2: \"Tiger\", 3: \"Fox\", 4: \"Wolf\"} # print the sizes of sample Dictionariesprint(\"Size of dic1: \" + str(sys.getsizeof(dic1)) + \"bytes\")print(\"Size of dic2: \" + str(sys.getsizeof(dic2)) + \"bytes\")print(\"Size of dic3: \" + str(sys.getsizeof(dic3)) + \"bytes\")",
"e": 27040,
"s": 26636,
"text": null
},
{
"code": null,
"e": 27048,
"s": 27040,
"text": "Output:"
},
{
"code": null,
"e": 27117,
"s": 27048,
"text": "Size of dic1: 216bytes\nSize of dic2: 216bytes\nSize of dic3: 216bytes"
},
{
"code": null,
"e": 27154,
"s": 27117,
"text": "1.Using inbuilt __sizeof__() method:"
},
{
"code": null,
"e": 27342,
"s": 27154,
"text": "Python also has an inbuilt __sizeof__() method to determine the space allocation of an object without any additional garbage value. It has been implemented in the below example.Example 2:"
},
{
"code": "# sample Dictionariesdic1 = {\"A\": 1, \"B\": 2, \"C\": 3} dic2 = {\"Geek1\": \"Raju\", \"Geek2\": \"Nikhil\", \"Geek3\": \"Deepanshu\"}dic3 = {1: \"Lion\", 2: \"Tiger\", 3: \"Fox\", 4: \"Wolf\"} # print the sizes of sample Dictionariesprint(\"Size of dic1: \" + str(dic1.__sizeof__()) + \"bytes\")print(\"Size of dic2: \" + str(dic2.__sizeof__()) + \"bytes\")print(\"Size of dic3: \" + str(dic3.__sizeof__()) + \"bytes\")",
"e": 27728,
"s": 27342,
"text": null
},
{
"code": null,
"e": 27736,
"s": 27728,
"text": "Output:"
},
{
"code": null,
"e": 27805,
"s": 27736,
"text": "Size of dic1: 216bytes\nSize of dic2: 216bytes\nSize of dic3: 216bytes"
},
{
"code": null,
"e": 27832,
"s": 27805,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27839,
"s": 27832,
"text": "Python"
},
{
"code": null,
"e": 27855,
"s": 27839,
"text": "Python Programs"
},
{
"code": null,
"e": 27953,
"s": 27855,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27971,
"s": 27953,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28006,
"s": 27971,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28038,
"s": 28006,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28060,
"s": 28038,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28102,
"s": 28060,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28145,
"s": 28102,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28167,
"s": 28145,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28206,
"s": 28167,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28252,
"s": 28206,
"text": "Python | Split string into list of characters"
}
] |
Playfair Cipher with Examples - GeeksforGeeks | 24 Dec, 2021
The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in 1854 by Charles Wheatstone but was named after Lord Playfair who promoted the use of the cipher. In playfair cipher unlike traditional cipher we encrypt a pair of alphabets(digraphs) instead of a single alphabet.It was used for tactical purposes by British forces in the Second Boer War and in World War I and for the same purpose by the Australians during World War II. This was because Playfair is reasonably fast to use and requires no special equipment.
For the encryption process let us consider the following example:
The Playfair Cipher Encryption Algorithm: The Algorithm consists of 2 steps:
Generate the key Square(5×5): The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is replaced by I. The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order. Algorithm to encrypt the plain text: The plaintext is split into pairs of two letters (digraphs). If there is an odd number of letters, a Z is added to the last letter. For example:
Generate the key Square(5×5): The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is replaced by I. The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order.
The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is replaced by I.
The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order.
Algorithm to encrypt the plain text: The plaintext is split into pairs of two letters (digraphs). If there is an odd number of letters, a Z is added to the last letter. For example:
PlainText: "instruments"
After Split: 'in' 'st' 'ru' 'me' 'nt' 'sz'
1. Pair cannot be made with same letter. Break the letter in single and add a bogus letter to the previous letter.
Plain Text: “hello”
After Split: ‘he’ ‘lx’ ‘lo’
Here ‘x’ is the bogus letter.
2. If the letter is standing alone in the process of pairing, then add an extra bogus letter with the alone letter
Plain Text: “helloe”
AfterSplit: ‘he’ ‘lx’ ‘lo’ ‘ez’
Here ‘z’ is the bogus letter.
Rules for Encryption:
If both the letters are in the same column: Take the letter below each one (going back to the top if at the bottom).For example:
Diagraph: "me"
Encrypted Text: cl
Encryption:
m -> c
e -> l
If both the letters are in the same row: Take the letter to the right of each one (going back to the leftmost if at the rightmost position).For example:
Diagraph: "st"
Encrypted Text: tl
Encryption:
s -> t
t -> l
If neither of the above rules is true: Form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle.For example:
Diagraph: "nt"
Encrypted Text: rq
Encryption:
n -> r
t -> q
For example:
Plain Text: "instrumentsz"
Encrypted Text: gatlmzclrqtx
Encryption:
i -> g
n -> a
s -> t
t -> l
r -> m
u -> z
m -> c
e -> l
n -> r
t -> q
s -> t
z -> x
Below is an implementation of Playfair Cipher in C:
C
// C program to implement Playfair Cipher #include <stdio.h>#include <stdlib.h>#include <string.h> #define SIZE 30 // Function to convert the string to lowercasevoid toLowerCase(char plain[], int ps){ int i; for (i = 0; i < ps; i++) { if (plain[i] > 64 && plain[i] < 91) plain[i] += 32; }} // Function to remove all spaces in a stringint removeSpaces(char* plain, int ps){ int i, count = 0; for (i = 0; i < ps; i++) if (plain[i] != ' ') plain[count++] = plain[i]; plain[count] = '\0'; return count;} // Function to generate the 5x5 key squarevoid generateKeyTable(char key[], int ks, char keyT[5][5]){ int i, j, k, flag = 0, *dicty; // a 26 character hashmap // to store count of the alphabet dicty = (int*)calloc(26, sizeof(int)); for (i = 0; i < ks; i++) { if (key[i] != 'j') dicty[key[i] - 97] = 2; } dicty['j' - 97] = 1; i = 0; j = 0; for (k = 0; k < ks; k++) { if (dicty[key[k] - 97] == 2) { dicty[key[k] - 97] -= 1; keyT[i][j] = key[k]; j++; if (j == 5) { i++; j = 0; } } } for (k = 0; k < 26; k++) { if (dicty[k] == 0) { keyT[i][j] = (char)(k + 97); j++; if (j == 5) { i++; j = 0; } } }} // Function to search for the characters of a digraph// in the key square and return their positionvoid search(char keyT[5][5], char a, char b, int arr[]){ int i, j; if (a == 'j') a = 'i'; else if (b == 'j') b = 'i'; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { if (keyT[i][j] == a) { arr[0] = i; arr[1] = j; } else if (keyT[i][j] == b) { arr[2] = i; arr[3] = j; } } }} // Function to find the modulus with 5int mod5(int a) { return (a % 5); } // Function to make the plain text length to be evenint prepare(char str[], int ptrs){ if (ptrs % 2 != 0) { str[ptrs++] = 'z'; str[ptrs] = '\0'; } return ptrs;} // Function for performing the encryptionvoid encrypt(char str[], char keyT[5][5], int ps){ int i, a[4]; for (i = 0; i < ps; i += 2) { search(keyT, str[i], str[i + 1], a); if (a[0] == a[2]) { str[i] = keyT[a[0]][mod5(a[1] + 1)]; str[i + 1] = keyT[a[0]][mod5(a[3] + 1)]; } else if (a[1] == a[3]) { str[i] = keyT[mod5(a[0] + 1)][a[1]]; str[i + 1] = keyT[mod5(a[2] + 1)][a[1]]; } else { str[i] = keyT[a[0]][a[3]]; str[i + 1] = keyT[a[2]][a[1]]; } }} // Function to encrypt using Playfair Ciphervoid encryptByPlayfairCipher(char str[], char key[]){ char ps, ks, keyT[5][5]; // Key ks = strlen(key); ks = removeSpaces(key, ks); toLowerCase(key, ks); // Plaintext ps = strlen(str); toLowerCase(str, ps); ps = removeSpaces(str, ps); ps = prepare(str, ps); generateKeyTable(key, ks, keyT); encrypt(str, keyT, ps);} // Driver codeint main(){ char str[SIZE], key[SIZE]; // Key to be encrypted strcpy(key, "Monarchy"); printf("Key text: %s\n", key); // Plaintext to be encrypted strcpy(str, "instruments"); printf("Plain text: %s\n", str); // encrypt using Playfair Cipher encryptByPlayfairCipher(str, key); printf("Cipher text: %s\n", str); return 0;} // This code is contributed by AbhayBhat
Key text: Monarchy
Plain text: instruments
Cipher text: gatlmzclrqtx
Decrypting the Playfair cipher is as simple as doing the same process in reverse. The receiver has the same key and can create the same key table, and then decrypt any messages made using that key.
The Playfair Cipher Decryption Algorithm: The Algorithm consistes of 2 steps:
Generate the key Square(5×5) at the receiver’s end: The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is replaced by I. The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order. Algorithm to decrypt the ciphertext: The ciphertext is split into pairs of two letters (digraphs).
Generate the key Square(5×5) at the receiver’s end: The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is replaced by I. The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order.
The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is replaced by I.
The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order.
Algorithm to decrypt the ciphertext: The ciphertext is split into pairs of two letters (digraphs).
Note: The ciphertext always have even number of characters.
For example:
For example:
CipherText: "gatlmzclrqtx"
After Split: 'ga' 'tl' 'mz' 'cl' 'rq' 'tx'
Rules for Decryption: If both the letters are in the same column: Take the letter above each one (going back to the bottom if at the top).For example:
Rules for Decryption: If both the letters are in the same column: Take the letter above each one (going back to the bottom if at the top).For example:
If both the letters are in the same column: Take the letter above each one (going back to the bottom if at the top).For example:
Diagraph: "cl"
Decrypted Text: me
Decryption:
c -> m
l -> e
If both the letters are in the same row: Take the letter to the left of each one (going back to the rightmost if at the leftmost position).For example:
Diagraph: "tl"
Decrypted Text: st
Decryption:
t -> s
l -> t
If neither of the above rules is true: Form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle.For example:
Diagraph: "rq"
Decrypted Text: nt
Decryption:
r -> n
q -> t
For example:
Plain Text: "gatlmzclrqtx"
Decrypted Text: instrumentsz
Decryption:
(red)-> (green)
ga -> in
tl -> st
mz -> ru
cl -> me
rq -> nt
tx -> sz
Below is an implementation of Playfair Cipher Decryption in C:
C
#include <stdio.h>#include <stdlib.h>#include <string.h>#define SIZE 30 // Convert all the characters// of a string to lowercasevoid toLowerCase(char plain[], int ps){ int i; for (i = 0; i < ps; i++) { if (plain[i] > 64 && plain[i] < 91) plain[i] += 32; }} // Remove all spaces in a string// can be extended to remove punctuationint removeSpaces(char* plain, int ps){ int i, count = 0; for (i = 0; i < ps; i++) if (plain[i] != ' ') plain[count++] = plain[i]; plain[count] = '\0'; return count;} // generates the 5x5 key squarevoid generateKeyTable(char key[], int ks, char keyT[5][5]){ int i, j, k, flag = 0, *dicty; // a 26 character hashmap // to store count of the alphabet dicty = (int*)calloc(26, sizeof(int)); for (i = 0; i < ks; i++) { if (key[i] != 'j') dicty[key[i] - 97] = 2; } dicty['j' - 97] = 1; i = 0; j = 0; for (k = 0; k < ks; k++) { if (dicty[key[k] - 97] == 2) { dicty[key[k] - 97] -= 1; keyT[i][j] = key[k]; j++; if (j == 5) { i++; j = 0; } } } for (k = 0; k < 26; k++) { if (dicty[k] == 0) { keyT[i][j] = (char)(k + 97); j++; if (j == 5) { i++; j = 0; } } }} // Search for the characters of a digraph// in the key square and return their positionvoid search(char keyT[5][5], char a, char b, int arr[]){ int i, j; if (a == 'j') a = 'i'; else if (b == 'j') b = 'i'; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { if (keyT[i][j] == a) { arr[0] = i; arr[1] = j; } else if (keyT[i][j] == b) { arr[2] = i; arr[3] = j; } } }} // Function to find the modulus with 5int mod5(int a){ if (a < 0) a += 5; return (a % 5);} // Function to decryptvoid decrypt(char str[], char keyT[5][5], int ps){ int i, a[4]; for (i = 0; i < ps; i += 2) { search(keyT, str[i], str[i + 1], a); if (a[0] == a[2]) { str[i] = keyT[a[0]][mod5(a[1] - 1)]; str[i + 1] = keyT[a[0]][mod5(a[3] - 1)]; } else if (a[1] == a[3]) { str[i] = keyT[mod5(a[0] - 1)][a[1]]; str[i + 1] = keyT[mod5(a[2] - 1)][a[1]]; } else { str[i] = keyT[a[0]][a[3]]; str[i + 1] = keyT[a[2]][a[1]]; } }} // Function to call decryptvoid decryptByPlayfairCipher(char str[], char key[]){ char ps, ks, keyT[5][5]; // Key ks = strlen(key); ks = removeSpaces(key, ks); toLowerCase(key, ks); // ciphertext ps = strlen(str); toLowerCase(str, ps); ps = removeSpaces(str, ps); generateKeyTable(key, ks, keyT); decrypt(str, keyT, ps);} // Driver codeint main(){ char str[SIZE], key[SIZE]; // Key to be encrypted strcpy(key, "Monarchy"); printf("Key text: %s\n", key); // Ciphertext to be decrypted strcpy(str, "gatlmzclrqtx"); printf("Plain text: %s\n", str); // encrypt using Playfair Cipher decryptByPlayfairCipher(str, key); printf("Deciphered text: %s\n", str); return 0;} // This code is contributed by AbhayBhat
Key text: Monarchy
Plain text: gatlmzclrqtx
Deciphered text: instrumentsz
Advantages: It is significantly harder to break since the frequency analysis technique used to break simple substitution ciphers is difficult but still can be used on (25*25) = 625 digraphs rather than 25 monographs which is difficult. Frequency analysis thus requires more cipher text to crack the encryption.
It is significantly harder to break since the frequency analysis technique used to break simple substitution ciphers is difficult but still can be used on (25*25) = 625 digraphs rather than 25 monographs which is difficult. Frequency analysis thus requires more cipher text to crack the encryption.
It is significantly harder to break since the frequency analysis technique used to break simple substitution ciphers is difficult but still can be used on (25*25) = 625 digraphs rather than 25 monographs which is difficult.
Frequency analysis thus requires more cipher text to crack the encryption.
Disadvantages: An interesting weakness is the fact that a digraph in the ciphertext (AB) and it’s reverse (BA) will have corresponding plaintexts like UR and RU (and also ciphertext UR and RU will correspond to plaintext AB and BA, i.e. the substitution is self-inverse). That can easily be exploited with the aid of frequency analysis, if the language of the plaintext is known. Another disadvantage is that playfair cipher is a symmetric cipher thus same key is used for both encryption and decryption.
An interesting weakness is the fact that a digraph in the ciphertext (AB) and it’s reverse (BA) will have corresponding plaintexts like UR and RU (and also ciphertext UR and RU will correspond to plaintext AB and BA, i.e. the substitution is self-inverse). That can easily be exploited with the aid of frequency analysis, if the language of the plaintext is known. Another disadvantage is that playfair cipher is a symmetric cipher thus same key is used for both encryption and decryption.
An interesting weakness is the fact that a digraph in the ciphertext (AB) and it’s reverse (BA) will have corresponding plaintexts like UR and RU (and also ciphertext UR and RU will correspond to plaintext AB and BA, i.e. the substitution is self-inverse). That can easily be exploited with the aid of frequency analysis, if the language of the plaintext is known.
Another disadvantage is that playfair cipher is a symmetric cipher thus same key is used for both encryption and decryption.
divyanshtrivedi16
aashray1042
codeyash
vaniyagoel
cryptography
Algorithms
cryptography
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
How to Start Learning DSA?
Difference between NP hard and NP complete problem
Converting Roman Numerals to Decimal lying between 1 to 3999
Difference between Algorithm, Pseudocode and Program
Generate all permutation of a set in Python
Difference Between Symmetric and Asymmetric Key Encryption
K means Clustering - Introduction | [
{
"code": null,
"e": 25733,
"s": 25705,
"text": "\n24 Dec, 2021"
},
{
"code": null,
"e": 26292,
"s": 25733,
"text": "The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented in 1854 by Charles Wheatstone but was named after Lord Playfair who promoted the use of the cipher. In playfair cipher unlike traditional cipher we encrypt a pair of alphabets(digraphs) instead of a single alphabet.It was used for tactical purposes by British forces in the Second Boer War and in World War I and for the same purpose by the Australians during World War II. This was because Playfair is reasonably fast to use and requires no special equipment. "
},
{
"code": null,
"e": 26359,
"s": 26292,
"text": "For the encryption process let us consider the following example: "
},
{
"code": null,
"e": 26438,
"s": 26359,
"text": "The Playfair Cipher Encryption Algorithm: The Algorithm consists of 2 steps: "
},
{
"code": null,
"e": 27124,
"s": 26438,
"text": "Generate the key Square(5×5): The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is replaced by I. The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order. Algorithm to encrypt the plain text: The plaintext is split into pairs of two letters (digraphs). If there is an odd number of letters, a Z is added to the last letter. For example: "
},
{
"code": null,
"e": 27627,
"s": 27124,
"text": "Generate the key Square(5×5): The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is replaced by I. The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order. "
},
{
"code": null,
"e": 27929,
"s": 27627,
"text": "The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is replaced by I. "
},
{
"code": null,
"e": 28101,
"s": 27929,
"text": "The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order. "
},
{
"code": null,
"e": 28285,
"s": 28101,
"text": "Algorithm to encrypt the plain text: The plaintext is split into pairs of two letters (digraphs). If there is an odd number of letters, a Z is added to the last letter. For example: "
},
{
"code": null,
"e": 28354,
"s": 28285,
"text": "PlainText: \"instruments\" \nAfter Split: 'in' 'st' 'ru' 'me' 'nt' 'sz'"
},
{
"code": null,
"e": 28469,
"s": 28354,
"text": "1. Pair cannot be made with same letter. Break the letter in single and add a bogus letter to the previous letter."
},
{
"code": null,
"e": 28489,
"s": 28469,
"text": "Plain Text: “hello”"
},
{
"code": null,
"e": 28517,
"s": 28489,
"text": "After Split: ‘he’ ‘lx’ ‘lo’"
},
{
"code": null,
"e": 28547,
"s": 28517,
"text": "Here ‘x’ is the bogus letter."
},
{
"code": null,
"e": 28662,
"s": 28547,
"text": "2. If the letter is standing alone in the process of pairing, then add an extra bogus letter with the alone letter"
},
{
"code": null,
"e": 28683,
"s": 28662,
"text": "Plain Text: “helloe”"
},
{
"code": null,
"e": 28715,
"s": 28683,
"text": "AfterSplit: ‘he’ ‘lx’ ‘lo’ ‘ez’"
},
{
"code": null,
"e": 28746,
"s": 28715,
"text": "Here ‘z’ is the bogus letter."
},
{
"code": null,
"e": 28770,
"s": 28746,
"text": "Rules for Encryption: "
},
{
"code": null,
"e": 28901,
"s": 28770,
"text": "If both the letters are in the same column: Take the letter below each one (going back to the top if at the bottom).For example: "
},
{
"code": null,
"e": 28966,
"s": 28901,
"text": "Diagraph: \"me\"\nEncrypted Text: cl\nEncryption: \n m -> c\n e -> l"
},
{
"code": null,
"e": 29125,
"s": 28970,
"text": "If both the letters are in the same row: Take the letter to the right of each one (going back to the leftmost if at the rightmost position).For example: "
},
{
"code": null,
"e": 29190,
"s": 29125,
"text": "Diagraph: \"st\"\nEncrypted Text: tl\nEncryption: \n s -> t\n t -> l"
},
{
"code": null,
"e": 29358,
"s": 29194,
"text": "If neither of the above rules is true: Form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle.For example: "
},
{
"code": null,
"e": 29423,
"s": 29358,
"text": "Diagraph: \"nt\"\nEncrypted Text: rq\nEncryption: \n n -> r\n t -> q"
},
{
"code": null,
"e": 29442,
"s": 29427,
"text": "For example: "
},
{
"code": null,
"e": 29619,
"s": 29442,
"text": "Plain Text: \"instrumentsz\"\nEncrypted Text: gatlmzclrqtx\nEncryption: \n i -> g\n n -> a\n s -> t\n t -> l\n r -> m\n u -> z\n m -> c\n e -> l\n n -> r\n t -> q\n s -> t\n z -> x"
},
{
"code": null,
"e": 29674,
"s": 29621,
"text": "Below is an implementation of Playfair Cipher in C: "
},
{
"code": null,
"e": 29676,
"s": 29674,
"text": "C"
},
{
"code": "// C program to implement Playfair Cipher #include <stdio.h>#include <stdlib.h>#include <string.h> #define SIZE 30 // Function to convert the string to lowercasevoid toLowerCase(char plain[], int ps){ int i; for (i = 0; i < ps; i++) { if (plain[i] > 64 && plain[i] < 91) plain[i] += 32; }} // Function to remove all spaces in a stringint removeSpaces(char* plain, int ps){ int i, count = 0; for (i = 0; i < ps; i++) if (plain[i] != ' ') plain[count++] = plain[i]; plain[count] = '\\0'; return count;} // Function to generate the 5x5 key squarevoid generateKeyTable(char key[], int ks, char keyT[5][5]){ int i, j, k, flag = 0, *dicty; // a 26 character hashmap // to store count of the alphabet dicty = (int*)calloc(26, sizeof(int)); for (i = 0; i < ks; i++) { if (key[i] != 'j') dicty[key[i] - 97] = 2; } dicty['j' - 97] = 1; i = 0; j = 0; for (k = 0; k < ks; k++) { if (dicty[key[k] - 97] == 2) { dicty[key[k] - 97] -= 1; keyT[i][j] = key[k]; j++; if (j == 5) { i++; j = 0; } } } for (k = 0; k < 26; k++) { if (dicty[k] == 0) { keyT[i][j] = (char)(k + 97); j++; if (j == 5) { i++; j = 0; } } }} // Function to search for the characters of a digraph// in the key square and return their positionvoid search(char keyT[5][5], char a, char b, int arr[]){ int i, j; if (a == 'j') a = 'i'; else if (b == 'j') b = 'i'; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { if (keyT[i][j] == a) { arr[0] = i; arr[1] = j; } else if (keyT[i][j] == b) { arr[2] = i; arr[3] = j; } } }} // Function to find the modulus with 5int mod5(int a) { return (a % 5); } // Function to make the plain text length to be evenint prepare(char str[], int ptrs){ if (ptrs % 2 != 0) { str[ptrs++] = 'z'; str[ptrs] = '\\0'; } return ptrs;} // Function for performing the encryptionvoid encrypt(char str[], char keyT[5][5], int ps){ int i, a[4]; for (i = 0; i < ps; i += 2) { search(keyT, str[i], str[i + 1], a); if (a[0] == a[2]) { str[i] = keyT[a[0]][mod5(a[1] + 1)]; str[i + 1] = keyT[a[0]][mod5(a[3] + 1)]; } else if (a[1] == a[3]) { str[i] = keyT[mod5(a[0] + 1)][a[1]]; str[i + 1] = keyT[mod5(a[2] + 1)][a[1]]; } else { str[i] = keyT[a[0]][a[3]]; str[i + 1] = keyT[a[2]][a[1]]; } }} // Function to encrypt using Playfair Ciphervoid encryptByPlayfairCipher(char str[], char key[]){ char ps, ks, keyT[5][5]; // Key ks = strlen(key); ks = removeSpaces(key, ks); toLowerCase(key, ks); // Plaintext ps = strlen(str); toLowerCase(str, ps); ps = removeSpaces(str, ps); ps = prepare(str, ps); generateKeyTable(key, ks, keyT); encrypt(str, keyT, ps);} // Driver codeint main(){ char str[SIZE], key[SIZE]; // Key to be encrypted strcpy(key, \"Monarchy\"); printf(\"Key text: %s\\n\", key); // Plaintext to be encrypted strcpy(str, \"instruments\"); printf(\"Plain text: %s\\n\", str); // encrypt using Playfair Cipher encryptByPlayfairCipher(str, key); printf(\"Cipher text: %s\\n\", str); return 0;} // This code is contributed by AbhayBhat",
"e": 33252,
"s": 29676,
"text": null
},
{
"code": null,
"e": 33321,
"s": 33252,
"text": "Key text: Monarchy\nPlain text: instruments\nCipher text: gatlmzclrqtx"
},
{
"code": null,
"e": 33520,
"s": 33321,
"text": "Decrypting the Playfair cipher is as simple as doing the same process in reverse. The receiver has the same key and can create the same key table, and then decrypt any messages made using that key. "
},
{
"code": null,
"e": 33600,
"s": 33520,
"text": "The Playfair Cipher Decryption Algorithm: The Algorithm consistes of 2 steps: "
},
{
"code": null,
"e": 34225,
"s": 33600,
"text": "Generate the key Square(5×5) at the receiver’s end: The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is replaced by I. The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order. Algorithm to decrypt the ciphertext: The ciphertext is split into pairs of two letters (digraphs). "
},
{
"code": null,
"e": 34750,
"s": 34225,
"text": "Generate the key Square(5×5) at the receiver’s end: The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is replaced by I. The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order. "
},
{
"code": null,
"e": 35052,
"s": 34750,
"text": "The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is replaced by I. "
},
{
"code": null,
"e": 35224,
"s": 35052,
"text": "The initial alphabets in the key square are the unique alphabets of the key in the order in which they appear followed by the remaining letters of the alphabet in order. "
},
{
"code": null,
"e": 35325,
"s": 35224,
"text": "Algorithm to decrypt the ciphertext: The ciphertext is split into pairs of two letters (digraphs). "
},
{
"code": null,
"e": 35385,
"s": 35325,
"text": "Note: The ciphertext always have even number of characters."
},
{
"code": null,
"e": 35400,
"s": 35385,
"text": "For example: "
},
{
"code": null,
"e": 35415,
"s": 35400,
"text": "For example: "
},
{
"code": null,
"e": 35486,
"s": 35415,
"text": "CipherText: \"gatlmzclrqtx\" \nAfter Split: 'ga' 'tl' 'mz' 'cl' 'rq' 'tx'"
},
{
"code": null,
"e": 35639,
"s": 35486,
"text": "Rules for Decryption: If both the letters are in the same column: Take the letter above each one (going back to the bottom if at the top).For example: "
},
{
"code": null,
"e": 35792,
"s": 35639,
"text": "Rules for Decryption: If both the letters are in the same column: Take the letter above each one (going back to the bottom if at the top).For example: "
},
{
"code": null,
"e": 35923,
"s": 35792,
"text": "If both the letters are in the same column: Take the letter above each one (going back to the bottom if at the top).For example: "
},
{
"code": null,
"e": 35989,
"s": 35923,
"text": "Diagraph: \"cl\" \nDecrypted Text: me\nDecryption: \n c -> m\n l -> e"
},
{
"code": null,
"e": 36147,
"s": 35993,
"text": "If both the letters are in the same row: Take the letter to the left of each one (going back to the rightmost if at the leftmost position).For example: "
},
{
"code": null,
"e": 36214,
"s": 36147,
"text": "Diagraph: \"tl\" \nDecrypted Text: st \nDecryption: \n t -> s\n l -> t"
},
{
"code": null,
"e": 36382,
"s": 36218,
"text": "If neither of the above rules is true: Form a rectangle with the two letters and take the letters on the horizontal opposite corner of the rectangle.For example: "
},
{
"code": null,
"e": 36449,
"s": 36382,
"text": "Diagraph: \"rq\" \nDecrypted Text: nt \nDecryption: \n r -> n\n q -> t"
},
{
"code": null,
"e": 36468,
"s": 36453,
"text": "For example: "
},
{
"code": null,
"e": 36619,
"s": 36468,
"text": "Plain Text: \"gatlmzclrqtx\"\nDecrypted Text: instrumentsz\nDecryption: \n(red)-> (green)\n ga -> in\n tl -> st\n mz -> ru\n cl -> me\n rq -> nt\n tx -> sz"
},
{
"code": null,
"e": 36686,
"s": 36621,
"text": "Below is an implementation of Playfair Cipher Decryption in C: "
},
{
"code": null,
"e": 36688,
"s": 36686,
"text": "C"
},
{
"code": "#include <stdio.h>#include <stdlib.h>#include <string.h>#define SIZE 30 // Convert all the characters// of a string to lowercasevoid toLowerCase(char plain[], int ps){ int i; for (i = 0; i < ps; i++) { if (plain[i] > 64 && plain[i] < 91) plain[i] += 32; }} // Remove all spaces in a string// can be extended to remove punctuationint removeSpaces(char* plain, int ps){ int i, count = 0; for (i = 0; i < ps; i++) if (plain[i] != ' ') plain[count++] = plain[i]; plain[count] = '\\0'; return count;} // generates the 5x5 key squarevoid generateKeyTable(char key[], int ks, char keyT[5][5]){ int i, j, k, flag = 0, *dicty; // a 26 character hashmap // to store count of the alphabet dicty = (int*)calloc(26, sizeof(int)); for (i = 0; i < ks; i++) { if (key[i] != 'j') dicty[key[i] - 97] = 2; } dicty['j' - 97] = 1; i = 0; j = 0; for (k = 0; k < ks; k++) { if (dicty[key[k] - 97] == 2) { dicty[key[k] - 97] -= 1; keyT[i][j] = key[k]; j++; if (j == 5) { i++; j = 0; } } } for (k = 0; k < 26; k++) { if (dicty[k] == 0) { keyT[i][j] = (char)(k + 97); j++; if (j == 5) { i++; j = 0; } } }} // Search for the characters of a digraph// in the key square and return their positionvoid search(char keyT[5][5], char a, char b, int arr[]){ int i, j; if (a == 'j') a = 'i'; else if (b == 'j') b = 'i'; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { if (keyT[i][j] == a) { arr[0] = i; arr[1] = j; } else if (keyT[i][j] == b) { arr[2] = i; arr[3] = j; } } }} // Function to find the modulus with 5int mod5(int a){ if (a < 0) a += 5; return (a % 5);} // Function to decryptvoid decrypt(char str[], char keyT[5][5], int ps){ int i, a[4]; for (i = 0; i < ps; i += 2) { search(keyT, str[i], str[i + 1], a); if (a[0] == a[2]) { str[i] = keyT[a[0]][mod5(a[1] - 1)]; str[i + 1] = keyT[a[0]][mod5(a[3] - 1)]; } else if (a[1] == a[3]) { str[i] = keyT[mod5(a[0] - 1)][a[1]]; str[i + 1] = keyT[mod5(a[2] - 1)][a[1]]; } else { str[i] = keyT[a[0]][a[3]]; str[i + 1] = keyT[a[2]][a[1]]; } }} // Function to call decryptvoid decryptByPlayfairCipher(char str[], char key[]){ char ps, ks, keyT[5][5]; // Key ks = strlen(key); ks = removeSpaces(key, ks); toLowerCase(key, ks); // ciphertext ps = strlen(str); toLowerCase(str, ps); ps = removeSpaces(str, ps); generateKeyTable(key, ks, keyT); decrypt(str, keyT, ps);} // Driver codeint main(){ char str[SIZE], key[SIZE]; // Key to be encrypted strcpy(key, \"Monarchy\"); printf(\"Key text: %s\\n\", key); // Ciphertext to be decrypted strcpy(str, \"gatlmzclrqtx\"); printf(\"Plain text: %s\\n\", str); // encrypt using Playfair Cipher decryptByPlayfairCipher(str, key); printf(\"Deciphered text: %s\\n\", str); return 0;} // This code is contributed by AbhayBhat",
"e": 40019,
"s": 36688,
"text": null
},
{
"code": null,
"e": 40093,
"s": 40019,
"text": "Key text: Monarchy\nPlain text: gatlmzclrqtx\nDeciphered text: instrumentsz"
},
{
"code": null,
"e": 40407,
"s": 40093,
"text": "Advantages: It is significantly harder to break since the frequency analysis technique used to break simple substitution ciphers is difficult but still can be used on (25*25) = 625 digraphs rather than 25 monographs which is difficult. Frequency analysis thus requires more cipher text to crack the encryption. "
},
{
"code": null,
"e": 40709,
"s": 40407,
"text": "It is significantly harder to break since the frequency analysis technique used to break simple substitution ciphers is difficult but still can be used on (25*25) = 625 digraphs rather than 25 monographs which is difficult. Frequency analysis thus requires more cipher text to crack the encryption. "
},
{
"code": null,
"e": 40935,
"s": 40709,
"text": "It is significantly harder to break since the frequency analysis technique used to break simple substitution ciphers is difficult but still can be used on (25*25) = 625 digraphs rather than 25 monographs which is difficult. "
},
{
"code": null,
"e": 41012,
"s": 40935,
"text": "Frequency analysis thus requires more cipher text to crack the encryption. "
},
{
"code": null,
"e": 41520,
"s": 41012,
"text": "Disadvantages: An interesting weakness is the fact that a digraph in the ciphertext (AB) and it’s reverse (BA) will have corresponding plaintexts like UR and RU (and also ciphertext UR and RU will correspond to plaintext AB and BA, i.e. the substitution is self-inverse). That can easily be exploited with the aid of frequency analysis, if the language of the plaintext is known. Another disadvantage is that playfair cipher is a symmetric cipher thus same key is used for both encryption and decryption. "
},
{
"code": null,
"e": 42013,
"s": 41520,
"text": "An interesting weakness is the fact that a digraph in the ciphertext (AB) and it’s reverse (BA) will have corresponding plaintexts like UR and RU (and also ciphertext UR and RU will correspond to plaintext AB and BA, i.e. the substitution is self-inverse). That can easily be exploited with the aid of frequency analysis, if the language of the plaintext is known. Another disadvantage is that playfair cipher is a symmetric cipher thus same key is used for both encryption and decryption. "
},
{
"code": null,
"e": 42380,
"s": 42013,
"text": "An interesting weakness is the fact that a digraph in the ciphertext (AB) and it’s reverse (BA) will have corresponding plaintexts like UR and RU (and also ciphertext UR and RU will correspond to plaintext AB and BA, i.e. the substitution is self-inverse). That can easily be exploited with the aid of frequency analysis, if the language of the plaintext is known. "
},
{
"code": null,
"e": 42507,
"s": 42380,
"text": "Another disadvantage is that playfair cipher is a symmetric cipher thus same key is used for both encryption and decryption. "
},
{
"code": null,
"e": 42525,
"s": 42507,
"text": "divyanshtrivedi16"
},
{
"code": null,
"e": 42537,
"s": 42525,
"text": "aashray1042"
},
{
"code": null,
"e": 42546,
"s": 42537,
"text": "codeyash"
},
{
"code": null,
"e": 42557,
"s": 42546,
"text": "vaniyagoel"
},
{
"code": null,
"e": 42570,
"s": 42557,
"text": "cryptography"
},
{
"code": null,
"e": 42581,
"s": 42570,
"text": "Algorithms"
},
{
"code": null,
"e": 42594,
"s": 42581,
"text": "cryptography"
},
{
"code": null,
"e": 42605,
"s": 42594,
"text": "Algorithms"
},
{
"code": null,
"e": 42703,
"s": 42605,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42752,
"s": 42703,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 42777,
"s": 42752,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 42804,
"s": 42777,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 42831,
"s": 42804,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 42882,
"s": 42831,
"text": "Difference between NP hard and NP complete problem"
},
{
"code": null,
"e": 42943,
"s": 42882,
"text": "Converting Roman Numerals to Decimal lying between 1 to 3999"
},
{
"code": null,
"e": 42996,
"s": 42943,
"text": "Difference between Algorithm, Pseudocode and Program"
},
{
"code": null,
"e": 43040,
"s": 42996,
"text": "Generate all permutation of a set in Python"
},
{
"code": null,
"e": 43099,
"s": 43040,
"text": "Difference Between Symmetric and Asymmetric Key Encryption"
}
] |
HTML <slot> Tag - GeeksforGeeks | 18 Oct, 2021
The slot is the element part of the web component technology which is a placeholder inside a component that you simply can fill together with your own markup, which allows you to make separate DOM trees and represent them together.
Syntax:
<slot>
<h1>Heading</h1>
</slot>
Attributes:
name: It describes the name of the slot.
Approach: The following elements are used in the example code given below.
Template: The template element is employed to declare fragments of HTML that will be inserted within the document by script. Contents aren’t rendered until they are added to the document in a script. This is often the part that contains the <slot> elements.
Content: This part contains the content that’s inserted where the <slot> elements are within the template. So during this case, the span elements will find yourself where the elements are available. Each span element refers to a selected <slot> element via its slot attribute. Any CSS that you simply include within the template element is merely applied to the DOM tree. It won’t affect the remainder of the page.
Script: The primary list is inserted <slot> with the element but the second list isn’t. The main styles are declared inside the template element, which suggests that they are only applied to HTML elements that are within that shadow DOM tree. If the styles are outside of the template element, those styles are only applied to the second list, and therefore the first list goes unstyled.
Example:
HTML
<!DOCTYPE html><html lang="en"> <head> <style> h1 { font-size: 2.2em; font-family: Arial, Helvetica, sans-serif; color: coral; } dl { border-left: 5px solid yellowgreen; padding-left: 1em; } dt { font-weight: bold; font-size: 2em; } dd { color: darkslategray; font-size: 1.6em; } </style></head> <body> <template> <h1> <slot name="heading"></slot> </h1> <dl> <dt> <slot name="parent-1"></slot> </dt> <dd> <slot name="child-1"></slot> </dd> <dt> <slot name="parent-2"></slot> </dt> <dd> <slot name="child-2"></slot> </dd> </dl> </template> <section> <span slot="heading">GeeksforGeeks</span> <span slot="parent-1">GFG</span> <span slot="child-1"> A computer science portal for geeks </span> <span slot="parent-2">Slot tag</span> <span slot="child-2"> Create separate DOM trees and present them together. </span> </section> <script> let dlTemplate = document.querySelector('template').content; let sections = document.querySelectorAll('section'); sections.forEach(function (section) { section.attachShadow({ mode: 'open' }).appendChild( dlTemplate.cloneNode(true)) }); </script></body> </html>
Output:
Supported Browsers:
Chrome
Edge
Firefox
Brave
Opera
Safari
Internet Explorer
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
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": 26139,
"s": 26111,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 26371,
"s": 26139,
"text": "The slot is the element part of the web component technology which is a placeholder inside a component that you simply can fill together with your own markup, which allows you to make separate DOM trees and represent them together."
},
{
"code": null,
"e": 26379,
"s": 26371,
"text": "Syntax:"
},
{
"code": null,
"e": 26415,
"s": 26379,
"text": "<slot>\n <h1>Heading</h1>\n</slot>"
},
{
"code": null,
"e": 26427,
"s": 26415,
"text": "Attributes:"
},
{
"code": null,
"e": 26468,
"s": 26427,
"text": "name: It describes the name of the slot."
},
{
"code": null,
"e": 26543,
"s": 26468,
"text": "Approach: The following elements are used in the example code given below."
},
{
"code": null,
"e": 26801,
"s": 26543,
"text": "Template: The template element is employed to declare fragments of HTML that will be inserted within the document by script. Contents aren’t rendered until they are added to the document in a script. This is often the part that contains the <slot> elements."
},
{
"code": null,
"e": 27216,
"s": 26801,
"text": "Content: This part contains the content that’s inserted where the <slot> elements are within the template. So during this case, the span elements will find yourself where the elements are available. Each span element refers to a selected <slot> element via its slot attribute. Any CSS that you simply include within the template element is merely applied to the DOM tree. It won’t affect the remainder of the page."
},
{
"code": null,
"e": 27605,
"s": 27216,
"text": "Script: The primary list is inserted <slot> with the element but the second list isn’t. The main styles are declared inside the template element, which suggests that they are only applied to HTML elements that are within that shadow DOM tree. If the styles are outside of the template element, those styles are only applied to the second list, and therefore the first list goes unstyled."
},
{
"code": null,
"e": 27614,
"s": 27605,
"text": "Example:"
},
{
"code": null,
"e": 27619,
"s": 27614,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> h1 { font-size: 2.2em; font-family: Arial, Helvetica, sans-serif; color: coral; } dl { border-left: 5px solid yellowgreen; padding-left: 1em; } dt { font-weight: bold; font-size: 2em; } dd { color: darkslategray; font-size: 1.6em; } </style></head> <body> <template> <h1> <slot name=\"heading\"></slot> </h1> <dl> <dt> <slot name=\"parent-1\"></slot> </dt> <dd> <slot name=\"child-1\"></slot> </dd> <dt> <slot name=\"parent-2\"></slot> </dt> <dd> <slot name=\"child-2\"></slot> </dd> </dl> </template> <section> <span slot=\"heading\">GeeksforGeeks</span> <span slot=\"parent-1\">GFG</span> <span slot=\"child-1\"> A computer science portal for geeks </span> <span slot=\"parent-2\">Slot tag</span> <span slot=\"child-2\"> Create separate DOM trees and present them together. </span> </section> <script> let dlTemplate = document.querySelector('template').content; let sections = document.querySelectorAll('section'); sections.forEach(function (section) { section.attachShadow({ mode: 'open' }).appendChild( dlTemplate.cloneNode(true)) }); </script></body> </html>",
"e": 29221,
"s": 27619,
"text": null
},
{
"code": null,
"e": 29252,
"s": 29221,
"text": "Output: "
},
{
"code": null,
"e": 29272,
"s": 29252,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 29279,
"s": 29272,
"text": "Chrome"
},
{
"code": null,
"e": 29284,
"s": 29279,
"text": "Edge"
},
{
"code": null,
"e": 29292,
"s": 29284,
"text": "Firefox"
},
{
"code": null,
"e": 29298,
"s": 29292,
"text": "Brave"
},
{
"code": null,
"e": 29304,
"s": 29298,
"text": "Opera"
},
{
"code": null,
"e": 29311,
"s": 29304,
"text": "Safari"
},
{
"code": null,
"e": 29329,
"s": 29311,
"text": "Internet Explorer"
},
{
"code": null,
"e": 29466,
"s": 29329,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 29476,
"s": 29466,
"text": "HTML-Tags"
},
{
"code": null,
"e": 29483,
"s": 29476,
"text": "Picked"
},
{
"code": null,
"e": 29488,
"s": 29483,
"text": "HTML"
},
{
"code": null,
"e": 29505,
"s": 29488,
"text": "Web Technologies"
},
{
"code": null,
"e": 29510,
"s": 29505,
"text": "HTML"
},
{
"code": null,
"e": 29608,
"s": 29510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29632,
"s": 29608,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 29673,
"s": 29632,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 29710,
"s": 29673,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29739,
"s": 29710,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29759,
"s": 29739,
"text": "Angular File Upload"
},
{
"code": null,
"e": 29799,
"s": 29759,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29832,
"s": 29799,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29877,
"s": 29832,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29920,
"s": 29877,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Check if Particular Key Exists in Java HashMap - GeeksforGeeks | 20 Nov, 2021
HashMap in Java is the realization of the Hash Table data structure of sorts. It is composed of Key and Value pairs which are symbolically represented as <K,V> where K stands for Key and V for Value. It is an implementation of the Maps Interface and is advantageous in the ways that it provides constant-time performance in assigning and accessing elements via the put and get methods respectively. It is used to form associated pairs and access or modify one based on the other.
There are various approaches to check if particular key exists which are mentioned below :
Using the built-in containsKey() method of the HashMap class
Converting the keys of the HashMap to a list and then iterating through them
Creating a Map from all the entries of the HashMap and then iterating over it
Approach 1 :
Using this approach, we make use of the containsKey() predefined method of the HashMap class which returns a boolean value.
Syntax:
Hash_Map.containsKey(key_element)
Parameters: The method takes just one parameter key_element that refers to the key whose mapping is supposed to be checked inside a map.
Return Value: The method returns boolean true if the presence of the key is detected else false
Algorithm :
Create a function with a return type of boolean.Inside the function, create a new HashMap specifying the data types of the key and the value respectively.Fill up the HashMap with Key-Value Pairs using the put() method of the HashMap class.Declare a boolean variable to store the result.Call the containsKey() method of the HashMap class with the key to be checked as the parameter.Return the variable.
Create a function with a return type of boolean.
Inside the function, create a new HashMap specifying the data types of the key and the value respectively.
Fill up the HashMap with Key-Value Pairs using the put() method of the HashMap class.
Declare a boolean variable to store the result.
Call the containsKey() method of the HashMap class with the key to be checked as the parameter.
Return the variable.
Code :
Java
// java program to check if a particular// key exists in HashMap import java.util.*; class GFG { // declaring the method // the parameter keyToBeChecked is the // key to be checked boolean checkForKey(String keyToBeChecked) { // initializing the hashmap HashMap<String, Integer> hashMap = new HashMap<>(); // filling the key - value pairs in hashmap hashMap.put("first", 1); hashMap.put("second", 2); hashMap.put("third", 3); hashMap.put("fourth", 4); // variable to store the boolean value // for result boolean result = hashMap.containsKey(keyToBeChecked); // returning the result return result; } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // displaying and calling the checkForKey() // method System.out.println(ob.checkForKey("fourth")); }}
true
Approach 2 :
We create an ArrayList from the keys of the HashMap and then iterate over them to check if the specified key is present or not.
Algorithm :
Repeat steps 1 through 3 as mentioned in the first approach.Next, we initialize an ArrayList of the same data type as the keys of the HashMap using the keySet() predefined method of the HashMap class.For the next step, we declare an iterator to iterate through the elements of the ArrayList created above.We then iterate through the ArrayList checking in each iteration if the particular key matches with any of the elements of the ArrayList created above.Return the corresponding output.
Repeat steps 1 through 3 as mentioned in the first approach.
Next, we initialize an ArrayList of the same data type as the keys of the HashMap using the keySet() predefined method of the HashMap class.
For the next step, we declare an iterator to iterate through the elements of the ArrayList created above.
We then iterate through the ArrayList checking in each iteration if the particular key matches with any of the elements of the ArrayList created above.
Return the corresponding output.
Code :
Java
// java program to check if a particular// key exists in the HashMap import java.util.*; class GFG { // declaring the method // the parameter keyToBeChecked is // the key to be checked boolean checkForKey(String keyToBeChecked) { // initializing the HashMap HashMap<String, Integer> hashMap = new HashMap<>(); // filling the key-value pairs // in the HashMap hashMap.put("first", 1); hashMap.put("second", 2); hashMap.put("third", 3); hashMap.put("fourth", 4); // creating an ArrayList from the keys ArrayList<String> listOfKeys = new ArrayList<>(hashMap.keySet()); // declaring the iterator Iterator<String> itr = listOfKeys.iterator(); // loop to iterate through the // elements of the ArrayList while (itr.hasNext()) { // condition to check against // the specific key if (itr.next() == keyToBeChecked) return true; } return false; } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // displaying and calling the // checkForKey method System.out.println(ob.checkForKey("second")); }}
true
Approach 3 :
We iterate over the keys checking if the specified one is present or not.
Algorithm :
Repeat steps 1 through 3 in the first approach to create a HashMap.Using a for each loop and the entrySet() predefined method of the HashMap class, create a Map of the same.In each iteration of the for loop, get a key from the Map built above using the built-in getKey() method of the Map class.Compare it with the specified key.Return true if the key matches with any of the elements of the key set or else return false.
Repeat steps 1 through 3 in the first approach to create a HashMap.
Using a for each loop and the entrySet() predefined method of the HashMap class, create a Map of the same.
In each iteration of the for loop, get a key from the Map built above using the built-in getKey() method of the Map class.
Compare it with the specified key.
Return true if the key matches with any of the elements of the key set or else return false.
Code :
Java
// java program to check if a particular// key exists in the HashMap import java.util.*; class GFG { // declaring the method // the parameter keyToBeChecked specifies // the particular key boolean checkForKey(String keyToBeChecked) { // initializing the HashMap HashMap<String, Integer> hashMap = new HashMap<>(); // filling up the key-value // pairs in the HashMap hashMap.put("first", 1); hashMap.put("second", 2); hashMap.put("third", 3); hashMap.put("fourth", 4); // initializing the for each loop // using which the entries of the // HashMap are stored in a Set for (Map.Entry<String, Integer> mapEntries : hashMap.entrySet()) { // getting the keys and checking // against the specified key if (mapEntries.getKey() == keyToBeChecked) return true; } return false; } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // displaying and calling the // checkForKey method System.out.println(ob.checkForKey("seventh")); }}
false
adnanirshad158
prachisoda1234
clintra
Java-HashMap
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n20 Nov, 2021"
},
{
"code": null,
"e": 25706,
"s": 25225,
"text": "HashMap in Java is the realization of the Hash Table data structure of sorts. It is composed of Key and Value pairs which are symbolically represented as <K,V> where K stands for Key and V for Value. It is an implementation of the Maps Interface and is advantageous in the ways that it provides constant-time performance in assigning and accessing elements via the put and get methods respectively. It is used to form associated pairs and access or modify one based on the other. "
},
{
"code": null,
"e": 25797,
"s": 25706,
"text": "There are various approaches to check if particular key exists which are mentioned below :"
},
{
"code": null,
"e": 25858,
"s": 25797,
"text": "Using the built-in containsKey() method of the HashMap class"
},
{
"code": null,
"e": 25935,
"s": 25858,
"text": "Converting the keys of the HashMap to a list and then iterating through them"
},
{
"code": null,
"e": 26013,
"s": 25935,
"text": "Creating a Map from all the entries of the HashMap and then iterating over it"
},
{
"code": null,
"e": 26026,
"s": 26013,
"text": "Approach 1 :"
},
{
"code": null,
"e": 26150,
"s": 26026,
"text": "Using this approach, we make use of the containsKey() predefined method of the HashMap class which returns a boolean value."
},
{
"code": null,
"e": 26158,
"s": 26150,
"text": "Syntax:"
},
{
"code": null,
"e": 26192,
"s": 26158,
"text": "Hash_Map.containsKey(key_element)"
},
{
"code": null,
"e": 26329,
"s": 26192,
"text": "Parameters: The method takes just one parameter key_element that refers to the key whose mapping is supposed to be checked inside a map."
},
{
"code": null,
"e": 26425,
"s": 26329,
"text": "Return Value: The method returns boolean true if the presence of the key is detected else false"
},
{
"code": null,
"e": 26437,
"s": 26425,
"text": "Algorithm :"
},
{
"code": null,
"e": 26839,
"s": 26437,
"text": "Create a function with a return type of boolean.Inside the function, create a new HashMap specifying the data types of the key and the value respectively.Fill up the HashMap with Key-Value Pairs using the put() method of the HashMap class.Declare a boolean variable to store the result.Call the containsKey() method of the HashMap class with the key to be checked as the parameter.Return the variable."
},
{
"code": null,
"e": 26888,
"s": 26839,
"text": "Create a function with a return type of boolean."
},
{
"code": null,
"e": 26995,
"s": 26888,
"text": "Inside the function, create a new HashMap specifying the data types of the key and the value respectively."
},
{
"code": null,
"e": 27081,
"s": 26995,
"text": "Fill up the HashMap with Key-Value Pairs using the put() method of the HashMap class."
},
{
"code": null,
"e": 27129,
"s": 27081,
"text": "Declare a boolean variable to store the result."
},
{
"code": null,
"e": 27225,
"s": 27129,
"text": "Call the containsKey() method of the HashMap class with the key to be checked as the parameter."
},
{
"code": null,
"e": 27246,
"s": 27225,
"text": "Return the variable."
},
{
"code": null,
"e": 27253,
"s": 27246,
"text": "Code :"
},
{
"code": null,
"e": 27258,
"s": 27253,
"text": "Java"
},
{
"code": "// java program to check if a particular// key exists in HashMap import java.util.*; class GFG { // declaring the method // the parameter keyToBeChecked is the // key to be checked boolean checkForKey(String keyToBeChecked) { // initializing the hashmap HashMap<String, Integer> hashMap = new HashMap<>(); // filling the key - value pairs in hashmap hashMap.put(\"first\", 1); hashMap.put(\"second\", 2); hashMap.put(\"third\", 3); hashMap.put(\"fourth\", 4); // variable to store the boolean value // for result boolean result = hashMap.containsKey(keyToBeChecked); // returning the result return result; } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // displaying and calling the checkForKey() // method System.out.println(ob.checkForKey(\"fourth\")); }}",
"e": 28241,
"s": 27258,
"text": null
},
{
"code": null,
"e": 28246,
"s": 28241,
"text": "true"
},
{
"code": null,
"e": 28259,
"s": 28246,
"text": "Approach 2 :"
},
{
"code": null,
"e": 28387,
"s": 28259,
"text": "We create an ArrayList from the keys of the HashMap and then iterate over them to check if the specified key is present or not."
},
{
"code": null,
"e": 28400,
"s": 28387,
"text": "Algorithm : "
},
{
"code": null,
"e": 28889,
"s": 28400,
"text": "Repeat steps 1 through 3 as mentioned in the first approach.Next, we initialize an ArrayList of the same data type as the keys of the HashMap using the keySet() predefined method of the HashMap class.For the next step, we declare an iterator to iterate through the elements of the ArrayList created above.We then iterate through the ArrayList checking in each iteration if the particular key matches with any of the elements of the ArrayList created above.Return the corresponding output."
},
{
"code": null,
"e": 28950,
"s": 28889,
"text": "Repeat steps 1 through 3 as mentioned in the first approach."
},
{
"code": null,
"e": 29091,
"s": 28950,
"text": "Next, we initialize an ArrayList of the same data type as the keys of the HashMap using the keySet() predefined method of the HashMap class."
},
{
"code": null,
"e": 29197,
"s": 29091,
"text": "For the next step, we declare an iterator to iterate through the elements of the ArrayList created above."
},
{
"code": null,
"e": 29349,
"s": 29197,
"text": "We then iterate through the ArrayList checking in each iteration if the particular key matches with any of the elements of the ArrayList created above."
},
{
"code": null,
"e": 29382,
"s": 29349,
"text": "Return the corresponding output."
},
{
"code": null,
"e": 29389,
"s": 29382,
"text": "Code :"
},
{
"code": null,
"e": 29394,
"s": 29389,
"text": "Java"
},
{
"code": "// java program to check if a particular// key exists in the HashMap import java.util.*; class GFG { // declaring the method // the parameter keyToBeChecked is // the key to be checked boolean checkForKey(String keyToBeChecked) { // initializing the HashMap HashMap<String, Integer> hashMap = new HashMap<>(); // filling the key-value pairs // in the HashMap hashMap.put(\"first\", 1); hashMap.put(\"second\", 2); hashMap.put(\"third\", 3); hashMap.put(\"fourth\", 4); // creating an ArrayList from the keys ArrayList<String> listOfKeys = new ArrayList<>(hashMap.keySet()); // declaring the iterator Iterator<String> itr = listOfKeys.iterator(); // loop to iterate through the // elements of the ArrayList while (itr.hasNext()) { // condition to check against // the specific key if (itr.next() == keyToBeChecked) return true; } return false; } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // displaying and calling the // checkForKey method System.out.println(ob.checkForKey(\"second\")); }}",
"e": 30697,
"s": 29394,
"text": null
},
{
"code": null,
"e": 30702,
"s": 30697,
"text": "true"
},
{
"code": null,
"e": 30715,
"s": 30702,
"text": "Approach 3 :"
},
{
"code": null,
"e": 30789,
"s": 30715,
"text": "We iterate over the keys checking if the specified one is present or not."
},
{
"code": null,
"e": 30802,
"s": 30789,
"text": "Algorithm : "
},
{
"code": null,
"e": 31224,
"s": 30802,
"text": "Repeat steps 1 through 3 in the first approach to create a HashMap.Using a for each loop and the entrySet() predefined method of the HashMap class, create a Map of the same.In each iteration of the for loop, get a key from the Map built above using the built-in getKey() method of the Map class.Compare it with the specified key.Return true if the key matches with any of the elements of the key set or else return false."
},
{
"code": null,
"e": 31292,
"s": 31224,
"text": "Repeat steps 1 through 3 in the first approach to create a HashMap."
},
{
"code": null,
"e": 31399,
"s": 31292,
"text": "Using a for each loop and the entrySet() predefined method of the HashMap class, create a Map of the same."
},
{
"code": null,
"e": 31522,
"s": 31399,
"text": "In each iteration of the for loop, get a key from the Map built above using the built-in getKey() method of the Map class."
},
{
"code": null,
"e": 31557,
"s": 31522,
"text": "Compare it with the specified key."
},
{
"code": null,
"e": 31650,
"s": 31557,
"text": "Return true if the key matches with any of the elements of the key set or else return false."
},
{
"code": null,
"e": 31658,
"s": 31650,
"text": "Code : "
},
{
"code": null,
"e": 31663,
"s": 31658,
"text": "Java"
},
{
"code": "// java program to check if a particular// key exists in the HashMap import java.util.*; class GFG { // declaring the method // the parameter keyToBeChecked specifies // the particular key boolean checkForKey(String keyToBeChecked) { // initializing the HashMap HashMap<String, Integer> hashMap = new HashMap<>(); // filling up the key-value // pairs in the HashMap hashMap.put(\"first\", 1); hashMap.put(\"second\", 2); hashMap.put(\"third\", 3); hashMap.put(\"fourth\", 4); // initializing the for each loop // using which the entries of the // HashMap are stored in a Set for (Map.Entry<String, Integer> mapEntries : hashMap.entrySet()) { // getting the keys and checking // against the specified key if (mapEntries.getKey() == keyToBeChecked) return true; } return false; } // Driver Code public static void main(String[] args) { // instantiating the class GFG ob = new GFG(); // displaying and calling the // checkForKey method System.out.println(ob.checkForKey(\"seventh\")); }}",
"e": 32869,
"s": 31663,
"text": null
},
{
"code": null,
"e": 32875,
"s": 32869,
"text": "false"
},
{
"code": null,
"e": 32892,
"s": 32877,
"text": "adnanirshad158"
},
{
"code": null,
"e": 32907,
"s": 32892,
"text": "prachisoda1234"
},
{
"code": null,
"e": 32915,
"s": 32907,
"text": "clintra"
},
{
"code": null,
"e": 32928,
"s": 32915,
"text": "Java-HashMap"
},
{
"code": null,
"e": 32935,
"s": 32928,
"text": "Picked"
},
{
"code": null,
"e": 32940,
"s": 32935,
"text": "Java"
},
{
"code": null,
"e": 32954,
"s": 32940,
"text": "Java Programs"
},
{
"code": null,
"e": 32959,
"s": 32954,
"text": "Java"
},
{
"code": null,
"e": 33057,
"s": 32959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33072,
"s": 33057,
"text": "Stream In Java"
},
{
"code": null,
"e": 33093,
"s": 33072,
"text": "Constructors in Java"
},
{
"code": null,
"e": 33112,
"s": 33093,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 33142,
"s": 33112,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 33188,
"s": 33142,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 33214,
"s": 33188,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 33248,
"s": 33214,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 33295,
"s": 33248,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 33327,
"s": 33295,
"text": "How to Iterate HashMap in Java?"
}
] |
PyQt5 QDateTimeEdit – Setting Display format - GeeksforGeeks | 14 Jul, 2020
In this article we will see how we can set display format of date to the QDateTimeEdit. Display format property holds the format used to display the time/date of the date time edit. By default, we see date in format like 01-01-2000 although by setting display format we can make this date as 1 Jan 2020.
In order to do this we will use setDisplayFormat method with the QDateTimeEdit object.
Syntax : datetimeedit.setDisplayFormat(format)
Argument : It takes string as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateTimeEdit widget datetimeedit = QDateTimeEdit(self) # setting geometry datetimeedit.setGeometry(100, 100, 150, 35) # setting date format datetimeedit.setDisplayFormat("dd MMM yyyy") # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QDateTimeEdit
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25751,
"s": 25723,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 26055,
"s": 25751,
"text": "In this article we will see how we can set display format of date to the QDateTimeEdit. Display format property holds the format used to display the time/date of the date time edit. By default, we see date in format like 01-01-2000 although by setting display format we can make this date as 1 Jan 2020."
},
{
"code": null,
"e": 26142,
"s": 26055,
"text": "In order to do this we will use setDisplayFormat method with the QDateTimeEdit object."
},
{
"code": null,
"e": 26189,
"s": 26142,
"text": "Syntax : datetimeedit.setDisplayFormat(format)"
},
{
"code": null,
"e": 26228,
"s": 26189,
"text": "Argument : It takes string as argument"
},
{
"code": null,
"e": 26253,
"s": 26228,
"text": "Return : It returns None"
},
{
"code": null,
"e": 26281,
"s": 26253,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateTimeEdit widget datetimeedit = QDateTimeEdit(self) # setting geometry datetimeedit.setGeometry(100, 100, 150, 35) # setting date format datetimeedit.setDisplayFormat(\"dd MMM yyyy\") # creating a label label = QLabel(\"GeeksforGeeks\", self) # setting geometry to the label label.setGeometry(100, 200, 300, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27425,
"s": 26281,
"text": null
},
{
"code": null,
"e": 27434,
"s": 27425,
"text": "Output :"
},
{
"code": null,
"e": 27460,
"s": 27434,
"text": "Python PyQt-QDateTimeEdit"
},
{
"code": null,
"e": 27471,
"s": 27460,
"text": "Python-gui"
},
{
"code": null,
"e": 27483,
"s": 27471,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27490,
"s": 27483,
"text": "Python"
},
{
"code": null,
"e": 27588,
"s": 27490,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27606,
"s": 27588,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27641,
"s": 27606,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27673,
"s": 27641,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27695,
"s": 27673,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27737,
"s": 27695,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27767,
"s": 27737,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27793,
"s": 27767,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27822,
"s": 27793,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27866,
"s": 27822,
"text": "Reading and Writing to text files in Python"
}
] |
dos.h header in C with examples - GeeksforGeeks | 20 Jul, 2021
dos.h is a header file of C Language. This library has functions that are used for handling interrupts, producing sound, date and time functions, etc. It is Borland specific and works in compilers like Turbo C Compiler.Below are the functions supported by this library:
delay(): The delay() function in C is used to stop the execution of the program for some period of time.Syntax:delay(unsigned int)
Parameters: It accepts a time in milliseconds to stop the execution of the program to that period of time.Below is the program to illustrate delay():// C program to implement delay()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ printf("Takes 10 sec and exit.\n"); // Delay the program execution // for 1 second delay(10000); return 0;}sleep(): The sleep() function in C is used to delay the execution of the program for some period of time.Syntax:sleep(unsigned seconds)
Parameters: It accepts a time in seconds to delay the execution of the program to that period of time.Below is the program to illustrate sleep():// C program to implement sleep()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ printf("Wait 2 sec and exit.\n"); // Delay the program execution // for by 2 seconds sleep(2); return 0;}getdate(): The getdate() function in C is used to get the current Date of the system.Syntax:getdate(struct date d)
Parameters: It accepts a structure date which is defined in dos.h library itself. To print the date it uses function da_day(), da_mon() and da_year().Below is the program to illustrate getdate():// C program to implement getdate()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Structure of date struct date a; // Function call to get the date // of the system getdate(&a); // Print the date, month and year printf("The Date is: %d/%d/%d\n", a.da_day, a.da_mon, a.da_year); return 0;}gettime(): The gettime() function in C is used to get the Time shown by the System.Syntax:gettime(struct time t)
Parameters: It accepts a structure time which is defined in dos.h library itself. To print the date it uses function ti_hour(), ti_min() and ti_sec().Below is the program to illustrate gettime():// C program to implement gettime()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Structure of time struct time t; // Function call to get the time // of the system getdate(&t); // Print the hour, minutes and second printf("The time is: %d : %d : %d\n", x.ti_hour, x.ti_min, x.ti_sec); return 0;}sound(): The sound() function in C is used to play different sound on different frequency on our system.Syntax:sound(int frequency)
Parameters: It accepts a frequency and play the sound of that frequency in our system.Below is the program to illustrate sound():// C program to implement sound()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Initialise frequency int x = 200; // Loop for playing sound of // increasing frequency for (; x < 1000; x++) { // Function to play sound sound(x); delay(25); } // To stop the frequency nosound(); return 0;}nosound(): The nosound() function in C is used to stop the sound played by souns() function.Syntax:nosound()
Parameters: It doesn’t accepts any parameters.Below is the program to illustrate nosound():// C program to implement nosound()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Initialise frequency int x = 200; // Function call to play sound // with frequency 200htz sound(x); // Delay sound for 1 sec delay(1000); // To stop the sound nosound(); return 0;}
delay(): The delay() function in C is used to stop the execution of the program for some period of time.Syntax:delay(unsigned int)
Parameters: It accepts a time in milliseconds to stop the execution of the program to that period of time.Below is the program to illustrate delay():// C program to implement delay()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ printf("Takes 10 sec and exit.\n"); // Delay the program execution // for 1 second delay(10000); return 0;}
delay(unsigned int)
Parameters: It accepts a time in milliseconds to stop the execution of the program to that period of time.
Below is the program to illustrate delay():
// C program to implement delay()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ printf("Takes 10 sec and exit.\n"); // Delay the program execution // for 1 second delay(10000); return 0;}
sleep(): The sleep() function in C is used to delay the execution of the program for some period of time.Syntax:sleep(unsigned seconds)
Parameters: It accepts a time in seconds to delay the execution of the program to that period of time.Below is the program to illustrate sleep():// C program to implement sleep()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ printf("Wait 2 sec and exit.\n"); // Delay the program execution // for by 2 seconds sleep(2); return 0;}
sleep(unsigned seconds)
Parameters: It accepts a time in seconds to delay the execution of the program to that period of time.
Below is the program to illustrate sleep():
// C program to implement sleep()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ printf("Wait 2 sec and exit.\n"); // Delay the program execution // for by 2 seconds sleep(2); return 0;}
getdate(): The getdate() function in C is used to get the current Date of the system.Syntax:getdate(struct date d)
Parameters: It accepts a structure date which is defined in dos.h library itself. To print the date it uses function da_day(), da_mon() and da_year().Below is the program to illustrate getdate():// C program to implement getdate()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Structure of date struct date a; // Function call to get the date // of the system getdate(&a); // Print the date, month and year printf("The Date is: %d/%d/%d\n", a.da_day, a.da_mon, a.da_year); return 0;}
Syntax:
getdate(struct date d)
Parameters: It accepts a structure date which is defined in dos.h library itself. To print the date it uses function da_day(), da_mon() and da_year().
Below is the program to illustrate getdate():
// C program to implement getdate()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Structure of date struct date a; // Function call to get the date // of the system getdate(&a); // Print the date, month and year printf("The Date is: %d/%d/%d\n", a.da_day, a.da_mon, a.da_year); return 0;}
gettime(): The gettime() function in C is used to get the Time shown by the System.Syntax:gettime(struct time t)
Parameters: It accepts a structure time which is defined in dos.h library itself. To print the date it uses function ti_hour(), ti_min() and ti_sec().Below is the program to illustrate gettime():// C program to implement gettime()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Structure of time struct time t; // Function call to get the time // of the system getdate(&t); // Print the hour, minutes and second printf("The time is: %d : %d : %d\n", x.ti_hour, x.ti_min, x.ti_sec); return 0;}
Syntax:
gettime(struct time t)
Parameters: It accepts a structure time which is defined in dos.h library itself. To print the date it uses function ti_hour(), ti_min() and ti_sec().
Below is the program to illustrate gettime():
// C program to implement gettime()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Structure of time struct time t; // Function call to get the time // of the system getdate(&t); // Print the hour, minutes and second printf("The time is: %d : %d : %d\n", x.ti_hour, x.ti_min, x.ti_sec); return 0;}
sound(): The sound() function in C is used to play different sound on different frequency on our system.Syntax:sound(int frequency)
Parameters: It accepts a frequency and play the sound of that frequency in our system.Below is the program to illustrate sound():// C program to implement sound()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Initialise frequency int x = 200; // Loop for playing sound of // increasing frequency for (; x < 1000; x++) { // Function to play sound sound(x); delay(25); } // To stop the frequency nosound(); return 0;}
Syntax:
sound(int frequency)
Parameters: It accepts a frequency and play the sound of that frequency in our system.
Below is the program to illustrate sound():
// C program to implement sound()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Initialise frequency int x = 200; // Loop for playing sound of // increasing frequency for (; x < 1000; x++) { // Function to play sound sound(x); delay(25); } // To stop the frequency nosound(); return 0;}
nosound(): The nosound() function in C is used to stop the sound played by souns() function.Syntax:nosound()
Parameters: It doesn’t accepts any parameters.Below is the program to illustrate nosound():// C program to implement nosound()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Initialise frequency int x = 200; // Function call to play sound // with frequency 200htz sound(x); // Delay sound for 1 sec delay(1000); // To stop the sound nosound(); return 0;}
Syntax:
nosound()
Parameters: It doesn’t accepts any parameters.
Below is the program to illustrate nosound():
// C program to implement nosound()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Initialise frequency int x = 200; // Function call to play sound // with frequency 200htz sound(x); // Delay sound for 1 sec delay(1000); // To stop the sound nosound(); return 0;}
anikakapoor
C Language
C Programs
Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
Basics of File Handling in C | [
{
"code": null,
"e": 25453,
"s": 25425,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 25723,
"s": 25453,
"text": "dos.h is a header file of C Language. This library has functions that are used for handling interrupts, producing sound, date and time functions, etc. It is Borland specific and works in compilers like Turbo C Compiler.Below are the functions supported by this library:"
},
{
"code": null,
"e": 29291,
"s": 25723,
"text": "delay(): The delay() function in C is used to stop the execution of the program for some period of time.Syntax:delay(unsigned int)\nParameters: It accepts a time in milliseconds to stop the execution of the program to that period of time.Below is the program to illustrate delay():// C program to implement delay()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ printf(\"Takes 10 sec and exit.\\n\"); // Delay the program execution // for 1 second delay(10000); return 0;}sleep(): The sleep() function in C is used to delay the execution of the program for some period of time.Syntax:sleep(unsigned seconds)\nParameters: It accepts a time in seconds to delay the execution of the program to that period of time.Below is the program to illustrate sleep():// C program to implement sleep()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ printf(\"Wait 2 sec and exit.\\n\"); // Delay the program execution // for by 2 seconds sleep(2); return 0;}getdate(): The getdate() function in C is used to get the current Date of the system.Syntax:getdate(struct date d)\nParameters: It accepts a structure date which is defined in dos.h library itself. To print the date it uses function da_day(), da_mon() and da_year().Below is the program to illustrate getdate():// C program to implement getdate()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Structure of date struct date a; // Function call to get the date // of the system getdate(&a); // Print the date, month and year printf(\"The Date is: %d/%d/%d\\n\", a.da_day, a.da_mon, a.da_year); return 0;}gettime(): The gettime() function in C is used to get the Time shown by the System.Syntax:gettime(struct time t)\nParameters: It accepts a structure time which is defined in dos.h library itself. To print the date it uses function ti_hour(), ti_min() and ti_sec().Below is the program to illustrate gettime():// C program to implement gettime()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Structure of time struct time t; // Function call to get the time // of the system getdate(&t); // Print the hour, minutes and second printf(\"The time is: %d : %d : %d\\n\", x.ti_hour, x.ti_min, x.ti_sec); return 0;}sound(): The sound() function in C is used to play different sound on different frequency on our system.Syntax:sound(int frequency)\nParameters: It accepts a frequency and play the sound of that frequency in our system.Below is the program to illustrate sound():// C program to implement sound()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Initialise frequency int x = 200; // Loop for playing sound of // increasing frequency for (; x < 1000; x++) { // Function to play sound sound(x); delay(25); } // To stop the frequency nosound(); return 0;}nosound(): The nosound() function in C is used to stop the sound played by souns() function.Syntax:nosound()\nParameters: It doesn’t accepts any parameters.Below is the program to illustrate nosound():// C program to implement nosound()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Initialise frequency int x = 200; // Function call to play sound // with frequency 200htz sound(x); // Delay sound for 1 sec delay(1000); // To stop the sound nosound(); return 0;}"
},
{
"code": null,
"e": 29809,
"s": 29291,
"text": "delay(): The delay() function in C is used to stop the execution of the program for some period of time.Syntax:delay(unsigned int)\nParameters: It accepts a time in milliseconds to stop the execution of the program to that period of time.Below is the program to illustrate delay():// C program to implement delay()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ printf(\"Takes 10 sec and exit.\\n\"); // Delay the program execution // for 1 second delay(10000); return 0;}"
},
{
"code": null,
"e": 29830,
"s": 29809,
"text": "delay(unsigned int)\n"
},
{
"code": null,
"e": 29937,
"s": 29830,
"text": "Parameters: It accepts a time in milliseconds to stop the execution of the program to that period of time."
},
{
"code": null,
"e": 29981,
"s": 29937,
"text": "Below is the program to illustrate delay():"
},
{
"code": "// C program to implement delay()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ printf(\"Takes 10 sec and exit.\\n\"); // Delay the program execution // for 1 second delay(10000); return 0;}",
"e": 30219,
"s": 29981,
"text": null
},
{
"code": null,
"e": 30736,
"s": 30219,
"text": "sleep(): The sleep() function in C is used to delay the execution of the program for some period of time.Syntax:sleep(unsigned seconds)\nParameters: It accepts a time in seconds to delay the execution of the program to that period of time.Below is the program to illustrate sleep():// C program to implement sleep()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ printf(\"Wait 2 sec and exit.\\n\"); // Delay the program execution // for by 2 seconds sleep(2); return 0;}"
},
{
"code": null,
"e": 30761,
"s": 30736,
"text": "sleep(unsigned seconds)\n"
},
{
"code": null,
"e": 30864,
"s": 30761,
"text": "Parameters: It accepts a time in seconds to delay the execution of the program to that period of time."
},
{
"code": null,
"e": 30908,
"s": 30864,
"text": "Below is the program to illustrate sleep():"
},
{
"code": "// C program to implement sleep()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ printf(\"Wait 2 sec and exit.\\n\"); // Delay the program execution // for by 2 seconds sleep(2); return 0;}",
"e": 31144,
"s": 30908,
"text": null
},
{
"code": null,
"e": 31826,
"s": 31144,
"text": "getdate(): The getdate() function in C is used to get the current Date of the system.Syntax:getdate(struct date d)\nParameters: It accepts a structure date which is defined in dos.h library itself. To print the date it uses function da_day(), da_mon() and da_year().Below is the program to illustrate getdate():// C program to implement getdate()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Structure of date struct date a; // Function call to get the date // of the system getdate(&a); // Print the date, month and year printf(\"The Date is: %d/%d/%d\\n\", a.da_day, a.da_mon, a.da_year); return 0;}"
},
{
"code": null,
"e": 31834,
"s": 31826,
"text": "Syntax:"
},
{
"code": null,
"e": 31858,
"s": 31834,
"text": "getdate(struct date d)\n"
},
{
"code": null,
"e": 32009,
"s": 31858,
"text": "Parameters: It accepts a structure date which is defined in dos.h library itself. To print the date it uses function da_day(), da_mon() and da_year()."
},
{
"code": null,
"e": 32055,
"s": 32009,
"text": "Below is the program to illustrate getdate():"
},
{
"code": "// C program to implement getdate()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Structure of date struct date a; // Function call to get the date // of the system getdate(&a); // Print the date, month and year printf(\"The Date is: %d/%d/%d\\n\", a.da_day, a.da_mon, a.da_year); return 0;}",
"e": 32427,
"s": 32055,
"text": null
},
{
"code": null,
"e": 33115,
"s": 32427,
"text": "gettime(): The gettime() function in C is used to get the Time shown by the System.Syntax:gettime(struct time t)\nParameters: It accepts a structure time which is defined in dos.h library itself. To print the date it uses function ti_hour(), ti_min() and ti_sec().Below is the program to illustrate gettime():// C program to implement gettime()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Structure of time struct time t; // Function call to get the time // of the system getdate(&t); // Print the hour, minutes and second printf(\"The time is: %d : %d : %d\\n\", x.ti_hour, x.ti_min, x.ti_sec); return 0;}"
},
{
"code": null,
"e": 33123,
"s": 33115,
"text": "Syntax:"
},
{
"code": null,
"e": 33147,
"s": 33123,
"text": "gettime(struct time t)\n"
},
{
"code": null,
"e": 33298,
"s": 33147,
"text": "Parameters: It accepts a structure time which is defined in dos.h library itself. To print the date it uses function ti_hour(), ti_min() and ti_sec()."
},
{
"code": null,
"e": 33344,
"s": 33298,
"text": "Below is the program to illustrate gettime():"
},
{
"code": "// C program to implement gettime()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Structure of time struct time t; // Function call to get the time // of the system getdate(&t); // Print the hour, minutes and second printf(\"The time is: %d : %d : %d\\n\", x.ti_hour, x.ti_min, x.ti_sec); return 0;}",
"e": 33724,
"s": 33344,
"text": null
},
{
"code": null,
"e": 34360,
"s": 33724,
"text": "sound(): The sound() function in C is used to play different sound on different frequency on our system.Syntax:sound(int frequency)\nParameters: It accepts a frequency and play the sound of that frequency in our system.Below is the program to illustrate sound():// C program to implement sound()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Initialise frequency int x = 200; // Loop for playing sound of // increasing frequency for (; x < 1000; x++) { // Function to play sound sound(x); delay(25); } // To stop the frequency nosound(); return 0;}"
},
{
"code": null,
"e": 34368,
"s": 34360,
"text": "Syntax:"
},
{
"code": null,
"e": 34390,
"s": 34368,
"text": "sound(int frequency)\n"
},
{
"code": null,
"e": 34477,
"s": 34390,
"text": "Parameters: It accepts a frequency and play the sound of that frequency in our system."
},
{
"code": null,
"e": 34521,
"s": 34477,
"text": "Below is the program to illustrate sound():"
},
{
"code": "// C program to implement sound()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Initialise frequency int x = 200; // Loop for playing sound of // increasing frequency for (; x < 1000; x++) { // Function to play sound sound(x); delay(25); } // To stop the frequency nosound(); return 0;}",
"e": 34896,
"s": 34521,
"text": null
},
{
"code": null,
"e": 35428,
"s": 34896,
"text": "nosound(): The nosound() function in C is used to stop the sound played by souns() function.Syntax:nosound()\nParameters: It doesn’t accepts any parameters.Below is the program to illustrate nosound():// C program to implement nosound()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Initialise frequency int x = 200; // Function call to play sound // with frequency 200htz sound(x); // Delay sound for 1 sec delay(1000); // To stop the sound nosound(); return 0;}"
},
{
"code": null,
"e": 35436,
"s": 35428,
"text": "Syntax:"
},
{
"code": null,
"e": 35447,
"s": 35436,
"text": "nosound()\n"
},
{
"code": null,
"e": 35494,
"s": 35447,
"text": "Parameters: It doesn’t accepts any parameters."
},
{
"code": null,
"e": 35540,
"s": 35494,
"text": "Below is the program to illustrate nosound():"
},
{
"code": "// C program to implement nosound()#include <dos.h>#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ // Initialise frequency int x = 200; // Function call to play sound // with frequency 200htz sound(x); // Delay sound for 1 sec delay(1000); // To stop the sound nosound(); return 0;}",
"e": 35872,
"s": 35540,
"text": null
},
{
"code": null,
"e": 35884,
"s": 35872,
"text": "anikakapoor"
},
{
"code": null,
"e": 35895,
"s": 35884,
"text": "C Language"
},
{
"code": null,
"e": 35906,
"s": 35895,
"text": "C Programs"
},
{
"code": null,
"e": 35923,
"s": 35906,
"text": "Computer Subject"
},
{
"code": null,
"e": 36021,
"s": 35923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36059,
"s": 36021,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 36085,
"s": 36059,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 36105,
"s": 36085,
"text": "Multithreading in C"
},
{
"code": null,
"e": 36127,
"s": 36105,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 36168,
"s": 36127,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 36181,
"s": 36168,
"text": "Strings in C"
},
{
"code": null,
"e": 36222,
"s": 36181,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 36263,
"s": 36222,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 36298,
"s": 36263,
"text": "Header files in C/C++ and its uses"
}
] |
How to create a Spotlight Effect using HTML and CSS ? - GeeksforGeeks | 23 Feb, 2021
In this article, we are going to create a spotlight effect over the image when we hover over it. This is mainly based on HTML, CSS and JavaScript. The below steps have to be followed to create this effect.
HTML Section: In this section, we will create a container elements for the background image and the mouse pointer. The CSS and JavaScript files are also linked here.
HTML
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="style.css"> <script src="index.js"></script></head> <body> <h1> Hover mouse over the image to get spotlight effect </h1> <div class="main_box"> <div class="img"></div> <div class="mouse"></div> </div></body> </html>
CSS Section: In this section, CSS is used to give different types of animations and effects to our HTML page so that it looks interactive to the users. The browser effects are first reset, then the position and size of the image and mouse pointer are set. The filter property is used to give visual effects to the element. The clip-path property is used to convert the element into different kind of shapes.
CSS
/* Resetting the browser stylesheet */* { padding: 0; margin: 0; box-sizing: border-box; overflow: hidden; background-color: #000; color: #fff;} /* Styling the heading */h1 { display: flex; align-items: center; align-content: center; justify-content: center;} /* Position the mouse pointer and the background image */.main_box,.img,.mouse { position: absolute; top: 0; left: 0; width: 100%; height: 100%;} .main_box { cursor: none; margin-top: 3em;} .img,.mouse { background-image: url('https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png'); background-size: cover; background-repeat: no-repeat; background-position: center;} /* Reduce the brightness of the image */.img { filter: brightness(10%);} /* Make a circle with the clip-path property for the spotlight in the effect */.mouse { clip-path: circle(5em at 0, 0);}
JavaScript Section: This section handles the interactive portion of the webpage. It detects the mouse movement over the image using the offsetX and offsetY properties for getting the X and Y coordinates. The clipPath property is then used to create a circle for the spotlight effect.
Javascript
// Select the container box and the mouse placeholderlet main = document.querySelector('.main_box');let mouse = document.querySelector('.mouse'); // Add an event listener for detecting// the movement of the mousemain.addEventListener('mousemove', (e) => { // Use a circle with a clipPath // and the offsetX and offsetY property mouse.style.clipPath = `circle(10em at ${e.offsetX}px ${e.offsetY}px)`;});
Complete Code: It is the combination of above three sections of code.
HTML
<!DOCTYPE html><html> <head> <style> /* Resetting the browser stylesheet */ * { padding: 0; margin: 0; box-sizing: border-box; overflow: hidden; background-color: #000; color: #fff; } /* Styling the heading */ h1 { display: flex; align-items: center; align-content: center; justify-content: center; } /* Position the mouse pointer and the background image */ .main_box, .img, .mouse { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .main_box { cursor: none; margin-top: 3em; } .img, .mouse { background-image: url('https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png'); background-size: cover; background-repeat: no-repeat; background-position: center; } /* Reduce the brightness of the image */ .img { filter: brightness(10%); } /* Make a circle with the clip-path property for the spotlight in the effect */ .mouse { clip-path: circle(5em at 0, 0); } </style></head> <body> <h1> Hover mouse over the image to get spotlight effect </h1> <div class="main_box"> <div class="img"></div> <div class="mouse"></div> </div> <script> // Select the container box and the // mouse placeholder let main = document.querySelector('.main_box'); let mouse = document.querySelector('.mouse'); // Add an event listener for detecting // the movement of the mouse main.addEventListener('mousemove', (e) => { // Use a circle with a clipPath // and the offsetX and offsetY property mouse.style.clipPath = `circle(10em at ${e.offsetX}px ${e.offsetY}px)`; }); </script></body> </html>
Output:
CSS-Questions
HTML-Questions
CSS
HTML
JavaScript
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 26827,
"s": 26621,
"text": "In this article, we are going to create a spotlight effect over the image when we hover over it. This is mainly based on HTML, CSS and JavaScript. The below steps have to be followed to create this effect."
},
{
"code": null,
"e": 26993,
"s": 26827,
"text": "HTML Section: In this section, we will create a container elements for the background image and the mouse pointer. The CSS and JavaScript files are also linked here."
},
{
"code": null,
"e": 26998,
"s": 26993,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"style.css\"> <script src=\"index.js\"></script></head> <body> <h1> Hover mouse over the image to get spotlight effect </h1> <div class=\"main_box\"> <div class=\"img\"></div> <div class=\"mouse\"></div> </div></body> </html>",
"e": 27328,
"s": 26998,
"text": null
},
{
"code": null,
"e": 27736,
"s": 27328,
"text": "CSS Section: In this section, CSS is used to give different types of animations and effects to our HTML page so that it looks interactive to the users. The browser effects are first reset, then the position and size of the image and mouse pointer are set. The filter property is used to give visual effects to the element. The clip-path property is used to convert the element into different kind of shapes."
},
{
"code": null,
"e": 27740,
"s": 27736,
"text": "CSS"
},
{
"code": "/* Resetting the browser stylesheet */* { padding: 0; margin: 0; box-sizing: border-box; overflow: hidden; background-color: #000; color: #fff;} /* Styling the heading */h1 { display: flex; align-items: center; align-content: center; justify-content: center;} /* Position the mouse pointer and the background image */.main_box,.img,.mouse { position: absolute; top: 0; left: 0; width: 100%; height: 100%;} .main_box { cursor: none; margin-top: 3em;} .img,.mouse { background-image: url('https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png'); background-size: cover; background-repeat: no-repeat; background-position: center;} /* Reduce the brightness of the image */.img { filter: brightness(10%);} /* Make a circle with the clip-path property for the spotlight in the effect */.mouse { clip-path: circle(5em at 0, 0);}",
"e": 28667,
"s": 27740,
"text": null
},
{
"code": null,
"e": 28951,
"s": 28667,
"text": "JavaScript Section: This section handles the interactive portion of the webpage. It detects the mouse movement over the image using the offsetX and offsetY properties for getting the X and Y coordinates. The clipPath property is then used to create a circle for the spotlight effect."
},
{
"code": null,
"e": 28962,
"s": 28951,
"text": "Javascript"
},
{
"code": "// Select the container box and the mouse placeholderlet main = document.querySelector('.main_box');let mouse = document.querySelector('.mouse'); // Add an event listener for detecting// the movement of the mousemain.addEventListener('mousemove', (e) => { // Use a circle with a clipPath // and the offsetX and offsetY property mouse.style.clipPath = `circle(10em at ${e.offsetX}px ${e.offsetY}px)`;});",
"e": 29397,
"s": 28962,
"text": null
},
{
"code": null,
"e": 29467,
"s": 29397,
"text": "Complete Code: It is the combination of above three sections of code."
},
{
"code": null,
"e": 29472,
"s": 29467,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> /* Resetting the browser stylesheet */ * { padding: 0; margin: 0; box-sizing: border-box; overflow: hidden; background-color: #000; color: #fff; } /* Styling the heading */ h1 { display: flex; align-items: center; align-content: center; justify-content: center; } /* Position the mouse pointer and the background image */ .main_box, .img, .mouse { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .main_box { cursor: none; margin-top: 3em; } .img, .mouse { background-image: url('https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png'); background-size: cover; background-repeat: no-repeat; background-position: center; } /* Reduce the brightness of the image */ .img { filter: brightness(10%); } /* Make a circle with the clip-path property for the spotlight in the effect */ .mouse { clip-path: circle(5em at 0, 0); } </style></head> <body> <h1> Hover mouse over the image to get spotlight effect </h1> <div class=\"main_box\"> <div class=\"img\"></div> <div class=\"mouse\"></div> </div> <script> // Select the container box and the // mouse placeholder let main = document.querySelector('.main_box'); let mouse = document.querySelector('.mouse'); // Add an event listener for detecting // the movement of the mouse main.addEventListener('mousemove', (e) => { // Use a circle with a clipPath // and the offsetX and offsetY property mouse.style.clipPath = `circle(10em at ${e.offsetX}px ${e.offsetY}px)`; }); </script></body> </html>",
"e": 31631,
"s": 29472,
"text": null
},
{
"code": null,
"e": 31639,
"s": 31631,
"text": "Output:"
},
{
"code": null,
"e": 31653,
"s": 31639,
"text": "CSS-Questions"
},
{
"code": null,
"e": 31668,
"s": 31653,
"text": "HTML-Questions"
},
{
"code": null,
"e": 31672,
"s": 31668,
"text": "CSS"
},
{
"code": null,
"e": 31677,
"s": 31672,
"text": "HTML"
},
{
"code": null,
"e": 31688,
"s": 31677,
"text": "JavaScript"
},
{
"code": null,
"e": 31707,
"s": 31688,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31724,
"s": 31707,
"text": "Web Technologies"
},
{
"code": null,
"e": 31729,
"s": 31724,
"text": "HTML"
},
{
"code": null,
"e": 31827,
"s": 31729,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31866,
"s": 31827,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 31903,
"s": 31866,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 31932,
"s": 31903,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 31967,
"s": 31932,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 32009,
"s": 31967,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 32069,
"s": 32009,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 32122,
"s": 32069,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 32183,
"s": 32122,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 32207,
"s": 32183,
"text": "REST API (Introduction)"
}
] |
MultiFernet Module in Python - GeeksforGeeks | 20 Apr, 2021
Cryptography is the process or technique of converting plaintext into ciphertext to protect information from the hackers during transmission from one computer to another. Python cryptography module allows the conversion of plaintext or message (in bytes) into ciphertext using the fernet module. The fernet module consists of inbuilt methods encrypt(), decrypt() and generate_key() to encrypt, decrypt and generate keys for encryption. The text message encrypted using fernet cannot be manipulated or read without the key. The MultiFernet class implements key rotation for Fernet. The MultiFernet has an inbuilt method rotate() which can be further used to retire an old key that has been exposed.
Methods used:
generate_key(): This method generates a new fernet key. The key must be kept safe as it is the most important component to decrypt the ciphertext. If the key is lost then the user can no longer decrypt the message. Also if an intruder or hacker gets access to the key they can not only read the data but also forge the data.
encrypt(data): It encrypts data passed as a parameter to the method. The outcome of this encryption is known as a “Fernet token” which is basically the ciphertext. The encrypted token also contains the current timestamp when it was generated in plaintext. The encrypt method throws an exception if the data is not in bytes.
Syntax: encrypt(data)
Parameter:
data (bytes) – The plaintext to be encrypted.
Returns: A ciphertext that cannot be read or altered without the key. It is URL-safe base64-encoded and is referred to as Fernet token.
decrypt(token, ttl = None): This method decrypts the Fernet token passed as a parameter to the method. On successful decryption the original plaintext is obtained as a result, otherwise, an exception is thrown.
Syntax: decrypt(token, ttl = None)
Parameters:
token (bytes) – The Fernet token (ciphertext) is passed for decryption.
ttl (int) – Optionally, one may provide an integer as the second parameter in the decrypt method. The ttl denotes the time about how long a token is valid. If the token is older than ttl seconds (from the time it was originally created) an exception is thrown. If ttl is not passed as a parameter, then age of the token is not considered. If the token is somehow invalid, an exception is thrown.
Returns: Returns the original plaintext.
rotate(token): This method rotates a token by re-encrypting with the MultiFernet instance’s primary key. However, re-encryption preserves the timestamp originally saved with the token.
Syntax: rotate(token)
Parameter:
token (bytes): The token to be rotated for re-encryption
Returns: If the token has successfully been rotated then the rotated token is returned. If rotation fails then it throws an exception.
Install cryptography package:
pip install cryptography
First Approach MultiFernet performs encryption using the first key in the list provided. MultiFernet decrypts tokens with each key in turn. If the correct key is not found in the list provided, a cryptography.fernet.InvalidToken exception is thrown. In the code snippet below, keys are generated and appended to the list. The MultiFernet takes the first key and stores in the f variable. This key is used to encrypt the plaintext into ciphertext. On the other hand, during decryption, MultiFernet tries all the keys in the list to decrypt the ciphertext.
Python3
# import Fernet and MultiFernet modulesfrom cryptography.fernet import Fernet, MultiFernet # key generationkey1 = Fernet(Fernet.generate_key())key2 = Fernet(Fernet.generate_key()) # the MultiFernet takes a list of Fernet instancesf = MultiFernet([key1, key2]) # encryption and token generationtoken = f.encrypt(b"Welcome to GeeksForGeeks Python Module!") # display the ciphertextprint(token) # decryption of ciphertext to plaintextd = f.decrypt(token) #display the plaintext#decode() method converts byte to stringprint(d.decode())
Output:
b’gAAAAABfYfRrB3f0RQl108YFuGyFHZ2lIQBKpFkuEqJ0EgLi6TNPR9vhElTmyuo5EfBivBwEBfSkOQJPEtIqOBBKZH8iElFn3ON5eg5d_JA1G9oARG7RKiqiQiOP8R22U4pIxnO1banH’
Welcome to GeeksForGeeks Python Module!
Second Approach The second approach demonstrates key rotation. Key rotation makes it easy to replace old or exposed keys. The new key can be added at the front of the already existing key list to start encrypting new messages, and the old keys are removed as they are no longer needed. Token rotation offered by MultiFernet.rotate() limits the damage in the event of an undetected event and to increase the difficulty or frequency of attacks. For example, if an employee having access to the company’s fernet keys leaves, the company will want to generate a new fernet key, rotate all of the tokens deployed currently using the new key, and remove the old fernet keys to which the employee had access. This can be easily achieved by MultiFernet.
Python3
# import Fernet and MultiFernet modulesfrom cryptography.fernet import Fernet, MultiFernet # key generationkey1 = Fernet(Fernet.generate_key())key2 = Fernet(Fernet.generate_key()) # the MultiFernet takes a list of Fernet instancesf = MultiFernet([key1, key2]) # encryption and token generationtoken = f.encrypt(b"Welcome to GeeksForGeeks Python Module!") # display the ciphertextprint(token) # decryption of ciphertext to plaintextd = f.decrypt(token) #display the plaintextprint(d.decode()) print('Key rotation')key3 = Fernet(Fernet.generate_key())f2 = MultiFernet([key3, key1, key2])rotated = f2.rotate(token)d2 = f2.decrypt(rotated)print(d2.decode())
Output:
b’gAAAAABfYfUe1Zh3JAa33k_RBRgkXgh-40jS6iqjXEq5Tc6jCeds-QY_nmlhzjkVBdZzeoExKj-YJsefBkgVSjUH1CVNG4080cwa3ZBHA9Aftx5upXzNQnaZ5fgeJacPNY0jcm4PMZSs’
Welcome to GeeksForGeeks Python Module!
Key rotation
Welcome to GeeksForGeeks Python Module!
AshokJaiswal
cryptography
python-modules
python-utility
Python
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 26255,
"s": 25555,
"text": "Cryptography is the process or technique of converting plaintext into ciphertext to protect information from the hackers during transmission from one computer to another. Python cryptography module allows the conversion of plaintext or message (in bytes) into ciphertext using the fernet module. The fernet module consists of inbuilt methods encrypt(), decrypt() and generate_key() to encrypt, decrypt and generate keys for encryption. The text message encrypted using fernet cannot be manipulated or read without the key. The MultiFernet class implements key rotation for Fernet. The MultiFernet has an inbuilt method rotate() which can be further used to retire an old key that has been exposed. "
},
{
"code": null,
"e": 26269,
"s": 26255,
"text": "Methods used:"
},
{
"code": null,
"e": 26594,
"s": 26269,
"text": "generate_key(): This method generates a new fernet key. The key must be kept safe as it is the most important component to decrypt the ciphertext. If the key is lost then the user can no longer decrypt the message. Also if an intruder or hacker gets access to the key they can not only read the data but also forge the data."
},
{
"code": null,
"e": 26918,
"s": 26594,
"text": "encrypt(data): It encrypts data passed as a parameter to the method. The outcome of this encryption is known as a “Fernet token” which is basically the ciphertext. The encrypted token also contains the current timestamp when it was generated in plaintext. The encrypt method throws an exception if the data is not in bytes."
},
{
"code": null,
"e": 26940,
"s": 26918,
"text": "Syntax: encrypt(data)"
},
{
"code": null,
"e": 26952,
"s": 26940,
"text": "Parameter: "
},
{
"code": null,
"e": 26998,
"s": 26952,
"text": "data (bytes) – The plaintext to be encrypted."
},
{
"code": null,
"e": 27134,
"s": 26998,
"text": "Returns: A ciphertext that cannot be read or altered without the key. It is URL-safe base64-encoded and is referred to as Fernet token."
},
{
"code": null,
"e": 27345,
"s": 27134,
"text": "decrypt(token, ttl = None): This method decrypts the Fernet token passed as a parameter to the method. On successful decryption the original plaintext is obtained as a result, otherwise, an exception is thrown."
},
{
"code": null,
"e": 27380,
"s": 27345,
"text": "Syntax: decrypt(token, ttl = None)"
},
{
"code": null,
"e": 27393,
"s": 27380,
"text": "Parameters: "
},
{
"code": null,
"e": 27465,
"s": 27393,
"text": "token (bytes) – The Fernet token (ciphertext) is passed for decryption."
},
{
"code": null,
"e": 27861,
"s": 27465,
"text": "ttl (int) – Optionally, one may provide an integer as the second parameter in the decrypt method. The ttl denotes the time about how long a token is valid. If the token is older than ttl seconds (from the time it was originally created) an exception is thrown. If ttl is not passed as a parameter, then age of the token is not considered. If the token is somehow invalid, an exception is thrown."
},
{
"code": null,
"e": 27902,
"s": 27861,
"text": "Returns: Returns the original plaintext."
},
{
"code": null,
"e": 28088,
"s": 27902,
"text": "rotate(token): This method rotates a token by re-encrypting with the MultiFernet instance’s primary key. However, re-encryption preserves the timestamp originally saved with the token. "
},
{
"code": null,
"e": 28110,
"s": 28088,
"text": "Syntax: rotate(token)"
},
{
"code": null,
"e": 28122,
"s": 28110,
"text": "Parameter: "
},
{
"code": null,
"e": 28179,
"s": 28122,
"text": "token (bytes): The token to be rotated for re-encryption"
},
{
"code": null,
"e": 28314,
"s": 28179,
"text": "Returns: If the token has successfully been rotated then the rotated token is returned. If rotation fails then it throws an exception."
},
{
"code": null,
"e": 28344,
"s": 28314,
"text": "Install cryptography package:"
},
{
"code": null,
"e": 28369,
"s": 28344,
"text": "pip install cryptography"
},
{
"code": null,
"e": 28926,
"s": 28369,
"text": "First Approach MultiFernet performs encryption using the first key in the list provided. MultiFernet decrypts tokens with each key in turn. If the correct key is not found in the list provided, a cryptography.fernet.InvalidToken exception is thrown. In the code snippet below, keys are generated and appended to the list. The MultiFernet takes the first key and stores in the f variable. This key is used to encrypt the plaintext into ciphertext. On the other hand, during decryption, MultiFernet tries all the keys in the list to decrypt the ciphertext. "
},
{
"code": null,
"e": 28934,
"s": 28926,
"text": "Python3"
},
{
"code": "# import Fernet and MultiFernet modulesfrom cryptography.fernet import Fernet, MultiFernet # key generationkey1 = Fernet(Fernet.generate_key())key2 = Fernet(Fernet.generate_key()) # the MultiFernet takes a list of Fernet instancesf = MultiFernet([key1, key2]) # encryption and token generationtoken = f.encrypt(b\"Welcome to GeeksForGeeks Python Module!\") # display the ciphertextprint(token) # decryption of ciphertext to plaintextd = f.decrypt(token) #display the plaintext#decode() method converts byte to stringprint(d.decode())",
"e": 29466,
"s": 28934,
"text": null
},
{
"code": null,
"e": 29478,
"s": 29470,
"text": "Output:"
},
{
"code": null,
"e": 29624,
"s": 29480,
"text": "b’gAAAAABfYfRrB3f0RQl108YFuGyFHZ2lIQBKpFkuEqJ0EgLi6TNPR9vhElTmyuo5EfBivBwEBfSkOQJPEtIqOBBKZH8iElFn3ON5eg5d_JA1G9oARG7RKiqiQiOP8R22U4pIxnO1banH’"
},
{
"code": null,
"e": 29664,
"s": 29624,
"text": "Welcome to GeeksForGeeks Python Module!"
},
{
"code": null,
"e": 30414,
"s": 29666,
"text": "Second Approach The second approach demonstrates key rotation. Key rotation makes it easy to replace old or exposed keys. The new key can be added at the front of the already existing key list to start encrypting new messages, and the old keys are removed as they are no longer needed. Token rotation offered by MultiFernet.rotate() limits the damage in the event of an undetected event and to increase the difficulty or frequency of attacks. For example, if an employee having access to the company’s fernet keys leaves, the company will want to generate a new fernet key, rotate all of the tokens deployed currently using the new key, and remove the old fernet keys to which the employee had access. This can be easily achieved by MultiFernet. "
},
{
"code": null,
"e": 30424,
"s": 30416,
"text": "Python3"
},
{
"code": "# import Fernet and MultiFernet modulesfrom cryptography.fernet import Fernet, MultiFernet # key generationkey1 = Fernet(Fernet.generate_key())key2 = Fernet(Fernet.generate_key()) # the MultiFernet takes a list of Fernet instancesf = MultiFernet([key1, key2]) # encryption and token generationtoken = f.encrypt(b\"Welcome to GeeksForGeeks Python Module!\") # display the ciphertextprint(token) # decryption of ciphertext to plaintextd = f.decrypt(token) #display the plaintextprint(d.decode()) print('Key rotation')key3 = Fernet(Fernet.generate_key())f2 = MultiFernet([key3, key1, key2])rotated = f2.rotate(token)d2 = f2.decrypt(rotated)print(d2.decode())",
"e": 31078,
"s": 30424,
"text": null
},
{
"code": null,
"e": 31090,
"s": 31082,
"text": "Output:"
},
{
"code": null,
"e": 31236,
"s": 31092,
"text": "b’gAAAAABfYfUe1Zh3JAa33k_RBRgkXgh-40jS6iqjXEq5Tc6jCeds-QY_nmlhzjkVBdZzeoExKj-YJsefBkgVSjUH1CVNG4080cwa3ZBHA9Aftx5upXzNQnaZ5fgeJacPNY0jcm4PMZSs’"
},
{
"code": null,
"e": 31276,
"s": 31236,
"text": "Welcome to GeeksForGeeks Python Module!"
},
{
"code": null,
"e": 31289,
"s": 31276,
"text": "Key rotation"
},
{
"code": null,
"e": 31329,
"s": 31289,
"text": "Welcome to GeeksForGeeks Python Module!"
},
{
"code": null,
"e": 31348,
"s": 31335,
"text": "AshokJaiswal"
},
{
"code": null,
"e": 31361,
"s": 31348,
"text": "cryptography"
},
{
"code": null,
"e": 31376,
"s": 31361,
"text": "python-modules"
},
{
"code": null,
"e": 31391,
"s": 31376,
"text": "python-utility"
},
{
"code": null,
"e": 31398,
"s": 31391,
"text": "Python"
},
{
"code": null,
"e": 31411,
"s": 31398,
"text": "cryptography"
},
{
"code": null,
"e": 31509,
"s": 31411,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31541,
"s": 31509,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31583,
"s": 31541,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 31625,
"s": 31583,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 31681,
"s": 31625,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 31708,
"s": 31681,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 31739,
"s": 31708,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 31778,
"s": 31739,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 31807,
"s": 31778,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 31829,
"s": 31807,
"text": "Defaultdict in Python"
}
] |
7 JavaScript Concepts That Every Web Developer Should Know - GeeksforGeeks | 13 Dec, 2021
JavaScript is Everywhere. Millions of webpages are built on JavaScript and it’s not going anywhere at least for now. On one side HTML and CSS give styling to the web pages but on the other side, it’s the magic of JavaScript that makes your web page alive. Today this language is not just limited to your web browser. You can also use it for server-side applications. Isn’t it cool to use a single language for both client-side and server-side applications? A single language fulfills both of the purposes and this is the main reason TON of job posting is there for javascript developer in the tech industry.
According to Stack Overflow Developer Survey 2019 Javascript is #1 programming language. The language is widely used by 95% of all the websites which you can check here. Whether it’s a small startup or a big company, most of them are working on some kind of website or an app that requires a good knowledge of this language. A lot of frameworks and libraries are there for javascript. These frameworks and libraries can be easily learned if your javascript fundamentals are clear. A lot of concepts are confusing and overwhelming for developers but a good knowledge of these concepts will help you in the along run. Frameworks and libraries come and go but the fundamentals always remain the same. It’s easy to build any kind of application and learn any framework and libraries if the fundamentals are clear. Also, it will help you in interviews as well. Let’s discuss some of the basic concepts of javascript which are important to learn for any javascript developer.
Scope means variable access. What variable do I have access to when a code is running? In javascript by default, you’re always in root scope i.e. the window scope. The scope is simply a box with a boundary for variables, functions, and objects. These boundaries put restrictions on variables and determine whether you have access to the variable or not. It limits the visibility or availability of a variable to the other parts of the code. You must have a clear understanding of this concept because it helps you to separates logic in your code and also improves the readability. A scope can be defined in two ways...
Local Scope allow access to everything within the boundaries (inside the box)
Global Scope is everything outside the boundaries (outside the box). A global scope can not access a variable defined in local scope because it is enclosed from the outer world, except if you return it.
Example: The code given below will give you an error because “name” is defined within the boundary (local scope) of showName() function. You can not have access to this variable outside the function.
NOTE: THE CODE BELOW IS IN ERROR DUE TO A TYPO IN THE FUNCTION CALL, causing an error before the intended scoping error is raised by the console.log call.
Now, take a look at the code given below and see how you can access the variable “name” defined in the local scope.
As the name suggests IIFE is a function in javascript which immediately invoked and executed as soon as it is defined. Variables declared within the IIFE cannot be accessed by the outside world and this way you can avoid global scope from getting polluted. So the primary reason to use IIFE is to immediately executes the code and obtain data privacy.
A lot of developers get unexpected results when they are not clear with the concept of Hoisting in javascript. In javascript, you can call a function before it is defined and you won’t get an error ‘Uncaught ReferenceError’. The reason behind this is hoisting where the javascript interpreter always moves the variables and function declaration to the top of the current scope (function scope or global scope) before the code execution. Let’s understand this with example.
Example: Take a look at the code given below.
Now what happens if we invoke our function before we declare it (with hoisting)
The above code is not giving an error and you get the output ‘moo’ in your console. This is hoisting in javascript.
Example 2:
var a = 5;
console.log(5);
output: // 3
The above code with hoisting will give you the same output.
a = 5;
console.log(5);
var a;
output // 5
A closure is simply a function inside another function that has access to the outer function variable. Now, this definition sound pretty much straightforward but the real magic is created with the scope. The inner function (closure) can access the variable defined in its scope (variables defined between its curly brackets), in the scope of its parent function, and the global variables. Now here you need to remember that the outer function can not have access to the inner function variable (we have already discussed this in scope concept). Let’s take an example and understand it in a better way.
Example:
In the above example, the inner function ‘second()’ is a Closure. This inner function will have access to the variable ‘greet’ which is the part of the outer function ‘first()’ scope. Here the parent scope won’t have the access of child scope variable ‘name’.
Now the question is why do we need to learn closures? What’s the use of it? Closures are used when you want to extend behavior such as pass variables, methods, or arrays from an outer function to an inner function. In the above example, second() extends the behavior of the function first() and also has access to the variable ‘greet’. Javascript is not pure object-oriented language but you can achieve object-oriented behavior through closures. In the above example, you can think const ‘newFunc’ as an Object having property ‘greet’ and ‘second()’ a method as in an OOP language.
Here you need to notice that after first() statement is executed, variables inside the first() function will not be destroyed (even if it has ‘return’ statement) because of closures as the scope is kept alive here and child function can still access the properties of the parent function. So closures can be defined in simple terms as “a function run, the function executed. It’s never going to execute again but it’s going to remember that there are references to those variables so the child scope always has access to the parent scope.”
In javascript, a callback is simply a function that is passed to another function as a parameter and is invoked or executed inside the other function. Here a function needs to wait for another function to execute or return value and this makes the chain of the functionalities (when X is completed, then Y executed, and it goes on.). This is the reason callback is generally used in the asynchronous operation of javascript to provide the synchronous capability.
Example:
In the above example notice that greeting passed as an argument (callback) to the ‘processUserName’ function. Before the ‘greeting’ function executed it waits for the event ‘processUserName’ to execute first.
We understand the concept of callback but what will happen if your code will have callbacks within callbacks within callbacks and it goes on. Well, this recursive structure of callback is called as ‘callback hell’ and promises help to solve this kind of issue. Promises are useful in asynchronous javascript operation when we need to execute two or more back to back operations (or chaining callback), where each subsequent function starts when the previous one is completed. A promise is an object that may produce a single value some time in the future, either a resolved value or a reason that it’s not resolved (rejected). According to developer.mozilla “A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.”. Promises resolve the issue of ‘callback hell’ which is nothing but a recursive structure of callbacks (callbacks within callbacks within callbacks and so forth). A promise may be in three possible states...
Fulfilled: When the operation is completed successfully.
Rejected: When the operation is failed.
Pending: initial state, neither fulfilled nor rejected.
Let’s discuss how to create a promise in javascript with an example.
Example:
Consider the above code for a sample promise assume like doing ‘isNameExist’ operation asynchronously, In that promise Object arguments as two function resolve and reject. If the operation is successful which means ‘isNameExist’ is ‘true’ then it will be resolved and display the output “User name exist” else the operation will be failed or rejected and it will display the result ‘error !’. You can easily perform chaining operations in promises where the first operation will be executed and the result of the first operation will be passed to the second operation and this will be continued further. 7. Async & Await
Stop and wait until something is resolved. Async & await just syntactic sugar on top of Promises and like promises it also provides a way to maintain asynchronous operation more synchronously. So in javascript asynchronous operation can be handled in various versions...
ES5 -> Callback
ES6 -> Promise
ES7 -> async & await
You can use Async/await to perform the Rest API request where you want the data to fully load before pushing it to the view. For Nodejs and browser programmers async/await is a great syntactic improvement. It helps the developer to implement functional programming in javascript and it also increases the code readability.
Example:
const showPosts = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await response.json();
console.log(posts);
}
showPosts();
Below is the image of when you will run this code in your console.
To notify JS that we are working with promises we need to wrap ‘await’ inside an ‘async’ function. In the above example, we (a)wait for two things: response and posts. Before we can convert the response to JSON format, we need to make sure we have the response fetched, otherwise we can end up converting a response that is not there yet, which will most likely prompt an error.
steve43
javaScript
GBlog
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Types of Software Testing
Working with csv files in Python
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": 26283,
"s": 26255,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 26893,
"s": 26283,
"text": "JavaScript is Everywhere. Millions of webpages are built on JavaScript and it’s not going anywhere at least for now. On one side HTML and CSS give styling to the web pages but on the other side, it’s the magic of JavaScript that makes your web page alive. Today this language is not just limited to your web browser. You can also use it for server-side applications. Isn’t it cool to use a single language for both client-side and server-side applications? A single language fulfills both of the purposes and this is the main reason TON of job posting is there for javascript developer in the tech industry. "
},
{
"code": null,
"e": 27864,
"s": 26893,
"text": "According to Stack Overflow Developer Survey 2019 Javascript is #1 programming language. The language is widely used by 95% of all the websites which you can check here. Whether it’s a small startup or a big company, most of them are working on some kind of website or an app that requires a good knowledge of this language. A lot of frameworks and libraries are there for javascript. These frameworks and libraries can be easily learned if your javascript fundamentals are clear. A lot of concepts are confusing and overwhelming for developers but a good knowledge of these concepts will help you in the along run. Frameworks and libraries come and go but the fundamentals always remain the same. It’s easy to build any kind of application and learn any framework and libraries if the fundamentals are clear. Also, it will help you in interviews as well. Let’s discuss some of the basic concepts of javascript which are important to learn for any javascript developer. "
},
{
"code": null,
"e": 28485,
"s": 27864,
"text": "Scope means variable access. What variable do I have access to when a code is running? In javascript by default, you’re always in root scope i.e. the window scope. The scope is simply a box with a boundary for variables, functions, and objects. These boundaries put restrictions on variables and determine whether you have access to the variable or not. It limits the visibility or availability of a variable to the other parts of the code. You must have a clear understanding of this concept because it helps you to separates logic in your code and also improves the readability. A scope can be defined in two ways... "
},
{
"code": null,
"e": 28563,
"s": 28485,
"text": "Local Scope allow access to everything within the boundaries (inside the box)"
},
{
"code": null,
"e": 28766,
"s": 28563,
"text": "Global Scope is everything outside the boundaries (outside the box). A global scope can not access a variable defined in local scope because it is enclosed from the outer world, except if you return it."
},
{
"code": null,
"e": 28967,
"s": 28766,
"text": "Example: The code given below will give you an error because “name” is defined within the boundary (local scope) of showName() function. You can not have access to this variable outside the function. "
},
{
"code": null,
"e": 29122,
"s": 28967,
"text": "NOTE: THE CODE BELOW IS IN ERROR DUE TO A TYPO IN THE FUNCTION CALL, causing an error before the intended scoping error is raised by the console.log call."
},
{
"code": null,
"e": 29241,
"s": 29124,
"text": "Now, take a look at the code given below and see how you can access the variable “name” defined in the local scope. "
},
{
"code": null,
"e": 29599,
"s": 29245,
"text": "As the name suggests IIFE is a function in javascript which immediately invoked and executed as soon as it is defined. Variables declared within the IIFE cannot be accessed by the outside world and this way you can avoid global scope from getting polluted. So the primary reason to use IIFE is to immediately executes the code and obtain data privacy. "
},
{
"code": null,
"e": 30073,
"s": 29599,
"text": "A lot of developers get unexpected results when they are not clear with the concept of Hoisting in javascript. In javascript, you can call a function before it is defined and you won’t get an error ‘Uncaught ReferenceError’. The reason behind this is hoisting where the javascript interpreter always moves the variables and function declaration to the top of the current scope (function scope or global scope) before the code execution. Let’s understand this with example. "
},
{
"code": null,
"e": 30120,
"s": 30073,
"text": "Example: Take a look at the code given below. "
},
{
"code": null,
"e": 30203,
"s": 30122,
"text": "Now what happens if we invoke our function before we declare it (with hoisting) "
},
{
"code": null,
"e": 30322,
"s": 30205,
"text": "The above code is not giving an error and you get the output ‘moo’ in your console. This is hoisting in javascript. "
},
{
"code": null,
"e": 30334,
"s": 30322,
"text": "Example 2: "
},
{
"code": null,
"e": 30374,
"s": 30334,
"text": "var a = 5;\nconsole.log(5);\noutput: // 3"
},
{
"code": null,
"e": 30435,
"s": 30374,
"text": "The above code with hoisting will give you the same output. "
},
{
"code": null,
"e": 30477,
"s": 30435,
"text": "a = 5;\nconsole.log(5);\nvar a;\noutput // 5"
},
{
"code": null,
"e": 31080,
"s": 30477,
"text": "A closure is simply a function inside another function that has access to the outer function variable. Now, this definition sound pretty much straightforward but the real magic is created with the scope. The inner function (closure) can access the variable defined in its scope (variables defined between its curly brackets), in the scope of its parent function, and the global variables. Now here you need to remember that the outer function can not have access to the inner function variable (we have already discussed this in scope concept). Let’s take an example and understand it in a better way. "
},
{
"code": null,
"e": 31090,
"s": 31080,
"text": "Example: "
},
{
"code": null,
"e": 31353,
"s": 31092,
"text": "In the above example, the inner function ‘second()’ is a Closure. This inner function will have access to the variable ‘greet’ which is the part of the outer function ‘first()’ scope. Here the parent scope won’t have the access of child scope variable ‘name’. "
},
{
"code": null,
"e": 31937,
"s": 31353,
"text": "Now the question is why do we need to learn closures? What’s the use of it? Closures are used when you want to extend behavior such as pass variables, methods, or arrays from an outer function to an inner function. In the above example, second() extends the behavior of the function first() and also has access to the variable ‘greet’. Javascript is not pure object-oriented language but you can achieve object-oriented behavior through closures. In the above example, you can think const ‘newFunc’ as an Object having property ‘greet’ and ‘second()’ a method as in an OOP language. "
},
{
"code": null,
"e": 32478,
"s": 31937,
"text": "Here you need to notice that after first() statement is executed, variables inside the first() function will not be destroyed (even if it has ‘return’ statement) because of closures as the scope is kept alive here and child function can still access the properties of the parent function. So closures can be defined in simple terms as “a function run, the function executed. It’s never going to execute again but it’s going to remember that there are references to those variables so the child scope always has access to the parent scope.” "
},
{
"code": null,
"e": 32944,
"s": 32480,
"text": "In javascript, a callback is simply a function that is passed to another function as a parameter and is invoked or executed inside the other function. Here a function needs to wait for another function to execute or return value and this makes the chain of the functionalities (when X is completed, then Y executed, and it goes on.). This is the reason callback is generally used in the asynchronous operation of javascript to provide the synchronous capability. "
},
{
"code": null,
"e": 32954,
"s": 32944,
"text": "Example: "
},
{
"code": null,
"e": 33166,
"s": 32956,
"text": "In the above example notice that greeting passed as an argument (callback) to the ‘processUserName’ function. Before the ‘greeting’ function executed it waits for the event ‘processUserName’ to execute first. "
},
{
"code": null,
"e": 34257,
"s": 33166,
"text": "We understand the concept of callback but what will happen if your code will have callbacks within callbacks within callbacks and it goes on. Well, this recursive structure of callback is called as ‘callback hell’ and promises help to solve this kind of issue. Promises are useful in asynchronous javascript operation when we need to execute two or more back to back operations (or chaining callback), where each subsequent function starts when the previous one is completed. A promise is an object that may produce a single value some time in the future, either a resolved value or a reason that it’s not resolved (rejected). According to developer.mozilla “A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.”. Promises resolve the issue of ‘callback hell’ which is nothing but a recursive structure of callbacks (callbacks within callbacks within callbacks and so forth). A promise may be in three possible states... "
},
{
"code": null,
"e": 34316,
"s": 34259,
"text": "Fulfilled: When the operation is completed successfully."
},
{
"code": null,
"e": 34356,
"s": 34316,
"text": "Rejected: When the operation is failed."
},
{
"code": null,
"e": 34412,
"s": 34356,
"text": "Pending: initial state, neither fulfilled nor rejected."
},
{
"code": null,
"e": 34482,
"s": 34412,
"text": "Let’s discuss how to create a promise in javascript with an example. "
},
{
"code": null,
"e": 34493,
"s": 34482,
"text": "Example: "
},
{
"code": null,
"e": 35114,
"s": 34493,
"text": "Consider the above code for a sample promise assume like doing ‘isNameExist’ operation asynchronously, In that promise Object arguments as two function resolve and reject. If the operation is successful which means ‘isNameExist’ is ‘true’ then it will be resolved and display the output “User name exist” else the operation will be failed or rejected and it will display the result ‘error !’. You can easily perform chaining operations in promises where the first operation will be executed and the result of the first operation will be passed to the second operation and this will be continued further. 7. Async & Await"
},
{
"code": null,
"e": 35387,
"s": 35114,
"text": "Stop and wait until something is resolved. Async & await just syntactic sugar on top of Promises and like promises it also provides a way to maintain asynchronous operation more synchronously. So in javascript asynchronous operation can be handled in various versions... "
},
{
"code": null,
"e": 35403,
"s": 35387,
"text": "ES5 -> Callback"
},
{
"code": null,
"e": 35418,
"s": 35403,
"text": "ES6 -> Promise"
},
{
"code": null,
"e": 35439,
"s": 35418,
"text": "ES7 -> async & await"
},
{
"code": null,
"e": 35763,
"s": 35439,
"text": "You can use Async/await to perform the Rest API request where you want the data to fully load before pushing it to the view. For Nodejs and browser programmers async/await is a great syntactic improvement. It helps the developer to implement functional programming in javascript and it also increases the code readability. "
},
{
"code": null,
"e": 35773,
"s": 35763,
"text": "Example: "
},
{
"code": null,
"e": 35958,
"s": 35773,
"text": " const showPosts = async () => {\n const response = await fetch('https://jsonplaceholder.typicode.com/posts');\n const posts = await response.json();\n console.log(posts);\n}\n\nshowPosts();"
},
{
"code": null,
"e": 36026,
"s": 35958,
"text": "Below is the image of when you will run this code in your console. "
},
{
"code": null,
"e": 36405,
"s": 36026,
"text": "To notify JS that we are working with promises we need to wrap ‘await’ inside an ‘async’ function. In the above example, we (a)wait for two things: response and posts. Before we can convert the response to JSON format, we need to make sure we have the response fetched, otherwise we can end up converting a response that is not there yet, which will most likely prompt an error."
},
{
"code": null,
"e": 36413,
"s": 36405,
"text": "steve43"
},
{
"code": null,
"e": 36424,
"s": 36413,
"text": "javaScript"
},
{
"code": null,
"e": 36430,
"s": 36424,
"text": "GBlog"
},
{
"code": null,
"e": 36447,
"s": 36430,
"text": "Web Technologies"
},
{
"code": null,
"e": 36545,
"s": 36447,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36570,
"s": 36545,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36605,
"s": 36570,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 36667,
"s": 36605,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 36693,
"s": 36667,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 36726,
"s": 36693,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 36766,
"s": 36726,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 36799,
"s": 36766,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 36844,
"s": 36799,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 36887,
"s": 36844,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
cal command in Linux with Examples - GeeksforGeeks | 28 Jul, 2021
If a user wants a quick view of the calendar in the Linux terminal, cal is the command for you. By default, the cal command shows the current month calendar as output.
cal command is a calendar command in Linux which is used to see the calendar of a specific month or a whole year.
Syntax:
cal [ [ month ] year]
The rectangular bracket means it is optional, so if used without an option, it will display a calendar of the current month and year.
cal : Shows current month calendar on the terminal with the current date highlighted.
cal -y : Shows the calendar of the complete current year with the current date highlighted.
cal 08 2000 : Shows calendar of selected month and year.
cal 2018 : Shows the whole calendar of the year.
cal 2018 | more : But year may not be visible in the same screen use more with cal use spacebar to scroll down.
cal -3 : Shows calendar of previous, current and next month
cal -j : Shows the calendar of the current month in the Julian calendar format not in the default Gregorian calendar format. In Julian calendar format, the date does not reset to 1 after every month’s end i.e. after 31st Jan, Feb will start as 32nd Feb, not as 1st Feb. But in the Gregorian calendar format, the date is reset to 1 after every month’s end i.e after 31st Jan, Feb will start as of 1st Feb.
YouTubeGeeksforGeeks507K subscribersLinux Tutorials | General Purpose Utilities | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:09•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=g6cPFj9ptdc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
sanju6890
Linux-basic-commands
linux-command
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
UDP Server-Client implementation in C
Tail command in Linux with examples
echo command in Linux with Examples
Compiling with g++
scp command in Linux with Examples | [
{
"code": null,
"e": 25342,
"s": 25314,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 25511,
"s": 25342,
"text": "If a user wants a quick view of the calendar in the Linux terminal, cal is the command for you. By default, the cal command shows the current month calendar as output. "
},
{
"code": null,
"e": 25626,
"s": 25511,
"text": "cal command is a calendar command in Linux which is used to see the calendar of a specific month or a whole year. "
},
{
"code": null,
"e": 25635,
"s": 25626,
"text": "Syntax: "
},
{
"code": null,
"e": 25657,
"s": 25635,
"text": "cal [ [ month ] year]"
},
{
"code": null,
"e": 25793,
"s": 25657,
"text": "The rectangular bracket means it is optional, so if used without an option, it will display a calendar of the current month and year. "
},
{
"code": null,
"e": 25881,
"s": 25793,
"text": "cal : Shows current month calendar on the terminal with the current date highlighted. "
},
{
"code": null,
"e": 25973,
"s": 25881,
"text": "cal -y : Shows the calendar of the complete current year with the current date highlighted."
},
{
"code": null,
"e": 26032,
"s": 25973,
"text": "cal 08 2000 : Shows calendar of selected month and year. "
},
{
"code": null,
"e": 26083,
"s": 26032,
"text": "cal 2018 : Shows the whole calendar of the year. "
},
{
"code": null,
"e": 26197,
"s": 26083,
"text": "cal 2018 | more : But year may not be visible in the same screen use more with cal use spacebar to scroll down. "
},
{
"code": null,
"e": 26259,
"s": 26197,
"text": "cal -3 : Shows calendar of previous, current and next month "
},
{
"code": null,
"e": 26666,
"s": 26259,
"text": "cal -j : Shows the calendar of the current month in the Julian calendar format not in the default Gregorian calendar format. In Julian calendar format, the date does not reset to 1 after every month’s end i.e. after 31st Jan, Feb will start as 32nd Feb, not as 1st Feb. But in the Gregorian calendar format, the date is reset to 1 after every month’s end i.e after 31st Jan, Feb will start as of 1st Feb."
},
{
"code": null,
"e": 27508,
"s": 26666,
"text": "YouTubeGeeksforGeeks507K subscribersLinux Tutorials | General Purpose Utilities | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:09•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=g6cPFj9ptdc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 27518,
"s": 27508,
"text": "sanju6890"
},
{
"code": null,
"e": 27539,
"s": 27518,
"text": "Linux-basic-commands"
},
{
"code": null,
"e": 27553,
"s": 27539,
"text": "linux-command"
},
{
"code": null,
"e": 27560,
"s": 27553,
"text": "Picked"
},
{
"code": null,
"e": 27571,
"s": 27560,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27669,
"s": 27571,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27704,
"s": 27669,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 27742,
"s": 27704,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27777,
"s": 27742,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 27813,
"s": 27777,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 27851,
"s": 27813,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 27889,
"s": 27851,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27925,
"s": 27889,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 27961,
"s": 27925,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 27980,
"s": 27961,
"text": "Compiling with g++"
}
] |
How to set Maximum Date in the DateTimePicker in C#? - GeeksforGeeks | 02 Aug, 2019
In Windows Forms, the DateTimePicker control is used to select and display date/time with a specific format in your form. In DateTimePicker control, you can set the maximum date and time that can be selected in the DateTimePicker using the MaxDate Property. The default value of this property is December 31st, 9998 12 am. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the maximum date and time in the DateTimePicker as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Next, drag and drop the DateTimePicker control from the toolbox to the form as shown in the below image:
Step 3: After drag and drop you will go to the properties of the DateTimePicker and set the maximum date and time in the DateTimePicker as shown in the below image:Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the maximum date and time in the DateTimePicker control programmatically with the help of given syntax:
public DateTime MaxDate { get; set; }
It will throw an ArgumentException if the value of this property is not less than the MaxDate value and also throw a SystemException if the value of this property is less than the MinDateTime value. The following steps show how to set the maximum date and time in the DateTimePicker dynamically:
Step 1: Create a DateTimePicker using the DateTimePicker() constructor is provided by the DateTimePicker class.// Creating a DateTimePicker
DateTimePicker dt = new DateTimePicker();
// Creating a DateTimePicker
DateTimePicker dt = new DateTimePicker();
Step 2: After creating DateTimePicker, set the MaxDate property of the DateTimePicker provided by the DateTimePicker class.// Setting the maximum date and time
dt.MaxDate = new DateTime(2500, 12, 20);
// Setting the maximum date and time
dt.MaxDate = new DateTime(2500, 12, 20);
Step 3: And last add this DateTimePicker control to the form using the following statement:// Adding this control to the form
this.Controls.Add(dt);
// Adding this control to the form
this.Controls.Add(dt);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp48 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label lab = new Label(); lab.Location = new Point(183, 162); lab.Size = new Size(172, 20); lab.Text = "Select Date and Time"; lab.Font = new Font("Comic Sans MS", 12); // Adding this control // to the form this.Controls.Add(lab); // Creating and setting the // properties of the DateTimePicker DateTimePicker dt = new DateTimePicker(); dt.Location = new Point(360, 162); dt.Size = new Size(292, 26); dt.MaxDate = new DateTime(2500, 12, 20); dt.MinDate = new DateTime(1753, 1, 1); dt.Format = DateTimePickerFormat.Long; dt.Name = "MyPicker"; dt.Font = new Font("Comic Sans MS", 12); dt.Visible = true; dt.Value = DateTime.Today; // Adding this control // to the form this.Controls.Add(dt); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Arrays | [
{
"code": null,
"e": 25239,
"s": 25211,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 25611,
"s": 25239,
"text": "In Windows Forms, the DateTimePicker control is used to select and display date/time with a specific format in your form. In DateTimePicker control, you can set the maximum date and time that can be selected in the DateTimePicker using the MaxDate Property. The default value of this property is December 31st, 9998 12 am. You can set this property in two different ways:"
},
{
"code": null,
"e": 25737,
"s": 25611,
"text": "1. Design-Time: It is the easiest way to set the maximum date and time in the DateTimePicker as shown in the following steps:"
},
{
"code": null,
"e": 25853,
"s": 25737,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 25911,
"s": 25853,
"text": "Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 26024,
"s": 25911,
"text": "Step 2: Next, drag and drop the DateTimePicker control from the toolbox to the form as shown in the below image:"
},
{
"code": null,
"e": 26196,
"s": 26024,
"text": "Step 3: After drag and drop you will go to the properties of the DateTimePicker and set the maximum date and time in the DateTimePicker as shown in the below image:Output:"
},
{
"code": null,
"e": 26204,
"s": 26196,
"text": "Output:"
},
{
"code": null,
"e": 26400,
"s": 26204,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the maximum date and time in the DateTimePicker control programmatically with the help of given syntax:"
},
{
"code": null,
"e": 26438,
"s": 26400,
"text": "public DateTime MaxDate { get; set; }"
},
{
"code": null,
"e": 26734,
"s": 26438,
"text": "It will throw an ArgumentException if the value of this property is not less than the MaxDate value and also throw a SystemException if the value of this property is less than the MinDateTime value. The following steps show how to set the maximum date and time in the DateTimePicker dynamically:"
},
{
"code": null,
"e": 26917,
"s": 26734,
"text": "Step 1: Create a DateTimePicker using the DateTimePicker() constructor is provided by the DateTimePicker class.// Creating a DateTimePicker\nDateTimePicker dt = new DateTimePicker();\n"
},
{
"code": null,
"e": 26989,
"s": 26917,
"text": "// Creating a DateTimePicker\nDateTimePicker dt = new DateTimePicker();\n"
},
{
"code": null,
"e": 27192,
"s": 26989,
"text": "Step 2: After creating DateTimePicker, set the MaxDate property of the DateTimePicker provided by the DateTimePicker class.// Setting the maximum date and time \ndt.MaxDate = new DateTime(2500, 12, 20);\n"
},
{
"code": null,
"e": 27272,
"s": 27192,
"text": "// Setting the maximum date and time \ndt.MaxDate = new DateTime(2500, 12, 20);\n"
},
{
"code": null,
"e": 27422,
"s": 27272,
"text": "Step 3: And last add this DateTimePicker control to the form using the following statement:// Adding this control to the form\nthis.Controls.Add(dt);\n"
},
{
"code": null,
"e": 27481,
"s": 27422,
"text": "// Adding this control to the form\nthis.Controls.Add(dt);\n"
},
{
"code": null,
"e": 27490,
"s": 27481,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp48 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label lab = new Label(); lab.Location = new Point(183, 162); lab.Size = new Size(172, 20); lab.Text = \"Select Date and Time\"; lab.Font = new Font(\"Comic Sans MS\", 12); // Adding this control // to the form this.Controls.Add(lab); // Creating and setting the // properties of the DateTimePicker DateTimePicker dt = new DateTimePicker(); dt.Location = new Point(360, 162); dt.Size = new Size(292, 26); dt.MaxDate = new DateTime(2500, 12, 20); dt.MinDate = new DateTime(1753, 1, 1); dt.Format = DateTimePickerFormat.Long; dt.Name = \"MyPicker\"; dt.Font = new Font(\"Comic Sans MS\", 12); dt.Visible = true; dt.Value = DateTime.Today; // Adding this control // to the form this.Controls.Add(dt); }}}",
"e": 28819,
"s": 27490,
"text": null
},
{
"code": null,
"e": 28827,
"s": 28819,
"text": "Output:"
},
{
"code": null,
"e": 28858,
"s": 28827,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 28861,
"s": 28858,
"text": "C#"
},
{
"code": null,
"e": 28959,
"s": 28861,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28987,
"s": 28959,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 29002,
"s": 28987,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29025,
"s": 29002,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 29047,
"s": 29025,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 29093,
"s": 29047,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 29116,
"s": 29093,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29138,
"s": 29116,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 29178,
"s": 29138,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 29209,
"s": 29178,
"text": "Introduction to .NET Framework"
}
] |
What is MySQL NOT NULL constraint and how can we declare a field NOT NULL while creating a table? | Actually, MySQL NOT NULL constraint restricts a column of the table from having a NULL value. Once we applied NOT NULL constraint to a column, then we cannot pass a null value to that column. It cannot be declared on the whole table i.e., in other words, we can say that NOT NULL is a column level constraint.
For declaring a field NOT NULL, we have to use NOT NULL keyword while defining the column in CREATE TABLE statement.
mysql> Create table Employee(ID Int NOT NULL, First_Name Varchar(20), Last_name Varchar(20), Designation Varchar(15));
Query OK, 0 rows affected (0.59 sec)
In the query above, we have applied NOT NULL constraint on the field ‘ID’ of ‘Employee’ table. Now, the column ‘ID’ cannot take NULL value. It can be also checked from DESCRIBE statement that ID filed cannot accept NULL values.
mysql> DESCRIBE Employee123\G
*************************** 1. row ***************************
Field: ID
Type: int(11)
Null: NO
Key:
Default: NULL
Extra:
*************************** 2. row ***************************
Field: First_Name
Type: varchar(20)
Null: YES
Key:
Default: NULL
Extra:
*************************** 3. row ***************************
Field: Last_name
Type: varchar(20)
Null: YES
Key:
Default: NULL
Extra:
*************************** 4. row ***************************
Field: Designation
Type: varchar(15)
Null: YES
Key:
Default: NULL
Extra:
4 rows in set (0.03 sec) | [
{
"code": null,
"e": 1372,
"s": 1062,
"text": "Actually, MySQL NOT NULL constraint restricts a column of the table from having a NULL value. Once we applied NOT NULL constraint to a column, then we cannot pass a null value to that column. It cannot be declared on the whole table i.e., in other words, we can say that NOT NULL is a column level constraint."
},
{
"code": null,
"e": 1489,
"s": 1372,
"text": "For declaring a field NOT NULL, we have to use NOT NULL keyword while defining the column in CREATE TABLE statement."
},
{
"code": null,
"e": 1645,
"s": 1489,
"text": "mysql> Create table Employee(ID Int NOT NULL, First_Name Varchar(20), Last_name Varchar(20), Designation Varchar(15));\nQuery OK, 0 rows affected (0.59 sec)"
},
{
"code": null,
"e": 1873,
"s": 1645,
"text": "In the query above, we have applied NOT NULL constraint on the field ‘ID’ of ‘Employee’ table. Now, the column ‘ID’ cannot take NULL value. It can be also checked from DESCRIBE statement that ID filed cannot accept NULL values."
},
{
"code": null,
"e": 2511,
"s": 1873,
"text": "mysql> DESCRIBE Employee123\\G\n*************************** 1. row ***************************\n Field: ID\n Type: int(11)\n Null: NO\n Key:\nDefault: NULL\n Extra:\n*************************** 2. row ***************************\n Field: First_Name\n Type: varchar(20)\n Null: YES\n Key:\nDefault: NULL\n Extra:\n*************************** 3. row ***************************\n Field: Last_name\n Type: varchar(20)\n Null: YES\n Key:\nDefault: NULL\n Extra:\n*************************** 4. row ***************************\n Field: Designation\n Type: varchar(15)\n Null: YES\n Key:\nDefault: NULL\n Extra:\n4 rows in set (0.03 sec)"
}
] |
Node.js v8.deserialize() Method - GeeksforGeeks | 28 Jul, 2020
The v8.deserialize() method is an inbuilt application programming interface of the v8 module which is used to deserialize a buffered data into JS value using default deserializer.
Syntax:
v8.deserialize( buffer );
Parameters: This method accepts one parameter as mentioned above and described below:
buffer: This is a required parameter, a Buffer / TypedArray / DataView, refers to a buffered data to be deserialized.
Return Value: This method returns JS value after deserializing the buffered data.
Below examples illustrate the use of v8.deserialize() method in Node.js.
Example 1: Filename: index.js
// Accessing v8 moduleconst v8 = require('v8'); // Calling v8.deserialize() console.log(v8.deserialize(v8.serialize("geeksforgeeks")));
Run index.js file using the following command:
node index.js
Output:
geeksforgeeks
Example 2: Filename: index.js
// Accessing v8 moduleconst v8 = require('v8'); // Calling v8.deserialize() deserialized_data = v8.deserialize(v8.serialize("abcdefg"));console.log("\nDeserialized data is ");console.log(deserialized_data); deserialized_data = v8.deserialize(v8.serialize(58375693));console.log("\nDeserialized data is ");console.log(deserialized_data); deserialized_data = v8.deserialize(v8.serialize(73847.0234));console.log("\nDeserialized data is ");console.log(deserialized_data); deserialized_data = v8.deserialize(v8.serialize('Geek'));console.log("\nDeserialized data is ");console.log(deserialized_data);
Run index.js file using the following command:
node index.js
Output:
Deserialized data is
abcdefg
Deserialized data is
58375693
Deserialized data is
73847.0234
Deserialized data is
Geek
Reference: https://nodejs.org/api/v8.html#v8_v8_deserialize_buffer
Node.js-V8-Module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.readFileSync() Method
How to update Node.js and NPM to next version ?
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 37256,
"s": 37228,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 37436,
"s": 37256,
"text": "The v8.deserialize() method is an inbuilt application programming interface of the v8 module which is used to deserialize a buffered data into JS value using default deserializer."
},
{
"code": null,
"e": 37444,
"s": 37436,
"text": "Syntax:"
},
{
"code": null,
"e": 37470,
"s": 37444,
"text": "v8.deserialize( buffer );"
},
{
"code": null,
"e": 37556,
"s": 37470,
"text": "Parameters: This method accepts one parameter as mentioned above and described below:"
},
{
"code": null,
"e": 37674,
"s": 37556,
"text": "buffer: This is a required parameter, a Buffer / TypedArray / DataView, refers to a buffered data to be deserialized."
},
{
"code": null,
"e": 37756,
"s": 37674,
"text": "Return Value: This method returns JS value after deserializing the buffered data."
},
{
"code": null,
"e": 37829,
"s": 37756,
"text": "Below examples illustrate the use of v8.deserialize() method in Node.js."
},
{
"code": null,
"e": 37859,
"s": 37829,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Accessing v8 moduleconst v8 = require('v8'); // Calling v8.deserialize() console.log(v8.deserialize(v8.serialize(\"geeksforgeeks\")));",
"e": 37996,
"s": 37859,
"text": null
},
{
"code": null,
"e": 38043,
"s": 37996,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 38057,
"s": 38043,
"text": "node index.js"
},
{
"code": null,
"e": 38065,
"s": 38057,
"text": "Output:"
},
{
"code": null,
"e": 38080,
"s": 38065,
"text": "geeksforgeeks\n"
},
{
"code": null,
"e": 38110,
"s": 38080,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Accessing v8 moduleconst v8 = require('v8'); // Calling v8.deserialize() deserialized_data = v8.deserialize(v8.serialize(\"abcdefg\"));console.log(\"\\nDeserialized data is \");console.log(deserialized_data); deserialized_data = v8.deserialize(v8.serialize(58375693));console.log(\"\\nDeserialized data is \");console.log(deserialized_data); deserialized_data = v8.deserialize(v8.serialize(73847.0234));console.log(\"\\nDeserialized data is \");console.log(deserialized_data); deserialized_data = v8.deserialize(v8.serialize('Geek'));console.log(\"\\nDeserialized data is \");console.log(deserialized_data);",
"e": 38711,
"s": 38110,
"text": null
},
{
"code": null,
"e": 38758,
"s": 38711,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 38772,
"s": 38758,
"text": "node index.js"
},
{
"code": null,
"e": 38780,
"s": 38772,
"text": "Output:"
},
{
"code": null,
"e": 38901,
"s": 38780,
"text": "Deserialized data is\nabcdefg\n\nDeserialized data is\n58375693\n\nDeserialized data is\n73847.0234\n\nDeserialized data is\nGeek\n"
},
{
"code": null,
"e": 38968,
"s": 38901,
"text": "Reference: https://nodejs.org/api/v8.html#v8_v8_deserialize_buffer"
},
{
"code": null,
"e": 38986,
"s": 38968,
"text": "Node.js-V8-Module"
},
{
"code": null,
"e": 38994,
"s": 38986,
"text": "Node.js"
},
{
"code": null,
"e": 39011,
"s": 38994,
"text": "Web Technologies"
},
{
"code": null,
"e": 39109,
"s": 39011,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39142,
"s": 39109,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 39190,
"s": 39142,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 39220,
"s": 39190,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 39240,
"s": 39220,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 39294,
"s": 39240,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 39336,
"s": 39294,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 39379,
"s": 39336,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 39441,
"s": 39379,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 39486,
"s": 39441,
"text": "Convert a string to an integer in JavaScript"
}
] |
JavaFX Label setLabelFor() method example | In JavaFX, you can create a label by instantiating the javafx.scene.control.Label class. This class provides a method named labelFor(). Using this method, you can set the current label as a label for another control node.
This method comes handy while setting, mnemonics, and accelerator parsing.
In the following JavaFX example, we have created a label, a text field, and a button. Using the labelFor() method we have associated the label (Text) with a text field, enabling the mnemonic parsing (T). Therefore, on the output window, if you press Alt + t, the text field will be focused.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class LabelFor_Example extends Application {
public void start(Stage stage) {
//Creating nodes
TextField textField = new TextField();
Button button = new Button("Click Me");
//creating labels
Label label1 = new Label("_Text");
label1.setMnemonicParsing(true);
label1.setLabelFor(textField);
//Adding labels for nodes
HBox box1 = new HBox(5);
box1.setPadding(new Insets(25, 5 , 5, 50));
box1.getChildren().addAll(label1, textField, button);
//Setting the stage
Scene scene = new Scene(box1, 595, 150, Color.BEIGE);
stage.setTitle("JavaFX Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
} | [
{
"code": null,
"e": 1284,
"s": 1062,
"text": "In JavaFX, you can create a label by instantiating the javafx.scene.control.Label class. This class provides a method named labelFor(). Using this method, you can set the current label as a label for another control node."
},
{
"code": null,
"e": 1359,
"s": 1284,
"text": "This method comes handy while setting, mnemonics, and accelerator parsing."
},
{
"code": null,
"e": 1650,
"s": 1359,
"text": "In the following JavaFX example, we have created a label, a text field, and a button. Using the labelFor() method we have associated the label (Text) with a text field, enabling the mnemonic parsing (T). Therefore, on the output window, if you press Alt + t, the text field will be focused."
},
{
"code": null,
"e": 2716,
"s": 1650,
"text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.TextField;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class LabelFor_Example extends Application {\n public void start(Stage stage) {\n //Creating nodes\n TextField textField = new TextField();\n Button button = new Button(\"Click Me\");\n //creating labels\n Label label1 = new Label(\"_Text\");\n label1.setMnemonicParsing(true);\n label1.setLabelFor(textField);\n //Adding labels for nodes\n HBox box1 = new HBox(5);\n box1.setPadding(new Insets(25, 5 , 5, 50));\n box1.getChildren().addAll(label1, textField, button);\n //Setting the stage\n Scene scene = new Scene(box1, 595, 150, Color.BEIGE);\n stage.setTitle(\"JavaFX Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
Implementing Photomosaics in Python | The photomosaic is a technique, where we can split our image into a grid of squares. Each square will be replaced by some other images or colors. So when we want to see the actual image from a certain distance, we can see the actual image, but if we come closer, we can see the grid of different colored blocks.
In this case we are using a Python module called photomosaic. Using this module, we can easily create some photomosaics. To install it please follow this link. It will also download the scikit learn module.
sudo pip3 install photomosaic
This module has some features. These are listed below −
Here we can use different size of tiles.
We can set smaller tiles for detailed part of an image.
Use flicker api to get large collection of images to use as tiles
In this article, we will see how to implement this module for photomosaics in a very simple way.
We are using an image from skimage library.
Take the actual image (here image from skimage library)
define the grid tile size
Provide a location to create colorful RGB image blocks as pool
Set the folder as Pool for the photomosaic
Turn into photomosaic using the pool and the grid size.
Save the image
exit
from skimage.io import *
import sys
import photomosaic asphmos
from skimage import data
image = data.coffee() #Get coffee image from skimage
#Get the mosaic size from the command line argument.
mos_size = (int(sys.argv[1]), int(sys.argv[2]))
#create all image squares and generate pool
phmos.rainbow_of_squares('square/')
square_pool = phmos.make_pool('square/*.png')
#Create the mosaic image and save
mosaic = phmos.basic_mosaic(image, square_pool, mos_size)
imsave('mosaic_op.png', mosaic)
$ python3 225.Photomosaic.py 100 100
5832it [00:02, 2506.05it/s]
analyzing pool: 100%|| 5832/5832 [00:08<00:00, 717.90it/s]
/usr/local/lib/python3.6/dist-packages/skimage/transform/_warps.py:105: UserWarning: The default mode, 'constant', will be changed to 'reflect' in skimage 0.15.
warn("The default mode, 'constant', will be changed to 'reflect' in "
/usr/local/lib/python3.6/dist-packages/skimage/transform/_warps.py:110: UserWarning: Anti-aliasing will be enabled by default in skimage 0.15 to avoid aliasing artifacts when down-sampling images.
warn("Anti-aliasing will be enabled by default in skimage 0.15 to "
partitioning: depth 0: 100%|| 10000/10000 [00:00<00:00, 852292.94it/s]
analyzing tiles: 100%|| 10000/10000 [00:00<00:00, 93084.50it/s]
matching: 100%|| 10000/10000 [00:00<00:00, 30864.50it/s]
drawing mosaic: 100%|| 10000/10000 [00:00<00:00, 13227.12it/s]
/usr/local/lib/python3.6/dist-packages/skimage/util/dtype.py:141: UserWarning: Possible precision loss when converting from float64 to uint8
.format(dtypeobj_in, dtypeobj_out))
$ python3 225.Photomosaic.py 500 500
5832it [00:02, 2634.16it/s]
analyzing pool: 100%|| 5832/5832 [00:08<00:00, 709.54it/s]
/usr/local/lib/python3.6/dist-packages/skimage/transform/_warps.py:105: UserWarning: The default mode, 'constant', will be changed to 'reflect' in skimage 0.15.
warn("The default mode, 'constant', will be changed to 'reflect' in "
/usr/local/lib/python3.6/dist-packages/skimage/transform/_warps.py:110: UserWarning: Anti-aliasing will be enabled by default in skimage 0.15 to avoid aliasing artifacts when down-sampling images.
warn("Anti-aliasing will be enabled by default in skimage 0.15 to "
partitioning: depth 0: 100%|| 250000/250000 [00:00<00:00, 456159.45it/s]
analyzing tiles: 100%|| 250000/250000 [00:02<00:00, 113937.01it/s]
matching: 100%|| 250000/250000 [00:07<00:00, 32591.43it/s]
drawing mosaic: 100%|| 250000/250000 [00:02<00:00, 104349.90it/s]
/usr/local/lib/python3.6/dist-packages/skimage/util/dtype.py:141: UserWarning: Possible precision loss when converting from float64 to uint8
.format(dtypeobj_in, dtypeobj_out)) | [
{
"code": null,
"e": 1374,
"s": 1062,
"text": "The photomosaic is a technique, where we can split our image into a grid of squares. Each square will be replaced by some other images or colors. So when we want to see the actual image from a certain distance, we can see the actual image, but if we come closer, we can see the grid of different colored blocks."
},
{
"code": null,
"e": 1581,
"s": 1374,
"text": "In this case we are using a Python module called photomosaic. Using this module, we can easily create some photomosaics. To install it please follow this link. It will also download the scikit learn module."
},
{
"code": null,
"e": 1612,
"s": 1581,
"text": "sudo pip3 install photomosaic\n"
},
{
"code": null,
"e": 1668,
"s": 1612,
"text": "This module has some features. These are listed below −"
},
{
"code": null,
"e": 1709,
"s": 1668,
"text": "Here we can use different size of tiles."
},
{
"code": null,
"e": 1765,
"s": 1709,
"text": "We can set smaller tiles for detailed part of an image."
},
{
"code": null,
"e": 1831,
"s": 1765,
"text": "Use flicker api to get large collection of images to use as tiles"
},
{
"code": null,
"e": 1928,
"s": 1831,
"text": "In this article, we will see how to implement this module for photomosaics in a very simple way."
},
{
"code": null,
"e": 1972,
"s": 1928,
"text": "We are using an image from skimage library."
},
{
"code": null,
"e": 2028,
"s": 1972,
"text": "Take the actual image (here image from skimage library)"
},
{
"code": null,
"e": 2054,
"s": 2028,
"text": "define the grid tile size"
},
{
"code": null,
"e": 2117,
"s": 2054,
"text": "Provide a location to create colorful RGB image blocks as pool"
},
{
"code": null,
"e": 2160,
"s": 2117,
"text": "Set the folder as Pool for the photomosaic"
},
{
"code": null,
"e": 2216,
"s": 2160,
"text": "Turn into photomosaic using the pool and the grid size."
},
{
"code": null,
"e": 2231,
"s": 2216,
"text": "Save the image"
},
{
"code": null,
"e": 2236,
"s": 2231,
"text": "exit"
},
{
"code": null,
"e": 2728,
"s": 2236,
"text": "from skimage.io import *\nimport sys\nimport photomosaic asphmos\nfrom skimage import data\nimage = data.coffee() #Get coffee image from skimage\n#Get the mosaic size from the command line argument.\nmos_size = (int(sys.argv[1]), int(sys.argv[2]))\n#create all image squares and generate pool\nphmos.rainbow_of_squares('square/')\nsquare_pool = phmos.make_pool('square/*.png')\n#Create the mosaic image and save\nmosaic = phmos.basic_mosaic(image, square_pool, mos_size)\nimsave('mosaic_op.png', mosaic)"
},
{
"code": null,
"e": 3781,
"s": 2728,
"text": "$ python3 225.Photomosaic.py 100 100\n5832it [00:02, 2506.05it/s]\nanalyzing pool: 100%|| 5832/5832 [00:08<00:00, 717.90it/s]\n/usr/local/lib/python3.6/dist-packages/skimage/transform/_warps.py:105: UserWarning: The default mode, 'constant', will be changed to 'reflect' in skimage 0.15.\nwarn(\"The default mode, 'constant', will be changed to 'reflect' in \"\n/usr/local/lib/python3.6/dist-packages/skimage/transform/_warps.py:110: UserWarning: Anti-aliasing will be enabled by default in skimage 0.15 to avoid aliasing artifacts when down-sampling images.\nwarn(\"Anti-aliasing will be enabled by default in skimage 0.15 to \"\npartitioning: depth 0: 100%|| 10000/10000 [00:00<00:00, 852292.94it/s]\nanalyzing tiles: 100%|| 10000/10000 [00:00<00:00, 93084.50it/s]\nmatching: 100%|| 10000/10000 [00:00<00:00, 30864.50it/s]\ndrawing mosaic: 100%|| 10000/10000 [00:00<00:00, 13227.12it/s]\n/usr/local/lib/python3.6/dist-packages/skimage/util/dtype.py:141: UserWarning: Possible precision loss when converting from float64 to uint8\n.format(dtypeobj_in, dtypeobj_out))\n"
},
{
"code": null,
"e": 4844,
"s": 3781,
"text": "$ python3 225.Photomosaic.py 500 500\n5832it [00:02, 2634.16it/s]\nanalyzing pool: 100%|| 5832/5832 [00:08<00:00, 709.54it/s]\n/usr/local/lib/python3.6/dist-packages/skimage/transform/_warps.py:105: UserWarning: The default mode, 'constant', will be changed to 'reflect' in skimage 0.15.\nwarn(\"The default mode, 'constant', will be changed to 'reflect' in \"\n/usr/local/lib/python3.6/dist-packages/skimage/transform/_warps.py:110: UserWarning: Anti-aliasing will be enabled by default in skimage 0.15 to avoid aliasing artifacts when down-sampling images.\nwarn(\"Anti-aliasing will be enabled by default in skimage 0.15 to \"\npartitioning: depth 0: 100%|| 250000/250000 [00:00<00:00, 456159.45it/s]\nanalyzing tiles: 100%|| 250000/250000 [00:02<00:00, 113937.01it/s]\nmatching: 100%|| 250000/250000 [00:07<00:00, 32591.43it/s]\ndrawing mosaic: 100%|| 250000/250000 [00:02<00:00, 104349.90it/s]\n/usr/local/lib/python3.6/dist-packages/skimage/util/dtype.py:141: UserWarning: Possible precision loss when converting from float64 to uint8\n.format(dtypeobj_in, dtypeobj_out))\n"
}
] |
How to create a module in Java 9? | The module is a package of code and data. The module's code has organized into multiple packages and each package contains java classes and interfaces. The module's data includes resource files and other static information. An important feature of the module is that it contains "module-info.class" file that describes the module in the root directory of its artifacts. The artifact format can be a traditional JAR file or a JMOD file. This file is compiled from the source code file module-info.java in the root directory.
We can declare a module in module-info.java file with the new keyword module, the basic module declaration for a module com.company.mymodule is given below.
module com.tutorialspoint.mymodule {
}
Create a folder C:\JAVA\src and then create a folder com.tutorialspoint.greetings with the same name as the module.
Create a module-info.java file in the C:\JAVA\src\com.tutorialspoint.greetings directory with the following code.
module com.tutorialspoint.greetings {
}
Add a source code file to the module, and create a file JavaTest.java in the directory C:\JAVA\src\com.tutorialspoint.greetings\com\tutorialspoint\greetings, the code is as follows:
package com.tutorialspoint.greetings;
public class JavaTest {
public static void main(String args[]) {
System.out.println("Hello Tutorialspoint!");
}
}
Create a folder C:\JAVA\mods, and then create a com.tutorialspoint.greetings folder in this directory, and compile the module to this directory.
C:\JAVA>javac -d mods/com.tutorialspoint.greetings src/com.tutorialspoint.greetings/module-info.java
C:\JAVA>javac -d mods/com.tutorialspoint.greetings src/com.tutorialspoint.greetings/com/tutorialspoint/greetings/JavaTest.java
Execute the module and see the output
C:\JAVA>java --module-path mods -m com.tutorialspoint.greetings/com.tutorialspoint.greetings.JavaTest
Hello Tutorialspoint!
In the above, module-path specifies the path where the module is located and -m specifies the main module. | [
{
"code": null,
"e": 1586,
"s": 1062,
"text": "The module is a package of code and data. The module's code has organized into multiple packages and each package contains java classes and interfaces. The module's data includes resource files and other static information. An important feature of the module is that it contains \"module-info.class\" file that describes the module in the root directory of its artifacts. The artifact format can be a traditional JAR file or a JMOD file. This file is compiled from the source code file module-info.java in the root directory."
},
{
"code": null,
"e": 1743,
"s": 1586,
"text": "We can declare a module in module-info.java file with the new keyword module, the basic module declaration for a module com.company.mymodule is given below."
},
{
"code": null,
"e": 1782,
"s": 1743,
"text": "module com.tutorialspoint.mymodule {\n}"
},
{
"code": null,
"e": 1898,
"s": 1782,
"text": "Create a folder C:\\JAVA\\src and then create a folder com.tutorialspoint.greetings with the same name as the module."
},
{
"code": null,
"e": 2012,
"s": 1898,
"text": "Create a module-info.java file in the C:\\JAVA\\src\\com.tutorialspoint.greetings directory with the following code."
},
{
"code": null,
"e": 2052,
"s": 2012,
"text": "module com.tutorialspoint.greetings {\n}"
},
{
"code": null,
"e": 2234,
"s": 2052,
"text": "Add a source code file to the module, and create a file JavaTest.java in the directory C:\\JAVA\\src\\com.tutorialspoint.greetings\\com\\tutorialspoint\\greetings, the code is as follows:"
},
{
"code": null,
"e": 2399,
"s": 2234,
"text": "package com.tutorialspoint.greetings;\n\npublic class JavaTest {\n public static void main(String args[]) {\n System.out.println(\"Hello Tutorialspoint!\");\n }\n}"
},
{
"code": null,
"e": 2544,
"s": 2399,
"text": "Create a folder C:\\JAVA\\mods, and then create a com.tutorialspoint.greetings folder in this directory, and compile the module to this directory."
},
{
"code": null,
"e": 2772,
"s": 2544,
"text": "C:\\JAVA>javac -d mods/com.tutorialspoint.greetings src/com.tutorialspoint.greetings/module-info.java\nC:\\JAVA>javac -d mods/com.tutorialspoint.greetings src/com.tutorialspoint.greetings/com/tutorialspoint/greetings/JavaTest.java"
},
{
"code": null,
"e": 2810,
"s": 2772,
"text": "Execute the module and see the output"
},
{
"code": null,
"e": 2934,
"s": 2810,
"text": "C:\\JAVA>java --module-path mods -m com.tutorialspoint.greetings/com.tutorialspoint.greetings.JavaTest\nHello Tutorialspoint!"
},
{
"code": null,
"e": 3041,
"s": 2934,
"text": "In the above, module-path specifies the path where the module is located and -m specifies the main module."
}
] |
static Keyword in Java | Static Variables
The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of the static variable exists regardless of the number of instances of the class.
Static variables are also known as class variables. Local variables cannot be declared static.
Static Methods
The static keyword is used to create methods that will exist independently of any instances created for the class.
Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.
Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.
The static modifier is used to create class methods and variables, as in the following example −
Live Demo
public class InstanceCounter {
private static int numInstances = 0;
protected static int getCount() {
return numInstances;
}
private static void addInstance() {
numInstances++;
}
InstanceCounter() {
InstanceCounter.addInstance();
}
public static void main(String[] arguments) {
System.out.println("Starting with " + InstanceCounter.getCount() + " instances");
for (int i = 0; i < 500; ++i) {
new InstanceCounter();
}
System.out.println("Created " + InstanceCounter.getCount() + " instances");
}
}
This will produce the following result −
Started with 0 instances
Created 500 instances | [
{
"code": null,
"e": 1079,
"s": 1062,
"text": "Static Variables"
},
{
"code": null,
"e": 1292,
"s": 1079,
"text": "The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of the static variable exists regardless of the number of instances of the class."
},
{
"code": null,
"e": 1387,
"s": 1292,
"text": "Static variables are also known as class variables. Local variables cannot be declared static."
},
{
"code": null,
"e": 1402,
"s": 1387,
"text": "Static Methods"
},
{
"code": null,
"e": 1517,
"s": 1402,
"text": "The static keyword is used to create methods that will exist independently of any instances created for the class."
},
{
"code": null,
"e": 1740,
"s": 1517,
"text": "Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables."
},
{
"code": null,
"e": 1863,
"s": 1740,
"text": "Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method."
},
{
"code": null,
"e": 1960,
"s": 1863,
"text": "The static modifier is used to create class methods and variables, as in the following example −"
},
{
"code": null,
"e": 1971,
"s": 1960,
"text": " Live Demo"
},
{
"code": null,
"e": 2552,
"s": 1971,
"text": "public class InstanceCounter {\n\n private static int numInstances = 0;\n\n protected static int getCount() {\n return numInstances;\n }\n\n private static void addInstance() {\n numInstances++;\n }\n\n InstanceCounter() {\n InstanceCounter.addInstance();\n }\n\n public static void main(String[] arguments) {\n System.out.println(\"Starting with \" + InstanceCounter.getCount() + \" instances\");\n\n for (int i = 0; i < 500; ++i) {\n new InstanceCounter();\n }\n System.out.println(\"Created \" + InstanceCounter.getCount() + \" instances\");\n }\n}"
},
{
"code": null,
"e": 2593,
"s": 2552,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 2640,
"s": 2593,
"text": "Started with 0 instances\nCreated 500 instances"
}
] |
Adaptive Histogram Equalization in Image Processing Using MATLAB - GeeksforGeeks | 22 Nov, 2021
Histogram Equalization is a mathematical technique to widen the dynamic range of the histogram. Sometimes the histogram is spanned over a short range, by equalization the span of the histogram is widened. In digital image processing, the contrast of an image is enhanced using this very technique.
Adaptive Histogram Equalization: Adaptive histogram equalization is a digital image processing technique used to enhance the contrast of images. It differs from normal histogram equalization in the respect that the adaptive method enhances the contrast locally. It divides the image into distinct blocks and computes histogram equalization for each section. Thus, AHE computes many histograms, each corresponding to a distinct section of the image. It enhances the local contrast and definitions of edges in all distinct regions of the image.
Advantages:
It computes the HE of distinct sections of the image.
It preserves the edges in distinct regions of the image.
It enhances the contrast locally.
Disadvantage:
AHE overamplifies the noise in relatively homogeneous regions of an image. To prevent this a variant of adaptive histogram equalization called contrast limited adaptive histogram equalization (CLAHE) is used.
Function Used:
imread( ) is in-built function used to read the image.
size( ) is in-built function used to get the size of image.
rgb2gray( ) is in-built function used to convert RGB image into grayscale image.
zeros(row, col) is in-built function used to create row*col matrix of zeros.
unit8( ) is in-built function used to convert double value into integer format.
blockproc( ) is in-built function used to apply HE function to distinct sections of the image.
length( ) is in-built function used to find the size of list.
imtool( ) is in-built function used to display image.
pause( ) is in-built function used to pause the system to execute next statements.
Matlab
% MATLAB code for Histogram equalisation% function to return resultant% image: Apply on single channel only.function res_img=myhistEq(img)Freq=zeros(1,256);[x,y,z]=size(img); % Convert into grayscale if % image is coloured.if(z==3) img=rgb2gray(img);end % Calculate frequency of each% intensity value.for i=1:x for j=1:y Freq(img(i,j)+1)=Freq(img(i,j)+1)+1; endend % Calculate PDF for each intensity value.PDF=zeros(1,256);Total=x*y;for i=1:256 PDF(i)=Freq(i)/Total;end % Calculate the CDF for each intensity value.CDF=zeros(1,256);CDF(1)=PDF(1);for i=2:256 CDF(i)=CDF(i-1)+PDF(i);end % Multiply by Maximum intensity value% and round off the result.Result=zeros(1,256);for i=1:256 Result(i)=uint8(CDF(i)*(255));end % Compute the new image.new_img=zeros(size(img));for i=1:x for j=1:y new_img(i,j)=Result(img(i,j)+1); endendres_img=new_img;end %%%%% UTILITY CODE %%%%%%%%fun=@(block_struct)myhisteq(block_struct.data); %blockproc() is block processing function.%it applies normal HE on distinct block of%defines sizes [m n] list=["hat_lady.jfif"];for i=1:length(list) img=imread(list(i)); AHEq=blockproc(img,[100 100], fun); %AHEq=blockproc(img,[200 200], fun); %AHEq=blockproc(img,[250 200], fun); %HEq=myhisteq(img); %imtool(HEq,[]); imtool(AHEq,[]); imtool(img,[]); pause(10); imtool close all;
Output:
AHE is better than ordinary HE when the image has extremely dark or bright spots. But AHE tends to overamplify the contrast in near-constant regions of the image since the histogram in such regions is highly concentrated. As a result, AHE may cause noise to be amplified in the near-constant region.
MATLAB image-processing
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
Boundary Extraction of image using MATLAB
Laplacian of Gaussian Filter in MATLAB
Forward and Inverse Fourier Transform of an Image in MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
MRI Image Segmentation in MATLAB
How to Remove Salt and Pepper Noise from Image Using MATLAB?
How to Normalize a Histogram in MATLAB?
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
Trigonometric Functions in MATLAB | [
{
"code": null,
"e": 24670,
"s": 24642,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 24969,
"s": 24670,
"text": "Histogram Equalization is a mathematical technique to widen the dynamic range of the histogram. Sometimes the histogram is spanned over a short range, by equalization the span of the histogram is widened. In digital image processing, the contrast of an image is enhanced using this very technique. "
},
{
"code": null,
"e": 25512,
"s": 24969,
"text": "Adaptive Histogram Equalization: Adaptive histogram equalization is a digital image processing technique used to enhance the contrast of images. It differs from normal histogram equalization in the respect that the adaptive method enhances the contrast locally. It divides the image into distinct blocks and computes histogram equalization for each section. Thus, AHE computes many histograms, each corresponding to a distinct section of the image. It enhances the local contrast and definitions of edges in all distinct regions of the image."
},
{
"code": null,
"e": 25524,
"s": 25512,
"text": "Advantages:"
},
{
"code": null,
"e": 25578,
"s": 25524,
"text": "It computes the HE of distinct sections of the image."
},
{
"code": null,
"e": 25635,
"s": 25578,
"text": "It preserves the edges in distinct regions of the image."
},
{
"code": null,
"e": 25669,
"s": 25635,
"text": "It enhances the contrast locally."
},
{
"code": null,
"e": 25684,
"s": 25669,
"text": "Disadvantage: "
},
{
"code": null,
"e": 25893,
"s": 25684,
"text": "AHE overamplifies the noise in relatively homogeneous regions of an image. To prevent this a variant of adaptive histogram equalization called contrast limited adaptive histogram equalization (CLAHE) is used."
},
{
"code": null,
"e": 25908,
"s": 25893,
"text": "Function Used:"
},
{
"code": null,
"e": 25963,
"s": 25908,
"text": "imread( ) is in-built function used to read the image."
},
{
"code": null,
"e": 26023,
"s": 25963,
"text": "size( ) is in-built function used to get the size of image."
},
{
"code": null,
"e": 26104,
"s": 26023,
"text": "rgb2gray( ) is in-built function used to convert RGB image into grayscale image."
},
{
"code": null,
"e": 26181,
"s": 26104,
"text": "zeros(row, col) is in-built function used to create row*col matrix of zeros."
},
{
"code": null,
"e": 26261,
"s": 26181,
"text": "unit8( ) is in-built function used to convert double value into integer format."
},
{
"code": null,
"e": 26356,
"s": 26261,
"text": "blockproc( ) is in-built function used to apply HE function to distinct sections of the image."
},
{
"code": null,
"e": 26418,
"s": 26356,
"text": "length( ) is in-built function used to find the size of list."
},
{
"code": null,
"e": 26472,
"s": 26418,
"text": "imtool( ) is in-built function used to display image."
},
{
"code": null,
"e": 26555,
"s": 26472,
"text": "pause( ) is in-built function used to pause the system to execute next statements."
},
{
"code": null,
"e": 26562,
"s": 26555,
"text": "Matlab"
},
{
"code": "% MATLAB code for Histogram equalisation% function to return resultant% image: Apply on single channel only.function res_img=myhistEq(img)Freq=zeros(1,256);[x,y,z]=size(img); % Convert into grayscale if % image is coloured.if(z==3) img=rgb2gray(img);end % Calculate frequency of each% intensity value.for i=1:x for j=1:y Freq(img(i,j)+1)=Freq(img(i,j)+1)+1; endend % Calculate PDF for each intensity value.PDF=zeros(1,256);Total=x*y;for i=1:256 PDF(i)=Freq(i)/Total;end % Calculate the CDF for each intensity value.CDF=zeros(1,256);CDF(1)=PDF(1);for i=2:256 CDF(i)=CDF(i-1)+PDF(i);end % Multiply by Maximum intensity value% and round off the result.Result=zeros(1,256);for i=1:256 Result(i)=uint8(CDF(i)*(255));end % Compute the new image.new_img=zeros(size(img));for i=1:x for j=1:y new_img(i,j)=Result(img(i,j)+1); endendres_img=new_img;end %%%%% UTILITY CODE %%%%%%%%fun=@(block_struct)myhisteq(block_struct.data); %blockproc() is block processing function.%it applies normal HE on distinct block of%defines sizes [m n] list=[\"hat_lady.jfif\"];for i=1:length(list) img=imread(list(i)); AHEq=blockproc(img,[100 100], fun); %AHEq=blockproc(img,[200 200], fun); %AHEq=blockproc(img,[250 200], fun); %HEq=myhisteq(img); %imtool(HEq,[]); imtool(AHEq,[]); imtool(img,[]); pause(10); imtool close all;",
"e": 27936,
"s": 26562,
"text": null
},
{
"code": null,
"e": 27944,
"s": 27936,
"text": "Output:"
},
{
"code": null,
"e": 28246,
"s": 27946,
"text": "AHE is better than ordinary HE when the image has extremely dark or bright spots. But AHE tends to overamplify the contrast in near-constant regions of the image since the histogram in such regions is highly concentrated. As a result, AHE may cause noise to be amplified in the near-constant region."
},
{
"code": null,
"e": 28272,
"s": 28248,
"text": "MATLAB image-processing"
},
{
"code": null,
"e": 28279,
"s": 28272,
"text": "MATLAB"
},
{
"code": null,
"e": 28377,
"s": 28279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28450,
"s": 28377,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 28492,
"s": 28450,
"text": "Boundary Extraction of image using MATLAB"
},
{
"code": null,
"e": 28531,
"s": 28492,
"text": "Laplacian of Gaussian Filter in MATLAB"
},
{
"code": null,
"e": 28591,
"s": 28531,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 28656,
"s": 28591,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 28689,
"s": 28656,
"text": "MRI Image Segmentation in MATLAB"
},
{
"code": null,
"e": 28750,
"s": 28689,
"text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?"
},
{
"code": null,
"e": 28790,
"s": 28750,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 28869,
"s": 28790,
"text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?"
}
] |
Design Turing Machine to reverse string consisting of a’s and b’s | Our aim is to design a Turing machine (TM) to reverse a string consisting of a’s and b’s over an alphabet {a,b}.
Input − aabbab
Output − babbaa
Step 1: Move to the last symbol, replace x for a or x for b and move right to convert the corresponding B to „a‟ or „b‟ accordingly.
Step 2: Move left until the symbol left to x is reached.
Step 3: Perform step 1 and step 2 until „B‟ is reached while traversing left.
Step 4: Replace every x to B to make the cells empty since the reverse of the string is performed by the previous steps.
The transition diagram for Turing Machine (TM) is as follows −
Let us consider an example to check whether the given input is getting reverse or not −
Input string - abb.
Expected output - {bba}
Therefore, the TM is as follows − | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "Our aim is to design a Turing machine (TM) to reverse a string consisting of a’s and b’s over an alphabet {a,b}."
},
{
"code": null,
"e": 1190,
"s": 1175,
"text": "Input − aabbab"
},
{
"code": null,
"e": 1206,
"s": 1190,
"text": "Output − babbaa"
},
{
"code": null,
"e": 1616,
"s": 1206,
"text": "Step 1: Move to the last symbol, replace x for a or x for b and move right to convert the corresponding B to „a‟ or „b‟ accordingly.\nStep 2: Move left until the symbol left to x is reached.\nStep 3: Perform step 1 and step 2 until „B‟ is reached while traversing left.\nStep 4: Replace every x to B to make the cells empty since the reverse of the string is performed by the previous steps."
},
{
"code": null,
"e": 1679,
"s": 1616,
"text": "The transition diagram for Turing Machine (TM) is as follows −"
},
{
"code": null,
"e": 1767,
"s": 1679,
"text": "Let us consider an example to check whether the given input is getting reverse or not −"
},
{
"code": null,
"e": 1787,
"s": 1767,
"text": "Input string - abb."
},
{
"code": null,
"e": 1811,
"s": 1787,
"text": "Expected output - {bba}"
},
{
"code": null,
"e": 1845,
"s": 1811,
"text": "Therefore, the TM is as follows −"
}
] |
Datasets in Python. 5 packages that provide easy access to... | by Zolzaya Luvsandorj | Towards Data Science | There are useful Python packages that allow loading publicly available datasets with just a few lines of code. In this post, we will look at 5 packages that give instant access to a range of datasets. For each package, we will look at how to check out its list of available datasets and how to load an example dataset to a pandas dataframe.
I assume the reader (👀 yes, you!) has access to and is familiar with Python including installing packages, defining functions and other basic tasks. If you are new to Python, this is a good place to get started.
I have used and tested the scripts in Python 3.7.1 in Jupyter Notebook. Let’s make sure you have the relevant packages installed before we dive in:
◼️ ️pydataset: Dataset package,◼️ ️seaborn: Data Visualisation package,◼️ ️sklearn: Machine Learning package,◼️ ️statsmodel: Statistical Model package and◼️ ️nltk: Natural Language Tool Kit package
For each package, we will inspect the shape, head and tail of an example dataset. To avoid repeating ourselves, let’s quickly make a function:
# Create a function to glimpse the datadef glimpse(df): print(f"{df.shape[0]} rows and {df.shape[1]} columns") display(df.head()) display(df.tail())
Alright, we are ready to dive in! 🐳
The first package we are going look at is PyDataset. It’s easy to use and gives access to over 700 datasets. The package was inspired by ease of accessing datasets in R and aimed to bring that ease in Python. Let’s check out the list of datasets:
# Import packagefrom pydataset import data# Check out datasetsdata()
This returns a dataframe containing dataset_id and title for all datasets which you can browse through. Currently, there are 757 datasets. Now, let’s load the famous iris dataset as an example:
# Load as a dataframedf = data('iris')glimpse(df)
Loading a dataset to a dataframe takes only one line once we import the package. So simple, right? Something to note is that row index starts from 1 as opposed to 0 in this dataset.
🔗 To learn more, check out PyDataset’s GitHub repository.
Seaborn is another package that provides easy access to example datasets. To find the full list of datasets, you can browse the GitHub repository or you can check it in Python like this:
# Import seabornimport seaborn as sns# Check out available datasetsprint(sns.get_dataset_names())
Currently, there are 17 datasets available. Let’s load iris dataset as an example:
# Load as a dataframedf = sns.load_dataset('iris')glimpse(df)
It also takes only one line to load a dataset as a dataframe after importing the package.
🔗 To learn more, check out documentation page for load_dataset.
Not only is scikit-learn awesome for feature engineering and building models, it also comes with toy datasets and provides easy access to download and load real world datasets. The list of toy and real datasets as well as other details are available here. You can find out more details about a dataset by scrolling through the link or referring to the individual documentation for functions. It’s worth mentioning that among the datasets, there are some toy and real image datasets such as digits dataset and Olivetti faces dataset.
Now, let’s look at how to load real dataset with an example:
# Import packagefrom sklearn.datasets import fetch_california_housing# Load data (will download the data if it's the first time loading)housing = fetch_california_housing(as_frame=True)# Create a dataframedf = housing['data'].join(housing['target'])glimpse(df)
Here’s how to load an example toy dataset, iris:
# Import packagefrom sklearn.datasets import load_iris# Load datairis = load_iris(as_frame=True)# Create a dataframedf = iris['data'].join(iris['target'])# Map target names (only for categorical target)df['target'].replace(dict(enumerate(iris['target_names'])), inplace=True)glimpse(df)
💡 If you get an error regarding the as_frame argument, either update your sklearn version to 0.23 or higher or use the script below:
# Import packagesimport pandas as pdfrom sklearn.datasets import load_iris# Load datairis = load_iris()# Create a dataframeX = pd.DataFrame(iris['data'], columns=iris['feature_names'])y = pd.DataFrame(iris['target'], columns=['target'])df = X.join(y)# Map target names (only for categorical target)df['target'].replace(dict(enumerate(iris['target_names'])), inplace=True)glimpse(df)
🔗 For more information, check out scikit-learn’s documentation page.
Another package through which we can access data is statsmodels. Available built-in datasets are listed here on their website. Let’s pick ‘United States Macroeconomic data’ as an example and load it:
# Import packageimport statsmodels.api as sm# Load data as a dataframedf = sm.datasets.macrodata.load_pandas()['data']glimpse(df)
As you may have noticed, the name we used to access ‘United States Macroeconomic data’ is macrodata. To find the equivalent name for other datasets, have a look at the end of the URL for that dataset documentation. For instance, if you click on ‘United States Macroeconomic data’ in Available Dataset section and look at the address bar in your browser, you will see ‘macrodata.html’ at the end of URL.
Statsmodels also allows loading datasets from R with the get_rdataset function. The list of available datasets are here. Using iris dataset as an example, here is how we can load the data:
# Load data as a dataframedf = sm.datasets.get_rdataset(dataname='iris', package='datasets')['data']glimpse(df)
🔗 For more information, check out documentation page for datasets.
This package is slightly different from the rest because it provides access only to text datasets. Here’s the list of text datasets available (Psst, please note some items in that list are models). Using the id, we can access the relevant text dataset from NLTK. Let’s take Sentiment Polarity Dataset as an example. Its id is movie_reviews. Let’s first download it with the following script:
# Import packageimport nltk# Download the corpus (only need to do once)nltk.download('movie_reviews')
If it is already downloaded, running this will notify that you have done so. Once downloaded, we can load the data to a dataframe like this:
# Import packagesimport pandas as pdfrom nltk.corpus import movie_reviews# Convert to dataframedocuments = []for fileid in movie_reviews.fileids(): tag, filename = fileid.split('/') documents.append((tag, movie_reviews.raw(fileid)))df = pd.DataFrame(documents, columns=['target', 'document'])glimpse(df)
There is no one size fits all approach when converting text data from NLTK to a dataframe. This means you will need to look up the appropriate way to convert to a dataframe on a case-by-case basis.
🔗 For more information, check out this resource on accessing text corpora and lexical resources.
There you have it, 5 packages that allow easy access to datasets. Now you know how to load datasets from any of these packages. It’s possible that datasets available in these packages could change in future but you know how to find all the available datasets, anyway! 🙆
Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me.
Thank you for reading my post. Hope you found something useful ✂️. If you are interested, here are the links to some of my other posts:◼️️ 5 tips for pandas users◼️️️️ How to transform variables in a pandas DataFrame◼️ TF-IDF explained◼️ Supervised text classification model in Python
Bye for now 🏃💨 | [
{
"code": null,
"e": 513,
"s": 172,
"text": "There are useful Python packages that allow loading publicly available datasets with just a few lines of code. In this post, we will look at 5 packages that give instant access to a range of datasets. For each package, we will look at how to check out its list of available datasets and how to load an example dataset to a pandas dataframe."
},
{
"code": null,
"e": 725,
"s": 513,
"text": "I assume the reader (👀 yes, you!) has access to and is familiar with Python including installing packages, defining functions and other basic tasks. If you are new to Python, this is a good place to get started."
},
{
"code": null,
"e": 873,
"s": 725,
"text": "I have used and tested the scripts in Python 3.7.1 in Jupyter Notebook. Let’s make sure you have the relevant packages installed before we dive in:"
},
{
"code": null,
"e": 1071,
"s": 873,
"text": "◼️ ️pydataset: Dataset package,◼️ ️seaborn: Data Visualisation package,◼️ ️sklearn: Machine Learning package,◼️ ️statsmodel: Statistical Model package and◼️ ️nltk: Natural Language Tool Kit package"
},
{
"code": null,
"e": 1214,
"s": 1071,
"text": "For each package, we will inspect the shape, head and tail of an example dataset. To avoid repeating ourselves, let’s quickly make a function:"
},
{
"code": null,
"e": 1372,
"s": 1214,
"text": "# Create a function to glimpse the datadef glimpse(df): print(f\"{df.shape[0]} rows and {df.shape[1]} columns\") display(df.head()) display(df.tail())"
},
{
"code": null,
"e": 1408,
"s": 1372,
"text": "Alright, we are ready to dive in! 🐳"
},
{
"code": null,
"e": 1655,
"s": 1408,
"text": "The first package we are going look at is PyDataset. It’s easy to use and gives access to over 700 datasets. The package was inspired by ease of accessing datasets in R and aimed to bring that ease in Python. Let’s check out the list of datasets:"
},
{
"code": null,
"e": 1724,
"s": 1655,
"text": "# Import packagefrom pydataset import data# Check out datasetsdata()"
},
{
"code": null,
"e": 1918,
"s": 1724,
"text": "This returns a dataframe containing dataset_id and title for all datasets which you can browse through. Currently, there are 757 datasets. Now, let’s load the famous iris dataset as an example:"
},
{
"code": null,
"e": 1968,
"s": 1918,
"text": "# Load as a dataframedf = data('iris')glimpse(df)"
},
{
"code": null,
"e": 2150,
"s": 1968,
"text": "Loading a dataset to a dataframe takes only one line once we import the package. So simple, right? Something to note is that row index starts from 1 as opposed to 0 in this dataset."
},
{
"code": null,
"e": 2208,
"s": 2150,
"text": "🔗 To learn more, check out PyDataset’s GitHub repository."
},
{
"code": null,
"e": 2395,
"s": 2208,
"text": "Seaborn is another package that provides easy access to example datasets. To find the full list of datasets, you can browse the GitHub repository or you can check it in Python like this:"
},
{
"code": null,
"e": 2493,
"s": 2395,
"text": "# Import seabornimport seaborn as sns# Check out available datasetsprint(sns.get_dataset_names())"
},
{
"code": null,
"e": 2576,
"s": 2493,
"text": "Currently, there are 17 datasets available. Let’s load iris dataset as an example:"
},
{
"code": null,
"e": 2638,
"s": 2576,
"text": "# Load as a dataframedf = sns.load_dataset('iris')glimpse(df)"
},
{
"code": null,
"e": 2728,
"s": 2638,
"text": "It also takes only one line to load a dataset as a dataframe after importing the package."
},
{
"code": null,
"e": 2792,
"s": 2728,
"text": "🔗 To learn more, check out documentation page for load_dataset."
},
{
"code": null,
"e": 3325,
"s": 2792,
"text": "Not only is scikit-learn awesome for feature engineering and building models, it also comes with toy datasets and provides easy access to download and load real world datasets. The list of toy and real datasets as well as other details are available here. You can find out more details about a dataset by scrolling through the link or referring to the individual documentation for functions. It’s worth mentioning that among the datasets, there are some toy and real image datasets such as digits dataset and Olivetti faces dataset."
},
{
"code": null,
"e": 3386,
"s": 3325,
"text": "Now, let’s look at how to load real dataset with an example:"
},
{
"code": null,
"e": 3647,
"s": 3386,
"text": "# Import packagefrom sklearn.datasets import fetch_california_housing# Load data (will download the data if it's the first time loading)housing = fetch_california_housing(as_frame=True)# Create a dataframedf = housing['data'].join(housing['target'])glimpse(df)"
},
{
"code": null,
"e": 3696,
"s": 3647,
"text": "Here’s how to load an example toy dataset, iris:"
},
{
"code": null,
"e": 4004,
"s": 3696,
"text": "# Import packagefrom sklearn.datasets import load_iris# Load datairis = load_iris(as_frame=True)# Create a dataframedf = iris['data'].join(iris['target'])# Map target names (only for categorical target)df['target'].replace(dict(enumerate(iris['target_names'])), inplace=True)glimpse(df)"
},
{
"code": null,
"e": 4137,
"s": 4004,
"text": "💡 If you get an error regarding the as_frame argument, either update your sklearn version to 0.23 or higher or use the script below:"
},
{
"code": null,
"e": 4541,
"s": 4137,
"text": "# Import packagesimport pandas as pdfrom sklearn.datasets import load_iris# Load datairis = load_iris()# Create a dataframeX = pd.DataFrame(iris['data'], columns=iris['feature_names'])y = pd.DataFrame(iris['target'], columns=['target'])df = X.join(y)# Map target names (only for categorical target)df['target'].replace(dict(enumerate(iris['target_names'])), inplace=True)glimpse(df)"
},
{
"code": null,
"e": 4610,
"s": 4541,
"text": "🔗 For more information, check out scikit-learn’s documentation page."
},
{
"code": null,
"e": 4810,
"s": 4610,
"text": "Another package through which we can access data is statsmodels. Available built-in datasets are listed here on their website. Let’s pick ‘United States Macroeconomic data’ as an example and load it:"
},
{
"code": null,
"e": 4940,
"s": 4810,
"text": "# Import packageimport statsmodels.api as sm# Load data as a dataframedf = sm.datasets.macrodata.load_pandas()['data']glimpse(df)"
},
{
"code": null,
"e": 5343,
"s": 4940,
"text": "As you may have noticed, the name we used to access ‘United States Macroeconomic data’ is macrodata. To find the equivalent name for other datasets, have a look at the end of the URL for that dataset documentation. For instance, if you click on ‘United States Macroeconomic data’ in Available Dataset section and look at the address bar in your browser, you will see ‘macrodata.html’ at the end of URL."
},
{
"code": null,
"e": 5532,
"s": 5343,
"text": "Statsmodels also allows loading datasets from R with the get_rdataset function. The list of available datasets are here. Using iris dataset as an example, here is how we can load the data:"
},
{
"code": null,
"e": 5644,
"s": 5532,
"text": "# Load data as a dataframedf = sm.datasets.get_rdataset(dataname='iris', package='datasets')['data']glimpse(df)"
},
{
"code": null,
"e": 5711,
"s": 5644,
"text": "🔗 For more information, check out documentation page for datasets."
},
{
"code": null,
"e": 6103,
"s": 5711,
"text": "This package is slightly different from the rest because it provides access only to text datasets. Here’s the list of text datasets available (Psst, please note some items in that list are models). Using the id, we can access the relevant text dataset from NLTK. Let’s take Sentiment Polarity Dataset as an example. Its id is movie_reviews. Let’s first download it with the following script:"
},
{
"code": null,
"e": 6205,
"s": 6103,
"text": "# Import packageimport nltk# Download the corpus (only need to do once)nltk.download('movie_reviews')"
},
{
"code": null,
"e": 6346,
"s": 6205,
"text": "If it is already downloaded, running this will notify that you have done so. Once downloaded, we can load the data to a dataframe like this:"
},
{
"code": null,
"e": 6656,
"s": 6346,
"text": "# Import packagesimport pandas as pdfrom nltk.corpus import movie_reviews# Convert to dataframedocuments = []for fileid in movie_reviews.fileids(): tag, filename = fileid.split('/') documents.append((tag, movie_reviews.raw(fileid)))df = pd.DataFrame(documents, columns=['target', 'document'])glimpse(df)"
},
{
"code": null,
"e": 6854,
"s": 6656,
"text": "There is no one size fits all approach when converting text data from NLTK to a dataframe. This means you will need to look up the appropriate way to convert to a dataframe on a case-by-case basis."
},
{
"code": null,
"e": 6951,
"s": 6854,
"text": "🔗 For more information, check out this resource on accessing text corpora and lexical resources."
},
{
"code": null,
"e": 7221,
"s": 6951,
"text": "There you have it, 5 packages that allow easy access to datasets. Now you know how to load datasets from any of these packages. It’s possible that datasets available in these packages could change in future but you know how to find all the available datasets, anyway! 🙆"
},
{
"code": null,
"e": 7445,
"s": 7221,
"text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me."
},
{
"code": null,
"e": 7730,
"s": 7445,
"text": "Thank you for reading my post. Hope you found something useful ✂️. If you are interested, here are the links to some of my other posts:◼️️ 5 tips for pandas users◼️️️️ How to transform variables in a pandas DataFrame◼️ TF-IDF explained◼️ Supervised text classification model in Python"
}
] |
Construct a linked list from 2D matrix - GeeksforGeeks | 07 Jun, 2021
Given a matrix. Convert it into a linked list matrix such that each node is connected to its next right and down node.Example:
Input : 2D matrix
1 2 3
4 5 6
7 8 9
Output :
1 -> 2 -> 3 -> NULL
| | |
v v v
4 -> 5 -> 6 -> NULL
| | |
v v v
7 -> 8 -> 9 -> NULL
| | |
v v v
NULL NULL NULL
Question Source: Factset Interview Experience | Set 9
The idea is to construct a new node for every element of matrix and recursively create its down and right nodes.
C++
Java
Python3
C#
Javascript
// CPP program to construct a linked list// from given 2D matrix#include <bits/stdc++.h>using namespace std; // struct node of linked liststruct Node { int data; Node* right, *down;}; // returns head pointer of linked list// constructed from 2D matrixNode* construct(int arr[][3], int i, int j, int m, int n){ // return if i or j is out of bounds if (i > n - 1 || j > m - 1) return NULL; // create a new node for current i and j // and recursively allocate its down and // right pointers Node* temp = new Node(); temp->data = arr[i][j]; temp->right = construct(arr, i, j + 1, m, n); temp->down = construct(arr, i + 1, j, m, n); return temp;} // utility function for displaying// linked list datavoid display(Node* head){ // pointer to move right Node* Rp; // pointer to move down Node* Dp = head; // loop till node->down is not NULL while (Dp) { Rp = Dp; // loop till node->right is not NULL while (Rp) { cout << Rp->data << " "; Rp = Rp->right; } cout << "\n"; Dp = Dp->down; }} // driver programint main(){ // 2D matrix int arr[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int m = 3, n = 3; Node* head = construct(arr, 0, 0, m, n); display(head); return 0;}
// Java program to construct a linked list// from given 2D matrixpublic class Linked_list_2D_Matrix { // node of linked list static class Node { int data; Node right; Node down; }; // returns head pointer of linked list // constructed from 2D matrix static Node construct(int arr[][], int i, int j, int m, int n) { // return if i or j is out of bounds if (i > n - 1 || j > m - 1) return null; // create a new node for current i and j // and recursively allocate its down and // right pointers Node temp = new Node(); temp.data = arr[i][j]; temp.right = construct(arr, i, j + 1, m, n); temp.down = construct(arr, i + 1, j, m, n); return temp; } // utility function for displaying // linked list data static void display(Node head) { // pointer to move right Node Rp; // pointer to move down Node Dp = head; // loop till node->down is not NULL while (Dp != null) { Rp = Dp; // loop till node->right is not NULL while (Rp != null) { System.out.print(Rp.data + " "); Rp = Rp.right; } System.out.println(); Dp = Dp.down; } } // driver program public static void main(String args[]) { // 2D matrix int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int m = 3, n = 3; Node head = construct(arr, 0, 0, m, n); display(head); } }// This code is contributed by Sumit Ghosh
# Python3 program to construct a linked list# from given 2D matriximport math # struct node of linked listclass Node: def __init__(self, data): self.data = data self.right = None self.down = None # returns head pointer of linked list# constructed from 2D matrixdef construct(arr, i, j, m, n): # return if i or j is out of bounds if (i > n - 1 or j > m - 1): return None # create a new node for current i and j # and recursively allocate its down and # right pointers temp = Node(arr[i][j]) temp.data = arr[i][j] temp.right = construct(arr, i, j + 1, m, n) temp.down = construct(arr, i + 1, j, m, n) return temp # utility function for displaying# linked list datadef display(head): # pointer to move right # Rp # pointer to move down Dp = head # loop till node.down is not None while (Dp): Rp = Dp # loop till node.right is not None while (Rp): print(Rp.data, end = " ") Rp = Rp.right print() Dp = Dp.down # Driver Codeif __name__=='__main__': # 2D matrix arr = [[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]] m, n = 3, 3 head = construct(arr, 0, 0, m, n) display(head) # This code is contributed by AbhiThakur
// C# program to construct a linked list// from given 2D matrixusing System; public class Linked_list_2D_Matrix{ // node of linked list public class Node { public int data; public Node right; public Node down; }; // returns head pointer of linked list // constructed from 2D matrix static Node construct(int [,]arr, int i, int j, int m, int n) { // return if i or j is out of bounds if (i > n - 1 || j > m - 1) return null; // create a new node for current i and j // and recursively allocate its down and // right pointers Node temp = new Node(); temp.data = arr[i, j]; temp.right = construct(arr, i, j + 1, m, n); temp.down = construct(arr, i + 1, j, m, n); return temp; } // utility function for displaying // linked list data static void display(Node head) { // pointer to move right Node Rp; // pointer to move down Node Dp = head; // loop till node->down is not NULL while (Dp != null) { Rp = Dp; // loop till node->right is not NULL while (Rp != null) { Console.Write(Rp.data + " "); Rp = Rp.right; } Console.WriteLine(); Dp = Dp.down; } } // Driver program public static void Main() { // 2D matrix int [,]arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int m = 3, n = 3; Node head = construct(arr, 0, 0, m, n); display(head); }} /* This code contributed by PrinciRaj1992 */
<script> // JavaScript program to construct a linked list// from given 2D matrix // node of linked list class Node { constructor(val) { this.data = val; this.down = null; this.right = null; } } // returns head pointer of linked list // constructed from 2D matrix function construct(arr , i , j , m , n) { // return if i or j is out of bounds if (i > n - 1 || j > m - 1) return null; // create a new node for current i and j // and recursively allocate its down and // right pointers var temp = new Node(); temp.data = arr[i][j]; temp.right = construct(arr, i, j + 1, m, n); temp.down = construct(arr, i + 1, j, m, n); return temp; } // utility function for displaying // linked list data function display(head) { // pointer to move right var Rp; // pointer to move down var Dp = head; // loop till node->down is not NULL while (Dp != null) { Rp = Dp; // loop till node->right is not NULL while (Rp != null) { document.write(Rp.data + " "); Rp = Rp.right; } document.write("<br/>"); Dp = Dp.down; } } // driver program // 2D matrix var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; var m = 3, n = 3; var head = construct(arr, 0, 0, m, n); display(head); // This code contributed by Rajput-Ji </script>
Output:
1 2 3
4 5 6
7 8 9
This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
princiraj1992
abhaysingh290895
Rajput-Ji
FactSet
Linked List
Matrix
FactSet
Linked List
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)
LinkedList in Java
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Rat in a Maze | Backtracking-2
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) | [
{
"code": null,
"e": 31012,
"s": 30984,
"text": "\n07 Jun, 2021"
},
{
"code": null,
"e": 31141,
"s": 31012,
"text": "Given a matrix. Convert it into a linked list matrix such that each node is connected to its next right and down node.Example: "
},
{
"code": null,
"e": 31335,
"s": 31141,
"text": "Input : 2D matrix \n1 2 3\n4 5 6\n7 8 9\n\nOutput :\n1 -> 2 -> 3 -> NULL\n| | |\nv v v\n4 -> 5 -> 6 -> NULL\n| | |\nv v v\n7 -> 8 -> 9 -> NULL\n| | |\nv v v\nNULL NULL NULL"
},
{
"code": null,
"e": 31390,
"s": 31335,
"text": "Question Source: Factset Interview Experience | Set 9 "
},
{
"code": null,
"e": 31505,
"s": 31390,
"text": "The idea is to construct a new node for every element of matrix and recursively create its down and right nodes. "
},
{
"code": null,
"e": 31509,
"s": 31505,
"text": "C++"
},
{
"code": null,
"e": 31514,
"s": 31509,
"text": "Java"
},
{
"code": null,
"e": 31522,
"s": 31514,
"text": "Python3"
},
{
"code": null,
"e": 31525,
"s": 31522,
"text": "C#"
},
{
"code": null,
"e": 31536,
"s": 31525,
"text": "Javascript"
},
{
"code": "// CPP program to construct a linked list// from given 2D matrix#include <bits/stdc++.h>using namespace std; // struct node of linked liststruct Node { int data; Node* right, *down;}; // returns head pointer of linked list// constructed from 2D matrixNode* construct(int arr[][3], int i, int j, int m, int n){ // return if i or j is out of bounds if (i > n - 1 || j > m - 1) return NULL; // create a new node for current i and j // and recursively allocate its down and // right pointers Node* temp = new Node(); temp->data = arr[i][j]; temp->right = construct(arr, i, j + 1, m, n); temp->down = construct(arr, i + 1, j, m, n); return temp;} // utility function for displaying// linked list datavoid display(Node* head){ // pointer to move right Node* Rp; // pointer to move down Node* Dp = head; // loop till node->down is not NULL while (Dp) { Rp = Dp; // loop till node->right is not NULL while (Rp) { cout << Rp->data << \" \"; Rp = Rp->right; } cout << \"\\n\"; Dp = Dp->down; }} // driver programint main(){ // 2D matrix int arr[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int m = 3, n = 3; Node* head = construct(arr, 0, 0, m, n); display(head); return 0;}",
"e": 32906,
"s": 31536,
"text": null
},
{
"code": "// Java program to construct a linked list// from given 2D matrixpublic class Linked_list_2D_Matrix { // node of linked list static class Node { int data; Node right; Node down; }; // returns head pointer of linked list // constructed from 2D matrix static Node construct(int arr[][], int i, int j, int m, int n) { // return if i or j is out of bounds if (i > n - 1 || j > m - 1) return null; // create a new node for current i and j // and recursively allocate its down and // right pointers Node temp = new Node(); temp.data = arr[i][j]; temp.right = construct(arr, i, j + 1, m, n); temp.down = construct(arr, i + 1, j, m, n); return temp; } // utility function for displaying // linked list data static void display(Node head) { // pointer to move right Node Rp; // pointer to move down Node Dp = head; // loop till node->down is not NULL while (Dp != null) { Rp = Dp; // loop till node->right is not NULL while (Rp != null) { System.out.print(Rp.data + \" \"); Rp = Rp.right; } System.out.println(); Dp = Dp.down; } } // driver program public static void main(String args[]) { // 2D matrix int arr[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int m = 3, n = 3; Node head = construct(arr, 0, 0, m, n); display(head); } }// This code is contributed by Sumit Ghosh",
"e": 34606,
"s": 32906,
"text": null
},
{
"code": " # Python3 program to construct a linked list# from given 2D matriximport math # struct node of linked listclass Node: def __init__(self, data): self.data = data self.right = None self.down = None # returns head pointer of linked list# constructed from 2D matrixdef construct(arr, i, j, m, n): # return if i or j is out of bounds if (i > n - 1 or j > m - 1): return None # create a new node for current i and j # and recursively allocate its down and # right pointers temp = Node(arr[i][j]) temp.data = arr[i][j] temp.right = construct(arr, i, j + 1, m, n) temp.down = construct(arr, i + 1, j, m, n) return temp # utility function for displaying# linked list datadef display(head): # pointer to move right # Rp # pointer to move down Dp = head # loop till node.down is not None while (Dp): Rp = Dp # loop till node.right is not None while (Rp): print(Rp.data, end = \" \") Rp = Rp.right print() Dp = Dp.down # Driver Codeif __name__=='__main__': # 2D matrix arr = [[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]] m, n = 3, 3 head = construct(arr, 0, 0, m, n) display(head) # This code is contributed by AbhiThakur",
"e": 35915,
"s": 34606,
"text": null
},
{
"code": "// C# program to construct a linked list// from given 2D matrixusing System; public class Linked_list_2D_Matrix{ // node of linked list public class Node { public int data; public Node right; public Node down; }; // returns head pointer of linked list // constructed from 2D matrix static Node construct(int [,]arr, int i, int j, int m, int n) { // return if i or j is out of bounds if (i > n - 1 || j > m - 1) return null; // create a new node for current i and j // and recursively allocate its down and // right pointers Node temp = new Node(); temp.data = arr[i, j]; temp.right = construct(arr, i, j + 1, m, n); temp.down = construct(arr, i + 1, j, m, n); return temp; } // utility function for displaying // linked list data static void display(Node head) { // pointer to move right Node Rp; // pointer to move down Node Dp = head; // loop till node->down is not NULL while (Dp != null) { Rp = Dp; // loop till node->right is not NULL while (Rp != null) { Console.Write(Rp.data + \" \"); Rp = Rp.right; } Console.WriteLine(); Dp = Dp.down; } } // Driver program public static void Main() { // 2D matrix int [,]arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int m = 3, n = 3; Node head = construct(arr, 0, 0, m, n); display(head); }} /* This code contributed by PrinciRaj1992 */",
"e": 37660,
"s": 35915,
"text": null
},
{
"code": "<script> // JavaScript program to construct a linked list// from given 2D matrix // node of linked list class Node { constructor(val) { this.data = val; this.down = null; this.right = null; } } // returns head pointer of linked list // constructed from 2D matrix function construct(arr , i , j , m , n) { // return if i or j is out of bounds if (i > n - 1 || j > m - 1) return null; // create a new node for current i and j // and recursively allocate its down and // right pointers var temp = new Node(); temp.data = arr[i][j]; temp.right = construct(arr, i, j + 1, m, n); temp.down = construct(arr, i + 1, j, m, n); return temp; } // utility function for displaying // linked list data function display(head) { // pointer to move right var Rp; // pointer to move down var Dp = head; // loop till node->down is not NULL while (Dp != null) { Rp = Dp; // loop till node->right is not NULL while (Rp != null) { document.write(Rp.data + \" \"); Rp = Rp.right; } document.write(\"<br/>\"); Dp = Dp.down; } } // driver program // 2D matrix var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; var m = 3, n = 3; var head = construct(arr, 0, 0, m, n); display(head); // This code contributed by Rajput-Ji </script>",
"e": 39287,
"s": 37660,
"text": null
},
{
"code": null,
"e": 39297,
"s": 39287,
"text": "Output: "
},
{
"code": null,
"e": 39317,
"s": 39297,
"text": "1 2 3 \n4 5 6 \n7 8 9"
},
{
"code": null,
"e": 39738,
"s": 39317,
"text": "This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 39752,
"s": 39738,
"text": "princiraj1992"
},
{
"code": null,
"e": 39769,
"s": 39752,
"text": "abhaysingh290895"
},
{
"code": null,
"e": 39779,
"s": 39769,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 39787,
"s": 39779,
"text": "FactSet"
},
{
"code": null,
"e": 39799,
"s": 39787,
"text": "Linked List"
},
{
"code": null,
"e": 39806,
"s": 39799,
"text": "Matrix"
},
{
"code": null,
"e": 39814,
"s": 39806,
"text": "FactSet"
},
{
"code": null,
"e": 39826,
"s": 39814,
"text": "Linked List"
},
{
"code": null,
"e": 39833,
"s": 39826,
"text": "Matrix"
},
{
"code": null,
"e": 39931,
"s": 39833,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39966,
"s": 39931,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 40005,
"s": 39966,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 40053,
"s": 40005,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 40091,
"s": 40053,
"text": "Linked List | Set 3 (Deleting a node)"
},
{
"code": null,
"e": 40110,
"s": 40091,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 40145,
"s": 40110,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 40189,
"s": 40145,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 40225,
"s": 40189,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 40256,
"s": 40225,
"text": "Rat in a Maze | Backtracking-2"
}
] |
Get record count for all tables in MySQL database? | To get the count of all the records in MySQL tables, we can use TABLE_ROWS with aggregate function SUM. The syntax is as follows.
SELECT SUM(TABLE_ROWS)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'yourDatabaseName';
Apply the above syntax in order to get the count of records for all tables. The query is as follows −
mysql> SELECT SUM(TABLE_ROWS)
->FROM INFORMATION_SCHEMA.TABLES
->WHERE TABLE_SCHEMA = 'business';
The following table returns the count of records.
+-----------------+
| SUM(TABLE_ROWS) |
+-----------------+
| 450 |
+-----------------+
1 row in set (13.54 sec)
To display the count of all records per table, use the following query −
mysql> SELECT table_name, table_rows
->FROM INFORMATION_SCHEMA.TABLES
->WHERE TABLE_SCHEMA = 'business';
The following is the output.
+------------------------------------------------------------------+------------+
| TABLE_NAME | TABLE_ROWS |
+------------------------------------------------------------------+------------+
| add1daydemo | 2 |
| addcheckconstraintdemo | 0 |
| addcolumntable | 0 |
| addconstraintdemo | 2 |
| adding5hours | 2 |
| addingunique | 2 |
| addnotnulldemo | 2 |
| alphademo | 0 |
| autoincrement | 4 |
| autoincrementtable | 5 |
| backticksymbol | 4 |
| bitdemo | 2 |
| blobtabledemo | 0 |
| bookindexes | 4 |
| booleandemo | 0 |
| chardemo | 0 |
| checkdemo | 0 |
| checkingintegerdemo | 2 |
| childdemo | 0 |
| clonestudent | 3 |
| college | 0 |
| colortable | 0 |
| columnexistdemo | 0 |
| columnnameasnumberdemo | 2 |
| columnnamewithspace | 4 |
| columnslist | 0 |
| columnvaluenulldemo | 2 |
| commaseperatedemo | 2 |
| commentdemo | 0 |
| commentdemo2 | 0 |
| commentdemo3 | 0 |
| countrycitydemo | 2 |
| currentdatetime | 0 |
| currenttimeadding2hours | 0 |
| currenttimezone | 1 |
| dateadddemo | 0 |
| datetimedemo | 3 |
| deletedemo | 5 |
| deleterecord | 6 |
| demo | 2 |
| demo1 | 0 |
| demoascii | 2 |
| demoauto | 2 |
| demobcrypt | 0 |
| demoemptyandnull | 0 |
| demoint | 0 |
| demoonreplace | 2 |
| demoschema | 0 |
| demowhere | 2 |
| distcountdemo | 4 |
| distinctdemo | 8 |
| distinctdemo1 | 4 |
| duplicatebookindexes | 4 |
| duplicatedeletedemo | 4 |
| duplicatefound | 4 |
| employeeinformation | 2 |
| employeerecords | 0 |
| employeetable | 0 |
| enumdemo | 2 |
| enumvalues | 0 |
| escapedeom | 0 |
| existsrowdemo | 4 |
| findandreplacedemo | 4 |
| finddemo | 2 |
| firsttable | 2 |
| firsttabledemo | 3 |
| foreigntable | 2 |
| foreigntabledemo | 2 |
| functionindexdemo | 0 |
| functiontriggersdemo | 0 |
| groupconcatenatedemo | 4 |
| groupdemo | 4 |
| groupdemo1 | 4 |
| groupt_concatdemo | 4 |
| ifelsedemo | 4 |
| imagedemo | 2 |
| incasesensdemo | 4 |
| indexingdemo | 0 |
| insertingemojidemo | 1 |
| insubquerydemo | 2 |
| int1demo | 0 |
| intdemo | 2 |
| ipv4addressdemo | 0 |
| ipv6demo | 0 |
| jasonasmysqldemo | 2 |
| keydemo | 2 |
| last10recordsdemo | 12 |
| lastinsertiddemo | 3 |
| lastinsertrecordiddemo | 3 |
| latandlangdemo | 0 |
| lengthandcharlengthdemo | 1 |
| limitoffsetdemo | 11 |
| lowcardinality | 2 |
| milliseconddemo | 0 |
| modifycolumnnamedemo | 0 |
| modifydatatype | 0 |
| moneydemo | 2 |
| moviecollection | 6 |
| multipleindexdemo | 0 |
| multiplerecordwithvalues | 4 |
| myisamtabledemo | 2 |
| myisamtoinnodbdemo | 0 |
| mytable | 0 |
| mytable1 | 0 |
| mytabledemo | 2 |
| newstudent | 0 |
| nextiddemo | 2 |
| nextpreviousdemo | 9 |
| nonasciidemo | 4 |
| nthrecorddemo | 4 |
| nulldemo | 0 |
| nullwithselect | 6 |
| numbercolumndemo | 0 |
| numberofcolumns | 2 |
| ondemo | 4 |
| orderdemo | 2 |
| originaltable | 4 |
| parentdemo | 0 |
| pasthistory | 4 |
| presenthistory | 2 |
| primarytable | 2 |
| primarytable1 | 2 |
| primarytabledemo | 2 |
| proctabledemo | 3 |
| querybetweentwodates | 0 |
| querydatedemo | 0 |
| qutesdemo | 2 |
| randomoptimizationdemo | 8 |
| randoptimizedemo | 26 |
| repairtabledemo | 3 |
| rowcountdemo | 8 |
| rowintocolumn | 4 |
| rownumberdemo | 4 |
| rowstranspose | 2 |
| rowstransposedemo | 4 |
| rowvaluedemo | 8 |
| saveintotextfile | 2 |
| saveoutputintext | 0 |
| schemadatabasemethoddemo | 0 |
| secondtable | 2 |
| secondtabledemo | 2 |
| sequencedemo | 7 |
| singlequotesdemo | 2 |
| smallintdemo | 0 |
| sortingvarchardemo | 6 |
| sourcetable | 4 |
| spacecolumn | 2 |
| stringoccurrencedemo | 3 |
| stringtodatedemo | 0 |
| student | 2 |
| studentenrollment | 0 |
| studentrecordwithmyisam | 0 |
| studenttable | 4 |
| swappingtwocoulmnsvaluedemo | 5 |
| table1 | 2 |
| table2 | 3 |
| tabledemo | 0 |
| tabledemo2 | 0 |
| tabledemo3 | 0 |
| tableforeign | 0 |
| tablename1tablename1tablename1tablename1tablename1tablename1demo | 0 |
| tablepri | 0 |
| tbldemotrail | 6 |
| tblf | 0 |
| tblfirst | 2 |
| tblfunctiontrigger | 0 |
| tblifdemo | 4 |
| tblnull | 0 |
| tblp | 0 |
| tblselectdemo | 6 |
| tblstudent | 2 |
| tbluni | 0 |
| tblupdatelimit | 8 |
| textdemo | 0 |
| textintonumberdemo | 4 |
| texttabledemo | 0 |
| texturl | 0 |
| timestampdemo | 0 |
| timestamptodatedemo | 0 |
| tinyint1demo | 0 |
| tinyintdemo | 2 |
| trailingandleadingdemo | 2 |
| transcationdemo | 2 |
| triggedemo | 0 |
| trigger1 | 0 |
| trigger2demo | 0 |
| trimdemo | 2 |
| trimdemo2 | 0 |
| truefalsetable | 0 |
| tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt | 0 |
| uniondemo1 | 3 |
| uniondemo2 | 7 |
| uniqueautoid | 3 |
| uniqueconstdemo | 2 |
| uniquedemo | 2 |
| uniquedemo1 | 2 |
| unsigneddemo | 2 |
| updatewithlimit | 5 |
| updtable | 4 |
| usernameandpassworddemo | 2 |
| varchardemo | 0 |
| varchardemo1 | 0 |
| varchardemo2 | 0 |
| varcharurl | 0 |
| variableastablename | 2 |
| variablenametable | 0 |
| whereconditon | 4 |
| wordcountdemo | 0 |
| xmldemo | 0 |
+------------------------------------------------------------------+------------+
209 rows in set (0.08 sec) | [
{
"code": null,
"e": 1192,
"s": 1062,
"text": "To get the count of all the records in MySQL tables, we can use TABLE_ROWS with aggregate function SUM. The syntax is as follows."
},
{
"code": null,
"e": 1293,
"s": 1192,
"text": "SELECT SUM(TABLE_ROWS)\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = 'yourDatabaseName';"
},
{
"code": null,
"e": 1395,
"s": 1293,
"text": "Apply the above syntax in order to get the count of records for all tables. The query is as follows −"
},
{
"code": null,
"e": 1499,
"s": 1395,
"text": "mysql> SELECT SUM(TABLE_ROWS)\n ->FROM INFORMATION_SCHEMA.TABLES\n ->WHERE TABLE_SCHEMA = 'business';"
},
{
"code": null,
"e": 1549,
"s": 1499,
"text": "The following table returns the count of records."
},
{
"code": null,
"e": 1675,
"s": 1549,
"text": "+-----------------+\n| SUM(TABLE_ROWS) |\n+-----------------+\n| 450 |\n+-----------------+\n1 row in set (13.54 sec)\n"
},
{
"code": null,
"e": 1748,
"s": 1675,
"text": "To display the count of all records per table, use the following query −"
},
{
"code": null,
"e": 1859,
"s": 1748,
"text": "mysql> SELECT table_name, table_rows\n ->FROM INFORMATION_SCHEMA.TABLES\n ->WHERE TABLE_SCHEMA = 'business';"
},
{
"code": null,
"e": 1888,
"s": 1859,
"text": "The following is the output."
},
{
"code": null,
"e": 19382,
"s": 1888,
"text": "+------------------------------------------------------------------+------------+\n| TABLE_NAME | TABLE_ROWS |\n+------------------------------------------------------------------+------------+\n| add1daydemo | 2 |\n| addcheckconstraintdemo | 0 |\n| addcolumntable | 0 |\n| addconstraintdemo | 2 |\n| adding5hours | 2 |\n| addingunique | 2 |\n| addnotnulldemo | 2 |\n| alphademo | 0 |\n| autoincrement | 4 |\n| autoincrementtable | 5 |\n| backticksymbol | 4 |\n| bitdemo | 2 |\n| blobtabledemo | 0 |\n| bookindexes | 4 |\n| booleandemo | 0 |\n| chardemo | 0 |\n| checkdemo | 0 |\n| checkingintegerdemo | 2 |\n| childdemo | 0 |\n| clonestudent | 3 |\n| college | 0 |\n| colortable | 0 |\n| columnexistdemo | 0 |\n| columnnameasnumberdemo | 2 |\n| columnnamewithspace | 4 |\n| columnslist | 0 |\n| columnvaluenulldemo | 2 |\n| commaseperatedemo | 2 |\n| commentdemo | 0 |\n| commentdemo2 | 0 |\n| commentdemo3 | 0 |\n| countrycitydemo | 2 |\n| currentdatetime | 0 |\n| currenttimeadding2hours | 0 |\n| currenttimezone | 1 |\n| dateadddemo | 0 |\n| datetimedemo | 3 |\n| deletedemo | 5 |\n| deleterecord | 6 |\n| demo | 2 |\n| demo1 | 0 |\n| demoascii | 2 |\n| demoauto | 2 |\n| demobcrypt | 0 |\n| demoemptyandnull | 0 |\n| demoint | 0 |\n| demoonreplace | 2 |\n| demoschema | 0 |\n| demowhere | 2 |\n| distcountdemo | 4 |\n| distinctdemo | 8 |\n| distinctdemo1 | 4 |\n| duplicatebookindexes | 4 |\n| duplicatedeletedemo | 4 |\n| duplicatefound | 4 |\n| employeeinformation | 2 |\n| employeerecords | 0 |\n| employeetable | 0 |\n| enumdemo | 2 |\n| enumvalues | 0 |\n| escapedeom | 0 |\n| existsrowdemo | 4 |\n| findandreplacedemo | 4 |\n| finddemo | 2 |\n| firsttable | 2 |\n| firsttabledemo | 3 |\n| foreigntable | 2 |\n| foreigntabledemo | 2 |\n| functionindexdemo | 0 |\n| functiontriggersdemo | 0 |\n| groupconcatenatedemo | 4 |\n| groupdemo | 4 |\n| groupdemo1 | 4 |\n| groupt_concatdemo | 4 |\n| ifelsedemo | 4 |\n| imagedemo | 2 |\n| incasesensdemo | 4 |\n| indexingdemo | 0 |\n| insertingemojidemo | 1 |\n| insubquerydemo | 2 |\n| int1demo | 0 |\n| intdemo | 2 |\n| ipv4addressdemo | 0 |\n| ipv6demo | 0 |\n| jasonasmysqldemo | 2 |\n| keydemo | 2 |\n| last10recordsdemo | 12 |\n| lastinsertiddemo | 3 |\n| lastinsertrecordiddemo | 3 |\n| latandlangdemo | 0 |\n| lengthandcharlengthdemo | 1 |\n| limitoffsetdemo | 11 |\n| lowcardinality | 2 |\n| milliseconddemo | 0 |\n| modifycolumnnamedemo | 0 |\n| modifydatatype | 0 |\n| moneydemo | 2 |\n| moviecollection | 6 |\n| multipleindexdemo | 0 |\n| multiplerecordwithvalues | 4 |\n| myisamtabledemo | 2 |\n| myisamtoinnodbdemo | 0 |\n| mytable | 0 |\n| mytable1 | 0 |\n| mytabledemo | 2 |\n| newstudent | 0 |\n| nextiddemo | 2 |\n| nextpreviousdemo | 9 |\n| nonasciidemo | 4 |\n| nthrecorddemo | 4 |\n| nulldemo | 0 |\n| nullwithselect | 6 |\n| numbercolumndemo | 0 |\n| numberofcolumns | 2 |\n| ondemo | 4 |\n| orderdemo | 2 |\n| originaltable | 4 |\n| parentdemo | 0 |\n| pasthistory | 4 |\n| presenthistory | 2 |\n| primarytable | 2 |\n| primarytable1 | 2 |\n| primarytabledemo | 2 |\n| proctabledemo | 3 |\n| querybetweentwodates | 0 |\n| querydatedemo | 0 |\n| qutesdemo | 2 |\n| randomoptimizationdemo | 8 |\n| randoptimizedemo | 26 |\n| repairtabledemo | 3 |\n| rowcountdemo | 8 |\n| rowintocolumn | 4 |\n| rownumberdemo | 4 |\n| rowstranspose | 2 |\n| rowstransposedemo | 4 |\n| rowvaluedemo | 8 |\n| saveintotextfile | 2 |\n| saveoutputintext | 0 |\n| schemadatabasemethoddemo | 0 |\n| secondtable | 2 |\n| secondtabledemo | 2 |\n| sequencedemo | 7 |\n| singlequotesdemo | 2 |\n| smallintdemo | 0 |\n| sortingvarchardemo | 6 |\n| sourcetable | 4 |\n| spacecolumn | 2 |\n| stringoccurrencedemo | 3 |\n| stringtodatedemo | 0 |\n| student | 2 |\n| studentenrollment | 0 |\n| studentrecordwithmyisam | 0 |\n| studenttable | 4 |\n| swappingtwocoulmnsvaluedemo | 5 |\n| table1 | 2 |\n| table2 | 3 |\n| tabledemo | 0 |\n| tabledemo2 | 0 |\n| tabledemo3 | 0 |\n| tableforeign | 0 |\n| tablename1tablename1tablename1tablename1tablename1tablename1demo | 0 |\n| tablepri | 0 |\n| tbldemotrail | 6 |\n| tblf | 0 |\n| tblfirst | 2 |\n| tblfunctiontrigger | 0 |\n| tblifdemo | 4 |\n| tblnull | 0 |\n| tblp | 0 |\n| tblselectdemo | 6 |\n| tblstudent | 2 |\n| tbluni | 0 |\n| tblupdatelimit | 8 |\n| textdemo | 0 |\n| textintonumberdemo | 4 |\n| texttabledemo | 0 |\n| texturl | 0 |\n| timestampdemo | 0 |\n| timestamptodatedemo | 0 |\n| tinyint1demo | 0 |\n| tinyintdemo | 2 |\n| trailingandleadingdemo | 2 |\n| transcationdemo | 2 |\n| triggedemo | 0 |\n| trigger1 | 0 |\n| trigger2demo | 0 |\n| trimdemo | 2 |\n| trimdemo2 | 0 |\n| truefalsetable | 0 |\n| tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt | 0 |\n| uniondemo1 | 3 |\n| uniondemo2 | 7 |\n| uniqueautoid | 3 |\n| uniqueconstdemo | 2 |\n| uniquedemo | 2 |\n| uniquedemo1 | 2 |\n| unsigneddemo | 2 |\n| updatewithlimit | 5 |\n| updtable | 4 |\n| usernameandpassworddemo | 2 |\n| varchardemo | 0 |\n| varchardemo1 | 0 |\n| varchardemo2 | 0 |\n| varcharurl | 0 |\n| variableastablename | 2 |\n| variablenametable | 0 |\n| whereconditon | 4 |\n| wordcountdemo | 0 |\n| xmldemo | 0 |\n+------------------------------------------------------------------+------------+\n209 rows in set (0.08 sec)\n"
}
] |
8086 program to Print a 16 bit Decimal number - GeeksforGeeks | 17 Jun, 2021
Problem: Write a 8086 program to Print a 16 bit Decimal number.
Examples:
Input: d1 = 655
Output: 655
Input: d1 = 234
Output:234
Explanation:
load the value stored into registerdivide the value by 10push the remainder into the stackincrease the countrepeat the steps until the value of the register is greater than 0until the count is greater than zeropop the stackadd 48 to the top element to convert it into ASCIIprint the character using interruptdecrements the count
load the value stored into register
divide the value by 10
push the remainder into the stack
increase the count
repeat the steps until the value of the register is greater than 0
until the count is greater than zero
pop the stack
add 48 to the top element to convert it into ASCII
print the character using interrupt
decrements the count
Program:
ALP
;8086 program to print a 16 bit decimal number.MODEL SMALL.STACK 100H.DATAd1 dw 655.CODEMAIN PROC FAR MOV AX,@DATA MOV DS,AX ;load the value stored ; in variable d1 mov ax,d1 ;print the value CALL PRINT ;interrupt to exit MOV AH,4CH INT 21H MAIN ENDPPRINT PROC ;initialize count mov cx,0 mov dx,0 label1: ; if ax is zero cmp ax,0 je print1 ;initialize bx to 10 mov bx,10 ; extract the last digit div bx ;push it in the stack push dx ;increment the count inc cx ;set dx to 0 xor dx,dx jmp label1 print1: ;check if count ;is greater than zero cmp cx,0 je exit ;pop the top of stack pop dx ;add 48 so that it ;represents the ASCII ;value of digits add dx,48 ;interrupt to print a ;character mov ah,02h int 21h ;decrease the count dec cx jmp print1exit:retPRINT ENDPEND MAIN
Output:
655
Note: The program cannot be run on an online editor , please use MASM to run the program and use dos box to run MASM , you might use any 8086 emulator to run the program
arorakashish0911
surinderdawra388
Computer Organization and Architecture
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Architecture of 8086
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Computer Organization | RISC and CISC
Architecture of 8085 microprocessor
Interrupts
Memory Hierarchy Design and its Characteristics
Computer Organization | Von Neumann architecture
Difference between Von Neumann and Harvard Architecture
Programmable peripheral interface 8255 | [
{
"code": null,
"e": 24763,
"s": 24735,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 24827,
"s": 24763,
"text": "Problem: Write a 8086 program to Print a 16 bit Decimal number."
},
{
"code": null,
"e": 24838,
"s": 24827,
"text": "Examples: "
},
{
"code": null,
"e": 24895,
"s": 24838,
"text": "Input: d1 = 655\nOutput: 655\n\nInput: d1 = 234\nOutput:234 "
},
{
"code": null,
"e": 24909,
"s": 24895,
"text": "Explanation: "
},
{
"code": null,
"e": 25238,
"s": 24909,
"text": "load the value stored into registerdivide the value by 10push the remainder into the stackincrease the countrepeat the steps until the value of the register is greater than 0until the count is greater than zeropop the stackadd 48 to the top element to convert it into ASCIIprint the character using interruptdecrements the count"
},
{
"code": null,
"e": 25274,
"s": 25238,
"text": "load the value stored into register"
},
{
"code": null,
"e": 25297,
"s": 25274,
"text": "divide the value by 10"
},
{
"code": null,
"e": 25331,
"s": 25297,
"text": "push the remainder into the stack"
},
{
"code": null,
"e": 25350,
"s": 25331,
"text": "increase the count"
},
{
"code": null,
"e": 25417,
"s": 25350,
"text": "repeat the steps until the value of the register is greater than 0"
},
{
"code": null,
"e": 25454,
"s": 25417,
"text": "until the count is greater than zero"
},
{
"code": null,
"e": 25468,
"s": 25454,
"text": "pop the stack"
},
{
"code": null,
"e": 25519,
"s": 25468,
"text": "add 48 to the top element to convert it into ASCII"
},
{
"code": null,
"e": 25555,
"s": 25519,
"text": "print the character using interrupt"
},
{
"code": null,
"e": 25576,
"s": 25555,
"text": "decrements the count"
},
{
"code": null,
"e": 25586,
"s": 25576,
"text": "Program: "
},
{
"code": null,
"e": 25590,
"s": 25586,
"text": "ALP"
},
{
"code": ";8086 program to print a 16 bit decimal number.MODEL SMALL.STACK 100H.DATAd1 dw 655.CODEMAIN PROC FAR MOV AX,@DATA MOV DS,AX ;load the value stored ; in variable d1 mov ax,d1 ;print the value CALL PRINT ;interrupt to exit MOV AH,4CH INT 21H MAIN ENDPPRINT PROC ;initialize count mov cx,0 mov dx,0 label1: ; if ax is zero cmp ax,0 je print1 ;initialize bx to 10 mov bx,10 ; extract the last digit div bx ;push it in the stack push dx ;increment the count inc cx ;set dx to 0 xor dx,dx jmp label1 print1: ;check if count ;is greater than zero cmp cx,0 je exit ;pop the top of stack pop dx ;add 48 so that it ;represents the ASCII ;value of digits add dx,48 ;interrupt to print a ;character mov ah,02h int 21h ;decrease the count dec cx jmp print1exit:retPRINT ENDPEND MAIN",
"e": 26832,
"s": 25590,
"text": null
},
{
"code": null,
"e": 26841,
"s": 26832,
"text": "Output: "
},
{
"code": null,
"e": 26845,
"s": 26841,
"text": "655"
},
{
"code": null,
"e": 27016,
"s": 26845,
"text": "Note: The program cannot be run on an online editor , please use MASM to run the program and use dos box to run MASM , you might use any 8086 emulator to run the program "
},
{
"code": null,
"e": 27033,
"s": 27016,
"text": "arorakashish0911"
},
{
"code": null,
"e": 27050,
"s": 27033,
"text": "surinderdawra388"
},
{
"code": null,
"e": 27089,
"s": 27050,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 27104,
"s": 27089,
"text": "microprocessor"
},
{
"code": null,
"e": 27123,
"s": 27104,
"text": "system-programming"
},
{
"code": null,
"e": 27160,
"s": 27123,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 27175,
"s": 27160,
"text": "microprocessor"
},
{
"code": null,
"e": 27273,
"s": 27175,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27282,
"s": 27273,
"text": "Comments"
},
{
"code": null,
"e": 27295,
"s": 27282,
"text": "Old Comments"
},
{
"code": null,
"e": 27316,
"s": 27295,
"text": "Architecture of 8086"
},
{
"code": null,
"e": 27365,
"s": 27316,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 27460,
"s": 27365,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 27498,
"s": 27460,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 27534,
"s": 27498,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 27545,
"s": 27534,
"text": "Interrupts"
},
{
"code": null,
"e": 27593,
"s": 27545,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 27642,
"s": 27593,
"text": "Computer Organization | Von Neumann architecture"
},
{
"code": null,
"e": 27698,
"s": 27642,
"text": "Difference between Von Neumann and Harvard Architecture"
}
] |
Android - Hello World Example | Let us start actual programming with Android Framework. Before you start writing your first example using Android SDK, you have to make sure that you have set-up your Android development environment properly as explained in Android - Environment Set-up tutorial. I also assume that you have a little bit working knowledge with Android studio.
So let us proceed to write a simple Android Application which will print "Hello World!".
The first step is to create a simple Android Application using Android studio. When you click on Android studio icon, it will show screen as shown below
You can start your application development by calling start a new android studio project. in a new installation frame should ask Application name, package information and location of the project.−
After entered application name, it going to be called select the form factors your application runs on, here need to specify Minimum SDK, in our tutorial, I have declared as API23: Android 6.0(Mashmallow) −
The next level of installation should contain selecting the activity to mobile, it specifies the default layout for Applications.
At the final stage it going to be open development tool to write the application code.
Before you run your app, you should be aware of a few directories and files in the Android project −
Java
This contains the .java source files for your project. By default, it includes an MainActivity.java source file having an activity class that runs when your app is launched using the app icon.
res/drawable-hdpi
This is a directory for drawable objects that are designed for high-density screens.
res/layout
This is a directory for files that define your app's user interface.
res/values
This is a directory for other various XML files that contain a collection of resources, such as strings and colours definitions.
AndroidManifest.xml
This is the manifest file which describes the fundamental characteristics of the app and defines each of its components.
Build.gradle
This is an auto generated file which contains compileSdkVersion, buildToolsVersion, applicationId, minSdkVersion, targetSdkVersion, versionCode and versionName
Following section will give a brief overview of the important application files.
The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for Hello World! application −
package com.example.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. The onCreate() method is one of many methods that are figured when an activity is loaded.
Whatever component you develop as a part of your application, you must declare all its components in a manifest.xml which resides at the root of the application project directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS. For example, a default manifest file will look like as following file −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
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>
Here <application>...</application> tags enclosed the components related to the application. Attribute android:icon will point to the application icon available under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the drawable folders
The <activity> tag is used to specify an activity and android:name attribute specifies the fully qualified class name of the Activity subclass and the android:label attributes specifies a string to use as the label for the activity. You can specify multiple activities using <activity> tags.
The action for the intent filter is named android.intent.action.MAIN to indicate that this activity serves as the entry point for the application. The category for the intent-filter is named android.intent.category.LAUNCHER to indicate that the application can be launched from the device's launcher icon.
The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to the app_name string defined in the strings.xml file, which is "HelloWorld". Similar way, other strings get populated in the application.
Following is the list of tags which you will use in your manifest file to specify different Android application components −
<activity>elements for activities
<activity>elements for activities
<service> elements for services
<service> elements for services
<receiver> elements for broadcast receivers
<receiver> elements for broadcast receivers
<provider> elements for content providers
<provider> elements for content providers
The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the names of buttons, labels, default text, and similar types of strings go into this file. This file is responsible for their textual content. For example, a default strings file will look like as following file −
<resources>
<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>
The activity_main.xml is a layout file available in res/layout directory, that is referenced by your application when building its interface. You will modify this file very frequently to change the layout of your application. For your "Hello World!" application, this file will have following content related to default layout −
<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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
This is an example of simple RelativeLayout which we will study in a separate chapter. The TextView is an Android control used to build the GUI and it have various attributes like android:layout_width, android:layout_height etc which are being used to set its width and height etc.. The @string refers to the strings.xml file located in the res/values folder. Hence, @string/hello_world refers to the hello string defined in the strings.xml file, which is "Hello World!".
Let's try to run our Hello World! application we just created. I assume you had created your AVD while doing environment set-up. To run the app from Android studio, open one of your project's activity files and click Run icon from the tool bar. Android studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window −
Congratulations!!! you have developed your first Android Application and now just keep following rest of the tutorial step by step to become a great Android Developer. All the very best.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3950,
"s": 3607,
"text": "Let us start actual programming with Android Framework. Before you start writing your first example using Android SDK, you have to make sure that you have set-up your Android development environment properly as explained in Android - Environment Set-up tutorial. I also assume that you have a little bit working knowledge with Android studio."
},
{
"code": null,
"e": 4039,
"s": 3950,
"text": "So let us proceed to write a simple Android Application which will print \"Hello World!\"."
},
{
"code": null,
"e": 4192,
"s": 4039,
"text": "The first step is to create a simple Android Application using Android studio. When you click on Android studio icon, it will show screen as shown below"
},
{
"code": null,
"e": 4389,
"s": 4192,
"text": "You can start your application development by calling start a new android studio project. in a new installation frame should ask Application name, package information and location of the project.−"
},
{
"code": null,
"e": 4596,
"s": 4389,
"text": "After entered application name, it going to be called select the form factors your application runs on, here need to specify Minimum SDK, in our tutorial, I have declared as API23: Android 6.0(Mashmallow) −"
},
{
"code": null,
"e": 4726,
"s": 4596,
"text": "The next level of installation should contain selecting the activity to mobile, it specifies the default layout for Applications."
},
{
"code": null,
"e": 4813,
"s": 4726,
"text": "At the final stage it going to be open development tool to write the application code."
},
{
"code": null,
"e": 4914,
"s": 4813,
"text": "Before you run your app, you should be aware of a few directories and files in the Android project −"
},
{
"code": null,
"e": 4919,
"s": 4914,
"text": "Java"
},
{
"code": null,
"e": 5112,
"s": 4919,
"text": "This contains the .java source files for your project. By default, it includes an MainActivity.java source file having an activity class that runs when your app is launched using the app icon."
},
{
"code": null,
"e": 5130,
"s": 5112,
"text": "res/drawable-hdpi"
},
{
"code": null,
"e": 5215,
"s": 5130,
"text": "This is a directory for drawable objects that are designed for high-density screens."
},
{
"code": null,
"e": 5226,
"s": 5215,
"text": "res/layout"
},
{
"code": null,
"e": 5295,
"s": 5226,
"text": "This is a directory for files that define your app's user interface."
},
{
"code": null,
"e": 5306,
"s": 5295,
"text": "res/values"
},
{
"code": null,
"e": 5435,
"s": 5306,
"text": "This is a directory for other various XML files that contain a collection of resources, such as strings and colours definitions."
},
{
"code": null,
"e": 5455,
"s": 5435,
"text": "AndroidManifest.xml"
},
{
"code": null,
"e": 5576,
"s": 5455,
"text": "This is the manifest file which describes the fundamental characteristics of the app and defines each of its components."
},
{
"code": null,
"e": 5589,
"s": 5576,
"text": "Build.gradle"
},
{
"code": null,
"e": 5750,
"s": 5589,
"text": "This is an auto generated file which contains compileSdkVersion, buildToolsVersion, applicationId, minSdkVersion, targetSdkVersion, versionCode and versionName"
},
{
"code": null,
"e": 5831,
"s": 5750,
"text": "Following section will give a brief overview of the important application files."
},
{
"code": null,
"e": 6103,
"s": 5831,
"text": "The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for Hello World! application −"
},
{
"code": null,
"e": 6430,
"s": 6103,
"text": "package com.example.helloworld;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}"
},
{
"code": null,
"e": 6620,
"s": 6430,
"text": "Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. The onCreate() method is one of many methods that are figured when an activity is loaded."
},
{
"code": null,
"e": 7042,
"s": 6620,
"text": "Whatever component you develop as a part of your application, you must declare all its components in a manifest.xml which resides at the root of the application project directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS. For example, a default manifest file will look like as following file −"
},
{
"code": null,
"e": 7699,
"s": 7042,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.tutorialspoint7.myapplication\">\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n \n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 7970,
"s": 7699,
"text": "Here <application>...</application> tags enclosed the components related to the application. Attribute android:icon will point to the application icon available under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the drawable folders"
},
{
"code": null,
"e": 8262,
"s": 7970,
"text": "The <activity> tag is used to specify an activity and android:name attribute specifies the fully qualified class name of the Activity subclass and the android:label attributes specifies a string to use as the label for the activity. You can specify multiple activities using <activity> tags."
},
{
"code": null,
"e": 8569,
"s": 8262,
"text": "The action for the intent filter is named android.intent.action.MAIN to indicate that this activity serves as the entry point for the application. The category for the intent-filter is named android.intent.category.LAUNCHER to indicate that the application can be launched from the device's launcher icon."
},
{
"code": null,
"e": 8800,
"s": 8569,
"text": "The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to the app_name string defined in the strings.xml file, which is \"HelloWorld\". Similar way, other strings get populated in the application."
},
{
"code": null,
"e": 8925,
"s": 8800,
"text": "Following is the list of tags which you will use in your manifest file to specify different Android application components −"
},
{
"code": null,
"e": 8959,
"s": 8925,
"text": "<activity>elements for activities"
},
{
"code": null,
"e": 8993,
"s": 8959,
"text": "<activity>elements for activities"
},
{
"code": null,
"e": 9025,
"s": 8993,
"text": "<service> elements for services"
},
{
"code": null,
"e": 9057,
"s": 9025,
"text": "<service> elements for services"
},
{
"code": null,
"e": 9101,
"s": 9057,
"text": "<receiver> elements for broadcast receivers"
},
{
"code": null,
"e": 9145,
"s": 9101,
"text": "<receiver> elements for broadcast receivers"
},
{
"code": null,
"e": 9187,
"s": 9145,
"text": "<provider> elements for content providers"
},
{
"code": null,
"e": 9229,
"s": 9187,
"text": "<provider> elements for content providers"
},
{
"code": null,
"e": 9571,
"s": 9229,
"text": "The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the names of buttons, labels, default text, and similar types of strings go into this file. This file is responsible for their textual content. For example, a default strings file will look like as following file −"
},
{
"code": null,
"e": 9805,
"s": 9571,
"text": "<resources>\n <string name=\"app_name\">HelloWorld</string>\n <string name=\"hello_world\">Hello world!</string>\n <string name=\"menu_settings\">Settings</string>\n <string name=\"title_activity_main\">MainActivity</string>\n</resources>"
},
{
"code": null,
"e": 10134,
"s": 9805,
"text": "The activity_main.xml is a layout file available in res/layout directory, that is referenced by your application when building its interface. You will modify this file very frequently to change the layout of your application. For your \"Hello World!\" application, this file will have following content related to default layout −"
},
{
"code": null,
"e": 10681,
"s": 10134,
"text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" >\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_centerVertical=\"true\"\n android:padding=\"@dimen/padding_medium\"\n android:text=\"@string/hello_world\"\n tools:context=\".MainActivity\" />\n \n</RelativeLayout>"
},
{
"code": null,
"e": 11153,
"s": 10681,
"text": "This is an example of simple RelativeLayout which we will study in a separate chapter. The TextView is an Android control used to build the GUI and it have various attributes like android:layout_width, android:layout_height etc which are being used to set its width and height etc.. The @string refers to the strings.xml file located in the res/values folder. Hence, @string/hello_world refers to the hello string defined in the strings.xml file, which is \"Hello World!\"."
},
{
"code": null,
"e": 11561,
"s": 11153,
"text": "Let's try to run our Hello World! application we just created. I assume you had created your AVD while doing environment set-up. To run the app from Android studio, open one of your project's activity files and click Run icon from the tool bar. Android studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window −"
},
{
"code": null,
"e": 11748,
"s": 11561,
"text": "Congratulations!!! you have developed your first Android Application and now just keep following rest of the tutorial step by step to become a great Android Developer. All the very best."
},
{
"code": null,
"e": 11783,
"s": 11748,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 11795,
"s": 11783,
"text": " Aditya Dua"
},
{
"code": null,
"e": 11830,
"s": 11795,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 11844,
"s": 11830,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 11876,
"s": 11844,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11893,
"s": 11876,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11928,
"s": 11893,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11945,
"s": 11928,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11980,
"s": 11945,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11997,
"s": 11980,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12030,
"s": 11997,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12047,
"s": 12030,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12054,
"s": 12047,
"text": " Print"
},
{
"code": null,
"e": 12065,
"s": 12054,
"text": " Add Notes"
}
] |
Make Selenium wait 10 seconds. | We can make Selenium wait for 10 seconds. This can be done by using the Thread.sleep method. Here, the wait time (10 seconds) is passed as a parameter to the method.
We can also use the synchronization concept in Selenium for waiting. There are two kinds of wait − implicit and explicit. Both these are of dynamic nature, however the implicit wait is applied to every step of automation, the explicit wait is applicable only to a particular element.
Code Implementation with sleep method.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class WaitThrd{
public static void main(String[] args)
throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/index.htm");
// wait time added
Thread.sleep(200);
// identify element,
WebElement m=driver.findElement(By.id("gsc−i−id1"));
m.sendKeys("Java");
driver.close();
}
}
Code Implementation with implicit wait.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class WaitImplicit{
public static void main(String[] args)
throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
// implicit wait
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/index.htm");
// identify element,
WebElement m=driver.findElement(By.id("gsc−i−id1"));
m.sendKeys("Python");
driver.close();
}
}
Code Implementation with explicit wait.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WaitExplicit{
public static void main(String[] args)
throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/index.htm");
// identify element,
WebElement l=driver.findElement(By.xpath("//*[text()='Library']"));
l.click();
//explicit wait
WebDriverWait w = new WebDriverWait(driver,7);
//expected condition
w.until(ExpectedConditions.
invisibilityOfElementLocated(By.xpath("//*[@class='mui−btn']")));
driver.close();
}
} | [
{
"code": null,
"e": 1228,
"s": 1062,
"text": "We can make Selenium wait for 10 seconds. This can be done by using the Thread.sleep method. Here, the wait time (10 seconds) is passed as a parameter to the method."
},
{
"code": null,
"e": 1512,
"s": 1228,
"text": "We can also use the synchronization concept in Selenium for waiting. There are two kinds of wait − implicit and explicit. Both these are of dynamic nature, however the implicit wait is applied to every step of automation, the explicit wait is applicable only to a particular element."
},
{
"code": null,
"e": 1551,
"s": 1512,
"text": "Code Implementation with sleep method."
},
{
"code": null,
"e": 2226,
"s": 1551,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class WaitThrd{\n public static void main(String[] args)\n throws InterruptedException{\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // wait time added\n Thread.sleep(200);\n // identify element,\n WebElement m=driver.findElement(By.id(\"gsc−i−id1\"));\n m.sendKeys(\"Java\");\n driver.close();\n }\n}"
},
{
"code": null,
"e": 2266,
"s": 2226,
"text": "Code Implementation with implicit wait."
},
{
"code": null,
"e": 2990,
"s": 2266,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class WaitImplicit{\n public static void main(String[] args)\n throws InterruptedException{\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n // implicit wait\n driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // identify element,\n WebElement m=driver.findElement(By.id(\"gsc−i−id1\"));\n m.sendKeys(\"Python\");\n driver.close();\n }\n}"
},
{
"code": null,
"e": 3030,
"s": 2990,
"text": "Code Implementation with explicit wait."
},
{
"code": null,
"e": 3984,
"s": 3030,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.support.ui.ExpectedConditions;\nimport org.openqa.selenium.support.ui.WebDriverWait;\npublic class WaitExplicit{\n public static void main(String[] args)\n throws InterruptedException{\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // identify element,\n WebElement l=driver.findElement(By.xpath(\"//*[text()='Library']\"));\n l.click();\n //explicit wait\n WebDriverWait w = new WebDriverWait(driver,7);\n //expected condition\n w.until(ExpectedConditions.\n invisibilityOfElementLocated(By.xpath(\"//*[@class='mui−btn']\")));\n driver.close();\n }\n}"
}
] |
Remove Primary Key in MySQL? | To remove primary key in MySQL, use tje drop primary key command. To understand the concept, let us create a table with column as primary key.
mysql> create table PrimaryKeyDemo
-> (
-> id int not null,
-> Primary key(id)
-> );
Query OK, 0 rows affected (0.60 sec)
Let us check the description of the table with the help of DESC command. The query is as follows.
mysql> desc PrimaryKeyDemo;
The following is the output.
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.06 sec)
Look at the output above, there is a column ‘Key’ which has the PRI keyword. This itself says that the “id” column is primary key. Now, let us remove the primary key with the help of ALTER and DROP command. The query is as follows.
mysql> alter table PrimaryKeyDemo drop primary key;
Query OK, 0 rows affected (1.70 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us now check whether primary key is removed or not successfully.
mysql> DESC PrimaryKeyDemo;
The following is the output that won’t display primary key now, since we have deleted it above.
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1205,
"s": 1062,
"text": "To remove primary key in MySQL, use tje drop primary key command. To understand the concept, let us create a table with column as primary key."
},
{
"code": null,
"e": 1339,
"s": 1205,
"text": "mysql> create table PrimaryKeyDemo\n -> (\n -> id int not null,\n -> Primary key(id)\n -> );\nQuery OK, 0 rows affected (0.60 sec)"
},
{
"code": null,
"e": 1437,
"s": 1339,
"text": "Let us check the description of the table with the help of DESC command. The query is as follows."
},
{
"code": null,
"e": 1465,
"s": 1437,
"text": "mysql> desc PrimaryKeyDemo;"
},
{
"code": null,
"e": 1494,
"s": 1465,
"text": "The following is the output."
},
{
"code": null,
"e": 1774,
"s": 1494,
"text": "+-------+---------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+---------+------+-----+---------+-------+\n| id | int(11) | NO | PRI | NULL | |\n+-------+---------+------+-----+---------+-------+\n1 row in set (0.06 sec)\n"
},
{
"code": null,
"e": 2006,
"s": 1774,
"text": "Look at the output above, there is a column ‘Key’ which has the PRI keyword. This itself says that the “id” column is primary key. Now, let us remove the primary key with the help of ALTER and DROP command. The query is as follows."
},
{
"code": null,
"e": 2135,
"s": 2006,
"text": "mysql> alter table PrimaryKeyDemo drop primary key;\nQuery OK, 0 rows affected (1.70 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2204,
"s": 2135,
"text": "Let us now check whether primary key is removed or not successfully."
},
{
"code": null,
"e": 2232,
"s": 2204,
"text": "mysql> DESC PrimaryKeyDemo;"
},
{
"code": null,
"e": 2328,
"s": 2232,
"text": "The following is the output that won’t display primary key now, since we have deleted it above."
},
{
"code": null,
"e": 2608,
"s": 2328,
"text": "+-------+---------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+---------+------+-----+---------+-------+\n| id | int(11) | NO | | NULL | |\n+-------+---------+------+-----+---------+-------+\n1 row in set (0.00 sec)\n"
}
] |
How to Run Animations in Altair and Streamlit | by Angelica Lo Duca | Towards Data Science | Altair is a very popular Python library for data visualisation. Through Altair, you can build very complex charts with few lines of code, since the library follows the guide lines provided by the Vega-lite grammar.
Unfortunately, Altair does not support native animations, because of the complexity of rendering them through Vega-lite.
In this tutorial, I illustrate a mechanism which combines the power of Streamlit with Altair, in order to render an animated line chart.
Streamlit is a very powerful Python library, which permits to build Web apps in Python with few lines of code.
Firstly, I install the required libraries:
pip install streamlitpip install altair
In order to build a Streamlit app, I can write a Python script, which cannot be in the form of a Jupyter notebook, since currently Streamlit does not support Jupyter.
Thus, I create a script, named AltairAnimation.py, I import all the needed libraries to my script:
import pandas as pdimport altair as altimport streamlit as stimport time
Then, I load the dataset. As example, I exploit the number of tourist arrivals to Italy from 2012 to 2020, released by the Eurostat Database. I exploit the Pandas library to load the dataset:
df = pd.read_csv('../sources/tourist_arrivals.csv')
The dataset contains the monthly number of tourists arrivals. I convert the date to a datetime type:
df['date'] = pd.to_datetime(df['date'])
I build an empty graph in Altair through the Chart() class. In details, I specify that I want to draw a line through the mark_line() function. Then, I set the axes (x and y) as well as the width and height of the graph. As default values for the x axis, I set 1:T, where T indicates a time variable. For the y axis, instead, I set the default value to 0:Q, where Q indicates a quantity, i.e. a number.
lines = alt.Chart(df).mark_line().encode( x=alt.X('1:T',axis=alt.Axis(title='date')), y=alt.Y('0:Q',axis=alt.Axis(title='value'))).properties( width=600, height=300)
I also define a function which updates the chart with the dataframe passed as argument:
def plot_animation(df): lines = alt.Chart(df).mark_line().encode( x=alt.X('date:T', axis=alt.Axis(title='date')), y=alt.Y('value:Q',axis=alt.Axis(title='value')), ).properties( width=600, height=300 ) return lines
I would like to build an animation as the following one:
When the user clicks on the start button, the animation starts, and initially it plots only the first 6 months of the dataframe. Then, other 6 months are added to the plot and so on up to the size of the dataframe.
This can be achieved as follows. Firstly, I define some auxiliary variables:
N = df.shape[0] # number of elements in the dataframeburst = 6 # number of elements (months) to add to the plotsize = burst # size of the current dataset
Now I can build the Streamlit interface. I draw a chart and a button:
line_plot = st.altair_chart(lines)start_btn = st.button('Start')
Finally, I can build the animation:
if start_btn: for i in range(1,N): step_df = df.iloc[0:size] lines = plot_animation(step_df) line_plot = line_plot.altair_chart(lines) size = i + burst if size >= N: size = N - 1 time.sleep(0.1)
If the user clicks the Start button (if start_btn:), then a loop starts, up to the number of elements N-1. A partial dataframe is built, including the first size elements. Then the chart is build on this partial dataframe and the variable size is updated.
Eventually, I’m ready to run the Web App. From command line, I can run the following command:
streamlit run AltairAnimation.py
The Web App will be available at the following URL:
http://localhost:8501
In this tutorial, I have illustrated how to build animations in Altair, by exploiting the very powerful Streamlit library.
The full code of the implemented Web App is available in my Github Repository.
I really would thank A B, who wrote this article, which inspired me for mine.
If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and and Github. | [
{
"code": null,
"e": 387,
"s": 172,
"text": "Altair is a very popular Python library for data visualisation. Through Altair, you can build very complex charts with few lines of code, since the library follows the guide lines provided by the Vega-lite grammar."
},
{
"code": null,
"e": 508,
"s": 387,
"text": "Unfortunately, Altair does not support native animations, because of the complexity of rendering them through Vega-lite."
},
{
"code": null,
"e": 645,
"s": 508,
"text": "In this tutorial, I illustrate a mechanism which combines the power of Streamlit with Altair, in order to render an animated line chart."
},
{
"code": null,
"e": 756,
"s": 645,
"text": "Streamlit is a very powerful Python library, which permits to build Web apps in Python with few lines of code."
},
{
"code": null,
"e": 799,
"s": 756,
"text": "Firstly, I install the required libraries:"
},
{
"code": null,
"e": 839,
"s": 799,
"text": "pip install streamlitpip install altair"
},
{
"code": null,
"e": 1006,
"s": 839,
"text": "In order to build a Streamlit app, I can write a Python script, which cannot be in the form of a Jupyter notebook, since currently Streamlit does not support Jupyter."
},
{
"code": null,
"e": 1105,
"s": 1006,
"text": "Thus, I create a script, named AltairAnimation.py, I import all the needed libraries to my script:"
},
{
"code": null,
"e": 1178,
"s": 1105,
"text": "import pandas as pdimport altair as altimport streamlit as stimport time"
},
{
"code": null,
"e": 1370,
"s": 1178,
"text": "Then, I load the dataset. As example, I exploit the number of tourist arrivals to Italy from 2012 to 2020, released by the Eurostat Database. I exploit the Pandas library to load the dataset:"
},
{
"code": null,
"e": 1422,
"s": 1370,
"text": "df = pd.read_csv('../sources/tourist_arrivals.csv')"
},
{
"code": null,
"e": 1523,
"s": 1422,
"text": "The dataset contains the monthly number of tourists arrivals. I convert the date to a datetime type:"
},
{
"code": null,
"e": 1563,
"s": 1523,
"text": "df['date'] = pd.to_datetime(df['date'])"
},
{
"code": null,
"e": 1965,
"s": 1563,
"text": "I build an empty graph in Altair through the Chart() class. In details, I specify that I want to draw a line through the mark_line() function. Then, I set the axes (x and y) as well as the width and height of the graph. As default values for the x axis, I set 1:T, where T indicates a time variable. For the y axis, instead, I set the default value to 0:Q, where Q indicates a quantity, i.e. a number."
},
{
"code": null,
"e": 2145,
"s": 1965,
"text": "lines = alt.Chart(df).mark_line().encode( x=alt.X('1:T',axis=alt.Axis(title='date')), y=alt.Y('0:Q',axis=alt.Axis(title='value'))).properties( width=600, height=300)"
},
{
"code": null,
"e": 2233,
"s": 2145,
"text": "I also define a function which updates the chart with the dataframe passed as argument:"
},
{
"code": null,
"e": 2487,
"s": 2233,
"text": "def plot_animation(df): lines = alt.Chart(df).mark_line().encode( x=alt.X('date:T', axis=alt.Axis(title='date')), y=alt.Y('value:Q',axis=alt.Axis(title='value')), ).properties( width=600, height=300 ) return lines"
},
{
"code": null,
"e": 2544,
"s": 2487,
"text": "I would like to build an animation as the following one:"
},
{
"code": null,
"e": 2759,
"s": 2544,
"text": "When the user clicks on the start button, the animation starts, and initially it plots only the first 6 months of the dataframe. Then, other 6 months are added to the plot and so on up to the size of the dataframe."
},
{
"code": null,
"e": 2836,
"s": 2759,
"text": "This can be achieved as follows. Firstly, I define some auxiliary variables:"
},
{
"code": null,
"e": 3000,
"s": 2836,
"text": "N = df.shape[0] # number of elements in the dataframeburst = 6 # number of elements (months) to add to the plotsize = burst # size of the current dataset"
},
{
"code": null,
"e": 3070,
"s": 3000,
"text": "Now I can build the Streamlit interface. I draw a chart and a button:"
},
{
"code": null,
"e": 3135,
"s": 3070,
"text": "line_plot = st.altair_chart(lines)start_btn = st.button('Start')"
},
{
"code": null,
"e": 3171,
"s": 3135,
"text": "Finally, I can build the animation:"
},
{
"code": null,
"e": 3407,
"s": 3171,
"text": "if start_btn: for i in range(1,N): step_df = df.iloc[0:size] lines = plot_animation(step_df) line_plot = line_plot.altair_chart(lines) size = i + burst if size >= N: size = N - 1 time.sleep(0.1)"
},
{
"code": null,
"e": 3663,
"s": 3407,
"text": "If the user clicks the Start button (if start_btn:), then a loop starts, up to the number of elements N-1. A partial dataframe is built, including the first size elements. Then the chart is build on this partial dataframe and the variable size is updated."
},
{
"code": null,
"e": 3757,
"s": 3663,
"text": "Eventually, I’m ready to run the Web App. From command line, I can run the following command:"
},
{
"code": null,
"e": 3790,
"s": 3757,
"text": "streamlit run AltairAnimation.py"
},
{
"code": null,
"e": 3842,
"s": 3790,
"text": "The Web App will be available at the following URL:"
},
{
"code": null,
"e": 3864,
"s": 3842,
"text": "http://localhost:8501"
},
{
"code": null,
"e": 3987,
"s": 3864,
"text": "In this tutorial, I have illustrated how to build animations in Altair, by exploiting the very powerful Streamlit library."
},
{
"code": null,
"e": 4066,
"s": 3987,
"text": "The full code of the implemented Web App is available in my Github Repository."
},
{
"code": null,
"e": 4144,
"s": 4066,
"text": "I really would thank A B, who wrote this article, which inspired me for mine."
}
] |
How to create a timer using tkinter? | In this example, we will create a timer using Python Tkinter. For displaying time, we will use the Time Module in Python.
Initially, we will follow these steps to create the timer,
Create three entry widget each for Hours, Minute and Seconds and set the value ‘00’ by default.
Create a Button for setting the timer. It will call the function countdowntimer().
Define a function countdowntimer() which does update once we click on the button to propagate the time.
#Import the required library
from tkinter import *
import time
#Create an instance of tkinter frame
win = Tk()
win.geometry('750x300')
win.resizable(False,False)
#Configure the background
win.config(bg='burlywood1')
#Create Entry Widgets for HH MM SS
sec = StringVar()
Entry(win, textvariable=sec, width = 2, font = 'Helvetica 14').place(x=220, y=120)
sec.set('00')
mins= StringVar()
Entry(win, textvariable = mins, width =2, font = 'Helvetica
14').place(x=180, y=120)
mins.set('00')
hrs= StringVar()
Entry(win, textvariable = hrs, width =2, font = 'Helvetica 14').place(x=142, y=120)
hrs.set('00')
#Define the function for the timer
def countdowntimer():
times = int(hrs.get())*3600+ int(mins.get())*60 + int(sec.get())
while times > -1:
minute,second = (times // 60 , times % 60)
hour =0
if minute > 60:
hour , minute = (minute // 60 , minute % 60)
sec.set(second)
mins.set(minute)
hrs.set(hour)
#Update the time
win.update()
time.sleep(1)
if(times == 0):
sec.set('00')
mins.set('00')
hrs.set('00')
times -= 1
Label(win, font =('Helvetica bold',22), text = 'Set the Timer',bg
='burlywood1').place(x=105,y=70)
Button(win, text='START', bd ='2', bg = 'IndianRed1',font =('Helvetica
bold',10), command = countdowntimer).place(x=167, y=165)
win.mainloop()
The above code will display a clock timer.
Now, set the timer by inserting some value in the box and click the "START" button to start the timer. | [
{
"code": null,
"e": 1184,
"s": 1062,
"text": "In this example, we will create a timer using Python Tkinter. For displaying time, we will use the Time Module in Python."
},
{
"code": null,
"e": 1243,
"s": 1184,
"text": "Initially, we will follow these steps to create the timer,"
},
{
"code": null,
"e": 1339,
"s": 1243,
"text": "Create three entry widget each for Hours, Minute and Seconds and set the value ‘00’ by default."
},
{
"code": null,
"e": 1422,
"s": 1339,
"text": "Create a Button for setting the timer. It will call the function countdowntimer()."
},
{
"code": null,
"e": 1526,
"s": 1422,
"text": "Define a function countdowntimer() which does update once we click on the button to propagate the time."
},
{
"code": null,
"e": 2888,
"s": 1526,
"text": "#Import the required library\nfrom tkinter import *\nimport time\n#Create an instance of tkinter frame\nwin = Tk()\nwin.geometry('750x300')\nwin.resizable(False,False)\n#Configure the background\nwin.config(bg='burlywood1')\n#Create Entry Widgets for HH MM SS\nsec = StringVar()\nEntry(win, textvariable=sec, width = 2, font = 'Helvetica 14').place(x=220, y=120)\nsec.set('00')\nmins= StringVar()\nEntry(win, textvariable = mins, width =2, font = 'Helvetica\n14').place(x=180, y=120)\nmins.set('00')\nhrs= StringVar()\nEntry(win, textvariable = hrs, width =2, font = 'Helvetica 14').place(x=142, y=120)\nhrs.set('00')\n#Define the function for the timer\ndef countdowntimer():\n times = int(hrs.get())*3600+ int(mins.get())*60 + int(sec.get())\n while times > -1:\n minute,second = (times // 60 , times % 60)\n hour =0\n if minute > 60:\n hour , minute = (minute // 60 , minute % 60)\n sec.set(second)\n mins.set(minute)\n hrs.set(hour)\n #Update the time\n win.update()\n time.sleep(1)\n if(times == 0):\n sec.set('00')\n mins.set('00')\n hrs.set('00')\n times -= 1\nLabel(win, font =('Helvetica bold',22), text = 'Set the Timer',bg\n='burlywood1').place(x=105,y=70)\nButton(win, text='START', bd ='2', bg = 'IndianRed1',font =('Helvetica\nbold',10), command = countdowntimer).place(x=167, y=165)\nwin.mainloop()"
},
{
"code": null,
"e": 2931,
"s": 2888,
"text": "The above code will display a clock timer."
},
{
"code": null,
"e": 3034,
"s": 2931,
"text": "Now, set the timer by inserting some value in the box and click the \"START\" button to start the timer."
}
] |
Find temperature of missing days using given sum and average - GeeksforGeeks | 01 Apr, 2021
Given integers x and y which denotes the average temperature of the week except for days Day1 and Day2 respectively, and the sum of the temperature of Day1 and Day2 as S, the task is to find the temperature of the days Day1 and Day2.Examples:
Input: x = 15, y = 10, S = 50 Output: Day1 = 10, Day2 = 40 Explanation: The average of week excluding Day1 is 15, the average of week excluding Day2 is 10 and the sum of temperature of Day1 and Day2 is 50. Individual temperature of the two days are 10 and 40 respecticvely.Input: x = 5, y = 10, s = 40 Output: Day1 = 35, Day2 = 5 Explanation: The average of week excluding Day1 is 5, the average of week excluding Day2 is 10 and the sum of temperature of Day1 and Day2 is 40. Individual temperature of the two days are 35 and 5 respecticvely.
Approach: We know that Average = sum of all observation / total number of observation. Hence, the sum of observation = Average * number of observation i.e., S = A * n
So after excluding Day1 or Day2 we are left with only 6 days so N = 6 and the equations are:
and
on subtracting the above two equations we get,
(Equation 1) and it is given in the problem statement that
(Equation 2)
Solving the above two equations, the value of Day1 and Day2 is given by:
[Tex]Day1 = S – Day2 [/Tex]
Below is the implementation of above approach:
C++
Java
Python
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function for finding the temperaturevoid findTemperature(int x, int y, int s){ double Day1, Day2; // Store Day1 - Day2 in diff double diff = (x - y) * 6; Day2 = (diff + s) / 2; // Remaining from s will be Day1 Day1 = s - Day2; // Print Day1 and Day2 cout << "Day1 : " << Day1 << endl; cout << "Day2 : " << Day2 << endl;} // Driver Codeint main(){ int x = 5, y = 10, s = 40; // Functions findTemperature(x, y, s); return 0;}
// Java program for the above approachclass GFG{ // Function for finding the temperaturestatic void findTemperature(int x, int y, int s){ double Day1, Day2; // Store Day1 - Day2 in diff double diff = (x - y) * 6; Day2 = (diff + s) / 2; // Remaining from s will be Day1 Day1 = s - Day2; // Print Day1 and Day2 System.out.println( "Day1 : " + Day1); System.out.println( "Day2 : " + Day2);} // Driver Codepublic static void main(String[] args){ int x = 5, y = 10, s = 40; // Functions findTemperature(x, y, s);}} // This code is contributed by rock_cool
# Python3 program for the above approach # Function for finding the temperaturedef findTemperature(x, y, s): # Store Day1 - Day2 in diff diff = (x - y) * 6 Day2 = (diff + s) // 2 # Remaining from s will be Day1 Day1 = s - Day2 # Print Day1 and Day2 print("Day1 : ", Day1) print("Day2 : ", Day2) # Driver Codeif __name__ == '__main__': x = 5 y = 10 s = 40 # Functions findTemperature(x, y, s) # This code is contributed by Mohit Kumar
// C# program for the above approachusing System;class GFG{ // Function for finding the temperaturestatic void findTemperature(int x, int y, int s){ double Day1, Day2; // Store Day1 - Day2 in diff double diff = (x - y) * 6; Day2 = (diff + s) / 2; // Remaining from s will be Day1 Day1 = s - Day2; // Print Day1 and Day2 Console.Write( "Day1 : " + Day1 + '\n'); Console.WriteLine( "Day2 : " + Day2 + '\n');} // Driver Codepublic static void Main(string[] args){ int x = 5, y = 10, s = 40; // Functions findTemperature(x, y, s);}} // This code is contributed by Ritik Bansal
<script> // Javascript program for the above approach // Function for finding the temperature function findTemperature(x, y, s) { let Day1, Day2; // Store Day1 - Day2 in diff let diff = (x - y) * 6; Day2 = (diff + s) / 2; // Remaining from s will be Day1 Day1 = s - Day2; // Print Day1 and Day2 document.write("Day1 : " + Day1 + "</br>"); document.write("Day2 : " + Day2 + "</br>"); } let x = 5, y = 10, s = 40; // Functions findTemperature(x, y, s); </script>
Day1 : 35
Day2 : 5
Time Complexity: O(1) Auxiliary Space: O(1)
mohit kumar 29
rock_cool
bansal_rtk_
nidhi_biet
mukesh07
school-programming
Mathematical
Puzzles
Mathematical
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo Operator (%) in C/C++ with Examples
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Euclidean algorithms (Basic and Extended)
SDE SHEET - A Complete Guide for SDE Preparation
Puzzle 1 | (How to Measure 45 minutes using two identical wires?)
Puzzle 2 | (Find ages of daughters)
Algorithm to solve Rubik's Cube
Puzzle 3 | (Calculate total distance travelled by bee) | [
{
"code": null,
"e": 25231,
"s": 25203,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 25476,
"s": 25231,
"text": "Given integers x and y which denotes the average temperature of the week except for days Day1 and Day2 respectively, and the sum of the temperature of Day1 and Day2 as S, the task is to find the temperature of the days Day1 and Day2.Examples: "
},
{
"code": null,
"e": 26021,
"s": 25476,
"text": "Input: x = 15, y = 10, S = 50 Output: Day1 = 10, Day2 = 40 Explanation: The average of week excluding Day1 is 15, the average of week excluding Day2 is 10 and the sum of temperature of Day1 and Day2 is 50. Individual temperature of the two days are 10 and 40 respecticvely.Input: x = 5, y = 10, s = 40 Output: Day1 = 35, Day2 = 5 Explanation: The average of week excluding Day1 is 5, the average of week excluding Day2 is 10 and the sum of temperature of Day1 and Day2 is 40. Individual temperature of the two days are 35 and 5 respecticvely. "
},
{
"code": null,
"e": 26191,
"s": 26023,
"text": "Approach: We know that Average = sum of all observation / total number of observation. Hence, the sum of observation = Average * number of observation i.e., S = A * n "
},
{
"code": null,
"e": 26286,
"s": 26191,
"text": "So after excluding Day1 or Day2 we are left with only 6 days so N = 6 and the equations are: "
},
{
"code": null,
"e": 26294,
"s": 26288,
"text": "and "
},
{
"code": null,
"e": 26345,
"s": 26296,
"text": "on subtracting the above two equations we get, "
},
{
"code": null,
"e": 26408,
"s": 26347,
"text": "(Equation 1) and it is given in the problem statement that "
},
{
"code": null,
"e": 26425,
"s": 26410,
"text": "(Equation 2) "
},
{
"code": null,
"e": 26502,
"s": 26427,
"text": "Solving the above two equations, the value of Day1 and Day2 is given by: "
},
{
"code": null,
"e": 26531,
"s": 26502,
"text": "[Tex]Day1 = S – Day2 [/Tex]"
},
{
"code": null,
"e": 26579,
"s": 26531,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 26583,
"s": 26579,
"text": "C++"
},
{
"code": null,
"e": 26588,
"s": 26583,
"text": "Java"
},
{
"code": null,
"e": 26595,
"s": 26588,
"text": "Python"
},
{
"code": null,
"e": 26598,
"s": 26595,
"text": "C#"
},
{
"code": null,
"e": 26609,
"s": 26598,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function for finding the temperaturevoid findTemperature(int x, int y, int s){ double Day1, Day2; // Store Day1 - Day2 in diff double diff = (x - y) * 6; Day2 = (diff + s) / 2; // Remaining from s will be Day1 Day1 = s - Day2; // Print Day1 and Day2 cout << \"Day1 : \" << Day1 << endl; cout << \"Day2 : \" << Day2 << endl;} // Driver Codeint main(){ int x = 5, y = 10, s = 40; // Functions findTemperature(x, y, s); return 0;}",
"e": 27164,
"s": 26609,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function for finding the temperaturestatic void findTemperature(int x, int y, int s){ double Day1, Day2; // Store Day1 - Day2 in diff double diff = (x - y) * 6; Day2 = (diff + s) / 2; // Remaining from s will be Day1 Day1 = s - Day2; // Print Day1 and Day2 System.out.println( \"Day1 : \" + Day1); System.out.println( \"Day2 : \" + Day2);} // Driver Codepublic static void main(String[] args){ int x = 5, y = 10, s = 40; // Functions findTemperature(x, y, s);}} // This code is contributed by rock_cool",
"e": 27763,
"s": 27164,
"text": null
},
{
"code": "# Python3 program for the above approach # Function for finding the temperaturedef findTemperature(x, y, s): # Store Day1 - Day2 in diff diff = (x - y) * 6 Day2 = (diff + s) // 2 # Remaining from s will be Day1 Day1 = s - Day2 # Print Day1 and Day2 print(\"Day1 : \", Day1) print(\"Day2 : \", Day2) # Driver Codeif __name__ == '__main__': x = 5 y = 10 s = 40 # Functions findTemperature(x, y, s) # This code is contributed by Mohit Kumar",
"e": 28240,
"s": 27763,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function for finding the temperaturestatic void findTemperature(int x, int y, int s){ double Day1, Day2; // Store Day1 - Day2 in diff double diff = (x - y) * 6; Day2 = (diff + s) / 2; // Remaining from s will be Day1 Day1 = s - Day2; // Print Day1 and Day2 Console.Write( \"Day1 : \" + Day1 + '\\n'); Console.WriteLine( \"Day2 : \" + Day2 + '\\n');} // Driver Codepublic static void Main(string[] args){ int x = 5, y = 10, s = 40; // Functions findTemperature(x, y, s);}} // This code is contributed by Ritik Bansal",
"e": 28868,
"s": 28240,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function for finding the temperature function findTemperature(x, y, s) { let Day1, Day2; // Store Day1 - Day2 in diff let diff = (x - y) * 6; Day2 = (diff + s) / 2; // Remaining from s will be Day1 Day1 = s - Day2; // Print Day1 and Day2 document.write(\"Day1 : \" + Day1 + \"</br>\"); document.write(\"Day2 : \" + Day2 + \"</br>\"); } let x = 5, y = 10, s = 40; // Functions findTemperature(x, y, s); </script>",
"e": 29434,
"s": 28868,
"text": null
},
{
"code": null,
"e": 29455,
"s": 29436,
"text": "Day1 : 35\nDay2 : 5"
},
{
"code": null,
"e": 29504,
"s": 29459,
"text": "Time Complexity: O(1) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 29521,
"s": 29506,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 29531,
"s": 29521,
"text": "rock_cool"
},
{
"code": null,
"e": 29543,
"s": 29531,
"text": "bansal_rtk_"
},
{
"code": null,
"e": 29554,
"s": 29543,
"text": "nidhi_biet"
},
{
"code": null,
"e": 29563,
"s": 29554,
"text": "mukesh07"
},
{
"code": null,
"e": 29582,
"s": 29563,
"text": "school-programming"
},
{
"code": null,
"e": 29595,
"s": 29582,
"text": "Mathematical"
},
{
"code": null,
"e": 29603,
"s": 29595,
"text": "Puzzles"
},
{
"code": null,
"e": 29616,
"s": 29603,
"text": "Mathematical"
},
{
"code": null,
"e": 29624,
"s": 29616,
"text": "Puzzles"
},
{
"code": null,
"e": 29722,
"s": 29624,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29765,
"s": 29722,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 29814,
"s": 29765,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 29848,
"s": 29814,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 29869,
"s": 29848,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 29911,
"s": 29869,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 29960,
"s": 29911,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30026,
"s": 29960,
"text": "Puzzle 1 | (How to Measure 45 minutes using two identical wires?)"
},
{
"code": null,
"e": 30062,
"s": 30026,
"text": "Puzzle 2 | (Find ages of daughters)"
},
{
"code": null,
"e": 30094,
"s": 30062,
"text": "Algorithm to solve Rubik's Cube"
}
] |
3D Point Cloud processing tutorial by F. Poux | Towards Data Science | In this article, I will give you my two favourite 3D processes for quickly structuring and sub-sampling point cloud data with python. You will also be able to automate, export, visualize and integrate results into your favourite 3D software, without any coding experience. I will focus on code optimization while using a minimum number of libraries (mainly NumPy) so that you can extend what you learnt with very high flexibility! Ready 😁?
Point cloud datasets are marvellous! You can get a geometric description of world entities by discretizing them through a bunch of points, which, aggregated together, resemble the shape — the environment — of interest.
But a major problem with 3D point clouds is that the data density may be more than necessary for a given application. This often leads to higher computational cost in subsequent data processing or visualisation. To make the dense point clouds more manageable, their data density can be reduced. This article provides you with the knowledge and actual scripts to implement sub-sampling methods for reducing point cloud data density.
Let us dive in 🤿!
Ha, I tricked you 🙃. Before directly diving to the implementation of sampling strategies, let us first review the typical sub-sampling methods for point cloud data thinning. These include the random, the minimal distance and the grid (often tagged as uniform) methods. The random method is the simplest for reducing data density, in which a specified number of data points is selected randomly.
In the minimal distance method, the data point selection is constrained by a minimum distance so that no data point in the selected subset is closer to another data point than the minimum distance specified.
In the grid method (which can be uniform), a grid structure — the handier being a voxel grid structure — is created and a representative data point is selected.
The latter two methods can achieve a more homogeneous spatial distribution of data points in the reduced point cloud. In such cases, the average data spacing is determined by the minimal distance or the voxel edge length specified. If you want extended details, you can follow the eLearning Formation below:
learngeodata.eu
Okay for the theory, let us put it into action 🤠!
In the previous article below, we saw how to set-up an environment easily with Anaconda and how to use the IDE Spyder for managing your code. I recommend continuing in this fashion if you set yourself up to becoming a fully-fledge python app developer 😆.
towardsdatascience.com
But hey, if you prefer to do everything from scratch in the next 5 minutes, I also give you access to a Google Colab notebook that you will find at the end of the article. There is nothing to install; you can just save it to your google drive and start working with it, also using the free datasets from Step 2 👇.
In previous tutorials, I illustrated point cloud processing and meshing over a 3D dataset obtained by using photogrammetry: the jaguar, that you can freely download from this repository.
In this tutorial, we will extend the scope, and test on a point cloud obtained through an aerial LiDAR survey. This is an excellent opportunity to introduce you to the great Open Data platform: Open Topography. It is a collaborative data repository for LiDAR users. Through a web map, you can select a region of interest, and download the related point cloud dataset with its metadata in different file formats (.laz, .las or as an ASCII file).
At this phase, what is important to know is that you can easily process both the ASCII file and the .las file with python (the .laz is more tricky). The .las file is far more compressed than the ASCII file (355 Mo vs 1026 Mo for the example in this guide), but it will necessitate that you use a library called LasPy. So now, if you need 3D point cloud datasets over a large region, you know where you can find great datasets easily 🗺️.
🤓 Note: For this how-to guide, you can use the point cloud in this repository, that I already filtered, colourized and translated so that you are in the optimal conditions. If you want to visualize and play with it beforehand without installing anything, you can check out the webGL version.
Okay, now that we are set-up, let us write some code 💻. First, we install the library package that is missing to read .las files. If you are with anaconda, I suggest you run the following command by looking up the conda-forge channel:
conda install -c conda-forge
Else, in general, you can use the pip package installer for Python by typing:
pip install laspy
Then, let us import necessary libraries within the script (NumPy and LasPy), and load the .las file in a variable called point_cloud.
import numpy as npimport laspy as lpinput_path="gdrive/My Drive/10-MEDIUM/DATA/Point Cloud Sample/"dataname="NZ19_Wellington.las"point_cloud=lp.file.File(input_path+dataname+".las", mode="r")
Nice, we are almost ready! What is great, is that the LasPy library also give a structure to the point_cloud variable, and we can use straightforward methods to get, for example, X, Y, Z, Red, Blue and Green fields. Let us do this to separate coordinates from colours, and put them in NumPy arrays:
points = np.vstack((point_cloud.x, point_cloud.y, point_cloud.z)).transpose()colors = np.vstack((point_cloud.red, point_cloud.green, point_cloud.blue)).transpose()
🤓 Note: We use a vertical stack method from NumPy, and we have to transpose it to get from (n x 3) to a (3 x n) matrix of the point cloud.
And we are set up! Moving on to step 3 👇.
We will focus on decimation and voxel grid sampling. Now is the time to pick a side 🙂
💡 Hint: I will give you code scripts that actually maximize the use of NumPy, but know that you can achieve similar results with widely different implementations (or through importing other packages). The main difference is often the execution time. The goal is to have the best execution runtime while having a readable script.
If we define a point cloud as a matrix (m x n), then the decimated cloud is obtained by keeping one row out of n of this matrix :
Slicing a list in python is pretty simple with the command l[start:end:step]. To shorten and parametrize the expression, you can just write the lines:
factor=160decimated_points_random = points[::factor]
🤓 Note: Running this will keep 1 row every 160 rows, thus diving the size of the original point cloud by 160. It goes from 13 993 118 points to 87 457 points.
The grid subsampling strategy will be based on the division of the 3D space in regular cubic cells called voxels. For each cell of this grid, we will only keep one representative point. This point, the representant of the cell, can be chosen in different ways. For example, it can be the barycenter of the points in that cell, or the closest point to it.
We will work in two sub-steps.
1. First, we create a grid structure over the points. For this, we actually want to initially compute the bounding box of the point cloud (i.e. the box dimensions that englobe all the points). Then, we can discretize the bounding box into small cubic grids: the voxels. These are obtained by setting the length, width and height of the voxel (which is equal), but it could also be set by giving the number of desired voxels in the three directions of the bounding box.
voxel_size=6nb_vox=np.ceil((np.max(points, axis=0) - np.min(points, axis=0))/voxel_size)
🤓 Note: You can see the little axis=0 that is actually fundamental if you want to be sure you apply the max method “per column”. The ceil then will make sure to keep the ceiling of the difference (element-wise), and thus, when divided by the voxel_size, it returns the number of empty voxels in each direction. With a cubic size of 6 m, we get 254 voxels along X, 154 voxels along Y and 51 along Z: 1 994 916 empty voxels.
2. For each small voxel, we test if it contains one or more points. If it does, we keep it, and we take note of the points indexes that we will have to link to each voxel.
non_empty_voxel_keys, inverse, nb_pts_per_voxel = np.unique(((points - np.min(points, axis=0)) // voxel_size).astype(int), axis=0, return_inverse=True, return_counts=True)idx_pts_vox_sorted=np.argsort(inverse)
🤓 Note: We want to work with indices rather than coordinates for simplicity and efficiency. The little script above is a super-compact way to return the “designation” of each non-empty voxel. On top, we want to access the points that are linked to each non_empty_voxel through idx_pts_vox_sorted, and how many there are (nb_pts_per_voxel). This is done by first looking out unique values based on the integer “indices” gathered for each point. The argsort method is actually returning the index of the points that we can later link to the voxel index.
3. Finally, we compute the representant of the voxel. I will illustrate this for both the barycenter (grid_barycenter) and the closest point to the barycenter (grid_candidate_center).
💡 Hint: The use of python dictionaries to keep the points in each voxel is my recommendation. This sparse structure is more adapted than full arrays which will use all your memory on bigger point clouds. A dictionary cannot take a [i, j, k] vector of coordinates as key if it is a list, but converting it to a tuple (i, j, k) will make it work.
We initialise self-explanatory variables of which a counter last_seen:
voxel_grid={}grid_barycenter,grid_candidate_center=[],[]last_seen=0
We create a loop that will iterate over each non-empty voxel, while allowing to work with both the index idx of the array, and the value vox, which is actually the [i, j, k] of the voxel.
for idx,vox in enumerate(non_empty_voxel_keys):
Then (don’t forget to indent) we feed the loop with a way to complete the voxel_grid dictionary with contained points.
voxel_grid[tuple(vox)]= points[idx_pts_vox_sorted[ last_seen:last_seen+nb_pts_per_voxel[idx]]]
Still in the loop, you can now pick/compute the representative of the voxel. It can be the barycenter that you append to the list of all barycenters:
grid_barycenter.append(np.mean(voxel_grid[tuple(vox)],axis=0))
Or it can be the closest point to the barycenter (uses Euclidean distances):
grid_candidate_center.append( voxel_grid[tuple(vox)][np.linalg.norm(voxel_grid[tuple(vox)] - np.mean(voxel_grid[tuple(vox)],axis=0),axis=1).argmin()])
Finally, don’t forget to update your counter, to make sure the selection in the array of points is correct:
last_seen+=nb_pts_per_voxel[idx]
🤓 Note: Most of my M.Sc. students will accomplish the task with a bunch of imbricated “for” or “while” loop. It does work, but it is not the most efficient. You have to know Python is not very optimized with loops. Thus, when processing point clouds (which are often massive), you should aim at a minimal amount of loops, and a maximum amount of “vectorization”. With NumPy, this is by “broadcasting”, a mean of vectorizing array operations so that looping occurs in C instead of Python (more efficient). Take the time to digest what I do in this third step (especially the details of playing with indexes and voxels), or check out the Google Colab script for more in-depth information.
This voxel sampling strategy is usually very efficient, relatively uniform, and useful for downward processes (but this extend the scope of the current tutorial). However, you should know that while the point spacing can be controlled by the size of the grid, we cannot “accurately” control the number of sampling points.
To simply visualize in-line your results (or within Python), you can use the matplotlib library, with its 3D toolkit (see the previous article for understanding what happens under the hood). Run the following command, illustrated over the decimated point cloud :
import matplotlib.pyplot as pltfrom mpl_toolkits import mplot3ddecimated_colors = colors[::factor]ax = plt.axes(projection='3d')ax.scatter(decimated_points[:,0], decimated_points[:,1], decimated_points[:,2], c = decimated_colors/65535, s=0.01)plt.show()
🤓 Note: Looking at the number of possible points, I would not recommend in-line visualisation with classical libraries such as matplotlib if your subsampled results exceed the million mark.
In the very likely event your point cloud is too heavy for visualizing this way, you can export the data in an eatable file format for your software of choice. To get an ASCII file, you can use the command:
np.savetxt(output_path+dataname+"_voxel-best_point_%s.poux" % (voxel_size), grid_candidate_center, delimiter=";", fmt="%s")
🤓 Note: A “;” delimited ASCII file is created, ending with .poux 🤭. The “fmt” command is to make sure the writing is most standard, for example as a string.
💡 Hint: If you also want to make operations to retrieve the colour of voxels representatives, be careful with the NumPy dtype of the sum of colours. The colour type “uint16” can take values from 0 to 65535. Change the type when summing and go to uint16 (or uint8) after the final division.
Now that you addressed steps 1 to 4, it is time to create functions and put them together in an automated fashion 🤖. Basically, we want (a) to load the data and libraries, (b) set parameters value, (c) declare functions, (d) call them when needed, (e) return some kind of results. This can be to show in-line the results and/or to export a sampled point cloud file to be used in your 3D software, outside of Python.
You already know how to do a, b and e, so let us focus on b and c 🎯. To create a function, you can just follow the provided template below:
def cloud_decimation(points, factor): # YOUR CODE TO EXECUTE return decimated_points
🤓 Note: The function created is called cloud_decimation, and eats two arguments which are points and factor. It will execute the desired code written inside and return the variable decimated_points when it is called. and to call a function, nothing more straightforward: simply write cloud_decimation(point_cloud, 6) (the same way you would use the function print(), but here you have two arguments to fill by the values/variables that you want to pass to the function).
By creating a suite of functions, you can then use your script directly, just changing the set parameters at the beginning.
The full code is accessible here: Google Colab notebook.
Additionally, you can check out the follow-up article if you want to extend your capabilities using the library Open3D, and learn specific commands related to 3D point clouds and 3D mesh processing.
towardsdatascience.com
You just learned how to import, sub-sample, export and visualize a point cloud composed of millions of points, with different strategies! Well done! But the path does not end here, and future posts will dive deeper in point cloud spatial analysis, file formats, data structures, visualization, animation and meshing. We will especially look into how to manage big point cloud data as defined in the article below.
towardsdatascience.com
My contributions aim to condense actionable information so you can start from scratch to build 3D automation systems for your projects. You can get started today by taking a formation at the Geodata Academy.
learngeodata.eu
Other advanced sampling methods for point cloud exist. For example, you could follow a uniform sampling method such as the Farthest Point method, a more advanced geometric sampling [1] or even semantic sampling. Also, the voxelisation algorithm given here can be used for advanced processing such as 3D semantic modelling [2] or semantic segmentation, as shown in [3].
1. Fernández-Martínez J.L., Tompkins M., Mukerji T., Alumbaugh D. (2010) Geometric Sampling: An Approach to Uncertainty in High Dimensional Spaces. Advances in Intelligent and Soft Computing. 2010, vol 77. Springer, Berlin, Heidelberg. https://doi.org/10.1007/978-3-642-14746-3_31
2. Poux, F.; Neuville, R.; Nys, G.-A.; Billen, R. 3D Point Cloud Semantic Modelling: Integrated Framework for Indoor Spaces and Furniture. Remote Sens. 2018, 10, 1412. https://doi.org/10.3390/rs10091412
3. Poux, F.; Billen, R. Voxel-based 3D Point Cloud Semantic Segmentation: Unsupervised Geometric and Relationship Featuring vs Deep Learning Methods. ISPRS Int. J. Geo-Inf. 2019, 8, 213. https://doi.org/10.3390/ijgi8050213 | [
{
"code": null,
"e": 612,
"s": 172,
"text": "In this article, I will give you my two favourite 3D processes for quickly structuring and sub-sampling point cloud data with python. You will also be able to automate, export, visualize and integrate results into your favourite 3D software, without any coding experience. I will focus on code optimization while using a minimum number of libraries (mainly NumPy) so that you can extend what you learnt with very high flexibility! Ready 😁?"
},
{
"code": null,
"e": 831,
"s": 612,
"text": "Point cloud datasets are marvellous! You can get a geometric description of world entities by discretizing them through a bunch of points, which, aggregated together, resemble the shape — the environment — of interest."
},
{
"code": null,
"e": 1263,
"s": 831,
"text": "But a major problem with 3D point clouds is that the data density may be more than necessary for a given application. This often leads to higher computational cost in subsequent data processing or visualisation. To make the dense point clouds more manageable, their data density can be reduced. This article provides you with the knowledge and actual scripts to implement sub-sampling methods for reducing point cloud data density."
},
{
"code": null,
"e": 1281,
"s": 1263,
"text": "Let us dive in 🤿!"
},
{
"code": null,
"e": 1676,
"s": 1281,
"text": "Ha, I tricked you 🙃. Before directly diving to the implementation of sampling strategies, let us first review the typical sub-sampling methods for point cloud data thinning. These include the random, the minimal distance and the grid (often tagged as uniform) methods. The random method is the simplest for reducing data density, in which a specified number of data points is selected randomly."
},
{
"code": null,
"e": 1884,
"s": 1676,
"text": "In the minimal distance method, the data point selection is constrained by a minimum distance so that no data point in the selected subset is closer to another data point than the minimum distance specified."
},
{
"code": null,
"e": 2045,
"s": 1884,
"text": "In the grid method (which can be uniform), a grid structure — the handier being a voxel grid structure — is created and a representative data point is selected."
},
{
"code": null,
"e": 2353,
"s": 2045,
"text": "The latter two methods can achieve a more homogeneous spatial distribution of data points in the reduced point cloud. In such cases, the average data spacing is determined by the minimal distance or the voxel edge length specified. If you want extended details, you can follow the eLearning Formation below:"
},
{
"code": null,
"e": 2369,
"s": 2353,
"text": "learngeodata.eu"
},
{
"code": null,
"e": 2419,
"s": 2369,
"text": "Okay for the theory, let us put it into action 🤠!"
},
{
"code": null,
"e": 2674,
"s": 2419,
"text": "In the previous article below, we saw how to set-up an environment easily with Anaconda and how to use the IDE Spyder for managing your code. I recommend continuing in this fashion if you set yourself up to becoming a fully-fledge python app developer 😆."
},
{
"code": null,
"e": 2697,
"s": 2674,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3011,
"s": 2697,
"text": "But hey, if you prefer to do everything from scratch in the next 5 minutes, I also give you access to a Google Colab notebook that you will find at the end of the article. There is nothing to install; you can just save it to your google drive and start working with it, also using the free datasets from Step 2 👇."
},
{
"code": null,
"e": 3198,
"s": 3011,
"text": "In previous tutorials, I illustrated point cloud processing and meshing over a 3D dataset obtained by using photogrammetry: the jaguar, that you can freely download from this repository."
},
{
"code": null,
"e": 3643,
"s": 3198,
"text": "In this tutorial, we will extend the scope, and test on a point cloud obtained through an aerial LiDAR survey. This is an excellent opportunity to introduce you to the great Open Data platform: Open Topography. It is a collaborative data repository for LiDAR users. Through a web map, you can select a region of interest, and download the related point cloud dataset with its metadata in different file formats (.laz, .las or as an ASCII file)."
},
{
"code": null,
"e": 4080,
"s": 3643,
"text": "At this phase, what is important to know is that you can easily process both the ASCII file and the .las file with python (the .laz is more tricky). The .las file is far more compressed than the ASCII file (355 Mo vs 1026 Mo for the example in this guide), but it will necessitate that you use a library called LasPy. So now, if you need 3D point cloud datasets over a large region, you know where you can find great datasets easily 🗺️."
},
{
"code": null,
"e": 4372,
"s": 4080,
"text": "🤓 Note: For this how-to guide, you can use the point cloud in this repository, that I already filtered, colourized and translated so that you are in the optimal conditions. If you want to visualize and play with it beforehand without installing anything, you can check out the webGL version."
},
{
"code": null,
"e": 4607,
"s": 4372,
"text": "Okay, now that we are set-up, let us write some code 💻. First, we install the library package that is missing to read .las files. If you are with anaconda, I suggest you run the following command by looking up the conda-forge channel:"
},
{
"code": null,
"e": 4636,
"s": 4607,
"text": "conda install -c conda-forge"
},
{
"code": null,
"e": 4714,
"s": 4636,
"text": "Else, in general, you can use the pip package installer for Python by typing:"
},
{
"code": null,
"e": 4732,
"s": 4714,
"text": "pip install laspy"
},
{
"code": null,
"e": 4866,
"s": 4732,
"text": "Then, let us import necessary libraries within the script (NumPy and LasPy), and load the .las file in a variable called point_cloud."
},
{
"code": null,
"e": 5058,
"s": 4866,
"text": "import numpy as npimport laspy as lpinput_path=\"gdrive/My Drive/10-MEDIUM/DATA/Point Cloud Sample/\"dataname=\"NZ19_Wellington.las\"point_cloud=lp.file.File(input_path+dataname+\".las\", mode=\"r\")"
},
{
"code": null,
"e": 5357,
"s": 5058,
"text": "Nice, we are almost ready! What is great, is that the LasPy library also give a structure to the point_cloud variable, and we can use straightforward methods to get, for example, X, Y, Z, Red, Blue and Green fields. Let us do this to separate coordinates from colours, and put them in NumPy arrays:"
},
{
"code": null,
"e": 5521,
"s": 5357,
"text": "points = np.vstack((point_cloud.x, point_cloud.y, point_cloud.z)).transpose()colors = np.vstack((point_cloud.red, point_cloud.green, point_cloud.blue)).transpose()"
},
{
"code": null,
"e": 5660,
"s": 5521,
"text": "🤓 Note: We use a vertical stack method from NumPy, and we have to transpose it to get from (n x 3) to a (3 x n) matrix of the point cloud."
},
{
"code": null,
"e": 5702,
"s": 5660,
"text": "And we are set up! Moving on to step 3 👇."
},
{
"code": null,
"e": 5788,
"s": 5702,
"text": "We will focus on decimation and voxel grid sampling. Now is the time to pick a side 🙂"
},
{
"code": null,
"e": 6117,
"s": 5788,
"text": "💡 Hint: I will give you code scripts that actually maximize the use of NumPy, but know that you can achieve similar results with widely different implementations (or through importing other packages). The main difference is often the execution time. The goal is to have the best execution runtime while having a readable script."
},
{
"code": null,
"e": 6247,
"s": 6117,
"text": "If we define a point cloud as a matrix (m x n), then the decimated cloud is obtained by keeping one row out of n of this matrix :"
},
{
"code": null,
"e": 6398,
"s": 6247,
"text": "Slicing a list in python is pretty simple with the command l[start:end:step]. To shorten and parametrize the expression, you can just write the lines:"
},
{
"code": null,
"e": 6451,
"s": 6398,
"text": "factor=160decimated_points_random = points[::factor]"
},
{
"code": null,
"e": 6610,
"s": 6451,
"text": "🤓 Note: Running this will keep 1 row every 160 rows, thus diving the size of the original point cloud by 160. It goes from 13 993 118 points to 87 457 points."
},
{
"code": null,
"e": 6965,
"s": 6610,
"text": "The grid subsampling strategy will be based on the division of the 3D space in regular cubic cells called voxels. For each cell of this grid, we will only keep one representative point. This point, the representant of the cell, can be chosen in different ways. For example, it can be the barycenter of the points in that cell, or the closest point to it."
},
{
"code": null,
"e": 6996,
"s": 6965,
"text": "We will work in two sub-steps."
},
{
"code": null,
"e": 7465,
"s": 6996,
"text": "1. First, we create a grid structure over the points. For this, we actually want to initially compute the bounding box of the point cloud (i.e. the box dimensions that englobe all the points). Then, we can discretize the bounding box into small cubic grids: the voxels. These are obtained by setting the length, width and height of the voxel (which is equal), but it could also be set by giving the number of desired voxels in the three directions of the bounding box."
},
{
"code": null,
"e": 7554,
"s": 7465,
"text": "voxel_size=6nb_vox=np.ceil((np.max(points, axis=0) - np.min(points, axis=0))/voxel_size)"
},
{
"code": null,
"e": 7977,
"s": 7554,
"text": "🤓 Note: You can see the little axis=0 that is actually fundamental if you want to be sure you apply the max method “per column”. The ceil then will make sure to keep the ceiling of the difference (element-wise), and thus, when divided by the voxel_size, it returns the number of empty voxels in each direction. With a cubic size of 6 m, we get 254 voxels along X, 154 voxels along Y and 51 along Z: 1 994 916 empty voxels."
},
{
"code": null,
"e": 8149,
"s": 7977,
"text": "2. For each small voxel, we test if it contains one or more points. If it does, we keep it, and we take note of the points indexes that we will have to link to each voxel."
},
{
"code": null,
"e": 8359,
"s": 8149,
"text": "non_empty_voxel_keys, inverse, nb_pts_per_voxel = np.unique(((points - np.min(points, axis=0)) // voxel_size).astype(int), axis=0, return_inverse=True, return_counts=True)idx_pts_vox_sorted=np.argsort(inverse)"
},
{
"code": null,
"e": 8911,
"s": 8359,
"text": "🤓 Note: We want to work with indices rather than coordinates for simplicity and efficiency. The little script above is a super-compact way to return the “designation” of each non-empty voxel. On top, we want to access the points that are linked to each non_empty_voxel through idx_pts_vox_sorted, and how many there are (nb_pts_per_voxel). This is done by first looking out unique values based on the integer “indices” gathered for each point. The argsort method is actually returning the index of the points that we can later link to the voxel index."
},
{
"code": null,
"e": 9095,
"s": 8911,
"text": "3. Finally, we compute the representant of the voxel. I will illustrate this for both the barycenter (grid_barycenter) and the closest point to the barycenter (grid_candidate_center)."
},
{
"code": null,
"e": 9440,
"s": 9095,
"text": "💡 Hint: The use of python dictionaries to keep the points in each voxel is my recommendation. This sparse structure is more adapted than full arrays which will use all your memory on bigger point clouds. A dictionary cannot take a [i, j, k] vector of coordinates as key if it is a list, but converting it to a tuple (i, j, k) will make it work."
},
{
"code": null,
"e": 9511,
"s": 9440,
"text": "We initialise self-explanatory variables of which a counter last_seen:"
},
{
"code": null,
"e": 9579,
"s": 9511,
"text": "voxel_grid={}grid_barycenter,grid_candidate_center=[],[]last_seen=0"
},
{
"code": null,
"e": 9767,
"s": 9579,
"text": "We create a loop that will iterate over each non-empty voxel, while allowing to work with both the index idx of the array, and the value vox, which is actually the [i, j, k] of the voxel."
},
{
"code": null,
"e": 9815,
"s": 9767,
"text": "for idx,vox in enumerate(non_empty_voxel_keys):"
},
{
"code": null,
"e": 9934,
"s": 9815,
"text": "Then (don’t forget to indent) we feed the loop with a way to complete the voxel_grid dictionary with contained points."
},
{
"code": null,
"e": 10034,
"s": 9934,
"text": " voxel_grid[tuple(vox)]= points[idx_pts_vox_sorted[ last_seen:last_seen+nb_pts_per_voxel[idx]]]"
},
{
"code": null,
"e": 10184,
"s": 10034,
"text": "Still in the loop, you can now pick/compute the representative of the voxel. It can be the barycenter that you append to the list of all barycenters:"
},
{
"code": null,
"e": 10250,
"s": 10184,
"text": " grid_barycenter.append(np.mean(voxel_grid[tuple(vox)],axis=0))"
},
{
"code": null,
"e": 10327,
"s": 10250,
"text": "Or it can be the closest point to the barycenter (uses Euclidean distances):"
},
{
"code": null,
"e": 10485,
"s": 10327,
"text": " grid_candidate_center.append( voxel_grid[tuple(vox)][np.linalg.norm(voxel_grid[tuple(vox)] - np.mean(voxel_grid[tuple(vox)],axis=0),axis=1).argmin()])"
},
{
"code": null,
"e": 10593,
"s": 10485,
"text": "Finally, don’t forget to update your counter, to make sure the selection in the array of points is correct:"
},
{
"code": null,
"e": 10629,
"s": 10593,
"text": " last_seen+=nb_pts_per_voxel[idx]"
},
{
"code": null,
"e": 11316,
"s": 10629,
"text": "🤓 Note: Most of my M.Sc. students will accomplish the task with a bunch of imbricated “for” or “while” loop. It does work, but it is not the most efficient. You have to know Python is not very optimized with loops. Thus, when processing point clouds (which are often massive), you should aim at a minimal amount of loops, and a maximum amount of “vectorization”. With NumPy, this is by “broadcasting”, a mean of vectorizing array operations so that looping occurs in C instead of Python (more efficient). Take the time to digest what I do in this third step (especially the details of playing with indexes and voxels), or check out the Google Colab script for more in-depth information."
},
{
"code": null,
"e": 11638,
"s": 11316,
"text": "This voxel sampling strategy is usually very efficient, relatively uniform, and useful for downward processes (but this extend the scope of the current tutorial). However, you should know that while the point spacing can be controlled by the size of the grid, we cannot “accurately” control the number of sampling points."
},
{
"code": null,
"e": 11901,
"s": 11638,
"text": "To simply visualize in-line your results (or within Python), you can use the matplotlib library, with its 3D toolkit (see the previous article for understanding what happens under the hood). Run the following command, illustrated over the decimated point cloud :"
},
{
"code": null,
"e": 12155,
"s": 11901,
"text": "import matplotlib.pyplot as pltfrom mpl_toolkits import mplot3ddecimated_colors = colors[::factor]ax = plt.axes(projection='3d')ax.scatter(decimated_points[:,0], decimated_points[:,1], decimated_points[:,2], c = decimated_colors/65535, s=0.01)plt.show()"
},
{
"code": null,
"e": 12345,
"s": 12155,
"text": "🤓 Note: Looking at the number of possible points, I would not recommend in-line visualisation with classical libraries such as matplotlib if your subsampled results exceed the million mark."
},
{
"code": null,
"e": 12552,
"s": 12345,
"text": "In the very likely event your point cloud is too heavy for visualizing this way, you can export the data in an eatable file format for your software of choice. To get an ASCII file, you can use the command:"
},
{
"code": null,
"e": 12676,
"s": 12552,
"text": "np.savetxt(output_path+dataname+\"_voxel-best_point_%s.poux\" % (voxel_size), grid_candidate_center, delimiter=\";\", fmt=\"%s\")"
},
{
"code": null,
"e": 12833,
"s": 12676,
"text": "🤓 Note: A “;” delimited ASCII file is created, ending with .poux 🤭. The “fmt” command is to make sure the writing is most standard, for example as a string."
},
{
"code": null,
"e": 13123,
"s": 12833,
"text": "💡 Hint: If you also want to make operations to retrieve the colour of voxels representatives, be careful with the NumPy dtype of the sum of colours. The colour type “uint16” can take values from 0 to 65535. Change the type when summing and go to uint16 (or uint8) after the final division."
},
{
"code": null,
"e": 13539,
"s": 13123,
"text": "Now that you addressed steps 1 to 4, it is time to create functions and put them together in an automated fashion 🤖. Basically, we want (a) to load the data and libraries, (b) set parameters value, (c) declare functions, (d) call them when needed, (e) return some kind of results. This can be to show in-line the results and/or to export a sampled point cloud file to be used in your 3D software, outside of Python."
},
{
"code": null,
"e": 13679,
"s": 13539,
"text": "You already know how to do a, b and e, so let us focus on b and c 🎯. To create a function, you can just follow the provided template below:"
},
{
"code": null,
"e": 13768,
"s": 13679,
"text": "def cloud_decimation(points, factor): # YOUR CODE TO EXECUTE return decimated_points"
},
{
"code": null,
"e": 14239,
"s": 13768,
"text": "🤓 Note: The function created is called cloud_decimation, and eats two arguments which are points and factor. It will execute the desired code written inside and return the variable decimated_points when it is called. and to call a function, nothing more straightforward: simply write cloud_decimation(point_cloud, 6) (the same way you would use the function print(), but here you have two arguments to fill by the values/variables that you want to pass to the function)."
},
{
"code": null,
"e": 14363,
"s": 14239,
"text": "By creating a suite of functions, you can then use your script directly, just changing the set parameters at the beginning."
},
{
"code": null,
"e": 14420,
"s": 14363,
"text": "The full code is accessible here: Google Colab notebook."
},
{
"code": null,
"e": 14619,
"s": 14420,
"text": "Additionally, you can check out the follow-up article if you want to extend your capabilities using the library Open3D, and learn specific commands related to 3D point clouds and 3D mesh processing."
},
{
"code": null,
"e": 14642,
"s": 14619,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 15056,
"s": 14642,
"text": "You just learned how to import, sub-sample, export and visualize a point cloud composed of millions of points, with different strategies! Well done! But the path does not end here, and future posts will dive deeper in point cloud spatial analysis, file formats, data structures, visualization, animation and meshing. We will especially look into how to manage big point cloud data as defined in the article below."
},
{
"code": null,
"e": 15079,
"s": 15056,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 15287,
"s": 15079,
"text": "My contributions aim to condense actionable information so you can start from scratch to build 3D automation systems for your projects. You can get started today by taking a formation at the Geodata Academy."
},
{
"code": null,
"e": 15303,
"s": 15287,
"text": "learngeodata.eu"
},
{
"code": null,
"e": 15672,
"s": 15303,
"text": "Other advanced sampling methods for point cloud exist. For example, you could follow a uniform sampling method such as the Farthest Point method, a more advanced geometric sampling [1] or even semantic sampling. Also, the voxelisation algorithm given here can be used for advanced processing such as 3D semantic modelling [2] or semantic segmentation, as shown in [3]."
},
{
"code": null,
"e": 15955,
"s": 15672,
"text": "1. Fernández-Martínez J.L., Tompkins M., Mukerji T., Alumbaugh D. (2010) Geometric Sampling: An Approach to Uncertainty in High Dimensional Spaces. Advances in Intelligent and Soft Computing. 2010, vol 77. Springer, Berlin, Heidelberg. https://doi.org/10.1007/978-3-642-14746-3_31"
},
{
"code": null,
"e": 16158,
"s": 15955,
"text": "2. Poux, F.; Neuville, R.; Nys, G.-A.; Billen, R. 3D Point Cloud Semantic Modelling: Integrated Framework for Indoor Spaces and Furniture. Remote Sens. 2018, 10, 1412. https://doi.org/10.3390/rs10091412"
}
] |
Convert number to reversed array of digits JavaScript | Let’s say, we have to write a function that takes in a number and returns an array of numbers
with elements as the digits of the number but in reverse order. We will convert the number into a
string, then split it to get an array of strings of digit, then we will convert the string into numbers,
reverse the array and finally return it.
Following is our function that takes in a number to be reversed −
const reversifyNumber = (num) => {
const numString = String(num);
return numString.split("").map(el => {
return +el;
}).reverse();
};
const reversifyNumber = (num) => {
const numString = String(num);
return numString.split("").map(el => {
return +el;
}).reverse();
};
console.log(reversifyNumber(1245));
console.log(reversifyNumber(123));
console.log(reversifyNumber(5645));
console.log(reversifyNumber(645));
The output in the console will be −
[ 5, 4, 2, 1 ]
[ 3, 2, 1 ]
[ 5, 4, 6, 5 ]
[ 5, 4, 6 ] | [
{
"code": null,
"e": 1400,
"s": 1062,
"text": "Let’s say, we have to write a function that takes in a number and returns an array of numbers\nwith elements as the digits of the number but in reverse order. We will convert the number into a\nstring, then split it to get an array of strings of digit, then we will convert the string into numbers,\nreverse the array and finally return it."
},
{
"code": null,
"e": 1466,
"s": 1400,
"text": "Following is our function that takes in a number to be reversed −"
},
{
"code": null,
"e": 1615,
"s": 1466,
"text": "const reversifyNumber = (num) => {\n const numString = String(num);\n return numString.split(\"\").map(el => {\n return +el;\n }).reverse();\n};"
},
{
"code": null,
"e": 1906,
"s": 1615,
"text": "const reversifyNumber = (num) => {\n const numString = String(num);\n return numString.split(\"\").map(el => {\n return +el;\n }).reverse();\n};\nconsole.log(reversifyNumber(1245));\nconsole.log(reversifyNumber(123));\nconsole.log(reversifyNumber(5645));\nconsole.log(reversifyNumber(645));"
},
{
"code": null,
"e": 1942,
"s": 1906,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 1996,
"s": 1942,
"text": "[ 5, 4, 2, 1 ]\n[ 3, 2, 1 ]\n[ 5, 4, 6, 5 ]\n[ 5, 4, 6 ]"
}
] |
Creating a MySQL Table in NodeJS using Sequelize | Sequealize follows the promise-based Node.js ORM for different servers like – Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server.
Following are some of the main features of NodeJS sequelize −
Transaction Support
Transaction Support
Relations
Relations
Eager and Lazy Loading
Eager and Lazy Loading
Read Replication and more...
Read Replication and more...
We need to establish a connection between MySQL and Node.js using Sequelize.
We need to establish a connection between MySQL and Node.js using Sequelize.
After creating a successful connection with sequelize, we would require the following three files for configuration. Please carefully create the following files in their respective folders only.SequelizeDemo > application.jsThis will be our root file which will hold the actual logic.SequelizeDemo>utils>database.jsThis will hold all the connection details to MySQL.SequelizeDemo>models>user.jsThis will contain the required model information.
After creating a successful connection with sequelize, we would require the following three files for configuration. Please carefully create the following files in their respective folders only.
SequelizeDemo > application.jsThis will be our root file which will hold the actual logic.
SequelizeDemo > application.js
This will be our root file which will hold the actual logic.
SequelizeDemo>utils>database.jsThis will hold all the connection details to MySQL.
SequelizeDemo>utils>database.js
This will hold all the connection details to MySQL.
SequelizeDemo>models>user.jsThis will contain the required model information.
SequelizeDemo>models>user.js
This will contain the required model information.
const Sequelize = require('sequelize')
const sequelize = new Sequelize(
'YOUR_DB_NAME', // TutorialsPoint
'YOUR_DB_USER_NAME', // root
'YOUR_DB_PASSWORD', //root{
dialect: 'mysql',
host: 'localhost'
}
);
module.exports = sequelize
Please make all the inputs for connecting with your database.
Use this file to define the mappings between a model and a table.
const Sequelize = require('sequelize')
const sequelize = require('../utils/database')
const User = sequelize.define('user', {
// Name of Column #1 and its properties defined: id
user_id:{
// Integer Datatype
type:Sequelize.INTEGER,
// Increment the value automatically
autoIncrement:true,
// user_id can not be null.
allowNull:false,
// To uniquely identify user
primaryKey:true
},
// Name of Column #2: name
name: { type: Sequelize.STRING, allowNull:false },
// Name of Column #3: email
email: { type: Sequelize.STRING, allowNull:false },
// Column: Timestamps
createdAt: Sequelize.DATE,
updatedAt: Sequelize.DATE,
})
module.exports = User
To create a model, we can use any one of the two methods −
sync() Method − Only create model if exists. If the model exists, it will not overwrite the model.
sync() Method − Only create model if exists. If the model exists, it will not overwrite the model.
sync({force: true}) Method − Will create a new model if the model does not exist, however, if the model exists, it will overwrite the existing model.
sync({force: true}) Method − Will create a new model if the model does not exist, however, if the model exists, it will overwrite the existing model.
// Importing the database model
const sequelize = require('./database')
// Importing the user model
const User = require('./user')
// Creating all the tables defined in user
sequelize.sync()
// You can change the user.js file
// And run this code to check if it overwrites the existing code.
sequelize.sync({force:true)
On running the above program, you will get the following Output -
C:\\Users\SequelizeDemo>> node app.js
Executing (default): CREATE TABLE IF NOT EXISTS `users` (`user_id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255) NOT NULL, `email` VARCHAR(255) NOT NULL, `createdAt` DATETIME, `updatedAt` DATETIME, PRIMARY KEY (`user_id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `users`
Now, you can check your database. The above table would have been created. | [
{
"code": null,
"e": 1200,
"s": 1062,
"text": "Sequealize follows the promise-based Node.js ORM for different servers like – Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server."
},
{
"code": null,
"e": 1262,
"s": 1200,
"text": "Following are some of the main features of NodeJS sequelize −"
},
{
"code": null,
"e": 1282,
"s": 1262,
"text": "Transaction Support"
},
{
"code": null,
"e": 1302,
"s": 1282,
"text": "Transaction Support"
},
{
"code": null,
"e": 1312,
"s": 1302,
"text": "Relations"
},
{
"code": null,
"e": 1322,
"s": 1312,
"text": "Relations"
},
{
"code": null,
"e": 1345,
"s": 1322,
"text": "Eager and Lazy Loading"
},
{
"code": null,
"e": 1368,
"s": 1345,
"text": "Eager and Lazy Loading"
},
{
"code": null,
"e": 1397,
"s": 1368,
"text": "Read Replication and more..."
},
{
"code": null,
"e": 1426,
"s": 1397,
"text": "Read Replication and more..."
},
{
"code": null,
"e": 1503,
"s": 1426,
"text": "We need to establish a connection between MySQL and Node.js using Sequelize."
},
{
"code": null,
"e": 1580,
"s": 1503,
"text": "We need to establish a connection between MySQL and Node.js using Sequelize."
},
{
"code": null,
"e": 2024,
"s": 1580,
"text": "After creating a successful connection with sequelize, we would require the following three files for configuration. Please carefully create the following files in their respective folders only.SequelizeDemo > application.jsThis will be our root file which will hold the actual logic.SequelizeDemo>utils>database.jsThis will hold all the connection details to MySQL.SequelizeDemo>models>user.jsThis will contain the required model information."
},
{
"code": null,
"e": 2219,
"s": 2024,
"text": "After creating a successful connection with sequelize, we would require the following three files for configuration. Please carefully create the following files in their respective folders only."
},
{
"code": null,
"e": 2310,
"s": 2219,
"text": "SequelizeDemo > application.jsThis will be our root file which will hold the actual logic."
},
{
"code": null,
"e": 2341,
"s": 2310,
"text": "SequelizeDemo > application.js"
},
{
"code": null,
"e": 2402,
"s": 2341,
"text": "This will be our root file which will hold the actual logic."
},
{
"code": null,
"e": 2485,
"s": 2402,
"text": "SequelizeDemo>utils>database.jsThis will hold all the connection details to MySQL."
},
{
"code": null,
"e": 2517,
"s": 2485,
"text": "SequelizeDemo>utils>database.js"
},
{
"code": null,
"e": 2569,
"s": 2517,
"text": "This will hold all the connection details to MySQL."
},
{
"code": null,
"e": 2647,
"s": 2569,
"text": "SequelizeDemo>models>user.jsThis will contain the required model information."
},
{
"code": null,
"e": 2676,
"s": 2647,
"text": "SequelizeDemo>models>user.js"
},
{
"code": null,
"e": 2726,
"s": 2676,
"text": "This will contain the required model information."
},
{
"code": null,
"e": 2981,
"s": 2726,
"text": "const Sequelize = require('sequelize')\nconst sequelize = new Sequelize(\n 'YOUR_DB_NAME', // TutorialsPoint\n 'YOUR_DB_USER_NAME', // root\n 'YOUR_DB_PASSWORD', //root{\n dialect: 'mysql',\n host: 'localhost'\n }\n);\nmodule.exports = sequelize"
},
{
"code": null,
"e": 3043,
"s": 2981,
"text": "Please make all the inputs for connecting with your database."
},
{
"code": null,
"e": 3109,
"s": 3043,
"text": "Use this file to define the mappings between a model and a table."
},
{
"code": null,
"e": 3835,
"s": 3109,
"text": "const Sequelize = require('sequelize')\nconst sequelize = require('../utils/database')\nconst User = sequelize.define('user', {\n // Name of Column #1 and its properties defined: id\n user_id:{\n\n // Integer Datatype\n type:Sequelize.INTEGER,\n\n // Increment the value automatically\n autoIncrement:true,\n\n // user_id can not be null.\n allowNull:false,\n\n // To uniquely identify user\n primaryKey:true\n },\n\n // Name of Column #2: name\n name: { type: Sequelize.STRING, allowNull:false },\n\n // Name of Column #3: email\n email: { type: Sequelize.STRING, allowNull:false },\n\n // Column: Timestamps\n createdAt: Sequelize.DATE,\n updatedAt: Sequelize.DATE,\n})\nmodule.exports = User"
},
{
"code": null,
"e": 3894,
"s": 3835,
"text": "To create a model, we can use any one of the two methods −"
},
{
"code": null,
"e": 3993,
"s": 3894,
"text": "sync() Method − Only create model if exists. If the model exists, it will not overwrite the model."
},
{
"code": null,
"e": 4092,
"s": 3993,
"text": "sync() Method − Only create model if exists. If the model exists, it will not overwrite the model."
},
{
"code": null,
"e": 4242,
"s": 4092,
"text": "sync({force: true}) Method − Will create a new model if the model does not exist, however, if the model exists, it will overwrite the existing model."
},
{
"code": null,
"e": 4392,
"s": 4242,
"text": "sync({force: true}) Method − Will create a new model if the model does not exist, however, if the model exists, it will overwrite the existing model."
},
{
"code": null,
"e": 4715,
"s": 4392,
"text": "// Importing the database model\nconst sequelize = require('./database')\n\n// Importing the user model\nconst User = require('./user')\n\n// Creating all the tables defined in user\nsequelize.sync()\n\n// You can change the user.js file\n// And run this code to check if it overwrites the existing code.\nsequelize.sync({force:true)"
},
{
"code": null,
"e": 4781,
"s": 4715,
"text": "On running the above program, you will get the following Output -"
},
{
"code": null,
"e": 5110,
"s": 4781,
"text": "C:\\\\Users\\SequelizeDemo>> node app.js\nExecuting (default): CREATE TABLE IF NOT EXISTS `users` (`user_id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255) NOT NULL, `email` VARCHAR(255) NOT NULL, `createdAt` DATETIME, `updatedAt` DATETIME, PRIMARY KEY (`user_id`)) ENGINE=InnoDB;\nExecuting (default): SHOW INDEX FROM `users`"
},
{
"code": null,
"e": 5185,
"s": 5110,
"text": "Now, you can check your database. The above table would have been created."
}
] |
Set Column Ordering in Bootstrap | Write the columns in an order, and show them in another one. You can easily change the order of built-in grid columns with .col-md-push-* and .col-md-pull-*modifier classes where * range from 1 to 11.
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<h1>Heading</h1>
<div class = "row">
<p>Before Ordering</p>
<div class = "col-md-4" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
I am on left
</div>
<div class = "col-md-8" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
I am on right
</div>
</div>
<br>
<div class = "row">
<p>After Ordering</p>
<div class = "col-md-4 col-md-push-8" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
I was on left
</div>
<div class = "col-md-8 col-md-pull-4" style = "background-color: #dedef8;
box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
I was on right
</div>
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1263,
"s": 1062,
"text": "Write the columns in an order, and show them in another one. You can easily change the order of built-in grid columns with .col-md-push-* and .col-md-pull-*modifier classes where * range from 1 to 11."
},
{
"code": null,
"e": 1274,
"s": 1263,
"text": " Live Demo"
},
{
"code": null,
"e": 2648,
"s": 1274,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h1>Heading</h1>\n <div class = \"row\">\n <p>Before Ordering</p>\n <div class = \"col-md-4\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n I am on left\n </div>\n <div class = \"col-md-8\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n I am on right\n </div>\n </div>\n <br>\n <div class = \"row\">\n <p>After Ordering</p>\n <div class = \"col-md-4 col-md-push-8\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n I was on left\n </div>\n <div class = \"col-md-8 col-md-pull-4\" style = \"background-color: #dedef8;\n box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;\">\n I was on right\n </div>\n </div>\n </div> \n </body>\n</html>"
}
] |
Error and Exception Handling in Python: Fundamentals for Data Scientists | by Erdem Isbilen | Towards Data Science | There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.
Syntax errors are similar to grammar or spelling errors in a Language. If there is such an error in your code, Python cannot start to execute your code. You get a clear error message stating what is wrong and what needs to be fixed. Therefore, it is the easiest error type you can fix.
Missing symbols (such as comma, bracket, colon), misspelling a keyword, having incorrect indentation are common syntax errors in Python.
Exceptions may occur in syntactically correct code blocks at run time. When Python cannot execute the requested action, it terminates the code and raises an error message.
Trying to read from a file which does not exist, performing operations with incompatible types of variables, dividing a number by zero are common exceptions that raise an error in Python.
We must eliminate the syntax errors to run our Python code, while exceptions can be handled at runtime.
Logical errors are the most difficult errors to fix as they don’t crash your code and you don’t get any error message.
If you have logical errors, your code does not run as you expected.
Using incorrect variable names, code that is not reflecting the algorithm logic properly, making mistakes on boolean operators will result in logical errors.
# Syntax Error-1: Misusing the Assignment Operatorlen("data") = 4Output: File "ErrorsAndExceptions.py", line 1 len("data") = 4SyntaxError: can't assign to function call# Syntax Error-2: Python Keyword Misusefr k in range(10): print(k)Output: File "ErrorsAndExceptions.py", line 4 fr k in range(10): ^SyntaxError: invalid syntax# Exception-1: ZeroDivisionErrorprint (5/0)Output:Traceback (most recent call last): File "ErrorsAndExceptions.py", line 12, in <module> print (5/0)ZeroDivisionError: integer division or modulo by zero# Exception-2: TypeErrorprint ('4' + 4)Output:Traceback (most recent call last): File "ErrorsAndExceptions.py", line 10, in <module> print ('4' + 4)TypeError: cannot concatenate 'str' and 'int' objects
When your code has a syntax error, Python stops and raises an error by providing the location of the error in your code and a clear error definition.
# Syntax Error-1: Misusing the Assignment Operatorlen("data") = 4Output: File "ErrorsAndExceptions.py", line 1 len("data") = 4SyntaxError: can't assign to function call
You need to correct the syntax error to run your code.
len("data") == 4Output:True
The main aim of the exception handling is to prevent potential failures and uncontrolled stops.
We can catch and handle an exception with a try-except block:
try block contains the code to be monitored for the exceptions.
except block contains what to be done if a specific exception occurs. If no exception occurs then this section is skipped and the try-except statement is concluded.
If exception raised matches with the one specified in except keyword, the code inside the except block is executed to handle the exception.
You can catch any exception if you do not specify any type of exception in the except keyword.
try block execution is terminated when the first exception occurs.
try-except block may have more than one except block to handle several different types of exceptions.
Optional else block is executed only if there is no exception occurs in a try block. If any exception is raised, the else block will not be executed.
Optional finally block is used for clean up code. This block is always executed.
try: #code to monitor print (5/0)#this code will not be executed #as above line raises a ZeroDivisionError print ("this code will not be executed")except ZeroDivisionError as e: #code to handle the exception when it occurs print(e) print("OPPS")else: print("try block executed if there is no error")finally: print("finally block is always executed")Output:integer division or modulo by zeroOPPSfinally block is always executed
If a specific condition occurs, you can manually raise exceptions with a raise keyword.
student_age = -4if student_age < 2: raise Exception("Sorry, student age cannot be lower than 2")Output:Traceback (most recent call last): File "ErrorsAndExceptions.py", line 49, in <module> raise Exception("Sorry, student age cannot be lower than 2")Exception: Sorry, student age cannot be lower than 2
We can define our own exception types if we would like to have more control over what will happen in specific conditions.
To do this, we inherit from the Exception class.
class InvalidStudentAgeException(Exception):"""Exception for errors in the student age Attributes: student_age -- student_age that we monitor error_message -- explanation of the error """def __init__(self, student_age, error_message="Student age should be in 2-10 range"):self.student_age = student_age self.error_message = error_message super().__init__(self.error_message)student_age = int(input("Enter Student age: "))if not 1 < student_age < 11: raise InvalidStudentAgeException(student_age)Output:Enter Student age: 54Traceback (most recent call last): File "ErrorsAndExceptions.py", line 68, in <module> raise InvalidStudentAgeException(student_age)__main__.InvalidStudentAgeException: Student age should be in 2-10 range: 54 is not a valid age
Above, we override the constructor of the Exception base class to use our own custom arguments student_age and error_message. With using super().__init__(self.error_message), we instantiate the base class, Exception, argument which help us to display the error message.
We must eliminate the syntax errors to run our Python code, while exceptions can be handled at runtime.
We can catch and handle an exception with a try-except block.
We can define our own exception types if we would like to have more control over what will happen in specific conditions.
In this post, I explained the basics of error and exception handling in Python.
The code in this post is available in my GitHub repository.
I hope you found this post useful.
Thank you for reading! | [
{
"code": null,
"e": 159,
"s": 47,
"text": "There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors."
},
{
"code": null,
"e": 445,
"s": 159,
"text": "Syntax errors are similar to grammar or spelling errors in a Language. If there is such an error in your code, Python cannot start to execute your code. You get a clear error message stating what is wrong and what needs to be fixed. Therefore, it is the easiest error type you can fix."
},
{
"code": null,
"e": 582,
"s": 445,
"text": "Missing symbols (such as comma, bracket, colon), misspelling a keyword, having incorrect indentation are common syntax errors in Python."
},
{
"code": null,
"e": 754,
"s": 582,
"text": "Exceptions may occur in syntactically correct code blocks at run time. When Python cannot execute the requested action, it terminates the code and raises an error message."
},
{
"code": null,
"e": 942,
"s": 754,
"text": "Trying to read from a file which does not exist, performing operations with incompatible types of variables, dividing a number by zero are common exceptions that raise an error in Python."
},
{
"code": null,
"e": 1046,
"s": 942,
"text": "We must eliminate the syntax errors to run our Python code, while exceptions can be handled at runtime."
},
{
"code": null,
"e": 1165,
"s": 1046,
"text": "Logical errors are the most difficult errors to fix as they don’t crash your code and you don’t get any error message."
},
{
"code": null,
"e": 1233,
"s": 1165,
"text": "If you have logical errors, your code does not run as you expected."
},
{
"code": null,
"e": 1391,
"s": 1233,
"text": "Using incorrect variable names, code that is not reflecting the algorithm logic properly, making mistakes on boolean operators will result in logical errors."
},
{
"code": null,
"e": 2146,
"s": 1391,
"text": "# Syntax Error-1: Misusing the Assignment Operatorlen(\"data\") = 4Output: File \"ErrorsAndExceptions.py\", line 1 len(\"data\") = 4SyntaxError: can't assign to function call# Syntax Error-2: Python Keyword Misusefr k in range(10): print(k)Output: File \"ErrorsAndExceptions.py\", line 4 fr k in range(10): ^SyntaxError: invalid syntax# Exception-1: ZeroDivisionErrorprint (5/0)Output:Traceback (most recent call last): File \"ErrorsAndExceptions.py\", line 12, in <module> print (5/0)ZeroDivisionError: integer division or modulo by zero# Exception-2: TypeErrorprint ('4' + 4)Output:Traceback (most recent call last): File \"ErrorsAndExceptions.py\", line 10, in <module> print ('4' + 4)TypeError: cannot concatenate 'str' and 'int' objects"
},
{
"code": null,
"e": 2296,
"s": 2146,
"text": "When your code has a syntax error, Python stops and raises an error by providing the location of the error in your code and a clear error definition."
},
{
"code": null,
"e": 2469,
"s": 2296,
"text": "# Syntax Error-1: Misusing the Assignment Operatorlen(\"data\") = 4Output: File \"ErrorsAndExceptions.py\", line 1 len(\"data\") = 4SyntaxError: can't assign to function call"
},
{
"code": null,
"e": 2524,
"s": 2469,
"text": "You need to correct the syntax error to run your code."
},
{
"code": null,
"e": 2552,
"s": 2524,
"text": "len(\"data\") == 4Output:True"
},
{
"code": null,
"e": 2648,
"s": 2552,
"text": "The main aim of the exception handling is to prevent potential failures and uncontrolled stops."
},
{
"code": null,
"e": 2710,
"s": 2648,
"text": "We can catch and handle an exception with a try-except block:"
},
{
"code": null,
"e": 2774,
"s": 2710,
"text": "try block contains the code to be monitored for the exceptions."
},
{
"code": null,
"e": 2939,
"s": 2774,
"text": "except block contains what to be done if a specific exception occurs. If no exception occurs then this section is skipped and the try-except statement is concluded."
},
{
"code": null,
"e": 3079,
"s": 2939,
"text": "If exception raised matches with the one specified in except keyword, the code inside the except block is executed to handle the exception."
},
{
"code": null,
"e": 3174,
"s": 3079,
"text": "You can catch any exception if you do not specify any type of exception in the except keyword."
},
{
"code": null,
"e": 3241,
"s": 3174,
"text": "try block execution is terminated when the first exception occurs."
},
{
"code": null,
"e": 3343,
"s": 3241,
"text": "try-except block may have more than one except block to handle several different types of exceptions."
},
{
"code": null,
"e": 3493,
"s": 3343,
"text": "Optional else block is executed only if there is no exception occurs in a try block. If any exception is raised, the else block will not be executed."
},
{
"code": null,
"e": 3574,
"s": 3493,
"text": "Optional finally block is used for clean up code. This block is always executed."
},
{
"code": null,
"e": 4001,
"s": 3574,
"text": "try: #code to monitor print (5/0)#this code will not be executed #as above line raises a ZeroDivisionError print (\"this code will not be executed\")except ZeroDivisionError as e: #code to handle the exception when it occurs print(e) print(\"OPPS\")else: print(\"try block executed if there is no error\")finally: print(\"finally block is always executed\")Output:integer division or modulo by zeroOPPSfinally block is always executed"
},
{
"code": null,
"e": 4089,
"s": 4001,
"text": "If a specific condition occurs, you can manually raise exceptions with a raise keyword."
},
{
"code": null,
"e": 4396,
"s": 4089,
"text": "student_age = -4if student_age < 2: raise Exception(\"Sorry, student age cannot be lower than 2\")Output:Traceback (most recent call last): File \"ErrorsAndExceptions.py\", line 49, in <module> raise Exception(\"Sorry, student age cannot be lower than 2\")Exception: Sorry, student age cannot be lower than 2"
},
{
"code": null,
"e": 4518,
"s": 4396,
"text": "We can define our own exception types if we would like to have more control over what will happen in specific conditions."
},
{
"code": null,
"e": 4567,
"s": 4518,
"text": "To do this, we inherit from the Exception class."
},
{
"code": null,
"e": 5326,
"s": 4567,
"text": "class InvalidStudentAgeException(Exception):\"\"\"Exception for errors in the student age Attributes: student_age -- student_age that we monitor error_message -- explanation of the error \"\"\"def __init__(self, student_age, error_message=\"Student age should be in 2-10 range\"):self.student_age = student_age self.error_message = error_message super().__init__(self.error_message)student_age = int(input(\"Enter Student age: \"))if not 1 < student_age < 11: raise InvalidStudentAgeException(student_age)Output:Enter Student age: 54Traceback (most recent call last): File \"ErrorsAndExceptions.py\", line 68, in <module> raise InvalidStudentAgeException(student_age)__main__.InvalidStudentAgeException: Student age should be in 2-10 range: 54 is not a valid age"
},
{
"code": null,
"e": 5596,
"s": 5326,
"text": "Above, we override the constructor of the Exception base class to use our own custom arguments student_age and error_message. With using super().__init__(self.error_message), we instantiate the base class, Exception, argument which help us to display the error message."
},
{
"code": null,
"e": 5700,
"s": 5596,
"text": "We must eliminate the syntax errors to run our Python code, while exceptions can be handled at runtime."
},
{
"code": null,
"e": 5762,
"s": 5700,
"text": "We can catch and handle an exception with a try-except block."
},
{
"code": null,
"e": 5884,
"s": 5762,
"text": "We can define our own exception types if we would like to have more control over what will happen in specific conditions."
},
{
"code": null,
"e": 5964,
"s": 5884,
"text": "In this post, I explained the basics of error and exception handling in Python."
},
{
"code": null,
"e": 6024,
"s": 5964,
"text": "The code in this post is available in my GitHub repository."
},
{
"code": null,
"e": 6059,
"s": 6024,
"text": "I hope you found this post useful."
}
] |
Data Structures and Algorithms | Set 30 - GeeksforGeeks | 27 Mar, 2017
Following questions have been asked in GATE CS 2013 exam.
1) Which of the following statements is/are TRUE for an undirected graph?P: Number of odd degree vertices is evenQ: Sum of degrees of all vertices is even
A) P OnlyB) Q OnlyC) Both P and QD) Neither P nor Q
Answer (C)Q is true: Since the graph is undirected, every edge increases the sum of degrees by 2.P is true: If we consider sum of degrees and subtract all even degrees, we get an even number (because Q is true). So total number of odd degree vertices must be even.
2) Consider an undirected random graph of eight vertices. The probability that there is an edge between a pair of vertices is 1/2. What is the expected number of unordered cycles of length three?(A) 1/8(B) 1(C) 7(D) 8
Answer (C)A cycle of length 3 can be formed with 3 vertices. There can be total 8C3 ways to pick 3 vertices from 8. The probability that there is an edge between two vertices is 1/2. So expected number of unordered cycles of length 3 = (8C3)*(1/2)^3 = 7
3) What is the time complexity of Bellman-Ford single-source shortest path algorithm on a complete graph of n vertices?(A) Θ(n2)(B) Θ(n2 Logn)(C) Θ(n3)(D) Θ(n3 Logn)
Answer (C).Time complexity of Bellman-Ford algorithm is Θ(VE) where V is number of vertices and E is number edges (See this). If the graph is complete, the value of E becomes Θ(V2). So overall time complexity becomes Θ(V3)
4) Which of the following statements are TRUE?(1) The problem of determining whether there exists a cycle in an undirected graph is in P.(2) The problem of determining whether there exists a cycle in an undirected graph is in NP.(3) If a problem A is NP-Complete, there exists a non-deterministic polynomial time algorithm to solve A.
(A) 1,2 and 3(B) 1 and 2 only(C) 2 and 3 only(D) 1 and 3 only
Answer (A)1 is true because cycle detection can be done in polynomial time using DFS (See this).2 is true because P is a subset of NP.3 is true because NP complete is also a subset of NP and NP means Non-deterministic Polynomial time solution exists. (See this)
5) Which one of the following is the tightest upper bound that represents the time complexity of inserting an object into a binary search tree of n nodes?(A) O(1)(B) O(log n)(C) O(n)(D) O(n log n)
Answer (C)The worst case occurs for a skewed tree. In a skewed tree, when a new node is inserted as a child of bottommost node, the time for insertion requires traversal of all node. For example, consider the following tree and the case when something smaller than 70 is inserted.
100
/
90
/
80
/
70
6) Which one of the following is the tightest upper bound that represents the number of swaps required to sort n numbers using selection sort?(A) O(log n)(B) O(n)(C) O(n log n)(D) O(n^2)
Answer (B)Selection sort requires only O(n) swaps. See this for details.
7) Consider the following operation along with Enqueue and Dequeue operations onqueues, where k is a global parameter
MultiDequeue(Q){
m = k
while (Q is not empty and m > 0) {
Dequeue(Q)
m = m - 1
}
}
What is the worst case time complexity of a sequence of n MultiDequeue() operations on an initially empty queue?(A) Θ(n)(B) Θ(n + k)(C) Θ(nk)(D) Θ(n2)
Answer (A)Since the queue is empty initially, the condition of while loop never becomes true. So the time complexity is Θ(n)
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
GATE-CS-2013
GATE-CS-DS-&-Algo
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Normal Forms in DBMS
Differences between TCP and UDP
Semaphores in Process Synchronization
LRU Cache Implementation
Practice questions on Height balanced/AVL Tree
Operating Systems | Set 1
Computer Networks | Set 1
Computer Networks | Set 2
Database Management Systems | Set 1 | [
{
"code": null,
"e": 24388,
"s": 24360,
"text": "\n27 Mar, 2017"
},
{
"code": null,
"e": 24446,
"s": 24388,
"text": "Following questions have been asked in GATE CS 2013 exam."
},
{
"code": null,
"e": 24601,
"s": 24446,
"text": "1) Which of the following statements is/are TRUE for an undirected graph?P: Number of odd degree vertices is evenQ: Sum of degrees of all vertices is even"
},
{
"code": null,
"e": 24653,
"s": 24601,
"text": "A) P OnlyB) Q OnlyC) Both P and QD) Neither P nor Q"
},
{
"code": null,
"e": 24918,
"s": 24653,
"text": "Answer (C)Q is true: Since the graph is undirected, every edge increases the sum of degrees by 2.P is true: If we consider sum of degrees and subtract all even degrees, we get an even number (because Q is true). So total number of odd degree vertices must be even."
},
{
"code": null,
"e": 25136,
"s": 24918,
"text": "2) Consider an undirected random graph of eight vertices. The probability that there is an edge between a pair of vertices is 1/2. What is the expected number of unordered cycles of length three?(A) 1/8(B) 1(C) 7(D) 8"
},
{
"code": null,
"e": 25390,
"s": 25136,
"text": "Answer (C)A cycle of length 3 can be formed with 3 vertices. There can be total 8C3 ways to pick 3 vertices from 8. The probability that there is an edge between two vertices is 1/2. So expected number of unordered cycles of length 3 = (8C3)*(1/2)^3 = 7"
},
{
"code": null,
"e": 25556,
"s": 25390,
"text": "3) What is the time complexity of Bellman-Ford single-source shortest path algorithm on a complete graph of n vertices?(A) Θ(n2)(B) Θ(n2 Logn)(C) Θ(n3)(D) Θ(n3 Logn)"
},
{
"code": null,
"e": 25779,
"s": 25556,
"text": "Answer (C).Time complexity of Bellman-Ford algorithm is Θ(VE) where V is number of vertices and E is number edges (See this). If the graph is complete, the value of E becomes Θ(V2). So overall time complexity becomes Θ(V3)"
},
{
"code": null,
"e": 26114,
"s": 25779,
"text": "4) Which of the following statements are TRUE?(1) The problem of determining whether there exists a cycle in an undirected graph is in P.(2) The problem of determining whether there exists a cycle in an undirected graph is in NP.(3) If a problem A is NP-Complete, there exists a non-deterministic polynomial time algorithm to solve A."
},
{
"code": null,
"e": 26176,
"s": 26114,
"text": "(A) 1,2 and 3(B) 1 and 2 only(C) 2 and 3 only(D) 1 and 3 only"
},
{
"code": null,
"e": 26438,
"s": 26176,
"text": "Answer (A)1 is true because cycle detection can be done in polynomial time using DFS (See this).2 is true because P is a subset of NP.3 is true because NP complete is also a subset of NP and NP means Non-deterministic Polynomial time solution exists. (See this)"
},
{
"code": null,
"e": 26635,
"s": 26438,
"text": "5) Which one of the following is the tightest upper bound that represents the time complexity of inserting an object into a binary search tree of n nodes?(A) O(1)(B) O(log n)(C) O(n)(D) O(n log n)"
},
{
"code": null,
"e": 26916,
"s": 26635,
"text": "Answer (C)The worst case occurs for a skewed tree. In a skewed tree, when a new node is inserted as a child of bottommost node, the time for insertion requires traversal of all node. For example, consider the following tree and the case when something smaller than 70 is inserted."
},
{
"code": null,
"e": 27005,
"s": 26916,
"text": " 100\n /\n 90\n /\n 80\n /\n 70 \n"
},
{
"code": null,
"e": 27192,
"s": 27005,
"text": "6) Which one of the following is the tightest upper bound that represents the number of swaps required to sort n numbers using selection sort?(A) O(log n)(B) O(n)(C) O(n log n)(D) O(n^2)"
},
{
"code": null,
"e": 27265,
"s": 27192,
"text": "Answer (B)Selection sort requires only O(n) swaps. See this for details."
},
{
"code": null,
"e": 27383,
"s": 27265,
"text": "7) Consider the following operation along with Enqueue and Dequeue operations onqueues, where k is a global parameter"
},
{
"code": null,
"e": 27488,
"s": 27383,
"text": "MultiDequeue(Q){\n m = k\n while (Q is not empty and m > 0) {\n Dequeue(Q)\n m = m - 1\n }\n}"
},
{
"code": null,
"e": 27639,
"s": 27488,
"text": "What is the worst case time complexity of a sequence of n MultiDequeue() operations on an initially empty queue?(A) Θ(n)(B) Θ(n + k)(C) Θ(nk)(D) Θ(n2)"
},
{
"code": null,
"e": 27764,
"s": 27639,
"text": "Answer (A)Since the queue is empty initially, the condition of while loop never becomes true. So the time complexity is Θ(n)"
},
{
"code": null,
"e": 27878,
"s": 27764,
"text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc."
},
{
"code": null,
"e": 28027,
"s": 27878,
"text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above."
},
{
"code": null,
"e": 28040,
"s": 28027,
"text": "GATE-CS-2013"
},
{
"code": null,
"e": 28058,
"s": 28040,
"text": "GATE-CS-DS-&-Algo"
},
{
"code": null,
"e": 28066,
"s": 28058,
"text": "GATE CS"
},
{
"code": null,
"e": 28070,
"s": 28066,
"text": "MCQ"
},
{
"code": null,
"e": 28168,
"s": 28070,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28217,
"s": 28168,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 28238,
"s": 28217,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 28270,
"s": 28238,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 28308,
"s": 28270,
"text": "Semaphores in Process Synchronization"
},
{
"code": null,
"e": 28333,
"s": 28308,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 28380,
"s": 28333,
"text": "Practice questions on Height balanced/AVL Tree"
},
{
"code": null,
"e": 28406,
"s": 28380,
"text": "Operating Systems | Set 1"
},
{
"code": null,
"e": 28432,
"s": 28406,
"text": "Computer Networks | Set 1"
},
{
"code": null,
"e": 28458,
"s": 28432,
"text": "Computer Networks | Set 2"
}
] |
How to catch ValueError using Exception in Python? | A ValueError is used when a function receives a value that has the right type but an invalid value.
The given code can be rewritten as follows to handle the exception and find its type.
import sys
try:
n = int('magnolia')
except Exception as e:
print e
print sys.exc_type
invalid literal for int() with base 10: 'magnolia'
<type 'exceptions.ValueError'> | [
{
"code": null,
"e": 1162,
"s": 1062,
"text": "A ValueError is used when a function receives a value that has the right type but an invalid value."
},
{
"code": null,
"e": 1248,
"s": 1162,
"text": "The given code can be rewritten as follows to handle the exception and find its type."
},
{
"code": null,
"e": 1334,
"s": 1248,
"text": "import sys\ntry:\nn = int('magnolia')\nexcept Exception as e:\nprint e\nprint sys.exc_type"
},
{
"code": null,
"e": 1416,
"s": 1334,
"text": "invalid literal for int() with base 10: 'magnolia'\n<type 'exceptions.ValueError'>"
}
] |
C# | Adding new node or value at the start of LinkedList<T> - GeeksforGeeks | 01 Feb, 2019
LinkedList<T>.AddFirst Method is used to add a new node or value at the starting of the LinkedList<T>. There are 2 methods in the overload list of this method as follows:
AddFirst(LinkedList<T>)AddFirst(T)
AddFirst(LinkedList<T>)
AddFirst(T)
This method is used to add the specified new node at the starting of the LinkedList<T>.
Syntax:
public void AddFirst (System.Collections.Generic.LinkedListNode<T> node);
Here, node is the new LinkedListNode<T> to add at the start of the LinkedList<T>.
Exceptions:
ArgumentNullException : If the node is null.
InvalidOperationException : If the node belongs to another LinkedList<T>.
Example:
// C# code to add new node// at the start of LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(6); myList.AddLast(6); myList.AddLast(8); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } // Adding new node at the start of LinkedList // This will give error as node is null myList.AddFirst(5); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } }}
Output:
Total nodes in myList are : 6246668
Unhandled Exception:System.ArgumentNullException: Value cannot be null.Parameter name: node
Note:
LinkedList<T> accepts null as a valid Value for reference types and allows duplicate values.
If the LinkedList<T> is empty, the new node becomes the First and the Last.
This method is an O(1) operation.
This method is used to add a new node containing the specified value at the start of the LinkedList<T>.
Syntax:
public System.Collections.Generic.LinkedListNode AddFirst (T value);
Here, value is the value to add at the start of the LinkedList<T>.
Return Value: The new LinkedListNode<T> containing value.
Example:
// C# code to add new node containing// the specified value at the start// of LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(6); myList.AddLast(6); myList.AddLast(8); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } // Adding new node containing the // specified value at the start of LinkedList myList.AddFirst(20); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } }}
Output:
Total nodes in myList are : 6
2
4
6
6
6
8
Total nodes in myList are : 7
20
2
4
6
6
6
8
Note:
LinkedList<T> accepts null as a valid Value for reference types and allows duplicate values.
If the LinkedList<T> is empty, the new node becomes the First and the Last.
This method is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.addfirst?view=netframework-4.7.2
CSharp-Generic-Namespace
CSharp-LinkedList
CSharp-LinkedList-Methods
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C# | [
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24082,
"s": 23911,
"text": "LinkedList<T>.AddFirst Method is used to add a new node or value at the starting of the LinkedList<T>. There are 2 methods in the overload list of this method as follows:"
},
{
"code": null,
"e": 24117,
"s": 24082,
"text": "AddFirst(LinkedList<T>)AddFirst(T)"
},
{
"code": null,
"e": 24141,
"s": 24117,
"text": "AddFirst(LinkedList<T>)"
},
{
"code": null,
"e": 24153,
"s": 24141,
"text": "AddFirst(T)"
},
{
"code": null,
"e": 24241,
"s": 24153,
"text": "This method is used to add the specified new node at the starting of the LinkedList<T>."
},
{
"code": null,
"e": 24249,
"s": 24241,
"text": "Syntax:"
},
{
"code": null,
"e": 24324,
"s": 24249,
"text": "public void AddFirst (System.Collections.Generic.LinkedListNode<T> node);\n"
},
{
"code": null,
"e": 24406,
"s": 24324,
"text": "Here, node is the new LinkedListNode<T> to add at the start of the LinkedList<T>."
},
{
"code": null,
"e": 24418,
"s": 24406,
"text": "Exceptions:"
},
{
"code": null,
"e": 24463,
"s": 24418,
"text": "ArgumentNullException : If the node is null."
},
{
"code": null,
"e": 24537,
"s": 24463,
"text": "InvalidOperationException : If the node belongs to another LinkedList<T>."
},
{
"code": null,
"e": 24546,
"s": 24537,
"text": "Example:"
},
{
"code": "// C# code to add new node// at the start of LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(6); myList.AddLast(6); myList.AddLast(8); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } // Adding new node at the start of LinkedList // This will give error as node is null myList.AddFirst(5); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } }}",
"e": 25758,
"s": 24546,
"text": null
},
{
"code": null,
"e": 25766,
"s": 25758,
"text": "Output:"
},
{
"code": null,
"e": 25802,
"s": 25766,
"text": "Total nodes in myList are : 6246668"
},
{
"code": null,
"e": 25894,
"s": 25802,
"text": "Unhandled Exception:System.ArgumentNullException: Value cannot be null.Parameter name: node"
},
{
"code": null,
"e": 25900,
"s": 25894,
"text": "Note:"
},
{
"code": null,
"e": 25993,
"s": 25900,
"text": "LinkedList<T> accepts null as a valid Value for reference types and allows duplicate values."
},
{
"code": null,
"e": 26069,
"s": 25993,
"text": "If the LinkedList<T> is empty, the new node becomes the First and the Last."
},
{
"code": null,
"e": 26103,
"s": 26069,
"text": "This method is an O(1) operation."
},
{
"code": null,
"e": 26207,
"s": 26103,
"text": "This method is used to add a new node containing the specified value at the start of the LinkedList<T>."
},
{
"code": null,
"e": 26215,
"s": 26207,
"text": "Syntax:"
},
{
"code": null,
"e": 26285,
"s": 26215,
"text": "public System.Collections.Generic.LinkedListNode AddFirst (T value);\n"
},
{
"code": null,
"e": 26352,
"s": 26285,
"text": "Here, value is the value to add at the start of the LinkedList<T>."
},
{
"code": null,
"e": 26410,
"s": 26352,
"text": "Return Value: The new LinkedListNode<T> containing value."
},
{
"code": null,
"e": 26419,
"s": 26410,
"text": "Example:"
},
{
"code": "// C# code to add new node containing// the specified value at the start// of LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(6); myList.AddLast(6); myList.AddLast(8); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } // Adding new node containing the // specified value at the start of LinkedList myList.AddFirst(20); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } }}",
"e": 27659,
"s": 26419,
"text": null
},
{
"code": null,
"e": 27667,
"s": 27659,
"text": "Output:"
},
{
"code": null,
"e": 27755,
"s": 27667,
"text": "Total nodes in myList are : 6\n2\n4\n6\n6\n6\n8\nTotal nodes in myList are : 7\n20\n2\n4\n6\n6\n6\n8\n"
},
{
"code": null,
"e": 27761,
"s": 27755,
"text": "Note:"
},
{
"code": null,
"e": 27854,
"s": 27761,
"text": "LinkedList<T> accepts null as a valid Value for reference types and allows duplicate values."
},
{
"code": null,
"e": 27930,
"s": 27854,
"text": "If the LinkedList<T> is empty, the new node becomes the First and the Last."
},
{
"code": null,
"e": 27964,
"s": 27930,
"text": "This method is an O(1) operation."
},
{
"code": null,
"e": 27975,
"s": 27964,
"text": "Reference:"
},
{
"code": null,
"e": 28092,
"s": 27975,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.addfirst?view=netframework-4.7.2"
},
{
"code": null,
"e": 28117,
"s": 28092,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 28135,
"s": 28117,
"text": "CSharp-LinkedList"
},
{
"code": null,
"e": 28161,
"s": 28135,
"text": "CSharp-LinkedList-Methods"
},
{
"code": null,
"e": 28164,
"s": 28161,
"text": "C#"
},
{
"code": null,
"e": 28262,
"s": 28164,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28271,
"s": 28262,
"text": "Comments"
},
{
"code": null,
"e": 28284,
"s": 28271,
"text": "Old Comments"
},
{
"code": null,
"e": 28324,
"s": 28284,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28347,
"s": 28324,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28375,
"s": 28347,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28397,
"s": 28375,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28414,
"s": 28397,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28454,
"s": 28414,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 28487,
"s": 28454,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 28530,
"s": 28487,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28546,
"s": 28530,
"text": "C# | List Class"
}
] |
PhantomJS - Environment Setup | PhantomJS is a free software and is distributed under the BSD License. It is easy to install and it offers multiple features to execute the scripts. PhantomJS can be easily run on multiple platforms such as Windows, Linux, and Mac.
For downloading PhantomJS, you can go to – http://phantomjs.org/ and then click on the download option.
The download page shows you the options for download for different OS. Download the zip file, unpack it and you will get an executable phantom.exe. Set the PATH environment variable to the path of phantom.exe file. Open a new command prompt and type phantomjs –v. It should give you the current version of PhantomJS that is running.
Download the PhantomJS zip file meant for MAC OS and extract the content. Once the content is downloaded, move the PhantomJS to – /usr/local/bin/. Execute PhantomJS command i.e. phantomjs –v at the terminal and it should give you the version description of PhantomJS.
Download the PhantomJS zip file meant for Linux 64 bit and extract the content. Once the content is downloaded, move PhantomJS folder to /usr/local/share/ and create a symlink −
sudo mv $PHANTOM_JS /usr/local/share
sudo ln -sf /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/bin.
Execute phantomjs –v at the terminal and it should give the version of PhantomJS.
Download the PhantomJS zip file meant for Linux 32 bit and extract the content. Once the content is downloaded, move the PhantomJS folder to /usr/local/share/ and create a symlink −
sudo mv $PHANTOM_JS /usr/local/share
sudo ln -sf /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/bin.
Execute phantomjs –v at the terminal and it should give the version of PhantomJS.
The PhantomJS source code can also be taken from the git repository by clicking on the following link – https://github.com/ariya/phantomjs/
To run scripts in PhantomJS, the command is as follows −
phantomjs jsfile arg1 arg2...
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2376,
"s": 2144,
"text": "PhantomJS is a free software and is distributed under the BSD License. It is easy to install and it offers multiple features to execute the scripts. PhantomJS can be easily run on multiple platforms such as Windows, Linux, and Mac."
},
{
"code": null,
"e": 2480,
"s": 2376,
"text": "For downloading PhantomJS, you can go to – http://phantomjs.org/ and then click on the download option."
},
{
"code": null,
"e": 2813,
"s": 2480,
"text": "The download page shows you the options for download for different OS. Download the zip file, unpack it and you will get an executable phantom.exe. Set the PATH environment variable to the path of phantom.exe file. Open a new command prompt and type phantomjs –v. It should give you the current version of PhantomJS that is running."
},
{
"code": null,
"e": 3081,
"s": 2813,
"text": "Download the PhantomJS zip file meant for MAC OS and extract the content. Once the content is downloaded, move the PhantomJS to – /usr/local/bin/. Execute PhantomJS command i.e. phantomjs –v at the terminal and it should give you the version description of PhantomJS."
},
{
"code": null,
"e": 3259,
"s": 3081,
"text": "Download the PhantomJS zip file meant for Linux 64 bit and extract the content. Once the content is downloaded, move PhantomJS folder to /usr/local/share/ and create a symlink −"
},
{
"code": null,
"e": 3369,
"s": 3259,
"text": "sudo mv $PHANTOM_JS /usr/local/share \nsudo ln -sf /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/bin.\n"
},
{
"code": null,
"e": 3451,
"s": 3369,
"text": "Execute phantomjs –v at the terminal and it should give the version of PhantomJS."
},
{
"code": null,
"e": 3633,
"s": 3451,
"text": "Download the PhantomJS zip file meant for Linux 32 bit and extract the content. Once the content is downloaded, move the PhantomJS folder to /usr/local/share/ and create a symlink −"
},
{
"code": null,
"e": 3743,
"s": 3633,
"text": "sudo mv $PHANTOM_JS /usr/local/share \nsudo ln -sf /usr/local/share/$PHANTOM_JS/bin/phantomjs /usr/local/bin.\n"
},
{
"code": null,
"e": 3825,
"s": 3743,
"text": "Execute phantomjs –v at the terminal and it should give the version of PhantomJS."
},
{
"code": null,
"e": 3965,
"s": 3825,
"text": "The PhantomJS source code can also be taken from the git repository by clicking on the following link – https://github.com/ariya/phantomjs/"
},
{
"code": null,
"e": 4022,
"s": 3965,
"text": "To run scripts in PhantomJS, the command is as follows −"
},
{
"code": null,
"e": 4054,
"s": 4022,
"text": "phantomjs jsfile arg1 arg2... \n"
},
{
"code": null,
"e": 4061,
"s": 4054,
"text": " Print"
},
{
"code": null,
"e": 4072,
"s": 4061,
"text": " Add Notes"
}
] |
SQL - TRUNCATE TABLE Command | The SQL TRUNCATE TABLE command is used to delete complete data from an existing table.
You can also use DROP TABLE command to delete complete table but it would remove complete table structure form the database and you would need to re-create this table once again if you wish you store some data.
The basic syntax of a TRUNCATE TABLE command is as follows.
TRUNCATE TABLE table_name;
Consider a CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is the example of a Truncate command.
SQL > TRUNCATE TABLE CUSTOMERS;
Now, the CUSTOMERS table is truncated and the output from SELECT statement will be as shown in the code block below −
SQL> SELECT * FROM CUSTOMERS;
Empty set (0.00 sec)
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2540,
"s": 2453,
"text": "The SQL TRUNCATE TABLE command is used to delete complete data from an existing table."
},
{
"code": null,
"e": 2751,
"s": 2540,
"text": "You can also use DROP TABLE command to delete complete table but it would remove complete table structure form the database and you would need to re-create this table once again if you wish you store some data."
},
{
"code": null,
"e": 2811,
"s": 2751,
"text": "The basic syntax of a TRUNCATE TABLE command is as follows."
},
{
"code": null,
"e": 2840,
"s": 2811,
"text": "TRUNCATE TABLE table_name;\n"
},
{
"code": null,
"e": 2898,
"s": 2840,
"text": "Consider a CUSTOMERS table having the following records −"
},
{
"code": null,
"e": 3416,
"s": 2898,
"text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n"
},
{
"code": null,
"e": 3464,
"s": 3416,
"text": "Following is the example of a Truncate command."
},
{
"code": null,
"e": 3496,
"s": 3464,
"text": "SQL > TRUNCATE TABLE CUSTOMERS;"
},
{
"code": null,
"e": 3614,
"s": 3496,
"text": "Now, the CUSTOMERS table is truncated and the output from SELECT statement will be as shown in the code block below −"
},
{
"code": null,
"e": 3666,
"s": 3614,
"text": "SQL> SELECT * FROM CUSTOMERS;\nEmpty set (0.00 sec)\n"
},
{
"code": null,
"e": 3699,
"s": 3666,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3713,
"s": 3699,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3746,
"s": 3713,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3760,
"s": 3746,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3795,
"s": 3760,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3809,
"s": 3795,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3842,
"s": 3809,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3864,
"s": 3842,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 3899,
"s": 3864,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3953,
"s": 3899,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 3986,
"s": 3953,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4014,
"s": 3986,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4021,
"s": 4014,
"text": " Print"
},
{
"code": null,
"e": 4032,
"s": 4021,
"text": " Add Notes"
}
] |
Java - isLowerCase() Method | The method determines whether the specified char value is lowercase.
boolean isLowerCase(char ch)
Here is the detail of parameters −
ch − Primitive character type.
ch − Primitive character type.
This method returns true, if the passed character is really in lowercase.
public class Test {
public static void main(String args[]) {
System.out.println(Character.isLowerCase('c'));
System.out.println(Character.isLowerCase('C'));
System.out.println(Character.isLowerCase('\n'));
System.out.println(Character.isLowerCase('\t'));
}
}
This will produce the following result −
true
false
false
false
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2446,
"s": 2377,
"text": "The method determines whether the specified char value is lowercase."
},
{
"code": null,
"e": 2476,
"s": 2446,
"text": "boolean isLowerCase(char ch)\n"
},
{
"code": null,
"e": 2511,
"s": 2476,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2542,
"s": 2511,
"text": "ch − Primitive character type."
},
{
"code": null,
"e": 2573,
"s": 2542,
"text": "ch − Primitive character type."
},
{
"code": null,
"e": 2647,
"s": 2573,
"text": "This method returns true, if the passed character is really in lowercase."
},
{
"code": null,
"e": 2937,
"s": 2647,
"text": "public class Test {\n\n public static void main(String args[]) {\n System.out.println(Character.isLowerCase('c'));\n System.out.println(Character.isLowerCase('C'));\n System.out.println(Character.isLowerCase('\\n'));\n System.out.println(Character.isLowerCase('\\t'));\n }\n}"
},
{
"code": null,
"e": 2978,
"s": 2937,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3002,
"s": 2978,
"text": "true\nfalse\nfalse\nfalse\n"
},
{
"code": null,
"e": 3035,
"s": 3002,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3051,
"s": 3035,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3084,
"s": 3051,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3100,
"s": 3084,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3135,
"s": 3100,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3149,
"s": 3135,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3183,
"s": 3149,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3197,
"s": 3183,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3234,
"s": 3197,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3249,
"s": 3234,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3282,
"s": 3249,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3301,
"s": 3282,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3308,
"s": 3301,
"text": " Print"
},
{
"code": null,
"e": 3319,
"s": 3308,
"text": " Add Notes"
}
] |
LISP - Comparison Operators | Following table shows all the relational operators supported by LISP that compares between numbers. However unlike relational operators in other languages, LISP comparison operators may take more than two operands and they work on numbers only.
Assume variable A holds 10 and variable B holds 20, then −
Create a new source code file named main.lisp and type the following code in it.
(setq a 10)
(setq b 20)
(format t "~% A = B is ~a" (= a b))
(format t "~% A /= B is ~a" (/= a b))
(format t "~% A > B is ~a" (> a b))
(format t "~% A < B is ~a" (< a b))
(format t "~% A >= B is ~a" (>= a b))
(format t "~% A <= B is ~a" (<= a b))
(format t "~% Max of A and B is ~d" (max a b))
(format t "~% Min of A and B is ~d" (min a b))
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
A = B is NIL
A /= B is T
A > B is NIL
A < B is T
A >= B is NIL
A <= B is T
Max of A and B is 20
Min of A and B is 10
79 Lectures
7 hours
Arnold Higuit
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2305,
"s": 2060,
"text": "Following table shows all the relational operators supported by LISP that compares between numbers. However unlike relational operators in other languages, LISP comparison operators may take more than two operands and they work on numbers only."
},
{
"code": null,
"e": 2364,
"s": 2305,
"text": "Assume variable A holds 10 and variable B holds 20, then −"
},
{
"code": null,
"e": 2445,
"s": 2364,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 2785,
"s": 2445,
"text": "(setq a 10)\n(setq b 20)\n(format t \"~% A = B is ~a\" (= a b))\n(format t \"~% A /= B is ~a\" (/= a b))\n(format t \"~% A > B is ~a\" (> a b))\n(format t \"~% A < B is ~a\" (< a b))\n(format t \"~% A >= B is ~a\" (>= a b))\n(format t \"~% A <= B is ~a\" (<= a b))\n(format t \"~% Max of A and B is ~d\" (max a b))\n(format t \"~% Min of A and B is ~d\" (min a b))"
},
{
"code": null,
"e": 2894,
"s": 2785,
"text": "When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −"
},
{
"code": null,
"e": 3012,
"s": 2894,
"text": "A = B is NIL\nA /= B is T\nA > B is NIL\nA < B is T\nA >= B is NIL\nA <= B is T\nMax of A and B is 20\nMin of A and B is 10\n"
},
{
"code": null,
"e": 3045,
"s": 3012,
"text": "\n 79 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3060,
"s": 3045,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3067,
"s": 3060,
"text": " Print"
},
{
"code": null,
"e": 3078,
"s": 3067,
"text": " Add Notes"
}
] |
Tryit Editor v3.6 - Show Python | mydb = mysql.connector.connect( | [] |
Rust - Error Handling - GeeksforGeeks | 18 Jul, 2021
An error is basically an unexpected behavior or event that may lead a program to produce undesired output or terminate abruptly. Errors are things that no one wants in their program. We can try to find and analyze parts of the program that can cause errors. Once we found those parts then we can define how those parts should behave if they encounter an error. This process of finding and defining cases for a particular block of code is what we call Error Handling. One thing we should keep in mind that we cannot completely get rid of errors but we can try to minimize them or at least reduce their effect on our program.
In Rust, errors can be classified into two categories namely recoverable and unrecoverable
Recoverable Errors: Recoverable errors are those that do not cause the program to terminate abruptly. Example- When we try to fetch a file that is not present or we do not have permission to open it.
Unrecoverable Errors: Unrecoverable errors are those that cause the program to terminate abruptly. Example- Trying to access array index greater than the size of the array.
Most language does not distinguish between the two errors and use an Exception class to overcome them while Rust uses a data type Result <R,T> to handle recoverable errors and panic! macro to stop the execution of the program in case of unrecoverable errors.
We will first see how and where should we use panic! macro. Before it, we will see what it does to a program.
Rust
fn main() { panic!("program crashed");}
Output:
thread 'main' panicked at 'program crashed', main.rs:2:7
So, it basically stops the execution of the program and prints what we passed it in its parameter.
panic! the macro may be in library files that we use, let us see some:
Rust
fn main() { let v = vec![1, 2, 3]; println!("{}",v[3])}
Output:
thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 3', main.rs:3:19
Since we are trying to access elements beyond the bounds of vector therefore it called a panic! macro.
We should only use panic in a condition if our code may end up in a bad state. A bad state is when some assumption, guarantee, contract, or invariant has been broken, such as when invalid values, contradictory values, or missing values are passed to our code and at least one of the following:-
If a bad state occurs once in a blue moon.
Your code after this point needs to rely on not being in this bad state.
There’s not a good way to encode this information in the types you use.
Result<T,E> is an enum data type with two variants OK and Err which is defined something like this
enum Result<T, E> {
Ok(T),
Err(E),
}
T and E are generic type parameters where T represents the type of value that will be returned in a success case within the Ok variant, and E represents the type of error that will be returned in a failure case within the Err variant.
Rust
use std::fs::File; fn main() { let f = File::open("gfg.txt"); println!("{:?}",f);}
Output:
Err(Os { code: 2, kind: NotFound, message: "No such file or directory" })
Since the file gfg.txt was not there so the Err instance was returned by File. If the file gfg.txt had been found then an instance to the file would have been returned.
If a file is not found just like the above case then it will be better if we ask the user to check the file name, file location or to give the file specifications once more or whatever the situation demands.
Rust
use std::fs::File;fn main() { // file doesn't exist let f = File::open("gfg.txt");/ match f { Ok(file)=> { println!("file found {:?}",file); }, Err(_error)=> { // replace it with whatever you want // to do if file is not found println!("file not found \n"); } }}
Output:
file not found
In the above program, it basically matches the return type of the result and performs the task accordingly.
Let’s create our own errors according to business logic. Suppose we want to produce an error if a person below 18 years tries to apply for voter ID.
Rust
fn main(){ let result = eligible(13); match result { Ok(age)=>{ println!("Person eligible to vote with age={}",age); }, Err(msg)=>{ println!("{}",msg); } }}fn eligible(age:i32)->Result<i32,String> { if age>=18 { return Ok(age); } else { return Err("Not Eligible..Wait for some years".to_string()); }}
Output:
Not Eligible..Wait for some years
If we want to abort the program after it encounters a recoverable error then we could use panic! macro and to simplify the process Rust provides two methods unwrap() and expect().
Unwrap()
Rust
use std::fs::File; fn main() { let f = File::open("gfg.txt").unwrap();}
Output:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value:
Os { code: 2, kind: NotFound, message: "No such file or directory" }', main.rs:17:14
The unwrap() calls the panic! macro in case of file not found while it returns the file handler instance if the file is found. Although unwrap() makes the program shorter but when there are too many unwrap() methods in our program then it becomes a bit confusing as to which unwrap() method called the panic! macro. So we need something that can produce the customized messages. In that case, expect() method comes to the rescue.
expect()
Rust
use std::fs::File; fn main() { let f = File::open("hello.txt").expect("Failed to open gfg.txt");}
Output:
thread 'main' panicked at 'Failed to open gfg.txt:
Os { code: 2, kind: NotFound, message: "No such file or directory" }', main.rs:17:14
We passed our message to panic! macro via the expected parameter.
Picked
Rust exceptions
Rust
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Rust - Creating a Library
Rust - Casting
Rust - Concept of Structures
Rust - Comments
Rust - For and Range
Rust - Box Smart Pointer
Rust - Recoverable Errors
Rust - Concept of Smart Pointers
Rust - Concept of Ownership
Scalar Datatypes in Rust | [
{
"code": null,
"e": 23548,
"s": 23520,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 24172,
"s": 23548,
"text": "An error is basically an unexpected behavior or event that may lead a program to produce undesired output or terminate abruptly. Errors are things that no one wants in their program. We can try to find and analyze parts of the program that can cause errors. Once we found those parts then we can define how those parts should behave if they encounter an error. This process of finding and defining cases for a particular block of code is what we call Error Handling. One thing we should keep in mind that we cannot completely get rid of errors but we can try to minimize them or at least reduce their effect on our program."
},
{
"code": null,
"e": 24263,
"s": 24172,
"text": "In Rust, errors can be classified into two categories namely recoverable and unrecoverable"
},
{
"code": null,
"e": 24463,
"s": 24263,
"text": "Recoverable Errors: Recoverable errors are those that do not cause the program to terminate abruptly. Example- When we try to fetch a file that is not present or we do not have permission to open it."
},
{
"code": null,
"e": 24636,
"s": 24463,
"text": "Unrecoverable Errors: Unrecoverable errors are those that cause the program to terminate abruptly. Example- Trying to access array index greater than the size of the array."
},
{
"code": null,
"e": 24896,
"s": 24636,
"text": "Most language does not distinguish between the two errors and use an Exception class to overcome them while Rust uses a data type Result <R,T> to handle recoverable errors and panic! macro to stop the execution of the program in case of unrecoverable errors. "
},
{
"code": null,
"e": 25006,
"s": 24896,
"text": "We will first see how and where should we use panic! macro. Before it, we will see what it does to a program."
},
{
"code": null,
"e": 25011,
"s": 25006,
"text": "Rust"
},
{
"code": "fn main() { panic!(\"program crashed\");}",
"e": 25056,
"s": 25011,
"text": null
},
{
"code": null,
"e": 25064,
"s": 25056,
"text": "Output:"
},
{
"code": null,
"e": 25121,
"s": 25064,
"text": "thread 'main' panicked at 'program crashed', main.rs:2:7"
},
{
"code": null,
"e": 25220,
"s": 25121,
"text": "So, it basically stops the execution of the program and prints what we passed it in its parameter."
},
{
"code": null,
"e": 25291,
"s": 25220,
"text": "panic! the macro may be in library files that we use, let us see some:"
},
{
"code": null,
"e": 25296,
"s": 25291,
"text": "Rust"
},
{
"code": "fn main() { let v = vec![1, 2, 3]; println!(\"{}\",v[3])}",
"e": 25360,
"s": 25296,
"text": null
},
{
"code": null,
"e": 25368,
"s": 25360,
"text": "Output:"
},
{
"code": null,
"e": 25463,
"s": 25368,
"text": "thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 3', main.rs:3:19"
},
{
"code": null,
"e": 25566,
"s": 25463,
"text": "Since we are trying to access elements beyond the bounds of vector therefore it called a panic! macro."
},
{
"code": null,
"e": 25861,
"s": 25566,
"text": "We should only use panic in a condition if our code may end up in a bad state. A bad state is when some assumption, guarantee, contract, or invariant has been broken, such as when invalid values, contradictory values, or missing values are passed to our code and at least one of the following:-"
},
{
"code": null,
"e": 25904,
"s": 25861,
"text": "If a bad state occurs once in a blue moon."
},
{
"code": null,
"e": 25977,
"s": 25904,
"text": "Your code after this point needs to rely on not being in this bad state."
},
{
"code": null,
"e": 26049,
"s": 25977,
"text": "There’s not a good way to encode this information in the types you use."
},
{
"code": null,
"e": 26148,
"s": 26049,
"text": "Result<T,E> is an enum data type with two variants OK and Err which is defined something like this"
},
{
"code": null,
"e": 26193,
"s": 26148,
"text": "enum Result<T, E> {\n Ok(T),\n Err(E),\n}"
},
{
"code": null,
"e": 26429,
"s": 26193,
"text": "T and E are generic type parameters where T represents the type of value that will be returned in a success case within the Ok variant, and E represents the type of error that will be returned in a failure case within the Err variant. "
},
{
"code": null,
"e": 26434,
"s": 26429,
"text": "Rust"
},
{
"code": "use std::fs::File; fn main() { let f = File::open(\"gfg.txt\"); println!(\"{:?}\",f);}",
"e": 26522,
"s": 26434,
"text": null
},
{
"code": null,
"e": 26530,
"s": 26522,
"text": "Output:"
},
{
"code": null,
"e": 26604,
"s": 26530,
"text": "Err(Os { code: 2, kind: NotFound, message: \"No such file or directory\" })"
},
{
"code": null,
"e": 26774,
"s": 26604,
"text": "Since the file gfg.txt was not there so the Err instance was returned by File. If the file gfg.txt had been found then an instance to the file would have been returned. "
},
{
"code": null,
"e": 26982,
"s": 26774,
"text": "If a file is not found just like the above case then it will be better if we ask the user to check the file name, file location or to give the file specifications once more or whatever the situation demands."
},
{
"code": null,
"e": 26987,
"s": 26982,
"text": "Rust"
},
{
"code": "use std::fs::File;fn main() { // file doesn't exist let f = File::open(\"gfg.txt\");/ match f { Ok(file)=> { println!(\"file found {:?}\",file); }, Err(_error)=> { // replace it with whatever you want // to do if file is not found println!(\"file not found \\n\"); } }}",
"e": 27326,
"s": 26987,
"text": null
},
{
"code": null,
"e": 27334,
"s": 27326,
"text": "Output:"
},
{
"code": null,
"e": 27350,
"s": 27334,
"text": "file not found "
},
{
"code": null,
"e": 27458,
"s": 27350,
"text": "In the above program, it basically matches the return type of the result and performs the task accordingly."
},
{
"code": null,
"e": 27607,
"s": 27458,
"text": "Let’s create our own errors according to business logic. Suppose we want to produce an error if a person below 18 years tries to apply for voter ID."
},
{
"code": null,
"e": 27612,
"s": 27607,
"text": "Rust"
},
{
"code": "fn main(){ let result = eligible(13); match result { Ok(age)=>{ println!(\"Person eligible to vote with age={}\",age); }, Err(msg)=>{ println!(\"{}\",msg); } }}fn eligible(age:i32)->Result<i32,String> { if age>=18 { return Ok(age); } else { return Err(\"Not Eligible..Wait for some years\".to_string()); }}",
"e": 27971,
"s": 27612,
"text": null
},
{
"code": null,
"e": 27979,
"s": 27971,
"text": "Output:"
},
{
"code": null,
"e": 28013,
"s": 27979,
"text": "Not Eligible..Wait for some years"
},
{
"code": null,
"e": 28193,
"s": 28013,
"text": "If we want to abort the program after it encounters a recoverable error then we could use panic! macro and to simplify the process Rust provides two methods unwrap() and expect()."
},
{
"code": null,
"e": 28202,
"s": 28193,
"text": "Unwrap()"
},
{
"code": null,
"e": 28207,
"s": 28202,
"text": "Rust"
},
{
"code": "use std::fs::File; fn main() { let f = File::open(\"gfg.txt\").unwrap();}",
"e": 28283,
"s": 28207,
"text": null
},
{
"code": null,
"e": 28291,
"s": 28283,
"text": "Output:"
},
{
"code": null,
"e": 28448,
"s": 28291,
"text": "thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value:\nOs { code: 2, kind: NotFound, message: \"No such file or directory\" }', main.rs:17:14"
},
{
"code": null,
"e": 28878,
"s": 28448,
"text": "The unwrap() calls the panic! macro in case of file not found while it returns the file handler instance if the file is found. Although unwrap() makes the program shorter but when there are too many unwrap() methods in our program then it becomes a bit confusing as to which unwrap() method called the panic! macro. So we need something that can produce the customized messages. In that case, expect() method comes to the rescue."
},
{
"code": null,
"e": 28887,
"s": 28878,
"text": "expect()"
},
{
"code": null,
"e": 28892,
"s": 28887,
"text": "Rust"
},
{
"code": "use std::fs::File; fn main() { let f = File::open(\"hello.txt\").expect(\"Failed to open gfg.txt\");}",
"e": 28994,
"s": 28892,
"text": null
},
{
"code": null,
"e": 29002,
"s": 28994,
"text": "Output:"
},
{
"code": null,
"e": 29138,
"s": 29002,
"text": "thread 'main' panicked at 'Failed to open gfg.txt:\nOs { code: 2, kind: NotFound, message: \"No such file or directory\" }', main.rs:17:14"
},
{
"code": null,
"e": 29204,
"s": 29138,
"text": "We passed our message to panic! macro via the expected parameter."
},
{
"code": null,
"e": 29211,
"s": 29204,
"text": "Picked"
},
{
"code": null,
"e": 29227,
"s": 29211,
"text": "Rust exceptions"
},
{
"code": null,
"e": 29232,
"s": 29227,
"text": "Rust"
},
{
"code": null,
"e": 29330,
"s": 29232,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29339,
"s": 29330,
"text": "Comments"
},
{
"code": null,
"e": 29352,
"s": 29339,
"text": "Old Comments"
},
{
"code": null,
"e": 29378,
"s": 29352,
"text": "Rust - Creating a Library"
},
{
"code": null,
"e": 29393,
"s": 29378,
"text": "Rust - Casting"
},
{
"code": null,
"e": 29422,
"s": 29393,
"text": "Rust - Concept of Structures"
},
{
"code": null,
"e": 29438,
"s": 29422,
"text": "Rust - Comments"
},
{
"code": null,
"e": 29459,
"s": 29438,
"text": "Rust - For and Range"
},
{
"code": null,
"e": 29484,
"s": 29459,
"text": "Rust - Box Smart Pointer"
},
{
"code": null,
"e": 29510,
"s": 29484,
"text": "Rust - Recoverable Errors"
},
{
"code": null,
"e": 29543,
"s": 29510,
"text": "Rust - Concept of Smart Pointers"
},
{
"code": null,
"e": 29571,
"s": 29543,
"text": "Rust - Concept of Ownership"
}
] |
QueryRunner interface | The org.apache.commons.dbutils.QueryRunner class is the central class in the DBUtils library. It executes SQL queries with pluggable strategies for handling ResultSets. This class is thread safe.
Following is the declaration for org.apache.commons.dbutils.QueryRunner class −
public class QueryRunner
extends AbstractQueryRunner
Step 1 − Create a connection object.
Step 1 − Create a connection object.
Step 2 − Use QueryRunner object methods to make database operations.
Step 2 − Use QueryRunner object methods to make database operations.
Following example will demonstrate how to read a record using QueryRunner class. We'll read one of the available record in employee Table.
ResultSetHandler<Employee> resultHandler = new BeanHandler<Employee>(Employee.class);
Employee emp =
queryRunner.query(conn, "SELECT * FROM employees WHERE first=?", resultHandler, "Sumit");
Where,
resultHandler − ResultSetHandler object to map result set to Employee object.
resultHandler − ResultSetHandler object to map result set to Employee object.
queryRunner − QueryRunner object to read employee object from database.
queryRunner − QueryRunner object to read employee object from database.
To understand the above-mentioned concepts related to DBUtils, let us write an example which will run a read query. To write our example, let us create a sample application.
Following is the content of the Employee.java.
public class Employee {
private int id;
private int age;
private String first;
private String last;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
}
Following is the content of the MainApp.java file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
public class MainApp {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/emp";
// Database credentials
static final String USER = "root";
static final String PASS = "admin";
public static void main(String[] args) throws SQLException {
Connection conn = null;
QueryRunner queryRunner = new QueryRunner();
//Step 1: Register JDBC driver
DbUtils.loadDriver(JDBC_DRIVER);
//Step 2: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Step 3: Create a ResultSet Handler to handle Employee Beans
ResultSetHandler<Employee> resultHandler = new BeanHandler<Employee>(Employee.class);
try {
Employee emp = queryRunner.query(conn,
"SELECT * FROM employees WHERE id=?", resultHandler, 103);
//Display values
System.out.print("ID: " + emp.getId());
System.out.print(", Age: " + emp.getAge());
System.out.print(", First: " + emp.getFirst());
System.out.println(", Last: " + emp.getLast());
} finally {
DbUtils.close(conn);
}
}
}
Once you are done creating the source files, let us run the application. If everything is fine with your application, it will print the following message.
ID: 103, Age: 28, First: Sumit, Last: Mittal
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2348,
"s": 2152,
"text": "The org.apache.commons.dbutils.QueryRunner class is the central class in the DBUtils library. It executes SQL queries with pluggable strategies for handling ResultSets. This class is thread safe."
},
{
"code": null,
"e": 2428,
"s": 2348,
"text": "Following is the declaration for org.apache.commons.dbutils.QueryRunner class −"
},
{
"code": null,
"e": 2485,
"s": 2428,
"text": "public class QueryRunner\n extends AbstractQueryRunner\n"
},
{
"code": null,
"e": 2522,
"s": 2485,
"text": "Step 1 − Create a connection object."
},
{
"code": null,
"e": 2559,
"s": 2522,
"text": "Step 1 − Create a connection object."
},
{
"code": null,
"e": 2628,
"s": 2559,
"text": "Step 2 − Use QueryRunner object methods to make database operations."
},
{
"code": null,
"e": 2697,
"s": 2628,
"text": "Step 2 − Use QueryRunner object methods to make database operations."
},
{
"code": null,
"e": 2836,
"s": 2697,
"text": "Following example will demonstrate how to read a record using QueryRunner class. We'll read one of the available record in employee Table."
},
{
"code": null,
"e": 3032,
"s": 2836,
"text": "ResultSetHandler<Employee> resultHandler = new BeanHandler<Employee>(Employee.class);\nEmployee emp = \n queryRunner.query(conn, \"SELECT * FROM employees WHERE first=?\", resultHandler, \"Sumit\");\n"
},
{
"code": null,
"e": 3039,
"s": 3032,
"text": "Where,"
},
{
"code": null,
"e": 3117,
"s": 3039,
"text": "resultHandler − ResultSetHandler object to map result set to Employee object."
},
{
"code": null,
"e": 3195,
"s": 3117,
"text": "resultHandler − ResultSetHandler object to map result set to Employee object."
},
{
"code": null,
"e": 3267,
"s": 3195,
"text": "queryRunner − QueryRunner object to read employee object from database."
},
{
"code": null,
"e": 3339,
"s": 3267,
"text": "queryRunner − QueryRunner object to read employee object from database."
},
{
"code": null,
"e": 3513,
"s": 3339,
"text": "To understand the above-mentioned concepts related to DBUtils, let us write an example which will run a read query. To write our example, let us create a sample application."
},
{
"code": null,
"e": 3560,
"s": 3513,
"text": "Following is the content of the Employee.java."
},
{
"code": null,
"e": 4130,
"s": 3560,
"text": "public class Employee {\n private int id;\n private int age;\n private String first;\n private String last;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String getFirst() {\n return first;\n }\n public void setFirst(String first) {\n this.first = first;\n }\n public String getLast() {\n return last;\n }\n public void setLast(String last) {\n this.last = last;\n }\n}"
},
{
"code": null,
"e": 4181,
"s": 4130,
"text": "Following is the content of the MainApp.java file."
},
{
"code": null,
"e": 5757,
"s": 4181,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\n\nimport org.apache.commons.dbutils.DbUtils;\nimport org.apache.commons.dbutils.QueryRunner;\nimport org.apache.commons.dbutils.ResultSetHandler;\nimport org.apache.commons.dbutils.handlers.BeanHandler;\n\npublic class MainApp {\n // JDBC driver name and database URL\n static final String JDBC_DRIVER = \"com.mysql.jdbc.Driver\"; \n static final String DB_URL = \"jdbc:mysql://localhost:3306/emp\";\n\n // Database credentials\n static final String USER = \"root\";\n static final String PASS = \"admin\";\n\n public static void main(String[] args) throws SQLException {\n Connection conn = null;\n QueryRunner queryRunner = new QueryRunner();\n \n //Step 1: Register JDBC driver\n DbUtils.loadDriver(JDBC_DRIVER);\n\n //Step 2: Open a connection\n System.out.println(\"Connecting to database...\");\n conn = DriverManager.getConnection(DB_URL, USER, PASS);\n\n //Step 3: Create a ResultSet Handler to handle Employee Beans\n ResultSetHandler<Employee> resultHandler = new BeanHandler<Employee>(Employee.class);\n\n try {\n Employee emp = queryRunner.query(conn,\n \"SELECT * FROM employees WHERE id=?\", resultHandler, 103);\n //Display values\n System.out.print(\"ID: \" + emp.getId());\n System.out.print(\", Age: \" + emp.getAge());\n System.out.print(\", First: \" + emp.getFirst());\n System.out.println(\", Last: \" + emp.getLast());\n } finally {\n DbUtils.close(conn);\n } \n }\n}"
},
{
"code": null,
"e": 5912,
"s": 5757,
"text": "Once you are done creating the source files, let us run the application. If everything is fine with your application, it will print the following message."
},
{
"code": null,
"e": 5958,
"s": 5912,
"text": "ID: 103, Age: 28, First: Sumit, Last: Mittal\n"
},
{
"code": null,
"e": 5965,
"s": 5958,
"text": " Print"
},
{
"code": null,
"e": 5976,
"s": 5965,
"text": " Add Notes"
}
] |
fmt.Sscan() Function in Golang With Examples - GeeksforGeeks | 05 May, 2020
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sscan() function in Go language scans the specified texts and store the successive space-separated texts into successive arguments. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.
Syntax:
func Sscan(str string, a ...interface{}) (n int, err error)
Parameters: This function accepts two parameters which are illustrated below:
str string: This parameter contains the specified text which is going to be scanned.
a ...interface{}: This parameter receives each texts.
Returns: It returns the number of items successfully scanned.
Example 1:
// Golang program to illustrate the usage of// fmt.Sscan() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring two variables var name string var alphabet_count int // Calling the Sscan() function which // returns the number of elements // successfully scanned and error if // it persists n, err := fmt.Sscan("GFG 3", &name, &alphabet_count) // Below statements get executed if there is any error if err != nil { panic(err) } // Printing the number of elements and each elements also fmt.Printf("%d: %s, %d\n", n, name, alphabet_count) }
Output:
2: GFG, 3
Example 2:
// Golang program to illustrate the usage of// fmt.Sscan() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int var float_value float32 var boolean_value bool // Calling the Sscan() function which // returns the number of elements // successfully scanned and error if // it persists n, err := fmt.Sscan("GeeksforGeeks 13 6.7 true", &name, &alphabet_count, &float_value, &boolean_value) // Below statements get // executed if there is any error if err != nil { panic(err) } // Printing the number of // elements and each elements also fmt.Printf("%d: %s, %d, %g, %t", n, name, alphabet_count, float_value, boolean_value) }
Output:
4: GeeksforGeeks, 13, 6.7, true
Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Rune in Golang
Anonymous function in Go Language
Loops in Go Language
Class and Object in Golang
Structures in Golang
Time Durations in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang? | [
{
"code": null,
"e": 24069,
"s": 24041,
"text": "\n05 May, 2020"
},
{
"code": null,
"e": 24459,
"s": 24069,
"text": "In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sscan() function in Go language scans the specified texts and store the successive space-separated texts into successive arguments. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions."
},
{
"code": null,
"e": 24467,
"s": 24459,
"text": "Syntax:"
},
{
"code": null,
"e": 24528,
"s": 24467,
"text": "func Sscan(str string, a ...interface{}) (n int, err error)\n"
},
{
"code": null,
"e": 24606,
"s": 24528,
"text": "Parameters: This function accepts two parameters which are illustrated below:"
},
{
"code": null,
"e": 24691,
"s": 24606,
"text": "str string: This parameter contains the specified text which is going to be scanned."
},
{
"code": null,
"e": 24745,
"s": 24691,
"text": "a ...interface{}: This parameter receives each texts."
},
{
"code": null,
"e": 24807,
"s": 24745,
"text": "Returns: It returns the number of items successfully scanned."
},
{
"code": null,
"e": 24818,
"s": 24807,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// fmt.Sscan() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring two variables var name string var alphabet_count int // Calling the Sscan() function which // returns the number of elements // successfully scanned and error if // it persists n, err := fmt.Sscan(\"GFG 3\", &name, &alphabet_count) // Below statements get executed if there is any error if err != nil { panic(err) } // Printing the number of elements and each elements also fmt.Printf(\"%d: %s, %d\\n\", n, name, alphabet_count) }",
"e": 25489,
"s": 24818,
"text": null
},
{
"code": null,
"e": 25497,
"s": 25489,
"text": "Output:"
},
{
"code": null,
"e": 25508,
"s": 25497,
"text": "2: GFG, 3\n"
},
{
"code": null,
"e": 25519,
"s": 25508,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// fmt.Sscan() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int var float_value float32 var boolean_value bool // Calling the Sscan() function which // returns the number of elements // successfully scanned and error if // it persists n, err := fmt.Sscan(\"GeeksforGeeks 13 6.7 true\", &name, &alphabet_count, &float_value, &boolean_value) // Below statements get // executed if there is any error if err != nil { panic(err) } // Printing the number of // elements and each elements also fmt.Printf(\"%d: %s, %d, %g, %t\", n, name, alphabet_count, float_value, boolean_value) }",
"e": 26351,
"s": 25519,
"text": null
},
{
"code": null,
"e": 26359,
"s": 26351,
"text": "Output:"
},
{
"code": null,
"e": 26392,
"s": 26359,
"text": "4: GeeksforGeeks, 13, 6.7, true\n"
},
{
"code": null,
"e": 26403,
"s": 26392,
"text": "Golang-fmt"
},
{
"code": null,
"e": 26415,
"s": 26403,
"text": "Go Language"
},
{
"code": null,
"e": 26513,
"s": 26415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26522,
"s": 26513,
"text": "Comments"
},
{
"code": null,
"e": 26535,
"s": 26522,
"text": "Old Comments"
},
{
"code": null,
"e": 26564,
"s": 26535,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 26588,
"s": 26564,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 26603,
"s": 26588,
"text": "Rune in Golang"
},
{
"code": null,
"e": 26637,
"s": 26603,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 26658,
"s": 26637,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 26685,
"s": 26658,
"text": "Class and Object in Golang"
},
{
"code": null,
"e": 26706,
"s": 26685,
"text": "Structures in Golang"
},
{
"code": null,
"e": 26731,
"s": 26706,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 26749,
"s": 26731,
"text": "Strings in Golang"
}
] |
\varphi - Tex Command | \varphi - Used to create varphi symbol.
{ \varphi}
\varphi command draws varphi symbol.
\varphi
φ
\varphi
φ
\varphi
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8026,
"s": 7986,
"text": "\\varphi - Used to create varphi symbol."
},
{
"code": null,
"e": 8037,
"s": 8026,
"text": "{ \\varphi}"
},
{
"code": null,
"e": 8074,
"s": 8037,
"text": "\\varphi command draws varphi symbol."
},
{
"code": null,
"e": 8089,
"s": 8074,
"text": "\n\\varphi\n\nφ\n\n\n"
},
{
"code": null,
"e": 8102,
"s": 8089,
"text": "\\varphi\n\nφ\n\n"
},
{
"code": null,
"e": 8110,
"s": 8102,
"text": "\\varphi"
},
{
"code": null,
"e": 8142,
"s": 8110,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8155,
"s": 8142,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8188,
"s": 8155,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8201,
"s": 8188,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8233,
"s": 8201,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8269,
"s": 8233,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8304,
"s": 8269,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8321,
"s": 8304,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8354,
"s": 8321,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8368,
"s": 8354,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8400,
"s": 8368,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8415,
"s": 8400,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8422,
"s": 8415,
"text": " Print"
},
{
"code": null,
"e": 8433,
"s": 8422,
"text": " Add Notes"
}
] |
Data Structures - Environment Setup | If you are still willing to set up your environment for C programming language, you need the following two tools available on your computer, (a) Text Editor and (b) The C Compiler.
This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
The name and the version of the text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on Windows as well as Linux or UNIX.
The files you create with your editor are called source files and contain program source code. The source files for C programs are typically named with the extension ".c".
Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it, and finally execute it.
The source code written in the source file is the human readable source for your program. It needs to be "compiled", to turn into machine language so that your CPU can actually execute the program as per the given instructions.
This C programming language compiler will be used to compile your source code into a final executable program. We assume you have the basic knowledge about a programming language compiler.
Most frequently used and free available compiler is GNU C/C++ compiler. Otherwise, you can have compilers either from HP or Solaris if you have respective Operating Systems (OS).
The following section guides you on how to install GNU C/C++ compiler on various OS. We are mentioning C/C++ together because GNU GCC compiler works for both C and C++ programming languages.
If you are using Linux or UNIX, then check whether GCC is installed on your system by entering the following command from the command line −
$ gcc -v
If you have GNU compiler installed on your machine, then it should print a message such as the following −
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix = /usr .......
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/
This tutorial has been written based on Linux and all the given examples have been compiled on Cent OS flavor of Linux system.
If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's website and follow the simple installation instructions. Once you have Xcode setup, you will be able to use GNU compiler for C/C++.
Xcode is currently available at developer.apple.com/technologies/tools/
To install GCC on Windows, you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program, which should be named MinGW-<version>.exe.
While installing MinWG, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment variable, so that you can specify these tools on the command line by their simple names.
When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line.
42 Lectures
1.5 hours
Ravi Kiran
141 Lectures
13 hours
Arnab Chakraborty
26 Lectures
8.5 hours
Parth Panjabi
65 Lectures
6 hours
Arnab Chakraborty
75 Lectures
13 hours
Eduonix Learning Solutions
64 Lectures
10.5 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2761,
"s": 2580,
"text": "If you are still willing to set up your environment for C programming language, you need the following two tools available on your computer, (a) Text Editor and (b) The C Compiler."
},
{
"code": null,
"e": 2905,
"s": 2761,
"text": "This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi."
},
{
"code": null,
"e": 3099,
"s": 2905,
"text": "The name and the version of the text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on Windows as well as Linux or UNIX."
},
{
"code": null,
"e": 3271,
"s": 3099,
"text": "The files you create with your editor are called source files and contain program source code. The source files for C programs are typically named with the extension \".c\"."
},
{
"code": null,
"e": 3464,
"s": 3271,
"text": "Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it, and finally execute it."
},
{
"code": null,
"e": 3692,
"s": 3464,
"text": "The source code written in the source file is the human readable source for your program. It needs to be \"compiled\", to turn into machine language so that your CPU can actually execute the program as per the given instructions."
},
{
"code": null,
"e": 3881,
"s": 3692,
"text": "This C programming language compiler will be used to compile your source code into a final executable program. We assume you have the basic knowledge about a programming language compiler."
},
{
"code": null,
"e": 4060,
"s": 3881,
"text": "Most frequently used and free available compiler is GNU C/C++ compiler. Otherwise, you can have compilers either from HP or Solaris if you have respective Operating Systems (OS)."
},
{
"code": null,
"e": 4251,
"s": 4060,
"text": "The following section guides you on how to install GNU C/C++ compiler on various OS. We are mentioning C/C++ together because GNU GCC compiler works for both C and C++ programming languages."
},
{
"code": null,
"e": 4392,
"s": 4251,
"text": "If you are using Linux or UNIX, then check whether GCC is installed on your system by entering the following command from the command line −"
},
{
"code": null,
"e": 4402,
"s": 4392,
"text": "$ gcc -v\n"
},
{
"code": null,
"e": 4509,
"s": 4402,
"text": "If you have GNU compiler installed on your machine, then it should print a message such as the following −"
},
{
"code": null,
"e": 4678,
"s": 4509,
"text": "Using built-in specs.\nTarget: i386-redhat-linux\nConfigured with: ../configure --prefix = /usr .......\nThread model: posix\ngcc version 4.1.2 20080704 (Red Hat 4.1.2-46)\n"
},
{
"code": null,
"e": 4819,
"s": 4678,
"text": "If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/"
},
{
"code": null,
"e": 4946,
"s": 4819,
"text": "This tutorial has been written based on Linux and all the given examples have been compiled on Cent OS flavor of Linux system."
},
{
"code": null,
"e": 5191,
"s": 4946,
"text": "If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's website and follow the simple installation instructions. Once you have Xcode setup, you will be able to use GNU compiler for C/C++."
},
{
"code": null,
"e": 5263,
"s": 5191,
"text": "Xcode is currently available at developer.apple.com/technologies/tools/"
},
{
"code": null,
"e": 5530,
"s": 5263,
"text": "To install GCC on Windows, you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program, which should be named MinGW-<version>.exe."
},
{
"code": null,
"e": 5671,
"s": 5530,
"text": "While installing MinWG, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more."
},
{
"code": null,
"e": 5837,
"s": 5671,
"text": "Add the bin subdirectory of your MinGW installation to your PATH environment variable, so that you can specify these tools on the command line by their simple names."
},
{
"code": null,
"e": 5986,
"s": 5837,
"text": "When the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line."
},
{
"code": null,
"e": 6021,
"s": 5986,
"text": "\n 42 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6033,
"s": 6021,
"text": " Ravi Kiran"
},
{
"code": null,
"e": 6068,
"s": 6033,
"text": "\n 141 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6087,
"s": 6068,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6122,
"s": 6087,
"text": "\n 26 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6137,
"s": 6122,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 6170,
"s": 6137,
"text": "\n 65 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6189,
"s": 6170,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6223,
"s": 6189,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6251,
"s": 6223,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6287,
"s": 6251,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 6315,
"s": 6287,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6322,
"s": 6315,
"text": " Print"
},
{
"code": null,
"e": 6333,
"s": 6322,
"text": " Add Notes"
}
] |
Find the mean vector of a Matrix in C++ | Suppose we have a matrix of order M x N, we have to find the mean vector of the given matrix. So if the matrix is like −
Then the mean vector is [4, 5, 6] As the mean of each column is (1 + 4 + 7)/3 = 4, (2 + 5 + 8)/3 = 5, and (3 + 6 + 9)/3 = 6
From the example, we can easily identify that if we calculate the mean of each column will be the mean vector.
Live Demo
#include<iostream>
#define M 3
#define N 3
using namespace std;
void calculateMeanVector(int mat[M][N]) {
cout << "[ ";
for (int i = 0; i < M; i++) {
double average = 0.00;
int sum = 0;
for (int j = 0; j < N; j++)
sum += mat[j][i];
average = sum / M;
cout << average << " ";
}
cout << "]";
}
int main() {
int mat[M][N] = {{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
cout << "Mean vector is: ";
calculateMeanVector(mat);
}
Mean vector is: [ 4 5 6 ] | [
{
"code": null,
"e": 1183,
"s": 1062,
"text": "Suppose we have a matrix of order M x N, we have to find the mean vector of the given matrix. So if the matrix is like −"
},
{
"code": null,
"e": 1307,
"s": 1183,
"text": "Then the mean vector is [4, 5, 6] As the mean of each column is (1 + 4 + 7)/3 = 4, (2 + 5 + 8)/3 = 5, and (3 + 6 + 9)/3 = 6"
},
{
"code": null,
"e": 1418,
"s": 1307,
"text": "From the example, we can easily identify that if we calculate the mean of each column will be the mean vector."
},
{
"code": null,
"e": 1429,
"s": 1418,
"text": " Live Demo"
},
{
"code": null,
"e": 1920,
"s": 1429,
"text": "#include<iostream>\n#define M 3\n#define N 3\nusing namespace std;\nvoid calculateMeanVector(int mat[M][N]) {\n cout << \"[ \";\n for (int i = 0; i < M; i++) {\n double average = 0.00;\n int sum = 0;\n for (int j = 0; j < N; j++)\n sum += mat[j][i];\n average = sum / M;\n cout << average << \" \";\n }\n cout << \"]\";\n}\nint main() {\n int mat[M][N] = {{ 1, 2, 3 },\n { 4, 5, 6 },\n { 7, 8, 9 }\n };\n cout << \"Mean vector is: \";\n calculateMeanVector(mat);\n}"
},
{
"code": null,
"e": 1946,
"s": 1920,
"text": "Mean vector is: [ 4 5 6 ]"
}
] |
Python Object Comparison : “is” vs “==” | 10 Sep, 2018
Both “is” and “==” are used for object comparison in Python. The operator “==” compares values of two objects, while “is” checks if two objects are same (In other words two references to same object).
# Python program to demonstrate working of # "==" # Two different objects having same valuesx1 = [10, 20, 30]x2 = [10, 20, 30] # Comparison using "==" operatorif x1 == x2: print("Yes")else: print("No")
Yes
The “==” operator does not tell us whether x1 and x2 are actually referring to the same object or not. We use “is” for this purpose.
# Python program to demonstrate working of # "is" # Two different objects having same valuesx1 = [10, 20, 30]x2 = [10, 20, 30] # We get "No" hereif x1 is x2: print("Yes")else: print("No") # It creates another reference x3 to same list.x3 = x1 # So we get "Yes" hereif x1 is x3: print("Yes")else: print("No") # "==" would also produce yes anywayif x1 == x3: print("Yes")else: print("No")
No
Yes
Yes
x1 = [10, 20, 30] # Here a new list x2 is created using x1x2 = list(x1) # The "==" operator would produce "Yes"if x1 == x2: print("Yes")else: print("No") # But "is" operator would produce "No"if x1 is x2: print("Yes")else: print("No")
Yes
No
Conclusion:
“is” returns True if two variables point to the same object.
“==” returns True if two variables have same values(or content).
python-basics
Python-Operators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Sep, 2018"
},
{
"code": null,
"e": 229,
"s": 28,
"text": "Both “is” and “==” are used for object comparison in Python. The operator “==” compares values of two objects, while “is” checks if two objects are same (In other words two references to same object)."
},
{
"code": "# Python program to demonstrate working of # \"==\" # Two different objects having same valuesx1 = [10, 20, 30]x2 = [10, 20, 30] # Comparison using \"==\" operatorif x1 == x2: print(\"Yes\")else: print(\"No\")",
"e": 440,
"s": 229,
"text": null
},
{
"code": null,
"e": 445,
"s": 440,
"text": "Yes\n"
},
{
"code": null,
"e": 578,
"s": 445,
"text": "The “==” operator does not tell us whether x1 and x2 are actually referring to the same object or not. We use “is” for this purpose."
},
{
"code": "# Python program to demonstrate working of # \"is\" # Two different objects having same valuesx1 = [10, 20, 30]x2 = [10, 20, 30] # We get \"No\" hereif x1 is x2: print(\"Yes\")else: print(\"No\") # It creates another reference x3 to same list.x3 = x1 # So we get \"Yes\" hereif x1 is x3: print(\"Yes\")else: print(\"No\") # \"==\" would also produce yes anywayif x1 == x3: print(\"Yes\")else: print(\"No\")",
"e": 991,
"s": 578,
"text": null
},
{
"code": null,
"e": 1003,
"s": 991,
"text": "No\nYes\nYes\n"
},
{
"code": "x1 = [10, 20, 30] # Here a new list x2 is created using x1x2 = list(x1) # The \"==\" operator would produce \"Yes\"if x1 == x2: print(\"Yes\")else: print(\"No\") # But \"is\" operator would produce \"No\"if x1 is x2: print(\"Yes\")else: print(\"No\")",
"e": 1255,
"s": 1003,
"text": null
},
{
"code": null,
"e": 1263,
"s": 1255,
"text": "Yes\nNo\n"
},
{
"code": null,
"e": 1275,
"s": 1263,
"text": "Conclusion:"
},
{
"code": null,
"e": 1336,
"s": 1275,
"text": "“is” returns True if two variables point to the same object."
},
{
"code": null,
"e": 1401,
"s": 1336,
"text": "“==” returns True if two variables have same values(or content)."
},
{
"code": null,
"e": 1415,
"s": 1401,
"text": "python-basics"
},
{
"code": null,
"e": 1432,
"s": 1415,
"text": "Python-Operators"
},
{
"code": null,
"e": 1439,
"s": 1432,
"text": "Python"
},
{
"code": null,
"e": 1537,
"s": 1439,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1555,
"s": 1537,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1597,
"s": 1555,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1619,
"s": 1597,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1645,
"s": 1619,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1677,
"s": 1645,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1706,
"s": 1677,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1733,
"s": 1706,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1763,
"s": 1733,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1784,
"s": 1763,
"text": "Python OOPs Concepts"
}
] |
Reversing a Stack using two empty Stacks | 24 Aug, 2021
Given a stack S, the task is to reverse the stack S using two additional stacks.
Example:
Input: S={1, 2, 3, 4, 5}Output: 5 4 3 2 1Explanation:The initial stack S:1→top2345After reversing it, use two additional stacks:5→top4321
Input: S={1, 25, 17}Output: 17 25 1
Approach: Follow the steps below to solve the problem:
Create two additional empty stacks, say A and B.Define a function transfer() that accepts two stacks X and Y as parameters and performs the following operations:Loop while X is not empty and perform the following operations:Push the top element of the stack X into Y.Pop that element from X.Call transfer(S, A) tos transfers all elements of the stack S to A. (The order of the elements is reversed).Call transfer(A, B) to transfer all elements of the stack A to B. (The order of the elements is the same as initially in S)Call transfer(B, S) to transfer all elements of B to S. (The order of the elements is reversed)Finally, display the stack S.
Create two additional empty stacks, say A and B.
Define a function transfer() that accepts two stacks X and Y as parameters and performs the following operations:Loop while X is not empty and perform the following operations:Push the top element of the stack X into Y.Pop that element from X.
Loop while X is not empty and perform the following operations:Push the top element of the stack X into Y.Pop that element from X.
Loop while X is not empty and perform the following operations:Push the top element of the stack X into Y.Pop that element from X.
Push the top element of the stack X into Y.Pop that element from X.
Push the top element of the stack X into Y.
Pop that element from X.
Call transfer(S, A) tos transfers all elements of the stack S to A. (The order of the elements is reversed).
Call transfer(A, B) to transfer all elements of the stack A to B. (The order of the elements is the same as initially in S)
Call transfer(B, S) to transfer all elements of B to S. (The order of the elements is reversed)
Finally, display the stack S.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to transfer elements// from the stack X to the stack Yvoid transfer(stack<int>& X, stack<int>& Y){ // Iterate while X is not empty while (!X.empty()) { // Push the top element // of X into Y Y.push(X.top()); // Pop from X X.pop(); }} // Function to display the// contents of the stack Svoid display(stack<int> S){ // Iterate while S is // not empty while (!S.empty()) { // Print the top // element of the stack S cout << S.top() << " "; // Pop from S S.pop(); } cout << endl;} // Function to reverse a stack using two stacksvoid reverseStackUsingTwoStacks(stack<int>& S){ // Two additional stacks stack<int> A, B; // Transfer all elements // from the stack S to A transfer(S, A); // Transfer all elements // from the stack A to B transfer(A, B); // Transfer all elements // from the stack B to S transfer(B, S); // Print the contents of S display(S);}// Driver Codeint main(){ // Input stack<int> S; S.push(5); S.push(4); S.push(3); S.push(2); S.push(1); // Function call reverseStackUsingTwoStacks(S); return 0;}
// Java program for the above approachimport java.util.Stack;public class GFG{ // Function to transfer elements // from the stack X to the stack Y static void transfer(Stack<Integer> X, Stack<Integer> Y) { // Iterate while X is not empty while (!X.empty()) { // Push the top element // of X into Y Y.push(X.peek()); // Pop from X X.pop(); } } // Function to display the // contents of the stack S static void display(Stack<Integer> S) { // Iterate while S is // not empty while (!S.empty()) { // Print the top // element of the stack S System.out.print(S.peek() + " "); // Pop from S S.pop(); } System.out.println(); } // Function to reverse a stack using two stacks static void reverseStackUsingTwoStacks(Stack<Integer> S) { // Two additional stacks Stack<Integer> A = new Stack<>(); Stack<Integer> B = new Stack<>(); // Transfer all elements // from the stack S to A while (!S.empty()) A.push(S.pop()); // Transfer all elements // from the stack A to B while (!A.empty()) B.push(A.pop()); // Transfer all elements // from the stack B to S while (!B.empty()) S.push(B.pop()); // Print the contents of S display(S); } // Driver code public static void main(String[] args) { // Given Input // Input Stack<Integer> S = new Stack<>(); S.push(5); S.push(4); S.push(3); S.push(2); S.push(1); // Function call reverseStackUsingTwoStacks(S); }} // This code is contributed by abhinavjain194
# Python3 program for the above approach # Function to display the# contents of the stack Sdef display(S): # Iterate while S is # not empty while len(S) > 0: # Print the top # element of the stack S print(S[-1], end = " ") # Pop from S S.pop() print() # Function to reverse a stack using two stacksdef reverseStackUsingTwoStacks(S): # Two additional stacks A = [] B = [] # Transfer all elements # from the stack S to A while len(S) > 0: A.append(S[-1]) S.pop() # Transfer all elements # from the stack A to B while len(A) > 0: B.append(A[-1]) A.pop() # Transfer all elements # from the stack B to S while len(B) > 0: S.append(B[-1]) B.pop() # Print the contents of S display(S) # Given Input# InputS = []S.append(5)S.append(4)S.append(3)S.append(2)S.append(1) # Function callreverseStackUsingTwoStacks(S) # This code is contributed by suresh07.
// C# program for the above approachusing System;using System.Collections;class GFG { // Function to transfer elements // from the stack X to the stack Y static void transfer(Stack X, Stack Y) { // Iterate while X is not empty while (X.Count > 0) { // Push the top element // of X into Y Y.Push(X.Peek()); // Pop from X X.Pop(); } } // Function to display the // contents of the stack S static void display(Stack S) { // Iterate while S is // not empty while (S.Count > 0) { // Print the top // element of the stack S Console.Write(S.Peek() + " "); // Pop from S S.Pop(); } Console.WriteLine(); } // Function to reverse a stack using two stacks static void reverseStackUsingTwoStacks(Stack S) { // Two additional stacks Stack A = new Stack(); Stack B = new Stack(); // Transfer all elements // from the stack S to A while (S.Count > 0) A.Push(S.Pop()); // Transfer all elements // from the stack A to B while (A.Count > 0) B.Push(A.Pop()); // Transfer all elements // from the stack B to S while (B.Count > 0) S.Push(B.Pop()); // Print the contents of S display(S); } static void Main() { // Given Input // Input Stack S = new Stack(); S.Push(5); S.Push(4); S.Push(3); S.Push(2); S.Push(1); // Function call reverseStackUsingTwoStacks(S); }} // This code is contributed by divyesh072019.
<script> // Javascript program for the above approach // Function to display the // contents of the stack S function display(S) { // Iterate while S is // not empty while (S.length > 0) { // Print the top // element of the stack S document.write(S[S.length - 1] + " "); // Pop from S S.pop(); } document.write("</br>"); } // Function to reverse a stack using two stacks function reverseStackUsingTwoStacks(S) { // Two additional stacks let A = []; let B = []; // Transfer all elements // from the stack S to A while (S.length > 0) { A.push(S[S.length - 1]); S.pop(); } // Transfer all elements // from the stack A to B while (A.length > 0) { B.push(A[A.length - 1]); A.pop(); } // Transfer all elements // from the stack B to S while (B.length > 0) { S.push(B[B.length - 1]); B.pop(); } // Print the contents of S display(S); } // Given Input // Input let S = []; S.push(5); S.push(4); S.push(3); S.push(2); S.push(1); // Function call reverseStackUsingTwoStacks(S); // This code is contributed by mukesh07.</script>
5 4 3 2 1
Time Complexity: O(N)Auxiliary Space: O(N)
abhinavjain194
divyesh072019
mukesh07
suresh07
cpp-stack
cpp-stack-functions
Reverse
Stack
Stack
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Design a stack with operations on middle element
How to efficiently implement k stacks in a single array?
Real-time application of Data Structures
Next Smaller Element
Construct Binary Tree from String with bracket representation
Reverse individual words
ZigZag Tree Traversal
Length of the longest valid substring | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 134,
"s": 53,
"text": "Given a stack S, the task is to reverse the stack S using two additional stacks."
},
{
"code": null,
"e": 143,
"s": 134,
"text": "Example:"
},
{
"code": null,
"e": 281,
"s": 143,
"text": "Input: S={1, 2, 3, 4, 5}Output: 5 4 3 2 1Explanation:The initial stack S:1→top2345After reversing it, use two additional stacks:5→top4321"
},
{
"code": null,
"e": 317,
"s": 281,
"text": "Input: S={1, 25, 17}Output: 17 25 1"
},
{
"code": null,
"e": 372,
"s": 317,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1019,
"s": 372,
"text": "Create two additional empty stacks, say A and B.Define a function transfer() that accepts two stacks X and Y as parameters and performs the following operations:Loop while X is not empty and perform the following operations:Push the top element of the stack X into Y.Pop that element from X.Call transfer(S, A) tos transfers all elements of the stack S to A. (The order of the elements is reversed).Call transfer(A, B) to transfer all elements of the stack A to B. (The order of the elements is the same as initially in S)Call transfer(B, S) to transfer all elements of B to S. (The order of the elements is reversed)Finally, display the stack S."
},
{
"code": null,
"e": 1068,
"s": 1019,
"text": "Create two additional empty stacks, say A and B."
},
{
"code": null,
"e": 1312,
"s": 1068,
"text": "Define a function transfer() that accepts two stacks X and Y as parameters and performs the following operations:Loop while X is not empty and perform the following operations:Push the top element of the stack X into Y.Pop that element from X."
},
{
"code": null,
"e": 1443,
"s": 1312,
"text": "Loop while X is not empty and perform the following operations:Push the top element of the stack X into Y.Pop that element from X."
},
{
"code": null,
"e": 1574,
"s": 1443,
"text": "Loop while X is not empty and perform the following operations:Push the top element of the stack X into Y.Pop that element from X."
},
{
"code": null,
"e": 1642,
"s": 1574,
"text": "Push the top element of the stack X into Y.Pop that element from X."
},
{
"code": null,
"e": 1686,
"s": 1642,
"text": "Push the top element of the stack X into Y."
},
{
"code": null,
"e": 1711,
"s": 1686,
"text": "Pop that element from X."
},
{
"code": null,
"e": 1820,
"s": 1711,
"text": "Call transfer(S, A) tos transfers all elements of the stack S to A. (The order of the elements is reversed)."
},
{
"code": null,
"e": 1944,
"s": 1820,
"text": "Call transfer(A, B) to transfer all elements of the stack A to B. (The order of the elements is the same as initially in S)"
},
{
"code": null,
"e": 2040,
"s": 1944,
"text": "Call transfer(B, S) to transfer all elements of B to S. (The order of the elements is reversed)"
},
{
"code": null,
"e": 2070,
"s": 2040,
"text": "Finally, display the stack S."
},
{
"code": null,
"e": 2121,
"s": 2070,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2125,
"s": 2121,
"text": "C++"
},
{
"code": null,
"e": 2130,
"s": 2125,
"text": "Java"
},
{
"code": null,
"e": 2138,
"s": 2130,
"text": "Python3"
},
{
"code": null,
"e": 2141,
"s": 2138,
"text": "C#"
},
{
"code": null,
"e": 2152,
"s": 2141,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to transfer elements// from the stack X to the stack Yvoid transfer(stack<int>& X, stack<int>& Y){ // Iterate while X is not empty while (!X.empty()) { // Push the top element // of X into Y Y.push(X.top()); // Pop from X X.pop(); }} // Function to display the// contents of the stack Svoid display(stack<int> S){ // Iterate while S is // not empty while (!S.empty()) { // Print the top // element of the stack S cout << S.top() << \" \"; // Pop from S S.pop(); } cout << endl;} // Function to reverse a stack using two stacksvoid reverseStackUsingTwoStacks(stack<int>& S){ // Two additional stacks stack<int> A, B; // Transfer all elements // from the stack S to A transfer(S, A); // Transfer all elements // from the stack A to B transfer(A, B); // Transfer all elements // from the stack B to S transfer(B, S); // Print the contents of S display(S);}// Driver Codeint main(){ // Input stack<int> S; S.push(5); S.push(4); S.push(3); S.push(2); S.push(1); // Function call reverseStackUsingTwoStacks(S); return 0;}",
"e": 3446,
"s": 2152,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.Stack;public class GFG{ // Function to transfer elements // from the stack X to the stack Y static void transfer(Stack<Integer> X, Stack<Integer> Y) { // Iterate while X is not empty while (!X.empty()) { // Push the top element // of X into Y Y.push(X.peek()); // Pop from X X.pop(); } } // Function to display the // contents of the stack S static void display(Stack<Integer> S) { // Iterate while S is // not empty while (!S.empty()) { // Print the top // element of the stack S System.out.print(S.peek() + \" \"); // Pop from S S.pop(); } System.out.println(); } // Function to reverse a stack using two stacks static void reverseStackUsingTwoStacks(Stack<Integer> S) { // Two additional stacks Stack<Integer> A = new Stack<>(); Stack<Integer> B = new Stack<>(); // Transfer all elements // from the stack S to A while (!S.empty()) A.push(S.pop()); // Transfer all elements // from the stack A to B while (!A.empty()) B.push(A.pop()); // Transfer all elements // from the stack B to S while (!B.empty()) S.push(B.pop()); // Print the contents of S display(S); } // Driver code public static void main(String[] args) { // Given Input // Input Stack<Integer> S = new Stack<>(); S.push(5); S.push(4); S.push(3); S.push(2); S.push(1); // Function call reverseStackUsingTwoStacks(S); }} // This code is contributed by abhinavjain194",
"e": 5274,
"s": 3446,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to display the# contents of the stack Sdef display(S): # Iterate while S is # not empty while len(S) > 0: # Print the top # element of the stack S print(S[-1], end = \" \") # Pop from S S.pop() print() # Function to reverse a stack using two stacksdef reverseStackUsingTwoStacks(S): # Two additional stacks A = [] B = [] # Transfer all elements # from the stack S to A while len(S) > 0: A.append(S[-1]) S.pop() # Transfer all elements # from the stack A to B while len(A) > 0: B.append(A[-1]) A.pop() # Transfer all elements # from the stack B to S while len(B) > 0: S.append(B[-1]) B.pop() # Print the contents of S display(S) # Given Input# InputS = []S.append(5)S.append(4)S.append(3)S.append(2)S.append(1) # Function callreverseStackUsingTwoStacks(S) # This code is contributed by suresh07.",
"e": 6290,
"s": 5274,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections;class GFG { // Function to transfer elements // from the stack X to the stack Y static void transfer(Stack X, Stack Y) { // Iterate while X is not empty while (X.Count > 0) { // Push the top element // of X into Y Y.Push(X.Peek()); // Pop from X X.Pop(); } } // Function to display the // contents of the stack S static void display(Stack S) { // Iterate while S is // not empty while (S.Count > 0) { // Print the top // element of the stack S Console.Write(S.Peek() + \" \"); // Pop from S S.Pop(); } Console.WriteLine(); } // Function to reverse a stack using two stacks static void reverseStackUsingTwoStacks(Stack S) { // Two additional stacks Stack A = new Stack(); Stack B = new Stack(); // Transfer all elements // from the stack S to A while (S.Count > 0) A.Push(S.Pop()); // Transfer all elements // from the stack A to B while (A.Count > 0) B.Push(A.Pop()); // Transfer all elements // from the stack B to S while (B.Count > 0) S.Push(B.Pop()); // Print the contents of S display(S); } static void Main() { // Given Input // Input Stack S = new Stack(); S.Push(5); S.Push(4); S.Push(3); S.Push(2); S.Push(1); // Function call reverseStackUsingTwoStacks(S); }} // This code is contributed by divyesh072019.",
"e": 7983,
"s": 6290,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to display the // contents of the stack S function display(S) { // Iterate while S is // not empty while (S.length > 0) { // Print the top // element of the stack S document.write(S[S.length - 1] + \" \"); // Pop from S S.pop(); } document.write(\"</br>\"); } // Function to reverse a stack using two stacks function reverseStackUsingTwoStacks(S) { // Two additional stacks let A = []; let B = []; // Transfer all elements // from the stack S to A while (S.length > 0) { A.push(S[S.length - 1]); S.pop(); } // Transfer all elements // from the stack A to B while (A.length > 0) { B.push(A[A.length - 1]); A.pop(); } // Transfer all elements // from the stack B to S while (B.length > 0) { S.push(B[B.length - 1]); B.pop(); } // Print the contents of S display(S); } // Given Input // Input let S = []; S.push(5); S.push(4); S.push(3); S.push(2); S.push(1); // Function call reverseStackUsingTwoStacks(S); // This code is contributed by mukesh07.</script>",
"e": 9427,
"s": 7983,
"text": null
},
{
"code": null,
"e": 9440,
"s": 9430,
"text": "5 4 3 2 1"
},
{
"code": null,
"e": 9487,
"s": 9444,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 9504,
"s": 9489,
"text": "abhinavjain194"
},
{
"code": null,
"e": 9518,
"s": 9504,
"text": "divyesh072019"
},
{
"code": null,
"e": 9527,
"s": 9518,
"text": "mukesh07"
},
{
"code": null,
"e": 9536,
"s": 9527,
"text": "suresh07"
},
{
"code": null,
"e": 9546,
"s": 9536,
"text": "cpp-stack"
},
{
"code": null,
"e": 9566,
"s": 9546,
"text": "cpp-stack-functions"
},
{
"code": null,
"e": 9574,
"s": 9566,
"text": "Reverse"
},
{
"code": null,
"e": 9580,
"s": 9574,
"text": "Stack"
},
{
"code": null,
"e": 9586,
"s": 9580,
"text": "Stack"
},
{
"code": null,
"e": 9594,
"s": 9586,
"text": "Reverse"
},
{
"code": null,
"e": 9692,
"s": 9594,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9724,
"s": 9692,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9788,
"s": 9724,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9837,
"s": 9788,
"text": "Design a stack with operations on middle element"
},
{
"code": null,
"e": 9894,
"s": 9837,
"text": "How to efficiently implement k stacks in a single array?"
},
{
"code": null,
"e": 9935,
"s": 9894,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 9956,
"s": 9935,
"text": "Next Smaller Element"
},
{
"code": null,
"e": 10018,
"s": 9956,
"text": "Construct Binary Tree from String with bracket representation"
},
{
"code": null,
"e": 10043,
"s": 10018,
"text": "Reverse individual words"
},
{
"code": null,
"e": 10065,
"s": 10043,
"text": "ZigZag Tree Traversal"
}
] |
Python | Check if tuple has any None value | 26 Nov, 2019
Sometimes, while working with Python, we can have a problem in which we have a record and we need to check if it contains all valid values i.e has any None value. This kind of problem is common in data preprocessing steps. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using any() + map() + lambdaCombination of above functions can be used to perform this task. In this, we check for any element using any() and extension of logic is done by map() and lambda.
# Python3 code to demonstrate working of# Check if tuple has any None value# using any() + map() + lambda # initialize tupletest_tup = (10, 4, 5, 6, None) # printing original tupleprint("The original tuple : " + str(test_tup)) # Check if tuple has any None value# using any() + map() + lambdares = any(map(lambda ele: ele is None, test_tup)) # printing resultprint("Does tuple contain any None value ? : " + str(res))
The original tuple : (10, 4, 5, 6, None)
Does tuple contain any None value ? : True
Method #2 : Using not + all()This checks for truthness of all elements of tuple using all() and with not, returns True if there is no None element.
# Python3 code to demonstrate working of# Check if tuple has any None value# using not + all() # initialize tupletest_tup = (10, 4, 5, 6, None) # printing original tupleprint("The original tuple : " + str(test_tup)) # Check if tuple has any None value# using not + all()res = not all(test_tup) # printing resultprint("Does tuple contain any None value ? : " + str(res))
The original tuple : (10, 4, 5, 6, None)
Does tuple contain any None value ? : True
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Nov, 2019"
},
{
"code": null,
"e": 315,
"s": 28,
"text": "Sometimes, while working with Python, we can have a problem in which we have a record and we need to check if it contains all valid values i.e has any None value. This kind of problem is common in data preprocessing steps. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 518,
"s": 315,
"text": "Method #1 : Using any() + map() + lambdaCombination of above functions can be used to perform this task. In this, we check for any element using any() and extension of logic is done by map() and lambda."
},
{
"code": "# Python3 code to demonstrate working of# Check if tuple has any None value# using any() + map() + lambda # initialize tupletest_tup = (10, 4, 5, 6, None) # printing original tupleprint(\"The original tuple : \" + str(test_tup)) # Check if tuple has any None value# using any() + map() + lambdares = any(map(lambda ele: ele is None, test_tup)) # printing resultprint(\"Does tuple contain any None value ? : \" + str(res))",
"e": 940,
"s": 518,
"text": null
},
{
"code": null,
"e": 1025,
"s": 940,
"text": "The original tuple : (10, 4, 5, 6, None)\nDoes tuple contain any None value ? : True\n"
},
{
"code": null,
"e": 1175,
"s": 1027,
"text": "Method #2 : Using not + all()This checks for truthness of all elements of tuple using all() and with not, returns True if there is no None element."
},
{
"code": "# Python3 code to demonstrate working of# Check if tuple has any None value# using not + all() # initialize tupletest_tup = (10, 4, 5, 6, None) # printing original tupleprint(\"The original tuple : \" + str(test_tup)) # Check if tuple has any None value# using not + all()res = not all(test_tup) # printing resultprint(\"Does tuple contain any None value ? : \" + str(res))",
"e": 1549,
"s": 1175,
"text": null
},
{
"code": null,
"e": 1634,
"s": 1549,
"text": "The original tuple : (10, 4, 5, 6, None)\nDoes tuple contain any None value ? : True\n"
},
{
"code": null,
"e": 1656,
"s": 1634,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 1663,
"s": 1656,
"text": "Python"
},
{
"code": null,
"e": 1679,
"s": 1663,
"text": "Python Programs"
}
] |
How to find arctangent with Examples | 21 Oct, 2020
The arctangent is the inverse of the tangent function. It returns the angle whose tangent is the given number.
catan() is an inbuilt function in <complex.h> header file which returns the complex inverse tangent (or arc tangent) of any constant, which divides the imaginary axis on the basis of the inverse tangent in the closed interval [-i, +i] (where i stands for iota), used for evaluation of a complex object say z is on imaginary axis whereas to determine a complex object which is real or integer, then internally invokes pre-defined methods as:
Method
Return Type
1.
Returns complex arc tangent lies in a range along real axis [-PI/2, +PI/2] for an argument of type double.
2.
Returns complex arc tangent lies in a range along real axis [-PI/2, +PI/2] for an argument of type float.
3.
Returns complex arc tangent lies in a range along real axis [-PI/2, +PI/2] for an argument of type long double.
4.
5.
6.
Syntax:
atan(double arg);
atanf(float arg);
atanl(long double arg);
where arg is a floating-point value
catan(double complex z);
catanf(float complex z);
catanl( long double complex z);
where z is a Type – generic macro
Parameter: These functions accept one mandatory parameter z which specifies the inverse tangent. The parameter can be of double, float, or long double datatype.
Return Value: This function returns complex arc tangent/arc tangent according to the type of the argument passed.
Below are the programs illustrate the above method:
Program 1: This program will illustrate the functions atan(), atanf(), and atanl() computes the principal value of the arc tangent of floating – point argument. If a range error occurs due to underflow, the correct result after rounding off is returned.
C
// C program to illustrate the use// of functions atan(), atanf(),// and atanl()#include <math.h>#include <stdio.h> // Driver Codeint main(){ // For function atan() printf("atan(1) = %lf, ", atan(1)); printf(" 4*atan(1)=%lf\n", 4 * atan(1)); printf("atan(-0.0) = %+lf, ", atan(-0.0)); printf("atan(+0.0) = %+lf\n", atan(0)); // For special values INFINITY printf("atan(Inf) = %lf, ", atan(INFINITY)); printf("2*atan(Inf) = %lf\n\n", 2 * atan(INFINITY)); // For function atanf() printf("atanf(1.1) = %f, ", atanf(1.1)); printf("4*atanf(1.5)=%f\n", 4 * atanf(1.5)); printf("atanf(-0.3) = %+f, ", atanf(-0.3)); printf("atanf(+0.3) = %+f\n", atanf(0.3)); // For special values INFINITY printf("atanf(Inf) = %f, ", atanf(INFINITY)); printf("2*atanf(Inf) = %f\n\n", 2 * atanf(INFINITY)); // For function atanl() printf("atanl(1.1) = %Lf, ", atanl(1.1)); printf("4*atanl(1.7)=%Lf\n", 4 * atanl(1.7)); printf("atanl(-1.3) = %+Lf, ", atanl(-1.3)); printf("atanl(+0.3) = %+Lf\n", atanl(0.3)); // For special values INFINITY printf("atanl(Inf) = %Lf, ", atanl(INFINITY)); printf("2*atanl(Inf) = %Lf\n\n", 2 * atanl(INFINITY)); return 0;}
atan(1) = 0.785398, 4*atan(1)=3.141593
atan(-0.0) = -0.000000, atan(+0.0) = +0.000000
atan(Inf) = 1.570796, 2*atan(Inf) = 3.141593
atanf(1.1) = 0.832981, 4*atanf(1.5)=3.931175
atanf(-0.3) = -0.291457, atanf(+0.3) = +0.291457
atanf(Inf) = 1.570796, 2*atanf(Inf) = 3.141593
atanl(1.1) = 0.832981, 4*atanl(1.7)=4.156289
atanl(-1.3) = -0.915101, atanl(+0.3) = +0.291457
atanl(Inf) = 1.570796, 2*atanl(Inf) = 3.141593
Program 2: This program will illustrate the functions catan(), catanf(), and catanl() computes the principal value of the arc tangent of complex number as argument.
C
// C program to illustrate the use// of functions catan(), catanf(),// and catanl()#include <complex.h>#include <float.h>#include <stdio.h> // Driver Codeint main(){ // Given Complex Number double complex z1 = catan(2 * I); // Function catan() printf("catan(+0 + 2i) = %lf + %lfi\n", creal(z1), cimag(z1)); // Complex(0, + INFINITY) double complex z2 = 2 * catan(2 * I * DBL_MAX); printf("2*catan(+0 + i*Inf) = %lf%+lfi\n", creal(z2), cimag(z2)); printf("\n"); // Function catanf() float complex z3 = catanf(2 * I); printf("catanf(+0 + 2i) = %f + %fi\n", crealf(z3), cimagf(z3)); // Complex(0, + INFINITY) float complex z4 = 2 * catanf(2 * I * DBL_MAX); printf("2*catanf(+0 + i*Inf) = %f + %fi\n", crealf(z4), cimagf(z4)); printf("\n"); // Function catanl() long double complex z5 = catanl(2 * I); printf("catan(+0+2i) = %Lf%+Lfi\n", creall(z5), cimagl(z5)); // Complex(0, + INFINITY) long double complex z6 = 2 * catanl(2 * I * DBL_MAX); printf("2*catanl(+0 + i*Inf) = %Lf + %Lfi\n", creall(z6), cimagl(z6));}
catan(+0 + 2i) = 1.570796 + 0.549306i
2*catan(+0 + i*Inf) = 3.141593+0.000000i
catanf(+0 + 2i) = 1.570796 + 0.549306i
2*catanf(+0 + i*Inf) = 3.141593 + 0.000000i
catan(+0+2i) = 1.570796+0.549306i
2*catanl(+0 + i*Inf) = 3.141593 + 0.000000i
Program 3: This program will illustrate the functions catanh(), catanhf(), and catanhl() computes the complex arc hyperbolic tangent of z along the real axis and in the interval [-i*PI/2, +i*PI/2] along the imaginary axis.
C
// C program to illustrate the use// of functions catanh(), catanhf(),// and catanhl()#include <complex.h>#include <stdio.h> // Driver Codeint main(){ // Function catanh() double complex z1 = catanh(2); printf("catanh(+2+0i) = %lf%+lfi\n", creal(z1), cimag(z1)); // for any z, atanh(z) = atan(iz)/i // I denotes Imaginary // part of the complex number double complex z2 = catanh(1 + 2 * I); printf("catanh(1+2i) = %lf%+lfi\n\n", creal(z2), cimag(z2)); // Function catanhf() float complex z3 = catanhf(2); printf("catanhf(+2+0i) = %f%+fi\n", crealf(z3), cimagf(z3)); // for any z, atanh(z) = atan(iz)/i float complex z4 = catanhf(1 + 2 * I); printf("catanhf(1+2i) = %f%+fi\n\n", crealf(z4), cimagf(z4)); // Function catanh() long double complex z5 = catanhl(2); printf("catanhl(+2+0i) = %Lf%+Lfi\n", creall(z5), cimagl(z5)); // for any z, atanh(z) = atan(iz)/i long double complex z6 = catanhl(1 + 2 * I); printf("catanhl(1+2i) = %Lf%+Lfi\n\n", creall(z6), cimagl(z6));}
catanh(+2+0i) = 0.549306+1.570796i
catanh(1+2i) = 0.173287+1.178097i
catanhf(+2+0i) = 0.549306+1.570796i
catanhf(1+2i) = 0.173287+1.178097i
catanhl(+2+0i) = 0.549306+1.570796i
catanhl(1+2i) = 0.173287+1.178097i
CPP-Library
cpp-math
C Programs
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Difference between break and continue statement in C
C Hello World Program
C program to find the length of a string
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Oct, 2020"
},
{
"code": null,
"e": 139,
"s": 28,
"text": "The arctangent is the inverse of the tangent function. It returns the angle whose tangent is the given number."
},
{
"code": null,
"e": 580,
"s": 139,
"text": "catan() is an inbuilt function in <complex.h> header file which returns the complex inverse tangent (or arc tangent) of any constant, which divides the imaginary axis on the basis of the inverse tangent in the closed interval [-i, +i] (where i stands for iota), used for evaluation of a complex object say z is on imaginary axis whereas to determine a complex object which is real or integer, then internally invokes pre-defined methods as:"
},
{
"code": null,
"e": 588,
"s": 580,
"text": "Method "
},
{
"code": null,
"e": 600,
"s": 588,
"text": "Return Type"
},
{
"code": null,
"e": 603,
"s": 600,
"text": "1."
},
{
"code": null,
"e": 710,
"s": 603,
"text": "Returns complex arc tangent lies in a range along real axis [-PI/2, +PI/2] for an argument of type double."
},
{
"code": null,
"e": 713,
"s": 710,
"text": "2."
},
{
"code": null,
"e": 819,
"s": 713,
"text": "Returns complex arc tangent lies in a range along real axis [-PI/2, +PI/2] for an argument of type float."
},
{
"code": null,
"e": 822,
"s": 819,
"text": "3."
},
{
"code": null,
"e": 934,
"s": 822,
"text": "Returns complex arc tangent lies in a range along real axis [-PI/2, +PI/2] for an argument of type long double."
},
{
"code": null,
"e": 937,
"s": 934,
"text": "4."
},
{
"code": null,
"e": 940,
"s": 937,
"text": "5."
},
{
"code": null,
"e": 943,
"s": 940,
"text": "6."
},
{
"code": null,
"e": 951,
"s": 943,
"text": "Syntax:"
},
{
"code": null,
"e": 1165,
"s": 951,
"text": "atan(double arg);\natanf(float arg);\natanl(long double arg);\nwhere arg is a floating-point value\n\ncatan(double complex z);\ncatanf(float complex z);\ncatanl( long double complex z);\nwhere z is a Type – generic macro\n"
},
{
"code": null,
"e": 1326,
"s": 1165,
"text": "Parameter: These functions accept one mandatory parameter z which specifies the inverse tangent. The parameter can be of double, float, or long double datatype."
},
{
"code": null,
"e": 1440,
"s": 1326,
"text": "Return Value: This function returns complex arc tangent/arc tangent according to the type of the argument passed."
},
{
"code": null,
"e": 1492,
"s": 1440,
"text": "Below are the programs illustrate the above method:"
},
{
"code": null,
"e": 1746,
"s": 1492,
"text": "Program 1: This program will illustrate the functions atan(), atanf(), and atanl() computes the principal value of the arc tangent of floating – point argument. If a range error occurs due to underflow, the correct result after rounding off is returned."
},
{
"code": null,
"e": 1748,
"s": 1746,
"text": "C"
},
{
"code": "// C program to illustrate the use// of functions atan(), atanf(),// and atanl()#include <math.h>#include <stdio.h> // Driver Codeint main(){ // For function atan() printf(\"atan(1) = %lf, \", atan(1)); printf(\" 4*atan(1)=%lf\\n\", 4 * atan(1)); printf(\"atan(-0.0) = %+lf, \", atan(-0.0)); printf(\"atan(+0.0) = %+lf\\n\", atan(0)); // For special values INFINITY printf(\"atan(Inf) = %lf, \", atan(INFINITY)); printf(\"2*atan(Inf) = %lf\\n\\n\", 2 * atan(INFINITY)); // For function atanf() printf(\"atanf(1.1) = %f, \", atanf(1.1)); printf(\"4*atanf(1.5)=%f\\n\", 4 * atanf(1.5)); printf(\"atanf(-0.3) = %+f, \", atanf(-0.3)); printf(\"atanf(+0.3) = %+f\\n\", atanf(0.3)); // For special values INFINITY printf(\"atanf(Inf) = %f, \", atanf(INFINITY)); printf(\"2*atanf(Inf) = %f\\n\\n\", 2 * atanf(INFINITY)); // For function atanl() printf(\"atanl(1.1) = %Lf, \", atanl(1.1)); printf(\"4*atanl(1.7)=%Lf\\n\", 4 * atanl(1.7)); printf(\"atanl(-1.3) = %+Lf, \", atanl(-1.3)); printf(\"atanl(+0.3) = %+Lf\\n\", atanl(0.3)); // For special values INFINITY printf(\"atanl(Inf) = %Lf, \", atanl(INFINITY)); printf(\"2*atanl(Inf) = %Lf\\n\\n\", 2 * atanl(INFINITY)); return 0;}",
"e": 3149,
"s": 1748,
"text": null
},
{
"code": null,
"e": 3566,
"s": 3149,
"text": "atan(1) = 0.785398, 4*atan(1)=3.141593\natan(-0.0) = -0.000000, atan(+0.0) = +0.000000\natan(Inf) = 1.570796, 2*atan(Inf) = 3.141593\n\natanf(1.1) = 0.832981, 4*atanf(1.5)=3.931175\natanf(-0.3) = -0.291457, atanf(+0.3) = +0.291457\natanf(Inf) = 1.570796, 2*atanf(Inf) = 3.141593\n\natanl(1.1) = 0.832981, 4*atanl(1.7)=4.156289\natanl(-1.3) = -0.915101, atanl(+0.3) = +0.291457\natanl(Inf) = 1.570796, 2*atanl(Inf) = 3.141593\n"
},
{
"code": null,
"e": 3731,
"s": 3566,
"text": "Program 2: This program will illustrate the functions catan(), catanf(), and catanl() computes the principal value of the arc tangent of complex number as argument."
},
{
"code": null,
"e": 3733,
"s": 3731,
"text": "C"
},
{
"code": "// C program to illustrate the use// of functions catan(), catanf(),// and catanl()#include <complex.h>#include <float.h>#include <stdio.h> // Driver Codeint main(){ // Given Complex Number double complex z1 = catan(2 * I); // Function catan() printf(\"catan(+0 + 2i) = %lf + %lfi\\n\", creal(z1), cimag(z1)); // Complex(0, + INFINITY) double complex z2 = 2 * catan(2 * I * DBL_MAX); printf(\"2*catan(+0 + i*Inf) = %lf%+lfi\\n\", creal(z2), cimag(z2)); printf(\"\\n\"); // Function catanf() float complex z3 = catanf(2 * I); printf(\"catanf(+0 + 2i) = %f + %fi\\n\", crealf(z3), cimagf(z3)); // Complex(0, + INFINITY) float complex z4 = 2 * catanf(2 * I * DBL_MAX); printf(\"2*catanf(+0 + i*Inf) = %f + %fi\\n\", crealf(z4), cimagf(z4)); printf(\"\\n\"); // Function catanl() long double complex z5 = catanl(2 * I); printf(\"catan(+0+2i) = %Lf%+Lfi\\n\", creall(z5), cimagl(z5)); // Complex(0, + INFINITY) long double complex z6 = 2 * catanl(2 * I * DBL_MAX); printf(\"2*catanl(+0 + i*Inf) = %Lf + %Lfi\\n\", creall(z6), cimagl(z6));}",
"e": 4957,
"s": 3733,
"text": null
},
{
"code": null,
"e": 5200,
"s": 4957,
"text": "catan(+0 + 2i) = 1.570796 + 0.549306i\n2*catan(+0 + i*Inf) = 3.141593+0.000000i\n\ncatanf(+0 + 2i) = 1.570796 + 0.549306i\n2*catanf(+0 + i*Inf) = 3.141593 + 0.000000i\n\ncatan(+0+2i) = 1.570796+0.549306i\n2*catanl(+0 + i*Inf) = 3.141593 + 0.000000i\n"
},
{
"code": null,
"e": 5423,
"s": 5200,
"text": "Program 3: This program will illustrate the functions catanh(), catanhf(), and catanhl() computes the complex arc hyperbolic tangent of z along the real axis and in the interval [-i*PI/2, +i*PI/2] along the imaginary axis."
},
{
"code": null,
"e": 5425,
"s": 5423,
"text": "C"
},
{
"code": "// C program to illustrate the use// of functions catanh(), catanhf(),// and catanhl()#include <complex.h>#include <stdio.h> // Driver Codeint main(){ // Function catanh() double complex z1 = catanh(2); printf(\"catanh(+2+0i) = %lf%+lfi\\n\", creal(z1), cimag(z1)); // for any z, atanh(z) = atan(iz)/i // I denotes Imaginary // part of the complex number double complex z2 = catanh(1 + 2 * I); printf(\"catanh(1+2i) = %lf%+lfi\\n\\n\", creal(z2), cimag(z2)); // Function catanhf() float complex z3 = catanhf(2); printf(\"catanhf(+2+0i) = %f%+fi\\n\", crealf(z3), cimagf(z3)); // for any z, atanh(z) = atan(iz)/i float complex z4 = catanhf(1 + 2 * I); printf(\"catanhf(1+2i) = %f%+fi\\n\\n\", crealf(z4), cimagf(z4)); // Function catanh() long double complex z5 = catanhl(2); printf(\"catanhl(+2+0i) = %Lf%+Lfi\\n\", creall(z5), cimagl(z5)); // for any z, atanh(z) = atan(iz)/i long double complex z6 = catanhl(1 + 2 * I); printf(\"catanhl(1+2i) = %Lf%+Lfi\\n\\n\", creall(z6), cimagl(z6));}",
"e": 6527,
"s": 5425,
"text": null
},
{
"code": null,
"e": 6741,
"s": 6527,
"text": "catanh(+2+0i) = 0.549306+1.570796i\ncatanh(1+2i) = 0.173287+1.178097i\n\ncatanhf(+2+0i) = 0.549306+1.570796i\ncatanhf(1+2i) = 0.173287+1.178097i\n\ncatanhl(+2+0i) = 0.549306+1.570796i\ncatanhl(1+2i) = 0.173287+1.178097i\n"
},
{
"code": null,
"e": 6753,
"s": 6741,
"text": "CPP-Library"
},
{
"code": null,
"e": 6762,
"s": 6753,
"text": "cpp-math"
},
{
"code": null,
"e": 6773,
"s": 6762,
"text": "C Programs"
},
{
"code": null,
"e": 6786,
"s": 6773,
"text": "Mathematical"
},
{
"code": null,
"e": 6799,
"s": 6786,
"text": "Mathematical"
},
{
"code": null,
"e": 6897,
"s": 6799,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6938,
"s": 6897,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 6969,
"s": 6938,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 7022,
"s": 6969,
"text": "Difference between break and continue statement in C"
},
{
"code": null,
"e": 7044,
"s": 7022,
"text": "C Hello World Program"
},
{
"code": null,
"e": 7085,
"s": 7044,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 7115,
"s": 7085,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 7158,
"s": 7115,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7218,
"s": 7158,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 7233,
"s": 7218,
"text": "C++ Data Types"
}
] |
Harshad (Or Niven) Number | 17 Jun, 2022
An integer number in base 10 which is divisible by the sum of its digits is said to be a Harshad Number. An n-harshad number is an integer number divisible by the sum of its digit in base n.Below are the first few Harshad Numbers represented in base 10:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20.........Given a number in base 10, our task is to check if it is a Harshad Number or not.
Examples :
Input: 3
Output: 3 is a Harshad Number
Input: 18
Output: 18 is a Harshad Number
Input: 15
Output: 15 is not a Harshad Number
1. Extract all the digits from the number using the % operator and calculate the sum. 2. Check if the number is divisible by sum.
Below is the implementation of the above idea:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if a number is Harshad// Number or not.#include <bits/stdc++.h>using namespace std; // function to check Harshad Numberbool checkHarshad(int n){ // calculate sum of digits int sum = 0; for (int temp = n; temp > 0; temp /= 10) sum += temp % 10; // Return true if sum of digits is multiple // of n return (n % sum == 0);} // driver program to check above functionint main(){ checkHarshad(12) ? cout << "Yes\n" : cout << "No\n"; checkHarshad(15) ? cout << "Yes\n" : cout << "No\n"; return 0;}
// Java program to check if a number is Harshad// Number or not public class GFG { // method to check Harshad Number static boolean checkHarshad(int n) { // calculate sum of digits int sum = 0; for (int temp = n; temp > 0; temp /= 10) sum += temp % 10; // Return true if sum of digits is multiple // of n return (n % sum == 0); } // Driver program to test above functions public static void main(String[] args) { System.out.println(checkHarshad(12) ? "Yes" : "No"); System.out.println(checkHarshad(15) ? "Yes" : "No"); }}
# Python program to check# if a number is Harshad# Number or not. def checkHarshad( n ) : sum = 0 temp = n while temp > 0 : sum = sum + temp % 10 temp = temp // 10 # Return true if sum of # digits is multiple of n return n % sum == 0 # Driver Codeif(checkHarshad(12)) : print("Yes")else : print ("No") if (checkHarshad(15)) : print("Yes")else : print ("No") # This code is contributed# by Nikita Tiwari
// C# program to check if a number is Harshad// Number or notusing System; public class GFG { // method to check Harshad Number static bool checkHarshad(int n) { // calculate sum of digits int sum = 0; for (int temp = n; temp > 0; temp /= 10) sum += temp % 10; // Return true if sum of digits is // multiple of n return (n % sum == 0); } // Driver program to test above functions public static void Main() { Console.WriteLine(checkHarshad(12) ? "Yes" : "No"); Console.WriteLine(checkHarshad(15) ? "Yes" : "No"); }} // This code is contributed by vt_m.
<?php// php program to check if// a number is Harshad// Number or not. // function to check// Harshad Numberfunction checkHarshad($n){ // calculate sum of digits $sum = 0; for ($temp = $n; $temp > 0; $temp /= 10) $sum += $temp % 10; // Return true if sum of // digits is multiple of n return ($n % $sum == 0);} // Driver Code$k = checkHarshad(12) ? "Yes\n" : "No\n"; echo($k);$k = checkHarshad(15) ? "Yes\n" : "No\n"; echo($k); // This code is contributed by ajit.?>
<script> // Javascript program to check if a number is Harshad Number or not // method to check Harshad Number function checkHarshad(n) { // calculate sum of digits let sum = 0; for (let temp = n; temp > 0; temp = parseInt(temp / 10, 10)) sum += temp % 10; // Return true if sum of digits is // multiple of n return (n % sum == 0); } document.write(checkHarshad(12) ? "Yes" + "</br>" : "No" + "</br>"); document.write(checkHarshad(15) ? "Yes" + "</br>" : "No" + "</br>"); </script>
Output :
Yes
No
Method #2: Using string:
We have to convert the given number to a string by taking a new variable.
Traverse the string, Convert each element to integer and add this to sum.
If the number is divisible by sum then it is Harshad number.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of above approach#include<bits/stdc++.h>using namespace std; string checkHarshad(int n){ // Converting integer to string string st = to_string(n); // Initialising sum to 0 int sum = 0; int length = st.length(); // Traversing through the string for(char i : st) { // Converting character to int sum = sum + (i - '0'); } // Comparing number and sum if (n % sum == 0) { return "Yes"; } else { return "No"; }} // Driver Codeint main(){ int number = 18; // Passing this number to get result function cout << checkHarshad(number) << endl;} // This code is contributed by rrrtnx
import java.io.*;// java code to check the given number is Harshad or notclass GFG{ // function to check that given number // is Harshad or not. static String checkHarshad(int n) { // converting the integer to string String st = Integer.toString(n); int sum = 0; // calculating total number of digits // in a number int length=st.length(); // adding the all digits of a number for(int i = 0; i < length; i++){ sum += st.charAt(i)-'0'; } // checking that sum is divisior of n or not if(n % sum == 0){ return "YES"; } else{ return "NO"; } } // driver code public static void main(String args[]){ int number = 18; // function call System.out.println(checkHarshad(number)); }} // This code is contributed by Machhaliya Muhammad
# Python implementation of above approachdef checkHarshad(n): # Converting integer to string st = str(n) # Initialising sum to 0 sum = 0 length = len(st) # Traversing through the string for i in st: # Converting character to int sum = sum + int(i) # Comparing number and sum if (n % sum == 0): return "Yes" else: return "No" # Driver Codenumber = 18# passing this number to get result functionprint(checkHarshad(number)) # This code is contributed by vikkycirus
// C# program to find the radii// of the three tangent circles// of equal radius when the radius// of the circumscribed circle is givenusing System; class GFG { static String checkHarshad(int n) { // Converting integer to string String st = n.ToString(); // Initialising sum to 0 int sum = 0; int length = st.Length; // Traversing through the string foreach(char i in st) { // Converting character to int sum = sum + (i - '0'); } // Comparing number and sum if (n % sum == 0) { return "Yes"; } else { return "No"; } } // Driver code public static void Main() { int number = 18; // Passing this number to get result function Console.WriteLine(checkHarshad(number)); }} // This code is contributed by Nidhi goel
<script>// Javascript implementation of above approachfunction checkHarshad(n){ // Converting integer to string let st = String(n) // Initialising sum to 0 let sum = 0 let length = st.length // Traversing through the string for(i in st){ // Converting character to int sum = sum + parseInt(i) } // Comparing number and sum if (n % sum == 0){ return "Yes" } else{ return "No" }} // Driver Codelet number = 18// passing this number to get result functiondocument.write(checkHarshad(number)) // This code is contributed by _saurabh_jaiswal</script>
Yes
Time Complexity: O(n)
References: https://en.wikipedia.org/wiki/Harshad_numberThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
nandanamar
vikkycirus
divyesh072019
_saurabh_jaiswal
rrrtnx
amartyaghoshgfg
shaheeneallamaiqbal
classroompxico
number-digits
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operators in C / C++
Find minimum number of coins that make a given value
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Modulo 10^9+7 (1000000007)
Program for factorial of a number
Program to find sum of elements in a given array
Program to print prime numbers from 1 to N.
Merge two sorted arrays with O(1) extra space
Print all possible combinations of r elements in a given array of size n | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 437,
"s": 52,
"text": "An integer number in base 10 which is divisible by the sum of its digits is said to be a Harshad Number. An n-harshad number is an integer number divisible by the sum of its digit in base n.Below are the first few Harshad Numbers represented in base 10:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20.........Given a number in base 10, our task is to check if it is a Harshad Number or not."
},
{
"code": null,
"e": 449,
"s": 437,
"text": "Examples : "
},
{
"code": null,
"e": 576,
"s": 449,
"text": "Input: 3\nOutput: 3 is a Harshad Number\n\nInput: 18\nOutput: 18 is a Harshad Number\n\nInput: 15\nOutput: 15 is not a Harshad Number"
},
{
"code": null,
"e": 706,
"s": 576,
"text": "1. Extract all the digits from the number using the % operator and calculate the sum. 2. Check if the number is divisible by sum."
},
{
"code": null,
"e": 753,
"s": 706,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 757,
"s": 753,
"text": "C++"
},
{
"code": null,
"e": 762,
"s": 757,
"text": "Java"
},
{
"code": null,
"e": 770,
"s": 762,
"text": "Python3"
},
{
"code": null,
"e": 773,
"s": 770,
"text": "C#"
},
{
"code": null,
"e": 777,
"s": 773,
"text": "PHP"
},
{
"code": null,
"e": 788,
"s": 777,
"text": "Javascript"
},
{
"code": "// C++ program to check if a number is Harshad// Number or not.#include <bits/stdc++.h>using namespace std; // function to check Harshad Numberbool checkHarshad(int n){ // calculate sum of digits int sum = 0; for (int temp = n; temp > 0; temp /= 10) sum += temp % 10; // Return true if sum of digits is multiple // of n return (n % sum == 0);} // driver program to check above functionint main(){ checkHarshad(12) ? cout << \"Yes\\n\" : cout << \"No\\n\"; checkHarshad(15) ? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}",
"e": 1346,
"s": 788,
"text": null
},
{
"code": "// Java program to check if a number is Harshad// Number or not public class GFG { // method to check Harshad Number static boolean checkHarshad(int n) { // calculate sum of digits int sum = 0; for (int temp = n; temp > 0; temp /= 10) sum += temp % 10; // Return true if sum of digits is multiple // of n return (n % sum == 0); } // Driver program to test above functions public static void main(String[] args) { System.out.println(checkHarshad(12) ? \"Yes\" : \"No\"); System.out.println(checkHarshad(15) ? \"Yes\" : \"No\"); }}",
"e": 1961,
"s": 1346,
"text": null
},
{
"code": "# Python program to check# if a number is Harshad# Number or not. def checkHarshad( n ) : sum = 0 temp = n while temp > 0 : sum = sum + temp % 10 temp = temp // 10 # Return true if sum of # digits is multiple of n return n % sum == 0 # Driver Codeif(checkHarshad(12)) : print(\"Yes\")else : print (\"No\") if (checkHarshad(15)) : print(\"Yes\")else : print (\"No\") # This code is contributed# by Nikita Tiwari",
"e": 2400,
"s": 1961,
"text": null
},
{
"code": "// C# program to check if a number is Harshad// Number or notusing System; public class GFG { // method to check Harshad Number static bool checkHarshad(int n) { // calculate sum of digits int sum = 0; for (int temp = n; temp > 0; temp /= 10) sum += temp % 10; // Return true if sum of digits is // multiple of n return (n % sum == 0); } // Driver program to test above functions public static void Main() { Console.WriteLine(checkHarshad(12) ? \"Yes\" : \"No\"); Console.WriteLine(checkHarshad(15) ? \"Yes\" : \"No\"); }} // This code is contributed by vt_m.",
"e": 3048,
"s": 2400,
"text": null
},
{
"code": "<?php// php program to check if// a number is Harshad// Number or not. // function to check// Harshad Numberfunction checkHarshad($n){ // calculate sum of digits $sum = 0; for ($temp = $n; $temp > 0; $temp /= 10) $sum += $temp % 10; // Return true if sum of // digits is multiple of n return ($n % $sum == 0);} // Driver Code$k = checkHarshad(12) ? \"Yes\\n\" : \"No\\n\"; echo($k);$k = checkHarshad(15) ? \"Yes\\n\" : \"No\\n\"; echo($k); // This code is contributed by ajit.?>",
"e": 3569,
"s": 3048,
"text": null
},
{
"code": "<script> // Javascript program to check if a number is Harshad Number or not // method to check Harshad Number function checkHarshad(n) { // calculate sum of digits let sum = 0; for (let temp = n; temp > 0; temp = parseInt(temp / 10, 10)) sum += temp % 10; // Return true if sum of digits is // multiple of n return (n % sum == 0); } document.write(checkHarshad(12) ? \"Yes\" + \"</br>\" : \"No\" + \"</br>\"); document.write(checkHarshad(15) ? \"Yes\" + \"</br>\" : \"No\" + \"</br>\"); </script>",
"e": 4151,
"s": 3569,
"text": null
},
{
"code": null,
"e": 4161,
"s": 4151,
"text": "Output : "
},
{
"code": null,
"e": 4168,
"s": 4161,
"text": "Yes\nNo"
},
{
"code": null,
"e": 4193,
"s": 4168,
"text": "Method #2: Using string:"
},
{
"code": null,
"e": 4267,
"s": 4193,
"text": "We have to convert the given number to a string by taking a new variable."
},
{
"code": null,
"e": 4341,
"s": 4267,
"text": "Traverse the string, Convert each element to integer and add this to sum."
},
{
"code": null,
"e": 4402,
"s": 4341,
"text": "If the number is divisible by sum then it is Harshad number."
},
{
"code": null,
"e": 4453,
"s": 4402,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 4457,
"s": 4453,
"text": "C++"
},
{
"code": null,
"e": 4462,
"s": 4457,
"text": "Java"
},
{
"code": null,
"e": 4470,
"s": 4462,
"text": "Python3"
},
{
"code": null,
"e": 4473,
"s": 4470,
"text": "C#"
},
{
"code": null,
"e": 4484,
"s": 4473,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include<bits/stdc++.h>using namespace std; string checkHarshad(int n){ // Converting integer to string string st = to_string(n); // Initialising sum to 0 int sum = 0; int length = st.length(); // Traversing through the string for(char i : st) { // Converting character to int sum = sum + (i - '0'); } // Comparing number and sum if (n % sum == 0) { return \"Yes\"; } else { return \"No\"; }} // Driver Codeint main(){ int number = 18; // Passing this number to get result function cout << checkHarshad(number) << endl;} // This code is contributed by rrrtnx",
"e": 5193,
"s": 4484,
"text": null
},
{
"code": "import java.io.*;// java code to check the given number is Harshad or notclass GFG{ // function to check that given number // is Harshad or not. static String checkHarshad(int n) { // converting the integer to string String st = Integer.toString(n); int sum = 0; // calculating total number of digits // in a number int length=st.length(); // adding the all digits of a number for(int i = 0; i < length; i++){ sum += st.charAt(i)-'0'; } // checking that sum is divisior of n or not if(n % sum == 0){ return \"YES\"; } else{ return \"NO\"; } } // driver code public static void main(String args[]){ int number = 18; // function call System.out.println(checkHarshad(number)); }} // This code is contributed by Machhaliya Muhammad",
"e": 6112,
"s": 5193,
"text": null
},
{
"code": "# Python implementation of above approachdef checkHarshad(n): # Converting integer to string st = str(n) # Initialising sum to 0 sum = 0 length = len(st) # Traversing through the string for i in st: # Converting character to int sum = sum + int(i) # Comparing number and sum if (n % sum == 0): return \"Yes\" else: return \"No\" # Driver Codenumber = 18# passing this number to get result functionprint(checkHarshad(number)) # This code is contributed by vikkycirus",
"e": 6652,
"s": 6112,
"text": null
},
{
"code": "// C# program to find the radii// of the three tangent circles// of equal radius when the radius// of the circumscribed circle is givenusing System; class GFG { static String checkHarshad(int n) { // Converting integer to string String st = n.ToString(); // Initialising sum to 0 int sum = 0; int length = st.Length; // Traversing through the string foreach(char i in st) { // Converting character to int sum = sum + (i - '0'); } // Comparing number and sum if (n % sum == 0) { return \"Yes\"; } else { return \"No\"; } } // Driver code public static void Main() { int number = 18; // Passing this number to get result function Console.WriteLine(checkHarshad(number)); }} // This code is contributed by Nidhi goel",
"e": 7552,
"s": 6652,
"text": null
},
{
"code": "<script>// Javascript implementation of above approachfunction checkHarshad(n){ // Converting integer to string let st = String(n) // Initialising sum to 0 let sum = 0 let length = st.length // Traversing through the string for(i in st){ // Converting character to int sum = sum + parseInt(i) } // Comparing number and sum if (n % sum == 0){ return \"Yes\" } else{ return \"No\" }} // Driver Codelet number = 18// passing this number to get result functiondocument.write(checkHarshad(number)) // This code is contributed by _saurabh_jaiswal</script>",
"e": 8181,
"s": 7552,
"text": null
},
{
"code": null,
"e": 8185,
"s": 8181,
"text": "Yes"
},
{
"code": null,
"e": 8208,
"s": 8185,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 8685,
"s": 8208,
"text": "References: https://en.wikipedia.org/wiki/Harshad_numberThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 8693,
"s": 8687,
"text": "jit_t"
},
{
"code": null,
"e": 8704,
"s": 8693,
"text": "nandanamar"
},
{
"code": null,
"e": 8715,
"s": 8704,
"text": "vikkycirus"
},
{
"code": null,
"e": 8729,
"s": 8715,
"text": "divyesh072019"
},
{
"code": null,
"e": 8746,
"s": 8729,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 8753,
"s": 8746,
"text": "rrrtnx"
},
{
"code": null,
"e": 8769,
"s": 8753,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 8789,
"s": 8769,
"text": "shaheeneallamaiqbal"
},
{
"code": null,
"e": 8804,
"s": 8789,
"text": "classroompxico"
},
{
"code": null,
"e": 8818,
"s": 8804,
"text": "number-digits"
},
{
"code": null,
"e": 8825,
"s": 8818,
"text": "series"
},
{
"code": null,
"e": 8838,
"s": 8825,
"text": "Mathematical"
},
{
"code": null,
"e": 8851,
"s": 8838,
"text": "Mathematical"
},
{
"code": null,
"e": 8858,
"s": 8851,
"text": "series"
},
{
"code": null,
"e": 8956,
"s": 8858,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8977,
"s": 8956,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 9030,
"s": 8977,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 9073,
"s": 9030,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 9105,
"s": 9073,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 9132,
"s": 9105,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 9166,
"s": 9132,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 9215,
"s": 9166,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 9259,
"s": 9215,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 9305,
"s": 9259,
"text": "Merge two sorted arrays with O(1) extra space"
}
] |
Python reversed() function | 23 Sep, 2021
Python reversed() method returns an iterator that accesses the given sequence in the reverse order.
reversed(sequ)
sequ : Sequence to be reversed.
returns an iterator that accesses the given sequence in the reverse order.
Here we use tuple and range.
Python3
# Python code to demonstrate working of# reversed() # For tupleseqTuple = ('g', 'e', 'e', 'k', 's')print(list(reversed(seqTuple))) # For rangeseqRange = range(1, 5)print(list(reversed(seqRange)))
Output:
['s', 'k', 'e', 'e', 'g']
[4, 3, 2, 1]
Python3
class gfg: vowels = ['a', 'e', 'i', 'o', 'u'] # Function to reverse the list def __reversed__(self): return reversed(self.vowels) # Main Function if __name__ == '__main__': obj = gfg() print(list(reversed(obj)))
Output :
['u', 'o', 'i', 'e', 'a']
Python3
vowels = ['a', 'e', 'i', 'o', 'u']print(list(reversed(vowels)))
Output:
['u', 'o', 'i', 'e', 'a']
Python3
str = "Geeksforgeeks"print(list(reversed(str)))
Output:
['s', 'k', 'e', 'e', 'g', 'r', 'o', 'f', 's', 'k', 'e', 'e', 'G']
Python3
# For listseqList = [1, 2, 4, 3, 5]print(list(reversed(seqList)))
Output:
[5, 3, 4, 2, 1]
kumar_satyam
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 153,
"s": 53,
"text": "Python reversed() method returns an iterator that accesses the given sequence in the reverse order."
},
{
"code": null,
"e": 169,
"s": 153,
"text": "reversed(sequ) "
},
{
"code": null,
"e": 202,
"s": 169,
"text": "sequ : Sequence to be reversed. "
},
{
"code": null,
"e": 278,
"s": 202,
"text": "returns an iterator that accesses the given sequence in the reverse order. "
},
{
"code": null,
"e": 307,
"s": 278,
"text": "Here we use tuple and range."
},
{
"code": null,
"e": 315,
"s": 307,
"text": "Python3"
},
{
"code": "# Python code to demonstrate working of# reversed() # For tupleseqTuple = ('g', 'e', 'e', 'k', 's')print(list(reversed(seqTuple))) # For rangeseqRange = range(1, 5)print(list(reversed(seqRange)))",
"e": 511,
"s": 315,
"text": null
},
{
"code": null,
"e": 519,
"s": 511,
"text": "Output:"
},
{
"code": null,
"e": 558,
"s": 519,
"text": "['s', 'k', 'e', 'e', 'g']\n[4, 3, 2, 1]"
},
{
"code": null,
"e": 566,
"s": 558,
"text": "Python3"
},
{
"code": "class gfg: vowels = ['a', 'e', 'i', 'o', 'u'] # Function to reverse the list def __reversed__(self): return reversed(self.vowels) # Main Function if __name__ == '__main__': obj = gfg() print(list(reversed(obj)))",
"e": 803,
"s": 566,
"text": null
},
{
"code": null,
"e": 813,
"s": 803,
"text": "Output : "
},
{
"code": null,
"e": 839,
"s": 813,
"text": "['u', 'o', 'i', 'e', 'a']"
},
{
"code": null,
"e": 847,
"s": 839,
"text": "Python3"
},
{
"code": "vowels = ['a', 'e', 'i', 'o', 'u']print(list(reversed(vowels)))",
"e": 911,
"s": 847,
"text": null
},
{
"code": null,
"e": 919,
"s": 911,
"text": "Output:"
},
{
"code": null,
"e": 945,
"s": 919,
"text": "['u', 'o', 'i', 'e', 'a']"
},
{
"code": null,
"e": 953,
"s": 945,
"text": "Python3"
},
{
"code": "str = \"Geeksforgeeks\"print(list(reversed(str)))",
"e": 1001,
"s": 953,
"text": null
},
{
"code": null,
"e": 1009,
"s": 1001,
"text": "Output:"
},
{
"code": null,
"e": 1075,
"s": 1009,
"text": "['s', 'k', 'e', 'e', 'g', 'r', 'o', 'f', 's', 'k', 'e', 'e', 'G']"
},
{
"code": null,
"e": 1083,
"s": 1075,
"text": "Python3"
},
{
"code": "# For listseqList = [1, 2, 4, 3, 5]print(list(reversed(seqList)))",
"e": 1149,
"s": 1083,
"text": null
},
{
"code": null,
"e": 1157,
"s": 1149,
"text": "Output:"
},
{
"code": null,
"e": 1173,
"s": 1157,
"text": "[5, 3, 4, 2, 1]"
},
{
"code": null,
"e": 1186,
"s": 1173,
"text": "kumar_satyam"
},
{
"code": null,
"e": 1203,
"s": 1186,
"text": "Python-Functions"
},
{
"code": null,
"e": 1210,
"s": 1203,
"text": "Python"
},
{
"code": null,
"e": 1308,
"s": 1210,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1326,
"s": 1308,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1368,
"s": 1326,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1390,
"s": 1368,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1416,
"s": 1390,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1448,
"s": 1416,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1477,
"s": 1448,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1504,
"s": 1477,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1534,
"s": 1504,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1555,
"s": 1534,
"text": "Python OOPs Concepts"
}
] |
How to deal with error “$ operator is invalid for atomic vectors” in R? | This error occurs because $ operator is not designed to access vector elements. If we use $ operator to access the vector elements then R does not understand it and consider it invalid, therefore, we must be very careful about where we should use $ operator. It happens when we give a name to our elements and start thinking that we can treat them as data frame columns which is a wrong approach. To access the vector elements, we should use single square brackets.
Consider the below vector −
> set.seed(1)
> x1<-sample(1:10,20,replace=TRUE)
> x1
[1] 9 4 7 1 2 7 2 3 1 5 5 10 6 10 7 9 5 5 9 9
> names(x1)<-LETTERS[1:20]
> x1
A B C D E F G H I J K L M N O P Q R S T
9 4 7 1 2 7 2 3 1 5 5 10 6 10 7 9 5 5 9 9
> x1$K
Error in x1$K : $ operator is invalid for atomic vectors
Here, we are getting the error that “$ operator is invalid for atomic vectors”. Now we should access the elements of the vector x1 with single square brackets as shown below −
> x1["K"]
K
5
> x1["T"]
T
9
> x1["A"]
A
9
> x1[1]
A
9
Let’s have a look at one more example −
> x2<-sample(1:100,10)
> x2
[1] 37 34 89 44 79 33 84 35 70 74
> names(x2)<-c("A1","A2","A3","A4","A5","A6","A7","A8","A9","A10")
> x2
A1 A2 A3 A4 A5 A6 A7 A8 A9 A10
37 34 89 44 79 33 84 35 70 74
> x2["A10"]
A10
74
> x2["A5"]
A5
79
> x2["A6"]
A6
33
> x2["A1"]
A1
37
> x2["A3"]
A3
89 | [
{
"code": null,
"e": 1653,
"s": 1187,
"text": "This error occurs because $ operator is not designed to access vector elements. If we use $ operator to access the vector elements then R does not understand it and consider it invalid, therefore, we must be very careful about where we should use $ operator. It happens when we give a name to our elements and start thinking that we can treat them as data frame columns which is a wrong approach. To access the vector elements, we should use single square brackets."
},
{
"code": null,
"e": 1681,
"s": 1653,
"text": "Consider the below vector −"
},
{
"code": null,
"e": 1959,
"s": 1681,
"text": "> set.seed(1)\n> x1<-sample(1:10,20,replace=TRUE)\n> x1\n[1] 9 4 7 1 2 7 2 3 1 5 5 10 6 10 7 9 5 5 9 9\n> names(x1)<-LETTERS[1:20]\n> x1\nA B C D E F G H I J K L M N O P Q R S T\n9 4 7 1 2 7 2 3 1 5 5 10 6 10 7 9 5 5 9 9\n> x1$K\nError in x1$K : $ operator is invalid for atomic vectors"
},
{
"code": null,
"e": 2135,
"s": 1959,
"text": "Here, we are getting the error that “$ operator is invalid for atomic vectors”. Now we should access the elements of the vector x1 with single square brackets as shown below −"
},
{
"code": null,
"e": 2189,
"s": 2135,
"text": "> x1[\"K\"]\nK\n5\n> x1[\"T\"]\nT\n9\n> x1[\"A\"]\nA\n9\n> x1[1]\nA\n9"
},
{
"code": null,
"e": 2229,
"s": 2189,
"text": "Let’s have a look at one more example −"
},
{
"code": null,
"e": 2511,
"s": 2229,
"text": "> x2<-sample(1:100,10)\n> x2\n[1] 37 34 89 44 79 33 84 35 70 74\n> names(x2)<-c(\"A1\",\"A2\",\"A3\",\"A4\",\"A5\",\"A6\",\"A7\",\"A8\",\"A9\",\"A10\")\n> x2\nA1 A2 A3 A4 A5 A6 A7 A8 A9 A10\n37 34 89 44 79 33 84 35 70 74\n> x2[\"A10\"]\nA10\n74\n> x2[\"A5\"]\nA5\n79\n> x2[\"A6\"]\nA6\n33\n> x2[\"A1\"]\nA1\n37\n> x2[\"A3\"]\nA3\n89"
}
] |
How to import SASS through npm ? | 02 Oct, 2020
Introduction to SASS: SASS stands for ‘Syntactically awesome style sheets’. It is an extension of CSS, that makes it easy to use variables of CSS, nested rules, inline import, and many other important features
SASS has two syntax options:
SCSS (Sassy CSS): It uses the .scss file extension and is fully compliant with CSS syntax.
SASS: It uses .sass file extension and indentation rather than brackets.
Note: Files can be convert from one syntax to another using sass-convert command.
Steps to install SASS:Step 1: To install SASS, first make sure that node and npm are already installed in the system. If not, then install them using the instructions given below.
First, download the latest version of a node in the system and install it.
Now go to command prompt and address the folder where you want to install SASS.
After that, you have to create package.json file. It manages the dependencies of our project.
Use command written below that will ask for the package name of the user’s choice and the description. Some more formalities are there, just press enter for that and your package.json file will be created.npm init
npm init
Step 2: Now to install SASS one simple command is used:
npm install node-sass --save
Note: – –save in above command is used to save the SASS in dependencies of json file.Now SASS has been installed in your system successfully.
Step 3: To work with SASS, go to package.json file in your project, i.e. if you are working with VSC, open your project there and then open package.json file.You will get package.json file like:
{
"name": "sass-ex",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
},
"author": "",
"license": "ISC"
}
Remove the “test” script and add your own script of name compile: sass(any other name can be chosen), give the link of your sass file as a target.
package.json should look like this:
{
"name": "sass-ex",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"compile:sass": "node-sass scss/style.scss css/style.css"
},
"author": "",
"license": "ISC"
}
Now go back to command prompt and run command
npm rum compile:sass
Or just add node-sass script like this:Open the package.json file in your text editor of choice, and add the following line inside the “scripts” object:
"scss": "node-sass --watch assets/scss -o assets/css"
package.json file look like this:
{
"name": "sass-ex",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"scss": "node-sass --watch assets/scss -o assets/css"
},
"author": "",
"license": "ISC"
}
Save the file and close it. Now in the root of the project directory, run command given below to start watching for any changes to your .scss files.
npm run scss
Alternative ways to install sass: It is good to know a little bit of extra. So for installing Sass, there are some alternative ways too. You can install Sass via paid and free applications such as Codekit. You can install Sass by downloading the package from the Official Github Site and add it directly to your path.
To install node-sass: Once you install npm, it’s time to install node-sass. You can do so by running this command in your terminal to install the package globally.
npm install -g node-sass
or you can run above command without the -g flag to only install to your current directory as below.
npm install node-sass
andreasschlapbach
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.
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
Design a Tribute Page using HTML & CSS
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Oct, 2020"
},
{
"code": null,
"e": 238,
"s": 28,
"text": "Introduction to SASS: SASS stands for ‘Syntactically awesome style sheets’. It is an extension of CSS, that makes it easy to use variables of CSS, nested rules, inline import, and many other important features"
},
{
"code": null,
"e": 267,
"s": 238,
"text": "SASS has two syntax options:"
},
{
"code": null,
"e": 358,
"s": 267,
"text": "SCSS (Sassy CSS): It uses the .scss file extension and is fully compliant with CSS syntax."
},
{
"code": null,
"e": 431,
"s": 358,
"text": "SASS: It uses .sass file extension and indentation rather than brackets."
},
{
"code": null,
"e": 513,
"s": 431,
"text": "Note: Files can be convert from one syntax to another using sass-convert command."
},
{
"code": null,
"e": 693,
"s": 513,
"text": "Steps to install SASS:Step 1: To install SASS, first make sure that node and npm are already installed in the system. If not, then install them using the instructions given below."
},
{
"code": null,
"e": 768,
"s": 693,
"text": "First, download the latest version of a node in the system and install it."
},
{
"code": null,
"e": 848,
"s": 768,
"text": "Now go to command prompt and address the folder where you want to install SASS."
},
{
"code": null,
"e": 942,
"s": 848,
"text": "After that, you have to create package.json file. It manages the dependencies of our project."
},
{
"code": null,
"e": 1156,
"s": 942,
"text": "Use command written below that will ask for the package name of the user’s choice and the description. Some more formalities are there, just press enter for that and your package.json file will be created.npm init"
},
{
"code": null,
"e": 1165,
"s": 1156,
"text": "npm init"
},
{
"code": null,
"e": 1221,
"s": 1165,
"text": "Step 2: Now to install SASS one simple command is used:"
},
{
"code": null,
"e": 1250,
"s": 1221,
"text": "npm install node-sass --save"
},
{
"code": null,
"e": 1392,
"s": 1250,
"text": "Note: – –save in above command is used to save the SASS in dependencies of json file.Now SASS has been installed in your system successfully."
},
{
"code": null,
"e": 1587,
"s": 1392,
"text": "Step 3: To work with SASS, go to package.json file in your project, i.e. if you are working with VSC, open your project there and then open package.json file.You will get package.json file like:"
},
{
"code": null,
"e": 1812,
"s": 1587,
"text": "{\n \"name\": \"sass-ex\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n },\n \"author\": \"\",\n \"license\": \"ISC\"\n}\n"
},
{
"code": null,
"e": 1959,
"s": 1812,
"text": "Remove the “test” script and add your own script of name compile: sass(any other name can be chosen), give the link of your sass file as a target."
},
{
"code": null,
"e": 1995,
"s": 1959,
"text": "package.json should look like this:"
},
{
"code": null,
"e": 2222,
"s": 1995,
"text": "{\n \"name\": \"sass-ex\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"compile:sass\": \"node-sass scss/style.scss css/style.css\"\n },\n \"author\": \"\",\n \"license\": \"ISC\"\n}"
},
{
"code": null,
"e": 2268,
"s": 2222,
"text": "Now go back to command prompt and run command"
},
{
"code": null,
"e": 2289,
"s": 2268,
"text": "npm rum compile:sass"
},
{
"code": null,
"e": 2442,
"s": 2289,
"text": "Or just add node-sass script like this:Open the package.json file in your text editor of choice, and add the following line inside the “scripts” object:"
},
{
"code": null,
"e": 2496,
"s": 2442,
"text": "\"scss\": \"node-sass --watch assets/scss -o assets/css\""
},
{
"code": null,
"e": 2530,
"s": 2496,
"text": "package.json file look like this:"
},
{
"code": null,
"e": 2817,
"s": 2530,
"text": "{\n \"name\": \"sass-ex\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"scss\": \"node-sass --watch assets/scss -o assets/css\"\n },\n \"author\": \"\",\n \"license\": \"ISC\"\n}\n"
},
{
"code": null,
"e": 2966,
"s": 2817,
"text": "Save the file and close it. Now in the root of the project directory, run command given below to start watching for any changes to your .scss files."
},
{
"code": null,
"e": 2979,
"s": 2966,
"text": "npm run scss"
},
{
"code": null,
"e": 3297,
"s": 2979,
"text": "Alternative ways to install sass: It is good to know a little bit of extra. So for installing Sass, there are some alternative ways too. You can install Sass via paid and free applications such as Codekit. You can install Sass by downloading the package from the Official Github Site and add it directly to your path."
},
{
"code": null,
"e": 3461,
"s": 3297,
"text": "To install node-sass: Once you install npm, it’s time to install node-sass. You can do so by running this command in your terminal to install the package globally."
},
{
"code": null,
"e": 3486,
"s": 3461,
"text": "npm install -g node-sass"
},
{
"code": null,
"e": 3587,
"s": 3486,
"text": "or you can run above command without the -g flag to only install to your current directory as below."
},
{
"code": null,
"e": 3609,
"s": 3587,
"text": "npm install node-sass"
},
{
"code": null,
"e": 3627,
"s": 3609,
"text": "andreasschlapbach"
},
{
"code": null,
"e": 3636,
"s": 3627,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3643,
"s": 3636,
"text": "Picked"
},
{
"code": null,
"e": 3648,
"s": 3643,
"text": "SASS"
},
{
"code": null,
"e": 3652,
"s": 3648,
"text": "CSS"
},
{
"code": null,
"e": 3669,
"s": 3652,
"text": "Web Technologies"
},
{
"code": null,
"e": 3696,
"s": 3669,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3794,
"s": 3696,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3831,
"s": 3794,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 3870,
"s": 3831,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 3934,
"s": 3870,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 3995,
"s": 3934,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 4034,
"s": 3995,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 4067,
"s": 4034,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4128,
"s": 4067,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4171,
"s": 4128,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 4243,
"s": 4171,
"text": "Differences between Functional Components and Class Components in React"
}
] |
HTML | <font> face Attribute | 28 May, 2019
The HTML <font> face Attribute is used to specify the font family of the text inside <font> element.
Syntax:
<font face="font_family">
Attribute Values: It contains single value font_family which is used to specify the font family. Several font family can be used by separating comma.
Note: The <font> face attribute is not supported by HTML5.
Example:
<!DOCTYPE html><html> <head> <title> HTML font face Attribute </title></head> <body> <font size="6" face="verdana"> GeeksforGeeks! </font> <br> <font size="6" face="arial"> GeeksforGeeks! </font> <br> <font size="6"> GeeksforGeeks! </font></body> </html>
Output:
Supported Browsers: The browser supported by HTML <font> face attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 May, 2019"
},
{
"code": null,
"e": 129,
"s": 28,
"text": "The HTML <font> face Attribute is used to specify the font family of the text inside <font> element."
},
{
"code": null,
"e": 137,
"s": 129,
"text": "Syntax:"
},
{
"code": null,
"e": 163,
"s": 137,
"text": "<font face=\"font_family\">"
},
{
"code": null,
"e": 313,
"s": 163,
"text": "Attribute Values: It contains single value font_family which is used to specify the font family. Several font family can be used by separating comma."
},
{
"code": null,
"e": 372,
"s": 313,
"text": "Note: The <font> face attribute is not supported by HTML5."
},
{
"code": null,
"e": 381,
"s": 372,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML font face Attribute </title></head> <body> <font size=\"6\" face=\"verdana\"> GeeksforGeeks! </font> <br> <font size=\"6\" face=\"arial\"> GeeksforGeeks! </font> <br> <font size=\"6\"> GeeksforGeeks! </font></body> </html>",
"e": 725,
"s": 381,
"text": null
},
{
"code": null,
"e": 733,
"s": 725,
"text": "Output:"
},
{
"code": null,
"e": 823,
"s": 733,
"text": "Supported Browsers: The browser supported by HTML <font> face attribute are listed below:"
},
{
"code": null,
"e": 837,
"s": 823,
"text": "Google Chrome"
},
{
"code": null,
"e": 855,
"s": 837,
"text": "Internet Explorer"
},
{
"code": null,
"e": 863,
"s": 855,
"text": "Firefox"
},
{
"code": null,
"e": 870,
"s": 863,
"text": "Safari"
},
{
"code": null,
"e": 876,
"s": 870,
"text": "Opera"
},
{
"code": null,
"e": 892,
"s": 876,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 897,
"s": 892,
"text": "HTML"
},
{
"code": null,
"e": 914,
"s": 897,
"text": "Web Technologies"
},
{
"code": null,
"e": 919,
"s": 914,
"text": "HTML"
},
{
"code": null,
"e": 1017,
"s": 919,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1041,
"s": 1017,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1078,
"s": 1041,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 1117,
"s": 1078,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1145,
"s": 1117,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 1195,
"s": 1145,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1228,
"s": 1195,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1289,
"s": 1228,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1332,
"s": 1289,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1404,
"s": 1332,
"text": "Differences between Functional Components and Class Components in React"
}
] |
numpy.random.uniform() in Python | 18 Aug, 2020
With the help of numpy.random.uniform() method, we can get the random samples from uniform distribution and returns the random samples as numpy array by using this method.
Uniform distribution
Syntax : numpy.random.uniform(low=0.0, high=1.0, size=None)
Return : Return the random samples as numpy array.
Example #1 :
In this example we can see that by using numpy.random.uniform() method, we are able to get the random samples from uniform distribution and return the random samples.
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt # Using uniform() methodgfg = np.random.uniform(-5, 5, 5000) plt.hist(gfg, bins = 50, density = True)plt.show()
Output :
Example #2 :
Python3
# import numpyimport numpy as npimport matplotlib.pyplot as plt # Using uniform() methodgfg = np.random.uniform(2.1, 5.5, 10000) plt.hist(gfg, bins = 100, density = True)plt.show()
Output :
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 225,
"s": 53,
"text": "With the help of numpy.random.uniform() method, we can get the random samples from uniform distribution and returns the random samples as numpy array by using this method."
},
{
"code": null,
"e": 246,
"s": 225,
"text": "Uniform distribution"
},
{
"code": null,
"e": 306,
"s": 246,
"text": "Syntax : numpy.random.uniform(low=0.0, high=1.0, size=None)"
},
{
"code": null,
"e": 357,
"s": 306,
"text": "Return : Return the random samples as numpy array."
},
{
"code": null,
"e": 370,
"s": 357,
"text": "Example #1 :"
},
{
"code": null,
"e": 537,
"s": 370,
"text": "In this example we can see that by using numpy.random.uniform() method, we are able to get the random samples from uniform distribution and return the random samples."
},
{
"code": null,
"e": 545,
"s": 537,
"text": "Python3"
},
{
"code": "# import numpyimport numpy as npimport matplotlib.pyplot as plt # Using uniform() methodgfg = np.random.uniform(-5, 5, 5000) plt.hist(gfg, bins = 50, density = True)plt.show()",
"e": 723,
"s": 545,
"text": null
},
{
"code": null,
"e": 732,
"s": 723,
"text": "Output :"
},
{
"code": null,
"e": 745,
"s": 732,
"text": "Example #2 :"
},
{
"code": null,
"e": 753,
"s": 745,
"text": "Python3"
},
{
"code": "# import numpyimport numpy as npimport matplotlib.pyplot as plt # Using uniform() methodgfg = np.random.uniform(2.1, 5.5, 10000) plt.hist(gfg, bins = 100, density = True)plt.show()",
"e": 936,
"s": 753,
"text": null
},
{
"code": null,
"e": 945,
"s": 936,
"text": "Output :"
},
{
"code": null,
"e": 965,
"s": 945,
"text": "Python numpy-Random"
},
{
"code": null,
"e": 978,
"s": 965,
"text": "Python-numpy"
},
{
"code": null,
"e": 985,
"s": 978,
"text": "Python"
},
{
"code": null,
"e": 1083,
"s": 985,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1115,
"s": 1083,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1142,
"s": 1115,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1163,
"s": 1142,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1186,
"s": 1163,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1242,
"s": 1186,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1273,
"s": 1242,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1315,
"s": 1273,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1357,
"s": 1315,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1396,
"s": 1357,
"text": "Python | datetime.timedelta() function"
}
] |
Logger addHandler() method in Java with Examples | 24 Jun, 2021
addHandler() method of a Logger class used to add a log Handler to receive logging messages. A Handler is a component of JVM that takes care of actual logging to the defined output writers like a file, console out etc. one or more Handlers can be added to a Logger. When different types of messages are logged using the Logger, the logs are forwarded to the Handler’s output. By default, Loggers send their output to their parent logger.So we can say Parent Logger is a type of handler for child logger.Syntax:
public void addHandler(Handler handler)
throws SecurityException
Parameters: This method accepts one parameter handler which represents a logging Handler.Return value: This method returns nothing.Exception: This method throws SecurityException if a security manager exists, this logger is not anonymous, and the caller does not have LoggingPermission(“control”).Below programs illustrate the isLoggable() method: Program 1:
Java
// Java program to demonstrate// Logger.addHandler() method import java.util.logging.*;import java.io.IOException; public class GFG { private static Logger logger = Logger.getLogger( GFG.class.getName()); public static void main(String args[]) throws SecurityException, IOException { // Create a file handler object FileHandler handler = new FileHandler("logs.txt"); // Add file handler as // handler of logs logger.addHandler(handler); // Log message logger.info("This is Info Message "); logger.log(Level.WARNING, "Warning Message"); }}
Output: The output printed on logs.txt file is shown below-
addHandler
Program 2:
Java
// Java program to demonstrate// Logger.addHandler() method import java.util.logging.*;import java.io.IOException; public class GFG { private static Logger logger = Logger.getLogger( GFG.class.getName()); public static void main(String args[]) throws SecurityException, IOException { // Create a ConsoleHandler object ConsoleHandler handler = new ConsoleHandler(); // Add console handler as // handler of logs logger.addHandler(handler); // Log message logger.info("This is Info Message "); logger.log(Level.WARNING, "Warning Message"); }}
The output printed on console output is shown below-
addHandler(java.util.logging.Handler)
References: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#addHandler(java.util.logging.Handler)
sooda367
Java - util package
Java-Functions
Java-Logger
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 541,
"s": 28,
"text": "addHandler() method of a Logger class used to add a log Handler to receive logging messages. A Handler is a component of JVM that takes care of actual logging to the defined output writers like a file, console out etc. one or more Handlers can be added to a Logger. When different types of messages are logged using the Logger, the logs are forwarded to the Handler’s output. By default, Loggers send their output to their parent logger.So we can say Parent Logger is a type of handler for child logger.Syntax: "
},
{
"code": null,
"e": 622,
"s": 541,
"text": "public void addHandler(Handler handler)\n throws SecurityException"
},
{
"code": null,
"e": 983,
"s": 622,
"text": "Parameters: This method accepts one parameter handler which represents a logging Handler.Return value: This method returns nothing.Exception: This method throws SecurityException if a security manager exists, this logger is not anonymous, and the caller does not have LoggingPermission(“control”).Below programs illustrate the isLoggable() method: Program 1: "
},
{
"code": null,
"e": 988,
"s": 983,
"text": "Java"
},
{
"code": "// Java program to demonstrate// Logger.addHandler() method import java.util.logging.*;import java.io.IOException; public class GFG { private static Logger logger = Logger.getLogger( GFG.class.getName()); public static void main(String args[]) throws SecurityException, IOException { // Create a file handler object FileHandler handler = new FileHandler(\"logs.txt\"); // Add file handler as // handler of logs logger.addHandler(handler); // Log message logger.info(\"This is Info Message \"); logger.log(Level.WARNING, \"Warning Message\"); }}",
"e": 1643,
"s": 988,
"text": null
},
{
"code": null,
"e": 1705,
"s": 1643,
"text": "Output: The output printed on logs.txt file is shown below- "
},
{
"code": null,
"e": 1716,
"s": 1705,
"text": "addHandler"
},
{
"code": null,
"e": 1729,
"s": 1716,
"text": "Program 2: "
},
{
"code": null,
"e": 1734,
"s": 1729,
"text": "Java"
},
{
"code": "// Java program to demonstrate// Logger.addHandler() method import java.util.logging.*;import java.io.IOException; public class GFG { private static Logger logger = Logger.getLogger( GFG.class.getName()); public static void main(String args[]) throws SecurityException, IOException { // Create a ConsoleHandler object ConsoleHandler handler = new ConsoleHandler(); // Add console handler as // handler of logs logger.addHandler(handler); // Log message logger.info(\"This is Info Message \"); logger.log(Level.WARNING, \"Warning Message\"); }}",
"e": 2383,
"s": 1734,
"text": null
},
{
"code": null,
"e": 2438,
"s": 2383,
"text": "The output printed on console output is shown below- "
},
{
"code": null,
"e": 2476,
"s": 2438,
"text": "addHandler(java.util.logging.Handler)"
},
{
"code": null,
"e": 2600,
"s": 2476,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#addHandler(java.util.logging.Handler) "
},
{
"code": null,
"e": 2609,
"s": 2600,
"text": "sooda367"
},
{
"code": null,
"e": 2629,
"s": 2609,
"text": "Java - util package"
},
{
"code": null,
"e": 2644,
"s": 2629,
"text": "Java-Functions"
},
{
"code": null,
"e": 2656,
"s": 2644,
"text": "Java-Logger"
},
{
"code": null,
"e": 2661,
"s": 2656,
"text": "Java"
},
{
"code": null,
"e": 2666,
"s": 2661,
"text": "Java"
}
] |
nslookup command in Linux with Examples | 09 Nov, 2021
Nslookup (stands for “Name Server Lookup”) is a useful command for getting information from the DNS server. It is a network administration tool for querying the Domain Name System (DNS) to obtain domain name or IP address mapping or any other specific DNS record. It is also used to troubleshoot DNS-related problems.
Syntax:
nslookup [option]
Options of nslookup command:
nslookup google.com : nslookup followed by the domain name will display the “A Record” (IP Address) of the domain. Use this command to find the address record for a domain. It queries to domain name servers and gets the details.
nslookup 192.168.0.10: Reverse DNS lookup You can also do the reverse DNS look-up by providing the IP Address as an argument to nslookup.
You can also do the reverse DNS look-up by providing the IP Address as an argument to nslookup.
nslookup -type=any google.com : Lookup for any record We can also view all the available DNS records using the -type=any option.
nslookup -type=soa redhat.com : Lookup for an soa record SOA record (start of authority), provides the authoritative information about the domain, the e-mail address of the domain admin, the domain serial number, etc...
nslookup -type=ns google.com : Lookup for an ns record NS (Name Server) record maps a domain name to a list of DNS servers authoritative for that domain. It will output the name serves which are associated with the given domain.
nslookup -type=a google.com : Lookup for an a record We can also view all the available DNS records for a particular record using the -type=a option.
nslookup -type=mx google.com : Lookup for an mx record MX (Mail Exchange) record maps a domain name to a list of mail exchange servers for that domain. The MX record tells that all the mails sent to “google.com” should be routed to the Mail server in that domain.
nslookup -type=txt google.com : Lookup for an txt record TXT records are useful for multiple types of records like DKIM, SPF, etc. You can find all TXT records configured for any domain using the below command.
marcosarcticseal
linux-command
Linux-networking-commands
Picked
Computer Networks
Linux-Unix
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Types of Network Topology
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Socket Programming in Python
AWK command in Unix/Linux with examples
cut command in Linux with examples
cp command in Linux with examples
ZIP command in Linux with examples
tar command in Linux with examples | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Nov, 2021"
},
{
"code": null,
"e": 373,
"s": 54,
"text": "Nslookup (stands for “Name Server Lookup”) is a useful command for getting information from the DNS server. It is a network administration tool for querying the Domain Name System (DNS) to obtain domain name or IP address mapping or any other specific DNS record. It is also used to troubleshoot DNS-related problems. "
},
{
"code": null,
"e": 382,
"s": 373,
"text": "Syntax: "
},
{
"code": null,
"e": 400,
"s": 382,
"text": "nslookup [option]"
},
{
"code": null,
"e": 431,
"s": 400,
"text": "Options of nslookup command: "
},
{
"code": null,
"e": 661,
"s": 431,
"text": "nslookup google.com : nslookup followed by the domain name will display the “A Record” (IP Address) of the domain. Use this command to find the address record for a domain. It queries to domain name servers and gets the details. "
},
{
"code": null,
"e": 800,
"s": 661,
"text": "nslookup 192.168.0.10: Reverse DNS lookup You can also do the reverse DNS look-up by providing the IP Address as an argument to nslookup. "
},
{
"code": null,
"e": 897,
"s": 800,
"text": "You can also do the reverse DNS look-up by providing the IP Address as an argument to nslookup. "
},
{
"code": null,
"e": 1027,
"s": 897,
"text": "nslookup -type=any google.com : Lookup for any record We can also view all the available DNS records using the -type=any option. "
},
{
"code": null,
"e": 1248,
"s": 1027,
"text": "nslookup -type=soa redhat.com : Lookup for an soa record SOA record (start of authority), provides the authoritative information about the domain, the e-mail address of the domain admin, the domain serial number, etc... "
},
{
"code": null,
"e": 1478,
"s": 1248,
"text": "nslookup -type=ns google.com : Lookup for an ns record NS (Name Server) record maps a domain name to a list of DNS servers authoritative for that domain. It will output the name serves which are associated with the given domain. "
},
{
"code": null,
"e": 1629,
"s": 1478,
"text": "nslookup -type=a google.com : Lookup for an a record We can also view all the available DNS records for a particular record using the -type=a option. "
},
{
"code": null,
"e": 1894,
"s": 1629,
"text": "nslookup -type=mx google.com : Lookup for an mx record MX (Mail Exchange) record maps a domain name to a list of mail exchange servers for that domain. The MX record tells that all the mails sent to “google.com” should be routed to the Mail server in that domain. "
},
{
"code": null,
"e": 2106,
"s": 1894,
"text": "nslookup -type=txt google.com : Lookup for an txt record TXT records are useful for multiple types of records like DKIM, SPF, etc. You can find all TXT records configured for any domain using the below command. "
},
{
"code": null,
"e": 2125,
"s": 2108,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 2139,
"s": 2125,
"text": "linux-command"
},
{
"code": null,
"e": 2165,
"s": 2139,
"text": "Linux-networking-commands"
},
{
"code": null,
"e": 2172,
"s": 2165,
"text": "Picked"
},
{
"code": null,
"e": 2190,
"s": 2172,
"text": "Computer Networks"
},
{
"code": null,
"e": 2201,
"s": 2190,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2219,
"s": 2201,
"text": "Computer Networks"
},
{
"code": null,
"e": 2317,
"s": 2219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2349,
"s": 2317,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 2375,
"s": 2349,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 2405,
"s": 2375,
"text": "RSA Algorithm in Cryptography"
},
{
"code": null,
"e": 2443,
"s": 2405,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 2472,
"s": 2443,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 2512,
"s": 2472,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 2547,
"s": 2512,
"text": "cut command in Linux with examples"
},
{
"code": null,
"e": 2581,
"s": 2547,
"text": "cp command in Linux with examples"
},
{
"code": null,
"e": 2616,
"s": 2581,
"text": "ZIP command in Linux with examples"
}
] |
Boundary Value Analysis – Triangle Problem | 11 Jun, 2021
Boundary Value Analysis (BVA) is a black box software testing technique where test cases are designed using boundary values. BVA is based on the single fault assumption, also known as critical fault assumption which states that failures are rarely the product of two or more simultaneous faults. Hence while designing the test cases for BVA we keep all but one variable to the nominal value and allowing the remaining variable to take the extreme value.
Test Case Design for BVA: While designing the test cases for BVA first we determine the number of input variables in the problem. For each input variable, we then determine the range of values it can take. Then we determine the extreme values and nominal value for each input variable.
Consider an input variable t taking values in the range [l, r].Extreme values for t are –
t = l
t = l+1
t = r-1
t = r
The nominal value for the variable can be any value in the range (l, r). In most of the BVA implementations, it is taken as the middle value of the range (r+l)/2. The figure on the right shows the nominal and extreme values for boundary value of analysis of a two variable problem.
Under the single fault assumption, the total number of test cases in BVA for a problem with n inputs is 4n+1. The 4n cases correspond to the test cases with the four extreme values of each variable keeping the other n-1 variable at nominal value. The one additional case is where all variables are held at a nominal value.
One of the common problem for Test Case Design using BVA is the Triangle Problem that is discussed below –
Triangle Problem accepts three integers – a, b, c as three sides of the triangle .We also define a range for the sides of the triangle as [l, r] where l>0. It returns the type of triangle (Scalene, Isosceles, Equilateral, Not a Triangle) formed by a, b, c.
For a, b, c to form a triangle the following conditions should be satisfied –
a < b+c
b < a+c
c < a+b
If any of these conditions is violated output is Not a Triangle.
For Equilateral Triangle all the sides are equal.
For Isosceles Triangle exactly one pair of sides is equal.
For Scalene Triangle all the sides are different.
The table shows the Test Cases Design for the Triangle Problem.The range value [l, r] is taken as [1, 100] and nominal value is taken as 50.
The total test cases is,
4n+1 = 4*3+1 = 13
akshaysingh98088
Software Testing
Technical Scripter 2019
Software Engineering
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 483,
"s": 28,
"text": "Boundary Value Analysis (BVA) is a black box software testing technique where test cases are designed using boundary values. BVA is based on the single fault assumption, also known as critical fault assumption which states that failures are rarely the product of two or more simultaneous faults. Hence while designing the test cases for BVA we keep all but one variable to the nominal value and allowing the remaining variable to take the extreme value. "
},
{
"code": null,
"e": 770,
"s": 483,
"text": "Test Case Design for BVA: While designing the test cases for BVA first we determine the number of input variables in the problem. For each input variable, we then determine the range of values it can take. Then we determine the extreme values and nominal value for each input variable. "
},
{
"code": null,
"e": 862,
"s": 770,
"text": "Consider an input variable t taking values in the range [l, r].Extreme values for t are – "
},
{
"code": null,
"e": 891,
"s": 862,
"text": "t = l\nt = l+1\nt = r-1\nt = r "
},
{
"code": null,
"e": 1174,
"s": 891,
"text": "The nominal value for the variable can be any value in the range (l, r). In most of the BVA implementations, it is taken as the middle value of the range (r+l)/2. The figure on the right shows the nominal and extreme values for boundary value of analysis of a two variable problem. "
},
{
"code": null,
"e": 1498,
"s": 1174,
"text": "Under the single fault assumption, the total number of test cases in BVA for a problem with n inputs is 4n+1. The 4n cases correspond to the test cases with the four extreme values of each variable keeping the other n-1 variable at nominal value. The one additional case is where all variables are held at a nominal value. "
},
{
"code": null,
"e": 1606,
"s": 1498,
"text": "One of the common problem for Test Case Design using BVA is the Triangle Problem that is discussed below – "
},
{
"code": null,
"e": 1864,
"s": 1606,
"text": "Triangle Problem accepts three integers – a, b, c as three sides of the triangle .We also define a range for the sides of the triangle as [l, r] where l>0. It returns the type of triangle (Scalene, Isosceles, Equilateral, Not a Triangle) formed by a, b, c. "
},
{
"code": null,
"e": 1943,
"s": 1864,
"text": "For a, b, c to form a triangle the following conditions should be satisfied – "
},
{
"code": null,
"e": 1968,
"s": 1943,
"text": "a < b+c\nb < a+c\nc < a+b "
},
{
"code": null,
"e": 2035,
"s": 1968,
"text": "If any of these conditions is violated output is Not a Triangle. "
},
{
"code": null,
"e": 2085,
"s": 2035,
"text": "For Equilateral Triangle all the sides are equal."
},
{
"code": null,
"e": 2144,
"s": 2085,
"text": "For Isosceles Triangle exactly one pair of sides is equal."
},
{
"code": null,
"e": 2194,
"s": 2144,
"text": "For Scalene Triangle all the sides are different."
},
{
"code": null,
"e": 2336,
"s": 2194,
"text": "The table shows the Test Cases Design for the Triangle Problem.The range value [l, r] is taken as [1, 100] and nominal value is taken as 50. "
},
{
"code": null,
"e": 2363,
"s": 2336,
"text": "The total test cases is, "
},
{
"code": null,
"e": 2382,
"s": 2363,
"text": "4n+1 = 4*3+1 = 13 "
},
{
"code": null,
"e": 2401,
"s": 2384,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 2418,
"s": 2401,
"text": "Software Testing"
},
{
"code": null,
"e": 2442,
"s": 2418,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 2463,
"s": 2442,
"text": "Software Engineering"
},
{
"code": null,
"e": 2482,
"s": 2463,
"text": "Technical Scripter"
}
] |
Software Engineering | Software Quality | 30 Sep, 2019
Traditionally, a high-quality product is outlined in terms of its fitness of purpose. That is, a high-quality product will specifically what the users need it to try to. For code merchandise, the fitness of purpose is typically taken in terms of satisfaction of the wants arranged down within the SRS document. though “fitness of purpose” could be a satisfactory definition of quality for several merchandises like an automobile, a table fan, a grinding machine, etc. – for code merchandise, “fitness of purpose” isn’t a completely satisfactory definition of quality. To convey associate degree example, think about a software that’s functionally correct.
It performs all functions as laid out in the SRS document. But, it has an associate degree virtually unusable program. despite the fact that it should be functionally correct, we have a tendency to cannot think about it to be a high-quality product. Another example is also that of a product that will everything that the users need however has associate degree virtually incomprehensible and not maintainable code. Therefore, the normal construct of quality as “fitness of purpose” for code merchandise isn’t totally satisfactory.
The modern read of high-quality associates with software many quality factors like the following:
Portability:A software is claimed to be transportable, if it may be simply created to figure in several package environments, in several machines, with alternative code merchandise, etc.
Usability:A software has smart usability if completely different classes of users (i.e. each knowledgeable and novice users) will simply invoke the functions of the merchandise.
Reusability:A software has smart reusability if completely different modules of the merchandise will simply be reused to develop new merchandise.
Correctness:A software is correct if completely different needs as laid out in the SRS document are properly enforced.
Maintainability:A software is reparable, if errors may be simply corrected as and once they show up, new functions may be simply added to the merchandise, and therefore the functionalities of the merchandise may be simply changed, etc
nidhi_biet
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Sep, 2019"
},
{
"code": null,
"e": 684,
"s": 28,
"text": "Traditionally, a high-quality product is outlined in terms of its fitness of purpose. That is, a high-quality product will specifically what the users need it to try to. For code merchandise, the fitness of purpose is typically taken in terms of satisfaction of the wants arranged down within the SRS document. though “fitness of purpose” could be a satisfactory definition of quality for several merchandises like an automobile, a table fan, a grinding machine, etc. – for code merchandise, “fitness of purpose” isn’t a completely satisfactory definition of quality. To convey associate degree example, think about a software that’s functionally correct."
},
{
"code": null,
"e": 1216,
"s": 684,
"text": "It performs all functions as laid out in the SRS document. But, it has an associate degree virtually unusable program. despite the fact that it should be functionally correct, we have a tendency to cannot think about it to be a high-quality product. Another example is also that of a product that will everything that the users need however has associate degree virtually incomprehensible and not maintainable code. Therefore, the normal construct of quality as “fitness of purpose” for code merchandise isn’t totally satisfactory."
},
{
"code": null,
"e": 1314,
"s": 1216,
"text": "The modern read of high-quality associates with software many quality factors like the following:"
},
{
"code": null,
"e": 1501,
"s": 1314,
"text": "Portability:A software is claimed to be transportable, if it may be simply created to figure in several package environments, in several machines, with alternative code merchandise, etc."
},
{
"code": null,
"e": 1679,
"s": 1501,
"text": "Usability:A software has smart usability if completely different classes of users (i.e. each knowledgeable and novice users) will simply invoke the functions of the merchandise."
},
{
"code": null,
"e": 1825,
"s": 1679,
"text": "Reusability:A software has smart reusability if completely different modules of the merchandise will simply be reused to develop new merchandise."
},
{
"code": null,
"e": 1944,
"s": 1825,
"text": "Correctness:A software is correct if completely different needs as laid out in the SRS document are properly enforced."
},
{
"code": null,
"e": 2179,
"s": 1944,
"text": "Maintainability:A software is reparable, if errors may be simply corrected as and once they show up, new functions may be simply added to the merchandise, and therefore the functionalities of the merchandise may be simply changed, etc"
},
{
"code": null,
"e": 2190,
"s": 2179,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2211,
"s": 2190,
"text": "Software Engineering"
}
] |
Is it possible to manually set the attribute value of a Web Element using Selenium? | Yes it is possible to manually set the attribute value of a web element in Selenium webdriver using the JavaScript Executor. Selenium can run JavaScript commands with the help of the executeScript method.
First, we shall identify the element on which we want to manually set the attribute value with the JavaScript command document.getElementsByClassname. Next to set the attribute we have to use the setAttribute method.
Let us modify the background color of the button CHECK IT NOW to yellow. By default it is green on the page.
The can be done by setting the style attribute of the background-color to yellow.
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript ("document.getElementsByClassName('mui-btn')[0].setAttribute('style', " + "'background-color: yellow')");
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class BackGroundColr{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.tutorialspoint.com/index.htm");
// Javascript executor to modify background color
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript ("document.getElementsByClassName('mui-btn')[0].setAttribute('style', "
+ "'background-color: yellow')");
}
} | [
{
"code": null,
"e": 1267,
"s": 1062,
"text": "Yes it is possible to manually set the attribute value of a web element in Selenium webdriver using the JavaScript Executor. Selenium can run JavaScript commands with the help of the executeScript method."
},
{
"code": null,
"e": 1484,
"s": 1267,
"text": "First, we shall identify the element on which we want to manually set the attribute value with the JavaScript command document.getElementsByClassname. Next to set the attribute we have to use the setAttribute method."
},
{
"code": null,
"e": 1593,
"s": 1484,
"text": "Let us modify the background color of the button CHECK IT NOW to yellow. By default it is green on the page."
},
{
"code": null,
"e": 1675,
"s": 1593,
"text": "The can be done by setting the style attribute of the background-color to yellow."
},
{
"code": null,
"e": 1849,
"s": 1675,
"text": "JavascriptExecutor j = (JavascriptExecutor) driver;\nj.executeScript (\"document.getElementsByClassName('mui-btn')[0].setAttribute('style', \" + \"'background-color: yellow')\");"
},
{
"code": null,
"e": 2646,
"s": 1849,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class BackGroundColr{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // Javascript executor to modify background color\n JavascriptExecutor j = (JavascriptExecutor) driver;\n j.executeScript (\"document.getElementsByClassName('mui-btn')[0].setAttribute('style', \"\n + \"'background-color: yellow')\");\n }\n}"
}
] |
Reading a text file into an Array in Node.js | We can read a text file and return its content as an Array using node.js. We can use this array content to either process its lines or just for the sake of reading. We can use the 'fs' module to deal with the reading of file. The fs.readFile() and fs.readFileSync() methods are used for the reading files. We can also read large text files using this method.
Create a file with name – fileToArray.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −
node fileToArray.js
fileToArray.js
// Importing the fs module
let fs = require("fs")
// Intitializing the readFileLines with the file
const readFileLines = filename =>
fs.readFileSync(filename)
.toString('UTF8')
.split('\n');
// Calling the readFiles function with file name
let arr = readFileLines('tutorialsPoint.txt');
// Printing the response array
console.log(arr);
C:\home\node>> node fileToArray.js
[ 'Welcome to TutorialsPoint !',
'SIMPLY LEARNING', '' ]
Let's take a look at one more example.
// Importing the fs module
var fs = require("fs")
// Intitializing the readFileLines with filename
fs.readFile('tutorialsPoint.txt', function(err, data) {
if(err) throw err;
var array = data.toString().split("\n");
for(i in array) {
// Printing the response array
console.log(array[i]);
}
});
C:\home\node>> node fileToArray.js
Welcome to TutorialsPoint !
SIMPLY LEARNING | [
{
"code": null,
"e": 1421,
"s": 1062,
"text": "We can read a text file and return its content as an Array using node.js. We can use this array content to either process its lines or just for the sake of reading. We can use the 'fs' module to deal with the reading of file. The fs.readFile() and fs.readFileSync() methods are used for the reading files. We can also read large text files using this method."
},
{
"code": null,
"e": 1591,
"s": 1421,
"text": "Create a file with name – fileToArray.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −"
},
{
"code": null,
"e": 1611,
"s": 1591,
"text": "node fileToArray.js"
},
{
"code": null,
"e": 1626,
"s": 1611,
"text": "fileToArray.js"
},
{
"code": null,
"e": 1974,
"s": 1626,
"text": "// Importing the fs module\nlet fs = require(\"fs\")\n\n// Intitializing the readFileLines with the file\nconst readFileLines = filename =>\n fs.readFileSync(filename)\n .toString('UTF8')\n .split('\\n');\n\n// Calling the readFiles function with file name\nlet arr = readFileLines('tutorialsPoint.txt');\n\n// Printing the response array\nconsole.log(arr);"
},
{
"code": null,
"e": 2069,
"s": 1974,
"text": "C:\\home\\node>> node fileToArray.js\n[ 'Welcome to TutorialsPoint !',\n 'SIMPLY LEARNING', '' ]"
},
{
"code": null,
"e": 2108,
"s": 2069,
"text": "Let's take a look at one more example."
},
{
"code": null,
"e": 2429,
"s": 2108,
"text": "// Importing the fs module\nvar fs = require(\"fs\")\n\n// Intitializing the readFileLines with filename\nfs.readFile('tutorialsPoint.txt', function(err, data) {\n if(err) throw err;\n var array = data.toString().split(\"\\n\");\n for(i in array) {\n // Printing the response array\n console.log(array[i]);\n }\n});"
},
{
"code": null,
"e": 2508,
"s": 2429,
"text": "C:\\home\\node>> node fileToArray.js\nWelcome to TutorialsPoint !\nSIMPLY LEARNING"
}
] |
The easiest way to download YouTube videos using Python | by Eryk Lewinson | Towards Data Science | In one of my first articles on Medium, I showed how to train a Convolutional Neural Network to classify images coming from old GameBoy games — Mario and Wario. After over a year, I wanted to revisit one aspect of the process — downloading videos (and potentially audio) from YouTube videos and extracting frames as images. We can use such images for various machine learning projects.
In my previous article, I used a library called pytube to download the videos. However, after some changes introduced by YouTube, it is not really usable anymore — any attempt to download videos results in KeyError: ‘url_encoded_fmt_stream_map’. Also, the library is not actively maintained anymore.
That is why in this article I suggest using pytube3, which is a fork of the original pytube library and has the error fixed (it only works with Python 3). All the functionalities of the original library are preserved and we actually still use import pytube to import the library (even though we install it using pip install pytube3).
Below I present the list of all the imports required for this article:
from pytube import YouTube# miscimport osimport shutilimport mathimport datetime# plotsimport matplotlib.pyplot as plt%matplotlib inline# image operationimport cv2
In this part, I present how to download a YouTube video using Python. I will use a classic video game from GameBoy — Mega Man: Dr. Wily’s Revenge. The first step is to create an instance of the YouTube class using the link to the video we want to download.
video = YouTube('https://www.youtube.com/watch?v=NqC_1GuY3dw')
Using this object, we can download the video/audio, and inspect some of the properties of the video itself. Some of the interesting methods we can use are:
length — length of the video in seconds
rating — the rating of the video
views — the number of views
The next step is to inspect the available streams using the streams method. We can chain it with the all method to see all the available streams.
video.streams.all()
Running that line of code returns the following list of media formats:
For a more in-depth description of the options regarding the media formats and working with streams, I refer to pytube’s documentation available here.
Let’s narrow down all the available streams to mp4 files using the filter method:
video.streams.filter(file_extension = "mp4").all()
Running the code results in the following selection:
In this case, we will use the first available option, the one in 360p (resolution). To download the video, we first indicate which one we want to download by using the itag and then download the file using the download method. The full code for downloading the video is as follows:
video.streams.get_by_itag(18).download()
In the download method, we can also specify the destination path for the video. The default value is the current directory.
I created a special class called FrameExtractor to — as the name pretty much reveals it — extract individual frames from the video and save them as images. The class is defined as follows:
While instantiating the object of the FrameExtractor class, we need to provide the path to the video we want to work with. In the __init__ method, we also extract some characteristics of the video such as the total number of frames and the frames per second (FPS). In general, the class provides functionality to extract every x-th frame from the video, as the difference between any two neighboring frames will be minimal. We provide a few convenience methods as well. All the methods are described below:
get_video_duration — prints the duration of the video
get_n_images — prints the number of images that will be extracted given we extract every x-th frame (indicated by every_x_frame)
extract_frames — this is the main method of the class, which is used to extract the images. The bare minimum is providing the value for every_x_frame and the name of the image (the numbers indicating the sequence will be added automatically at the end of the name). By default, the images will be saved in the current directory. We can also provide a path to the desired directory (dest_path), and if it does not exist, it will be created for us. We can also specify the format of the image file, the default is JPG.
Now it is time to actually use the class. We start by instantiating the object of the FrameExtractor class:
fe = FrameExtractor('Game Boy Longplay [009] Mega Man Dr Wilys Revenge.mp4')
Next, we investigate the length of the video:
fe.get_video_duration()# Duration: 0:39:48.333333
As an example, let’s assume we want to extract every 1000th frame. To calculate the number of images extracted using this setting, we run:
fe.get_n_images(every_x_frame=1000)# Extracting every 1000 (nd/rd/th) frame would result in 71 images.
As the last step, we extract the images:
fe.extract_frames(every_x_frame=1000, img_name='megaman', dest_path='megaman_images')# Created the following directory: megaman_images
The indicated directory did not exist prior to using the extract_frames method, so it was automatically created and we saw a printed statement confirming this.
Finally, we define a short function for viewing the downloaded images:
def show_image(path): image = cv2.imread(path) plt.imshow(image) plt.show()show_image('megaman_images/megaman_61.jpg')
Running the code results in displaying the following image:
In this article, I described how to download videos from YouTube using the pytube3 library and coded a custom class used for extracting frames as images from the downloaded videos. A potential modification to the class is to account for skipping the first n seconds of the video, as the beginning often contains title screens, company logos, etc. The same could be done about the end of the video. However, for the time being, we can also account for that by manually deleting the images that are of no use to us.
You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments.
Liked the article? Become a Medium member to continue learning by reading without limits. If you use this link to become a member, you will support me at no extra cost to you. Thanks in advance and see you around!
I recently published a book on using Python for solving practical tasks in the financial domain. If you are interested, I posted an article introducing the contents of the book. You can get the book on Amazon or Packt’s website. | [
{
"code": null,
"e": 432,
"s": 47,
"text": "In one of my first articles on Medium, I showed how to train a Convolutional Neural Network to classify images coming from old GameBoy games — Mario and Wario. After over a year, I wanted to revisit one aspect of the process — downloading videos (and potentially audio) from YouTube videos and extracting frames as images. We can use such images for various machine learning projects."
},
{
"code": null,
"e": 732,
"s": 432,
"text": "In my previous article, I used a library called pytube to download the videos. However, after some changes introduced by YouTube, it is not really usable anymore — any attempt to download videos results in KeyError: ‘url_encoded_fmt_stream_map’. Also, the library is not actively maintained anymore."
},
{
"code": null,
"e": 1066,
"s": 732,
"text": "That is why in this article I suggest using pytube3, which is a fork of the original pytube library and has the error fixed (it only works with Python 3). All the functionalities of the original library are preserved and we actually still use import pytube to import the library (even though we install it using pip install pytube3)."
},
{
"code": null,
"e": 1137,
"s": 1066,
"text": "Below I present the list of all the imports required for this article:"
},
{
"code": null,
"e": 1301,
"s": 1137,
"text": "from pytube import YouTube# miscimport osimport shutilimport mathimport datetime# plotsimport matplotlib.pyplot as plt%matplotlib inline# image operationimport cv2"
},
{
"code": null,
"e": 1558,
"s": 1301,
"text": "In this part, I present how to download a YouTube video using Python. I will use a classic video game from GameBoy — Mega Man: Dr. Wily’s Revenge. The first step is to create an instance of the YouTube class using the link to the video we want to download."
},
{
"code": null,
"e": 1621,
"s": 1558,
"text": "video = YouTube('https://www.youtube.com/watch?v=NqC_1GuY3dw')"
},
{
"code": null,
"e": 1777,
"s": 1621,
"text": "Using this object, we can download the video/audio, and inspect some of the properties of the video itself. Some of the interesting methods we can use are:"
},
{
"code": null,
"e": 1817,
"s": 1777,
"text": "length — length of the video in seconds"
},
{
"code": null,
"e": 1850,
"s": 1817,
"text": "rating — the rating of the video"
},
{
"code": null,
"e": 1878,
"s": 1850,
"text": "views — the number of views"
},
{
"code": null,
"e": 2024,
"s": 1878,
"text": "The next step is to inspect the available streams using the streams method. We can chain it with the all method to see all the available streams."
},
{
"code": null,
"e": 2044,
"s": 2024,
"text": "video.streams.all()"
},
{
"code": null,
"e": 2115,
"s": 2044,
"text": "Running that line of code returns the following list of media formats:"
},
{
"code": null,
"e": 2266,
"s": 2115,
"text": "For a more in-depth description of the options regarding the media formats and working with streams, I refer to pytube’s documentation available here."
},
{
"code": null,
"e": 2348,
"s": 2266,
"text": "Let’s narrow down all the available streams to mp4 files using the filter method:"
},
{
"code": null,
"e": 2399,
"s": 2348,
"text": "video.streams.filter(file_extension = \"mp4\").all()"
},
{
"code": null,
"e": 2452,
"s": 2399,
"text": "Running the code results in the following selection:"
},
{
"code": null,
"e": 2734,
"s": 2452,
"text": "In this case, we will use the first available option, the one in 360p (resolution). To download the video, we first indicate which one we want to download by using the itag and then download the file using the download method. The full code for downloading the video is as follows:"
},
{
"code": null,
"e": 2775,
"s": 2734,
"text": "video.streams.get_by_itag(18).download()"
},
{
"code": null,
"e": 2899,
"s": 2775,
"text": "In the download method, we can also specify the destination path for the video. The default value is the current directory."
},
{
"code": null,
"e": 3088,
"s": 2899,
"text": "I created a special class called FrameExtractor to — as the name pretty much reveals it — extract individual frames from the video and save them as images. The class is defined as follows:"
},
{
"code": null,
"e": 3595,
"s": 3088,
"text": "While instantiating the object of the FrameExtractor class, we need to provide the path to the video we want to work with. In the __init__ method, we also extract some characteristics of the video such as the total number of frames and the frames per second (FPS). In general, the class provides functionality to extract every x-th frame from the video, as the difference between any two neighboring frames will be minimal. We provide a few convenience methods as well. All the methods are described below:"
},
{
"code": null,
"e": 3649,
"s": 3595,
"text": "get_video_duration — prints the duration of the video"
},
{
"code": null,
"e": 3778,
"s": 3649,
"text": "get_n_images — prints the number of images that will be extracted given we extract every x-th frame (indicated by every_x_frame)"
},
{
"code": null,
"e": 4295,
"s": 3778,
"text": "extract_frames — this is the main method of the class, which is used to extract the images. The bare minimum is providing the value for every_x_frame and the name of the image (the numbers indicating the sequence will be added automatically at the end of the name). By default, the images will be saved in the current directory. We can also provide a path to the desired directory (dest_path), and if it does not exist, it will be created for us. We can also specify the format of the image file, the default is JPG."
},
{
"code": null,
"e": 4403,
"s": 4295,
"text": "Now it is time to actually use the class. We start by instantiating the object of the FrameExtractor class:"
},
{
"code": null,
"e": 4480,
"s": 4403,
"text": "fe = FrameExtractor('Game Boy Longplay [009] Mega Man Dr Wilys Revenge.mp4')"
},
{
"code": null,
"e": 4526,
"s": 4480,
"text": "Next, we investigate the length of the video:"
},
{
"code": null,
"e": 4576,
"s": 4526,
"text": "fe.get_video_duration()# Duration: 0:39:48.333333"
},
{
"code": null,
"e": 4715,
"s": 4576,
"text": "As an example, let’s assume we want to extract every 1000th frame. To calculate the number of images extracted using this setting, we run:"
},
{
"code": null,
"e": 4818,
"s": 4715,
"text": "fe.get_n_images(every_x_frame=1000)# Extracting every 1000 (nd/rd/th) frame would result in 71 images."
},
{
"code": null,
"e": 4859,
"s": 4818,
"text": "As the last step, we extract the images:"
},
{
"code": null,
"e": 5030,
"s": 4859,
"text": "fe.extract_frames(every_x_frame=1000, img_name='megaman', dest_path='megaman_images')# Created the following directory: megaman_images"
},
{
"code": null,
"e": 5190,
"s": 5030,
"text": "The indicated directory did not exist prior to using the extract_frames method, so it was automatically created and we saw a printed statement confirming this."
},
{
"code": null,
"e": 5261,
"s": 5190,
"text": "Finally, we define a short function for viewing the downloaded images:"
},
{
"code": null,
"e": 5389,
"s": 5261,
"text": "def show_image(path): image = cv2.imread(path) plt.imshow(image) plt.show()show_image('megaman_images/megaman_61.jpg')"
},
{
"code": null,
"e": 5449,
"s": 5389,
"text": "Running the code results in displaying the following image:"
},
{
"code": null,
"e": 5963,
"s": 5449,
"text": "In this article, I described how to download videos from YouTube using the pytube3 library and coded a custom class used for extracting frames as images from the downloaded videos. A potential modification to the class is to account for skipping the first n seconds of the video, as the beginning often contains title screens, company logos, etc. The same could be done about the end of the video. However, for the time being, we can also account for that by manually deleting the images that are of no use to us."
},
{
"code": null,
"e": 6125,
"s": 5963,
"text": "You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments."
},
{
"code": null,
"e": 6339,
"s": 6125,
"text": "Liked the article? Become a Medium member to continue learning by reading without limits. If you use this link to become a member, you will support me at no extra cost to you. Thanks in advance and see you around!"
}
] |
How to Easily Use Gradient Accumulation in Keras Models | by Raz Rotenberg | Towards Data Science | In another article, we covered what is gradient accumulation in deep learning and how it can solve issues when running neural networks with large batch sizes.
In this article, we will first see how you can easily use the generic gradient accumulation tool we implemented and used at Run:AI. Then, we will deep-dive into Keras optimizers and the way we have implemented such a generic tool.
The code is available on GitHub along with examples you can use right out of the box.
Adding gradient accumulation support to your Keras models is extremely simple. First of all, install the Run:AI Python library using the command:
pip install runai
Then, import the gradient accumulation package into your Python code:
import runai.ga
Now, you can choose one of two options. You can either wrap an existing optimizer with the generic gradient accumulation wrapper or create a gradient accumulation version of any of the built-in optimizers. The two options require specifying the number of steps you want to accumulate gradients over (passed as STEPS in the examples below).
Use the next line to wrap an existing optimizer (where optimizer is your optimizer):
optimizer = runai.ga.keras.optimizers.Optimizer( optimizer, steps=STEPS)
Or, use the next line to create a gradient accumulation version of any of the built-in optimizers (“Adam” is used in the next example):
optimizer = runai.ga.keras.optimizers.Adam(steps=STEPS)
And that’s it! you have successfully added gradient accumulation support to your Keras model.
After seeing how easy it is to use, let’s now see what’s going on under the hood. First, we are going to examine the concept of optimizers in Keras and discuss their responsibility and their implementation. Then, we will deep-dive into how we implemented such a generic mechanism.
Optimizers in Keras are responsible for implementing the optimization algorithm — the mathematical formula responsible for minimizing the loss function. They receive all the model parameters — weights and biases — as inputs, compute their gradients and use them to generate updates for the model parameters. The updates for the model parameters are not the gradients themselves and are calculated using the gradients, as well as other parameters.
Every optimization algorithm has parameters. Some optimizers have similar parameters (e.g. “epsilon”, “beta_1”, “beta_2”, etc...), some may have unique ones (e.g. “amsgrad” in Adam), and they all support “learning rate” (and learning rate decay).
While building the model, Keras will call the optimizer and will pass two arguments. The first argument will be all the trainable variables — weights and biases — of the model. The second argument will be the loss value. Note that the trainable variables and the loss are tensors and not the actual values of the tensors.
The optimizer then takes these input tensors and adds the optimization algorithm to the model. It first calculates the gradients of the trainable variables with respect to the loss (by calling tf.gradients()), and then generates the tensors representing the mathematical formula.
Keras will then evaluate these tensors — that were generated by the optimizer — every step. By evaluating those tensors, the gradients will be calculated, and then the variable updates will be calculated and assigned to the model variables — the weights and biases.
Keras optimizers are Python classes, and they all inherit a base class called Optimizer (can be seen here). The base class implements a few methods and declares other (virtual) methods that must be implemented in subclasses. Let’s briefly examine the methods in Optimizer:
__init__(self, **kwargs): Initializes common members and configuration parameters.
get_updates(self, loss, params): A virtual method that is not implemented in the base class, and must be defined in subclasses, implementing the mathematical formula of the optimizer.
get_gradients(self, loss, params): A utility method to ease the gradient calculations of loss with respect to params (a wrapper of tf.gradients() technically).
set_weights(self, weights): Sets the values of the optimizer’s weights.
get_weights(self): Gets the values of the optimizer’s weights.
get_config(self): Gets the common configuration values.
We will be focusing on get_updates(). This method is only declared (virtual) in the base class; it is not implemented in it and must be implemented in all subclasses. Its implementation is the main difference between one optimizer to another.
As we said, Keras will call get_updates() as part of building the model. The method receives two arguments: loss and params, which both are tensors. and returns a list of tensors, which are the “Assign” ops — the tensors that actually assign the variable updates upon evaluation.
Let’s examine a simplified version of the implementation of SGD’s get_updates(). Note that this is a simplified version and not the actual code in Keras:
First, at line 2, the optimizer calculates the gradients of loss with respect to params by calling self.get_gradients().
Then, in lines 4–6, the optimizer iterates through all the trainable variables of the model, with their respective calculated gradients. For every parameter, it calculates (line 5) the new value of the variable (new_p) using the gradient and the learning rate (self.lr is a tensor initialized in __init__()). Then, it creates a tensor that will assign the variable’s new value (K.update(p, new_p)) and adds it to the list of such tensors (self.updates).
Finally, in line 8, the optimizer returns the list of the “Assign” tensors (self.updates), which will be evaluated by Keras in every step.
This method is called exactly once when the model is being built. It may take some time to digest, but be sure to understand that the arguments and the results are tensor objects and not the actual tensor values. Note that line 5 may be misleading and may seem like it calculates actual values, but this is not the case and is just syntactic sugar (TensorFlow’s operator overloading) on tensor objects.
After examining a simplified version, it’s time to figure out what happens in reality.
In addition to their plain algorithm, most of the optimizers support learning rate decay, which means they modify the learning rate throughout the training of the model, instead of having a constant value for it. In order to support modifying the learning rate over time, the concept of time should be defined. As expected, the learning rate is not modified as a function of the actual time that has passed since the beginning of the training phase, but as a function of the step number, and to support this, optimizers count steps (called iterations in their implementations).
Moreover, SGD in Keras supports momentums and the Nesterov momentum algorithm, which complicates things a bit more. Let’s take a look at the actual implementation of SGD’s get_updates() (can be seen on GitHub also):
Let’s go through the additions over the simplified version we examined before.
In line 3, the optimizer creates an “Assign” tensor to increase self.iterations by 1 in every step. self.iterations is the step counter (a tensor object) and is created in __init__() with an initial value of 0.
In lines 5–7 we can see the learning rate decay formula as a function of the step counter (self.iterations) and the decay value (an argument passed to the optimizer upon creation, and set to self.decay).
In line 11 it creates variables for the momentums. It declares another variable, for every trainable variable, with the same shape, and initializes it to 0 (the call to K.zeros(shape)).
Then, inside the iteration over the trainable variables, it calculates the new value for every momentum (line 14) and creates an “Assign” tensor to update the momentum with the new value (line 15).
Then, in lines 17–20, it calculates the new value for the parameter — depending on whether configured to apply Nesterov momentum or not — and applies the necessary constraints on the parameter (if there are such) in lines 23–24.
The rest of the lines are similar to the simplified version from before.
You can wander around optimizers.py and read the implementations of the different optimizers of Keras.
Now, after deep-diving into what exactly Keras optimizers are and how they are implemented, we are ready to discuss the different implementation alternatives for a gradient accumulation mechanism.
It is possible to rewrite any optimizer to support gradient-accumulation. Gradients should be accumulated over a few steps and only then should the optimizer use them for updating the model parameters. This is not optimal as gradient accumulation is a generic approach and should be optimizer-independent, and there are several flaws to this approach:
Every optimizer has a different formula for implementing a different optimization algorithm and therefore will require a different implementation for the respective gradient accumulation version.This is quite version-specific and code modification will be required every time the original implementation will be changed or a new optimizer will be added.It causes code duplication and is less elegant.
Every optimizer has a different formula for implementing a different optimization algorithm and therefore will require a different implementation for the respective gradient accumulation version.
This is quite version-specific and code modification will be required every time the original implementation will be changed or a new optimizer will be added.
It causes code duplication and is less elegant.
A preferable approach is to design the gradient accumulation model so that it can wrap any Keras optimizer regardless of its optimization algorithm.
By having a generic gradient accumulation mechanism, changes in the original optimizers will not require code updates.
In order to design and implement a generic gradient accumulation mechanism, there are some things that need to be taken into consideration.
Running the optimization algorithm on every mini-batch will not result in the same updates for the model parameters. In other words, we cannot just evaluate the optimization algorithm in every step — on every mini-batch. Otherwise, there was no need for gradient accumulation, and we could have just used a smaller batch size.
If we were to use the global batch, all the gradients would have been calculated using the same values of the model parameters — the weights and biases. When splitting the global batch into several mini-batches, evaluating the optimization algorithm every step will cause the model parameters to be updated after every mini-batch. This means that the gradients of all mini-batches will not be calculated using the same values of the weights and biases.
In addition, optimizers use various parameters as part of their formula, and those parameters are updated as part of the evaluation of the optimization algorithm. Updating those parameters every step — after every mini-batch — will result in changes in the state of the optimization algorithm between different mini-batches.
Our wrapper is a Python class that inherits Keras’s base Optimizer class. We receive the original optimizer as an argument upon creation (in __init__()), as well as the number of steps we want to accumulate gradients over.
We define all the methods exposed by optimizers (i.e. get_gradients(), set_weights(), get_weights(), etc...) and transparently call the original optimizer’s respective methods. The main logic lives — as expected — in get_updates().
Let’s start examining get_updates() (can be seen on GitHub as well), and deep-dive into the algorithm and implementation:
The first line (2) should seem familiar, where we calculate the gradients in the same way as other optimizers do. Note that grads will hold the value of the gradients of every mini-batch.
In line 5, we declare a step counter — called iterations — with an initial value of 0 (pretty similar to other optimizers). We use the step counter to tell if we are either at the first or the last step of the accumulation. To do so, we declare two tensors: first and last (lines 6–7).
first will be set to True every time we passed exactly self.steps steps. Technically, this is when iterations % self.steps will be equal to 0. For example, if we accumulate over five steps, this will be the case at the first step (indexed 0), the sixth step (indexed 5), the eleventh step (indexed 10), etc... In those cases, at the beginning of the step, we want to reset the accumulated gradients to 0 and start accumulating them once again.
last will be set to True every step we want to update the variables. Technically, this is when iterations % self.steps will be equal to self.steps — 1. Continuing the example from before, this will be the case at the fifth step (indexed 4), tenth step (indexed 9), etc...
In line 10, we declare variables to hold the values accumulated gradients between steps. We declare such a variable for every model parameter — for every trainable weight or bias — with the shape and type of the parameter, and initialize them with zeros.
Using those variables, in line 13 we declare tensors — agrads — to hold the values of accumulated gradients in every step. We use first to tell whether we should start accumulating the gradients from now on or use the gradients accumulated in the previous steps. If first is True — meaning we start accumulating from now on — we use the gradients of the current mini-batch alone. If first is False — meaning we should use the gradients accumulated over the past steps — we add the gradients of the current mini-batch to vagrads. This control flow (checking the value of first) is generated into the model using K.switch().
As a generic wrapper, we don’t implement any optimization algorithm. The original optimizer is responsible for that. As we covered, every optimizer implements its mathematical formula in get_updates(). There, the optimizer manages and uses all the needed parameters for the formula (e.g. step counter, learning rate, momentums, etc...). The optimizer stores the values of the parameters in dedicated variables, and every time a parameter needs to be updated, it assigns the new value to its dedicated variable.
The method get_updates() is called once, generating “Assign” tensors that will be evaluated in every step. Some of them are the updates of the model parameters, and the other ones are updates to the optimizer parameters.
As long as we are accumulating gradients, we don’t want any of these updates to happen. We don’t want the model parameters to be updated in order for all the mini-batches to start from the exact same point, in terms of having the same values for the weights and biases. We don’t want the optimizer parameters to be updated in order for the optimizer to advance in the pace as if it were to run on the global batch. For example, we want the step counter to increase only after all mini-batches passed, so the learning rate will be modified at the correct rate.
We want all the updates to take place only after all the mini-batches have passed. Technically, this means we want the updates to occur at the last step of the accumulation — when last is True.
So, if we could have just called the original optimizer’s get_updates(), while (1) making it use the accumulated gradients, and (2) causing all the variable updates to take place only at the last steps of the accumulation, we would have achieved what we wanted.
Fortunately, replacing (hooking) methods is really easy in Python, and by replacing a few methods with a different implementation we can easily achieve exactly that.
Optimizers call their get_gradients() from get_updates() to calculate the gradients of the parameters with respect to the loss. Therefore, we replace the optimizer’s get_gradients() with a function that does nothing but returning the accumulated gradients (agrads — the tensors we generated in line 13). This will cause the original optimizer to refer to the accumulated gradients in its algorithm and will solve (1). Let’s take a look at a simplified implementation for such a replacement method:
Regarding (2), variables in Keras can be assigned using 3 methods: K.update(), K.update_add(), and K.update_sub(). Optimizers use these methods for all updates — for the model parameters as well as for the optimizer parameters. We replace all three of them (can be seen on GitHub). We want all tensors created using those methods to assign values only in the last mini-batch and to do nothing otherwise. Therefore, in our methods — that replace the three — we wrap every value being assigned with a conditional switch and pass this switch to the respective method. If this is the last mini-batch (last is True), we assign the actual value to the variable, otherwise, we assign a value that does not affect the variable. For K.update_add() and K.update_sub() we assign zero, causing the variable to not actually increase or decrease. For K.update() we assign the current value of the variable, causing the variable to keep its current value. Let’s take a look at a simplified implementation for such replacement methods:
Back to our get_updates(), in lines 15–18 we actually replace all those methods. We use helper classes — subclasses of runai.utils.Hook — to do so.
In line 19 we call the original optimizer’s get_updates(). With all those methods replaced, we (1) make it refer to the accumulated gradients, and (2) cause all updates (“Assign” ops) to take place only when last is True.
We have two more things we have to do at the end of every step.
First, we have to update our variables to hold the current value of the accumulated gradients. This is done in line 33.
Second, we have to advance our step counter — self.iterations (line 36). To make sure this happens at the end of the step we generate the tensors under control dependencies of all other “Assign” ops. This causes the step counter update to take place only after all other updates have already taken place.
This article along with previous ones was meant to describe a few things in details:
The problems in batch sizing one might encounter while training neural networks and being limited by GPU memory.Why and how gradient accumulation might help in fixing them.A deep-dive into Keras optimizers and the things that need to be taken into consideration while building a gradient accumulation mechanism.How to use the Run:AI Python library and easily add gradient accumulation support to your Keras models.
The problems in batch sizing one might encounter while training neural networks and being limited by GPU memory.
Why and how gradient accumulation might help in fixing them.
A deep-dive into Keras optimizers and the things that need to be taken into consideration while building a gradient accumulation mechanism.
How to use the Run:AI Python library and easily add gradient accumulation support to your Keras models.
We hope we were able to shed some light on those subjects and help you understand them a bit better.
An open-source gradient accumulation tool, as well as usage examples and more resources, are available on GitHub.
Please share with us if you found this interesting and helpful in running your own neural networks! | [
{
"code": null,
"e": 331,
"s": 172,
"text": "In another article, we covered what is gradient accumulation in deep learning and how it can solve issues when running neural networks with large batch sizes."
},
{
"code": null,
"e": 562,
"s": 331,
"text": "In this article, we will first see how you can easily use the generic gradient accumulation tool we implemented and used at Run:AI. Then, we will deep-dive into Keras optimizers and the way we have implemented such a generic tool."
},
{
"code": null,
"e": 648,
"s": 562,
"text": "The code is available on GitHub along with examples you can use right out of the box."
},
{
"code": null,
"e": 794,
"s": 648,
"text": "Adding gradient accumulation support to your Keras models is extremely simple. First of all, install the Run:AI Python library using the command:"
},
{
"code": null,
"e": 812,
"s": 794,
"text": "pip install runai"
},
{
"code": null,
"e": 882,
"s": 812,
"text": "Then, import the gradient accumulation package into your Python code:"
},
{
"code": null,
"e": 898,
"s": 882,
"text": "import runai.ga"
},
{
"code": null,
"e": 1238,
"s": 898,
"text": "Now, you can choose one of two options. You can either wrap an existing optimizer with the generic gradient accumulation wrapper or create a gradient accumulation version of any of the built-in optimizers. The two options require specifying the number of steps you want to accumulate gradients over (passed as STEPS in the examples below)."
},
{
"code": null,
"e": 1323,
"s": 1238,
"text": "Use the next line to wrap an existing optimizer (where optimizer is your optimizer):"
},
{
"code": null,
"e": 1399,
"s": 1323,
"text": "optimizer = runai.ga.keras.optimizers.Optimizer( optimizer, steps=STEPS)"
},
{
"code": null,
"e": 1535,
"s": 1399,
"text": "Or, use the next line to create a gradient accumulation version of any of the built-in optimizers (“Adam” is used in the next example):"
},
{
"code": null,
"e": 1591,
"s": 1535,
"text": "optimizer = runai.ga.keras.optimizers.Adam(steps=STEPS)"
},
{
"code": null,
"e": 1685,
"s": 1591,
"text": "And that’s it! you have successfully added gradient accumulation support to your Keras model."
},
{
"code": null,
"e": 1966,
"s": 1685,
"text": "After seeing how easy it is to use, let’s now see what’s going on under the hood. First, we are going to examine the concept of optimizers in Keras and discuss their responsibility and their implementation. Then, we will deep-dive into how we implemented such a generic mechanism."
},
{
"code": null,
"e": 2413,
"s": 1966,
"text": "Optimizers in Keras are responsible for implementing the optimization algorithm — the mathematical formula responsible for minimizing the loss function. They receive all the model parameters — weights and biases — as inputs, compute their gradients and use them to generate updates for the model parameters. The updates for the model parameters are not the gradients themselves and are calculated using the gradients, as well as other parameters."
},
{
"code": null,
"e": 2660,
"s": 2413,
"text": "Every optimization algorithm has parameters. Some optimizers have similar parameters (e.g. “epsilon”, “beta_1”, “beta_2”, etc...), some may have unique ones (e.g. “amsgrad” in Adam), and they all support “learning rate” (and learning rate decay)."
},
{
"code": null,
"e": 2982,
"s": 2660,
"text": "While building the model, Keras will call the optimizer and will pass two arguments. The first argument will be all the trainable variables — weights and biases — of the model. The second argument will be the loss value. Note that the trainable variables and the loss are tensors and not the actual values of the tensors."
},
{
"code": null,
"e": 3262,
"s": 2982,
"text": "The optimizer then takes these input tensors and adds the optimization algorithm to the model. It first calculates the gradients of the trainable variables with respect to the loss (by calling tf.gradients()), and then generates the tensors representing the mathematical formula."
},
{
"code": null,
"e": 3528,
"s": 3262,
"text": "Keras will then evaluate these tensors — that were generated by the optimizer — every step. By evaluating those tensors, the gradients will be calculated, and then the variable updates will be calculated and assigned to the model variables — the weights and biases."
},
{
"code": null,
"e": 3801,
"s": 3528,
"text": "Keras optimizers are Python classes, and they all inherit a base class called Optimizer (can be seen here). The base class implements a few methods and declares other (virtual) methods that must be implemented in subclasses. Let’s briefly examine the methods in Optimizer:"
},
{
"code": null,
"e": 3884,
"s": 3801,
"text": "__init__(self, **kwargs): Initializes common members and configuration parameters."
},
{
"code": null,
"e": 4068,
"s": 3884,
"text": "get_updates(self, loss, params): A virtual method that is not implemented in the base class, and must be defined in subclasses, implementing the mathematical formula of the optimizer."
},
{
"code": null,
"e": 4228,
"s": 4068,
"text": "get_gradients(self, loss, params): A utility method to ease the gradient calculations of loss with respect to params (a wrapper of tf.gradients() technically)."
},
{
"code": null,
"e": 4300,
"s": 4228,
"text": "set_weights(self, weights): Sets the values of the optimizer’s weights."
},
{
"code": null,
"e": 4363,
"s": 4300,
"text": "get_weights(self): Gets the values of the optimizer’s weights."
},
{
"code": null,
"e": 4419,
"s": 4363,
"text": "get_config(self): Gets the common configuration values."
},
{
"code": null,
"e": 4662,
"s": 4419,
"text": "We will be focusing on get_updates(). This method is only declared (virtual) in the base class; it is not implemented in it and must be implemented in all subclasses. Its implementation is the main difference between one optimizer to another."
},
{
"code": null,
"e": 4942,
"s": 4662,
"text": "As we said, Keras will call get_updates() as part of building the model. The method receives two arguments: loss and params, which both are tensors. and returns a list of tensors, which are the “Assign” ops — the tensors that actually assign the variable updates upon evaluation."
},
{
"code": null,
"e": 5096,
"s": 4942,
"text": "Let’s examine a simplified version of the implementation of SGD’s get_updates(). Note that this is a simplified version and not the actual code in Keras:"
},
{
"code": null,
"e": 5217,
"s": 5096,
"text": "First, at line 2, the optimizer calculates the gradients of loss with respect to params by calling self.get_gradients()."
},
{
"code": null,
"e": 5671,
"s": 5217,
"text": "Then, in lines 4–6, the optimizer iterates through all the trainable variables of the model, with their respective calculated gradients. For every parameter, it calculates (line 5) the new value of the variable (new_p) using the gradient and the learning rate (self.lr is a tensor initialized in __init__()). Then, it creates a tensor that will assign the variable’s new value (K.update(p, new_p)) and adds it to the list of such tensors (self.updates)."
},
{
"code": null,
"e": 5810,
"s": 5671,
"text": "Finally, in line 8, the optimizer returns the list of the “Assign” tensors (self.updates), which will be evaluated by Keras in every step."
},
{
"code": null,
"e": 6213,
"s": 5810,
"text": "This method is called exactly once when the model is being built. It may take some time to digest, but be sure to understand that the arguments and the results are tensor objects and not the actual tensor values. Note that line 5 may be misleading and may seem like it calculates actual values, but this is not the case and is just syntactic sugar (TensorFlow’s operator overloading) on tensor objects."
},
{
"code": null,
"e": 6300,
"s": 6213,
"text": "After examining a simplified version, it’s time to figure out what happens in reality."
},
{
"code": null,
"e": 6878,
"s": 6300,
"text": "In addition to their plain algorithm, most of the optimizers support learning rate decay, which means they modify the learning rate throughout the training of the model, instead of having a constant value for it. In order to support modifying the learning rate over time, the concept of time should be defined. As expected, the learning rate is not modified as a function of the actual time that has passed since the beginning of the training phase, but as a function of the step number, and to support this, optimizers count steps (called iterations in their implementations)."
},
{
"code": null,
"e": 7094,
"s": 6878,
"text": "Moreover, SGD in Keras supports momentums and the Nesterov momentum algorithm, which complicates things a bit more. Let’s take a look at the actual implementation of SGD’s get_updates() (can be seen on GitHub also):"
},
{
"code": null,
"e": 7173,
"s": 7094,
"text": "Let’s go through the additions over the simplified version we examined before."
},
{
"code": null,
"e": 7384,
"s": 7173,
"text": "In line 3, the optimizer creates an “Assign” tensor to increase self.iterations by 1 in every step. self.iterations is the step counter (a tensor object) and is created in __init__() with an initial value of 0."
},
{
"code": null,
"e": 7588,
"s": 7384,
"text": "In lines 5–7 we can see the learning rate decay formula as a function of the step counter (self.iterations) and the decay value (an argument passed to the optimizer upon creation, and set to self.decay)."
},
{
"code": null,
"e": 7774,
"s": 7588,
"text": "In line 11 it creates variables for the momentums. It declares another variable, for every trainable variable, with the same shape, and initializes it to 0 (the call to K.zeros(shape))."
},
{
"code": null,
"e": 7972,
"s": 7774,
"text": "Then, inside the iteration over the trainable variables, it calculates the new value for every momentum (line 14) and creates an “Assign” tensor to update the momentum with the new value (line 15)."
},
{
"code": null,
"e": 8201,
"s": 7972,
"text": "Then, in lines 17–20, it calculates the new value for the parameter — depending on whether configured to apply Nesterov momentum or not — and applies the necessary constraints on the parameter (if there are such) in lines 23–24."
},
{
"code": null,
"e": 8274,
"s": 8201,
"text": "The rest of the lines are similar to the simplified version from before."
},
{
"code": null,
"e": 8377,
"s": 8274,
"text": "You can wander around optimizers.py and read the implementations of the different optimizers of Keras."
},
{
"code": null,
"e": 8574,
"s": 8377,
"text": "Now, after deep-diving into what exactly Keras optimizers are and how they are implemented, we are ready to discuss the different implementation alternatives for a gradient accumulation mechanism."
},
{
"code": null,
"e": 8926,
"s": 8574,
"text": "It is possible to rewrite any optimizer to support gradient-accumulation. Gradients should be accumulated over a few steps and only then should the optimizer use them for updating the model parameters. This is not optimal as gradient accumulation is a generic approach and should be optimizer-independent, and there are several flaws to this approach:"
},
{
"code": null,
"e": 9327,
"s": 8926,
"text": "Every optimizer has a different formula for implementing a different optimization algorithm and therefore will require a different implementation for the respective gradient accumulation version.This is quite version-specific and code modification will be required every time the original implementation will be changed or a new optimizer will be added.It causes code duplication and is less elegant."
},
{
"code": null,
"e": 9523,
"s": 9327,
"text": "Every optimizer has a different formula for implementing a different optimization algorithm and therefore will require a different implementation for the respective gradient accumulation version."
},
{
"code": null,
"e": 9682,
"s": 9523,
"text": "This is quite version-specific and code modification will be required every time the original implementation will be changed or a new optimizer will be added."
},
{
"code": null,
"e": 9730,
"s": 9682,
"text": "It causes code duplication and is less elegant."
},
{
"code": null,
"e": 9879,
"s": 9730,
"text": "A preferable approach is to design the gradient accumulation model so that it can wrap any Keras optimizer regardless of its optimization algorithm."
},
{
"code": null,
"e": 9998,
"s": 9879,
"text": "By having a generic gradient accumulation mechanism, changes in the original optimizers will not require code updates."
},
{
"code": null,
"e": 10138,
"s": 9998,
"text": "In order to design and implement a generic gradient accumulation mechanism, there are some things that need to be taken into consideration."
},
{
"code": null,
"e": 10465,
"s": 10138,
"text": "Running the optimization algorithm on every mini-batch will not result in the same updates for the model parameters. In other words, we cannot just evaluate the optimization algorithm in every step — on every mini-batch. Otherwise, there was no need for gradient accumulation, and we could have just used a smaller batch size."
},
{
"code": null,
"e": 10918,
"s": 10465,
"text": "If we were to use the global batch, all the gradients would have been calculated using the same values of the model parameters — the weights and biases. When splitting the global batch into several mini-batches, evaluating the optimization algorithm every step will cause the model parameters to be updated after every mini-batch. This means that the gradients of all mini-batches will not be calculated using the same values of the weights and biases."
},
{
"code": null,
"e": 11243,
"s": 10918,
"text": "In addition, optimizers use various parameters as part of their formula, and those parameters are updated as part of the evaluation of the optimization algorithm. Updating those parameters every step — after every mini-batch — will result in changes in the state of the optimization algorithm between different mini-batches."
},
{
"code": null,
"e": 11466,
"s": 11243,
"text": "Our wrapper is a Python class that inherits Keras’s base Optimizer class. We receive the original optimizer as an argument upon creation (in __init__()), as well as the number of steps we want to accumulate gradients over."
},
{
"code": null,
"e": 11698,
"s": 11466,
"text": "We define all the methods exposed by optimizers (i.e. get_gradients(), set_weights(), get_weights(), etc...) and transparently call the original optimizer’s respective methods. The main logic lives — as expected — in get_updates()."
},
{
"code": null,
"e": 11820,
"s": 11698,
"text": "Let’s start examining get_updates() (can be seen on GitHub as well), and deep-dive into the algorithm and implementation:"
},
{
"code": null,
"e": 12008,
"s": 11820,
"text": "The first line (2) should seem familiar, where we calculate the gradients in the same way as other optimizers do. Note that grads will hold the value of the gradients of every mini-batch."
},
{
"code": null,
"e": 12294,
"s": 12008,
"text": "In line 5, we declare a step counter — called iterations — with an initial value of 0 (pretty similar to other optimizers). We use the step counter to tell if we are either at the first or the last step of the accumulation. To do so, we declare two tensors: first and last (lines 6–7)."
},
{
"code": null,
"e": 12738,
"s": 12294,
"text": "first will be set to True every time we passed exactly self.steps steps. Technically, this is when iterations % self.steps will be equal to 0. For example, if we accumulate over five steps, this will be the case at the first step (indexed 0), the sixth step (indexed 5), the eleventh step (indexed 10), etc... In those cases, at the beginning of the step, we want to reset the accumulated gradients to 0 and start accumulating them once again."
},
{
"code": null,
"e": 13010,
"s": 12738,
"text": "last will be set to True every step we want to update the variables. Technically, this is when iterations % self.steps will be equal to self.steps — 1. Continuing the example from before, this will be the case at the fifth step (indexed 4), tenth step (indexed 9), etc..."
},
{
"code": null,
"e": 13265,
"s": 13010,
"text": "In line 10, we declare variables to hold the values accumulated gradients between steps. We declare such a variable for every model parameter — for every trainable weight or bias — with the shape and type of the parameter, and initialize them with zeros."
},
{
"code": null,
"e": 13888,
"s": 13265,
"text": "Using those variables, in line 13 we declare tensors — agrads — to hold the values of accumulated gradients in every step. We use first to tell whether we should start accumulating the gradients from now on or use the gradients accumulated in the previous steps. If first is True — meaning we start accumulating from now on — we use the gradients of the current mini-batch alone. If first is False — meaning we should use the gradients accumulated over the past steps — we add the gradients of the current mini-batch to vagrads. This control flow (checking the value of first) is generated into the model using K.switch()."
},
{
"code": null,
"e": 14399,
"s": 13888,
"text": "As a generic wrapper, we don’t implement any optimization algorithm. The original optimizer is responsible for that. As we covered, every optimizer implements its mathematical formula in get_updates(). There, the optimizer manages and uses all the needed parameters for the formula (e.g. step counter, learning rate, momentums, etc...). The optimizer stores the values of the parameters in dedicated variables, and every time a parameter needs to be updated, it assigns the new value to its dedicated variable."
},
{
"code": null,
"e": 14620,
"s": 14399,
"text": "The method get_updates() is called once, generating “Assign” tensors that will be evaluated in every step. Some of them are the updates of the model parameters, and the other ones are updates to the optimizer parameters."
},
{
"code": null,
"e": 15180,
"s": 14620,
"text": "As long as we are accumulating gradients, we don’t want any of these updates to happen. We don’t want the model parameters to be updated in order for all the mini-batches to start from the exact same point, in terms of having the same values for the weights and biases. We don’t want the optimizer parameters to be updated in order for the optimizer to advance in the pace as if it were to run on the global batch. For example, we want the step counter to increase only after all mini-batches passed, so the learning rate will be modified at the correct rate."
},
{
"code": null,
"e": 15374,
"s": 15180,
"text": "We want all the updates to take place only after all the mini-batches have passed. Technically, this means we want the updates to occur at the last step of the accumulation — when last is True."
},
{
"code": null,
"e": 15636,
"s": 15374,
"text": "So, if we could have just called the original optimizer’s get_updates(), while (1) making it use the accumulated gradients, and (2) causing all the variable updates to take place only at the last steps of the accumulation, we would have achieved what we wanted."
},
{
"code": null,
"e": 15802,
"s": 15636,
"text": "Fortunately, replacing (hooking) methods is really easy in Python, and by replacing a few methods with a different implementation we can easily achieve exactly that."
},
{
"code": null,
"e": 16300,
"s": 15802,
"text": "Optimizers call their get_gradients() from get_updates() to calculate the gradients of the parameters with respect to the loss. Therefore, we replace the optimizer’s get_gradients() with a function that does nothing but returning the accumulated gradients (agrads — the tensors we generated in line 13). This will cause the original optimizer to refer to the accumulated gradients in its algorithm and will solve (1). Let’s take a look at a simplified implementation for such a replacement method:"
},
{
"code": null,
"e": 17320,
"s": 16300,
"text": "Regarding (2), variables in Keras can be assigned using 3 methods: K.update(), K.update_add(), and K.update_sub(). Optimizers use these methods for all updates — for the model parameters as well as for the optimizer parameters. We replace all three of them (can be seen on GitHub). We want all tensors created using those methods to assign values only in the last mini-batch and to do nothing otherwise. Therefore, in our methods — that replace the three — we wrap every value being assigned with a conditional switch and pass this switch to the respective method. If this is the last mini-batch (last is True), we assign the actual value to the variable, otherwise, we assign a value that does not affect the variable. For K.update_add() and K.update_sub() we assign zero, causing the variable to not actually increase or decrease. For K.update() we assign the current value of the variable, causing the variable to keep its current value. Let’s take a look at a simplified implementation for such replacement methods:"
},
{
"code": null,
"e": 17468,
"s": 17320,
"text": "Back to our get_updates(), in lines 15–18 we actually replace all those methods. We use helper classes — subclasses of runai.utils.Hook — to do so."
},
{
"code": null,
"e": 17690,
"s": 17468,
"text": "In line 19 we call the original optimizer’s get_updates(). With all those methods replaced, we (1) make it refer to the accumulated gradients, and (2) cause all updates (“Assign” ops) to take place only when last is True."
},
{
"code": null,
"e": 17754,
"s": 17690,
"text": "We have two more things we have to do at the end of every step."
},
{
"code": null,
"e": 17874,
"s": 17754,
"text": "First, we have to update our variables to hold the current value of the accumulated gradients. This is done in line 33."
},
{
"code": null,
"e": 18179,
"s": 17874,
"text": "Second, we have to advance our step counter — self.iterations (line 36). To make sure this happens at the end of the step we generate the tensors under control dependencies of all other “Assign” ops. This causes the step counter update to take place only after all other updates have already taken place."
},
{
"code": null,
"e": 18264,
"s": 18179,
"text": "This article along with previous ones was meant to describe a few things in details:"
},
{
"code": null,
"e": 18679,
"s": 18264,
"text": "The problems in batch sizing one might encounter while training neural networks and being limited by GPU memory.Why and how gradient accumulation might help in fixing them.A deep-dive into Keras optimizers and the things that need to be taken into consideration while building a gradient accumulation mechanism.How to use the Run:AI Python library and easily add gradient accumulation support to your Keras models."
},
{
"code": null,
"e": 18792,
"s": 18679,
"text": "The problems in batch sizing one might encounter while training neural networks and being limited by GPU memory."
},
{
"code": null,
"e": 18853,
"s": 18792,
"text": "Why and how gradient accumulation might help in fixing them."
},
{
"code": null,
"e": 18993,
"s": 18853,
"text": "A deep-dive into Keras optimizers and the things that need to be taken into consideration while building a gradient accumulation mechanism."
},
{
"code": null,
"e": 19097,
"s": 18993,
"text": "How to use the Run:AI Python library and easily add gradient accumulation support to your Keras models."
},
{
"code": null,
"e": 19198,
"s": 19097,
"text": "We hope we were able to shed some light on those subjects and help you understand them a bit better."
},
{
"code": null,
"e": 19312,
"s": 19198,
"text": "An open-source gradient accumulation tool, as well as usage examples and more resources, are available on GitHub."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.