title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Bezier Curves in OpenGL - GeeksforGeeks
|
30 Jun, 2021
OpenGL is a cross-language, cross-platform API for rendering 2D and 3D Vector Graphics. It is used to perform a lot of design as well as animation using OpenGL. In this article, we will discuss the concept and implementation of the Bezier Curves OpenGL.
Beizer Curves:
The concept of Bezier curves was discovered by the French engineer Pierre Bézier.
Bezier curves are basically used in computer graphics to draw shapes, for CSS animation, and in many other places.
These are the curves that are generated under the control of some other points, also called control points.
Properties of Bezier Curves:
A very important property of Bezier curves is that they always pass through the first and last control points.
The degree of the polynomial defining the curve segment is always one less than the number of defining polygon points. So, for example, if we have 4 control points, then the degree of the polynomial is 3, i.e., cubic polynomial.
In the Bezier curves, moving a control point alters the shape of the whole curve.
A Bezier curve generally follows the shape of the defining polygon.
A curve is always inside the convex hull of control points.
Below is the C++ program to implement the Bezier Curves:
C++
// C++ program to implement Bezier Curves#include <GL/gl.h>#include <GL/glu.h>#include <GL/glut.h>#include <stdlib.h> int i; // Function to initialize the Beizer// curve pointervoid init(void){ glClearColor(1.0, 1.0, 1.0, 1.0);} // Function to draw the Bitmap Textvoid drawBitmapText(char* string, float x, float y, float z){ char* c; glRasterPos2f(x, y); // Traverse the string for (c = string; *c != '\0'; c++) { glutBitmapCharacter( GLUT_BITMAP_TIMES_ROMAN_24, *c); }} // Function to draw the shapesvoid draw(GLfloat ctrlpoints[4][3]){ glShadeModel(GL_FLAT); glMap1f(GL_MAP1_VERTEX_3, 0.0, 1.0, 3, 4, &ctrlpoints[0][0]); glEnable(GL_MAP1_VERTEX_3); // Fill the color glColor3f(1.0, 1.0, 1.0); glBegin(GL_LINE_STRIP); // Find the coordinates for (i = 0; i <= 30; i++) glEvalCoord1f((GLfloat)i / 30.0); glEnd(); glFlush();} // Function to display the curved// drawn using the Beizer Curvevoid display(void){ int i; // Specifying all the control // points through which the // curve will pass GLfloat ctrlpoints[4][3] = { { -0.00, 2.00, 0.0 }, { -2.00, 2.00, 0.0 }, { -2.00, -1.00, 0.0 }, { -0.00, -1.00, 0.0 } }; draw(ctrlpoints); GLfloat ctrlpoints2[4][3] = { { 0.0, -1.00, 0.0 }, { 0.55, -0.65, 0.0 }, { 0.65, -0.25, 0.0 }, { 0.00, 0.70, 0.0 } }; draw(ctrlpoints2); GLfloat ctrlpoints3[4][3] = { { 0.0, 0.70, 0.0 }, { 0.15, 0.70, 0.0 }, { 0.25, 0.70, 0.0 }, { 0.65, 0.700, 0.0 } }; draw(ctrlpoints3); GLfloat ctrlpoints4[4][3] = { { 0.65, 0.70, 0.0 }, { 0.65, -0.90, 0.0 }, { 0.65, -0.70, 0.0 }, { 0.65, -1.00, 0.0 } }; draw(ctrlpoints4); GLfloat ctrlpoints5[4][3] = { { 1.00, -1.00, 0.0 }, { 1.00, -0.5, 0.0 }, { 1.00, -0.20, 0.0 }, { 1.00, 1.35, 0.0 } }; draw(ctrlpoints5); GLfloat ctrlpoints6[4][3] = { { 1.00, 1.35 }, { 1.10, 1.35, 0.0 }, { 1.10, 1.35, 0.0 }, { 1.90, 1.35, 0.0 } }; draw(ctrlpoints6); GLfloat ctrlpoints7[4][3] = { { 1.00, 0.50, 0.0 }, { 1.10, 0.5, 0.0 }, { 1.10, 0.5, 0.0 }, { 1.90, 0.5, 0.0 } }; draw(ctrlpoints7); GLfloat ctrlpoints8[4][3] = { { 3.50, 2.00, 0.0 }, { 1.50, 2.00, 0.0 }, { 1.50, -1.00, 0.0 }, { 3.50, -1.00, 0.0 } }; draw(ctrlpoints8); GLfloat ctrlpoints9[4][3] = { { 3.50, -1.00, 0.0 }, { 4.05, -0.65, 0.0 }, { 4.15, -0.25, 0.0 }, { 3.50, 0.70, 0.0 } }; draw(ctrlpoints9); GLfloat ctrlpoints10[4][3] = { { 3.50, 0.70, 0.0 }, { 3.65, 0.70, 0.0 }, { 3.75, 0.70, 0.0 }, { 4.15, 0.700, 0.0 } }; draw(ctrlpoints10); GLfloat ctrlpoints11[4][3] = { { 4.15, 0.70, 0.0 }, { 4.15, -0.90, 0.0 }, { 4.15, -0.70, 0.0 }, { 4.15, -1.00, 0.0 } }; draw(ctrlpoints11); GLfloat ctrlpoints12[4][3] = { { -2.0, 2.50, 0.0 }, { 2.05, 2.50, 0.0 }, { 3.15, 2.50, 0.0 }, { 4.65, 2.50, 0.0 } }; draw(ctrlpoints12); GLfloat ctrlpoints13[4][3] = { { -2.0, -1.80, 0.0 }, { 2.05, -1.80, 0.0 }, { 3.15, -1.80, 0.0 }, { 4.65, -1.80, 0.0 } }; draw(ctrlpoints13); GLfloat ctrlpoints14[4][3] = { { -2.0, -1.80, 0.0 }, { -2.0, 1.80, 0.0 }, { -2.0, 1.90, 0.0 }, { -2.0, 2.50, 0.0 } }; draw(ctrlpoints14); GLfloat ctrlpoints15[4][3] = { { 4.650, -1.80, 0.0 }, { 4.65, 1.80, 0.0 }, { 4.65, 1.90, 0.0 }, { 4.65, 2.50, 0.0 } }; draw(ctrlpoints15); // Specifying the colour of // text to be displayed glColor3f(1, 0, 0); drawBitmapText("Bezier Curves " "Implementation", -1.00, -3.0, 0); glFlush();} // Function perform the reshaping// of the curvevoid reshape(int w, int h){ glViewport(0, 0, (GLsizei)w, (GLsizei)h); // Matrix mode glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w <= h) glOrtho(-5.0, 5.0, -5.0 * (GLfloat)h / (GLfloat)w, 5.0 * (GLfloat)h / (GLfloat)w, -5.0, 5.0); else glOrtho(-5.0 * (GLfloat)w / (GLfloat)h, 5.0 * (GLfloat)w / (GLfloat)h, -5.0, 5.0, -5.0, 5.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity();} // Driver Codeint main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB); // Specifies the window size glutInitWindowSize(500, 500); glutInitWindowPosition(100, 100); // Creates the window as // specified by the user glutCreateWindow(argv[0]); init(); // Links display event with the // display event handler(display) glutDisplayFunc(display); glutReshapeFunc(reshape); // Loops the current event glutMainLoop(); return 0;}
Output:
simmytarika5
c-graphics
computer-graphics
OpenGL
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 25597,
"s": 25343,
"text": "OpenGL is a cross-language, cross-platform API for rendering 2D and 3D Vector Graphics. It is used to perform a lot of design as well as animation using OpenGL. In this article, we will discuss the concept and implementation of the Bezier Curves OpenGL."
},
{
"code": null,
"e": 25612,
"s": 25597,
"text": "Beizer Curves:"
},
{
"code": null,
"e": 25695,
"s": 25612,
"text": "The concept of Bezier curves was discovered by the French engineer Pierre Bézier."
},
{
"code": null,
"e": 25810,
"s": 25695,
"text": "Bezier curves are basically used in computer graphics to draw shapes, for CSS animation, and in many other places."
},
{
"code": null,
"e": 25918,
"s": 25810,
"text": "These are the curves that are generated under the control of some other points, also called control points."
},
{
"code": null,
"e": 25947,
"s": 25918,
"text": "Properties of Bezier Curves:"
},
{
"code": null,
"e": 26058,
"s": 25947,
"text": "A very important property of Bezier curves is that they always pass through the first and last control points."
},
{
"code": null,
"e": 26287,
"s": 26058,
"text": "The degree of the polynomial defining the curve segment is always one less than the number of defining polygon points. So, for example, if we have 4 control points, then the degree of the polynomial is 3, i.e., cubic polynomial."
},
{
"code": null,
"e": 26369,
"s": 26287,
"text": "In the Bezier curves, moving a control point alters the shape of the whole curve."
},
{
"code": null,
"e": 26437,
"s": 26369,
"text": "A Bezier curve generally follows the shape of the defining polygon."
},
{
"code": null,
"e": 26497,
"s": 26437,
"text": "A curve is always inside the convex hull of control points."
},
{
"code": null,
"e": 26554,
"s": 26497,
"text": "Below is the C++ program to implement the Bezier Curves:"
},
{
"code": null,
"e": 26558,
"s": 26554,
"text": "C++"
},
{
"code": "// C++ program to implement Bezier Curves#include <GL/gl.h>#include <GL/glu.h>#include <GL/glut.h>#include <stdlib.h> int i; // Function to initialize the Beizer// curve pointervoid init(void){ glClearColor(1.0, 1.0, 1.0, 1.0);} // Function to draw the Bitmap Textvoid drawBitmapText(char* string, float x, float y, float z){ char* c; glRasterPos2f(x, y); // Traverse the string for (c = string; *c != '\\0'; c++) { glutBitmapCharacter( GLUT_BITMAP_TIMES_ROMAN_24, *c); }} // Function to draw the shapesvoid draw(GLfloat ctrlpoints[4][3]){ glShadeModel(GL_FLAT); glMap1f(GL_MAP1_VERTEX_3, 0.0, 1.0, 3, 4, &ctrlpoints[0][0]); glEnable(GL_MAP1_VERTEX_3); // Fill the color glColor3f(1.0, 1.0, 1.0); glBegin(GL_LINE_STRIP); // Find the coordinates for (i = 0; i <= 30; i++) glEvalCoord1f((GLfloat)i / 30.0); glEnd(); glFlush();} // Function to display the curved// drawn using the Beizer Curvevoid display(void){ int i; // Specifying all the control // points through which the // curve will pass GLfloat ctrlpoints[4][3] = { { -0.00, 2.00, 0.0 }, { -2.00, 2.00, 0.0 }, { -2.00, -1.00, 0.0 }, { -0.00, -1.00, 0.0 } }; draw(ctrlpoints); GLfloat ctrlpoints2[4][3] = { { 0.0, -1.00, 0.0 }, { 0.55, -0.65, 0.0 }, { 0.65, -0.25, 0.0 }, { 0.00, 0.70, 0.0 } }; draw(ctrlpoints2); GLfloat ctrlpoints3[4][3] = { { 0.0, 0.70, 0.0 }, { 0.15, 0.70, 0.0 }, { 0.25, 0.70, 0.0 }, { 0.65, 0.700, 0.0 } }; draw(ctrlpoints3); GLfloat ctrlpoints4[4][3] = { { 0.65, 0.70, 0.0 }, { 0.65, -0.90, 0.0 }, { 0.65, -0.70, 0.0 }, { 0.65, -1.00, 0.0 } }; draw(ctrlpoints4); GLfloat ctrlpoints5[4][3] = { { 1.00, -1.00, 0.0 }, { 1.00, -0.5, 0.0 }, { 1.00, -0.20, 0.0 }, { 1.00, 1.35, 0.0 } }; draw(ctrlpoints5); GLfloat ctrlpoints6[4][3] = { { 1.00, 1.35 }, { 1.10, 1.35, 0.0 }, { 1.10, 1.35, 0.0 }, { 1.90, 1.35, 0.0 } }; draw(ctrlpoints6); GLfloat ctrlpoints7[4][3] = { { 1.00, 0.50, 0.0 }, { 1.10, 0.5, 0.0 }, { 1.10, 0.5, 0.0 }, { 1.90, 0.5, 0.0 } }; draw(ctrlpoints7); GLfloat ctrlpoints8[4][3] = { { 3.50, 2.00, 0.0 }, { 1.50, 2.00, 0.0 }, { 1.50, -1.00, 0.0 }, { 3.50, -1.00, 0.0 } }; draw(ctrlpoints8); GLfloat ctrlpoints9[4][3] = { { 3.50, -1.00, 0.0 }, { 4.05, -0.65, 0.0 }, { 4.15, -0.25, 0.0 }, { 3.50, 0.70, 0.0 } }; draw(ctrlpoints9); GLfloat ctrlpoints10[4][3] = { { 3.50, 0.70, 0.0 }, { 3.65, 0.70, 0.0 }, { 3.75, 0.70, 0.0 }, { 4.15, 0.700, 0.0 } }; draw(ctrlpoints10); GLfloat ctrlpoints11[4][3] = { { 4.15, 0.70, 0.0 }, { 4.15, -0.90, 0.0 }, { 4.15, -0.70, 0.0 }, { 4.15, -1.00, 0.0 } }; draw(ctrlpoints11); GLfloat ctrlpoints12[4][3] = { { -2.0, 2.50, 0.0 }, { 2.05, 2.50, 0.0 }, { 3.15, 2.50, 0.0 }, { 4.65, 2.50, 0.0 } }; draw(ctrlpoints12); GLfloat ctrlpoints13[4][3] = { { -2.0, -1.80, 0.0 }, { 2.05, -1.80, 0.0 }, { 3.15, -1.80, 0.0 }, { 4.65, -1.80, 0.0 } }; draw(ctrlpoints13); GLfloat ctrlpoints14[4][3] = { { -2.0, -1.80, 0.0 }, { -2.0, 1.80, 0.0 }, { -2.0, 1.90, 0.0 }, { -2.0, 2.50, 0.0 } }; draw(ctrlpoints14); GLfloat ctrlpoints15[4][3] = { { 4.650, -1.80, 0.0 }, { 4.65, 1.80, 0.0 }, { 4.65, 1.90, 0.0 }, { 4.65, 2.50, 0.0 } }; draw(ctrlpoints15); // Specifying the colour of // text to be displayed glColor3f(1, 0, 0); drawBitmapText(\"Bezier Curves \" \"Implementation\", -1.00, -3.0, 0); glFlush();} // Function perform the reshaping// of the curvevoid reshape(int w, int h){ glViewport(0, 0, (GLsizei)w, (GLsizei)h); // Matrix mode glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w <= h) glOrtho(-5.0, 5.0, -5.0 * (GLfloat)h / (GLfloat)w, 5.0 * (GLfloat)h / (GLfloat)w, -5.0, 5.0); else glOrtho(-5.0 * (GLfloat)w / (GLfloat)h, 5.0 * (GLfloat)w / (GLfloat)h, -5.0, 5.0, -5.0, 5.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity();} // Driver Codeint main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB); // Specifies the window size glutInitWindowSize(500, 500); glutInitWindowPosition(100, 100); // Creates the window as // specified by the user glutCreateWindow(argv[0]); init(); // Links display event with the // display event handler(display) glutDisplayFunc(display); glutReshapeFunc(reshape); // Loops the current event glutMainLoop(); return 0;}",
"e": 31743,
"s": 26558,
"text": null
},
{
"code": null,
"e": 31751,
"s": 31743,
"text": "Output:"
},
{
"code": null,
"e": 31764,
"s": 31751,
"text": "simmytarika5"
},
{
"code": null,
"e": 31775,
"s": 31764,
"text": "c-graphics"
},
{
"code": null,
"e": 31793,
"s": 31775,
"text": "computer-graphics"
},
{
"code": null,
"e": 31800,
"s": 31793,
"text": "OpenGL"
},
{
"code": null,
"e": 31804,
"s": 31800,
"text": "C++"
},
{
"code": null,
"e": 31817,
"s": 31804,
"text": "C++ Programs"
},
{
"code": null,
"e": 31821,
"s": 31817,
"text": "CPP"
},
{
"code": null,
"e": 31919,
"s": 31821,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31947,
"s": 31919,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 31967,
"s": 31947,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 32000,
"s": 31967,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 32024,
"s": 32000,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 32049,
"s": 32024,
"text": "std::string class in C++"
},
{
"code": null,
"e": 32084,
"s": 32049,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 32128,
"s": 32084,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 32187,
"s": 32128,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 32213,
"s": 32187,
"text": "C++ Program for QuickSort"
}
] |
Matplotlib.colors.ListedColormap class in Python - GeeksforGeeks
|
21 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.colors.ListedColormap class belongs to the matplotlib.colors module. The matplotlib.colors module is used for converting color or numbers arguments to RGBA or RGB.This module is used for mapping numbers to colors or color specification conversion in a 1-D array of colors also known as colormap.
The matplotlib.colors.ListedColormap class is used to create colarmap objects from a list of colors. This can be useful for directly indexing into colormap and it can also be used to create special colormaps for normal mapping.
Syntax: class matplotlib.colors.ListedColormap(colors, name=’from_list’, N=None)
Parameters:
colors: It is an array or list of Matplotlib color specifications or equat to N x 3 or N x 4 floating point array(N rgb or rgba values)
name: It is an optional parameter that accepts a string to identify the colormap.
N: It is an optional parameter that accepts an integer value representing the number of entries in the map. Its default is None, where there is single colormap entry for every element in the list of colors. If N is less than len(colors) the list truncates at N whereas if N is greater than the list is extended with repetition.
Methods of the class:1) reversed(): This is used to create a reversed instance of the Colormap.
Syntax: reversed(self, name=None)
Parameters:
name: It is an optional parameter that that represents the name for the reversed colormap. If it’s set to None the name will be the name of the parent colormap + “_r”.
Returns: It returns a reversed instance of the colormap
Example 1:
import matplotlib.pyplot as pltimport numpy as npimport matplotlib.colors a = np.linspace(-3, 3)A, B = np.meshgrid(a, a)X = np.exp(-(A**2 + B**2))figure, (axes1, axes2) = plt.subplots(ncols = 2) colors =["green", "orange", "gold", "blue", "k", "#550011", "purple", "red"] axes1.set_title(" color list")contour = axes1.contourf(A, B, X, colors = colors) axes2.set_title("with colormap")cmap = matplotlib.colors.ListedColormap(colors)contour = axes2.contourf(A, B, X, cmap = cmap)figure.colorbar(contour) plt.show()
Output:
Example 2:
import matplotlib.pyplot as pltimport numpy as npimport matplotlib.colors as colorsfrom mpl_toolkits.axes_grid1 import make_axes_locatable res = np.array([[0, 2], [3, 4]], dtype = int) u = np.unique(res)bounds = np.concatenate(([res.min()-1], u[:-1]+np.diff(u)/2., [res.max()+1])) norm = colors.BoundaryNorm(bounds, len(bounds)-1)color_map1 = ['#7fc97f', '#ffff99', '#386cb0', '#f0027f']color_map = colors.ListedColormap(color_map1) fig, axes = plt.subplots()img = axes.imshow(res, cmap = color_map, norm = norm)divider = make_axes_locatable(axes)cax = divider.append_axes("right", size ="5 %") color_bar = plt.colorbar(img, cmap = color_map, norm = norm, cax = cax) color_bar.set_ticks(bounds[:-1]+np.diff(bounds)/2.)color_bar.ax.set_yticklabels(color_map1)color_bar.ax.tick_params(labelsize = 10) plt.show()
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
|
[
{
"code": null,
"e": 25471,
"s": 25443,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 25683,
"s": 25471,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack."
},
{
"code": null,
"e": 25994,
"s": 25683,
"text": "The matplotlib.colors.ListedColormap class belongs to the matplotlib.colors module. The matplotlib.colors module is used for converting color or numbers arguments to RGBA or RGB.This module is used for mapping numbers to colors or color specification conversion in a 1-D array of colors also known as colormap."
},
{
"code": null,
"e": 26222,
"s": 25994,
"text": "The matplotlib.colors.ListedColormap class is used to create colarmap objects from a list of colors. This can be useful for directly indexing into colormap and it can also be used to create special colormaps for normal mapping."
},
{
"code": null,
"e": 26303,
"s": 26222,
"text": "Syntax: class matplotlib.colors.ListedColormap(colors, name=’from_list’, N=None)"
},
{
"code": null,
"e": 26315,
"s": 26303,
"text": "Parameters:"
},
{
"code": null,
"e": 26451,
"s": 26315,
"text": "colors: It is an array or list of Matplotlib color specifications or equat to N x 3 or N x 4 floating point array(N rgb or rgba values)"
},
{
"code": null,
"e": 26533,
"s": 26451,
"text": "name: It is an optional parameter that accepts a string to identify the colormap."
},
{
"code": null,
"e": 26861,
"s": 26533,
"text": "N: It is an optional parameter that accepts an integer value representing the number of entries in the map. Its default is None, where there is single colormap entry for every element in the list of colors. If N is less than len(colors) the list truncates at N whereas if N is greater than the list is extended with repetition."
},
{
"code": null,
"e": 26957,
"s": 26861,
"text": "Methods of the class:1) reversed(): This is used to create a reversed instance of the Colormap."
},
{
"code": null,
"e": 26991,
"s": 26957,
"text": "Syntax: reversed(self, name=None)"
},
{
"code": null,
"e": 27003,
"s": 26991,
"text": "Parameters:"
},
{
"code": null,
"e": 27171,
"s": 27003,
"text": "name: It is an optional parameter that that represents the name for the reversed colormap. If it’s set to None the name will be the name of the parent colormap + “_r”."
},
{
"code": null,
"e": 27227,
"s": 27171,
"text": "Returns: It returns a reversed instance of the colormap"
},
{
"code": null,
"e": 27238,
"s": 27227,
"text": "Example 1:"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as npimport matplotlib.colors a = np.linspace(-3, 3)A, B = np.meshgrid(a, a)X = np.exp(-(A**2 + B**2))figure, (axes1, axes2) = plt.subplots(ncols = 2) colors =[\"green\", \"orange\", \"gold\", \"blue\", \"k\", \"#550011\", \"purple\", \"red\"] axes1.set_title(\" color list\")contour = axes1.contourf(A, B, X, colors = colors) axes2.set_title(\"with colormap\")cmap = matplotlib.colors.ListedColormap(colors)contour = axes2.contourf(A, B, X, cmap = cmap)figure.colorbar(contour) plt.show()",
"e": 27807,
"s": 27238,
"text": null
},
{
"code": null,
"e": 27815,
"s": 27807,
"text": "Output:"
},
{
"code": null,
"e": 27826,
"s": 27815,
"text": "Example 2:"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as npimport matplotlib.colors as colorsfrom mpl_toolkits.axes_grid1 import make_axes_locatable res = np.array([[0, 2], [3, 4]], dtype = int) u = np.unique(res)bounds = np.concatenate(([res.min()-1], u[:-1]+np.diff(u)/2., [res.max()+1])) norm = colors.BoundaryNorm(bounds, len(bounds)-1)color_map1 = ['#7fc97f', '#ffff99', '#386cb0', '#f0027f']color_map = colors.ListedColormap(color_map1) fig, axes = plt.subplots()img = axes.imshow(res, cmap = color_map, norm = norm)divider = make_axes_locatable(axes)cax = divider.append_axes(\"right\", size =\"5 %\") color_bar = plt.colorbar(img, cmap = color_map, norm = norm, cax = cax) color_bar.set_ticks(bounds[:-1]+np.diff(bounds)/2.)color_bar.ax.set_yticklabels(color_map1)color_bar.ax.tick_params(labelsize = 10) plt.show()",
"e": 28747,
"s": 27826,
"text": null
},
{
"code": null,
"e": 28755,
"s": 28747,
"text": "Output:"
},
{
"code": null,
"e": 28773,
"s": 28755,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 28780,
"s": 28773,
"text": "Python"
},
{
"code": null,
"e": 28796,
"s": 28780,
"text": "Write From Home"
},
{
"code": null,
"e": 28894,
"s": 28796,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28929,
"s": 28894,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28961,
"s": 28929,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28983,
"s": 28961,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29025,
"s": 28983,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29055,
"s": 29025,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29091,
"s": 29055,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 29127,
"s": 29091,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 29143,
"s": 29127,
"text": "Python infinity"
},
{
"code": null,
"e": 29204,
"s": 29143,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Concatenate the Array of elements into a single element - GeeksforGeeks
|
16 Jul, 2021
Given an array, arr[] consisting of N integers, the task is to print the single integer value obtained by joining the array elements.
Examples:
Input: arr[] = {1, 23, 345} Output: 12345
Input: arr[] = {123, 45, 6, 78} Output: 12345678
Approach: The given problem can be solved based on the following observations:
Considering X and Y as the two integer values to be joined. And also considering the length of the integer Y as l.Then two integers X and Y can be joined together as following: X×10l +Y
Considering X and Y as the two integer values to be joined. And also considering the length of the integer Y as l.
Then two integers X and Y can be joined together as following: X×10l +Y
X×10l +Y
Follow the steps below to solve the problem:
Initialize a variable, say ans as 0, to store the resulting value.
Traverse the array arr[] using the variable i, and then in each iteration multiply ans by 10 to the power of the count of the digit in the integer arr[i] and increment ans by arr[i].
Finally, after the above step, print the answer obtained in ans.
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 find the integer value// obtained by joining array elements// togetherint ConcatenateArr(int arr[], int N){ // Stores the resulting integer value int ans = arr[0]; // Traverse the array arr[] for (int i = 1; i < N; i++) { // Stores the count of digits of // arr[i] int l = floor(log10(arr[i]) + 1); // Update ans ans = ans * pow(10, l); // Increment ans by arr[i] ans += arr[i]; } // Return the ans return ans;} // Driver Codeint main(){ // Input int arr[] = { 1, 23, 456 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << ConcatenateArr(arr, N); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find the integer value// obtained by joining array elements// togetherstatic int ConcatenateArr(int[] arr, int N){ // Stores the resulting integer value int ans = arr[0]; // Traverse the array arr[] for(int i = 1; i < N; i++) { // Stores the count of digits of // arr[i] int l = (int)Math.floor(Math.log10(arr[i]) + 1); // Update ans ans = ans * (int)Math.pow(10, l); // Increment ans by arr[i] ans += arr[i]; } // Return the ans return ans;} // Driver Codepublic static void main(String args[]){ // Input int arr[] = { 1, 23, 456 }; int N = arr.length; // Function call System.out.println(ConcatenateArr(arr, N));}} // This code is contributed by avijitmondal1998
# Python3 program for the above approachimport math # Function to find the integer value# obtained by joining array elements# togetherdef ConcatenateArr(arr, N): # Stores the resulting integer value ans = arr[0] # Traverse the array arr[] for i in range(1, N): # Stores the count of digits of # arr[i] l = math.floor(math.log10(arr[i]) + 1) # Update ans ans = ans * math.pow(10, l) # Increment ans by arr[i] ans += arr[i] # Return the ans return int( ans) # Driver Codeif __name__ == "__main__": # Input arr = [1, 23, 456] N = len(arr) # Function call print(ConcatenateArr(arr, N)) # This code is contributed by ukasp.
// C# program for the above approachusing System; class GFG{ // Function to find the integer value// obtained by joining array elements// togetherstatic int ConcatenateArr(int[] arr, int N){ // Stores the resulting integer value int ans = arr[0]; // Traverse the array arr[] for(int i = 1; i < N; i++) { // Stores the count of digits of // arr[i] int l = (int)Math.Floor(Math.Log10(arr[i]) + 1); // Update ans ans = ans * (int)Math.Pow(10, l); // Increment ans by arr[i] ans += arr[i]; } // Return the ans return ans;} // Driver Codepublic static void Main(){ // Input int[] arr = { 1, 23, 456 }; int N = arr.Length; // Function call Console.Write(ConcatenateArr(arr, N)); }} // This code is contributed by sanjoy_62.
<script> // JavaScript program for the above approach // Function to find the integer value // obtained by joining array elements // together function ConcatenateArr(arr, N) { // Stores the resulting integer value let ans = arr[0]; // Traverse the array arr[] for (let i = 1; i < N; i++) { // Stores the count of digits of // arr[i] let l = Math.floor(Math.log10(arr[i]) + 1); // Update ans ans = ans * Math.pow(10, l); // Increment ans by arr[i] ans += arr[i]; } // Return the ans return ans; } // Driver Code // Input let arr = [1, 23, 456]; let N = arr.length; // Function call document.write(ConcatenateArr(arr, N)); // This code is contributed by Potta Lokesh </script>
123456
Time Complexity: O(N*log(M)), where M is the maximum element of the array.Auxiliary Space: O(1)
lokeshpotta20
ukasp
avijitmondal1998
sanjoy_62
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 26175,
"s": 26041,
"text": "Given an array, arr[] consisting of N integers, the task is to print the single integer value obtained by joining the array elements."
},
{
"code": null,
"e": 26187,
"s": 26175,
"text": "Examples: "
},
{
"code": null,
"e": 26232,
"s": 26187,
"text": "Input: arr[] = {1, 23, 345} Output: 12345 "
},
{
"code": null,
"e": 26284,
"s": 26232,
"text": "Input: arr[] = {123, 45, 6, 78} Output: 12345678 "
},
{
"code": null,
"e": 26364,
"s": 26284,
"text": "Approach: The given problem can be solved based on the following observations: "
},
{
"code": null,
"e": 26550,
"s": 26364,
"text": "Considering X and Y as the two integer values to be joined. And also considering the length of the integer Y as l.Then two integers X and Y can be joined together as following: X×10l +Y"
},
{
"code": null,
"e": 26665,
"s": 26550,
"text": "Considering X and Y as the two integer values to be joined. And also considering the length of the integer Y as l."
},
{
"code": null,
"e": 26737,
"s": 26665,
"text": "Then two integers X and Y can be joined together as following: X×10l +Y"
},
{
"code": null,
"e": 26747,
"s": 26737,
"text": " X×10l +Y"
},
{
"code": null,
"e": 26792,
"s": 26747,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26859,
"s": 26792,
"text": "Initialize a variable, say ans as 0, to store the resulting value."
},
{
"code": null,
"e": 27042,
"s": 26859,
"text": "Traverse the array arr[] using the variable i, and then in each iteration multiply ans by 10 to the power of the count of the digit in the integer arr[i] and increment ans by arr[i]."
},
{
"code": null,
"e": 27107,
"s": 27042,
"text": "Finally, after the above step, print the answer obtained in ans."
},
{
"code": null,
"e": 27158,
"s": 27107,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27162,
"s": 27158,
"text": "C++"
},
{
"code": null,
"e": 27167,
"s": 27162,
"text": "Java"
},
{
"code": null,
"e": 27175,
"s": 27167,
"text": "Python3"
},
{
"code": null,
"e": 27178,
"s": 27175,
"text": "C#"
},
{
"code": null,
"e": 27189,
"s": 27178,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the integer value// obtained by joining array elements// togetherint ConcatenateArr(int arr[], int N){ // Stores the resulting integer value int ans = arr[0]; // Traverse the array arr[] for (int i = 1; i < N; i++) { // Stores the count of digits of // arr[i] int l = floor(log10(arr[i]) + 1); // Update ans ans = ans * pow(10, l); // Increment ans by arr[i] ans += arr[i]; } // Return the ans return ans;} // Driver Codeint main(){ // Input int arr[] = { 1, 23, 456 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << ConcatenateArr(arr, N); return 0;}",
"e": 27954,
"s": 27189,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the integer value// obtained by joining array elements// togetherstatic int ConcatenateArr(int[] arr, int N){ // Stores the resulting integer value int ans = arr[0]; // Traverse the array arr[] for(int i = 1; i < N; i++) { // Stores the count of digits of // arr[i] int l = (int)Math.floor(Math.log10(arr[i]) + 1); // Update ans ans = ans * (int)Math.pow(10, l); // Increment ans by arr[i] ans += arr[i]; } // Return the ans return ans;} // Driver Codepublic static void main(String args[]){ // Input int arr[] = { 1, 23, 456 }; int N = arr.length; // Function call System.out.println(ConcatenateArr(arr, N));}} // This code is contributed by avijitmondal1998",
"e": 28823,
"s": 27954,
"text": null
},
{
"code": "# Python3 program for the above approachimport math # Function to find the integer value# obtained by joining array elements# togetherdef ConcatenateArr(arr, N): # Stores the resulting integer value ans = arr[0] # Traverse the array arr[] for i in range(1, N): # Stores the count of digits of # arr[i] l = math.floor(math.log10(arr[i]) + 1) # Update ans ans = ans * math.pow(10, l) # Increment ans by arr[i] ans += arr[i] # Return the ans return int( ans) # Driver Codeif __name__ == \"__main__\": # Input arr = [1, 23, 456] N = len(arr) # Function call print(ConcatenateArr(arr, N)) # This code is contributed by ukasp.",
"e": 29538,
"s": 28823,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the integer value// obtained by joining array elements// togetherstatic int ConcatenateArr(int[] arr, int N){ // Stores the resulting integer value int ans = arr[0]; // Traverse the array arr[] for(int i = 1; i < N; i++) { // Stores the count of digits of // arr[i] int l = (int)Math.Floor(Math.Log10(arr[i]) + 1); // Update ans ans = ans * (int)Math.Pow(10, l); // Increment ans by arr[i] ans += arr[i]; } // Return the ans return ans;} // Driver Codepublic static void Main(){ // Input int[] arr = { 1, 23, 456 }; int N = arr.Length; // Function call Console.Write(ConcatenateArr(arr, N)); }} // This code is contributed by sanjoy_62.",
"e": 30367,
"s": 29538,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find the integer value // obtained by joining array elements // together function ConcatenateArr(arr, N) { // Stores the resulting integer value let ans = arr[0]; // Traverse the array arr[] for (let i = 1; i < N; i++) { // Stores the count of digits of // arr[i] let l = Math.floor(Math.log10(arr[i]) + 1); // Update ans ans = ans * Math.pow(10, l); // Increment ans by arr[i] ans += arr[i]; } // Return the ans return ans; } // Driver Code // Input let arr = [1, 23, 456]; let N = arr.length; // Function call document.write(ConcatenateArr(arr, N)); // This code is contributed by Potta Lokesh </script>",
"e": 31310,
"s": 30367,
"text": null
},
{
"code": null,
"e": 31317,
"s": 31310,
"text": "123456"
},
{
"code": null,
"e": 31413,
"s": 31317,
"text": "Time Complexity: O(N*log(M)), where M is the maximum element of the array.Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31429,
"s": 31415,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 31435,
"s": 31429,
"text": "ukasp"
},
{
"code": null,
"e": 31452,
"s": 31435,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 31462,
"s": 31452,
"text": "sanjoy_62"
},
{
"code": null,
"e": 31469,
"s": 31462,
"text": "Arrays"
},
{
"code": null,
"e": 31482,
"s": 31469,
"text": "Mathematical"
},
{
"code": null,
"e": 31489,
"s": 31482,
"text": "Arrays"
},
{
"code": null,
"e": 31502,
"s": 31489,
"text": "Mathematical"
},
{
"code": null,
"e": 31600,
"s": 31502,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31627,
"s": 31600,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 31658,
"s": 31627,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 31683,
"s": 31658,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 31721,
"s": 31683,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 31742,
"s": 31721,
"text": "Next Greater Element"
},
{
"code": null,
"e": 31772,
"s": 31742,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31832,
"s": 31772,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31847,
"s": 31832,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31890,
"s": 31847,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Check If every group of a's is followed by a group of b's of same length - GeeksforGeeks
|
10 May, 2021
Given string str, the task is to check whether every group of consecutive a’s is followed by a group of consecutive b’s of the same length. If the condition is true for every group then print 1 else print 0.Examples:
Input: str = “ababaabb” Output: 1 ab, ab, aabb. All groups are validInput: str = “aabbabb” Output: 0 aabb, abb (A single ‘a’ followed by 2 ‘b’)
Approach:
For every a in the string increment the count.
Starting from the first b, decrement the count for every b.
If at the end of the above cycle, count != 0 then return false.
Else repeat the first two steps for the rest of the string.
Return true if the condition is satisfied for all the cycles else print 0.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to match whether there are always n consecutive b's// followed by n consecutive a's throughout the stringint matchPattern(string s){ int count = 0; int n = s.length(); // Traverse through the string int i = 0; while (i < n) { // Count a's in current segment while (i < n && s[i] == 'a') { count++; i++; } // Count b's in current segment while (i < n && s[i] == 'b') { count--; i++; } // If both counts are not same. if (count != 0) return false; } return true;} // Driver codeint main(){ string s = "bb"; if (matchPattern(s) == true) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation of the above approach public class GFG{ // Function to match whether there are always n consecutive b's// followed by n consecutive a's throughout the stringstatic boolean matchPattern(String s){ int count = 0; int n = s.length(); // Traverse through the string int i = 0; while (i < n) { // Count a's in current segment while (i < n && s.charAt(i) == 'a') { count++; i++; } // Count b's in current segment while (i < n && s.charAt(i) == 'b') { count--; i++; } // If both counts are not same. if (count != 0) return false; } return true;} // Driver codepublic static void main(String []args){ String s = "bb"; if (matchPattern(s) == true) System.out.println("Yes"); else System.out.println("No");} // This code is contributed by Ryuga}
# Python 3 implementation of the approach # Function to match whether there are# always n consecutive b's followed by# n consecutive a's throughout the stringdef matchPattern(s): count = 0; n = len(s); # Traverse through the string i = 0; while (i < n) : # Count a's in current segment while (i < n and s[i] == 'a'): count += 1 ; i =+ 1; # Count b's in current segment while (i < n and s[i] == 'b'): count -= 1 ; i += 1; # If both counts are not same. if (count != 0): return False; return True; # Driver codes = "bb";if (matchPattern(s) == True): print("Yes");else: print("No"); # This code is contributed# by Akanksha Rai
// C# implementation of the above approach using System;public class GFG{ // Function to match whether there are always n consecutive b's// followed by n consecutive a's throughout the stringstatic bool matchPattern(string s){ int count = 0; int n = s.Length; // Traverse through the string int i = 0; while (i < n) { // Count a's in current segment while (i < n && s[i] == 'a') { count++; i++; } // Count b's in current segment while (i < n && s[i] == 'b') { count--; i++; } // If both counts are not same. if (count != 0) return false; } return true;} // Driver codepublic static void Main(){ string s = "bb"; if (matchPattern(s) == true) Console.Write("Yes"); else Console.Write("No");} }
<?php//PHP implementation of the approach // Function to match whether there are always n consecutive b's// followed by n consecutive a's throughout the stringfunction matchPattern($s){ $count = 0; $n = strlen($s); // Traverse through the string $i = 0; while ($i < $n) { // Count a's in current segment while ($i < $n && $s[$i] == 'a') { $count++; $i++; } // Count b's in current segment while ($i < $n && $s[$i] == 'b') { $count--; $i++; } // If both counts are not same. if ($count != 0) return false; } return true;} // Driver code $s = "bb"; if (matchPattern($s) == true) echo "Yes"; else echo "No"; // This code is contributed by ajit?>
<script> // Javascript implementation of // the above approach // Function to match whether there are // always n consecutive b's // followed by n consecutive a's // throughout the string function matchPattern(s) { let count = 0; let n = s.length; // Traverse through the string let i = 0; while (i < n) { // Count a's in current segment while (i < n && s[i] == 'a') { count++; i++; } // Count b's in current segment while (i < n && s[i] == 'b') { count--; i++; } // If both counts are not same. if (count != 0) return false; } return true; } let s = "bb"; if (matchPattern(s) == true) document.write("Yes"); else document.write("No"); </script>
No
ankthon
ukasp
jit_t
Akanksha_Rai
mukesh07
array-traversal-question
binary-string
C++ Programs
Competitive Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming
|
[
{
"code": null,
"e": 25773,
"s": 25745,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 25992,
"s": 25773,
"text": "Given string str, the task is to check whether every group of consecutive a’s is followed by a group of consecutive b’s of the same length. If the condition is true for every group then print 1 else print 0.Examples: "
},
{
"code": null,
"e": 26138,
"s": 25992,
"text": "Input: str = “ababaabb” Output: 1 ab, ab, aabb. All groups are validInput: str = “aabbabb” Output: 0 aabb, abb (A single ‘a’ followed by 2 ‘b’) "
},
{
"code": null,
"e": 26151,
"s": 26140,
"text": "Approach: "
},
{
"code": null,
"e": 26198,
"s": 26151,
"text": "For every a in the string increment the count."
},
{
"code": null,
"e": 26258,
"s": 26198,
"text": "Starting from the first b, decrement the count for every b."
},
{
"code": null,
"e": 26322,
"s": 26258,
"text": "If at the end of the above cycle, count != 0 then return false."
},
{
"code": null,
"e": 26382,
"s": 26322,
"text": "Else repeat the first two steps for the rest of the string."
},
{
"code": null,
"e": 26457,
"s": 26382,
"text": "Return true if the condition is satisfied for all the cycles else print 0."
},
{
"code": null,
"e": 26510,
"s": 26457,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26514,
"s": 26510,
"text": "C++"
},
{
"code": null,
"e": 26519,
"s": 26514,
"text": "Java"
},
{
"code": null,
"e": 26527,
"s": 26519,
"text": "Python3"
},
{
"code": null,
"e": 26530,
"s": 26527,
"text": "C#"
},
{
"code": null,
"e": 26534,
"s": 26530,
"text": "PHP"
},
{
"code": null,
"e": 26545,
"s": 26534,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to match whether there are always n consecutive b's// followed by n consecutive a's throughout the stringint matchPattern(string s){ int count = 0; int n = s.length(); // Traverse through the string int i = 0; while (i < n) { // Count a's in current segment while (i < n && s[i] == 'a') { count++; i++; } // Count b's in current segment while (i < n && s[i] == 'b') { count--; i++; } // If both counts are not same. if (count != 0) return false; } return true;} // Driver codeint main(){ string s = \"bb\"; if (matchPattern(s) == true) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 27381,
"s": 26545,
"text": null
},
{
"code": "// Java implementation of the above approach public class GFG{ // Function to match whether there are always n consecutive b's// followed by n consecutive a's throughout the stringstatic boolean matchPattern(String s){ int count = 0; int n = s.length(); // Traverse through the string int i = 0; while (i < n) { // Count a's in current segment while (i < n && s.charAt(i) == 'a') { count++; i++; } // Count b's in current segment while (i < n && s.charAt(i) == 'b') { count--; i++; } // If both counts are not same. if (count != 0) return false; } return true;} // Driver codepublic static void main(String []args){ String s = \"bb\"; if (matchPattern(s) == true) System.out.println(\"Yes\"); else System.out.println(\"No\");} // This code is contributed by Ryuga}",
"e": 28300,
"s": 27381,
"text": null
},
{
"code": "# Python 3 implementation of the approach # Function to match whether there are# always n consecutive b's followed by# n consecutive a's throughout the stringdef matchPattern(s): count = 0; n = len(s); # Traverse through the string i = 0; while (i < n) : # Count a's in current segment while (i < n and s[i] == 'a'): count += 1 ; i =+ 1; # Count b's in current segment while (i < n and s[i] == 'b'): count -= 1 ; i += 1; # If both counts are not same. if (count != 0): return False; return True; # Driver codes = \"bb\";if (matchPattern(s) == True): print(\"Yes\");else: print(\"No\"); # This code is contributed# by Akanksha Rai",
"e": 29056,
"s": 28300,
"text": null
},
{
"code": "// C# implementation of the above approach using System;public class GFG{ // Function to match whether there are always n consecutive b's// followed by n consecutive a's throughout the stringstatic bool matchPattern(string s){ int count = 0; int n = s.Length; // Traverse through the string int i = 0; while (i < n) { // Count a's in current segment while (i < n && s[i] == 'a') { count++; i++; } // Count b's in current segment while (i < n && s[i] == 'b') { count--; i++; } // If both counts are not same. if (count != 0) return false; } return true;} // Driver codepublic static void Main(){ string s = \"bb\"; if (matchPattern(s) == true) Console.Write(\"Yes\"); else Console.Write(\"No\");} }",
"e": 29916,
"s": 29056,
"text": null
},
{
"code": "<?php//PHP implementation of the approach // Function to match whether there are always n consecutive b's// followed by n consecutive a's throughout the stringfunction matchPattern($s){ $count = 0; $n = strlen($s); // Traverse through the string $i = 0; while ($i < $n) { // Count a's in current segment while ($i < $n && $s[$i] == 'a') { $count++; $i++; } // Count b's in current segment while ($i < $n && $s[$i] == 'b') { $count--; $i++; } // If both counts are not same. if ($count != 0) return false; } return true;} // Driver code $s = \"bb\"; if (matchPattern($s) == true) echo \"Yes\"; else echo \"No\"; // This code is contributed by ajit?>",
"e": 30728,
"s": 29916,
"text": null
},
{
"code": "<script> // Javascript implementation of // the above approach // Function to match whether there are // always n consecutive b's // followed by n consecutive a's // throughout the string function matchPattern(s) { let count = 0; let n = s.length; // Traverse through the string let i = 0; while (i < n) { // Count a's in current segment while (i < n && s[i] == 'a') { count++; i++; } // Count b's in current segment while (i < n && s[i] == 'b') { count--; i++; } // If both counts are not same. if (count != 0) return false; } return true; } let s = \"bb\"; if (matchPattern(s) == true) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 31685,
"s": 30728,
"text": null
},
{
"code": null,
"e": 31688,
"s": 31685,
"text": "No"
},
{
"code": null,
"e": 31698,
"s": 31690,
"text": "ankthon"
},
{
"code": null,
"e": 31704,
"s": 31698,
"text": "ukasp"
},
{
"code": null,
"e": 31710,
"s": 31704,
"text": "jit_t"
},
{
"code": null,
"e": 31723,
"s": 31710,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31732,
"s": 31723,
"text": "mukesh07"
},
{
"code": null,
"e": 31757,
"s": 31732,
"text": "array-traversal-question"
},
{
"code": null,
"e": 31771,
"s": 31757,
"text": "binary-string"
},
{
"code": null,
"e": 31784,
"s": 31771,
"text": "C++ Programs"
},
{
"code": null,
"e": 31808,
"s": 31784,
"text": "Competitive Programming"
},
{
"code": null,
"e": 31816,
"s": 31808,
"text": "Strings"
},
{
"code": null,
"e": 31824,
"s": 31816,
"text": "Strings"
},
{
"code": null,
"e": 31922,
"s": 31824,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31963,
"s": 31922,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 32022,
"s": 31963,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 32043,
"s": 32022,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 32055,
"s": 32043,
"text": "cout in C++"
},
{
"code": null,
"e": 32076,
"s": 32055,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 32119,
"s": 32076,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 32162,
"s": 32119,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 32203,
"s": 32162,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 32281,
"s": 32203,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
turtle.dot() function in Python - GeeksforGeeks
|
21 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to draw a circular dot with a particular size, with some color. If the size is not given, the maximum of pensize+4 and 2*pensize is used.
Syntax :
turtle.dot(size=None, *color)
Parameters:
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # motionturtle.forward(100) # dot with# 60 diameter# yellow colorturtle.dot(60, color="yellow")
Output :
Example 2 :
Python3
# import packageimport turtle # delay the turtle work speed# for better understandingsturtle.delay(500) # hide the turtleturtle.ht() # some dots with diameter and colorturtle.dot(200, color="red")turtle.dot(180, color="orange")turtle.dot(160, color="yellow")turtle.dot(140, color="green")turtle.dot(120, color="blue")turtle.dot(100, color="indigo")turtle.dot(80, color="violet")turtle.dot(60, color="white") # write textturtle.write("GFG", align="center", font=('Verdana', 12, 'bold'))
Output :
Python-turtle
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n21 Jul, 2020"
},
{
"code": null,
"e": 25754,
"s": 25537,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 25914,
"s": 25754,
"text": "This function is used to draw a circular dot with a particular size, with some color. If the size is not given, the maximum of pensize+4 and 2*pensize is used."
},
{
"code": null,
"e": 25923,
"s": 25914,
"text": "Syntax :"
},
{
"code": null,
"e": 25954,
"s": 25923,
"text": "turtle.dot(size=None, *color)\n"
},
{
"code": null,
"e": 25966,
"s": 25954,
"text": "Parameters:"
},
{
"code": null,
"e": 26035,
"s": 25966,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 26047,
"s": 26035,
"text": "Example 1 :"
},
{
"code": null,
"e": 26055,
"s": 26047,
"text": "Python3"
},
{
"code": "# import packageimport turtle # motionturtle.forward(100) # dot with# 60 diameter# yellow colorturtle.dot(60, color=\"yellow\")",
"e": 26185,
"s": 26055,
"text": null
},
{
"code": null,
"e": 26194,
"s": 26185,
"text": "Output :"
},
{
"code": null,
"e": 26206,
"s": 26194,
"text": "Example 2 :"
},
{
"code": null,
"e": 26214,
"s": 26206,
"text": "Python3"
},
{
"code": "# import packageimport turtle # delay the turtle work speed# for better understandingsturtle.delay(500) # hide the turtleturtle.ht() # some dots with diameter and colorturtle.dot(200, color=\"red\")turtle.dot(180, color=\"orange\")turtle.dot(160, color=\"yellow\")turtle.dot(140, color=\"green\")turtle.dot(120, color=\"blue\")turtle.dot(100, color=\"indigo\")turtle.dot(80, color=\"violet\")turtle.dot(60, color=\"white\") # write textturtle.write(\"GFG\", align=\"center\", font=('Verdana', 12, 'bold'))",
"e": 26718,
"s": 26214,
"text": null
},
{
"code": null,
"e": 26727,
"s": 26718,
"text": "Output :"
},
{
"code": null,
"e": 26741,
"s": 26727,
"text": "Python-turtle"
},
{
"code": null,
"e": 26748,
"s": 26741,
"text": "Python"
},
{
"code": null,
"e": 26846,
"s": 26748,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26878,
"s": 26846,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26920,
"s": 26878,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26962,
"s": 26920,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27018,
"s": 26962,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27045,
"s": 27018,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27084,
"s": 27045,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27115,
"s": 27084,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27137,
"s": 27115,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27166,
"s": 27137,
"text": "Create a directory in Python"
}
] |
C++ Program for Leaders in an array - GeeksforGeeks
|
13 Dec, 2021
Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2. Let the input array be arr[] and size of the array be size.
Method 1 (Simple) Use two loops. The outer loop runs from 0 to size – 1 and one by one picks all elements from left to right. The inner loop compares the picked element to all the elements to its right side. If the picked element is greater than all the elements to its right side, then the picked element is the leader.
C++
#include<iostream>using namespace std; /*C++ Function to print leaders in an array */void printLeaders(int arr[], int size){ for (int i = 0; i < size; i++) { int j; for (j = i+1; j < size; j++) { if (arr[i] <=arr[j]) break; } if (j == size) // the loop didn't break cout << arr[i] << " "; }} /* Driver program to test above function */int main(){ int arr[] = {16, 17, 4, 3, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]); printLeaders(arr, n); return 0;}
Output:
17 5 2
Time Complexity: O(n*n)Method 2 (Scan from right) Scan all the elements from right to left in an array and keep track of maximum till now. When maximum changes its value, print it.Below image is a dry run of the above approach:
Below is the implementation of the above approach:
C++
#include <iostream>using namespace std; /* C++ Function to print leaders in an array */void printLeaders(int arr[], int size){ int max_from_right = arr[size-1]; /* Rightmost element is always leader */ cout << max_from_right << " "; for (int i = size-2; i >= 0; i--) { if (max_from_right < arr[i]) { max_from_right = arr[i]; cout << max_from_right << " "; } } } /* Driver program to test above function*/int main(){ int arr[] = {16, 17, 4, 3, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]); printLeaders(arr, n); return 0;}
Output:
2 5 17
Time Complexity: O(n)
Please refer complete article on Leaders in an array for more details!
Amazon
Payu
Arrays
C++
C++ Programs
Amazon
Payu
Arrays
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
std::sort() in C++ STL
|
[
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 26355,
"s": 26041,
"text": "Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2. Let the input array be arr[] and size of the array be size. "
},
{
"code": null,
"e": 26678,
"s": 26355,
"text": "Method 1 (Simple) Use two loops. The outer loop runs from 0 to size – 1 and one by one picks all elements from left to right. The inner loop compares the picked element to all the elements to its right side. If the picked element is greater than all the elements to its right side, then the picked element is the leader. "
},
{
"code": null,
"e": 26682,
"s": 26678,
"text": "C++"
},
{
"code": "#include<iostream>using namespace std; /*C++ Function to print leaders in an array */void printLeaders(int arr[], int size){ for (int i = 0; i < size; i++) { int j; for (j = i+1; j < size; j++) { if (arr[i] <=arr[j]) break; } if (j == size) // the loop didn't break cout << arr[i] << \" \"; }} /* Driver program to test above function */int main(){ int arr[] = {16, 17, 4, 3, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]); printLeaders(arr, n); return 0;}",
"e": 27229,
"s": 26682,
"text": null
},
{
"code": null,
"e": 27238,
"s": 27229,
"text": "Output: "
},
{
"code": null,
"e": 27245,
"s": 27238,
"text": "17 5 2"
},
{
"code": null,
"e": 27474,
"s": 27245,
"text": "Time Complexity: O(n*n)Method 2 (Scan from right) Scan all the elements from right to left in an array and keep track of maximum till now. When maximum changes its value, print it.Below image is a dry run of the above approach: "
},
{
"code": null,
"e": 27526,
"s": 27474,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27530,
"s": 27526,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; /* C++ Function to print leaders in an array */void printLeaders(int arr[], int size){ int max_from_right = arr[size-1]; /* Rightmost element is always leader */ cout << max_from_right << \" \"; for (int i = size-2; i >= 0; i--) { if (max_from_right < arr[i]) { max_from_right = arr[i]; cout << max_from_right << \" \"; } } } /* Driver program to test above function*/int main(){ int arr[] = {16, 17, 4, 3, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]); printLeaders(arr, n); return 0;} ",
"e": 28152,
"s": 27530,
"text": null
},
{
"code": null,
"e": 28160,
"s": 28152,
"text": "Output:"
},
{
"code": null,
"e": 28167,
"s": 28160,
"text": "2 5 17"
},
{
"code": null,
"e": 28190,
"s": 28167,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 28261,
"s": 28190,
"text": "Please refer complete article on Leaders in an array for more details!"
},
{
"code": null,
"e": 28268,
"s": 28261,
"text": "Amazon"
},
{
"code": null,
"e": 28273,
"s": 28268,
"text": "Payu"
},
{
"code": null,
"e": 28280,
"s": 28273,
"text": "Arrays"
},
{
"code": null,
"e": 28284,
"s": 28280,
"text": "C++"
},
{
"code": null,
"e": 28297,
"s": 28284,
"text": "C++ Programs"
},
{
"code": null,
"e": 28304,
"s": 28297,
"text": "Amazon"
},
{
"code": null,
"e": 28309,
"s": 28304,
"text": "Payu"
},
{
"code": null,
"e": 28316,
"s": 28309,
"text": "Arrays"
},
{
"code": null,
"e": 28320,
"s": 28316,
"text": "CPP"
},
{
"code": null,
"e": 28418,
"s": 28320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28445,
"s": 28418,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 28476,
"s": 28445,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 28501,
"s": 28476,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 28539,
"s": 28501,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 28560,
"s": 28539,
"text": "Next Greater Element"
},
{
"code": null,
"e": 28578,
"s": 28560,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 28624,
"s": 28578,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 28643,
"s": 28624,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28686,
"s": 28643,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
Wand flip() function - Python - GeeksforGeeks
|
19 May, 2021
The flip() function is an inbuilt function in the Python Wand ImageMagick library which is used to create a vertical mirror image by reflecting the pixels around the central x-axis.
Syntax:
flip()
Parameters: This function does not accept any parameters.Return Value: This function returns the Wand ImageMagick object.
Original Image:
Example 1:
Python3
# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as flip: # Invoke flip function flip.flip() # Save the image flip.save(filename ='flip1.jpg')
Output:
Example 2:
Python3
# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke flip() function pic.flip() # Save the image pic.save(filename ='flip2.jpg')
Output:
sweetyty
Image-Processing
Python-wand
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 25719,
"s": 25537,
"text": "The flip() function is an inbuilt function in the Python Wand ImageMagick library which is used to create a vertical mirror image by reflecting the pixels around the central x-axis."
},
{
"code": null,
"e": 25728,
"s": 25719,
"text": "Syntax: "
},
{
"code": null,
"e": 25735,
"s": 25728,
"text": "flip()"
},
{
"code": null,
"e": 25857,
"s": 25735,
"text": "Parameters: This function does not accept any parameters.Return Value: This function returns the Wand ImageMagick object."
},
{
"code": null,
"e": 25874,
"s": 25857,
"text": "Original Image: "
},
{
"code": null,
"e": 25886,
"s": 25874,
"text": "Example 1: "
},
{
"code": null,
"e": 25894,
"s": 25886,
"text": "Python3"
},
{
"code": "# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as flip: # Invoke flip function flip.flip() # Save the image flip.save(filename ='flip1.jpg')",
"e": 26208,
"s": 25894,
"text": null
},
{
"code": null,
"e": 26217,
"s": 26208,
"text": "Output: "
},
{
"code": null,
"e": 26229,
"s": 26217,
"text": "Example 2: "
},
{
"code": null,
"e": 26237,
"s": 26229,
"text": "Python3"
},
{
"code": "# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke flip() function pic.flip() # Save the image pic.save(filename ='flip2.jpg')",
"e": 27218,
"s": 26237,
"text": null
},
{
"code": null,
"e": 27227,
"s": 27218,
"text": "Output: "
},
{
"code": null,
"e": 27238,
"s": 27229,
"text": "sweetyty"
},
{
"code": null,
"e": 27255,
"s": 27238,
"text": "Image-Processing"
},
{
"code": null,
"e": 27267,
"s": 27255,
"text": "Python-wand"
},
{
"code": null,
"e": 27274,
"s": 27267,
"text": "Python"
},
{
"code": null,
"e": 27372,
"s": 27274,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27404,
"s": 27372,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27446,
"s": 27404,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27488,
"s": 27446,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27544,
"s": 27488,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27571,
"s": 27544,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27610,
"s": 27571,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27641,
"s": 27610,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27663,
"s": 27641,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27692,
"s": 27663,
"text": "Create a directory in Python"
}
] |
How to display images using handlebars in Node.js ?
|
09 Apr, 2021
In this article, we will discuss how to display images using handlebars in Node.js. You may refer to this article for setting up handlebars View Engine in Node.js.
We will use the following steps to achieve our target:
Install express and express-handlebarsSet up our express serverCreate a basic Handlebars’ folder structureDefine proper routes
Install express and express-handlebars
Set up our express server
Create a basic Handlebars’ folder structure
Define proper routes
Install express and express-handlebars:
npm install --save express express-handlebars
Setting up express server:
Javascript
//importing modulesimport express from "express"import path from "path"import exphbs from "express-handlebars" // Express server's instanceconst app = express(); const PORT = process.env.PORT || 3000; // listeningapp.listen(PORT, () => console.log(`Server started running on PORT ${PORT}`));
Create basic folder structure as follows:
Folder Structure
Change the default view engine to handlebars: To serve static files like images from a directory named “images”
app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");
app.use(express.static("images"));
With the above line we are telling our Node.js app where our images will be stored. We will not have to specify a messy path to our image in our <img> tag.
Define routes and render views accordingly:
Javascript
// Route to display static src imagesapp.get("/static", (req, res) => { res.render("static");}); // Route to display dynamic src imagesapp.get("/dynamic", (req, res) => { imageList = []; imageList.push({ src: "icons/flask.png", name: "flask" }); imageList.push({ src: "icons/javascript.png", name: "javascript" }); imageList.push({ src: "icons/react.png", name: "react" }); res.render("dynamic", { imageList: imageList });});
Handlebar templates: Now let us create a static.handlebars file in our views directory with the following content:
HTML
<!DOCTYPE html><html lang="en"> <head> <title>Handlebars Images Demo</title> </head> <body> <h1>Display Static Images Using Handlebars In NodeJS</h1> <br> <img src="images/gfg.png" alt="" style="border: 5px inset black;"> </body><html>
index.js
//importing modulesimport express from "express"import path from "path"import exphbs from "express-handlebars" // Express server's instanceconst app = express(); const PORT = process.env.PORT || 3000; app.engine("handlebars", exphbs({ defaultLayout: "main" }));app.set("view engine", "handlebars"); app.use(express.static("images")); // Route to display static src imagesapp.get("/static", (req, res) => { res.render("static");}); // Route to display dynamic src imagesapp.get("/dynamic", (req, res) => { imageList = []; imageList.push({ src: "icons/flask.png", name: "flask" }); imageList.push({ src: "icons/javascript.png", name: "javascript" }); imageList.push({ src: "icons/react.png", name: "react" }); res.render("dynamic", { imageList: imageList });}) // Listeningapp.listen(PORT, () => console.log(`Server started running on PORT ${PORT}`));
node index.js
Output: Now, go to localhost:3000/static which will render GFG logo on the webpage.
Static img src display
Now let us create a dynamic.handlebars file in our views directory with the following content:
Javascript
<!DOCTYPE html><html lang="en"> <head> <title>Handlebars Images Demo</title> </head> <body> <h1>Display Dynamic Images Using Handlebars In NodeJS</h1> <br> <div class="row"> {{#each imageList}} <div class="col-md-4"> <div class="text-success" style="font-size: large; font-weight: 700;">{{this.name}}</div> <img src="{{this.src}}"> </div> {{/each}} </div> </body><html>
Output: Now, go to localhost:3000/dynamic which will render some icons on the webpage. (The urls of these images are passed from server side).
Dynamic img src display
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Apr, 2021"
},
{
"code": null,
"e": 193,
"s": 28,
"text": "In this article, we will discuss how to display images using handlebars in Node.js. You may refer to this article for setting up handlebars View Engine in Node.js. "
},
{
"code": null,
"e": 248,
"s": 193,
"text": "We will use the following steps to achieve our target:"
},
{
"code": null,
"e": 375,
"s": 248,
"text": "Install express and express-handlebarsSet up our express serverCreate a basic Handlebars’ folder structureDefine proper routes"
},
{
"code": null,
"e": 414,
"s": 375,
"text": "Install express and express-handlebars"
},
{
"code": null,
"e": 440,
"s": 414,
"text": "Set up our express server"
},
{
"code": null,
"e": 484,
"s": 440,
"text": "Create a basic Handlebars’ folder structure"
},
{
"code": null,
"e": 505,
"s": 484,
"text": "Define proper routes"
},
{
"code": null,
"e": 545,
"s": 505,
"text": "Install express and express-handlebars:"
},
{
"code": null,
"e": 591,
"s": 545,
"text": "npm install --save express express-handlebars"
},
{
"code": null,
"e": 618,
"s": 591,
"text": "Setting up express server:"
},
{
"code": null,
"e": 629,
"s": 618,
"text": "Javascript"
},
{
"code": "//importing modulesimport express from \"express\"import path from \"path\"import exphbs from \"express-handlebars\" // Express server's instanceconst app = express(); const PORT = process.env.PORT || 3000; // listeningapp.listen(PORT, () => console.log(`Server started running on PORT ${PORT}`));",
"e": 924,
"s": 629,
"text": null
},
{
"code": null,
"e": 966,
"s": 924,
"text": "Create basic folder structure as follows:"
},
{
"code": null,
"e": 983,
"s": 966,
"text": "Folder Structure"
},
{
"code": null,
"e": 1095,
"s": 983,
"text": "Change the default view engine to handlebars: To serve static files like images from a directory named “images”"
},
{
"code": null,
"e": 1229,
"s": 1095,
"text": "app.engine(\"handlebars\", exphbs({ defaultLayout: \"main\" }));\napp.set(\"view engine\", \"handlebars\");\napp.use(express.static(\"images\"));"
},
{
"code": null,
"e": 1385,
"s": 1229,
"text": "With the above line we are telling our Node.js app where our images will be stored. We will not have to specify a messy path to our image in our <img> tag."
},
{
"code": null,
"e": 1429,
"s": 1385,
"text": "Define routes and render views accordingly:"
},
{
"code": null,
"e": 1440,
"s": 1429,
"text": "Javascript"
},
{
"code": "// Route to display static src imagesapp.get(\"/static\", (req, res) => { res.render(\"static\");}); // Route to display dynamic src imagesapp.get(\"/dynamic\", (req, res) => { imageList = []; imageList.push({ src: \"icons/flask.png\", name: \"flask\" }); imageList.push({ src: \"icons/javascript.png\", name: \"javascript\" }); imageList.push({ src: \"icons/react.png\", name: \"react\" }); res.render(\"dynamic\", { imageList: imageList });});",
"e": 1885,
"s": 1440,
"text": null
},
{
"code": null,
"e": 2000,
"s": 1885,
"text": "Handlebar templates: Now let us create a static.handlebars file in our views directory with the following content:"
},
{
"code": null,
"e": 2005,
"s": 2000,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Handlebars Images Demo</title> </head> <body> <h1>Display Static Images Using Handlebars In NodeJS</h1> <br> <img src=\"images/gfg.png\" alt=\"\" style=\"border: 5px inset black;\"> </body><html>",
"e": 2261,
"s": 2005,
"text": null
},
{
"code": null,
"e": 2270,
"s": 2261,
"text": "index.js"
},
{
"code": "//importing modulesimport express from \"express\"import path from \"path\"import exphbs from \"express-handlebars\" // Express server's instanceconst app = express(); const PORT = process.env.PORT || 3000; app.engine(\"handlebars\", exphbs({ defaultLayout: \"main\" }));app.set(\"view engine\", \"handlebars\"); app.use(express.static(\"images\")); // Route to display static src imagesapp.get(\"/static\", (req, res) => { res.render(\"static\");}); // Route to display dynamic src imagesapp.get(\"/dynamic\", (req, res) => { imageList = []; imageList.push({ src: \"icons/flask.png\", name: \"flask\" }); imageList.push({ src: \"icons/javascript.png\", name: \"javascript\" }); imageList.push({ src: \"icons/react.png\", name: \"react\" }); res.render(\"dynamic\", { imageList: imageList });}) // Listeningapp.listen(PORT, () => console.log(`Server started running on PORT ${PORT}`));",
"e": 3145,
"s": 2270,
"text": null
},
{
"code": null,
"e": 3159,
"s": 3145,
"text": "node index.js"
},
{
"code": null,
"e": 3243,
"s": 3159,
"text": "Output: Now, go to localhost:3000/static which will render GFG logo on the webpage."
},
{
"code": null,
"e": 3267,
"s": 3243,
"text": "Static img src display"
},
{
"code": null,
"e": 3362,
"s": 3267,
"text": "Now let us create a dynamic.handlebars file in our views directory with the following content:"
},
{
"code": null,
"e": 3373,
"s": 3362,
"text": "Javascript"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Handlebars Images Demo</title> </head> <body> <h1>Display Dynamic Images Using Handlebars In NodeJS</h1> <br> <div class=\"row\"> {{#each imageList}} <div class=\"col-md-4\"> <div class=\"text-success\" style=\"font-size: large; font-weight: 700;\">{{this.name}}</div> <img src=\"{{this.src}}\"> </div> {{/each}} </div> </body><html>",
"e": 3792,
"s": 3373,
"text": null
},
{
"code": null,
"e": 3935,
"s": 3792,
"text": "Output: Now, go to localhost:3000/dynamic which will render some icons on the webpage. (The urls of these images are passed from server side)."
},
{
"code": null,
"e": 3960,
"s": 3935,
"text": "Dynamic img src display"
},
{
"code": null,
"e": 3971,
"s": 3960,
"text": "Express.js"
},
{
"code": null,
"e": 3988,
"s": 3971,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 3995,
"s": 3988,
"text": "Picked"
},
{
"code": null,
"e": 4003,
"s": 3995,
"text": "Node.js"
},
{
"code": null,
"e": 4020,
"s": 4003,
"text": "Web Technologies"
}
] |
Bubble Sort Algorithm
|
14 Jul, 2022
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.
Consider an array arr[] = {5, 1, 4, 2, 8}
First Pass:
Bubble sort starts with very first two elements, comparing them to check which one is greater.
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
Now, during second iteration it should look like this:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Third Pass:
Now, the array is already sorted, but our algorithm does not know if it is completed.
The algorithm needs one whole pass without any swap to know it is sorted.
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Illustration:
Following are the implementations of Bubble Sort.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program for implementation
// of Bubble sort
#include <bits/stdc++.h>
using namespace std;
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
// Last i elements are already
// in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
// Function to print an array
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int arr[] = { 5, 1, 4, 2, 8};
int N = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, N);
cout << "Sorted array: \n";
printArray(arr, N);
return 0;
}
// This code is contributed by rathbhupendra
// C program for implementation of Bubble sort
#include <stdio.h>
void swap(int* xp, int* yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
// Last i elements are already in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]);
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver program to test above functions
int main()
{
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
// Java program for implementation of Bubble Sort
class BubbleSort {
void bubbleSort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
// swap arr[j+1] and arr[j]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
/* Prints the array */
void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method to test above
public static void main(String args[])
{
BubbleSort ob = new BubbleSort();
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
ob.bubbleSort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}
/* This code is contributed by Rajat Mishra */
# Python program for implementation of Bubble Sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print("Sorted array is:")
for i in range(len(arr)):
print("%d" % arr[i], end=" ")
// C# program for implementation
// of Bubble Sort
using System;
class GFG {
static void bubbleSort(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
/* Prints the array */
static void printArray(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n; ++i)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// Driver method
public static void Main()
{
int[] arr = { 64, 34, 25, 12, 22, 11, 90 };
bubbleSort(arr);
Console.WriteLine("Sorted array");
printArray(arr);
}
}
// This code is contributed by Sam007
<?php
// PHP program for implementation
// of Bubble Sort
function bubbleSort(&$arr)
{
$n = sizeof($arr);
// Traverse through all array elements
for($i = 0; $i < $n; $i++)
{
// Last i elements are already in place
for ($j = 0; $j < $n - $i - 1; $j++)
{
// traverse the array from 0 to n-i-1
// Swap if the element found is greater
// than the next element
if ($arr[$j] > $arr[$j+1])
{
$t = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $t;
}
}
}
}
// Driver code to test above
$arr = array(64, 34, 25, 12, 22, 11, 90);
$len = sizeof($arr);
bubbleSort($arr);
echo "Sorted array : \n";
for ($i = 0; $i < $len; $i++)
echo $arr[$i]." ";
// This code is contributed by ChitraNayal.
?>
<script>
function swap(arr, xp, yp)
{
var temp = arr[xp];
arr[xp] = arr[yp];
arr[yp] = temp;
}
// An optimized version of Bubble Sort
function bubbleSort( arr, n)
{
var i, j;
for (i = 0; i < n-1; i++)
{
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr,j,j+1);
}
}
}
}
/* Function to print an array */
function printArray(arr, size)
{
var i;
for (i=0; i < size; i++)
document.write(arr[i]+ " ");
document.write("\n");
}
// Driver program to test above functions
var arr = [64, 34, 25, 12, 22, 11, 90];
var n = 7;
document.write("UnSorted array: \n");
printArray(arr, n);
bubbleSort(arr, n);
document.write("Sorted array: \n");
printArray(arr, n);
</script>
Sorted array:
1 2 4 5 8
The above function always runs O(n^2) time even if the array is sorted.
It can be optimized by stopping the algorithm if the inner loop didn’t cause any swap.
Below is the implementation for the above approach:
C++
C
Java
Python3
C#
PHP
Javascript
// Optimized implementation of Bubble sort
#include <bits/stdc++.h>
using namespace std;
// An optimized version of Bubble Sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n-1; i++)
{
swapped = false;
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped
// by inner loop, then break
if (swapped == false)
break;
}
}
// Function to print an array
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout <<" "<< arr[i];
}
// Driver program to test above functions
int main()
{
int arr[] = {5, 3, 1, 9, 8, 2, 4, 7};
int N = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, N);
cout <<"Sorted array: \n";
printArray(arr, N);
return 0;
}
// This code is contributed by shivanisinghss2110
// Optimized implementation of Bubble sort
#include <stdio.h>
#include <stdbool.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// An optimized version of Bubble Sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n-1; i++)
{
swapped = false;
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(&arr[j], &arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
// Optimized java implementation
// of Bubble sort
import java.io.*;
class GFG
{
// An optimized version of Bubble Sort
static void bubbleSort(int arr[], int n)
{
int i, j, temp;
boolean swapped;
for (i = 0; i < n - 1; i++)
{
swapped = false;
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// IF no two elements were
// swapped by inner loop, then break
if (swapped == false)
break;
}
}
// Function to print an array
static void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver program
public static void main(String args[])
{
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
int n = arr.length;
bubbleSort(arr, n);
System.out.println("Sorted array: ");
printArray(arr, n);
}
}
// This code is contributed
// by Nikita Tiwari.
# Python3 Optimized implementation
# of Bubble sort
# An optimized version of Bubble Sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
swapped = False
# Last i elements are already
# in place
for j in range(0, n-i-1):
# traverse the array from 0 to
# n-i-1. Swap if the element
# found is greater than the
# next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
# IF no two elements were swapped
# by inner loop, then break
if swapped == False:
break
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array :")
for i in range(len(arr)):
print ("%d" %arr[i],end=" ")
# This code is contributed by Shreyanshi Arun
// Optimized C# implementation
// of Bubble sort
using System;
class GFG
{
// An optimized version of Bubble Sort
static void bubbleSort(int []arr, int n)
{
int i, j, temp;
bool swapped;
for (i = 0; i < n - 1; i++)
{
swapped = false;
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// IF no two elements were
// swapped by inner loop, then break
if (swapped == false)
break;
}
}
// Function to print an array
static void printArray(int []arr, int size)
{
int i;
for (i = 0; i < size; i++)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// Driver method
public static void Main()
{
int []arr = {64, 34, 25, 12, 22, 11, 90};
int n = arr.Length;
bubbleSort(arr,n);
Console.WriteLine("Sorted array");
printArray(arr,n);
}
}
// This code is contributed by Sam007
<?php
// PHP Optimized implementation
// of Bubble sort
// An optimized version of Bubble Sort
function bubbleSort(&$arr)
{
$n = sizeof($arr);
// Traverse through all array elements
for($i = 0; $i < $n; $i++)
{
$swapped = False;
// Last i elements are already
// in place
for ($j = 0; $j < $n - $i - 1; $j++)
{
// traverse the array from 0 to
// n-i-1. Swap if the element
// found is greater than the
// next element
if ($arr[$j] > $arr[$j+1])
{
$t = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $t;
$swapped = True;
}
}
// IF no two elements were swapped
// by inner loop, then break
if ($swapped == False)
break;
}
}
// Driver code to test above
$arr = array(64, 34, 25, 12, 22, 11, 90);
$len = sizeof($arr);
bubbleSort($arr);
echo "Sorted array : \n";
for($i = 0; $i < $len; $i++)
echo $arr[$i]." ";
// This code is contributed by ChitraNayal.
?>
<script>
// Optimized javaScript implementation
// of Bubble sort
// An optimized version of Bubble Sort
function bubbleSort(arr, n)
{
var i, j, temp;
var swapped;
for (i = 0; i < n - 1; i++)
{
swapped = false;
for (j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// IF no two elements were
// swapped by inner loop, then break
if (swapped == false)
break;
}
}
// Function to print an array
function printArray(arr, size)
{
var i;
for (i = 0; i < size; i++)
document.write(arr[i] + " ");
document.writeln();
}
// Driver program
var arr = [ 64, 34, 25, 12, 22, 11, 90 ];
var n = arr.length;
bubbleSort(arr, n);
document.write("Sorted array: ");
printArray(arr, n);
// This code is contributed shivanisinghss2110
</script>
Sorted array:
1 2 3 4 5 7 8 9
Time Complexity: O(N2)Auxiliary Space: O(1)
The worst-case condition for bubble sort occurs when elements of the array are arranged in decreasing order.In the worst case, the total number of iterations or passes required to sort a given array is (n-1). where ‘n’ is a number of elements present in the array.
At pass 1 : Number of comparisons = (n-1) Number of swaps = (n-1)
At pass 2 : Number of comparisons = (n-2) Number of swaps = (n-2)
At pass 3 : Number of comparisons = (n-3) Number of swaps = (n-3) . . . At pass n-1 : Number of comparisons = 1 Number of swaps = 1
Now , calculating total number of comparison required to sort the array= (n-1) + (n-2) + (n-3) + . . . 2 + 1= (n-1)*(n-1+1)/2 { by using sum of N natural Number formula }= n (n-1)/2
For the Worst case:
Total number of swaps = Total number of comparisonTotal number of comparison (Worst case) = n(n-1)/2Total number of swaps (Worst case) = n(n-1)/2
Worst and Average Case Time Complexity: O(N2). The worst case occurs when an array is reverse sorted.Best Case Time Complexity: O(N). The best case occurs when an array is already sorted.Auxiliary Space: O(1)
The idea is to place the largest element at their position and keep doing the same for every other elements.
Approach:
Place the largest element at their position, this operation makes sure that first largest element will be placed at the end of array.
Recursively call for rest n – 1 elements with same operation and placing the next greater element at their position.
Base condition for this recursion call would be, when number of elements in the array becomes 0 or 1 then, simply return (as they are already sorted).
Below is the implementation of the above approach:
C++
//C++ code for recursive bubble sort algorithm
#include <iostream>
using namespace std;
void bubblesort(int arr[], int n)
{
if (n == 0 || n == 1)
{
return;
}
for (int i = 0; i < n - 1; i++)
{
if (arr[i] > arr[i + 1])
{
swap(arr[i], arr[i + 1]);
}
}
bubblesort(arr, n - 1);
}
int main()
{
int arr[5] = {2, 5, 1, 6, 9};
bubblesort(arr, 5);
for (int i = 0; i < 5; i++)
{
cout << arr[i] << " ";
}
return 0;
}
//code contributed by pragatikohli
1 2 5 6 9
Bubble sort takes minimum time (Order of n) when elements are already sorted. Hence it is best to check if the array is already sorted or not beforehand, to avoid O(N2) time complexity.
Yes, Bubble sort performs swapping of adjacent pairs without the use of any major data structure. Hence Bubble sort algorithm is an in-place algorithm.
Yes, the bubble sort algorithm is stable.
Due to its simplicity, bubble sort is often used to introduce the concept of a sorting algorithm. In computer graphics, it is popular for its capability to detect a tiny error (like a swap of just two elements) in almost-sorted arrays and fix it with just linear complexity (2n).
For example, it is used in a polygon filling algorithm, where bounding lines are sorted by their x coordinate at a specific scan line (a line parallel to the x-axis), and with incrementing y their order changes (two elements are swapped) only at intersections of two lines (Source: Wikipedia) Bubble Sort | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersBubble Sort | GeeksforGeeksWatch laterShareCopy link6/21InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=nmhjrI-aW5o" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Snapshots: Quiz on Bubble Sort
Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz: Recursive Bubble SortCoding practice for sorting.
ukasp
SumitBM
rathbhupendra
TanishJain1
adityakangs
akshitsaxenaa09
shivanisinghss2110
amartyaghoshgfg
pathakanurag605
vaishalishrivastava21
kashishkumar2
animeshdey
pragatikohli12
redBus
Sorting
redBus
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 57,
"s": 26,
"text": " \n14 Jul, 2022\n"
},
{
"code": null,
"e": 303,
"s": 57,
"text": "Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high."
},
{
"code": null,
"e": 345,
"s": 303,
"text": "Consider an array arr[] = {5, 1, 4, 2, 8}"
},
{
"code": null,
"e": 358,
"s": 345,
"text": "First Pass: "
},
{
"code": null,
"e": 781,
"s": 358,
"text": "Bubble sort starts with very first two elements, comparing them to check which one is greater.\n\n( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. \n( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4 \n( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2 \n( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.\n\n"
},
{
"code": null,
"e": 886,
"s": 781,
"text": "( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. "
},
{
"code": null,
"e": 937,
"s": 886,
"text": "( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4 "
},
{
"code": null,
"e": 988,
"s": 937,
"text": "( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2 "
},
{
"code": null,
"e": 1106,
"s": 988,
"text": "( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them."
},
{
"code": null,
"e": 1120,
"s": 1106,
"text": "Second Pass: "
},
{
"code": null,
"e": 1325,
"s": 1120,
"text": "Now, during second iteration it should look like this:\n\n( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) \n( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 \n( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) \n( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) \n\n"
},
{
"code": null,
"e": 1357,
"s": 1325,
"text": "( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) "
},
{
"code": null,
"e": 1407,
"s": 1357,
"text": "( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 "
},
{
"code": null,
"e": 1439,
"s": 1407,
"text": "( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) "
},
{
"code": null,
"e": 1472,
"s": 1439,
"text": "( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) "
},
{
"code": null,
"e": 1485,
"s": 1472,
"text": "Third Pass: "
},
{
"code": null,
"e": 1571,
"s": 1485,
"text": "Now, the array is already sorted, but our algorithm does not know if it is completed."
},
{
"code": null,
"e": 1776,
"s": 1571,
"text": "The algorithm needs one whole pass without any swap to know it is sorted.\n\n( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) \n( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) \n( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) \n( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) \n\n"
},
{
"code": null,
"e": 1808,
"s": 1776,
"text": "( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) "
},
{
"code": null,
"e": 1840,
"s": 1808,
"text": "( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) "
},
{
"code": null,
"e": 1872,
"s": 1840,
"text": "( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) "
},
{
"code": null,
"e": 1904,
"s": 1872,
"text": "( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) "
},
{
"code": null,
"e": 1918,
"s": 1904,
"text": "Illustration:"
},
{
"code": null,
"e": 1969,
"s": 1918,
"text": "Following are the implementations of Bubble Sort. "
},
{
"code": null,
"e": 1973,
"s": 1969,
"text": "C++"
},
{
"code": null,
"e": 1975,
"s": 1973,
"text": "C"
},
{
"code": null,
"e": 1980,
"s": 1975,
"text": "Java"
},
{
"code": null,
"e": 1988,
"s": 1980,
"text": "Python3"
},
{
"code": null,
"e": 1991,
"s": 1988,
"text": "C#"
},
{
"code": null,
"e": 1995,
"s": 1991,
"text": "PHP"
},
{
"code": null,
"e": 2006,
"s": 1995,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// C++ program for implementation \n// of Bubble sort \n#include <bits/stdc++.h> \nusing namespace std; \n \n// A function to implement bubble sort \nvoid bubbleSort(int arr[], int n) \n{ \n int i, j; \n for (i = 0; i < n - 1; i++) \n \n // Last i elements are already \n // in place \n for (j = 0; j < n - i - 1; j++) \n if (arr[j] > arr[j + 1]) \n swap(arr[j], arr[j + 1]); \n} \n \n// Function to print an array \nvoid printArray(int arr[], int size) \n{ \n int i; \n for (i = 0; i < size; i++) \n cout << arr[i] << \" \"; \n cout << endl; \n} \n \n// Driver code \nint main() \n{ \n int arr[] = { 5, 1, 4, 2, 8}; \n int N = sizeof(arr) / sizeof(arr[0]); \n bubbleSort(arr, N); \n cout << \"Sorted array: \\n\"; \n printArray(arr, N); \n return 0; \n} \n// This code is contributed by rathbhupendra\n\n\n\n\n\n",
"e": 2883,
"s": 2016,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C program for implementation of Bubble sort \n#include <stdio.h> \n \nvoid swap(int* xp, int* yp) \n{ \n int temp = *xp; \n *xp = *yp; \n *yp = temp; \n} \n \n// A function to implement bubble sort \nvoid bubbleSort(int arr[], int n) \n{ \n int i, j; \n for (i = 0; i < n - 1; i++) \n \n // Last i elements are already in place \n for (j = 0; j < n - i - 1; j++) \n if (arr[j] > arr[j + 1]) \n swap(&arr[j], &arr[j + 1]); \n} \n \n/* Function to print an array */\nvoid printArray(int arr[], int size) \n{ \n int i; \n for (i = 0; i < size; i++) \n printf(\"%d \", arr[i]); \n printf(\"\\n\"); \n} \n \n// Driver program to test above functions \nint main() \n{ \n int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; \n int n = sizeof(arr) / sizeof(arr[0]); \n bubbleSort(arr, n); \n printf(\"Sorted array: \\n\"); \n printArray(arr, n); \n return 0; \n}\n\n\n\n\n\n",
"e": 3802,
"s": 2893,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Java program for implementation of Bubble Sort \nclass BubbleSort { \n void bubbleSort(int arr[]) \n { \n int n = arr.length; \n for (int i = 0; i < n - 1; i++) \n for (int j = 0; j < n - i - 1; j++) \n if (arr[j] > arr[j + 1]) { \n // swap arr[j+1] and arr[j] \n int temp = arr[j]; \n arr[j] = arr[j + 1]; \n arr[j + 1] = temp; \n } \n } \n \n /* Prints the array */\n void printArray(int arr[]) \n { \n int n = arr.length; \n for (int i = 0; i < n; ++i) \n System.out.print(arr[i] + \" \"); \n System.out.println(); \n } \n \n // Driver method to test above \n public static void main(String args[]) \n { \n BubbleSort ob = new BubbleSort(); \n int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; \n ob.bubbleSort(arr); \n System.out.println(\"Sorted array\"); \n ob.printArray(arr); \n } \n} \n/* This code is contributed by Rajat Mishra */\n\n\n\n\n\n",
"e": 4859,
"s": 3812,
"text": null
},
{
"code": "\n\n\n\n\n\n\n# Python program for implementation of Bubble Sort \n \n \ndef bubbleSort(arr): \n n = len(arr) \n \n # Traverse through all array elements \n for i in range(n): \n \n # Last i elements are already in place \n for j in range(0, n-i-1): \n \n # traverse the array from 0 to n-i-1 \n # Swap if the element found is greater \n # than the next element \n if arr[j] > arr[j+1]: \n arr[j], arr[j+1] = arr[j+1], arr[j] \n \n \n# Driver code to test above \narr = [64, 34, 25, 12, 22, 11, 90] \n \nbubbleSort(arr) \n \nprint(\"Sorted array is:\") \nfor i in range(len(arr)): \n print(\"%d\" % arr[i], end=\" \") \n\n\n\n\n\n",
"e": 5549,
"s": 4869,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// C# program for implementation \n// of Bubble Sort \nusing System; \n \nclass GFG { \n static void bubbleSort(int[] arr) \n { \n int n = arr.Length; \n for (int i = 0; i < n - 1; i++) \n for (int j = 0; j < n - i - 1; j++) \n if (arr[j] > arr[j + 1]) { \n // swap temp and arr[i] \n int temp = arr[j]; \n arr[j] = arr[j + 1]; \n arr[j + 1] = temp; \n } \n } \n \n /* Prints the array */\n static void printArray(int[] arr) \n { \n int n = arr.Length; \n for (int i = 0; i < n; ++i) \n Console.Write(arr[i] + \" \"); \n Console.WriteLine(); \n } \n \n // Driver method \n public static void Main() \n { \n int[] arr = { 64, 34, 25, 12, 22, 11, 90 }; \n bubbleSort(arr); \n Console.WriteLine(\"Sorted array\"); \n printArray(arr); \n } \n} \n \n// This code is contributed by Sam007\n\n\n\n\n\n",
"e": 6542,
"s": 5559,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<?php \n// PHP program for implementation \n// of Bubble Sort \n \nfunction bubbleSort(&$arr) \n{ \n $n = sizeof($arr); \n \n // Traverse through all array elements \n for($i = 0; $i < $n; $i++) \n { \n // Last i elements are already in place \n for ($j = 0; $j < $n - $i - 1; $j++) \n { \n // traverse the array from 0 to n-i-1 \n // Swap if the element found is greater \n // than the next element \n if ($arr[$j] > $arr[$j+1]) \n { \n $t = $arr[$j]; \n $arr[$j] = $arr[$j+1]; \n $arr[$j+1] = $t; \n } \n } \n } \n} \n \n// Driver code to test above \n$arr = array(64, 34, 25, 12, 22, 11, 90); \n \n$len = sizeof($arr); \nbubbleSort($arr); \n \necho \"Sorted array : \\n\"; \n \nfor ($i = 0; $i < $len; $i++) \n echo $arr[$i].\" \"; \n \n// This code is contributed by ChitraNayal. \n?>\n\n\n\n\n\n",
"e": 7479,
"s": 6552,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<script> \n \nfunction swap(arr, xp, yp) \n{ \n var temp = arr[xp]; \n arr[xp] = arr[yp]; \n arr[yp] = temp; \n} \n \n// An optimized version of Bubble Sort \nfunction bubbleSort( arr, n) \n{ \nvar i, j; \nfor (i = 0; i < n-1; i++) \n{ \n for (j = 0; j < n-i-1; j++) \n { \n if (arr[j] > arr[j+1]) \n { \n swap(arr,j,j+1); \n \n } \n } \n \n} \n} \n \n/* Function to print an array */\nfunction printArray(arr, size) \n{ \n var i; \n for (i=0; i < size; i++) \n document.write(arr[i]+ \" \"); \n document.write(\"\\n\"); \n} \n \n// Driver program to test above functions \n var arr = [64, 34, 25, 12, 22, 11, 90]; \n var n = 7; \n document.write(\"UnSorted array: \\n\"); \n printArray(arr, n); \n \n bubbleSort(arr, n); \n document.write(\"Sorted array: \\n\"); \n printArray(arr, n); \n \n \n</script>\n\n\n\n\n\n",
"e": 8347,
"s": 7489,
"text": null
},
{
"code": null,
"e": 8373,
"s": 8347,
"text": "Sorted array: \n1 2 4 5 8 "
},
{
"code": null,
"e": 8445,
"s": 8373,
"text": "The above function always runs O(n^2) time even if the array is sorted."
},
{
"code": null,
"e": 8533,
"s": 8445,
"text": "It can be optimized by stopping the algorithm if the inner loop didn’t cause any swap. "
},
{
"code": null,
"e": 8586,
"s": 8533,
"text": "Below is the implementation for the above approach: "
},
{
"code": null,
"e": 8590,
"s": 8586,
"text": "C++"
},
{
"code": null,
"e": 8592,
"s": 8590,
"text": "C"
},
{
"code": null,
"e": 8597,
"s": 8592,
"text": "Java"
},
{
"code": null,
"e": 8605,
"s": 8597,
"text": "Python3"
},
{
"code": null,
"e": 8608,
"s": 8605,
"text": "C#"
},
{
"code": null,
"e": 8612,
"s": 8608,
"text": "PHP"
},
{
"code": null,
"e": 8623,
"s": 8612,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\n// Optimized implementation of Bubble sort \n#include <bits/stdc++.h> \nusing namespace std; \n \n// An optimized version of Bubble Sort \nvoid bubbleSort(int arr[], int n) \n{ \n int i, j; \n bool swapped; \n for (i = 0; i < n-1; i++) \n { \n swapped = false; \n for (j = 0; j < n-i-1; j++) \n { \n if (arr[j] > arr[j+1]) \n { \n swap(arr[j], arr[j+1]); \n swapped = true; \n } \n } \n \n // IF no two elements were swapped \n // by inner loop, then break \n if (swapped == false) \n break; \n } \n} \n \n// Function to print an array \nvoid printArray(int arr[], int size) \n{ \n int i; \n for (i = 0; i < size; i++) \n cout <<\" \"<< arr[i]; \n} \n \n// Driver program to test above functions \nint main() \n{ \n int arr[] = {5, 3, 1, 9, 8, 2, 4, 7}; \n int N = sizeof(arr)/sizeof(arr[0]); \n bubbleSort(arr, N); \n cout <<\"Sorted array: \\n\"; \n printArray(arr, N); \n return 0; \n} \n// This code is contributed by shivanisinghss2110\n\n\n\n\n\n",
"e": 9659,
"s": 8633,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Optimized implementation of Bubble sort \n#include <stdio.h> \n#include <stdbool.h> \n \nvoid swap(int *xp, int *yp) \n{ \n int temp = *xp; \n *xp = *yp; \n *yp = temp; \n} \n \n// An optimized version of Bubble Sort \nvoid bubbleSort(int arr[], int n) \n{ \n int i, j; \n bool swapped; \n for (i = 0; i < n-1; i++) \n { \n swapped = false; \n for (j = 0; j < n-i-1; j++) \n { \n if (arr[j] > arr[j+1]) \n { \n swap(&arr[j], &arr[j+1]); \n swapped = true; \n } \n } \n \n // IF no two elements were swapped by inner loop, then break \n if (swapped == false) \n break; \n } \n} \n \n/* Function to print an array */\nvoid printArray(int arr[], int size) \n{ \n int i; \n for (i=0; i < size; i++) \n printf(\"%d \", arr[i]); \n printf(\"n\"); \n} \n \n// Driver program to test above functions \nint main() \n{ \n int arr[] = {64, 34, 25, 12, 22, 11, 90}; \n int n = sizeof(arr)/sizeof(arr[0]); \n bubbleSort(arr, n); \n printf(\"Sorted array: \\n\"); \n printArray(arr, n); \n return 0; \n} \n\n\n\n\n\n",
"e": 10747,
"s": 9669,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Optimized java implementation \n// of Bubble sort \nimport java.io.*; \n \nclass GFG \n{ \n // An optimized version of Bubble Sort \n static void bubbleSort(int arr[], int n) \n { \n int i, j, temp; \n boolean swapped; \n for (i = 0; i < n - 1; i++) \n { \n swapped = false; \n for (j = 0; j < n - i - 1; j++) \n { \n if (arr[j] > arr[j + 1]) \n { \n // swap arr[j] and arr[j+1] \n temp = arr[j]; \n arr[j] = arr[j + 1]; \n arr[j + 1] = temp; \n swapped = true; \n } \n } \n \n // IF no two elements were \n // swapped by inner loop, then break \n if (swapped == false) \n break; \n } \n } \n \n // Function to print an array \n static void printArray(int arr[], int size) \n { \n int i; \n for (i = 0; i < size; i++) \n System.out.print(arr[i] + \" \"); \n System.out.println(); \n } \n \n // Driver program \n public static void main(String args[]) \n { \n int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; \n int n = arr.length; \n bubbleSort(arr, n); \n System.out.println(\"Sorted array: \"); \n printArray(arr, n); \n } \n} \n \n \n// This code is contributed \n// by Nikita Tiwari. \n\n\n\n\n\n",
"e": 12181,
"s": 10757,
"text": null
},
{
"code": "\n\n\n\n\n\n\n# Python3 Optimized implementation \n# of Bubble sort \n \n# An optimized version of Bubble Sort \ndef bubbleSort(arr): \n n = len(arr) \n \n # Traverse through all array elements \n for i in range(n): \n swapped = False\n \n # Last i elements are already \n # in place \n for j in range(0, n-i-1): \n \n # traverse the array from 0 to \n # n-i-1. Swap if the element \n # found is greater than the \n # next element \n if arr[j] > arr[j+1] : \n arr[j], arr[j+1] = arr[j+1], arr[j] \n swapped = True\n \n # IF no two elements were swapped \n # by inner loop, then break \n if swapped == False: \n break\n \n# Driver code to test above \narr = [64, 34, 25, 12, 22, 11, 90] \n \nbubbleSort(arr) \n \nprint (\"Sorted array :\") \nfor i in range(len(arr)): \n print (\"%d\" %arr[i],end=\" \") \n \n# This code is contributed by Shreyanshi Arun \n\n\n\n\n\n",
"e": 13183,
"s": 12191,
"text": null
},
{
"code": "\n\n\n\n\n\n\n// Optimized C# implementation \n// of Bubble sort \nusing System; \n \nclass GFG \n{ \n // An optimized version of Bubble Sort \n static void bubbleSort(int []arr, int n) \n { \n int i, j, temp; \n bool swapped; \n for (i = 0; i < n - 1; i++) \n { \n swapped = false; \n for (j = 0; j < n - i - 1; j++) \n { \n if (arr[j] > arr[j + 1]) \n { \n // swap arr[j] and arr[j+1] \n temp = arr[j]; \n arr[j] = arr[j + 1]; \n arr[j + 1] = temp; \n swapped = true; \n } \n } \n \n // IF no two elements were \n // swapped by inner loop, then break \n if (swapped == false) \n break; \n } \n } \n \n // Function to print an array \n static void printArray(int []arr, int size) \n { \n int i; \n for (i = 0; i < size; i++) \n Console.Write(arr[i] + \" \"); \n Console.WriteLine(); \n } \n \n // Driver method \n public static void Main() \n { \n int []arr = {64, 34, 25, 12, 22, 11, 90}; \n int n = arr.Length; \n bubbleSort(arr,n); \n Console.WriteLine(\"Sorted array\"); \n printArray(arr,n); \n } \n \n} \n// This code is contributed by Sam007 \n\n\n\n\n\n",
"e": 14568,
"s": 13193,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<?php \n// PHP Optimized implementation \n// of Bubble sort \n \n// An optimized version of Bubble Sort \nfunction bubbleSort(&$arr) \n{ \n $n = sizeof($arr); \n \n // Traverse through all array elements \n for($i = 0; $i < $n; $i++) \n { \n $swapped = False; \n \n // Last i elements are already \n // in place \n for ($j = 0; $j < $n - $i - 1; $j++) \n { \n \n // traverse the array from 0 to \n // n-i-1. Swap if the element \n // found is greater than the \n // next element \n if ($arr[$j] > $arr[$j+1]) \n { \n $t = $arr[$j]; \n $arr[$j] = $arr[$j+1]; \n $arr[$j+1] = $t; \n $swapped = True; \n } \n } \n \n // IF no two elements were swapped \n // by inner loop, then break \n if ($swapped == False) \n break; \n } \n} \n \n// Driver code to test above \n$arr = array(64, 34, 25, 12, 22, 11, 90); \n$len = sizeof($arr); \nbubbleSort($arr); \n \necho \"Sorted array : \\n\"; \n \nfor($i = 0; $i < $len; $i++) \n echo $arr[$i].\" \"; \n \n// This code is contributed by ChitraNayal. \n?> \n\n\n\n\n\n",
"e": 15795,
"s": 14578,
"text": null
},
{
"code": "\n\n\n\n\n\n\n<script> \n \n// Optimized javaScript implementation \n// of Bubble sort \n// An optimized version of Bubble Sort \nfunction bubbleSort(arr, n) \n { \n var i, j, temp; \n var swapped; \n for (i = 0; i < n - 1; i++) \n { \n swapped = false; \n for (j = 0; j < n - i - 1; j++) \n { \n if (arr[j] > arr[j + 1]) \n { \n // swap arr[j] and arr[j+1] \n temp = arr[j]; \n arr[j] = arr[j + 1]; \n arr[j + 1] = temp; \n swapped = true; \n } \n } \n \n // IF no two elements were \n // swapped by inner loop, then break \n if (swapped == false) \n break; \n } \n } \n \n // Function to print an array \n function printArray(arr, size) \n { \n var i; \n for (i = 0; i < size; i++) \n document.write(arr[i] + \" \"); \n document.writeln(); \n } \n \n // Driver program \n var arr = [ 64, 34, 25, 12, 22, 11, 90 ]; \n var n = arr.length; \n bubbleSort(arr, n); \n document.write(\"Sorted array: \"); \n printArray(arr, n); \n \n// This code is contributed shivanisinghss2110 \n</script> \n\n\n\n\n\n",
"e": 17106,
"s": 15805,
"text": null
},
{
"code": null,
"e": 17138,
"s": 17106,
"text": "Sorted array: \n 1 2 3 4 5 7 8 9"
},
{
"code": null,
"e": 17182,
"s": 17138,
"text": "Time Complexity: O(N2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 17447,
"s": 17182,
"text": "The worst-case condition for bubble sort occurs when elements of the array are arranged in decreasing order.In the worst case, the total number of iterations or passes required to sort a given array is (n-1). where ‘n’ is a number of elements present in the array."
},
{
"code": null,
"e": 17536,
"s": 17447,
"text": " At pass 1 : Number of comparisons = (n-1) Number of swaps = (n-1)"
},
{
"code": null,
"e": 17625,
"s": 17536,
"text": " At pass 2 : Number of comparisons = (n-2) Number of swaps = (n-2)"
},
{
"code": null,
"e": 17891,
"s": 17625,
"text": " At pass 3 : Number of comparisons = (n-3) Number of swaps = (n-3) . . . At pass n-1 : Number of comparisons = 1 Number of swaps = 1"
},
{
"code": null,
"e": 18079,
"s": 17891,
"text": "Now , calculating total number of comparison required to sort the array= (n-1) + (n-2) + (n-3) + . . . 2 + 1= (n-1)*(n-1+1)/2 { by using sum of N natural Number formula }= n (n-1)/2 "
},
{
"code": null,
"e": 18099,
"s": 18079,
"text": "For the Worst case:"
},
{
"code": null,
"e": 18245,
"s": 18099,
"text": "Total number of swaps = Total number of comparisonTotal number of comparison (Worst case) = n(n-1)/2Total number of swaps (Worst case) = n(n-1)/2"
},
{
"code": null,
"e": 18454,
"s": 18245,
"text": "Worst and Average Case Time Complexity: O(N2). The worst case occurs when an array is reverse sorted.Best Case Time Complexity: O(N). The best case occurs when an array is already sorted.Auxiliary Space: O(1)"
},
{
"code": null,
"e": 18563,
"s": 18454,
"text": "The idea is to place the largest element at their position and keep doing the same for every other elements."
},
{
"code": null,
"e": 18573,
"s": 18563,
"text": "Approach:"
},
{
"code": null,
"e": 18707,
"s": 18573,
"text": "Place the largest element at their position, this operation makes sure that first largest element will be placed at the end of array."
},
{
"code": null,
"e": 18824,
"s": 18707,
"text": "Recursively call for rest n – 1 elements with same operation and placing the next greater element at their position."
},
{
"code": null,
"e": 18975,
"s": 18824,
"text": "Base condition for this recursion call would be, when number of elements in the array becomes 0 or 1 then, simply return (as they are already sorted)."
},
{
"code": null,
"e": 19026,
"s": 18975,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 19030,
"s": 19026,
"text": "C++"
},
{
"code": "\n\n\n\n\n\n\n//C++ code for recursive bubble sort algorithm \n#include <iostream> \nusing namespace std; \nvoid bubblesort(int arr[], int n) \n{ \n if (n == 0 || n == 1) \n { \n return; \n } \n for (int i = 0; i < n - 1; i++) \n { \n if (arr[i] > arr[i + 1]) \n { \n swap(arr[i], arr[i + 1]); \n } \n } \n bubblesort(arr, n - 1); \n} \nint main() \n{ \n int arr[5] = {2, 5, 1, 6, 9}; \n bubblesort(arr, 5); \n for (int i = 0; i < 5; i++) \n { \n cout << arr[i] << \" \"; \n } \n return 0; \n} \n//code contributed by pragatikohli\n\n\n\n\n\n",
"e": 19625,
"s": 19040,
"text": null
},
{
"code": null,
"e": 19636,
"s": 19625,
"text": "1 2 5 6 9 "
},
{
"code": null,
"e": 19822,
"s": 19636,
"text": "Bubble sort takes minimum time (Order of n) when elements are already sorted. Hence it is best to check if the array is already sorted or not beforehand, to avoid O(N2) time complexity."
},
{
"code": null,
"e": 19974,
"s": 19822,
"text": "Yes, Bubble sort performs swapping of adjacent pairs without the use of any major data structure. Hence Bubble sort algorithm is an in-place algorithm."
},
{
"code": null,
"e": 20016,
"s": 19974,
"text": "Yes, the bubble sort algorithm is stable."
},
{
"code": null,
"e": 20297,
"s": 20016,
"text": "Due to its simplicity, bubble sort is often used to introduce the concept of a sorting algorithm. In computer graphics, it is popular for its capability to detect a tiny error (like a swap of just two elements) in almost-sorted arrays and fix it with just linear complexity (2n). "
},
{
"code": null,
"e": 21435,
"s": 20297,
"text": "For example, it is used in a polygon filling algorithm, where bounding lines are sorted by their x coordinate at a specific scan line (a line parallel to the x-axis), and with incrementing y their order changes (two elements are swapped) only at intersections of two lines (Source: Wikipedia) Bubble Sort | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersBubble Sort | GeeksforGeeksWatch laterShareCopy link6/21InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:58•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=nmhjrI-aW5o\" 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": 21466,
"s": 21435,
"text": "Snapshots: Quiz on Bubble Sort"
},
{
"code": null,
"e": 21569,
"s": 21466,
"text": "Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz: Recursive Bubble SortCoding practice for sorting."
},
{
"code": null,
"e": 21575,
"s": 21569,
"text": "ukasp"
},
{
"code": null,
"e": 21583,
"s": 21575,
"text": "SumitBM"
},
{
"code": null,
"e": 21597,
"s": 21583,
"text": "rathbhupendra"
},
{
"code": null,
"e": 21609,
"s": 21597,
"text": "TanishJain1"
},
{
"code": null,
"e": 21621,
"s": 21609,
"text": "adityakangs"
},
{
"code": null,
"e": 21637,
"s": 21621,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 21656,
"s": 21637,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 21672,
"s": 21656,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 21688,
"s": 21672,
"text": "pathakanurag605"
},
{
"code": null,
"e": 21710,
"s": 21688,
"text": "vaishalishrivastava21"
},
{
"code": null,
"e": 21724,
"s": 21710,
"text": "kashishkumar2"
},
{
"code": null,
"e": 21735,
"s": 21724,
"text": "animeshdey"
},
{
"code": null,
"e": 21750,
"s": 21735,
"text": "pragatikohli12"
},
{
"code": null,
"e": 21759,
"s": 21750,
"text": "\nredBus\n"
},
{
"code": null,
"e": 21769,
"s": 21759,
"text": "\nSorting\n"
},
{
"code": null,
"e": 21776,
"s": 21769,
"text": "redBus"
},
{
"code": null,
"e": 21784,
"s": 21776,
"text": "Sorting"
}
] |
Summarize Multiple Columns of data.table by Group in R
|
23 Sep, 2021
In this article, we will discuss how to summarize multiple columns of data.table by Group in R Programming Language.
R
# load data.table packagelibrary("data.table") # create data table with 3 columns# items# weight and #costdata <- data.table( items= c("chocos","milk","drinks","drinks", "milk","milk","chocos","milk", "honey","honey"), weight= c(10,20,34,23,12,45,23, 12,34,34), cost= c(120,345,567,324,112,345, 678,100,45,67)) # displaydata
Output:
By finding average
By finding sum
By finding the minimum value
By finding the maximum value
we can do this by using lapply() function
Syntax: datatable[, lapply(.SD, summarizing_function), by = column]
where
datatable is the input data table
lpply() is used to hold two parameters
first parameter is .SD is standard R object
second parameter is an summarizing function that takes summarizing functions to summarize the datatable
by is the name of the column in which data is grouped based on this column
R
# load data.table packagelibrary("data.table") # create data table with 3 columns# items# weight and #costdata <- data.table( items= c("chocos","milk","drinks","drinks", "milk","milk","chocos","milk", "honey","honey"), weight= c(10,20,34,23,12,45,23, 12,34,34), cost= c(120,345,567,324,112,345, 678,100,45,67)) # group by sum with items columnprint(data[, lapply(.SD, sum), by = items]) # group by average with items columnprint(data[, lapply(.SD, mean), by = items])
Output:
R
# load data.table packagelibrary("data.table") # create data table with 3 columns# items weight and #costdata <- data.table( items= c("chocos","milk","drinks","drinks", "milk","milk","chocos","milk", "honey","honey"), weight= c(10,20,34,23,12,45,23, 12,34,34), cost= c(120,345,567,324,112,345, 678,100,45,67)) # group by minimum with items columnprint(data[, lapply(.SD, min), by = items]) # group by maximum with items columnprint(data[, lapply(.SD, max), by = items])
Output:
Picked
R DataTable
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 145,
"s": 28,
"text": "In this article, we will discuss how to summarize multiple columns of data.table by Group in R Programming Language."
},
{
"code": null,
"e": 147,
"s": 145,
"text": "R"
},
{
"code": "# load data.table packagelibrary(\"data.table\") # create data table with 3 columns# items# weight and #costdata <- data.table( items= c(\"chocos\",\"milk\",\"drinks\",\"drinks\", \"milk\",\"milk\",\"chocos\",\"milk\", \"honey\",\"honey\"), weight= c(10,20,34,23,12,45,23, 12,34,34), cost= c(120,345,567,324,112,345, 678,100,45,67)) # displaydata",
"e": 668,
"s": 147,
"text": null
},
{
"code": null,
"e": 676,
"s": 668,
"text": "Output:"
},
{
"code": null,
"e": 695,
"s": 676,
"text": "By finding average"
},
{
"code": null,
"e": 710,
"s": 695,
"text": "By finding sum"
},
{
"code": null,
"e": 739,
"s": 710,
"text": "By finding the minimum value"
},
{
"code": null,
"e": 768,
"s": 739,
"text": "By finding the maximum value"
},
{
"code": null,
"e": 810,
"s": 768,
"text": "we can do this by using lapply() function"
},
{
"code": null,
"e": 878,
"s": 810,
"text": "Syntax: datatable[, lapply(.SD, summarizing_function), by = column]"
},
{
"code": null,
"e": 884,
"s": 878,
"text": "where"
},
{
"code": null,
"e": 918,
"s": 884,
"text": "datatable is the input data table"
},
{
"code": null,
"e": 957,
"s": 918,
"text": "lpply() is used to hold two parameters"
},
{
"code": null,
"e": 1001,
"s": 957,
"text": "first parameter is .SD is standard R object"
},
{
"code": null,
"e": 1105,
"s": 1001,
"text": "second parameter is an summarizing function that takes summarizing functions to summarize the datatable"
},
{
"code": null,
"e": 1180,
"s": 1105,
"text": "by is the name of the column in which data is grouped based on this column"
},
{
"code": null,
"e": 1182,
"s": 1180,
"text": "R"
},
{
"code": "# load data.table packagelibrary(\"data.table\") # create data table with 3 columns# items# weight and #costdata <- data.table( items= c(\"chocos\",\"milk\",\"drinks\",\"drinks\", \"milk\",\"milk\",\"chocos\",\"milk\", \"honey\",\"honey\"), weight= c(10,20,34,23,12,45,23, 12,34,34), cost= c(120,345,567,324,112,345, 678,100,45,67)) # group by sum with items columnprint(data[, lapply(.SD, sum), by = items]) # group by average with items columnprint(data[, lapply(.SD, mean), by = items])",
"e": 1849,
"s": 1182,
"text": null
},
{
"code": null,
"e": 1857,
"s": 1849,
"text": "Output:"
},
{
"code": null,
"e": 1859,
"s": 1857,
"text": "R"
},
{
"code": "# load data.table packagelibrary(\"data.table\") # create data table with 3 columns# items weight and #costdata <- data.table( items= c(\"chocos\",\"milk\",\"drinks\",\"drinks\", \"milk\",\"milk\",\"chocos\",\"milk\", \"honey\",\"honey\"), weight= c(10,20,34,23,12,45,23, 12,34,34), cost= c(120,345,567,324,112,345, 678,100,45,67)) # group by minimum with items columnprint(data[, lapply(.SD, min), by = items]) # group by maximum with items columnprint(data[, lapply(.SD, max), by = items])",
"e": 2527,
"s": 1859,
"text": null
},
{
"code": null,
"e": 2535,
"s": 2527,
"text": "Output:"
},
{
"code": null,
"e": 2542,
"s": 2535,
"text": "Picked"
},
{
"code": null,
"e": 2554,
"s": 2542,
"text": "R DataTable"
},
{
"code": null,
"e": 2565,
"s": 2554,
"text": "R Language"
}
] |
MediaPlayer Class in Android
|
26 Dec, 2020
MediaPlayer Class in Android is used to play media files. Those are Audio and Video files. It can also be used to play audio or video streams over the network. So in this article, the things discussed are:
MediaPlayer State diagram
Creating a simple audio player using MediaPlayer API. Have a look at the following image. Note that we are going to implement this project using the Kotlin language.
The playing of the audio or video file using MediaPlayer is done using a state machine.
The following image is the MediaPlayer state diagram.
In the above MediaPlayer state diagram, the oval shape represents the state of the MediaPlayer instance resides in.
There are two types of arcs showing in the state diagram. One with the single arrowhead represents the synchronous method calls of the MediaPlayer instance and one with the double arrowhead represents the asynchronous calls.
The release method which is one of the important element in the MediaPlayer API. This helps in releasing the Memory resources allocated for the Mediaplayer instance when it is not needed anymore. Refer to How to Clear or Release Audio Resources in Android? to know how the memory allocated by the Mediaplayer can be released. So that the memory management is done accordingly.
If the stop() method is called using Mediaplayer instance, then it needs to prepared for the next playback.
The MediaPlayer can be moved to the specific time position using seekTo() method so that the MediaPlayer instance can continue playing the Audio or Video playback from that specified position.
The focus of the audio playback should be managed accordingly using the AudioManager service which is discussed in the article How to Manage Audio Focus in Android?.
The following image is the summarised version of the MediaPlayer state diagram.
Step 1: Create an empty activity project
Create an empty activity Android Studio project. And select Kotlin as a programming language.
Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project.
Step 2: Create a raw resource folder
Create a raw resource folder under the res folder and copy one of the .mp3 file extension.
Step 3: Working with the activity_main.xml file
The layout of the application consists of three buttons PLAY, PAUSE, and STOP mainly, which is used to control the state of the MediaPlayer instance.
Invoke the following code inside the activity_main.xml file to implement the UI.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:id="@+id/headingText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="32dp" android:text="MEDIA PLAYER" android:textSize="18sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/headingText" android:layout_marginTop="16dp" android:gravity="center_horizontal"> <Button android:id="@+id/stopButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:backgroundTint="@color/colorPrimary" android:text="STOP" android:textColor="@android:color/white" /> <Button android:id="@+id/playButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:backgroundTint="@color/colorPrimary" android:text="PLAY" android:textColor="@android:color/white" /> <Button android:id="@+id/pauseButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="@color/colorPrimary" android:text="PAUSE" android:textColor="@android:color/white" /> </LinearLayout> </RelativeLayout>
Output UI:
Step 4: Working with the MainActivity.kt file
The MediaPlayer instance needs the attributes needs to be set before playing any audio or video file.
Invoke the following inside the MainActivity.kt file. Comments are added for better understanding.
Kotlin
import android.media.MediaPlayerimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Button class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // create an instance of mediplayer for audio playback val mediaPlayer: MediaPlayer = MediaPlayer.create(applicationContext, R.raw.music) // register all the buttons using their appropriate IDs val bPlay: Button = findViewById(R.id.playButton) val bPause: Button = findViewById(R.id.pauseButton) val bStop: Button = findViewById(R.id.stopButton) // handle the start button to // start the audio playback bPlay.setOnClickListener { // start method is used to start // playing the audio file mediaPlayer.start() } // handle the pause button to put the // MediaPlayer instance at the Pause state bPause.setOnClickListener { // pause() method can be used to // pause the mediaplyer instance mediaPlayer.pause() } // handle the stop button to stop playing // and prepare the mediaplayer instance // for the next instance of play bStop.setOnClickListener { // stop() method is used to completely // stop playing the mediaplayer instance mediaPlayer.stop() // after stopping the mediaplayer instance // it is again need to be prepared // for the next instance of playback mediaPlayer.prepare() } }}
adityamshidlyali
android
Technical Scripter 2020
Android
Kotlin
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Android RecyclerView in Kotlin
Android Project folder Structure
Broadcast Receiver in Android With Example
Navigation Drawer in Android
Android RecyclerView in Kotlin
Broadcast Receiver in Android With Example
Kotlin constructor
Kotlin Array
Android UI Layouts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Dec, 2020"
},
{
"code": null,
"e": 234,
"s": 28,
"text": "MediaPlayer Class in Android is used to play media files. Those are Audio and Video files. It can also be used to play audio or video streams over the network. So in this article, the things discussed are:"
},
{
"code": null,
"e": 260,
"s": 234,
"text": "MediaPlayer State diagram"
},
{
"code": null,
"e": 427,
"s": 260,
"text": "Creating a simple audio player using MediaPlayer API. Have a look at the following image. Note that we are going to implement this project using the Kotlin language. "
},
{
"code": null,
"e": 515,
"s": 427,
"text": "The playing of the audio or video file using MediaPlayer is done using a state machine."
},
{
"code": null,
"e": 569,
"s": 515,
"text": "The following image is the MediaPlayer state diagram."
},
{
"code": null,
"e": 685,
"s": 569,
"text": "In the above MediaPlayer state diagram, the oval shape represents the state of the MediaPlayer instance resides in."
},
{
"code": null,
"e": 910,
"s": 685,
"text": "There are two types of arcs showing in the state diagram. One with the single arrowhead represents the synchronous method calls of the MediaPlayer instance and one with the double arrowhead represents the asynchronous calls."
},
{
"code": null,
"e": 1287,
"s": 910,
"text": "The release method which is one of the important element in the MediaPlayer API. This helps in releasing the Memory resources allocated for the Mediaplayer instance when it is not needed anymore. Refer to How to Clear or Release Audio Resources in Android? to know how the memory allocated by the Mediaplayer can be released. So that the memory management is done accordingly."
},
{
"code": null,
"e": 1395,
"s": 1287,
"text": "If the stop() method is called using Mediaplayer instance, then it needs to prepared for the next playback."
},
{
"code": null,
"e": 1588,
"s": 1395,
"text": "The MediaPlayer can be moved to the specific time position using seekTo() method so that the MediaPlayer instance can continue playing the Audio or Video playback from that specified position."
},
{
"code": null,
"e": 1754,
"s": 1588,
"text": "The focus of the audio playback should be managed accordingly using the AudioManager service which is discussed in the article How to Manage Audio Focus in Android?."
},
{
"code": null,
"e": 1834,
"s": 1754,
"text": "The following image is the summarised version of the MediaPlayer state diagram."
},
{
"code": null,
"e": 1875,
"s": 1834,
"text": "Step 1: Create an empty activity project"
},
{
"code": null,
"e": 1969,
"s": 1875,
"text": "Create an empty activity Android Studio project. And select Kotlin as a programming language."
},
{
"code": null,
"e": 2105,
"s": 1969,
"text": "Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project."
},
{
"code": null,
"e": 2142,
"s": 2105,
"text": "Step 2: Create a raw resource folder"
},
{
"code": null,
"e": 2233,
"s": 2142,
"text": "Create a raw resource folder under the res folder and copy one of the .mp3 file extension."
},
{
"code": null,
"e": 2281,
"s": 2233,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2431,
"s": 2281,
"text": "The layout of the application consists of three buttons PLAY, PAUSE, and STOP mainly, which is used to control the state of the MediaPlayer instance."
},
{
"code": null,
"e": 2512,
"s": 2431,
"text": "Invoke the following code inside the activity_main.xml file to implement the UI."
},
{
"code": null,
"e": 2516,
"s": 2512,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:id=\"@+id/headingText\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"32dp\" android:text=\"MEDIA PLAYER\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/headingText\" android:layout_marginTop=\"16dp\" android:gravity=\"center_horizontal\"> <Button android:id=\"@+id/stopButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginEnd=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"STOP\" android:textColor=\"@android:color/white\" /> <Button android:id=\"@+id/playButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginEnd=\"8dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"PLAY\" android:textColor=\"@android:color/white\" /> <Button android:id=\"@+id/pauseButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"PAUSE\" android:textColor=\"@android:color/white\" /> </LinearLayout> </RelativeLayout>",
"e": 4388,
"s": 2516,
"text": null
},
{
"code": null,
"e": 4401,
"s": 4388,
"text": " Output UI: "
},
{
"code": null,
"e": 4448,
"s": 4401,
"text": "Step 4: Working with the MainActivity.kt file "
},
{
"code": null,
"e": 4550,
"s": 4448,
"text": "The MediaPlayer instance needs the attributes needs to be set before playing any audio or video file."
},
{
"code": null,
"e": 4650,
"s": 4550,
"text": "Invoke the following inside the MainActivity.kt file. Comments are added for better understanding. "
},
{
"code": null,
"e": 4657,
"s": 4650,
"text": "Kotlin"
},
{
"code": "import android.media.MediaPlayerimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Button class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // create an instance of mediplayer for audio playback val mediaPlayer: MediaPlayer = MediaPlayer.create(applicationContext, R.raw.music) // register all the buttons using their appropriate IDs val bPlay: Button = findViewById(R.id.playButton) val bPause: Button = findViewById(R.id.pauseButton) val bStop: Button = findViewById(R.id.stopButton) // handle the start button to // start the audio playback bPlay.setOnClickListener { // start method is used to start // playing the audio file mediaPlayer.start() } // handle the pause button to put the // MediaPlayer instance at the Pause state bPause.setOnClickListener { // pause() method can be used to // pause the mediaplyer instance mediaPlayer.pause() } // handle the stop button to stop playing // and prepare the mediaplayer instance // for the next instance of play bStop.setOnClickListener { // stop() method is used to completely // stop playing the mediaplayer instance mediaPlayer.stop() // after stopping the mediaplayer instance // it is again need to be prepared // for the next instance of playback mediaPlayer.prepare() } }}",
"e": 6358,
"s": 4657,
"text": null
},
{
"code": null,
"e": 6375,
"s": 6358,
"text": "adityamshidlyali"
},
{
"code": null,
"e": 6383,
"s": 6375,
"text": "android"
},
{
"code": null,
"e": 6407,
"s": 6383,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 6415,
"s": 6407,
"text": "Android"
},
{
"code": null,
"e": 6422,
"s": 6415,
"text": "Kotlin"
},
{
"code": null,
"e": 6441,
"s": 6422,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6449,
"s": 6441,
"text": "Android"
},
{
"code": null,
"e": 6547,
"s": 6449,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6579,
"s": 6547,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 6610,
"s": 6579,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 6643,
"s": 6610,
"text": "Android Project folder Structure"
},
{
"code": null,
"e": 6686,
"s": 6643,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 6715,
"s": 6686,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 6746,
"s": 6715,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 6789,
"s": 6746,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 6808,
"s": 6789,
"text": "Kotlin constructor"
},
{
"code": null,
"e": 6821,
"s": 6808,
"text": "Kotlin Array"
}
] |
Node.js Utility Module
|
13 Oct, 2021
Node.js Utility Module: The Util module in node.js provides access to various utility functions.
Syntax:
var util = require('util');
There are various utility modules available in node.js module library. The modules are extremely useful in developing node based web applications.Various utility modules present in node.js are as follows:
OS Module: Operating System based utility modules for node.js are provided by OS module.
Syntax:
var os = require('os');
Example:
// Require operating System modulevar os = require("os"); // Display operating System type console.log('Operating System type : ' + os.type()); // Display operating System platform console.log('platform : ' + os.platform()); // Display total memory console.log('total memory : ' + os.totalmem() + " bytes."); // Display available memory console.log('Available memory : ' + os.availmem() + " bytes.");
Output:
Path Module: Path module in node.js is used for transforming and handling various file paths.
Syntax:
var path = require('path');
Example:
// Require pathvar path = require('path'); // Display Resolveconsole.log('resolve:' + path.resolve('paths.js')); // Display Extensionconsole.log('extension:' + path.extname('paths.js'));
Output:
DNS Module: DNS Module enables us to use the underlying Operating System name resolution functionalities. The actual DNS lookup is also performed by the DNS Module. This DNS Module provides an asynchronous network wrapper. The DNS Module can be imported using the below syntax.
Syntax:
var dns = require('dns');
Example:
// Require dns moduleconst dns = require('dns'); // Store the web addressconst website = 'www.geeksforgeeks.org'; // Call lookup function of DNSdns.lookup(website, (err, address, family) => { console.log('Address of %s is %j family: IPv%s', website, address, family); });
Output:
Address of www.geeksforgeeks.org is "203.92.39.72"
family: IPv4
Net Module: Net Module in node.js is used for the creation of both client and server. Similar to DNS Module this module also provides an asynchronous network wrapper.
Syntax:
var net = require('net');
Example: This example containing the code for server side.
// Require net modulevar net = require('net'); var server = net.createServer(function(connection) { console.log('client connected'); connection.on('end', function() { console.log('client disconnected'); }); connection.write('Hello World!\r\n'); connection.pipe(connection); }); server.listen(8080, function() { console.log('server listening');});
Output:
Server listening
Example: This example is containing the for client side in net Module.
var net = require('net'); var client = net.connect(8124, function() { console.log('Client Connected'); client.write('GeeksforGeeks\r\n');}); client.on('data', function(data) { console.log(data.toString()); client.end();}); client.on('end', function() { console.log('Server Disconnected');});
Output:
Client Connected
GeeksforGeeks
Server Disconnected
Domain Module: Domain module in node.js is used to intercept unhandled errors. The interception can be performed by either:
Internal Binding: Error emitter executes the code internally within the run method of a domain.
External Binding: Error emitter is added explicitly to the domain using the add method.
Syntax:
var domain = require('domain');
The domain class in the domain module provides a mechanism of routing the unhandled exceptions and errors to the active domain object. It is considered to be the child class of EventEmitter.
Syntax:
var domain = require('domain');
var child = domain.create();
Example:
var EventEmitter = require("events").EventEmitter; var domain = require("domain");var emit_a = new EventEmitter();var dom_a = domain.create(); dom_a.on('error', function(err) { console.log("Error handled by dom_a ("+err.message+")"); }); dom_a.add(emit_a);emit_a.on('error', function(err) { console.log("listener handled this error ("+err.message+")"); }); emit_a.emit('error', new Error('Listener handles this')); emit_a.removeAllListeners('error'); emit_a.emit('error', new Error('Dom_a handles this')); var dom_b = domain.create(); dom_b.on('error', function(err) { console.log("Error handled by dom_b ("+err.message+")"); }); dom_b.run(function() { var emit_b = new EventEmitter(); emit_b.emit('error', new Error('Dom_b handles this')); }); dom_a.remove(emit_a);emit_a.emit('error', new Error('Exception message...!'));
Output:
Node.js-Basics
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 125,
"s": 28,
"text": "Node.js Utility Module: The Util module in node.js provides access to various utility functions."
},
{
"code": null,
"e": 133,
"s": 125,
"text": "Syntax:"
},
{
"code": null,
"e": 161,
"s": 133,
"text": "var util = require('util');"
},
{
"code": null,
"e": 366,
"s": 161,
"text": "There are various utility modules available in node.js module library. The modules are extremely useful in developing node based web applications.Various utility modules present in node.js are as follows:"
},
{
"code": null,
"e": 455,
"s": 366,
"text": "OS Module: Operating System based utility modules for node.js are provided by OS module."
},
{
"code": null,
"e": 463,
"s": 455,
"text": "Syntax:"
},
{
"code": null,
"e": 487,
"s": 463,
"text": "var os = require('os');"
},
{
"code": null,
"e": 496,
"s": 487,
"text": "Example:"
},
{
"code": "// Require operating System modulevar os = require(\"os\"); // Display operating System type console.log('Operating System type : ' + os.type()); // Display operating System platform console.log('platform : ' + os.platform()); // Display total memory console.log('total memory : ' + os.totalmem() + \" bytes.\"); // Display available memory console.log('Available memory : ' + os.availmem() + \" bytes.\");",
"e": 908,
"s": 496,
"text": null
},
{
"code": null,
"e": 916,
"s": 908,
"text": "Output:"
},
{
"code": null,
"e": 1010,
"s": 916,
"text": "Path Module: Path module in node.js is used for transforming and handling various file paths."
},
{
"code": null,
"e": 1018,
"s": 1010,
"text": "Syntax:"
},
{
"code": null,
"e": 1046,
"s": 1018,
"text": "var path = require('path');"
},
{
"code": null,
"e": 1055,
"s": 1046,
"text": "Example:"
},
{
"code": "// Require pathvar path = require('path'); // Display Resolveconsole.log('resolve:' + path.resolve('paths.js')); // Display Extensionconsole.log('extension:' + path.extname('paths.js'));",
"e": 1245,
"s": 1055,
"text": null
},
{
"code": null,
"e": 1253,
"s": 1245,
"text": "Output:"
},
{
"code": null,
"e": 1531,
"s": 1253,
"text": "DNS Module: DNS Module enables us to use the underlying Operating System name resolution functionalities. The actual DNS lookup is also performed by the DNS Module. This DNS Module provides an asynchronous network wrapper. The DNS Module can be imported using the below syntax."
},
{
"code": null,
"e": 1539,
"s": 1531,
"text": "Syntax:"
},
{
"code": null,
"e": 1565,
"s": 1539,
"text": "var dns = require('dns');"
},
{
"code": null,
"e": 1574,
"s": 1565,
"text": "Example:"
},
{
"code": "// Require dns moduleconst dns = require('dns'); // Store the web addressconst website = 'www.geeksforgeeks.org'; // Call lookup function of DNSdns.lookup(website, (err, address, family) => { console.log('Address of %s is %j family: IPv%s', website, address, family); }); ",
"e": 1865,
"s": 1574,
"text": null
},
{
"code": null,
"e": 1873,
"s": 1865,
"text": "Output:"
},
{
"code": null,
"e": 1938,
"s": 1873,
"text": "Address of www.geeksforgeeks.org is \"203.92.39.72\"\nfamily: IPv4\n"
},
{
"code": null,
"e": 2105,
"s": 1938,
"text": "Net Module: Net Module in node.js is used for the creation of both client and server. Similar to DNS Module this module also provides an asynchronous network wrapper."
},
{
"code": null,
"e": 2113,
"s": 2105,
"text": "Syntax:"
},
{
"code": null,
"e": 2139,
"s": 2113,
"text": "var net = require('net');"
},
{
"code": null,
"e": 2198,
"s": 2139,
"text": "Example: This example containing the code for server side."
},
{
"code": "// Require net modulevar net = require('net'); var server = net.createServer(function(connection) { console.log('client connected'); connection.on('end', function() { console.log('client disconnected'); }); connection.write('Hello World!\\r\\n'); connection.pipe(connection); }); server.listen(8080, function() { console.log('server listening');});",
"e": 2561,
"s": 2198,
"text": null
},
{
"code": null,
"e": 2569,
"s": 2561,
"text": "Output:"
},
{
"code": null,
"e": 2586,
"s": 2569,
"text": "Server listening"
},
{
"code": null,
"e": 2657,
"s": 2586,
"text": "Example: This example is containing the for client side in net Module."
},
{
"code": "var net = require('net'); var client = net.connect(8124, function() { console.log('Client Connected'); client.write('GeeksforGeeks\\r\\n');}); client.on('data', function(data) { console.log(data.toString()); client.end();}); client.on('end', function() { console.log('Server Disconnected');});",
"e": 2958,
"s": 2657,
"text": null
},
{
"code": null,
"e": 2966,
"s": 2958,
"text": "Output:"
},
{
"code": null,
"e": 3019,
"s": 2966,
"text": "Client Connected \nGeeksforGeeks\nServer Disconnected\n"
},
{
"code": null,
"e": 3143,
"s": 3019,
"text": "Domain Module: Domain module in node.js is used to intercept unhandled errors. The interception can be performed by either:"
},
{
"code": null,
"e": 3239,
"s": 3143,
"text": "Internal Binding: Error emitter executes the code internally within the run method of a domain."
},
{
"code": null,
"e": 3327,
"s": 3239,
"text": "External Binding: Error emitter is added explicitly to the domain using the add method."
},
{
"code": null,
"e": 3335,
"s": 3327,
"text": "Syntax:"
},
{
"code": null,
"e": 3367,
"s": 3335,
"text": "var domain = require('domain');"
},
{
"code": null,
"e": 3558,
"s": 3367,
"text": "The domain class in the domain module provides a mechanism of routing the unhandled exceptions and errors to the active domain object. It is considered to be the child class of EventEmitter."
},
{
"code": null,
"e": 3566,
"s": 3558,
"text": "Syntax:"
},
{
"code": null,
"e": 3628,
"s": 3566,
"text": "var domain = require('domain');\nvar child = domain.create();\n"
},
{
"code": null,
"e": 3637,
"s": 3628,
"text": "Example:"
},
{
"code": "var EventEmitter = require(\"events\").EventEmitter; var domain = require(\"domain\");var emit_a = new EventEmitter();var dom_a = domain.create(); dom_a.on('error', function(err) { console.log(\"Error handled by dom_a (\"+err.message+\")\"); }); dom_a.add(emit_a);emit_a.on('error', function(err) { console.log(\"listener handled this error (\"+err.message+\")\"); }); emit_a.emit('error', new Error('Listener handles this')); emit_a.removeAllListeners('error'); emit_a.emit('error', new Error('Dom_a handles this')); var dom_b = domain.create(); dom_b.on('error', function(err) { console.log(\"Error handled by dom_b (\"+err.message+\")\"); }); dom_b.run(function() { var emit_b = new EventEmitter(); emit_b.emit('error', new Error('Dom_b handles this')); }); dom_a.remove(emit_a);emit_a.emit('error', new Error('Exception message...!'));",
"e": 4478,
"s": 3637,
"text": null
},
{
"code": null,
"e": 4486,
"s": 4478,
"text": "Output:"
},
{
"code": null,
"e": 4501,
"s": 4486,
"text": "Node.js-Basics"
},
{
"code": null,
"e": 4508,
"s": 4501,
"text": "Picked"
},
{
"code": null,
"e": 4516,
"s": 4508,
"text": "Node.js"
},
{
"code": null,
"e": 4533,
"s": 4516,
"text": "Web Technologies"
}
] |
Python – Subscript Dictionary
|
22 Jun, 2020
Sometimes, while working with data in Python, we can have a problem in which we need to use subscripted version of numbers rather than normal ones. For this, having a dictionary which maps the number with its subscript version has good utility. Let’s discuss certain ways in which this task can be performed.
Input : test_str = “012345”Output : {‘0’: ‘?’, ‘1’: ‘?’, ‘2’: ‘?’, ‘3’: ‘?’, ‘4’: ‘?’, ‘5’: ‘?’}
Input : test_str = “0”Output : {‘0’: ‘?’}
Method #1 : Using loop + ord()This is brute force way in which we perform this task. In this, we iterate through the numbers that we require to subscript and construct subscript value using ord() and its binary value. Works in Python 3.7 +.
# Python3 code to demonstrate working of # Subscript Dictionary# Using loop + ord() # initializing stringtest_str = "0123456789" # printing original stringprint("The original string is : " + test_str) # initializing Subscript number valueK = u'\u2080' # Subscript Dictionary# Using loop + ord()res = {}for ele in test_str: res[ele] = K K = chr(ord(K) + 1) # printing result print("The split string is : " + str(res))
The original string is : 0123456789The split string is : {‘7’: ‘?’, ‘4’: ‘?’, ‘2’: ‘?’, ‘3’: ‘?’, ‘5’: ‘?’, ‘8’: ‘?’, ‘1’: ‘?’, ‘6’: ‘?’, ‘0’: ‘?’, ‘9’: ‘?’}
Method #2 : Using dictionary comprehensionThis is yet another way in which this task can be performed. In this, we perform a similar task as above, just employ in one-liner using comprehension. Works in Python 3.7 +.
# Python3 code to demonstrate working of # Subscript Dictionary# Using Dictionary comprehension # initializing stringtest_str = "0123456789" # printing original stringprint("The original string is : " + test_str) # initializing Subscript number valueK = u'\u2080' # Subscript Dictionary# Using Dictionary comprehensionres = {ele : chr(ord(K) + 1) for ele in test_str} # printing result print("The split string is : " + str(res))
The original string is : 0123456789The split string is : {‘7’: ‘?’, ‘4’: ‘?’, ‘2’: ‘?’, ‘3’: ‘?’, ‘5’: ‘?’, ‘8’: ‘?’, ‘1’: ‘?’, ‘6’: ‘?’, ‘0’: ‘?’, ‘9’: ‘?’}
Python dictionary-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": "\n22 Jun, 2020"
},
{
"code": null,
"e": 337,
"s": 28,
"text": "Sometimes, while working with data in Python, we can have a problem in which we need to use subscripted version of numbers rather than normal ones. For this, having a dictionary which maps the number with its subscript version has good utility. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 434,
"s": 337,
"text": "Input : test_str = “012345”Output : {‘0’: ‘?’, ‘1’: ‘?’, ‘2’: ‘?’, ‘3’: ‘?’, ‘4’: ‘?’, ‘5’: ‘?’}"
},
{
"code": null,
"e": 476,
"s": 434,
"text": "Input : test_str = “0”Output : {‘0’: ‘?’}"
},
{
"code": null,
"e": 717,
"s": 476,
"text": "Method #1 : Using loop + ord()This is brute force way in which we perform this task. In this, we iterate through the numbers that we require to subscript and construct subscript value using ord() and its binary value. Works in Python 3.7 +."
},
{
"code": "# Python3 code to demonstrate working of # Subscript Dictionary# Using loop + ord() # initializing stringtest_str = \"0123456789\" # printing original stringprint(\"The original string is : \" + test_str) # initializing Subscript number valueK = u'\\u2080' # Subscript Dictionary# Using loop + ord()res = {}for ele in test_str: res[ele] = K K = chr(ord(K) + 1) # printing result print(\"The split string is : \" + str(res)) ",
"e": 1146,
"s": 717,
"text": null
},
{
"code": null,
"e": 1304,
"s": 1146,
"text": "The original string is : 0123456789The split string is : {‘7’: ‘?’, ‘4’: ‘?’, ‘2’: ‘?’, ‘3’: ‘?’, ‘5’: ‘?’, ‘8’: ‘?’, ‘1’: ‘?’, ‘6’: ‘?’, ‘0’: ‘?’, ‘9’: ‘?’}"
},
{
"code": null,
"e": 1523,
"s": 1306,
"text": "Method #2 : Using dictionary comprehensionThis is yet another way in which this task can be performed. In this, we perform a similar task as above, just employ in one-liner using comprehension. Works in Python 3.7 +."
},
{
"code": "# Python3 code to demonstrate working of # Subscript Dictionary# Using Dictionary comprehension # initializing stringtest_str = \"0123456789\" # printing original stringprint(\"The original string is : \" + test_str) # initializing Subscript number valueK = u'\\u2080' # Subscript Dictionary# Using Dictionary comprehensionres = {ele : chr(ord(K) + 1) for ele in test_str} # printing result print(\"The split string is : \" + str(res)) ",
"e": 1958,
"s": 1523,
"text": null
},
{
"code": null,
"e": 2116,
"s": 1958,
"text": "The original string is : 0123456789The split string is : {‘7’: ‘?’, ‘4’: ‘?’, ‘2’: ‘?’, ‘3’: ‘?’, ‘5’: ‘?’, ‘8’: ‘?’, ‘1’: ‘?’, ‘6’: ‘?’, ‘0’: ‘?’, ‘9’: ‘?’}"
},
{
"code": null,
"e": 2143,
"s": 2116,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2150,
"s": 2143,
"text": "Python"
},
{
"code": null,
"e": 2166,
"s": 2150,
"text": "Python Programs"
}
] |
Import in GoLang
|
28 Jul, 2020
Pre-requisite learning: Installing Go on Windows / Installing Go on MacOS
Technically defining, a package is essentially a container of source code for some specific purpose. This means that the package is a capsule that holds multiple elements of drug/medicine binding them all together and protecting them in one mini shell. This capsule is easy to carry anywhere and use it as per choice, right? Yeah, that’s right. You can write thousands of lines of code, hundreds of functions, n number of operations, and much more in one package and store it so that you can just grab the package into your main file whenever you require it. Many packages come pre-built with Go.
Packages are very essential as in all programs ranging from the most basic programs to high-level complex codes, these are used. A package ensures that no code is repeated and that the main code is as concise as possible in a well-structured manner.
Example:
package main
The main package holds the code that is responsible to make the current program compilable and runnable.
Packages, as we’ve discussed, are sweethearts that help us code in Go. Now the question is how do we use them in our program? The answer is simple: using the “import” keyword. As the name suggests, this keyword imports the specified package from the directory of $GOPATH (if no path is mentioned) or else from the mentioned directory. Importing simply means bringing the specified package from its source location to the destination code, wiz the main program. Import in Go is very important because it helps bring the packages which are super essential to run programs. This article covers various aspects of “Imports in Go”.
Example:
import "fmt" --------------------------------> fmt is the name of a package
import "os" ---------------------------------> os is the name of a package
import "github.com/gopherguides/greet" ------> the underlined part is the path of the package
Well, yes there are different types of imports, many of which are unknown to many users. Let’s discuss these types in detail. Let us consider one package: Let’s say math and watch the differences in import styles.
Go supports the direct import of packages by following a simple syntax. Both single and multiple packages can be imported one by one using the import keyword.
Example:
Single:
import "fmt"
Multiple one-by-one:
import "fmt"
import "math"
Go
// Golang program to demonstrate the // application of direct importpackage main import "fmt" // Main functionfunc main() { fmt.Println("Hello Geeks")}
Go also supports grouped imports. This means that you don’t have to write the import keyword multiple times; instead, you can use the keyword import followed by round braces, (), and mention all the packages inside the round braces that you wish to import. This is a direct import too but the difference is that you’ve mentioned multiple packages within one import() here. Peek at the example to get an idea of the syntax of grouped import command.
Example:
import(
"fmt"
"math"
)
Go
// A program to demonstrate the// application of grouped importpackage main import ( "fmt" "math") // Main functionfunc main() { // math.Exp2(5) returns // the value of 2^5, wiz 32 c := math.Exp2(5) // Println is a function in fmt package // which prints value of c in a new // line on console fmt.Println(c) }
Go supports nested imports as well. Just as we hear of the name nested import, we suddenly think of the ladder if-else statements of nested loops, etc. But nested import is nothing of that sort: It’s different from those nested elements. Here nested import means, importing a sub-package from a larger package file. For instance, there are times when you only need to use one particular function from the entire package and so you do not want to import the entire package and increase your memory size of code and stuff like that, in short, you just want one sub-package. In such scenarios, we use nested import. Look at the example to follow syntax and example code for a better understanding.
Example:
import "math/rand"
Go
// Golang Program to demonstrate// application of nested importpackage main import ( "fmt" "math/rand") func main() { // this generates & displays a // random integer value < 100 fmt.Println(rand.Int(100))}
It supports aliased imports as well. Well at times we’re just tired of writing the full name again and again in our code as it may be lengthy or boring or whatsoever and so you wish to rename it. Alias import is just that. It doesn’t rename the package but it uses the name that you mention for the package and creates an alias of that package, giving you the impression that the package name has been renamed. Consider the example for syntax and example code for a better understanding of the aliased import.
Example:
import m "math"
import f "fmt"
Go
// Golang Program to demonstrate// the application of aliased importpackage main import ( f "fmt" m "math") // Main functionfunc main() { // this assigns value // of 2^5 = 32 to var c c := m.Exp2(5) // this prints the // value stored in var c f.Println(c) }
Go supports dot imports. Dot import is something that most users haven’t heard of. It is basically a rare type of import that is mostly used for testing purposes. Testers use this kind of import in order to test whether their public structures/functions/package elements are functioning properly. Dot import provides the perks of using elements of a package without mentioning the name of the package and can be used directly. As many perks as it provides, it also brings along with it a couple of drawbacks such as namespace collisions. Refer the example for syntax and example code for a better understanding of the dot import.
Example:
import . "math"
Go
// Golang Program to demonstrate // the application of dot importpackage main import ( "fmt" . "math") func main() { // this prints the value of // 2^5 = 32 on the console fmt.Println(Exp2(5)) }
Go supports blank imports. Blank means empty. That’s right. Many times, we do not plan of all the packages we require or the blueprint of a code that we’re about to write in the future. As a result, we often import many packages that we never use in the program. Then Go arises errors as whatever we import in Go, we ought to use it. Coding is an unpredictable process, one moment we need something and in the next instance, we don’t.
But go doesn’t cope up with this inconsistency and that’s why has provided the facility of blank imports. We can import the package and not using by placing a blank. This way your program runs successfully and you can remove the blank whenever you wish to use that package. Refer code for syntax and example code for a better understanding of the blank import.
Example:
import _ "math"
Go
// PROGRAM1package main// Program to demonstrate importance of blank import import ( "fmt" "math/rand") func main() { fmt.Println("Hello Geeks")} // -------------------------------------------------------------------------------------// Program1 looks accurate and everything // seems right but the compiler will throw an// error upon building this code. Why? Because // we imported the math/rand package but// We didn't use it anywhere in the program. // That's why. The following code is a solution.//------------------------------------------------------------------------------------- // PROGRAM2package main// Program to demonstrate application of blank import import ( "fmt" _ "math/rand") func main() { fmt.Println("Hello Geeks") // This program compiles successfully and // simply prints Hello Geeks on the console.}
When we create our packages and place them in a local directory or on the cloud directory, ultimately the $GOPATH directory or within that, we find that we cannot directly import the package with its name unless you make that your $GOPATH. So then you mention a path where the custom package is available. These types of imports are called relative imports. We often use this type but may not know its name (Relative import). Refer to the example for syntax and example code for a better understanding of relative import.
Example:
import "github.com/gopherguides/greet"
Go
package main import "github.com/gopherguides/greet" // Main functionfunc main() { // The hello function is in // the mentioned directory greet.Hello() // This function simply prints // hello world on the console screen}
Just like a circle, a loop, there exists a circular import too. This means defining a package which imports a second package implicitly and defining the second package such that it imports the first package implicitly. This creates a hidden loop that is called the “import loop“. This type, too, is unknown by many and that is because Go does not support circular imports explicitly. Upon building such packages, the Go compiler throws an error raising a warning: “import cycle not allowed”. Consider the following examples to understand this better.
// First package file code. Imagine that name of first package is "first"
package first
import "second"
// Imagine that the second package's name is "second"
var a = second.b
// Assigning value of variable b from second package to a in first package
// Second package file code. Imagine that name of second package is "second"
package second
import "first"
// Imagine that the first package's name is "first"
var b = first.a
// Assigning value of variable a from first package to b in second package
Upon building any one of these packages, you will find an error like this:
> go build
can't load package: import cycle not allowed
...
Golang-Packages
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 103,
"s": 28,
"text": "Pre-requisite learning: Installing Go on Windows / Installing Go on MacOS "
},
{
"code": null,
"e": 701,
"s": 103,
"text": "Technically defining, a package is essentially a container of source code for some specific purpose. This means that the package is a capsule that holds multiple elements of drug/medicine binding them all together and protecting them in one mini shell. This capsule is easy to carry anywhere and use it as per choice, right? Yeah, that’s right. You can write thousands of lines of code, hundreds of functions, n number of operations, and much more in one package and store it so that you can just grab the package into your main file whenever you require it. Many packages come pre-built with Go. "
},
{
"code": null,
"e": 951,
"s": 701,
"text": "Packages are very essential as in all programs ranging from the most basic programs to high-level complex codes, these are used. A package ensures that no code is repeated and that the main code is as concise as possible in a well-structured manner."
},
{
"code": null,
"e": 960,
"s": 951,
"text": "Example:"
},
{
"code": null,
"e": 974,
"s": 960,
"text": "package main\n"
},
{
"code": null,
"e": 1080,
"s": 974,
"text": "The main package holds the code that is responsible to make the current program compilable and runnable. "
},
{
"code": null,
"e": 1707,
"s": 1080,
"text": "Packages, as we’ve discussed, are sweethearts that help us code in Go. Now the question is how do we use them in our program? The answer is simple: using the “import” keyword. As the name suggests, this keyword imports the specified package from the directory of $GOPATH (if no path is mentioned) or else from the mentioned directory. Importing simply means bringing the specified package from its source location to the destination code, wiz the main program. Import in Go is very important because it helps bring the packages which are super essential to run programs. This article covers various aspects of “Imports in Go”."
},
{
"code": null,
"e": 1716,
"s": 1707,
"text": "Example:"
},
{
"code": null,
"e": 1962,
"s": 1716,
"text": "import \"fmt\" --------------------------------> fmt is the name of a package\nimport \"os\" ---------------------------------> os is the name of a package\nimport \"github.com/gopherguides/greet\" ------> the underlined part is the path of the package\n"
},
{
"code": null,
"e": 2176,
"s": 1962,
"text": "Well, yes there are different types of imports, many of which are unknown to many users. Let’s discuss these types in detail. Let us consider one package: Let’s say math and watch the differences in import styles."
},
{
"code": null,
"e": 2335,
"s": 2176,
"text": "Go supports the direct import of packages by following a simple syntax. Both single and multiple packages can be imported one by one using the import keyword."
},
{
"code": null,
"e": 2344,
"s": 2335,
"text": "Example:"
},
{
"code": null,
"e": 2415,
"s": 2344,
"text": "Single:\nimport \"fmt\"\n\nMultiple one-by-one:\nimport \"fmt\"\nimport \"math\"\n"
},
{
"code": null,
"e": 2418,
"s": 2415,
"text": "Go"
},
{
"code": "// Golang program to demonstrate the // application of direct importpackage main import \"fmt\" // Main functionfunc main() { fmt.Println(\"Hello Geeks\")}",
"e": 2579,
"s": 2418,
"text": null
},
{
"code": null,
"e": 3028,
"s": 2579,
"text": "Go also supports grouped imports. This means that you don’t have to write the import keyword multiple times; instead, you can use the keyword import followed by round braces, (), and mention all the packages inside the round braces that you wish to import. This is a direct import too but the difference is that you’ve mentioned multiple packages within one import() here. Peek at the example to get an idea of the syntax of grouped import command."
},
{
"code": null,
"e": 3037,
"s": 3028,
"text": "Example:"
},
{
"code": null,
"e": 3069,
"s": 3037,
"text": "import(\n \"fmt\"\n \"math\"\n)\n"
},
{
"code": null,
"e": 3072,
"s": 3069,
"text": "Go"
},
{
"code": "// A program to demonstrate the// application of grouped importpackage main import ( \"fmt\" \"math\") // Main functionfunc main() { // math.Exp2(5) returns // the value of 2^5, wiz 32 c := math.Exp2(5) // Println is a function in fmt package // which prints value of c in a new // line on console fmt.Println(c) }",
"e": 3431,
"s": 3072,
"text": null
},
{
"code": null,
"e": 4126,
"s": 3431,
"text": "Go supports nested imports as well. Just as we hear of the name nested import, we suddenly think of the ladder if-else statements of nested loops, etc. But nested import is nothing of that sort: It’s different from those nested elements. Here nested import means, importing a sub-package from a larger package file. For instance, there are times when you only need to use one particular function from the entire package and so you do not want to import the entire package and increase your memory size of code and stuff like that, in short, you just want one sub-package. In such scenarios, we use nested import. Look at the example to follow syntax and example code for a better understanding."
},
{
"code": null,
"e": 4135,
"s": 4126,
"text": "Example:"
},
{
"code": null,
"e": 4155,
"s": 4135,
"text": "import \"math/rand\"\n"
},
{
"code": null,
"e": 4158,
"s": 4155,
"text": "Go"
},
{
"code": "// Golang Program to demonstrate// application of nested importpackage main import ( \"fmt\" \"math/rand\") func main() { // this generates & displays a // random integer value < 100 fmt.Println(rand.Int(100))}",
"e": 4386,
"s": 4158,
"text": null
},
{
"code": null,
"e": 4896,
"s": 4386,
"text": "It supports aliased imports as well. Well at times we’re just tired of writing the full name again and again in our code as it may be lengthy or boring or whatsoever and so you wish to rename it. Alias import is just that. It doesn’t rename the package but it uses the name that you mention for the package and creates an alias of that package, giving you the impression that the package name has been renamed. Consider the example for syntax and example code for a better understanding of the aliased import."
},
{
"code": null,
"e": 4905,
"s": 4896,
"text": "Example:"
},
{
"code": null,
"e": 4937,
"s": 4905,
"text": "import m \"math\"\nimport f \"fmt\"\n"
},
{
"code": null,
"e": 4940,
"s": 4937,
"text": "Go"
},
{
"code": "// Golang Program to demonstrate// the application of aliased importpackage main import ( f \"fmt\" m \"math\") // Main functionfunc main() { // this assigns value // of 2^5 = 32 to var c c := m.Exp2(5) // this prints the // value stored in var c f.Println(c) }",
"e": 5257,
"s": 4940,
"text": null
},
{
"code": null,
"e": 5887,
"s": 5257,
"text": "Go supports dot imports. Dot import is something that most users haven’t heard of. It is basically a rare type of import that is mostly used for testing purposes. Testers use this kind of import in order to test whether their public structures/functions/package elements are functioning properly. Dot import provides the perks of using elements of a package without mentioning the name of the package and can be used directly. As many perks as it provides, it also brings along with it a couple of drawbacks such as namespace collisions. Refer the example for syntax and example code for a better understanding of the dot import."
},
{
"code": null,
"e": 5896,
"s": 5887,
"text": "Example:"
},
{
"code": null,
"e": 5913,
"s": 5896,
"text": "import . \"math\"\n"
},
{
"code": null,
"e": 5916,
"s": 5913,
"text": "Go"
},
{
"code": "// Golang Program to demonstrate // the application of dot importpackage main import ( \"fmt\" . \"math\") func main() { // this prints the value of // 2^5 = 32 on the console fmt.Println(Exp2(5)) }",
"e": 6136,
"s": 5916,
"text": null
},
{
"code": null,
"e": 6572,
"s": 6136,
"text": "Go supports blank imports. Blank means empty. That’s right. Many times, we do not plan of all the packages we require or the blueprint of a code that we’re about to write in the future. As a result, we often import many packages that we never use in the program. Then Go arises errors as whatever we import in Go, we ought to use it. Coding is an unpredictable process, one moment we need something and in the next instance, we don’t. "
},
{
"code": null,
"e": 6933,
"s": 6572,
"text": "But go doesn’t cope up with this inconsistency and that’s why has provided the facility of blank imports. We can import the package and not using by placing a blank. This way your program runs successfully and you can remove the blank whenever you wish to use that package. Refer code for syntax and example code for a better understanding of the blank import."
},
{
"code": null,
"e": 6942,
"s": 6933,
"text": "Example:"
},
{
"code": null,
"e": 6959,
"s": 6942,
"text": "import _ \"math\"\n"
},
{
"code": null,
"e": 6962,
"s": 6959,
"text": "Go"
},
{
"code": "// PROGRAM1package main// Program to demonstrate importance of blank import import ( \"fmt\" \"math/rand\") func main() { fmt.Println(\"Hello Geeks\")} // -------------------------------------------------------------------------------------// Program1 looks accurate and everything // seems right but the compiler will throw an// error upon building this code. Why? Because // we imported the math/rand package but// We didn't use it anywhere in the program. // That's why. The following code is a solution.//------------------------------------------------------------------------------------- // PROGRAM2package main// Program to demonstrate application of blank import import ( \"fmt\" _ \"math/rand\") func main() { fmt.Println(\"Hello Geeks\") // This program compiles successfully and // simply prints Hello Geeks on the console.}",
"e": 7821,
"s": 6962,
"text": null
},
{
"code": null,
"e": 8343,
"s": 7821,
"text": "When we create our packages and place them in a local directory or on the cloud directory, ultimately the $GOPATH directory or within that, we find that we cannot directly import the package with its name unless you make that your $GOPATH. So then you mention a path where the custom package is available. These types of imports are called relative imports. We often use this type but may not know its name (Relative import). Refer to the example for syntax and example code for a better understanding of relative import."
},
{
"code": null,
"e": 8352,
"s": 8343,
"text": "Example:"
},
{
"code": null,
"e": 8392,
"s": 8352,
"text": "import \"github.com/gopherguides/greet\"\n"
},
{
"code": null,
"e": 8395,
"s": 8392,
"text": "Go"
},
{
"code": "package main import \"github.com/gopherguides/greet\" // Main functionfunc main() { // The hello function is in // the mentioned directory greet.Hello() // This function simply prints // hello world on the console screen}",
"e": 8637,
"s": 8395,
"text": null
},
{
"code": null,
"e": 9188,
"s": 8637,
"text": "Just like a circle, a loop, there exists a circular import too. This means defining a package which imports a second package implicitly and defining the second package such that it imports the first package implicitly. This creates a hidden loop that is called the “import loop“. This type, too, is unknown by many and that is because Go does not support circular imports explicitly. Upon building such packages, the Go compiler throws an error raising a warning: “import cycle not allowed”. Consider the following examples to understand this better."
},
{
"code": null,
"e": 9441,
"s": 9188,
"text": "// First package file code. Imagine that name of first package is \"first\"\npackage first\n\nimport \"second\"\n// Imagine that the second package's name is \"second\"\n\nvar a = second.b\n// Assigning value of variable b from second package to a in first package\n"
},
{
"code": null,
"e": 9694,
"s": 9441,
"text": "// Second package file code. Imagine that name of second package is \"second\"\npackage second\n\nimport \"first\"\n// Imagine that the first package's name is \"first\"\n\nvar b = first.a\n// Assigning value of variable a from first package to b in second package\n"
},
{
"code": null,
"e": 9830,
"s": 9694,
"text": "Upon building any one of these packages, you will find an error like this:\n> go build\ncan't load package: import cycle not allowed\n...\n"
},
{
"code": null,
"e": 9846,
"s": 9830,
"text": "Golang-Packages"
},
{
"code": null,
"e": 9858,
"s": 9846,
"text": "Go Language"
}
] |
Python unittest – assertTrue() function
|
30 Oct, 2020
assertTrue() in Python is a unittest library function that is used in unit testing to compare test value with true. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is true then assertTrue() will return true else return false.
Syntax: assertTrue(testValue, message)
Parameters: assertTrue() accepts two parameters which are listed below with explanation:
testValue: variable of boolean type which is used in the comparison by function
message: a string sentence as a message which got displayed when the test case got failed.
Listed below are two different examples illustrating the positive and negative test case for given assert function:
Example 1: Negative Test case
Python3
# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function def test_negative(self): testValue = False # error message in case if test case got failed message = "Test value is not true." # assertTrue() to check true of test value self.assertTrue( testValue, message) if __name__ == '__main__': unittest.main()
Output:
F
======================================================================
FAIL: test_negative (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "p1.py", line 11, in test_negative
self.assertTrue( testValue, message)
AssertionError: False is not true : Test value is not true.
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
Example 2: Positive Test case
Python3
# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function def test_positive(self): testValue = True # error message in case if test case got failed message = "Test value is not true." # assertTrue() to check true of test value self.assertTrue( testValue, message) if __name__ == '__main__': unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Reference: https://docs.python.org/3/library/unittest.html
kumar_satyam
Python unittest-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Oct, 2020"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "assertTrue() in Python is a unittest library function that is used in unit testing to compare test value with true. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is true then assertTrue() will return true else return false."
},
{
"code": null,
"e": 372,
"s": 332,
"text": "Syntax: assertTrue(testValue, message) "
},
{
"code": null,
"e": 461,
"s": 372,
"text": "Parameters: assertTrue() accepts two parameters which are listed below with explanation:"
},
{
"code": null,
"e": 542,
"s": 461,
"text": "testValue: variable of boolean type which is used in the comparison by function"
},
{
"code": null,
"e": 633,
"s": 542,
"text": "message: a string sentence as a message which got displayed when the test case got failed."
},
{
"code": null,
"e": 749,
"s": 633,
"text": "Listed below are two different examples illustrating the positive and negative test case for given assert function:"
},
{
"code": null,
"e": 779,
"s": 749,
"text": "Example 1: Negative Test case"
},
{
"code": null,
"e": 787,
"s": 779,
"text": "Python3"
},
{
"code": "# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function def test_negative(self): testValue = False # error message in case if test case got failed message = \"Test value is not true.\" # assertTrue() to check true of test value self.assertTrue( testValue, message) if __name__ == '__main__': unittest.main()",
"e": 1173,
"s": 787,
"text": null
},
{
"code": null,
"e": 1181,
"s": 1173,
"text": "Output:"
},
{
"code": null,
"e": 1673,
"s": 1181,
"text": "F\n======================================================================\nFAIL: test_negative (__main__.TestStringMethods)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"p1.py\", line 11, in test_negative\n self.assertTrue( testValue, message)\nAssertionError: False is not true : Test value is not true.\n\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nFAILED (failures=1)\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 1703,
"s": 1673,
"text": "Example 2: Positive Test case"
},
{
"code": null,
"e": 1711,
"s": 1703,
"text": "Python3"
},
{
"code": "# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function def test_positive(self): testValue = True # error message in case if test case got failed message = \"Test value is not true.\" # assertTrue() to check true of test value self.assertTrue( testValue, message) if __name__ == '__main__': unittest.main()",
"e": 2096,
"s": 1711,
"text": null
},
{
"code": null,
"e": 2104,
"s": 2096,
"text": "Output:"
},
{
"code": null,
"e": 2209,
"s": 2104,
"text": ".\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 2268,
"s": 2209,
"text": "Reference: https://docs.python.org/3/library/unittest.html"
},
{
"code": null,
"e": 2281,
"s": 2268,
"text": "kumar_satyam"
},
{
"code": null,
"e": 2305,
"s": 2281,
"text": "Python unittest-library"
},
{
"code": null,
"e": 2312,
"s": 2305,
"text": "Python"
},
{
"code": null,
"e": 2410,
"s": 2312,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2428,
"s": 2410,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2470,
"s": 2428,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2492,
"s": 2470,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2527,
"s": 2492,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2553,
"s": 2527,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2585,
"s": 2553,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2614,
"s": 2585,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2644,
"s": 2614,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2671,
"s": 2644,
"text": "Python Classes and Objects"
}
] |
Scala Iterator seq() method with example
|
28 May, 2019
The seq() method belongs to the concrete value members of the class Iterable. It is helpful in visualizing the sequential view of the stated collection. It has a time complexity of O(1).
Method Definition:def seq: Iterator[A]
def seq: Iterator[A]
Return Type:It returns a sequential view of the iterator.
Example :
// Scala program of seq()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Declaring an iterator val iter = Iterator(3, 4, 5, 6, 7) // Applying seq method in // for loop for(n<-iter.seq) { // Displays output println(n) } }}
3
4
5
6
7
Here, a sequential view of the stated iterator is returned by the seq method of Scala.Example :
// Scala program of seq()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Declaring an iterator val iter = Iterator(8, 9, 10, 11) // Applying seq method val result = iter.seq // Displays output println(result) }}
non-empty iterator
Here, a non-empty iterator is returned.
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 May, 2019"
},
{
"code": null,
"e": 215,
"s": 28,
"text": "The seq() method belongs to the concrete value members of the class Iterable. It is helpful in visualizing the sequential view of the stated collection. It has a time complexity of O(1)."
},
{
"code": null,
"e": 255,
"s": 215,
"text": "Method Definition:def seq: Iterator[A]\n"
},
{
"code": null,
"e": 277,
"s": 255,
"text": "def seq: Iterator[A]\n"
},
{
"code": null,
"e": 335,
"s": 277,
"text": "Return Type:It returns a sequential view of the iterator."
},
{
"code": null,
"e": 345,
"s": 335,
"text": "Example :"
},
{
"code": "// Scala program of seq()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Declaring an iterator val iter = Iterator(3, 4, 5, 6, 7) // Applying seq method in // for loop for(n<-iter.seq) { // Displays output println(n) } }}",
"e": 728,
"s": 345,
"text": null
},
{
"code": null,
"e": 739,
"s": 728,
"text": "3\n4\n5\n6\n7\n"
},
{
"code": null,
"e": 835,
"s": 739,
"text": "Here, a sequential view of the stated iterator is returned by the seq method of Scala.Example :"
},
{
"code": "// Scala program of seq()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Declaring an iterator val iter = Iterator(8, 9, 10, 11) // Applying seq method val result = iter.seq // Displays output println(result) }}",
"e": 1178,
"s": 835,
"text": null
},
{
"code": null,
"e": 1198,
"s": 1178,
"text": "non-empty iterator\n"
},
{
"code": null,
"e": 1238,
"s": 1198,
"text": "Here, a non-empty iterator is returned."
},
{
"code": null,
"e": 1244,
"s": 1238,
"text": "Scala"
},
{
"code": null,
"e": 1257,
"s": 1244,
"text": "Scala-Method"
},
{
"code": null,
"e": 1263,
"s": 1257,
"text": "Scala"
}
] |
Different Ways to Convert java.util.Date to java.time.LocalDate in Java
|
07 Jan, 2021
Prior to Java 8 for handling time and dates we had Date, Calendar, TimeStamp (java.util) but there were several performance issues as well as some methods and classes were deprecated, so Java 8 introduced some new concepts Date and Time APIs’ (also known as Joda time APIs’) present in java.time package.
Java 7: Date, Calendar, TimeStamp present inside java.util package.
Java 8: Time Date APIs’ present inside the java.time package.
Different ways to Convert java.util.Date to java.time.LocalDate:
Using Instance and ZonedDateTimeUsing Instant and Date.getTime()Using ofInstant() and ZoneId.systemDefault()
Using Instance and ZonedDateTime
Using Instant and Date.getTime()
Using ofInstant() and ZoneId.systemDefault()
Method 1: Using Instance and ZonedDateTime
Approach:
First we will convert the date object to an instant object.
Every instant object is associated with the zoneId so we need to give the zoneId.
At last we will convert it into LocalDate object.
Example:
In this program, we will convert the date object into instant using toInstant() method which returns instant object and takes no parameters.
Now we need to assign zoneId to it using atZone() method in this we need to pass the zone Id as a parameter for default we can use ZoneId.systemDefault().
At last, we will convert it into a LocalDate object using the toLocalDate() method.
Syntax:
date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
Java
// Java program to convert java.util.Date to// java.time.LocalDate// Using Instance and ZonedDateTime import java.io.*;import java.time.*;import java.util.Date; class GFG { public static void main(String[] args) { // first create date object Date current = new Date(); // first convert the date object to instant using // toInstant() then add zoneId using .atZone() at // last convert into localDate using toLocalDate() LocalDate local = current.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate(); // printing the local date object System.out.println(local); }}
2020-12-21
Method 2: Using Instant and Date.getTime()
This approach is almost similar to the first one the only difference will be the way the instant object will be created.
Here we will use Instant.ofEpochMilli() method, it takes date as an argument.
After that again we will use atZone() method for adding the ZoneId followed by toLocalDate() method to get the LocalDate Object.
Syntax:
Instant.ofEpochMilli(date.getTime()) .atZone(ZoneId.systemDefault()).toLocalDate()
Java
// Java program to convert java.util.Date to// java.time.LocalDate// Using Instant and Date.getTime() import java.io.*;import java.time.*;import java.util.*; class GFG { public static void main(String[] args) { // first create date object Date current = new Date(); // first create instant object using // Instant.ofEpochMilli(date.getTime()) than add // zoneId using .atZone() at last convert into // localDate using toLocalDate() LocalDate local = Instant.ofEpochMilli(current.getTime()) .atZone(ZoneId.systemDefault()) .toLocalDate(); // printing the local date object System.out.println(local); }}
2020-12-21
Method 3: Using ofInstant() and ZoneId.systemDefault()
It is the easiest approach we will use Java 9’s ofInstant() method of LocalDate class it takes two parameters.
A first parameter is an instant object of date and the second is ZoneId.
Here in the first argument, we will use toInstant() method to get the instant object and for the second argument we will use ZoneId.systemDefault().
Syntax
LocalDate.ofInstant(date.toInstant(), ZoneId.systemDefault());
Java
// Java program to convert java.util.Date to// java.time.LocalDate// Using ofInstant() and ZoneId.systemDefault() import java.io.*;import java.time.*;import java.util.*; class GFG { public static void main(String[] args) { // first create date object Date current = new Date(); // use ofInstant method of LocalDate class // pass instant object and zone id as parameters LocalDate local = LocalDate.ofInstant( current.toInstant(), ZoneId.systemDefault()); // printing the local date object System.out.println(local); }}
2020-12-21
Java-Date-Time
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jan, 2021"
},
{
"code": null,
"e": 333,
"s": 28,
"text": "Prior to Java 8 for handling time and dates we had Date, Calendar, TimeStamp (java.util) but there were several performance issues as well as some methods and classes were deprecated, so Java 8 introduced some new concepts Date and Time APIs’ (also known as Joda time APIs’) present in java.time package."
},
{
"code": null,
"e": 401,
"s": 333,
"text": "Java 7: Date, Calendar, TimeStamp present inside java.util package."
},
{
"code": null,
"e": 463,
"s": 401,
"text": "Java 8: Time Date APIs’ present inside the java.time package."
},
{
"code": null,
"e": 528,
"s": 463,
"text": "Different ways to Convert java.util.Date to java.time.LocalDate:"
},
{
"code": null,
"e": 637,
"s": 528,
"text": "Using Instance and ZonedDateTimeUsing Instant and Date.getTime()Using ofInstant() and ZoneId.systemDefault()"
},
{
"code": null,
"e": 670,
"s": 637,
"text": "Using Instance and ZonedDateTime"
},
{
"code": null,
"e": 703,
"s": 670,
"text": "Using Instant and Date.getTime()"
},
{
"code": null,
"e": 748,
"s": 703,
"text": "Using ofInstant() and ZoneId.systemDefault()"
},
{
"code": null,
"e": 791,
"s": 748,
"text": "Method 1: Using Instance and ZonedDateTime"
},
{
"code": null,
"e": 801,
"s": 791,
"text": "Approach:"
},
{
"code": null,
"e": 861,
"s": 801,
"text": "First we will convert the date object to an instant object."
},
{
"code": null,
"e": 943,
"s": 861,
"text": "Every instant object is associated with the zoneId so we need to give the zoneId."
},
{
"code": null,
"e": 993,
"s": 943,
"text": "At last we will convert it into LocalDate object."
},
{
"code": null,
"e": 1002,
"s": 993,
"text": "Example:"
},
{
"code": null,
"e": 1144,
"s": 1002,
"text": "In this program, we will convert the date object into instant using toInstant() method which returns instant object and takes no parameters. "
},
{
"code": null,
"e": 1300,
"s": 1144,
"text": "Now we need to assign zoneId to it using atZone() method in this we need to pass the zone Id as a parameter for default we can use ZoneId.systemDefault(). "
},
{
"code": null,
"e": 1384,
"s": 1300,
"text": "At last, we will convert it into a LocalDate object using the toLocalDate() method."
},
{
"code": null,
"e": 1392,
"s": 1384,
"text": "Syntax:"
},
{
"code": null,
"e": 1454,
"s": 1392,
"text": "date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()"
},
{
"code": null,
"e": 1459,
"s": 1454,
"text": "Java"
},
{
"code": "// Java program to convert java.util.Date to// java.time.LocalDate// Using Instance and ZonedDateTime import java.io.*;import java.time.*;import java.util.Date; class GFG { public static void main(String[] args) { // first create date object Date current = new Date(); // first convert the date object to instant using // toInstant() then add zoneId using .atZone() at // last convert into localDate using toLocalDate() LocalDate local = current.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate(); // printing the local date object System.out.println(local); }}",
"e": 2139,
"s": 1459,
"text": null
},
{
"code": null,
"e": 2150,
"s": 2139,
"text": "2020-12-21"
},
{
"code": null,
"e": 2193,
"s": 2150,
"text": "Method 2: Using Instant and Date.getTime()"
},
{
"code": null,
"e": 2314,
"s": 2193,
"text": "This approach is almost similar to the first one the only difference will be the way the instant object will be created."
},
{
"code": null,
"e": 2393,
"s": 2314,
"text": "Here we will use Instant.ofEpochMilli() method, it takes date as an argument. "
},
{
"code": null,
"e": 2522,
"s": 2393,
"text": "After that again we will use atZone() method for adding the ZoneId followed by toLocalDate() method to get the LocalDate Object."
},
{
"code": null,
"e": 2530,
"s": 2522,
"text": "Syntax:"
},
{
"code": null,
"e": 2613,
"s": 2530,
"text": "Instant.ofEpochMilli(date.getTime()) .atZone(ZoneId.systemDefault()).toLocalDate()"
},
{
"code": null,
"e": 2618,
"s": 2613,
"text": "Java"
},
{
"code": "// Java program to convert java.util.Date to// java.time.LocalDate// Using Instant and Date.getTime() import java.io.*;import java.time.*;import java.util.*; class GFG { public static void main(String[] args) { // first create date object Date current = new Date(); // first create instant object using // Instant.ofEpochMilli(date.getTime()) than add // zoneId using .atZone() at last convert into // localDate using toLocalDate() LocalDate local = Instant.ofEpochMilli(current.getTime()) .atZone(ZoneId.systemDefault()) .toLocalDate(); // printing the local date object System.out.println(local); }}",
"e": 3334,
"s": 2618,
"text": null
},
{
"code": null,
"e": 3345,
"s": 3334,
"text": "2020-12-21"
},
{
"code": null,
"e": 3400,
"s": 3345,
"text": "Method 3: Using ofInstant() and ZoneId.systemDefault()"
},
{
"code": null,
"e": 3512,
"s": 3400,
"text": "It is the easiest approach we will use Java 9’s ofInstant() method of LocalDate class it takes two parameters. "
},
{
"code": null,
"e": 3586,
"s": 3512,
"text": "A first parameter is an instant object of date and the second is ZoneId. "
},
{
"code": null,
"e": 3735,
"s": 3586,
"text": "Here in the first argument, we will use toInstant() method to get the instant object and for the second argument we will use ZoneId.systemDefault()."
},
{
"code": null,
"e": 3742,
"s": 3735,
"text": "Syntax"
},
{
"code": null,
"e": 3805,
"s": 3742,
"text": "LocalDate.ofInstant(date.toInstant(), ZoneId.systemDefault());"
},
{
"code": null,
"e": 3810,
"s": 3805,
"text": "Java"
},
{
"code": "// Java program to convert java.util.Date to// java.time.LocalDate// Using ofInstant() and ZoneId.systemDefault() import java.io.*;import java.time.*;import java.util.*; class GFG { public static void main(String[] args) { // first create date object Date current = new Date(); // use ofInstant method of LocalDate class // pass instant object and zone id as parameters LocalDate local = LocalDate.ofInstant( current.toInstant(), ZoneId.systemDefault()); // printing the local date object System.out.println(local); }}",
"e": 4409,
"s": 3810,
"text": null
},
{
"code": null,
"e": 4420,
"s": 4409,
"text": "2020-12-21"
},
{
"code": null,
"e": 4435,
"s": 4420,
"text": "Java-Date-Time"
},
{
"code": null,
"e": 4442,
"s": 4435,
"text": "Picked"
},
{
"code": null,
"e": 4447,
"s": 4442,
"text": "Java"
},
{
"code": null,
"e": 4461,
"s": 4447,
"text": "Java Programs"
},
{
"code": null,
"e": 4466,
"s": 4461,
"text": "Java"
}
] |
How to Apply One Listener to Multiple Buttons in Android?
|
06 Jun, 2021
In this article we are going to write a shortcode for applying click events over different buttons, rather than writing different methods for different buttons, we are going to build only a single method that is onClick() for all buttons present and by using the concept of switch case we can perform different activities over different buttons. Now, without wasting further time let’s look at the implementation.
In this article, we will develop a sample application that will contain three buttons and by clicking those three buttons we can perform different actions by using only a single onClick() method. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
Now it’s time to design the layout of the application. So for that go to the app >res > layout > activity_main.xml and paste the below-written code in the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/root_layout" tools:context=".MainActivity"> <!--add three buttons in layout--> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="220px" android:text="Button 1" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/button" android:layout_centerHorizontal="true" android:text="Button 2" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/button2" android:layout_centerHorizontal="true" android:text="Button 3" /> </RelativeLayout>
Step 3: Working with the MainActivity.java file
Go to the app > java > package name > MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { // creating three buttons // by the of btn1, btn2,btn3 Button btn1, btn2 ,btn3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // connecting buttons with the // layout using findViewById() btn1= findViewById(R.id.button); btn2= findViewById(R.id.button2); btn3= findViewById(R.id.button3); // apply setOnClickListener over buttons btn1.setOnClickListener(this); btn2.setOnClickListener(this); btn3.setOnClickListener(this); } // common onClick() for all buttons @Override public void onClick(View v) { switch (v.getId()){ // cases applied over different buttons case R.id.button: // Toast message appears when button pressed Toast.makeText(this, "button1 pressed", Toast.LENGTH_SHORT).show(); break; case R.id.button2: Toast.makeText(this, "button2 pressed", Toast.LENGTH_SHORT).show(); break; case R.id.button3: Toast.makeText(this, "button3 pressed", Toast.LENGTH_SHORT).show(); break; } }}
That’s all, now the application is ready to install on the device. Here is what the output of the application looks like.
Output:
Android
Java
Java
Android
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": 442,
"s": 28,
"text": "In this article we are going to write a shortcode for applying click events over different buttons, rather than writing different methods for different buttons, we are going to build only a single method that is onClick() for all buttons present and by using the concept of switch case we can perform different activities over different buttons. Now, without wasting further time let’s look at the implementation."
},
{
"code": null,
"e": 804,
"s": 442,
"text": "In this article, we will develop a sample application that will contain three buttons and by clicking those three buttons we can perform different actions by using only a single onClick() method. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language."
},
{
"code": null,
"e": 833,
"s": 804,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 995,
"s": 833,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 1043,
"s": 995,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1222,
"s": 1043,
"text": "Now it’s time to design the layout of the application. So for that go to the app >res > layout > activity_main.xml and paste the below-written code in the activity_main.xml file."
},
{
"code": null,
"e": 1226,
"s": 1222,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/root_layout\" tools:context=\".MainActivity\"> <!--add three buttons in layout--> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"220px\" android:text=\"Button 1\" /> <Button android:id=\"@+id/button2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/button\" android:layout_centerHorizontal=\"true\" android:text=\"Button 2\" /> <Button android:id=\"@+id/button3\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/button2\" android:layout_centerHorizontal=\"true\" android:text=\"Button 3\" /> </RelativeLayout>",
"e": 2420,
"s": 1226,
"text": null
},
{
"code": null,
"e": 2468,
"s": 2420,
"text": "Step 3: Working with the MainActivity.java file"
},
{
"code": null,
"e": 2686,
"s": 2468,
"text": "Go to the app > java > package name > MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 2691,
"s": 2686,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { // creating three buttons // by the of btn1, btn2,btn3 Button btn1, btn2 ,btn3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // connecting buttons with the // layout using findViewById() btn1= findViewById(R.id.button); btn2= findViewById(R.id.button2); btn3= findViewById(R.id.button3); // apply setOnClickListener over buttons btn1.setOnClickListener(this); btn2.setOnClickListener(this); btn3.setOnClickListener(this); } // common onClick() for all buttons @Override public void onClick(View v) { switch (v.getId()){ // cases applied over different buttons case R.id.button: // Toast message appears when button pressed Toast.makeText(this, \"button1 pressed\", Toast.LENGTH_SHORT).show(); break; case R.id.button2: Toast.makeText(this, \"button2 pressed\", Toast.LENGTH_SHORT).show(); break; case R.id.button3: Toast.makeText(this, \"button3 pressed\", Toast.LENGTH_SHORT).show(); break; } }}",
"e": 4247,
"s": 2691,
"text": null
},
{
"code": null,
"e": 4369,
"s": 4247,
"text": "That’s all, now the application is ready to install on the device. Here is what the output of the application looks like."
},
{
"code": null,
"e": 4377,
"s": 4369,
"text": "Output:"
},
{
"code": null,
"e": 4385,
"s": 4377,
"text": "Android"
},
{
"code": null,
"e": 4390,
"s": 4385,
"text": "Java"
},
{
"code": null,
"e": 4395,
"s": 4390,
"text": "Java"
},
{
"code": null,
"e": 4403,
"s": 4395,
"text": "Android"
}
] |
Print all odd nodes of Binary Search Tree in C++
|
In this problem, we are given a binary search tree and we have to print all the nodes that have odd values.
The binary search tree is a special type of tree that possess the following properties −
The left subtree always has values smaller than the root node.
The left subtree always has values smaller than the root node.
The right subtree always has values larger than the root node.
The right subtree always has values larger than the root node.
Both the left and right subtree should also follow the above two properties.
Both the left and right subtree should also follow the above two properties.
Let’s take an example to understand the problem −
Output − 1 3 9
To solve this problem, a simple approach would be traversing the tree. On traversal, we will check the value of each node of the tree. If the node is odd print it otherwise more to the next node of the tree.
The complexity of the program will depend on the number of nodes. Time complexity: O(n).
The below program shows the implementation of our solution −
Live Demo
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
struct Node *left, *right;
};
Node* newNode(int item){
Node* temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
Node* insertNode(Node* node, int key){
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insertNode(node->left, key);
else
node->right = insertNode(node->right, key);
return node;
}
void printOddNodes(Node* root){
if (root != NULL) {
printOddNodes(root->left);
if (root->key % 2 != 0)
cout<<root->key<<"\t";
printOddNodes(root->right);
}
}
int main(){
Node* root = NULL;
root = insertNode(root, 6);
root = insertNode(root, 3);
root = insertNode(root, 1);
root = insertNode(root, 4);
root = insertNode(root, 9);
root = insertNode(root, 8);
root = insertNode(root, 10);
cout<<"Nodes with odd values are :\n";
printOddNodes(root);
return 0;
}
Nodes with odd values are −
1 3 9
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "In this problem, we are given a binary search tree and we have to print all the nodes that have odd values."
},
{
"code": null,
"e": 1259,
"s": 1170,
"text": "The binary search tree is a special type of tree that possess the following properties −"
},
{
"code": null,
"e": 1322,
"s": 1259,
"text": "The left subtree always has values smaller than the root node."
},
{
"code": null,
"e": 1385,
"s": 1322,
"text": "The left subtree always has values smaller than the root node."
},
{
"code": null,
"e": 1448,
"s": 1385,
"text": "The right subtree always has values larger than the root node."
},
{
"code": null,
"e": 1511,
"s": 1448,
"text": "The right subtree always has values larger than the root node."
},
{
"code": null,
"e": 1588,
"s": 1511,
"text": "Both the left and right subtree should also follow the above two properties."
},
{
"code": null,
"e": 1665,
"s": 1588,
"text": "Both the left and right subtree should also follow the above two properties."
},
{
"code": null,
"e": 1715,
"s": 1665,
"text": "Let’s take an example to understand the problem −"
},
{
"code": null,
"e": 1730,
"s": 1715,
"text": "Output − 1 3 9"
},
{
"code": null,
"e": 1938,
"s": 1730,
"text": "To solve this problem, a simple approach would be traversing the tree. On traversal, we will check the value of each node of the tree. If the node is odd print it otherwise more to the next node of the tree."
},
{
"code": null,
"e": 2027,
"s": 1938,
"text": "The complexity of the program will depend on the number of nodes. Time complexity: O(n)."
},
{
"code": null,
"e": 2088,
"s": 2027,
"text": "The below program shows the implementation of our solution −"
},
{
"code": null,
"e": 2099,
"s": 2088,
"text": " Live Demo"
},
{
"code": null,
"e": 3089,
"s": 2099,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct Node {\n int key;\n struct Node *left, *right;\n};\nNode* newNode(int item){\n Node* temp = new Node;\n temp->key = item;\n temp->left = temp->right = NULL;\n return temp;\n}\nNode* insertNode(Node* node, int key){\n if (node == NULL)\n return newNode(key);\n if (key < node->key)\n node->left = insertNode(node->left, key);\n else\n node->right = insertNode(node->right, key);\n return node;\n}\nvoid printOddNodes(Node* root){\n if (root != NULL) {\n printOddNodes(root->left);\n if (root->key % 2 != 0)\n cout<<root->key<<\"\\t\";\n printOddNodes(root->right);\n }\n}\nint main(){\n Node* root = NULL;\n root = insertNode(root, 6);\n root = insertNode(root, 3);\n root = insertNode(root, 1);\n root = insertNode(root, 4);\n root = insertNode(root, 9);\n root = insertNode(root, 8);\n root = insertNode(root, 10);\n cout<<\"Nodes with odd values are :\\n\";\n printOddNodes(root);\n return 0;\n}"
},
{
"code": null,
"e": 3117,
"s": 3089,
"text": "Nodes with odd values are −"
},
{
"code": null,
"e": 3123,
"s": 3117,
"text": "1 3 9"
}
] |
How to convert a Double array to a String array in java?
|
You can convert a double array to a string using the toString() method. To convert a double array to a string array, convert each element of it to string and populate the String array with them.
Live Demo
import java.util.Arrays;
public class DoubleArrayToString {
public static void main(String args[]) {
Double[] arr = {12.4, 35.2, 25.6, 98.7, 56.4};
int size = arr.length;
String[] str = new String[size];
for(int i=0; i<size; i++) {
str[i] = arr[i].toString();
System.out.println(str[i]);
}
}
}
12.4
35.2
25.6
98.7
56.4
|
[
{
"code": null,
"e": 1257,
"s": 1062,
"text": "You can convert a double array to a string using the toString() method. To convert a double array to a string array, convert each element of it to string and populate the String array with them."
},
{
"code": null,
"e": 1267,
"s": 1257,
"text": "Live Demo"
},
{
"code": null,
"e": 1620,
"s": 1267,
"text": "import java.util.Arrays;\n\npublic class DoubleArrayToString {\n public static void main(String args[]) {\n Double[] arr = {12.4, 35.2, 25.6, 98.7, 56.4};\n int size = arr.length;\n String[] str = new String[size];\n \n for(int i=0; i<size; i++) {\n str[i] = arr[i].toString();\n System.out.println(str[i]);\n }\n }\n}"
},
{
"code": null,
"e": 1645,
"s": 1620,
"text": "12.4\n35.2\n25.6\n98.7\n56.4"
}
] |
Multithreaded Priority Queue in Python - GeeksforGeeks
|
31 Dec, 2020
The Queue module is primarily used to manage to process large amounts of data on multiple threads. It supports the creation of a new queue object that can take a distinct number of items.The get() and put() methods are used to add or remove items from a queue respectively. Below is the list of operations that are used to manage Queue:
get(): It is used to add an item to a queue.
put(): It is used to remove an item from a queue.
qsize(): It is used to find the number of items in a queue.
empty(): It returns a boolean value depending upon whether the queue is empty or not.
full(): It returns a boolean value depending upon whether the queue is full or not.
A Priority Queue is an extension of the queue with the following properties:
An element with high priority is dequeued before an element with low priority.
If two elements have the same priority, they are served according to their order in the queue.
Below is a code example explaining the process of creating multi-threaded priority queue:
Example:
import queueimport threadingimport time thread_exit_Flag = 0 class sample_Thread (threading.Thread): def __init__(self, threadID, name, q): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.q = q def run(self): print ("initializing " + self.name) process_data(self.name, self.q) print ("Exiting " + self.name) # helper function to process data def process_data(threadName, q): while not thread_exit_Flag: queueLock.acquire() if not workQueue.empty(): data = q.get() queueLock.release() print ("% s processing % s" % (threadName, data)) else: queueLock.release() time.sleep(1) thread_list = ["Thread-1", "Thread-2", "Thread-3"]name_list = ["A", "B", "C", "D", "E"]queueLock = threading.Lock()workQueue = queue.Queue(10)threads = []threadID = 1 # Create new threadsfor thread_name in thread_list: thread = sample_Thread(threadID, thread_name, workQueue) thread.start() threads.append(thread) threadID += 1 # Fill the queuequeueLock.acquire()for items in name_list: workQueue.put(items) queueLock.release() # Wait for the queue to emptywhile not workQueue.empty(): pass # Notify threads it's time to exitthread_exit_Flag = 1 # Wait for all threads to completefor t in threads: t.join()print ("Exit Main Thread")
Output:
initializing Thread-1
initializing Thread-2initializing Thread-3
Thread-2 processing AThread-3 processing B
Thread-3 processing C
Thread-3 processing D
Thread-2 processing E
Exiting Thread-2
Exiting Thread-1
Exiting Thread-3
Exit Main Thread
Note: The output may differ depending upon the device specifications and processing power.
Python DSA-exercises
Python-threading
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
Factory method design pattern in Java
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n31 Dec, 2020"
},
{
"code": null,
"e": 24238,
"s": 23901,
"text": "The Queue module is primarily used to manage to process large amounts of data on multiple threads. It supports the creation of a new queue object that can take a distinct number of items.The get() and put() methods are used to add or remove items from a queue respectively. Below is the list of operations that are used to manage Queue:"
},
{
"code": null,
"e": 24283,
"s": 24238,
"text": "get(): It is used to add an item to a queue."
},
{
"code": null,
"e": 24333,
"s": 24283,
"text": "put(): It is used to remove an item from a queue."
},
{
"code": null,
"e": 24393,
"s": 24333,
"text": "qsize(): It is used to find the number of items in a queue."
},
{
"code": null,
"e": 24479,
"s": 24393,
"text": "empty(): It returns a boolean value depending upon whether the queue is empty or not."
},
{
"code": null,
"e": 24563,
"s": 24479,
"text": "full(): It returns a boolean value depending upon whether the queue is full or not."
},
{
"code": null,
"e": 24640,
"s": 24563,
"text": "A Priority Queue is an extension of the queue with the following properties:"
},
{
"code": null,
"e": 24719,
"s": 24640,
"text": "An element with high priority is dequeued before an element with low priority."
},
{
"code": null,
"e": 24814,
"s": 24719,
"text": "If two elements have the same priority, they are served according to their order in the queue."
},
{
"code": null,
"e": 24904,
"s": 24814,
"text": "Below is a code example explaining the process of creating multi-threaded priority queue:"
},
{
"code": null,
"e": 24913,
"s": 24904,
"text": "Example:"
},
{
"code": "import queueimport threadingimport time thread_exit_Flag = 0 class sample_Thread (threading.Thread): def __init__(self, threadID, name, q): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.q = q def run(self): print (\"initializing \" + self.name) process_data(self.name, self.q) print (\"Exiting \" + self.name) # helper function to process data def process_data(threadName, q): while not thread_exit_Flag: queueLock.acquire() if not workQueue.empty(): data = q.get() queueLock.release() print (\"% s processing % s\" % (threadName, data)) else: queueLock.release() time.sleep(1) thread_list = [\"Thread-1\", \"Thread-2\", \"Thread-3\"]name_list = [\"A\", \"B\", \"C\", \"D\", \"E\"]queueLock = threading.Lock()workQueue = queue.Queue(10)threads = []threadID = 1 # Create new threadsfor thread_name in thread_list: thread = sample_Thread(threadID, thread_name, workQueue) thread.start() threads.append(thread) threadID += 1 # Fill the queuequeueLock.acquire()for items in name_list: workQueue.put(items) queueLock.release() # Wait for the queue to emptywhile not workQueue.empty(): pass # Notify threads it's time to exitthread_exit_Flag = 1 # Wait for all threads to completefor t in threads: t.join()print (\"Exit Main Thread\")",
"e": 26278,
"s": 24913,
"text": null
},
{
"code": null,
"e": 26286,
"s": 26278,
"text": "Output:"
},
{
"code": null,
"e": 26530,
"s": 26286,
"text": "initializing Thread-1\ninitializing Thread-2initializing Thread-3\n\nThread-2 processing AThread-3 processing B\n\nThread-3 processing C\nThread-3 processing D\nThread-2 processing E\nExiting Thread-2\nExiting Thread-1\nExiting Thread-3\nExit Main Thread"
},
{
"code": null,
"e": 26621,
"s": 26530,
"text": "Note: The output may differ depending upon the device specifications and processing power."
},
{
"code": null,
"e": 26642,
"s": 26621,
"text": "Python DSA-exercises"
},
{
"code": null,
"e": 26659,
"s": 26642,
"text": "Python-threading"
},
{
"code": null,
"e": 26666,
"s": 26659,
"text": "Python"
},
{
"code": null,
"e": 26682,
"s": 26666,
"text": "Write From Home"
},
{
"code": null,
"e": 26780,
"s": 26682,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26789,
"s": 26780,
"text": "Comments"
},
{
"code": null,
"e": 26802,
"s": 26789,
"text": "Old Comments"
},
{
"code": null,
"e": 26834,
"s": 26802,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26890,
"s": 26834,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26932,
"s": 26890,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26974,
"s": 26932,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27010,
"s": 26974,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27046,
"s": 27010,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 27062,
"s": 27046,
"text": "Python infinity"
},
{
"code": null,
"e": 27123,
"s": 27062,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27159,
"s": 27123,
"text": "Matplotlib.pyplot.title() in Python"
}
] |
How to Handle Cyclical Data in Machine Learning | by Dario Radečić | Towards Data Science
|
Today we’ll look at a common but poorly understood topic in data science — cyclical data. It’s a part of many datasets and is easily spottable — date information is the most common form. There are plenty of approaches to encode date information to something machine-learning-friendly, but some are better than others.
Here’s how I was taught about dealing with date values — treat them as categorical. Different months/days/hours can be treated as individual categories, so to encode them, one can create a bunch of dummy variables. For example, when dealing with monthly data, we can make 11 dummy columns (one-hot) that take the form of Is_January, Is_February, and so on, where only one column can have a non-zero value for a row.
That’s just wrong.
Sure, you can do that, and a machine learning model wouldn’t complain, but it doesn’t mean it’s the right approach. Time data is cyclical, as one hour has 60 minutes, and one day has 24 hours. When an hour completes, the next one starts counting minutes from zero.
It makes the 1st and 2nd minute of an hour strongly connected, but it also makes the 59th and 1st minute connected, as there’s only one minute difference, not 59 as a model would assume.
And that’s the behavior we want. The next section will make the previous points more clear.
We need a dataset with some date or other cyclical attributes — that’s obvious. A quick Kaggle search resulted in this Hourly Energy Consumption dataset, of which we’ll use the first AEP_hourly.csv file. It’s a couple of MB in size, so download it to your machine.
The first couple of rows look like this, once loaded with Pandas:
import pandas as pddf = pd.read_csv('data/AEP_hourly.csv.zip')df.head()
Great — we have some date information, but is it an actual date or a string?
df.dtypes
Just as expected, so let’s make a conversion. We’ll also extract the hour information from the date, as that’s what we’re dealing with.
df['Datetime'] = pd.to_datetime(df['Datetime'])df['Hour'] = df['Datetime'].dt.hourdf.head()
Things are much better now. Let’s isolate the last week’s worth of data (the last 168 records) to visualize why one-hot encoding isn’t a good thing to do.
last_week = df.iloc[-168:]import matplotlib.pyplot as pltplt.title('Individual hours', size=20)plt.plot(range(len(last_week)), last_week['Hour'])
Expected behavior. It’s a cycle that repeats seven times (7 days), and there’s a rough cut off every day after the 23rd hour. I think you can easily reason why this type of behavior isn’t optimal for cyclical data.
But what can we do about it? Luckily, a lot.
One-hot encoding wouldn’t be that wise of thing to do in this case. We’d end up with 23 additional attributes (n — 1), which is terrible for two reasons:
Massive jump in dimensionality — from 2 to 24No connectivity between attributes — hour 23 doesn’t know it’s followed by hour 0
Massive jump in dimensionality — from 2 to 24
No connectivity between attributes — hour 23 doesn’t know it’s followed by hour 0
So, what can we do?
Use a sine an cosine transformations. Here are the formulas we’ll use:
Or, in Python:
import numpy as np last_week['Sin_Hour'] = np.sin(2 * np.pi * last_week['Hour'] / max(last_week['Hour'])) last_week['Cos_Hour'] = np.cos(2 * np.pi * last_week['Hour'] / max(last_week['Hour']))
Awesome! Here’s how the last week of data now looks:
These transformations allowed us to represent time data in a more meaningful and compact way. Just take a look at the last two rows. Sine values are almost identical, but still a bit different. The same goes for every following hour, as it now follows a waveform.
That’s great, but why do we need both functions?
Let’s explore the functions graphically before I give you the answer.
Look at one graph at a time. There’s a problem. The values repeat. Just take a look at the sine function, somewhere between 24 and 48, on the x-axis. If you were to draw a straight line, it would intersect with two points for the same day. That’s not the behavior we want.
To further prove this point, here’s what happens if we draw a scatter plot of both sine and cosine columns:
That’s right; we get a perfect cycle. It only makes sense to represent cyclical data with a cycle, don’t you agree?
That’s all you should know. Let’s wrap things up in the next section.
This was relatively short and to the point article, but I still hope I managed to convince you one-hot encoding isn’t a solution for everything. Sure, it works like a charm when categorical attributes aren’t ‘connected’ in any way, but this is the go-to approach for any cyclical data.
One may argue that we introduce two new dimensions, which isn’t ideal. I agree, but two are better than 23, which resulted from a one-hot encoding approach.
Thanks for reading.
Join my private email list for more helpful insights.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Originally published at https://betterdatascience.com on October 12, 2020.
|
[
{
"code": null,
"e": 490,
"s": 172,
"text": "Today we’ll look at a common but poorly understood topic in data science — cyclical data. It’s a part of many datasets and is easily spottable — date information is the most common form. There are plenty of approaches to encode date information to something machine-learning-friendly, but some are better than others."
},
{
"code": null,
"e": 906,
"s": 490,
"text": "Here’s how I was taught about dealing with date values — treat them as categorical. Different months/days/hours can be treated as individual categories, so to encode them, one can create a bunch of dummy variables. For example, when dealing with monthly data, we can make 11 dummy columns (one-hot) that take the form of Is_January, Is_February, and so on, where only one column can have a non-zero value for a row."
},
{
"code": null,
"e": 925,
"s": 906,
"text": "That’s just wrong."
},
{
"code": null,
"e": 1190,
"s": 925,
"text": "Sure, you can do that, and a machine learning model wouldn’t complain, but it doesn’t mean it’s the right approach. Time data is cyclical, as one hour has 60 minutes, and one day has 24 hours. When an hour completes, the next one starts counting minutes from zero."
},
{
"code": null,
"e": 1377,
"s": 1190,
"text": "It makes the 1st and 2nd minute of an hour strongly connected, but it also makes the 59th and 1st minute connected, as there’s only one minute difference, not 59 as a model would assume."
},
{
"code": null,
"e": 1469,
"s": 1377,
"text": "And that’s the behavior we want. The next section will make the previous points more clear."
},
{
"code": null,
"e": 1734,
"s": 1469,
"text": "We need a dataset with some date or other cyclical attributes — that’s obvious. A quick Kaggle search resulted in this Hourly Energy Consumption dataset, of which we’ll use the first AEP_hourly.csv file. It’s a couple of MB in size, so download it to your machine."
},
{
"code": null,
"e": 1800,
"s": 1734,
"text": "The first couple of rows look like this, once loaded with Pandas:"
},
{
"code": null,
"e": 1872,
"s": 1800,
"text": "import pandas as pddf = pd.read_csv('data/AEP_hourly.csv.zip')df.head()"
},
{
"code": null,
"e": 1949,
"s": 1872,
"text": "Great — we have some date information, but is it an actual date or a string?"
},
{
"code": null,
"e": 1959,
"s": 1949,
"text": "df.dtypes"
},
{
"code": null,
"e": 2095,
"s": 1959,
"text": "Just as expected, so let’s make a conversion. We’ll also extract the hour information from the date, as that’s what we’re dealing with."
},
{
"code": null,
"e": 2187,
"s": 2095,
"text": "df['Datetime'] = pd.to_datetime(df['Datetime'])df['Hour'] = df['Datetime'].dt.hourdf.head()"
},
{
"code": null,
"e": 2342,
"s": 2187,
"text": "Things are much better now. Let’s isolate the last week’s worth of data (the last 168 records) to visualize why one-hot encoding isn’t a good thing to do."
},
{
"code": null,
"e": 2488,
"s": 2342,
"text": "last_week = df.iloc[-168:]import matplotlib.pyplot as pltplt.title('Individual hours', size=20)plt.plot(range(len(last_week)), last_week['Hour'])"
},
{
"code": null,
"e": 2703,
"s": 2488,
"text": "Expected behavior. It’s a cycle that repeats seven times (7 days), and there’s a rough cut off every day after the 23rd hour. I think you can easily reason why this type of behavior isn’t optimal for cyclical data."
},
{
"code": null,
"e": 2748,
"s": 2703,
"text": "But what can we do about it? Luckily, a lot."
},
{
"code": null,
"e": 2902,
"s": 2748,
"text": "One-hot encoding wouldn’t be that wise of thing to do in this case. We’d end up with 23 additional attributes (n — 1), which is terrible for two reasons:"
},
{
"code": null,
"e": 3029,
"s": 2902,
"text": "Massive jump in dimensionality — from 2 to 24No connectivity between attributes — hour 23 doesn’t know it’s followed by hour 0"
},
{
"code": null,
"e": 3075,
"s": 3029,
"text": "Massive jump in dimensionality — from 2 to 24"
},
{
"code": null,
"e": 3157,
"s": 3075,
"text": "No connectivity between attributes — hour 23 doesn’t know it’s followed by hour 0"
},
{
"code": null,
"e": 3177,
"s": 3157,
"text": "So, what can we do?"
},
{
"code": null,
"e": 3248,
"s": 3177,
"text": "Use a sine an cosine transformations. Here are the formulas we’ll use:"
},
{
"code": null,
"e": 3263,
"s": 3248,
"text": "Or, in Python:"
},
{
"code": null,
"e": 3456,
"s": 3263,
"text": "import numpy as np last_week['Sin_Hour'] = np.sin(2 * np.pi * last_week['Hour'] / max(last_week['Hour'])) last_week['Cos_Hour'] = np.cos(2 * np.pi * last_week['Hour'] / max(last_week['Hour']))"
},
{
"code": null,
"e": 3509,
"s": 3456,
"text": "Awesome! Here’s how the last week of data now looks:"
},
{
"code": null,
"e": 3773,
"s": 3509,
"text": "These transformations allowed us to represent time data in a more meaningful and compact way. Just take a look at the last two rows. Sine values are almost identical, but still a bit different. The same goes for every following hour, as it now follows a waveform."
},
{
"code": null,
"e": 3822,
"s": 3773,
"text": "That’s great, but why do we need both functions?"
},
{
"code": null,
"e": 3892,
"s": 3822,
"text": "Let’s explore the functions graphically before I give you the answer."
},
{
"code": null,
"e": 4165,
"s": 3892,
"text": "Look at one graph at a time. There’s a problem. The values repeat. Just take a look at the sine function, somewhere between 24 and 48, on the x-axis. If you were to draw a straight line, it would intersect with two points for the same day. That’s not the behavior we want."
},
{
"code": null,
"e": 4273,
"s": 4165,
"text": "To further prove this point, here’s what happens if we draw a scatter plot of both sine and cosine columns:"
},
{
"code": null,
"e": 4389,
"s": 4273,
"text": "That’s right; we get a perfect cycle. It only makes sense to represent cyclical data with a cycle, don’t you agree?"
},
{
"code": null,
"e": 4459,
"s": 4389,
"text": "That’s all you should know. Let’s wrap things up in the next section."
},
{
"code": null,
"e": 4745,
"s": 4459,
"text": "This was relatively short and to the point article, but I still hope I managed to convince you one-hot encoding isn’t a solution for everything. Sure, it works like a charm when categorical attributes aren’t ‘connected’ in any way, but this is the go-to approach for any cyclical data."
},
{
"code": null,
"e": 4902,
"s": 4745,
"text": "One may argue that we introduce two new dimensions, which isn’t ideal. I agree, but two are better than 23, which resulted from a one-hot encoding approach."
},
{
"code": null,
"e": 4922,
"s": 4902,
"text": "Thanks for reading."
},
{
"code": null,
"e": 4976,
"s": 4922,
"text": "Join my private email list for more helpful insights."
},
{
"code": null,
"e": 5159,
"s": 4976,
"text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you."
},
{
"code": null,
"e": 5170,
"s": 5159,
"text": "medium.com"
}
] |
Print current day and time using HTML and JavaScript - GeeksforGeeks
|
16 Apr, 2019
The task is to print the system’s current day and time in the following format(Time in hours, minutes and milliseconds).
Use getDay() function to create an array of days in a week. It returns a number of day like 0 for Sunday, 1 for Monday and so on). Convert it into AM or PM using ternary operator.
Use getHours() method to get the hour value between 0 to 23. It returns an integer value.
Minutes and milliseconds were printed using getMinutes() and getMilliseconds() functions respectively.
Example:
<!DOCTYPE html><html> <head> <title> print current day and time </title></head> <body> <script type="text/javascript"> var myDate = new Date(); var myDay = myDate.getDay(); // Array of days. var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; document.write("Today is : " + weekday[myDay]); document.write("<br/>"); // get hour value. var hours = myDate.getHours(); var ampm = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; var minutes = myDate.getMinutes(); minutes = minutes < 10 ? '0' + minutes : minutes; var myTime = hours + " " + ampm + " : " + minutes + " : " + myDate.getMilliseconds(); document.write("\tCurrent time is : " + myTime); </script></body> </html>
HTML-Methods
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
|
[
{
"code": null,
"e": 24499,
"s": 24471,
"text": "\n16 Apr, 2019"
},
{
"code": null,
"e": 24620,
"s": 24499,
"text": "The task is to print the system’s current day and time in the following format(Time in hours, minutes and milliseconds)."
},
{
"code": null,
"e": 24800,
"s": 24620,
"text": "Use getDay() function to create an array of days in a week. It returns a number of day like 0 for Sunday, 1 for Monday and so on). Convert it into AM or PM using ternary operator."
},
{
"code": null,
"e": 24890,
"s": 24800,
"text": "Use getHours() method to get the hour value between 0 to 23. It returns an integer value."
},
{
"code": null,
"e": 24993,
"s": 24890,
"text": "Minutes and milliseconds were printed using getMinutes() and getMilliseconds() functions respectively."
},
{
"code": null,
"e": 25002,
"s": 24993,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> print current day and time </title></head> <body> <script type=\"text/javascript\"> var myDate = new Date(); var myDay = myDate.getDay(); // Array of days. var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; document.write(\"Today is : \" + weekday[myDay]); document.write(\"<br/>\"); // get hour value. var hours = myDate.getHours(); var ampm = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; var minutes = myDate.getMinutes(); minutes = minutes < 10 ? '0' + minutes : minutes; var myTime = hours + \" \" + ampm + \" : \" + minutes + \" : \" + myDate.getMilliseconds(); document.write(\"\\tCurrent time is : \" + myTime); </script></body> </html>",
"e": 25915,
"s": 25002,
"text": null
},
{
"code": null,
"e": 25928,
"s": 25915,
"text": "HTML-Methods"
},
{
"code": null,
"e": 25933,
"s": 25928,
"text": "HTML"
},
{
"code": null,
"e": 25944,
"s": 25933,
"text": "JavaScript"
},
{
"code": null,
"e": 25961,
"s": 25944,
"text": "Web Technologies"
},
{
"code": null,
"e": 25966,
"s": 25961,
"text": "HTML"
},
{
"code": null,
"e": 26064,
"s": 25966,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26073,
"s": 26064,
"text": "Comments"
},
{
"code": null,
"e": 26086,
"s": 26073,
"text": "Old Comments"
},
{
"code": null,
"e": 26134,
"s": 26086,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26171,
"s": 26134,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26221,
"s": 26171,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26271,
"s": 26221,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26295,
"s": 26271,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26356,
"s": 26295,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26401,
"s": 26356,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26473,
"s": 26401,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26542,
"s": 26473,
"text": "How to calculate the number of days between two dates in javascript?"
}
] |
Spring - Transaction Management
|
A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of RDBMS-oriented enterprise application to ensure data integrity and consistency. The concept of transactions can be described with the following four key properties described as ACID −
Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful.
Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful.
Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc.
Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc.
Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption.
Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption.
Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure.
Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure.
A real RDBMS database system will guarantee all four properties for each transaction. The simplistic view of a transaction issued to the database using SQL is as follows −
Begin the transaction using begin transaction command.
Begin the transaction using begin transaction command.
Perform various deleted, update or insert operations using SQL queries.
Perform various deleted, update or insert operations using SQL queries.
If all the operation are successful then perform commit otherwise rollback all the operations.
If all the operation are successful then perform commit otherwise rollback all the operations.
Spring framework provides an abstract layer on top of different underlying transaction management APIs. Spring's transaction support aims to provide an alternative to EJB transactions by adding transaction capabilities to POJOs. Spring supports both programmatic and declarative transaction management. EJBs require an application server, but Spring transaction management can be implemented without the need of an application server.
Local transactions are specific to a single transactional resource like a JDBC connection, whereas global transactions can span multiple transactional resources like transaction in a distributed system.
Local transaction management can be useful in a centralized computing environment where application components and resources are located at a single site, and transaction management only involves a local data manager running on a single machine. Local transactions are easier to be implemented.
Global transaction management is required in a distributed computing environment where all the resources are distributed across multiple systems. In such a case, transaction management needs to be done both at local and global levels. A distributed or a global transaction is executed across multiple systems, and its execution requires coordination between the global transaction management system and all the local data managers of all the involved systems.
Spring supports two types of transaction management −
Programmatic transaction management − This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
Programmatic transaction management − This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions.
Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions.
Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code. But as a kind of crosscutting concern, declarative transaction management can be modularized with the AOP approach. Spring supports declarative transaction management through the Spring AOP framework.
The key to the Spring transaction abstraction is defined by the org.springframework.transaction.PlatformTransactionManager interface, which is as follows −
public interface PlatformTransactionManager {
TransactionStatus getTransaction(TransactionDefinition definition);
throws TransactionException;
void commit(TransactionStatus status) throws TransactionException;
void rollback(TransactionStatus status) throws TransactionException;
}
TransactionStatus getTransaction(TransactionDefinition definition)
This method returns a currently active transaction or creates a new one, according to the specified propagation behavior.
void commit(TransactionStatus status)
This method commits the given transaction, with regard to its status.
void rollback(TransactionStatus status)
This method performs a rollback of the given transaction.
The TransactionDefinition is the core interface of the transaction support in Spring and it is defined as follows −
public interface TransactionDefinition {
int getPropagationBehavior();
int getIsolationLevel();
String getName();
int getTimeout();
boolean isReadOnly();
}
int getPropagationBehavior()
This method returns the propagation behavior. Spring offers all of the transaction propagation options familiar from EJB CMT.
int getIsolationLevel()
This method returns the degree to which this transaction is isolated from the work of other transactions.
String getName()
This method returns the name of this transaction.
int getTimeout()
This method returns the time in seconds in which the transaction must complete.
boolean isReadOnly()
This method returns whether the transaction is read-only.
Following are the possible values for isolation level −
TransactionDefinition.ISOLATION_DEFAULT
This is the default isolation level.
TransactionDefinition.ISOLATION_READ_COMMITTED
Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur.
TransactionDefinition.ISOLATION_READ_UNCOMMITTED
Indicates that dirty reads, non-repeatable reads, and phantom reads can occur.
TransactionDefinition.ISOLATION_REPEATABLE_READ
Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur.
TransactionDefinition.ISOLATION_SERIALIZABLE
Indicates that dirty reads, non-repeatable reads, and phantom reads are prevented.
Following are the possible values for propagation types −
TransactionDefinition.PROPAGATION_MANDATORY
Supports a current transaction; throws an exception if no current transaction exists.
TransactionDefinition.PROPAGATION_NESTED
Executes within a nested transaction if a current transaction exists.
TransactionDefinition.PROPAGATION_NEVER
Does not support a current transaction; throws an exception if a current transaction exists.
TransactionDefinition.PROPAGATION_NOT_SUPPORTED
Does not support a current transaction; rather always execute nontransactionally.
TransactionDefinition.PROPAGATION_REQUIRED
Supports a current transaction; creates a new one if none exists.
TransactionDefinition.PROPAGATION_REQUIRES_NEW
Creates a new transaction, suspending the current transaction if one exists.
TransactionDefinition.PROPAGATION_SUPPORTS
Supports a current transaction; executes non-transactionally if none exists.
TransactionDefinition.TIMEOUT_DEFAULT
Uses the default timeout of the underlying transaction system, or none if timeouts are not supported.
The TransactionStatus interface provides a simple way for transactional code to control transaction execution and query transaction status.
public interface TransactionStatus extends SavepointManager {
boolean isNewTransaction();
boolean hasSavepoint();
void setRollbackOnly();
boolean isRollbackOnly();
boolean isCompleted();
}
boolean hasSavepoint()
This method returns whether this transaction internally carries a savepoint, i.e., has been created as nested transaction based on a savepoint.
boolean isCompleted()
This method returns whether this transaction is completed, i.e., whether it has already been committed or rolled back.
boolean isNewTransaction()
This method returns true in case the present transaction is new.
boolean isRollbackOnly()
This method returns whether the transaction has been marked as rollback-only.
void setRollbackOnly()
This method sets the transaction as rollback-only.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2686,
"s": 2292,
"text": "A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of RDBMS-oriented enterprise application to ensure data integrity and consistency. The concept of transactions can be described with the following four key properties described as ACID −"
},
{
"code": null,
"e": 2845,
"s": 2686,
"text": "Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful."
},
{
"code": null,
"e": 3004,
"s": 2845,
"text": "Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful."
},
{
"code": null,
"e": 3132,
"s": 3004,
"text": "Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc."
},
{
"code": null,
"e": 3260,
"s": 3132,
"text": "Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc."
},
{
"code": null,
"e": 3430,
"s": 3260,
"text": "Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption."
},
{
"code": null,
"e": 3600,
"s": 3430,
"text": "Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption."
},
{
"code": null,
"e": 3767,
"s": 3600,
"text": "Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure."
},
{
"code": null,
"e": 3934,
"s": 3767,
"text": "Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure."
},
{
"code": null,
"e": 4106,
"s": 3934,
"text": "A real RDBMS database system will guarantee all four properties for each transaction. The simplistic view of a transaction issued to the database using SQL is as follows −"
},
{
"code": null,
"e": 4161,
"s": 4106,
"text": "Begin the transaction using begin transaction command."
},
{
"code": null,
"e": 4216,
"s": 4161,
"text": "Begin the transaction using begin transaction command."
},
{
"code": null,
"e": 4288,
"s": 4216,
"text": "Perform various deleted, update or insert operations using SQL queries."
},
{
"code": null,
"e": 4360,
"s": 4288,
"text": "Perform various deleted, update or insert operations using SQL queries."
},
{
"code": null,
"e": 4455,
"s": 4360,
"text": "If all the operation are successful then perform commit otherwise rollback all the operations."
},
{
"code": null,
"e": 4550,
"s": 4455,
"text": "If all the operation are successful then perform commit otherwise rollback all the operations."
},
{
"code": null,
"e": 4985,
"s": 4550,
"text": "Spring framework provides an abstract layer on top of different underlying transaction management APIs. Spring's transaction support aims to provide an alternative to EJB transactions by adding transaction capabilities to POJOs. Spring supports both programmatic and declarative transaction management. EJBs require an application server, but Spring transaction management can be implemented without the need of an application server."
},
{
"code": null,
"e": 5188,
"s": 4985,
"text": "Local transactions are specific to a single transactional resource like a JDBC connection, whereas global transactions can span multiple transactional resources like transaction in a distributed system."
},
{
"code": null,
"e": 5483,
"s": 5188,
"text": "Local transaction management can be useful in a centralized computing environment where application components and resources are located at a single site, and transaction management only involves a local data manager running on a single machine. Local transactions are easier to be implemented."
},
{
"code": null,
"e": 5943,
"s": 5483,
"text": "Global transaction management is required in a distributed computing environment where all the resources are distributed across multiple systems. In such a case, transaction management needs to be done both at local and global levels. A distributed or a global transaction is executed across multiple systems, and its execution requires coordination between the global transaction management system and all the local data managers of all the involved systems."
},
{
"code": null,
"e": 5997,
"s": 5943,
"text": "Spring supports two types of transaction management −"
},
{
"code": null,
"e": 6185,
"s": 5997,
"text": "Programmatic transaction management − This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain."
},
{
"code": null,
"e": 6373,
"s": 6185,
"text": "Programmatic transaction management − This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain."
},
{
"code": null,
"e": 6561,
"s": 6373,
"text": "Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions."
},
{
"code": null,
"e": 6749,
"s": 6561,
"text": "Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions."
},
{
"code": null,
"e": 7169,
"s": 6749,
"text": "Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code. But as a kind of crosscutting concern, declarative transaction management can be modularized with the AOP approach. Spring supports declarative transaction management through the Spring AOP framework."
},
{
"code": null,
"e": 7325,
"s": 7169,
"text": "The key to the Spring transaction abstraction is defined by the org.springframework.transaction.PlatformTransactionManager interface, which is as follows −"
},
{
"code": null,
"e": 7622,
"s": 7325,
"text": "public interface PlatformTransactionManager {\n TransactionStatus getTransaction(TransactionDefinition definition);\n throws TransactionException;\n \n void commit(TransactionStatus status) throws TransactionException;\n void rollback(TransactionStatus status) throws TransactionException;\n}"
},
{
"code": null,
"e": 7689,
"s": 7622,
"text": "TransactionStatus getTransaction(TransactionDefinition definition)"
},
{
"code": null,
"e": 7811,
"s": 7689,
"text": "This method returns a currently active transaction or creates a new one, according to the specified propagation behavior."
},
{
"code": null,
"e": 7849,
"s": 7811,
"text": "void commit(TransactionStatus status)"
},
{
"code": null,
"e": 7919,
"s": 7849,
"text": "This method commits the given transaction, with regard to its status."
},
{
"code": null,
"e": 7959,
"s": 7919,
"text": "void rollback(TransactionStatus status)"
},
{
"code": null,
"e": 8017,
"s": 7959,
"text": "This method performs a rollback of the given transaction."
},
{
"code": null,
"e": 8133,
"s": 8017,
"text": "The TransactionDefinition is the core interface of the transaction support in Spring and it is defined as follows −"
},
{
"code": null,
"e": 8304,
"s": 8133,
"text": "public interface TransactionDefinition {\n int getPropagationBehavior();\n int getIsolationLevel();\n String getName();\n int getTimeout();\n boolean isReadOnly();\n}"
},
{
"code": null,
"e": 8333,
"s": 8304,
"text": "int getPropagationBehavior()"
},
{
"code": null,
"e": 8459,
"s": 8333,
"text": "This method returns the propagation behavior. Spring offers all of the transaction propagation options familiar from EJB CMT."
},
{
"code": null,
"e": 8483,
"s": 8459,
"text": "int getIsolationLevel()"
},
{
"code": null,
"e": 8589,
"s": 8483,
"text": "This method returns the degree to which this transaction is isolated from the work of other transactions."
},
{
"code": null,
"e": 8606,
"s": 8589,
"text": "String getName()"
},
{
"code": null,
"e": 8656,
"s": 8606,
"text": "This method returns the name of this transaction."
},
{
"code": null,
"e": 8673,
"s": 8656,
"text": "int getTimeout()"
},
{
"code": null,
"e": 8753,
"s": 8673,
"text": "This method returns the time in seconds in which the transaction must complete."
},
{
"code": null,
"e": 8774,
"s": 8753,
"text": "boolean isReadOnly()"
},
{
"code": null,
"e": 8832,
"s": 8774,
"text": "This method returns whether the transaction is read-only."
},
{
"code": null,
"e": 8888,
"s": 8832,
"text": "Following are the possible values for isolation level −"
},
{
"code": null,
"e": 8928,
"s": 8888,
"text": "TransactionDefinition.ISOLATION_DEFAULT"
},
{
"code": null,
"e": 8965,
"s": 8928,
"text": "This is the default isolation level."
},
{
"code": null,
"e": 9012,
"s": 8965,
"text": "TransactionDefinition.ISOLATION_READ_COMMITTED"
},
{
"code": null,
"e": 9104,
"s": 9012,
"text": "Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur."
},
{
"code": null,
"e": 9153,
"s": 9104,
"text": "TransactionDefinition.ISOLATION_READ_UNCOMMITTED"
},
{
"code": null,
"e": 9232,
"s": 9153,
"text": "Indicates that dirty reads, non-repeatable reads, and phantom reads can occur."
},
{
"code": null,
"e": 9280,
"s": 9232,
"text": "TransactionDefinition.ISOLATION_REPEATABLE_READ"
},
{
"code": null,
"e": 9372,
"s": 9280,
"text": "Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur."
},
{
"code": null,
"e": 9417,
"s": 9372,
"text": "TransactionDefinition.ISOLATION_SERIALIZABLE"
},
{
"code": null,
"e": 9500,
"s": 9417,
"text": "Indicates that dirty reads, non-repeatable reads, and phantom reads are prevented."
},
{
"code": null,
"e": 9558,
"s": 9500,
"text": "Following are the possible values for propagation types −"
},
{
"code": null,
"e": 9602,
"s": 9558,
"text": "TransactionDefinition.PROPAGATION_MANDATORY"
},
{
"code": null,
"e": 9688,
"s": 9602,
"text": "Supports a current transaction; throws an exception if no current transaction exists."
},
{
"code": null,
"e": 9730,
"s": 9688,
"text": "TransactionDefinition.PROPAGATION_NESTED "
},
{
"code": null,
"e": 9800,
"s": 9730,
"text": "Executes within a nested transaction if a current transaction exists."
},
{
"code": null,
"e": 9841,
"s": 9800,
"text": "TransactionDefinition.PROPAGATION_NEVER "
},
{
"code": null,
"e": 9934,
"s": 9841,
"text": "Does not support a current transaction; throws an exception if a current transaction exists."
},
{
"code": null,
"e": 9983,
"s": 9934,
"text": "TransactionDefinition.PROPAGATION_NOT_SUPPORTED "
},
{
"code": null,
"e": 10065,
"s": 9983,
"text": "Does not support a current transaction; rather always execute nontransactionally."
},
{
"code": null,
"e": 10108,
"s": 10065,
"text": "TransactionDefinition.PROPAGATION_REQUIRED"
},
{
"code": null,
"e": 10174,
"s": 10108,
"text": "Supports a current transaction; creates a new one if none exists."
},
{
"code": null,
"e": 10221,
"s": 10174,
"text": "TransactionDefinition.PROPAGATION_REQUIRES_NEW"
},
{
"code": null,
"e": 10298,
"s": 10221,
"text": "Creates a new transaction, suspending the current transaction if one exists."
},
{
"code": null,
"e": 10341,
"s": 10298,
"text": "TransactionDefinition.PROPAGATION_SUPPORTS"
},
{
"code": null,
"e": 10418,
"s": 10341,
"text": "Supports a current transaction; executes non-transactionally if none exists."
},
{
"code": null,
"e": 10456,
"s": 10418,
"text": "TransactionDefinition.TIMEOUT_DEFAULT"
},
{
"code": null,
"e": 10558,
"s": 10456,
"text": "Uses the default timeout of the underlying transaction system, or none if timeouts are not supported."
},
{
"code": null,
"e": 10698,
"s": 10558,
"text": "The TransactionStatus interface provides a simple way for transactional code to control transaction execution and query transaction status."
},
{
"code": null,
"e": 10902,
"s": 10698,
"text": "public interface TransactionStatus extends SavepointManager {\n boolean isNewTransaction();\n boolean hasSavepoint();\n void setRollbackOnly();\n boolean isRollbackOnly();\n boolean isCompleted();\n}"
},
{
"code": null,
"e": 10925,
"s": 10902,
"text": "boolean hasSavepoint()"
},
{
"code": null,
"e": 11069,
"s": 10925,
"text": "This method returns whether this transaction internally carries a savepoint, i.e., has been created as nested transaction based on a savepoint."
},
{
"code": null,
"e": 11091,
"s": 11069,
"text": "boolean isCompleted()"
},
{
"code": null,
"e": 11210,
"s": 11091,
"text": "This method returns whether this transaction is completed, i.e., whether it has already been committed or rolled back."
},
{
"code": null,
"e": 11237,
"s": 11210,
"text": "boolean isNewTransaction()"
},
{
"code": null,
"e": 11302,
"s": 11237,
"text": "This method returns true in case the present transaction is new."
},
{
"code": null,
"e": 11327,
"s": 11302,
"text": "boolean isRollbackOnly()"
},
{
"code": null,
"e": 11405,
"s": 11327,
"text": "This method returns whether the transaction has been marked as rollback-only."
},
{
"code": null,
"e": 11428,
"s": 11405,
"text": "void setRollbackOnly()"
},
{
"code": null,
"e": 11479,
"s": 11428,
"text": "This method sets the transaction as rollback-only."
},
{
"code": null,
"e": 11513,
"s": 11479,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 11527,
"s": 11513,
"text": " Karthikeya T"
},
{
"code": null,
"e": 11560,
"s": 11527,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 11575,
"s": 11560,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 11610,
"s": 11575,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 11622,
"s": 11610,
"text": " Senol Atac"
},
{
"code": null,
"e": 11657,
"s": 11622,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11669,
"s": 11657,
"text": " Senol Atac"
},
{
"code": null,
"e": 11704,
"s": 11669,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11716,
"s": 11704,
"text": " Senol Atac"
},
{
"code": null,
"e": 11749,
"s": 11716,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 11761,
"s": 11749,
"text": " Senol Atac"
},
{
"code": null,
"e": 11768,
"s": 11761,
"text": " Print"
},
{
"code": null,
"e": 11779,
"s": 11768,
"text": " Add Notes"
}
] |
How to Easily Process Audio on Your GPU with TensorFlow | by David Schwertfeger | Towards Data Science
|
Deep Learning on audio data often requires a heavy preprocessing step.
While some models run on raw audio signals, others expect a time-frequency presentation as input. Preprocessing is often done as a separate step, before model training, with tools like librosa or Essentia.
But, as you start working with larger datasets, this workflow presents a challenge.
Anytime you change parameters, like sample-rate or FFT-size, you need to process the whole dataset again before you can resume training.
And that means waiting. 😴
Even when parallelized onto available CPU-cores, preprocessing can take a long time. Plus, you need to consider how to store and access files for different parameters. This undoubtedly wastes disk space and mental resources and can quickly become a headache.
Does any of this sound familiar?
Tired of this tedious two-step process, I started to ask myself if there wasn’t a better way.
“Isn’t there a better way?”
I recently set up an efficient audio-data pipeline which enables me to load audio from file paths into models on-demand.
towardsdatascience.com
And I wanted to use the same data pipeline for spectrogram-based models, too.
In this post, I want to share with you:
How to leverage the power of your GPU for your signal processing tasks.
How to build a custom preprocessing-layer to use in any neural network.
And a little bonus at the end. 😲
Read on to find out more.
A popular feature representation across audio-domains in Deep Learning applications is the mel-spectrogram.
A mel-spectrogram is a visual representation of a signal’s frequency spectrum over time. The main difference to a standard spectrogram is that frequencies are projected onto the mel-scale, where the perceived distance of pitches equals the distance of mel-frequencies. This is inspired by how we hear.
Likewise, the mel-spectrogram’s magnitudes are generally logarithmically scaled because this is closer to how we perceive changes in loudness. So, a more precise term would be log-magnitude mel-scaled spectrogram. But because this is quite a mouthful, most people call it log-mel-spectrogram or mel-spectrogram for short. It’s worth pointing out, though, that although mel refers to the frequency-scale, log describes the scale of the magnitudes.
So, how can you transform your raw audio signals into mel-spectrograms?
Compute the short-time Fourier transform of your audio signalsCompute the magnitudesInstantiate the mel filterbankWarp the linear-scale magnitude-spectrograms to mel-scaleTransform magnitudes to log-scale
Compute the short-time Fourier transform of your audio signals
Compute the magnitudes
Instantiate the mel filterbank
Warp the linear-scale magnitude-spectrograms to mel-scale
Transform magnitudes to log-scale
Let’s look at each step in detail.
The short-time Fourier transform (STFT) divides a long signal into shorter segments, often called frames, and computes the spectrum for each frame. The frames typically overlap to minimize data-loss at the edges. Joining the spectra for each frame creates the spectrogram.
To compute the STFT with TensorFlow, use tf.signal.stft(signals) where signals is a tensor containing your audio signals.
Some parameters you need to set are:
frame_length: The length of each frame in samples. This is often called window-length or window-size. The window-size trades temporal resolution (short windows) for frequential resolution (long windows).
frame_step: The number of samples between frames. This is often called hop-length or hop-size.
fft_length: The size of the FFT to apply. This is often called FFT-size and matches the frame_length. It defaults to the smallest power of 2 that can enclose a frame. So, if frame_length is a power of 2 and you don't explicitly set the fft_length, it takes on the same value.
spectrograms = tf.signal.stft(signals, frame_length=1024, frame_step=512)
The STFT from the previous step returns a tensor of complex values. Use tf.abs() to compute the magnitudes.
magnitude_spectrograms = tf.abs(spectrograms)
We can now plot the magnitude-spectrogram.
Note that you won’t see much before properly scaling the magnitudes, though. The second subplot is scaled with librosa.amplitude_to_db(). So, technically, it's a log-magnitude power-spectrogram.
More about that in step 5.
Transforming standard spectrograms to mel-spectrograms involves warping frequencies to the mel-scale and combining FFT bins to mel-frequency bins.
TensorFlow makes this transformation easy.
You can create a mel-filterbank which warps linear-scale spectrograms to the mel-scale with tf.signal.linear_to_mel_weight_matrix().
You only need to set a few parameters:
num_mel_bins: The number of mel-frequency bands in the resulting mel-spectrogram.
num_spectrogram_bins: The number of unique spectrogram-bins in the source spectrogram which equals fft_length // 2 + 1.
sample_rate: The number of samples per second of the input signal.
lower_edge_hertz: The lowest frequency in Hertz to include in the mel-scale.
upper_edge_hertz: The highest frequency in Hertz to include in the mel-scale.
Multiply the squared magnitude-spectrograms with the mel-filterbank and you get mel-scaled power-spectrograms.
mel_power_specgrams = tf.matmul(tf.square(magnitude_spectrograms), mel_filterbank)
We perceive changes in loudness logarithmically. So, in this last step, we want to scale the mel-spectrograms’ magnitudes logarithmically, too.
One way to do that would be taking the log of the mel-spectrograms. But that might get you into trouble because log(0) is undefined. Instead, you want to convert the magnitudes to decibel (dB) units in a numerically stable way.
log_magnitude_mel_spectrograms = power_to_db(mel_power_spectrograms)
Here’s how to do that in TensorFlow based on librosa.power_to_db.
After conversion to log-scale, the spectrograms’ maximum values are zero and the smallest values negative top_db.
Now here comes the fun part.
Combining the individual steps into a custom preprocessing layer allows you to feed raw audio to your network and compute mel-spectrograms on-the-fly on your GPU.
To create your mel-spectrogram layer (or any custom layer), you subclass from tf.keras.layers.Layer and implement three methods:
__init__(): Save the layer's configuration in member variables.build(): Define your weights.call(): Perform the logic of applying the layer to input tensors. This is where you transform your audio input-tensors to mel-spectrograms.
__init__(): Save the layer's configuration in member variables.
build(): Define your weights.
call(): Perform the logic of applying the layer to input tensors. This is where you transform your audio input-tensors to mel-spectrograms.
Here’s my implementation of a custom Keras layer that transforms raw audio to log-mel-spectrograms:
Once defined, you can add audio preprocessing to your neural networks in one line (8).
Now, you may be wondering if it isn’t incredibly inefficient to transform the same audio signals into spectrograms again and again.
And that’s a good point.
While writing this post, I came across Kapre, a library of “Keras layers for audio and music signal preprocessing.” The authors, Choi et al., present a benchmark that shows, their preprocessing layers add about 20 percent overhead.
So, it’s a trade-off. Like almost anything in life.
In this case, you trade storage space for slightly longer computation time. But not only that. You also get rid of a tedious two-step process and instantly gain more flexibility in training your Deep Learning models on audio data.
Trying different preprocessing parameters is now as simple as restarting your training routine with different parameters.
No need to maintain a separate preprocessing-script.
No need to remember changing parameters in more than one place.
No need to process the whole dataset before you can continue training.
Is it worth the overhead?
You decide for yourself.
All the code and examples are available in this Colab notebook:
colab.research.google.com
Now it’s your turn.
What is a workflow you have simplified (or like to simplify) that is giving you more flexibility and mental space, although it’s slightly more expensive?
[1] H. Purwins et al., Deep Learning for Audio Signal Processing (2019), IEEE Journal of Selected Topics in Signal Processing 13.2: 206–219
[2] K. Choi et al., Kapre: On-GPU Audio Preprocessing Layers for a Quick Implementation of Deep Neural Network Models with Keras (2017) arXiv preprint
|
[
{
"code": null,
"e": 243,
"s": 172,
"text": "Deep Learning on audio data often requires a heavy preprocessing step."
},
{
"code": null,
"e": 449,
"s": 243,
"text": "While some models run on raw audio signals, others expect a time-frequency presentation as input. Preprocessing is often done as a separate step, before model training, with tools like librosa or Essentia."
},
{
"code": null,
"e": 533,
"s": 449,
"text": "But, as you start working with larger datasets, this workflow presents a challenge."
},
{
"code": null,
"e": 670,
"s": 533,
"text": "Anytime you change parameters, like sample-rate or FFT-size, you need to process the whole dataset again before you can resume training."
},
{
"code": null,
"e": 696,
"s": 670,
"text": "And that means waiting. 😴"
},
{
"code": null,
"e": 955,
"s": 696,
"text": "Even when parallelized onto available CPU-cores, preprocessing can take a long time. Plus, you need to consider how to store and access files for different parameters. This undoubtedly wastes disk space and mental resources and can quickly become a headache."
},
{
"code": null,
"e": 988,
"s": 955,
"text": "Does any of this sound familiar?"
},
{
"code": null,
"e": 1082,
"s": 988,
"text": "Tired of this tedious two-step process, I started to ask myself if there wasn’t a better way."
},
{
"code": null,
"e": 1110,
"s": 1082,
"text": "“Isn’t there a better way?”"
},
{
"code": null,
"e": 1231,
"s": 1110,
"text": "I recently set up an efficient audio-data pipeline which enables me to load audio from file paths into models on-demand."
},
{
"code": null,
"e": 1254,
"s": 1231,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1332,
"s": 1254,
"text": "And I wanted to use the same data pipeline for spectrogram-based models, too."
},
{
"code": null,
"e": 1372,
"s": 1332,
"text": "In this post, I want to share with you:"
},
{
"code": null,
"e": 1444,
"s": 1372,
"text": "How to leverage the power of your GPU for your signal processing tasks."
},
{
"code": null,
"e": 1516,
"s": 1444,
"text": "How to build a custom preprocessing-layer to use in any neural network."
},
{
"code": null,
"e": 1549,
"s": 1516,
"text": "And a little bonus at the end. 😲"
},
{
"code": null,
"e": 1575,
"s": 1549,
"text": "Read on to find out more."
},
{
"code": null,
"e": 1683,
"s": 1575,
"text": "A popular feature representation across audio-domains in Deep Learning applications is the mel-spectrogram."
},
{
"code": null,
"e": 1985,
"s": 1683,
"text": "A mel-spectrogram is a visual representation of a signal’s frequency spectrum over time. The main difference to a standard spectrogram is that frequencies are projected onto the mel-scale, where the perceived distance of pitches equals the distance of mel-frequencies. This is inspired by how we hear."
},
{
"code": null,
"e": 2432,
"s": 1985,
"text": "Likewise, the mel-spectrogram’s magnitudes are generally logarithmically scaled because this is closer to how we perceive changes in loudness. So, a more precise term would be log-magnitude mel-scaled spectrogram. But because this is quite a mouthful, most people call it log-mel-spectrogram or mel-spectrogram for short. It’s worth pointing out, though, that although mel refers to the frequency-scale, log describes the scale of the magnitudes."
},
{
"code": null,
"e": 2504,
"s": 2432,
"text": "So, how can you transform your raw audio signals into mel-spectrograms?"
},
{
"code": null,
"e": 2709,
"s": 2504,
"text": "Compute the short-time Fourier transform of your audio signalsCompute the magnitudesInstantiate the mel filterbankWarp the linear-scale magnitude-spectrograms to mel-scaleTransform magnitudes to log-scale"
},
{
"code": null,
"e": 2772,
"s": 2709,
"text": "Compute the short-time Fourier transform of your audio signals"
},
{
"code": null,
"e": 2795,
"s": 2772,
"text": "Compute the magnitudes"
},
{
"code": null,
"e": 2826,
"s": 2795,
"text": "Instantiate the mel filterbank"
},
{
"code": null,
"e": 2884,
"s": 2826,
"text": "Warp the linear-scale magnitude-spectrograms to mel-scale"
},
{
"code": null,
"e": 2918,
"s": 2884,
"text": "Transform magnitudes to log-scale"
},
{
"code": null,
"e": 2953,
"s": 2918,
"text": "Let’s look at each step in detail."
},
{
"code": null,
"e": 3226,
"s": 2953,
"text": "The short-time Fourier transform (STFT) divides a long signal into shorter segments, often called frames, and computes the spectrum for each frame. The frames typically overlap to minimize data-loss at the edges. Joining the spectra for each frame creates the spectrogram."
},
{
"code": null,
"e": 3348,
"s": 3226,
"text": "To compute the STFT with TensorFlow, use tf.signal.stft(signals) where signals is a tensor containing your audio signals."
},
{
"code": null,
"e": 3385,
"s": 3348,
"text": "Some parameters you need to set are:"
},
{
"code": null,
"e": 3589,
"s": 3385,
"text": "frame_length: The length of each frame in samples. This is often called window-length or window-size. The window-size trades temporal resolution (short windows) for frequential resolution (long windows)."
},
{
"code": null,
"e": 3684,
"s": 3589,
"text": "frame_step: The number of samples between frames. This is often called hop-length or hop-size."
},
{
"code": null,
"e": 3960,
"s": 3684,
"text": "fft_length: The size of the FFT to apply. This is often called FFT-size and matches the frame_length. It defaults to the smallest power of 2 that can enclose a frame. So, if frame_length is a power of 2 and you don't explicitly set the fft_length, it takes on the same value."
},
{
"code": null,
"e": 4092,
"s": 3960,
"text": "spectrograms = tf.signal.stft(signals, frame_length=1024, frame_step=512)"
},
{
"code": null,
"e": 4200,
"s": 4092,
"text": "The STFT from the previous step returns a tensor of complex values. Use tf.abs() to compute the magnitudes."
},
{
"code": null,
"e": 4246,
"s": 4200,
"text": "magnitude_spectrograms = tf.abs(spectrograms)"
},
{
"code": null,
"e": 4289,
"s": 4246,
"text": "We can now plot the magnitude-spectrogram."
},
{
"code": null,
"e": 4484,
"s": 4289,
"text": "Note that you won’t see much before properly scaling the magnitudes, though. The second subplot is scaled with librosa.amplitude_to_db(). So, technically, it's a log-magnitude power-spectrogram."
},
{
"code": null,
"e": 4511,
"s": 4484,
"text": "More about that in step 5."
},
{
"code": null,
"e": 4658,
"s": 4511,
"text": "Transforming standard spectrograms to mel-spectrograms involves warping frequencies to the mel-scale and combining FFT bins to mel-frequency bins."
},
{
"code": null,
"e": 4701,
"s": 4658,
"text": "TensorFlow makes this transformation easy."
},
{
"code": null,
"e": 4834,
"s": 4701,
"text": "You can create a mel-filterbank which warps linear-scale spectrograms to the mel-scale with tf.signal.linear_to_mel_weight_matrix()."
},
{
"code": null,
"e": 4873,
"s": 4834,
"text": "You only need to set a few parameters:"
},
{
"code": null,
"e": 4955,
"s": 4873,
"text": "num_mel_bins: The number of mel-frequency bands in the resulting mel-spectrogram."
},
{
"code": null,
"e": 5075,
"s": 4955,
"text": "num_spectrogram_bins: The number of unique spectrogram-bins in the source spectrogram which equals fft_length // 2 + 1."
},
{
"code": null,
"e": 5142,
"s": 5075,
"text": "sample_rate: The number of samples per second of the input signal."
},
{
"code": null,
"e": 5219,
"s": 5142,
"text": "lower_edge_hertz: The lowest frequency in Hertz to include in the mel-scale."
},
{
"code": null,
"e": 5297,
"s": 5219,
"text": "upper_edge_hertz: The highest frequency in Hertz to include in the mel-scale."
},
{
"code": null,
"e": 5408,
"s": 5297,
"text": "Multiply the squared magnitude-spectrograms with the mel-filterbank and you get mel-scaled power-spectrograms."
},
{
"code": null,
"e": 5522,
"s": 5408,
"text": "mel_power_specgrams = tf.matmul(tf.square(magnitude_spectrograms), mel_filterbank)"
},
{
"code": null,
"e": 5666,
"s": 5522,
"text": "We perceive changes in loudness logarithmically. So, in this last step, we want to scale the mel-spectrograms’ magnitudes logarithmically, too."
},
{
"code": null,
"e": 5894,
"s": 5666,
"text": "One way to do that would be taking the log of the mel-spectrograms. But that might get you into trouble because log(0) is undefined. Instead, you want to convert the magnitudes to decibel (dB) units in a numerically stable way."
},
{
"code": null,
"e": 5963,
"s": 5894,
"text": "log_magnitude_mel_spectrograms = power_to_db(mel_power_spectrograms)"
},
{
"code": null,
"e": 6029,
"s": 5963,
"text": "Here’s how to do that in TensorFlow based on librosa.power_to_db."
},
{
"code": null,
"e": 6143,
"s": 6029,
"text": "After conversion to log-scale, the spectrograms’ maximum values are zero and the smallest values negative top_db."
},
{
"code": null,
"e": 6172,
"s": 6143,
"text": "Now here comes the fun part."
},
{
"code": null,
"e": 6335,
"s": 6172,
"text": "Combining the individual steps into a custom preprocessing layer allows you to feed raw audio to your network and compute mel-spectrograms on-the-fly on your GPU."
},
{
"code": null,
"e": 6464,
"s": 6335,
"text": "To create your mel-spectrogram layer (or any custom layer), you subclass from tf.keras.layers.Layer and implement three methods:"
},
{
"code": null,
"e": 6696,
"s": 6464,
"text": "__init__(): Save the layer's configuration in member variables.build(): Define your weights.call(): Perform the logic of applying the layer to input tensors. This is where you transform your audio input-tensors to mel-spectrograms."
},
{
"code": null,
"e": 6760,
"s": 6696,
"text": "__init__(): Save the layer's configuration in member variables."
},
{
"code": null,
"e": 6790,
"s": 6760,
"text": "build(): Define your weights."
},
{
"code": null,
"e": 6930,
"s": 6790,
"text": "call(): Perform the logic of applying the layer to input tensors. This is where you transform your audio input-tensors to mel-spectrograms."
},
{
"code": null,
"e": 7030,
"s": 6930,
"text": "Here’s my implementation of a custom Keras layer that transforms raw audio to log-mel-spectrograms:"
},
{
"code": null,
"e": 7117,
"s": 7030,
"text": "Once defined, you can add audio preprocessing to your neural networks in one line (8)."
},
{
"code": null,
"e": 7249,
"s": 7117,
"text": "Now, you may be wondering if it isn’t incredibly inefficient to transform the same audio signals into spectrograms again and again."
},
{
"code": null,
"e": 7274,
"s": 7249,
"text": "And that’s a good point."
},
{
"code": null,
"e": 7506,
"s": 7274,
"text": "While writing this post, I came across Kapre, a library of “Keras layers for audio and music signal preprocessing.” The authors, Choi et al., present a benchmark that shows, their preprocessing layers add about 20 percent overhead."
},
{
"code": null,
"e": 7558,
"s": 7506,
"text": "So, it’s a trade-off. Like almost anything in life."
},
{
"code": null,
"e": 7789,
"s": 7558,
"text": "In this case, you trade storage space for slightly longer computation time. But not only that. You also get rid of a tedious two-step process and instantly gain more flexibility in training your Deep Learning models on audio data."
},
{
"code": null,
"e": 7911,
"s": 7789,
"text": "Trying different preprocessing parameters is now as simple as restarting your training routine with different parameters."
},
{
"code": null,
"e": 7964,
"s": 7911,
"text": "No need to maintain a separate preprocessing-script."
},
{
"code": null,
"e": 8028,
"s": 7964,
"text": "No need to remember changing parameters in more than one place."
},
{
"code": null,
"e": 8099,
"s": 8028,
"text": "No need to process the whole dataset before you can continue training."
},
{
"code": null,
"e": 8125,
"s": 8099,
"text": "Is it worth the overhead?"
},
{
"code": null,
"e": 8150,
"s": 8125,
"text": "You decide for yourself."
},
{
"code": null,
"e": 8214,
"s": 8150,
"text": "All the code and examples are available in this Colab notebook:"
},
{
"code": null,
"e": 8240,
"s": 8214,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 8260,
"s": 8240,
"text": "Now it’s your turn."
},
{
"code": null,
"e": 8414,
"s": 8260,
"text": "What is a workflow you have simplified (or like to simplify) that is giving you more flexibility and mental space, although it’s slightly more expensive?"
},
{
"code": null,
"e": 8554,
"s": 8414,
"text": "[1] H. Purwins et al., Deep Learning for Audio Signal Processing (2019), IEEE Journal of Selected Topics in Signal Processing 13.2: 206–219"
}
] |
Java parameterized constructor
|
Yes! it is supported. A constructor with arguments is called the parameterized constructor. It is used to initialize an object with given values.
Live Demo
public class Tester {
private String message;
public Tester(String message){
this.message = message;
}
public String getMessage(){
return message ;
}
public void setMessage(String message){
this.message = message;
}
public static void main(String[] args) {
Tester tester = new Tester("Welcome");
System.out.println(tester.getMessage());
}
}
Welcome
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "Yes! it is supported. A constructor with arguments is called the parameterized constructor. It is used to initialize an object with given values. "
},
{
"code": null,
"e": 1219,
"s": 1209,
"text": "Live Demo"
},
{
"code": null,
"e": 1634,
"s": 1219,
"text": "public class Tester {\n \n private String message;\n \n public Tester(String message){\n this.message = message;\n }\n \n public String getMessage(){\n return message ;\n }\n \n public void setMessage(String message){\n this.message = message;\n }\n \n public static void main(String[] args) { \n Tester tester = new Tester(\"Welcome\");\n System.out.println(tester.getMessage()); \n }\n} "
},
{
"code": null,
"e": 1642,
"s": 1634,
"text": "Welcome"
}
] |
Tryit Editor v3.6 - Show Python
|
username = raw_input("Enter username:")
print("Username is: " + username)
|
[
{
"code": null,
"e": 40,
"s": 0,
"text": "username = raw_input(\"Enter username:\")"
}
] |
Data Structures and Algorithms | Set 13 - GeeksforGeeks
|
05 Jul, 2018
Following questions have been asked in GATE CS 2002 exam
1. The number of leaf nodes in a rooted tree of n nodes, with each node having 0 or 3 children is:a) n/2b) (n-1)/3c) (n-1)/2d) (2n+1)/3
Answer(d)
Let L be the number of leaf nodes and I be the number of internal nodes, then following relation holds for above given tree (For details, please see question 3 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-11/)
L = (3-1)I + 1 = 2I + 1
Total number of nodes(n) is sum of leaf nodes and internal nodes
n = L + I
After solving above two, we get L = (2n+1)/3
2. The running time of the following algorithm
Procedure A(n)
If n <= 2 return(1) else return A();
is best described bya) O(n)b) O(log n)c) O(1og log n)d) O(1)
Answer(c)For explanation, please see question 5 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-11/
3. A weight-balanced tree is a binary tree in which for each node. The number of nodes in the left sub tree is at least half and at most twice the number of nodes in the right sub tree. The maximum possible height (number of nodes on the path from the root to the farthest leaf) of such a tree on n nodes is best described by which of the following?a) log2 nb) log4/3 nc) log3 nd) log3/2 n
Answer(d)
Let the maximum possible height of a tree with n nodes is represented by H(n).
The maximum possible value of H(n) can be approximately written using the following recursion:
H(n) = H(2n/3) + 1
The solution of above recurrence is log3/2 n. We can simply get it by drawing a recursion tree.
4. Consider the following algorithm for searching for a given number x in an unsorted – array A[1..n] having n distinct values:
1) Choose an i uniformly at random from 1..n;
2) If A[i] = x then Stop else Goto 1;
Assuming that x is present in A, what is the expected number of comparisons made by the algorithm before it terminates?a) nb) n-lc) 2nd) n/2
Answer(a)
If you remember the coin and dice questions, you can just guess the answer for the above.
Below is proof of the answer.
Let expected number of comparisons be E. Value of E is sum of following expression for all the possible cases.
number_of_comparisons_for_a_case * probability_for_the_case
Case 1
If A[i] is found in the first attempt
number of comparisons = 1
probability of the case = 1/n
Case 2
If A[i] is found in the second attempt
number of comparisons = 2
probability of the case = (n-1)/n*1/n
Case 3
If A[i] is found in the third attempt
number of comparisons = 2
probability of the case = (n-1)/n*(n-1)/n*1/n
There are actually infinite such cases. So, we have following infinite series for E.
E = 1/n + [(n-1)/n]*[1/n]*2 + [(n-1)/n]*[(n-1)/n]*[1/n]*3 + .... (1)
After multiplying equation (1) with (n-1)/n, we get
E (n-1)/n = [(n-1)/n]*[1/n] + [(n-1)/n]*[(n-1)/n]*[1/n]*2 +
[(n-1)/n]*[(n-1)/n]*[(n-1)/n]*[1/n]*3 ..........(2)
Subtracting (2) from (1), we get
E/n = 1/n + (n-1)/n*1/n + (n-1)/n*(n-1)/n*1/n + ............
The expression on the right side is a GP with infinite elements. Let us apply the sum formula (a/(1-r))
E/n = [1/n]/[1-(n-1)/n] = 1
E = n
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-2002
GATE-CS-DS-&-Algo
GATE CS
MCQ
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Page Replacement Algorithms in Operating Systems
Normal Forms in DBMS
LRU Cache Implementation
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Data Structures and Algorithms | Set 21
Practice questions on Height balanced/AVL Tree
Operating Systems | Set 1
Computer Networks | Set 1
Computer Networks | Set 2
|
[
{
"code": null,
"e": 23981,
"s": 23953,
"text": "\n05 Jul, 2018"
},
{
"code": null,
"e": 24038,
"s": 23981,
"text": "Following questions have been asked in GATE CS 2002 exam"
},
{
"code": null,
"e": 24174,
"s": 24038,
"text": "1. The number of leaf nodes in a rooted tree of n nodes, with each node having 0 or 3 children is:a) n/2b) (n-1)/3c) (n-1)/2d) (2n+1)/3"
},
{
"code": null,
"e": 24184,
"s": 24174,
"text": "Answer(d)"
},
{
"code": null,
"e": 24417,
"s": 24184,
"text": "Let L be the number of leaf nodes and I be the number of internal nodes, then following relation holds for above given tree (For details, please see question 3 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-11/)"
},
{
"code": null,
"e": 24443,
"s": 24417,
"text": " L = (3-1)I + 1 = 2I + 1"
},
{
"code": null,
"e": 24508,
"s": 24443,
"text": "Total number of nodes(n) is sum of leaf nodes and internal nodes"
},
{
"code": null,
"e": 24521,
"s": 24508,
"text": " n = L + I "
},
{
"code": null,
"e": 24566,
"s": 24521,
"text": "After solving above two, we get L = (2n+1)/3"
},
{
"code": null,
"e": 24613,
"s": 24566,
"text": "2. The running time of the following algorithm"
},
{
"code": null,
"e": 24672,
"s": 24613,
"text": " Procedure A(n) \n If n <= 2 return(1) else return A();\n"
},
{
"code": null,
"e": 24733,
"s": 24672,
"text": "is best described bya) O(n)b) O(log n)c) O(1og log n)d) O(1)"
},
{
"code": null,
"e": 24853,
"s": 24733,
"text": "Answer(c)For explanation, please see question 5 of https://www.geeksforgeeks.org/data-structures-and-algorithms-set-11/"
},
{
"code": null,
"e": 25243,
"s": 24853,
"text": "3. A weight-balanced tree is a binary tree in which for each node. The number of nodes in the left sub tree is at least half and at most twice the number of nodes in the right sub tree. The maximum possible height (number of nodes on the path from the root to the farthest leaf) of such a tree on n nodes is best described by which of the following?a) log2 nb) log4/3 nc) log3 nd) log3/2 n"
},
{
"code": null,
"e": 25253,
"s": 25243,
"text": "Answer(d)"
},
{
"code": null,
"e": 25332,
"s": 25253,
"text": "Let the maximum possible height of a tree with n nodes is represented by H(n)."
},
{
"code": null,
"e": 25427,
"s": 25332,
"text": "The maximum possible value of H(n) can be approximately written using the following recursion:"
},
{
"code": null,
"e": 25455,
"s": 25427,
"text": " H(n) = H(2n/3) + 1 \n"
},
{
"code": null,
"e": 25551,
"s": 25455,
"text": "The solution of above recurrence is log3/2 n. We can simply get it by drawing a recursion tree."
},
{
"code": null,
"e": 25679,
"s": 25551,
"text": "4. Consider the following algorithm for searching for a given number x in an unsorted – array A[1..n] having n distinct values:"
},
{
"code": null,
"e": 25771,
"s": 25679,
"text": "1) Choose an i uniformly at random from 1..n; \n2) If A[i] = x then Stop else Goto 1; "
},
{
"code": null,
"e": 25912,
"s": 25771,
"text": "Assuming that x is present in A, what is the expected number of comparisons made by the algorithm before it terminates?a) nb) n-lc) 2nd) n/2"
},
{
"code": null,
"e": 25922,
"s": 25912,
"text": "Answer(a)"
},
{
"code": null,
"e": 26012,
"s": 25922,
"text": "If you remember the coin and dice questions, you can just guess the answer for the above."
},
{
"code": null,
"e": 26042,
"s": 26012,
"text": "Below is proof of the answer."
},
{
"code": null,
"e": 26153,
"s": 26042,
"text": "Let expected number of comparisons be E. Value of E is sum of following expression for all the possible cases."
},
{
"code": null,
"e": 26215,
"s": 26153,
"text": "number_of_comparisons_for_a_case * probability_for_the_case \n"
},
{
"code": null,
"e": 26222,
"s": 26215,
"text": "Case 1"
},
{
"code": null,
"e": 26325,
"s": 26222,
"text": " If A[i] is found in the first attempt \n number of comparisons = 1\n probability of the case = 1/n\n"
},
{
"code": null,
"e": 26332,
"s": 26325,
"text": "Case 2"
},
{
"code": null,
"e": 26444,
"s": 26332,
"text": " If A[i] is found in the second attempt \n number of comparisons = 2\n probability of the case = (n-1)/n*1/n\n"
},
{
"code": null,
"e": 26451,
"s": 26444,
"text": "Case 3"
},
{
"code": null,
"e": 26570,
"s": 26451,
"text": " If A[i] is found in the third attempt \n number of comparisons = 2\n probability of the case = (n-1)/n*(n-1)/n*1/n\n"
},
{
"code": null,
"e": 26655,
"s": 26570,
"text": "There are actually infinite such cases. So, we have following infinite series for E."
},
{
"code": null,
"e": 26727,
"s": 26655,
"text": "E = 1/n + [(n-1)/n]*[1/n]*2 + [(n-1)/n]*[(n-1)/n]*[1/n]*3 + .... (1)\n"
},
{
"code": null,
"e": 26779,
"s": 26727,
"text": "After multiplying equation (1) with (n-1)/n, we get"
},
{
"code": null,
"e": 26926,
"s": 26779,
"text": "E (n-1)/n = [(n-1)/n]*[1/n] + [(n-1)/n]*[(n-1)/n]*[1/n]*2 + \n [(n-1)/n]*[(n-1)/n]*[(n-1)/n]*[1/n]*3 ..........(2)\n"
},
{
"code": null,
"e": 26959,
"s": 26926,
"text": "Subtracting (2) from (1), we get"
},
{
"code": null,
"e": 27021,
"s": 26959,
"text": "E/n = 1/n + (n-1)/n*1/n + (n-1)/n*(n-1)/n*1/n + ............\n"
},
{
"code": null,
"e": 27125,
"s": 27021,
"text": "The expression on the right side is a GP with infinite elements. Let us apply the sum formula (a/(1-r))"
},
{
"code": null,
"e": 27165,
"s": 27125,
"text": " E/n = [1/n]/[1-(n-1)/n] = 1\n E = n\n"
},
{
"code": null,
"e": 27314,
"s": 27165,
"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": 27327,
"s": 27314,
"text": "GATE-CS-2002"
},
{
"code": null,
"e": 27345,
"s": 27327,
"text": "GATE-CS-DS-&-Algo"
},
{
"code": null,
"e": 27353,
"s": 27345,
"text": "GATE CS"
},
{
"code": null,
"e": 27357,
"s": 27353,
"text": "MCQ"
},
{
"code": null,
"e": 27455,
"s": 27357,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27464,
"s": 27455,
"text": "Comments"
},
{
"code": null,
"e": 27477,
"s": 27464,
"text": "Old Comments"
},
{
"code": null,
"e": 27526,
"s": 27477,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 27547,
"s": 27526,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 27572,
"s": 27547,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 27604,
"s": 27572,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 27643,
"s": 27604,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 27683,
"s": 27643,
"text": "Data Structures and Algorithms | Set 21"
},
{
"code": null,
"e": 27730,
"s": 27683,
"text": "Practice questions on Height balanced/AVL Tree"
},
{
"code": null,
"e": 27756,
"s": 27730,
"text": "Operating Systems | Set 1"
},
{
"code": null,
"e": 27782,
"s": 27756,
"text": "Computer Networks | Set 1"
}
] |
Expectation or expected value of an array - GeeksforGeeks
|
29 Apr, 2021
Expectation or expected value of any group of numbers in probability is the long-run average value of repetitions of the experiment it represents. For example, the expected value in rolling a six-sided die is 3.5, because the average of all the numbers that come up in an extremely large number of rolls is close to 3.5. Less roughly, the law of large numbers states that the arithmetic mean of the values almost surely converges to the expected value as the number of repetitions approaches infinity. The expected value is also known as the expectation, mathematical expectation, EV, or first moment. Given an array, the task is to calculate the expected value of the array.Examples :
Input : [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
Output : 3.5
Input :[1.0, 9.0, 6.0, 7.0, 8.0, 12.0]
Output :7.16
Below is the implementation :
C++
Java
Python3
C#
PHP
Javascript
// CPP code to calculate expected// value of an array#include <bits/stdc++.h>using namespace std; // Function to calculate expectationfloat calc_Expectation(float a[], float n){ /*variable prb is for probability of each element which is same for each element */ float prb = (1 / n); // calculating expectation overall float sum = 0; for (int i = 0; i < n; i++) sum += a[i] * prb; // returning expectation as sum return sum;} // Driver programint main(){ float expect, n = 6.0; float a[6] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 }; // Function for calculating expectation expect = calc_Expectation(a, n); // Display expectation of given array cout << "Expectation of array E(X) is : " << expect << "\n"; return 0;}
// Java code to calculate expected// value of an arrayimport java.io.*; class GFG{ // Function to calculate expectation static float calc_Expectation(float a[], float n) { // Variable prb is for probability of each // element which is same for each element float prb = (1 / n); // calculating expectation overall float sum = 0; for (int i = 0; i < n; i++) sum += a[i] * prb; // returning expectation as sum return sum; } // Driver program public static void main(String args[]) { float expect, n = 6f; float a[] = { 1f, 2f, 3f, 4f, 5f, 6f }; // Function for calculating expectation expect = calc_Expectation(a, n); // Display expectation of given array System.out.println("Expectation of array E(X) is : " + expect); }} // This code is contributed by Anshika Goyal.
# python code to calculate expected# value of an array # Function to calculate expectationdef calc_Expectation(a, n): # variable prb is for probability # of each element which is same for # each element prb = 1 / n # calculating expectation overall sum = 0 for i in range(0, n): sum += (a[i] * prb) # returning expectation as sum return float(sum) # Driver programn = 6;a = [ 1.0, 2.0, 3.0,4.0, 5.0, 6.0 ] # Function for calculating expectationexpect = calc_Expectation(a, n) # Display expectation of given arrayprint( "Expectation of array E(X) is : ", expect ) # This code is contributed by Sam007
// C# code to calculate expected// value of an arrayusing System; class GFG { // Function to calculate expectation static float calc_Expectation(float []a, float n) { // Variable prb is for probability // of each element which is same // for each element float prb = (1 / n); // calculating expectation overall float sum = 0; for (int i = 0; i < n; i++) sum += a[i] * prb; // returning expectation as sum return sum; } // Driver program public static void Main() { float expect, n = 6f; float []a = { 1f, 2f, 3f, 4f, 5f, 6f }; // Function for calculating // expectation expect = calc_Expectation(a, n); // Display expectation of given // array Console.WriteLine("Expectation" + " of array E(X) is : " + expect); }} // This code is contributed by vt_m.
<?php// PHP code to calculate expected// value of an array // Function to calculate expectationfunction calc_Expectation($a, $n){ /*variable prb is for probability of each element which is same for each element */ $prb = (1 / $n); // calculating expectation overall $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $a[$i] * $prb; // returning expectation as sum return $sum;} // Driver Code$n = 6.0;$a = array(1.0, 2.0, 3.0, 4.0, 5.0, 6.0); // Function for calculating expectation$expect = calc_Expectation($a, $n); // Display expectation of given arrayecho "Expectation of array E(X) is : ". $expect . "\n"; // This code is contributed by Sam007?>
<script>// Javascript code to calculate expected// value of an array // Function to calculate expectation function calc_Expectation(a, n) { // Variable prb is for probability of each // element which is same for each element let prb = (1 / n); // calculating expectation overall let sum = 0; for (let i = 0; i < n; i++) sum += a[i] * prb; // returning expectation as sum return sum; } // driver function let expect, n = 6; let a = [ 1, 2, 3, 4, 5, 6 ]; // Function for calculating expectation expect = calc_Expectation(a, n); // Display expectation of given array document.write("Expectation of array E(X) is : " + expect); </script>
Output :
Expectation of array E(X) is : 3.5
Time complexity of the program is O(n).As we can see that the expected value is actually average of numbers, we can also simply compute average of array.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.
vt_m
Sam007
sanjoy_62
Randomized
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reservoir Sampling
Shuffle a deck of cards
Randomized Algorithms | Set 1 (Introduction and Analysis)
Karger's algorithm for Minimum Cut | Set 1 (Introduction and Implementation)
Random number generator in arbitrary probability distribution fashion
Randomized Algorithms | Set 2 (Classification and Applications)
Number guessing game in C
Generate 0 and 1 with 25% and 75% probability
Mid-Square hashing
Randomized Binary Search Algorithm
|
[
{
"code": null,
"e": 25051,
"s": 25023,
"text": "\n29 Apr, 2021"
},
{
"code": null,
"e": 25739,
"s": 25051,
"text": "Expectation or expected value of any group of numbers in probability is the long-run average value of repetitions of the experiment it represents. For example, the expected value in rolling a six-sided die is 3.5, because the average of all the numbers that come up in an extremely large number of rolls is close to 3.5. Less roughly, the law of large numbers states that the arithmetic mean of the values almost surely converges to the expected value as the number of repetitions approaches infinity. The expected value is also known as the expectation, mathematical expectation, EV, or first moment. Given an array, the task is to calculate the expected value of the array.Examples : "
},
{
"code": null,
"e": 25844,
"s": 25739,
"text": "Input : [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]\nOutput : 3.5\n\nInput :[1.0, 9.0, 6.0, 7.0, 8.0, 12.0]\nOutput :7.16"
},
{
"code": null,
"e": 25876,
"s": 25844,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 25880,
"s": 25876,
"text": "C++"
},
{
"code": null,
"e": 25885,
"s": 25880,
"text": "Java"
},
{
"code": null,
"e": 25893,
"s": 25885,
"text": "Python3"
},
{
"code": null,
"e": 25896,
"s": 25893,
"text": "C#"
},
{
"code": null,
"e": 25900,
"s": 25896,
"text": "PHP"
},
{
"code": null,
"e": 25911,
"s": 25900,
"text": "Javascript"
},
{
"code": "// CPP code to calculate expected// value of an array#include <bits/stdc++.h>using namespace std; // Function to calculate expectationfloat calc_Expectation(float a[], float n){ /*variable prb is for probability of each element which is same for each element */ float prb = (1 / n); // calculating expectation overall float sum = 0; for (int i = 0; i < n; i++) sum += a[i] * prb; // returning expectation as sum return sum;} // Driver programint main(){ float expect, n = 6.0; float a[6] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 }; // Function for calculating expectation expect = calc_Expectation(a, n); // Display expectation of given array cout << \"Expectation of array E(X) is : \" << expect << \"\\n\"; return 0;}",
"e": 26717,
"s": 25911,
"text": null
},
{
"code": "// Java code to calculate expected// value of an arrayimport java.io.*; class GFG{ // Function to calculate expectation static float calc_Expectation(float a[], float n) { // Variable prb is for probability of each // element which is same for each element float prb = (1 / n); // calculating expectation overall float sum = 0; for (int i = 0; i < n; i++) sum += a[i] * prb; // returning expectation as sum return sum; } // Driver program public static void main(String args[]) { float expect, n = 6f; float a[] = { 1f, 2f, 3f, 4f, 5f, 6f }; // Function for calculating expectation expect = calc_Expectation(a, n); // Display expectation of given array System.out.println(\"Expectation of array E(X) is : \" + expect); }} // This code is contributed by Anshika Goyal.",
"e": 27689,
"s": 26717,
"text": null
},
{
"code": "# python code to calculate expected# value of an array # Function to calculate expectationdef calc_Expectation(a, n): # variable prb is for probability # of each element which is same for # each element prb = 1 / n # calculating expectation overall sum = 0 for i in range(0, n): sum += (a[i] * prb) # returning expectation as sum return float(sum) # Driver programn = 6;a = [ 1.0, 2.0, 3.0,4.0, 5.0, 6.0 ] # Function for calculating expectationexpect = calc_Expectation(a, n) # Display expectation of given arrayprint( \"Expectation of array E(X) is : \", expect ) # This code is contributed by Sam007",
"e": 28375,
"s": 27689,
"text": null
},
{
"code": "// C# code to calculate expected// value of an arrayusing System; class GFG { // Function to calculate expectation static float calc_Expectation(float []a, float n) { // Variable prb is for probability // of each element which is same // for each element float prb = (1 / n); // calculating expectation overall float sum = 0; for (int i = 0; i < n; i++) sum += a[i] * prb; // returning expectation as sum return sum; } // Driver program public static void Main() { float expect, n = 6f; float []a = { 1f, 2f, 3f, 4f, 5f, 6f }; // Function for calculating // expectation expect = calc_Expectation(a, n); // Display expectation of given // array Console.WriteLine(\"Expectation\" + \" of array E(X) is : \" + expect); }} // This code is contributed by vt_m.",
"e": 29425,
"s": 28375,
"text": null
},
{
"code": "<?php// PHP code to calculate expected// value of an array // Function to calculate expectationfunction calc_Expectation($a, $n){ /*variable prb is for probability of each element which is same for each element */ $prb = (1 / $n); // calculating expectation overall $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $a[$i] * $prb; // returning expectation as sum return $sum;} // Driver Code$n = 6.0;$a = array(1.0, 2.0, 3.0, 4.0, 5.0, 6.0); // Function for calculating expectation$expect = calc_Expectation($a, $n); // Display expectation of given arrayecho \"Expectation of array E(X) is : \". $expect . \"\\n\"; // This code is contributed by Sam007?>",
"e": 30144,
"s": 29425,
"text": null
},
{
"code": "<script>// Javascript code to calculate expected// value of an array // Function to calculate expectation function calc_Expectation(a, n) { // Variable prb is for probability of each // element which is same for each element let prb = (1 / n); // calculating expectation overall let sum = 0; for (let i = 0; i < n; i++) sum += a[i] * prb; // returning expectation as sum return sum; } // driver function let expect, n = 6; let a = [ 1, 2, 3, 4, 5, 6 ]; // Function for calculating expectation expect = calc_Expectation(a, n); // Display expectation of given array document.write(\"Expectation of array E(X) is : \" + expect); </script>",
"e": 30981,
"s": 30144,
"text": null
},
{
"code": null,
"e": 30992,
"s": 30981,
"text": "Output : "
},
{
"code": null,
"e": 31027,
"s": 30992,
"text": "Expectation of array E(X) is : 3.5"
},
{
"code": null,
"e": 31603,
"s": 31027,
"text": "Time complexity of the program is O(n).As we can see that the expected value is actually average of numbers, we can also simply compute average of array.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": 31608,
"s": 31603,
"text": "vt_m"
},
{
"code": null,
"e": 31615,
"s": 31608,
"text": "Sam007"
},
{
"code": null,
"e": 31625,
"s": 31615,
"text": "sanjoy_62"
},
{
"code": null,
"e": 31636,
"s": 31625,
"text": "Randomized"
},
{
"code": null,
"e": 31734,
"s": 31636,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31753,
"s": 31734,
"text": "Reservoir Sampling"
},
{
"code": null,
"e": 31777,
"s": 31753,
"text": "Shuffle a deck of cards"
},
{
"code": null,
"e": 31835,
"s": 31777,
"text": "Randomized Algorithms | Set 1 (Introduction and Analysis)"
},
{
"code": null,
"e": 31912,
"s": 31835,
"text": "Karger's algorithm for Minimum Cut | Set 1 (Introduction and Implementation)"
},
{
"code": null,
"e": 31982,
"s": 31912,
"text": "Random number generator in arbitrary probability distribution fashion"
},
{
"code": null,
"e": 32046,
"s": 31982,
"text": "Randomized Algorithms | Set 2 (Classification and Applications)"
},
{
"code": null,
"e": 32072,
"s": 32046,
"text": "Number guessing game in C"
},
{
"code": null,
"e": 32118,
"s": 32072,
"text": "Generate 0 and 1 with 25% and 75% probability"
},
{
"code": null,
"e": 32137,
"s": 32118,
"text": "Mid-Square hashing"
}
] |
Program to remove duplicate characters from a given string in Python
|
Suppose we have a string s. We have to remove all duplicate characters that have already appeared before. The final string will have same ordering of characters like the actual one.
We can solve this by using ordered dictionary to maintain the insertion order of the characters. The value will be the frequency of those characters, however the frequency values are not important here. After forming the dictionary, we can simply take the keys and join them to get the string.
So, if the input is like s = "bbabcaaccdbaabababc", then the output will be "bacd".
d := a dictionary where keys are stored in order by their insertion order
for each character c in s, doif c is not present in d, thend[c] := 0d[c] := d[c] + 1
if c is not present in d, thend[c] := 0
d[c] := 0
d[c] := d[c] + 1
join the keys one after another in proper order to make the output string and return.
Let us see the following implementation to get better understanding −
from collections import OrderedDict
def solve(s):
d = OrderedDict()
for c in s:
if c not in d:
d[c] = 0
d[c] += 1
return ''.join(d.keys())
s = "bbabcaaccdbaabababc"
print(solve(s))
"bbabcaaccdbaabababc"
"bacd"
|
[
{
"code": null,
"e": 1244,
"s": 1062,
"text": "Suppose we have a string s. We have to remove all duplicate characters that have already appeared before. The final string will have same ordering of characters like the actual one."
},
{
"code": null,
"e": 1538,
"s": 1244,
"text": "We can solve this by using ordered dictionary to maintain the insertion order of the characters. The value will be the frequency of those characters, however the frequency values are not important here. After forming the dictionary, we can simply take the keys and join them to get the string."
},
{
"code": null,
"e": 1622,
"s": 1538,
"text": "So, if the input is like s = \"bbabcaaccdbaabababc\", then the output will be \"bacd\"."
},
{
"code": null,
"e": 1696,
"s": 1622,
"text": "d := a dictionary where keys are stored in order by their insertion order"
},
{
"code": null,
"e": 1781,
"s": 1696,
"text": "for each character c in s, doif c is not present in d, thend[c] := 0d[c] := d[c] + 1"
},
{
"code": null,
"e": 1821,
"s": 1781,
"text": "if c is not present in d, thend[c] := 0"
},
{
"code": null,
"e": 1831,
"s": 1821,
"text": "d[c] := 0"
},
{
"code": null,
"e": 1848,
"s": 1831,
"text": "d[c] := d[c] + 1"
},
{
"code": null,
"e": 1934,
"s": 1848,
"text": "join the keys one after another in proper order to make the output string and return."
},
{
"code": null,
"e": 2004,
"s": 1934,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2217,
"s": 2004,
"text": "from collections import OrderedDict\ndef solve(s):\n d = OrderedDict()\n for c in s:\n if c not in d:\n d[c] = 0\n d[c] += 1\n\n return ''.join(d.keys())\n\ns = \"bbabcaaccdbaabababc\"\nprint(solve(s))"
},
{
"code": null,
"e": 2240,
"s": 2217,
"text": "\"bbabcaaccdbaabababc\"\n"
},
{
"code": null,
"e": 2247,
"s": 2240,
"text": "\"bacd\""
}
] |
Mixed Effects Random Forests in Python | by Sourav Dey | Towards Data Science
|
This blog post introduces an open source Python package for implementing mixed effects random forests (MERFs). The motivation for writing this package came from the models we have been building at Manifold. Much of the data we come across is clustered, e.g. longitudinal data from individuals, data clustered by demographics, etc. In many of these circumstances, we’ve found that using MERFs provide substantial improvements compared to vanilla random forests.
MERFs are great if your model has non-negligible random effects, e.g. there are large idiosyncrasies by cluster. You can pip install our package off of PyPi by typing:
pip install merf
The source code is available here. Contribute to it! The package is based on the excellent published work of Prof. Larocque from the Department of Decision Sciences at HEC and Prof. Ahlem from the Department of Marketing at l’UQAM.
Lots of data in the wild has a clustered structure. The most common example we see is longitudinal clustering, where there are multiple measurements per individual of a phenomena you wish to model. For example, say we want to model math test scores as a function of sleep factors but we have multiple measurements per student. In this case, the specific student is a cluster. Another common example is clustering due to a categorical variable. Continuing the example above, the specific math teacher a student has is a cluster. Clustering can also be hierarchical. For example, in the the example above there is a student cluster contained within a teacher cluster contained within a school cluster. When making this model, we want to learn the common effect of sleep factors on the math test scores — but want to account for the idiosyncrasies by student, teacher, and school. There are four sensible model building strategies for clustered data:
Make a separate models per cluster. This strategy is unsatisfying for two reasons: (a) sharding by cluster makes it so that any given model does not have much training data and (b) the model can’t learn across the population.Make one global model for all clusters. With this strategy, the model can learn across the population, but won’t learn anything idiosyncratic about particular clusters. For example, some students may have higher mathematical ability, irrespective of sleep factors. It would be nice to model that effect explicitly, rather than lumping it into the sleep factors.Make one global model, but put in cluster id as a feature. This is a sensible strategy, but has scaling issues as the cluster size grows. Specifically, in a random forest, a single categorical variable can only have a small cardinality before the splitting decision becomes unwieldy. In R that is about n_categories = 30. In H20, that is n_categories = 64. The random forest implementation in Python Scikit-learn doesn’t even support non-binary categorical variables. One hot encoding cluster is an option, but this has known bad performance as explained in this excellent blog post (and as we’ll show below). Long story short, directly using high cardinality categorical variables as features in a model sucks.Mixed effect model. This is the right way to attack clustered data. In a mixed effect model, each cluster gets a random effect that is learned but drawn from a prior that is itself learned from the data. As explained below, this is not a new idea, statisticians have been doing this forever. But mixed effects random forests are novel — they combine the best of linear mixed effects models with the power of non-parametric modeling, where you don’t need to understand the “physics” of the problem.
Make a separate models per cluster. This strategy is unsatisfying for two reasons: (a) sharding by cluster makes it so that any given model does not have much training data and (b) the model can’t learn across the population.
Make one global model for all clusters. With this strategy, the model can learn across the population, but won’t learn anything idiosyncratic about particular clusters. For example, some students may have higher mathematical ability, irrespective of sleep factors. It would be nice to model that effect explicitly, rather than lumping it into the sleep factors.
Make one global model, but put in cluster id as a feature. This is a sensible strategy, but has scaling issues as the cluster size grows. Specifically, in a random forest, a single categorical variable can only have a small cardinality before the splitting decision becomes unwieldy. In R that is about n_categories = 30. In H20, that is n_categories = 64. The random forest implementation in Python Scikit-learn doesn’t even support non-binary categorical variables. One hot encoding cluster is an option, but this has known bad performance as explained in this excellent blog post (and as we’ll show below). Long story short, directly using high cardinality categorical variables as features in a model sucks.
Mixed effect model. This is the right way to attack clustered data. In a mixed effect model, each cluster gets a random effect that is learned but drawn from a prior that is itself learned from the data. As explained below, this is not a new idea, statisticians have been doing this forever. But mixed effects random forests are novel — they combine the best of linear mixed effects models with the power of non-parametric modeling, where you don’t need to understand the “physics” of the problem.
Linear mixed effects (LME) modeling is a classic technique. Let’s look at this in some detail because it motivates the MERF model. The LME model assumes a generative model of the form:
In the equation above:
y is the target variable.
X is the fixed effect features. X is assumed to be p dimensional, e.g. there are p features.
Z is the random effect features. Z is assumed to be q dimensional, e.g. there are q features.
e is independent, identically distributed (iid) noise. It is distributed as N(0, sigma_e2)
a is the fixed effect coefficients. They are the same for all clusters.
i is the cluster index. We assume that there are k clusters in the training.
bi is the random effect coefficients. They are different per cluster i but are assumed to be drawn from the same distribution. In the classic LME problem, this distribution is assumed to be N(0, Sigma_b) where Sigma_b is learned from the data.
The LME is a special case of the more general hierarchical Bayesian model. These models assume that the fixed effect coefficients are unknown constants but that the random effect coefficients are drawn from some unknown distribution. The random effect coefficients and prior are learned together using iterative algorithms. This article is not about hierarchical Bayesian models though. If you want to learn more about them this is a great resource. Though hierarchical Bayesian modeling is a mature field, they require you to specify a functional form to the regression, i.e. you need to know the physics of the problem. Unfortunately, in many situations, particularly in complex systems, it’s hard to specify a functional form. This is where the random forest shines. Sinces it cuts up feature space, it can act as a universal function approximator. Our work at Manifold led us on a search to combine random forests with the power of mixed effects.
We found the answer in the excellent work of Prof. Larocque’s group at the Department of Decision Sciences at HEC Montreal. In a series of papers, they have illustrated a methodology to combine random forests with linear random effects. More importantly, Prof. Larocque has been very generous with his feedback to make the MERF Python package a reality.
Similar to LME, the MERF model assumes a generative model of the form:
Note all the terms are the same as the LME, except the linear fixed effect a*X is replaced with a general non-linear function f(.). In the paper, this non-linear function is learned using a random forest. More generally, f(.) can be any non-linear regression model like gradient boosting trees or a deep neural network. An expectation-maximization (EM) technique is used to fit the MERF. There are four parameters to fit:
f(.)
bi for all known clusters.
Sigma_b
sigma_e
We won’t go into the math here — the paper does it much better — but the basic intuition behind the EM algorithm is alternative optimization, e.g. optimize one parameter while keeping the others fixed. You keep doing this iteratively until convergence. Specifically, to fit MERF the steps are:
Fix all the bi and compute y* as y — bi*Z. Fit a random forest, f(X) to y* globally across all samples.Fix f(), Sigma_b, sigma_e. Optimize to find bi*. There is a closed form solution assuming a linear random effect and Gaussian prior.Fix f(), bi. Optimize to find Sigma_b and sigma_e. There is a closed form solution assuming a linear random effect and Gaussian prior.
Fix all the bi and compute y* as y — bi*Z. Fit a random forest, f(X) to y* globally across all samples.
Fix f(), Sigma_b, sigma_e. Optimize to find bi*. There is a closed form solution assuming a linear random effect and Gaussian prior.
Fix f(), bi. Optimize to find Sigma_b and sigma_e. There is a closed form solution assuming a linear random effect and Gaussian prior.
The generalized log likelihood (GLL), which can be computed at every iteration, is a measure of training loss. As the GLL goes down the fit improves. Once it flattens out we can usually stop iterating — the fit has converged. There is not much danger of overfitting with MERF — no more than the classic random forest which is fairly robust to overfitting. Once fit the MERF can be used to predict. For data in “known” clusters, that the MERF saw in training, the prediction includes the random effect correction:
For data in “new” clusters, that the MERF did not see in training, the prediction only includes the fixed effect:
Our contribution was to implement a MERF in Python and open source it. We implemented so that it adheres, as much as possible, to the scikit-learn model interface. We’ll illustrate with an example below. This example can be downloaded as a runnable Jupyter notebook here. We have three matrices containing our n_samples =500 of training data:
X. Matrix containing three fixed effect features. Dimension = 500 x 3.
y. Vector containing the single target variable. Dimension = 500 x 1.
clusters. Vector containing the cluster_id for each sample. Dimension = 500 x1. We have k = 100 unique clusters in the training data.
In this example, there is not an explicit Z matrix. We create one to model a random mean for each cluster. It is a matrix of all 1s with dimension = 500 x 1. Given the X, y, clusters, and Z matrices we can fix a MERF model to this data by instantiations a MERF model and running the fit method. The MERF model currently has two hyperparameters:
n_estimators. The number of trees in to train for the random forest.
max_iterations. The maximum number of iterations to run for the EM model.
We eventually plan on implementing early stopping for the EM algorithm as well. This will add an additional two hyper parameters, i.e. whether or not to early stop and what the patience on that should be. Here’s what the output of fit looks like. Note that fitting usually takes some time to run — especially if you run for many iterations. This is unavoidable because each EM iteration requires a random forest fit. Even with parallelization of the random forest fit a single MERF fit can take many minutes.
Once the model is trained we can access the final random forest and the final matrix of trained b_is through two public variables:
mrf.trained_rfmrf.trained_b
We can look at the distribution of the b’s. It looks approximately Gaussian with variance Sigma_b as expected:
The model also host the history of the EM iterations. We can look at the generalized log likelihood (GLL) at every step, the estimates of Sigma_b, sigma_e, and all the bi’s.
Once fit, the model can be used to predict on new samples given X, Z, and clusters. The predict code handles whether or not to apply the random effect correction based on if the cluster_id of the new sample was seen in training or not.
We tested the performance of MERF on synthetic data. The experimental setup mimics that of the published MERF paper. We generate data from this function:
In this equation:
m is a fixed constant of our choosing.
the bi are drawn from normal distribution N(0, sigma_b). They are constant per cluster i. sigma_b is a fixed constant of our choosing.
the error, e, is drawn IID from normal distribution N(0, sigma_e). sigma_e is a fixed constant of our choosing.
For our experiments, we choose various values for m, sigma_e, and sigma_b and generated 500 samples from 100 different unbalanced clusters. We summarize the values in the table below, but the specific values are not that important. What matters are two derived parameters, the percentage total effects variance (PTEV) and the percentage random effects variance (PREV). They are defined in detail in the paper, but intuitively they are:
PTEV = the amount of total variance that is not due to random noise. The higher it is, the more predictable the output y is.
PREV = the amount of PTEV that is due to random effect. The higher is it, the larger random effect there is.
We did an experiment comparing MERF to two competitors:
a random forest that does not take random effects into account, i.e. fitting a random forest on only X.
a random forest that includes one hot encoded cluster id as features, i.e. we create k new one hot encoded features, X_ohe, and join that with X and train a random forest on the combined [X, X_ohe] feature matrix.
We varied PTEV and PREV for the experiments and assessed performance on two different test sets:
test set consists of known clusters that the model trained on
test set consisted of new (unknown) clusters that the model had no knowledge of at training time
We use the average mean squared error (MSE) over 10 runs as our error metric. We define the MERF gain as the percentage gain over the compared algorithm:
The table and chart below summarize the results. MERF has marked performance gains over both of the compared models — particularly when the PREV is high (over 50%!). In addition, there is negligible loss in performance when predicting new clusters. MERF is a strictly better model when there are significant random effects in the data. It’s a winner. We have included the data generator as a utility module in merf package. The source code for the experiment is in a Jupyter notebook here. Check it out and run your own experiments!
Manifold is working on a thermal modelling problem for one of our clients. The problem is to predict, everyday, when a building is going to reach its target temperature based on a number of factors, e.g. outdoor temperature, outdoor humidity, indoor temperature the previous day. We have historical data that is clustered longitudinally by building. The clusters are highly imbalanced. For some buildings we have many years of data; for others we only have a few weeks. This problem is begging for a mixed effects model. We want to build one model that learns across the population, but, at the same time, accounts for the idiosyncrasies of each building.
Similar to the experiment above, we compared MERF against:
a random forest that does not take random effects into account, i.e. fitting a random forest on only the fixed effect features.
a random forest that includes one hot encoded building id as features, i.e. we create k new one hot encoded features, X_ohe, and join that with the fixed effect features and train a random forest on the combined [X, X_ohe] feature matrix.
Because of outliers, we changed the error metric to the median absolute error (MAE) rather than the MSE. We compare the performance using 5-fold cross validation on a small N~1000 data set. The results of the experiment are summarized below.
For this data set, there is a small MERF gain, but it’s not that significant. Looking at the MERF convergence plot we get some clues.
The GLL is flat even though we run for 100 iterations and the other variables are converging. It’s not clear what that means. In addition, the estimated error variance, sigma_e, is very significant. It seems like the data has a very low PTEV (because of outliers?). The one hot encoding (OHE) model is doing ok because the number of buildings is small — k = 15. As the number of buildings scale the OHE model performance will suffer more.
All of these factors, coupled with the fact that there is not that much data, leaves this experiment a bit inconclusive. MERF is not performing poorer than it’s counterparts — so it doesn’t hurt — and in fact has a slight gain on average. This experiment needs more analysis — when we do we’ll publish them on this blog.
Mixed effects models are powerful — and lots of data has a structure that is amenable to using them. Add them to your repertoire of models. Mixed effects random forests (MERFs) are a piece of the puzzle. They combine the best of random forests with the best of mixed effects models. We hope you find them useful. More importantly, we’re looking for help extending the MERF package! We would love more contributors. We have a bunch of open issues to work on:
Add early stopping.
Add more learners, e.g. gradient boosting trees, xgboost, etc.
Add generalization to classification using GMERFs. See paper here.
Conduct novel research into using a nonlinear mixed effect, rather than a purely linear one.
Send us a pull request!
Manifold is an AI studio with offices in Silicon Valley and Boston. Leading companies work with us on new AI solutions when the stakes are high. We accelerate time to market, create new IP, and foster in-house capabilities. Manifold’s team is experienced in conceiving of and deploying production machine learning systems and data platforms at places like Google, Facebook, Qualcomm, MIT, and successful venture-backed startups. Our domain expertise spans electronics (consumer and industrial), wireless, healthcare, and marketing. We have an extended network of experts that we draw on across industry and engineering sub-specialties.
Wanna work on stuff like this? Reach out at [email protected]! We’re hiring data scientists.
|
[
{
"code": null,
"e": 633,
"s": 172,
"text": "This blog post introduces an open source Python package for implementing mixed effects random forests (MERFs). The motivation for writing this package came from the models we have been building at Manifold. Much of the data we come across is clustered, e.g. longitudinal data from individuals, data clustered by demographics, etc. In many of these circumstances, we’ve found that using MERFs provide substantial improvements compared to vanilla random forests."
},
{
"code": null,
"e": 801,
"s": 633,
"text": "MERFs are great if your model has non-negligible random effects, e.g. there are large idiosyncrasies by cluster. You can pip install our package off of PyPi by typing:"
},
{
"code": null,
"e": 818,
"s": 801,
"text": "pip install merf"
},
{
"code": null,
"e": 1050,
"s": 818,
"text": "The source code is available here. Contribute to it! The package is based on the excellent published work of Prof. Larocque from the Department of Decision Sciences at HEC and Prof. Ahlem from the Department of Marketing at l’UQAM."
},
{
"code": null,
"e": 2000,
"s": 1050,
"text": "Lots of data in the wild has a clustered structure. The most common example we see is longitudinal clustering, where there are multiple measurements per individual of a phenomena you wish to model. For example, say we want to model math test scores as a function of sleep factors but we have multiple measurements per student. In this case, the specific student is a cluster. Another common example is clustering due to a categorical variable. Continuing the example above, the specific math teacher a student has is a cluster. Clustering can also be hierarchical. For example, in the the example above there is a student cluster contained within a teacher cluster contained within a school cluster. When making this model, we want to learn the common effect of sleep factors on the math test scores — but want to account for the idiosyncrasies by student, teacher, and school. There are four sensible model building strategies for clustered data:"
},
{
"code": null,
"e": 3795,
"s": 2000,
"text": "Make a separate models per cluster. This strategy is unsatisfying for two reasons: (a) sharding by cluster makes it so that any given model does not have much training data and (b) the model can’t learn across the population.Make one global model for all clusters. With this strategy, the model can learn across the population, but won’t learn anything idiosyncratic about particular clusters. For example, some students may have higher mathematical ability, irrespective of sleep factors. It would be nice to model that effect explicitly, rather than lumping it into the sleep factors.Make one global model, but put in cluster id as a feature. This is a sensible strategy, but has scaling issues as the cluster size grows. Specifically, in a random forest, a single categorical variable can only have a small cardinality before the splitting decision becomes unwieldy. In R that is about n_categories = 30. In H20, that is n_categories = 64. The random forest implementation in Python Scikit-learn doesn’t even support non-binary categorical variables. One hot encoding cluster is an option, but this has known bad performance as explained in this excellent blog post (and as we’ll show below). Long story short, directly using high cardinality categorical variables as features in a model sucks.Mixed effect model. This is the right way to attack clustered data. In a mixed effect model, each cluster gets a random effect that is learned but drawn from a prior that is itself learned from the data. As explained below, this is not a new idea, statisticians have been doing this forever. But mixed effects random forests are novel — they combine the best of linear mixed effects models with the power of non-parametric modeling, where you don’t need to understand the “physics” of the problem."
},
{
"code": null,
"e": 4021,
"s": 3795,
"text": "Make a separate models per cluster. This strategy is unsatisfying for two reasons: (a) sharding by cluster makes it so that any given model does not have much training data and (b) the model can’t learn across the population."
},
{
"code": null,
"e": 4383,
"s": 4021,
"text": "Make one global model for all clusters. With this strategy, the model can learn across the population, but won’t learn anything idiosyncratic about particular clusters. For example, some students may have higher mathematical ability, irrespective of sleep factors. It would be nice to model that effect explicitly, rather than lumping it into the sleep factors."
},
{
"code": null,
"e": 5095,
"s": 4383,
"text": "Make one global model, but put in cluster id as a feature. This is a sensible strategy, but has scaling issues as the cluster size grows. Specifically, in a random forest, a single categorical variable can only have a small cardinality before the splitting decision becomes unwieldy. In R that is about n_categories = 30. In H20, that is n_categories = 64. The random forest implementation in Python Scikit-learn doesn’t even support non-binary categorical variables. One hot encoding cluster is an option, but this has known bad performance as explained in this excellent blog post (and as we’ll show below). Long story short, directly using high cardinality categorical variables as features in a model sucks."
},
{
"code": null,
"e": 5593,
"s": 5095,
"text": "Mixed effect model. This is the right way to attack clustered data. In a mixed effect model, each cluster gets a random effect that is learned but drawn from a prior that is itself learned from the data. As explained below, this is not a new idea, statisticians have been doing this forever. But mixed effects random forests are novel — they combine the best of linear mixed effects models with the power of non-parametric modeling, where you don’t need to understand the “physics” of the problem."
},
{
"code": null,
"e": 5778,
"s": 5593,
"text": "Linear mixed effects (LME) modeling is a classic technique. Let’s look at this in some detail because it motivates the MERF model. The LME model assumes a generative model of the form:"
},
{
"code": null,
"e": 5801,
"s": 5778,
"text": "In the equation above:"
},
{
"code": null,
"e": 5827,
"s": 5801,
"text": "y is the target variable."
},
{
"code": null,
"e": 5920,
"s": 5827,
"text": "X is the fixed effect features. X is assumed to be p dimensional, e.g. there are p features."
},
{
"code": null,
"e": 6014,
"s": 5920,
"text": "Z is the random effect features. Z is assumed to be q dimensional, e.g. there are q features."
},
{
"code": null,
"e": 6105,
"s": 6014,
"text": "e is independent, identically distributed (iid) noise. It is distributed as N(0, sigma_e2)"
},
{
"code": null,
"e": 6177,
"s": 6105,
"text": "a is the fixed effect coefficients. They are the same for all clusters."
},
{
"code": null,
"e": 6254,
"s": 6177,
"text": "i is the cluster index. We assume that there are k clusters in the training."
},
{
"code": null,
"e": 6498,
"s": 6254,
"text": "bi is the random effect coefficients. They are different per cluster i but are assumed to be drawn from the same distribution. In the classic LME problem, this distribution is assumed to be N(0, Sigma_b) where Sigma_b is learned from the data."
},
{
"code": null,
"e": 7451,
"s": 6498,
"text": "The LME is a special case of the more general hierarchical Bayesian model. These models assume that the fixed effect coefficients are unknown constants but that the random effect coefficients are drawn from some unknown distribution. The random effect coefficients and prior are learned together using iterative algorithms. This article is not about hierarchical Bayesian models though. If you want to learn more about them this is a great resource. Though hierarchical Bayesian modeling is a mature field, they require you to specify a functional form to the regression, i.e. you need to know the physics of the problem. Unfortunately, in many situations, particularly in complex systems, it’s hard to specify a functional form. This is where the random forest shines. Sinces it cuts up feature space, it can act as a universal function approximator. Our work at Manifold led us on a search to combine random forests with the power of mixed effects."
},
{
"code": null,
"e": 7805,
"s": 7451,
"text": "We found the answer in the excellent work of Prof. Larocque’s group at the Department of Decision Sciences at HEC Montreal. In a series of papers, they have illustrated a methodology to combine random forests with linear random effects. More importantly, Prof. Larocque has been very generous with his feedback to make the MERF Python package a reality."
},
{
"code": null,
"e": 7876,
"s": 7805,
"text": "Similar to LME, the MERF model assumes a generative model of the form:"
},
{
"code": null,
"e": 8299,
"s": 7876,
"text": "Note all the terms are the same as the LME, except the linear fixed effect a*X is replaced with a general non-linear function f(.). In the paper, this non-linear function is learned using a random forest. More generally, f(.) can be any non-linear regression model like gradient boosting trees or a deep neural network. An expectation-maximization (EM) technique is used to fit the MERF. There are four parameters to fit:"
},
{
"code": null,
"e": 8304,
"s": 8299,
"text": "f(.)"
},
{
"code": null,
"e": 8331,
"s": 8304,
"text": "bi for all known clusters."
},
{
"code": null,
"e": 8339,
"s": 8331,
"text": "Sigma_b"
},
{
"code": null,
"e": 8347,
"s": 8339,
"text": "sigma_e"
},
{
"code": null,
"e": 8641,
"s": 8347,
"text": "We won’t go into the math here — the paper does it much better — but the basic intuition behind the EM algorithm is alternative optimization, e.g. optimize one parameter while keeping the others fixed. You keep doing this iteratively until convergence. Specifically, to fit MERF the steps are:"
},
{
"code": null,
"e": 9011,
"s": 8641,
"text": "Fix all the bi and compute y* as y — bi*Z. Fit a random forest, f(X) to y* globally across all samples.Fix f(), Sigma_b, sigma_e. Optimize to find bi*. There is a closed form solution assuming a linear random effect and Gaussian prior.Fix f(), bi. Optimize to find Sigma_b and sigma_e. There is a closed form solution assuming a linear random effect and Gaussian prior."
},
{
"code": null,
"e": 9115,
"s": 9011,
"text": "Fix all the bi and compute y* as y — bi*Z. Fit a random forest, f(X) to y* globally across all samples."
},
{
"code": null,
"e": 9248,
"s": 9115,
"text": "Fix f(), Sigma_b, sigma_e. Optimize to find bi*. There is a closed form solution assuming a linear random effect and Gaussian prior."
},
{
"code": null,
"e": 9383,
"s": 9248,
"text": "Fix f(), bi. Optimize to find Sigma_b and sigma_e. There is a closed form solution assuming a linear random effect and Gaussian prior."
},
{
"code": null,
"e": 9897,
"s": 9383,
"text": "The generalized log likelihood (GLL), which can be computed at every iteration, is a measure of training loss. As the GLL goes down the fit improves. Once it flattens out we can usually stop iterating — the fit has converged. There is not much danger of overfitting with MERF — no more than the classic random forest which is fairly robust to overfitting. Once fit the MERF can be used to predict. For data in “known” clusters, that the MERF saw in training, the prediction includes the random effect correction:"
},
{
"code": null,
"e": 10011,
"s": 9897,
"text": "For data in “new” clusters, that the MERF did not see in training, the prediction only includes the fixed effect:"
},
{
"code": null,
"e": 10356,
"s": 10011,
"text": "Our contribution was to implement a MERF in Python and open source it. We implemented so that it adheres, as much as possible, to the scikit-learn model interface. We’ll illustrate with an example below. This example can be downloaded as a runnable Jupyter notebook here. We have three matrices containing our n_samples =500 of training data:"
},
{
"code": null,
"e": 10427,
"s": 10356,
"text": "X. Matrix containing three fixed effect features. Dimension = 500 x 3."
},
{
"code": null,
"e": 10497,
"s": 10427,
"text": "y. Vector containing the single target variable. Dimension = 500 x 1."
},
{
"code": null,
"e": 10631,
"s": 10497,
"text": "clusters. Vector containing the cluster_id for each sample. Dimension = 500 x1. We have k = 100 unique clusters in the training data."
},
{
"code": null,
"e": 10977,
"s": 10631,
"text": "In this example, there is not an explicit Z matrix. We create one to model a random mean for each cluster. It is a matrix of all 1s with dimension = 500 x 1. Given the X, y, clusters, and Z matrices we can fix a MERF model to this data by instantiations a MERF model and running the fit method. The MERF model currently has two hyperparameters:"
},
{
"code": null,
"e": 11046,
"s": 10977,
"text": "n_estimators. The number of trees in to train for the random forest."
},
{
"code": null,
"e": 11120,
"s": 11046,
"text": "max_iterations. The maximum number of iterations to run for the EM model."
},
{
"code": null,
"e": 11631,
"s": 11120,
"text": "We eventually plan on implementing early stopping for the EM algorithm as well. This will add an additional two hyper parameters, i.e. whether or not to early stop and what the patience on that should be. Here’s what the output of fit looks like. Note that fitting usually takes some time to run — especially if you run for many iterations. This is unavoidable because each EM iteration requires a random forest fit. Even with parallelization of the random forest fit a single MERF fit can take many minutes."
},
{
"code": null,
"e": 11762,
"s": 11631,
"text": "Once the model is trained we can access the final random forest and the final matrix of trained b_is through two public variables:"
},
{
"code": null,
"e": 11790,
"s": 11762,
"text": "mrf.trained_rfmrf.trained_b"
},
{
"code": null,
"e": 11901,
"s": 11790,
"text": "We can look at the distribution of the b’s. It looks approximately Gaussian with variance Sigma_b as expected:"
},
{
"code": null,
"e": 12075,
"s": 11901,
"text": "The model also host the history of the EM iterations. We can look at the generalized log likelihood (GLL) at every step, the estimates of Sigma_b, sigma_e, and all the bi’s."
},
{
"code": null,
"e": 12311,
"s": 12075,
"text": "Once fit, the model can be used to predict on new samples given X, Z, and clusters. The predict code handles whether or not to apply the random effect correction based on if the cluster_id of the new sample was seen in training or not."
},
{
"code": null,
"e": 12465,
"s": 12311,
"text": "We tested the performance of MERF on synthetic data. The experimental setup mimics that of the published MERF paper. We generate data from this function:"
},
{
"code": null,
"e": 12483,
"s": 12465,
"text": "In this equation:"
},
{
"code": null,
"e": 12522,
"s": 12483,
"text": "m is a fixed constant of our choosing."
},
{
"code": null,
"e": 12657,
"s": 12522,
"text": "the bi are drawn from normal distribution N(0, sigma_b). They are constant per cluster i. sigma_b is a fixed constant of our choosing."
},
{
"code": null,
"e": 12769,
"s": 12657,
"text": "the error, e, is drawn IID from normal distribution N(0, sigma_e). sigma_e is a fixed constant of our choosing."
},
{
"code": null,
"e": 13205,
"s": 12769,
"text": "For our experiments, we choose various values for m, sigma_e, and sigma_b and generated 500 samples from 100 different unbalanced clusters. We summarize the values in the table below, but the specific values are not that important. What matters are two derived parameters, the percentage total effects variance (PTEV) and the percentage random effects variance (PREV). They are defined in detail in the paper, but intuitively they are:"
},
{
"code": null,
"e": 13330,
"s": 13205,
"text": "PTEV = the amount of total variance that is not due to random noise. The higher it is, the more predictable the output y is."
},
{
"code": null,
"e": 13439,
"s": 13330,
"text": "PREV = the amount of PTEV that is due to random effect. The higher is it, the larger random effect there is."
},
{
"code": null,
"e": 13495,
"s": 13439,
"text": "We did an experiment comparing MERF to two competitors:"
},
{
"code": null,
"e": 13599,
"s": 13495,
"text": "a random forest that does not take random effects into account, i.e. fitting a random forest on only X."
},
{
"code": null,
"e": 13813,
"s": 13599,
"text": "a random forest that includes one hot encoded cluster id as features, i.e. we create k new one hot encoded features, X_ohe, and join that with X and train a random forest on the combined [X, X_ohe] feature matrix."
},
{
"code": null,
"e": 13910,
"s": 13813,
"text": "We varied PTEV and PREV for the experiments and assessed performance on two different test sets:"
},
{
"code": null,
"e": 13972,
"s": 13910,
"text": "test set consists of known clusters that the model trained on"
},
{
"code": null,
"e": 14069,
"s": 13972,
"text": "test set consisted of new (unknown) clusters that the model had no knowledge of at training time"
},
{
"code": null,
"e": 14223,
"s": 14069,
"text": "We use the average mean squared error (MSE) over 10 runs as our error metric. We define the MERF gain as the percentage gain over the compared algorithm:"
},
{
"code": null,
"e": 14758,
"s": 14223,
"text": "The table and chart below summarize the results. MERF has marked performance gains over both of the compared models — particularly when the PREV is high (over 50%!). In addition, there is negligible loss in performance when predicting new clusters. MERF is a strictly better model when there are significant random effects in the data. It’s a winner. We have included the data generator as a utility module in merf package. The source code for the experiment is in a Jupyter notebook here. Check it out and run your own experiments!"
},
{
"code": null,
"e": 15414,
"s": 14758,
"text": "Manifold is working on a thermal modelling problem for one of our clients. The problem is to predict, everyday, when a building is going to reach its target temperature based on a number of factors, e.g. outdoor temperature, outdoor humidity, indoor temperature the previous day. We have historical data that is clustered longitudinally by building. The clusters are highly imbalanced. For some buildings we have many years of data; for others we only have a few weeks. This problem is begging for a mixed effects model. We want to build one model that learns across the population, but, at the same time, accounts for the idiosyncrasies of each building."
},
{
"code": null,
"e": 15473,
"s": 15414,
"text": "Similar to the experiment above, we compared MERF against:"
},
{
"code": null,
"e": 15601,
"s": 15473,
"text": "a random forest that does not take random effects into account, i.e. fitting a random forest on only the fixed effect features."
},
{
"code": null,
"e": 15840,
"s": 15601,
"text": "a random forest that includes one hot encoded building id as features, i.e. we create k new one hot encoded features, X_ohe, and join that with the fixed effect features and train a random forest on the combined [X, X_ohe] feature matrix."
},
{
"code": null,
"e": 16082,
"s": 15840,
"text": "Because of outliers, we changed the error metric to the median absolute error (MAE) rather than the MSE. We compare the performance using 5-fold cross validation on a small N~1000 data set. The results of the experiment are summarized below."
},
{
"code": null,
"e": 16216,
"s": 16082,
"text": "For this data set, there is a small MERF gain, but it’s not that significant. Looking at the MERF convergence plot we get some clues."
},
{
"code": null,
"e": 16655,
"s": 16216,
"text": "The GLL is flat even though we run for 100 iterations and the other variables are converging. It’s not clear what that means. In addition, the estimated error variance, sigma_e, is very significant. It seems like the data has a very low PTEV (because of outliers?). The one hot encoding (OHE) model is doing ok because the number of buildings is small — k = 15. As the number of buildings scale the OHE model performance will suffer more."
},
{
"code": null,
"e": 16976,
"s": 16655,
"text": "All of these factors, coupled with the fact that there is not that much data, leaves this experiment a bit inconclusive. MERF is not performing poorer than it’s counterparts — so it doesn’t hurt — and in fact has a slight gain on average. This experiment needs more analysis — when we do we’ll publish them on this blog."
},
{
"code": null,
"e": 17436,
"s": 16976,
"text": "Mixed effects models are powerful — and lots of data has a structure that is amenable to using them. Add them to your repertoire of models. Mixed effects random forests (MERFs) are a piece of the puzzle. They combine the best of random forests with the best of mixed effects models. We hope you find them useful. More importantly, we’re looking for help extending the MERF package! We would love more contributors. We have a bunch of open issues to work on:"
},
{
"code": null,
"e": 17456,
"s": 17436,
"text": "Add early stopping."
},
{
"code": null,
"e": 17519,
"s": 17456,
"text": "Add more learners, e.g. gradient boosting trees, xgboost, etc."
},
{
"code": null,
"e": 17586,
"s": 17519,
"text": "Add generalization to classification using GMERFs. See paper here."
},
{
"code": null,
"e": 17679,
"s": 17586,
"text": "Conduct novel research into using a nonlinear mixed effect, rather than a purely linear one."
},
{
"code": null,
"e": 17703,
"s": 17679,
"text": "Send us a pull request!"
},
{
"code": null,
"e": 18339,
"s": 17703,
"text": "Manifold is an AI studio with offices in Silicon Valley and Boston. Leading companies work with us on new AI solutions when the stakes are high. We accelerate time to market, create new IP, and foster in-house capabilities. Manifold’s team is experienced in conceiving of and deploying production machine learning systems and data platforms at places like Google, Facebook, Qualcomm, MIT, and successful venture-backed startups. Our domain expertise spans electronics (consumer and industrial), wireless, healthcare, and marketing. We have an extended network of experts that we draw on across industry and engineering sub-specialties."
}
] |
Find location of an element in Pandas dataframe in Python - GeeksforGeeks
|
11 Jun, 2021
In this article, we will see how to find the position of an element in the dataframe using a user-defined function. Let’s first Create a simple dataframe with a dictionary of lists, say column names are: ‘Name’, ‘Age’, ‘City’, and ‘Section’.
Python3
# Import pandas libraryimport pandas as pd # List of tuplesstudents = [('Ankit', 23, 'Delhi', 'A'), ('Swapnil', 22, 'Delhi', 'B'), ('Aman', 22, 'Dehradun', 'A'), ('Jiten', 22, 'Delhi', 'A'), ('Jeet', 21, 'Mumbai', 'B') ] # Creating Dataframe objectdf = pd.DataFrame(students, columns =['Name', 'Age', 'City', 'Section']) df
Output:
Example 1 : Find the location of an element in the dataframe.
Python3
# Import pandas libraryimport pandas as pd # List of tuplesstudents = [('Ankit', 23, 'Delhi', 'A'), ('Swapnil', 22, 'Delhi', 'B'), ('Aman', 22, 'Dehradun', 'A'), ('Jiten', 22, 'Delhi', 'A'), ('Jeet', 21, 'Mumbai', 'B') ] # Creating Dataframe objectdf = pd.DataFrame(students, columns =['Name', 'Age', 'City', 'Section']) # This function will return a list of# positions where element exists# in the dataframe.def getIndexes(dfObj, value): # Empty list listOfPos = [] # isin() method will return a dataframe with # boolean values, True at the positions # where element exists result = dfObj.isin([value]) # any() method will return # a boolean series seriesObj = result.any() # Get list of column names where # element exists columnNames = list(seriesObj[seriesObj == True].index) # Iterate over the list of columns and # extract the row index where element exists for col in columnNames: rows = list(result[col][result[col] == True].index) for row in rows: listOfPos.append((row, col)) # This list contains a list tuples with # the index of element in the dataframe return listOfPos # Calling getIndexes() function to get# the index positions of all occurrences# of 22 in the dataframelistOfPositions = getIndexes(df, 22) print('Index positions of 22 in Dataframe : ') # Printing the positionfor i in range(len(listOfPositions)): print( listOfPositions[i])
Output :
Now let’s understand how the function getIndexes() works. The isin(), dataframe/series.any(), accepts values and returns a dataframe with boolean values. This boolean dataframe is of a similar size as the first original dataframe. The value is True at places where given element exists in the dataframe, otherwise False. Then find the names of columns that contain element 22. We can accomplish this by getting names of columns in the boolean dataframe which contains True. Now in the boolean dataframe we iterate over each of the selected columns and for each column, we find rows with True. Now, these combinations of column names and row indexes where True exists are the index positions of 22 in the dataframe. This is how getIndexes() founds the exact index positions of the given element & stores each position in the form of (row, column) tuple. Finally, it returns a list of tuples representing its index positions in the dataframe.Example 2: Find location of multiple elements in the DataFrame.
Python3
# Import pandas libraryimport pandas as pd # List of tuplesstudents = [('Ankit', 23, 'Delhi', 'A'), ('Swapnil', 22, 'Delhi', 'B'), ('Aman', 22, 'Dehradun', 'A'), ('Jiten', 22, 'Delhi', 'A'), ('Jeet', 21, 'Mumbai', 'B') ] # Creating Dataframe objectdf = pd.DataFrame(students, columns =['Name', 'Age', 'City', 'Section']) # This function will return a# list of positions where# element exists in dataframedef getIndexes(dfObj, value): # Empty list listOfPos = [] # isin() method will return a dataframe with # boolean values, True at the positions # where element exists result = dfObj.isin([value]) # any() method will return # a boolean series seriesObj = result.any() # Get list of columns where element exists columnNames = list(seriesObj[seriesObj == True].index) # Iterate over the list of columns and # extract the row index where element exists for col in columnNames: rows = list(result[col][result[col] == True].index) for row in rows: listOfPos.append((row, col)) # This list contains a list tuples with # the index of element in the dataframe return listOfPos # Create a list which contains all the elements# whose index position you need to findlistOfElems = [22, 'Delhi'] # Using dictionary comprehension to find# index positions of multiple elements# in dataframedictOfPos = {elem: getIndexes(df, elem) for elem in listOfElems} print('Position of given elements in Dataframe are : ') # Looping through key, value pairs# in the dictionaryfor key, value in dictOfPos.items(): print(key, ' : ', value)
Output :
surinderdawra388
Python pandas-dataFrame
Python-pandas
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 25038,
"s": 25010,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 25281,
"s": 25038,
"text": "In this article, we will see how to find the position of an element in the dataframe using a user-defined function. Let’s first Create a simple dataframe with a dictionary of lists, say column names are: ‘Name’, ‘Age’, ‘City’, and ‘Section’. "
},
{
"code": null,
"e": 25289,
"s": 25281,
"text": "Python3"
},
{
"code": "# Import pandas libraryimport pandas as pd # List of tuplesstudents = [('Ankit', 23, 'Delhi', 'A'), ('Swapnil', 22, 'Delhi', 'B'), ('Aman', 22, 'Dehradun', 'A'), ('Jiten', 22, 'Delhi', 'A'), ('Jeet', 21, 'Mumbai', 'B') ] # Creating Dataframe objectdf = pd.DataFrame(students, columns =['Name', 'Age', 'City', 'Section']) df",
"e": 25668,
"s": 25289,
"text": null
},
{
"code": null,
"e": 25678,
"s": 25668,
"text": "Output: "
},
{
"code": null,
"e": 25742,
"s": 25678,
"text": "Example 1 : Find the location of an element in the dataframe. "
},
{
"code": null,
"e": 25750,
"s": 25742,
"text": "Python3"
},
{
"code": "# Import pandas libraryimport pandas as pd # List of tuplesstudents = [('Ankit', 23, 'Delhi', 'A'), ('Swapnil', 22, 'Delhi', 'B'), ('Aman', 22, 'Dehradun', 'A'), ('Jiten', 22, 'Delhi', 'A'), ('Jeet', 21, 'Mumbai', 'B') ] # Creating Dataframe objectdf = pd.DataFrame(students, columns =['Name', 'Age', 'City', 'Section']) # This function will return a list of# positions where element exists# in the dataframe.def getIndexes(dfObj, value): # Empty list listOfPos = [] # isin() method will return a dataframe with # boolean values, True at the positions # where element exists result = dfObj.isin([value]) # any() method will return # a boolean series seriesObj = result.any() # Get list of column names where # element exists columnNames = list(seriesObj[seriesObj == True].index) # Iterate over the list of columns and # extract the row index where element exists for col in columnNames: rows = list(result[col][result[col] == True].index) for row in rows: listOfPos.append((row, col)) # This list contains a list tuples with # the index of element in the dataframe return listOfPos # Calling getIndexes() function to get# the index positions of all occurrences# of 22 in the dataframelistOfPositions = getIndexes(df, 22) print('Index positions of 22 in Dataframe : ') # Printing the positionfor i in range(len(listOfPositions)): print( listOfPositions[i])",
"e": 27281,
"s": 25750,
"text": null
},
{
"code": null,
"e": 27292,
"s": 27281,
"text": "Output : "
},
{
"code": null,
"e": 28298,
"s": 27292,
"text": "Now let’s understand how the function getIndexes() works. The isin(), dataframe/series.any(), accepts values and returns a dataframe with boolean values. This boolean dataframe is of a similar size as the first original dataframe. The value is True at places where given element exists in the dataframe, otherwise False. Then find the names of columns that contain element 22. We can accomplish this by getting names of columns in the boolean dataframe which contains True. Now in the boolean dataframe we iterate over each of the selected columns and for each column, we find rows with True. Now, these combinations of column names and row indexes where True exists are the index positions of 22 in the dataframe. This is how getIndexes() founds the exact index positions of the given element & stores each position in the form of (row, column) tuple. Finally, it returns a list of tuples representing its index positions in the dataframe.Example 2: Find location of multiple elements in the DataFrame. "
},
{
"code": null,
"e": 28306,
"s": 28298,
"text": "Python3"
},
{
"code": "# Import pandas libraryimport pandas as pd # List of tuplesstudents = [('Ankit', 23, 'Delhi', 'A'), ('Swapnil', 22, 'Delhi', 'B'), ('Aman', 22, 'Dehradun', 'A'), ('Jiten', 22, 'Delhi', 'A'), ('Jeet', 21, 'Mumbai', 'B') ] # Creating Dataframe objectdf = pd.DataFrame(students, columns =['Name', 'Age', 'City', 'Section']) # This function will return a# list of positions where# element exists in dataframedef getIndexes(dfObj, value): # Empty list listOfPos = [] # isin() method will return a dataframe with # boolean values, True at the positions # where element exists result = dfObj.isin([value]) # any() method will return # a boolean series seriesObj = result.any() # Get list of columns where element exists columnNames = list(seriesObj[seriesObj == True].index) # Iterate over the list of columns and # extract the row index where element exists for col in columnNames: rows = list(result[col][result[col] == True].index) for row in rows: listOfPos.append((row, col)) # This list contains a list tuples with # the index of element in the dataframe return listOfPos # Create a list which contains all the elements# whose index position you need to findlistOfElems = [22, 'Delhi'] # Using dictionary comprehension to find# index positions of multiple elements# in dataframedictOfPos = {elem: getIndexes(df, elem) for elem in listOfElems} print('Position of given elements in Dataframe are : ') # Looping through key, value pairs# in the dictionaryfor key, value in dictOfPos.items(): print(key, ' : ', value)",
"e": 29991,
"s": 28306,
"text": null
},
{
"code": null,
"e": 30002,
"s": 29991,
"text": "Output : "
},
{
"code": null,
"e": 30021,
"s": 30004,
"text": "surinderdawra388"
},
{
"code": null,
"e": 30045,
"s": 30021,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 30059,
"s": 30045,
"text": "Python-pandas"
},
{
"code": null,
"e": 30066,
"s": 30059,
"text": "Python"
},
{
"code": null,
"e": 30164,
"s": 30066,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30182,
"s": 30164,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30217,
"s": 30182,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30239,
"s": 30217,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30271,
"s": 30239,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30301,
"s": 30271,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 30343,
"s": 30301,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30369,
"s": 30343,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30406,
"s": 30369,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 30449,
"s": 30406,
"text": "Python program to convert a list to string"
}
] |
React Native - ScrollView
|
In this chapter, we will show you how to work with the ScrollView element.
We will again create ScrollViewExample.js and import it in Home.
import React from 'react';
import ScrollViewExample from './scroll_view.js';
const App = () => {
return (
<ScrollViewExample />
)
}export default App
Scrollview will render a list of names. We will create it in state.
import React, { Component } from 'react';
import { Text, Image, View, StyleSheet, ScrollView } from 'react-native';
class ScrollViewExample extends Component {
state = {
names: [
{'name': 'Ben', 'id': 1},
{'name': 'Susan', 'id': 2},
{'name': 'Robert', 'id': 3},
{'name': 'Mary', 'id': 4},
{'name': 'Daniel', 'id': 5},
{'name': 'Laura', 'id': 6},
{'name': 'John', 'id': 7},
{'name': 'Debra', 'id': 8},
{'name': 'Aron', 'id': 9},
{'name': 'Ann', 'id': 10},
{'name': 'Steve', 'id': 11},
{'name': 'Olivia', 'id': 12}
]
}
render() {
return (
<View>
<ScrollView>
{
this.state.names.map((item, index) => (
<View key = {item.id} style = {styles.item}>
<Text>{item.name}</Text>
</View>
))
}
</ScrollView>
</View>
)
}
}
export default ScrollViewExample
const styles = StyleSheet.create ({
item: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
padding: 30,
margin: 2,
borderColor: '#2a4944',
borderWidth: 1,
backgroundColor: '#d2f7f1'
}
})
When we run the app, we will see the scrollable list of names.
20 Lectures
1.5 hours
Anadi Sharma
61 Lectures
6.5 hours
A To Z Mentor
40 Lectures
4.5 hours
Eduonix Learning Solutions
56 Lectures
12.5 hours
Eduonix Learning Solutions
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2419,
"s": 2344,
"text": "In this chapter, we will show you how to work with the ScrollView element."
},
{
"code": null,
"e": 2484,
"s": 2419,
"text": "We will again create ScrollViewExample.js and import it in Home."
},
{
"code": null,
"e": 2647,
"s": 2484,
"text": "import React from 'react';\nimport ScrollViewExample from './scroll_view.js';\n\nconst App = () => {\n return (\n <ScrollViewExample />\n )\n}export default App"
},
{
"code": null,
"e": 2715,
"s": 2647,
"text": "Scrollview will render a list of names. We will create it in state."
},
{
"code": null,
"e": 4049,
"s": 2715,
"text": "import React, { Component } from 'react';\nimport { Text, Image, View, StyleSheet, ScrollView } from 'react-native';\n\nclass ScrollViewExample extends Component {\n state = {\n names: [\n {'name': 'Ben', 'id': 1},\n {'name': 'Susan', 'id': 2},\n {'name': 'Robert', 'id': 3},\n {'name': 'Mary', 'id': 4},\n {'name': 'Daniel', 'id': 5},\n {'name': 'Laura', 'id': 6},\n {'name': 'John', 'id': 7},\n {'name': 'Debra', 'id': 8},\n {'name': 'Aron', 'id': 9},\n {'name': 'Ann', 'id': 10},\n {'name': 'Steve', 'id': 11},\n {'name': 'Olivia', 'id': 12}\n ]\n }\n render() {\n return (\n <View>\n <ScrollView>\n {\n this.state.names.map((item, index) => (\n <View key = {item.id} style = {styles.item}>\n <Text>{item.name}</Text>\n </View>\n ))\n }\n </ScrollView>\n </View>\n )\n }\n}\nexport default ScrollViewExample\n\nconst styles = StyleSheet.create ({\n item: {\n flexDirection: 'row',\n justifyContent: 'space-between',\n alignItems: 'center',\n padding: 30,\n margin: 2,\n borderColor: '#2a4944',\n borderWidth: 1,\n backgroundColor: '#d2f7f1'\n }\n})"
},
{
"code": null,
"e": 4112,
"s": 4049,
"text": "When we run the app, we will see the scrollable list of names."
},
{
"code": null,
"e": 4147,
"s": 4112,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4161,
"s": 4147,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4196,
"s": 4161,
"text": "\n 61 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4211,
"s": 4196,
"text": " A To Z Mentor"
},
{
"code": null,
"e": 4246,
"s": 4211,
"text": "\n 40 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4274,
"s": 4246,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4310,
"s": 4274,
"text": "\n 56 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 4338,
"s": 4310,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4373,
"s": 4338,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4385,
"s": 4373,
"text": " Senol Atac"
},
{
"code": null,
"e": 4420,
"s": 4385,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4432,
"s": 4420,
"text": " Senol Atac"
},
{
"code": null,
"e": 4439,
"s": 4432,
"text": " Print"
},
{
"code": null,
"e": 4450,
"s": 4439,
"text": " Add Notes"
}
] |
Find the ratio of number of elements in two Arrays from their individual and combined average - GeeksforGeeks
|
13 Mar, 2022
Given the average of elements in two arrays as ‘a’ and ‘b’ respectively, and their combined average as ‘c’, the task is to find the ratio of the number of elements in two array.Examples:
Input: a = 2, b = 8, c = 5
Output: 1:1
Input: a = 4, b = 10, c = 6
Output: 2:1
Approach:
Let the number of elements in two arrays are respectively x and y.
So sum of all elements in the combined array is .
Total number of elements in the combined array is and let .
So, So,
Here f is our required answer.
Below is the implementation of the above Approach:
C++
Java
Python3
C#
Javascript
// C++ program to Find the Ratio// of number of Elements in two Arrays// from their individual and combined Average #include <bits/stdc++.h>using namespace std; // C++ function to find the ratio// of number of array elementsvoid FindRatio(int a, int b, int c){ int up = abs(b - c); int down = abs(c - a); // calculating GCD of them int g = __gcd(up, down); // make neumarator and // denominator coprime up /= g; down /= g; cout << up << ":" << down << "\n";} // Driver Codeint main(){ int a = 4, b = 10, c = 6; FindRatio(a, b, c); return 0;}
// Java program to Find the Ratio// of number of Elements in two Arrays// from their individual and combined Averageclass GFG{ static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // function to find the ratio // of number of array elements static void FindRatio(int a, int b, int c) { int up = Math.abs(b - c); int down = Math.abs(c - a); // calculating GCD of them int g = gcd(up, down); // make neumarator and // denominator coprime up /= g; down /= g; System.out.println(up + ":" + down); } // Driver Code public static void main (String[] args) { int a = 4, b = 10, c = 6; FindRatio(a, b, c); }} // This code is contributed by AnkitRai01
# Python3 program to Find the Ratio# of number of Elements in two Arrays# from their individual and combined Averagefrom math import gcd # function to find the ratio# of number of array elementsdef FindRatio(a, b, c): up = abs(b - c) down = abs(c - a) # calculating GCD of them g = gcd(up, down) # make neumarator and # denominator coprime up //= g down //= g print(up,":", down) # Driver Codea = 4b = 10c = 6 FindRatio(a, b, c) # This code is contributed by Mohit Kumar
// C# program to Find the Ratio// of number of Elements in two Arrays// from their individual and combined Averageusing System; class GFG{ static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // function to find the ratio // of number of array elements static void FindRatio(int a, int b, int c) { int up = Math.Abs(b - c); int down = Math.Abs(c - a); // calculating GCD of them int g = gcd(up, down); // make neumarator and // denominator coprime up /= g; down /= g; Console.WriteLine(up + ":" + down); } // Driver Code public static void Main (String []args) { int a = 4, b = 10, c = 6; FindRatio(a, b, c); }} // This code is contributed by Arnab Kundu
<script>// Javascript program to Find the Ratio// of number of Elements in two Arrays// from their individual and combined Average // Javascript function to find the ratio// of number of array elementsfunction FindRatio(a, b, c){ let up = Math.abs(b - c); let down = Math.abs(c - a); // calculating GCD of them let g = gcd(up, down); // make neumarator and // denominator coprime up = parseInt(up / g); down = parseInt(down / g); document.write(up + ":" + down + "<br>");} function gcd(a, b){ if (b == 0) return a; return gcd(b, a % b); } // Driver Code let a = 4, b = 10, c = 6; FindRatio(a, b, c); </script>
2:1
Time Complexity: O(log( min(abs(b-c),abs(c-a)) ) )
Auxiliary Space: O(1)
mohit kumar 29
ankthon
andrew1234
subhammahato348
subham348
GCD-LCM
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Introduction to Arrays
Python | Using 2D arrays/lists the right way
Linked List vs Array
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24806,
"s": 24778,
"text": "\n13 Mar, 2022"
},
{
"code": null,
"e": 24995,
"s": 24806,
"text": "Given the average of elements in two arrays as ‘a’ and ‘b’ respectively, and their combined average as ‘c’, the task is to find the ratio of the number of elements in two array.Examples: "
},
{
"code": null,
"e": 25076,
"s": 24995,
"text": "Input: a = 2, b = 8, c = 5\nOutput: 1:1\n\nInput: a = 4, b = 10, c = 6\nOutput: 2:1"
},
{
"code": null,
"e": 25090,
"s": 25078,
"text": "Approach: "
},
{
"code": null,
"e": 25157,
"s": 25090,
"text": "Let the number of elements in two arrays are respectively x and y."
},
{
"code": null,
"e": 25207,
"s": 25157,
"text": "So sum of all elements in the combined array is ."
},
{
"code": null,
"e": 25267,
"s": 25207,
"text": "Total number of elements in the combined array is and let ."
},
{
"code": null,
"e": 25276,
"s": 25267,
"text": "So, So, "
},
{
"code": null,
"e": 25307,
"s": 25276,
"text": "Here f is our required answer."
},
{
"code": null,
"e": 25360,
"s": 25307,
"text": "Below is the implementation of the above Approach: "
},
{
"code": null,
"e": 25364,
"s": 25360,
"text": "C++"
},
{
"code": null,
"e": 25369,
"s": 25364,
"text": "Java"
},
{
"code": null,
"e": 25377,
"s": 25369,
"text": "Python3"
},
{
"code": null,
"e": 25380,
"s": 25377,
"text": "C#"
},
{
"code": null,
"e": 25391,
"s": 25380,
"text": "Javascript"
},
{
"code": "// C++ program to Find the Ratio// of number of Elements in two Arrays// from their individual and combined Average #include <bits/stdc++.h>using namespace std; // C++ function to find the ratio// of number of array elementsvoid FindRatio(int a, int b, int c){ int up = abs(b - c); int down = abs(c - a); // calculating GCD of them int g = __gcd(up, down); // make neumarator and // denominator coprime up /= g; down /= g; cout << up << \":\" << down << \"\\n\";} // Driver Codeint main(){ int a = 4, b = 10, c = 6; FindRatio(a, b, c); return 0;}",
"e": 25984,
"s": 25391,
"text": null
},
{
"code": "// Java program to Find the Ratio// of number of Elements in two Arrays// from their individual and combined Averageclass GFG{ static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // function to find the ratio // of number of array elements static void FindRatio(int a, int b, int c) { int up = Math.abs(b - c); int down = Math.abs(c - a); // calculating GCD of them int g = gcd(up, down); // make neumarator and // denominator coprime up /= g; down /= g; System.out.println(up + \":\" + down); } // Driver Code public static void main (String[] args) { int a = 4, b = 10, c = 6; FindRatio(a, b, c); }} // This code is contributed by AnkitRai01",
"e": 26828,
"s": 25984,
"text": null
},
{
"code": "# Python3 program to Find the Ratio# of number of Elements in two Arrays# from their individual and combined Averagefrom math import gcd # function to find the ratio# of number of array elementsdef FindRatio(a, b, c): up = abs(b - c) down = abs(c - a) # calculating GCD of them g = gcd(up, down) # make neumarator and # denominator coprime up //= g down //= g print(up,\":\", down) # Driver Codea = 4b = 10c = 6 FindRatio(a, b, c) # This code is contributed by Mohit Kumar",
"e": 27330,
"s": 26828,
"text": null
},
{
"code": "// C# program to Find the Ratio// of number of Elements in two Arrays// from their individual and combined Averageusing System; class GFG{ static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // function to find the ratio // of number of array elements static void FindRatio(int a, int b, int c) { int up = Math.Abs(b - c); int down = Math.Abs(c - a); // calculating GCD of them int g = gcd(up, down); // make neumarator and // denominator coprime up /= g; down /= g; Console.WriteLine(up + \":\" + down); } // Driver Code public static void Main (String []args) { int a = 4, b = 10, c = 6; FindRatio(a, b, c); }} // This code is contributed by Arnab Kundu",
"e": 28186,
"s": 27330,
"text": null
},
{
"code": "<script>// Javascript program to Find the Ratio// of number of Elements in two Arrays// from their individual and combined Average // Javascript function to find the ratio// of number of array elementsfunction FindRatio(a, b, c){ let up = Math.abs(b - c); let down = Math.abs(c - a); // calculating GCD of them let g = gcd(up, down); // make neumarator and // denominator coprime up = parseInt(up / g); down = parseInt(down / g); document.write(up + \":\" + down + \"<br>\");} function gcd(a, b){ if (b == 0) return a; return gcd(b, a % b); } // Driver Code let a = 4, b = 10, c = 6; FindRatio(a, b, c); </script>",
"e": 28850,
"s": 28186,
"text": null
},
{
"code": null,
"e": 28854,
"s": 28850,
"text": "2:1"
},
{
"code": null,
"e": 28907,
"s": 28856,
"text": "Time Complexity: O(log( min(abs(b-c),abs(c-a)) ) )"
},
{
"code": null,
"e": 28929,
"s": 28907,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28944,
"s": 28929,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 28952,
"s": 28944,
"text": "ankthon"
},
{
"code": null,
"e": 28963,
"s": 28952,
"text": "andrew1234"
},
{
"code": null,
"e": 28979,
"s": 28963,
"text": "subhammahato348"
},
{
"code": null,
"e": 28989,
"s": 28979,
"text": "subham348"
},
{
"code": null,
"e": 28997,
"s": 28989,
"text": "GCD-LCM"
},
{
"code": null,
"e": 29004,
"s": 28997,
"text": "Arrays"
},
{
"code": null,
"e": 29017,
"s": 29004,
"text": "Mathematical"
},
{
"code": null,
"e": 29024,
"s": 29017,
"text": "Arrays"
},
{
"code": null,
"e": 29037,
"s": 29024,
"text": "Mathematical"
},
{
"code": null,
"e": 29135,
"s": 29037,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29203,
"s": 29135,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 29235,
"s": 29203,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29258,
"s": 29235,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 29303,
"s": 29258,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 29324,
"s": 29303,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 29354,
"s": 29324,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 29414,
"s": 29354,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 29429,
"s": 29414,
"text": "C++ Data Types"
},
{
"code": null,
"e": 29472,
"s": 29429,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Why Constructors are not inherited in Java? - GeeksforGeeks
|
30 Nov, 2018
Constructor is a block of code that allows you to create an object of class and has same name as class with no explicit return type.
Whenever a class (child class) extends another class (parent class), the sub class inherits state and behavior in the form of variables and methods from its super class but it does not inherit constructor of super class because of following reasons:
Constructors are special and have same name as class name. So if constructors were inherited in child class then child class would contain a parent class constructor which is against the constraint that constructor should have same name as class name. For example see the below code:class Parent { public Parent() { } public void print() { }} public class Child extends Parent { public Parent() { } public void print() { } public static void main(String[] args) { Child c1 = new Child(); // allowed Child c2 = new Parent(); // not allowed }}If we define Parent class constructor inside Child class it will give compile time error for return type and consider it a method. But for print method it does not give any compile time error and consider it a overriding method.
class Parent { public Parent() { } public void print() { }} public class Child extends Parent { public Parent() { } public void print() { } public static void main(String[] args) { Child c1 = new Child(); // allowed Child c2 = new Parent(); // not allowed }}
If we define Parent class constructor inside Child class it will give compile time error for return type and consider it a method. But for print method it does not give any compile time error and consider it a overriding method.
Now suppose if constructors can be inherited then it will be impossible to achieving encapsulation. Because by using a super class’s constructor we can access/initialize private members of a class.
A constructor cannot be called as a method. It is called when object of the class is created so it does not make sense of creating child class object using parent class constructor notation. i.e. Child c = new Parent();
A parent class constructor is not inherited in child class and this is why super() is added automatically in child class constructor if there is no explicit call to super or this.
This article is contributed by Sajid Ali Khan. 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-Constructors
java-inheritance
java-overriding
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 23181,
"s": 23153,
"text": "\n30 Nov, 2018"
},
{
"code": null,
"e": 23314,
"s": 23181,
"text": "Constructor is a block of code that allows you to create an object of class and has same name as class with no explicit return type."
},
{
"code": null,
"e": 23564,
"s": 23314,
"text": "Whenever a class (child class) extends another class (parent class), the sub class inherits state and behavior in the form of variables and methods from its super class but it does not inherit constructor of super class because of following reasons:"
},
{
"code": null,
"e": 24398,
"s": 23564,
"text": "Constructors are special and have same name as class name. So if constructors were inherited in child class then child class would contain a parent class constructor which is against the constraint that constructor should have same name as class name. For example see the below code:class Parent { public Parent() { } public void print() { }} public class Child extends Parent { public Parent() { } public void print() { } public static void main(String[] args) { Child c1 = new Child(); // allowed Child c2 = new Parent(); // not allowed }}If we define Parent class constructor inside Child class it will give compile time error for return type and consider it a method. But for print method it does not give any compile time error and consider it a overriding method."
},
{
"code": "class Parent { public Parent() { } public void print() { }} public class Child extends Parent { public Parent() { } public void print() { } public static void main(String[] args) { Child c1 = new Child(); // allowed Child c2 = new Parent(); // not allowed }}",
"e": 24721,
"s": 24398,
"text": null
},
{
"code": null,
"e": 24950,
"s": 24721,
"text": "If we define Parent class constructor inside Child class it will give compile time error for return type and consider it a method. But for print method it does not give any compile time error and consider it a overriding method."
},
{
"code": null,
"e": 25148,
"s": 24950,
"text": "Now suppose if constructors can be inherited then it will be impossible to achieving encapsulation. Because by using a super class’s constructor we can access/initialize private members of a class."
},
{
"code": null,
"e": 25368,
"s": 25148,
"text": "A constructor cannot be called as a method. It is called when object of the class is created so it does not make sense of creating child class object using parent class constructor notation. i.e. Child c = new Parent();"
},
{
"code": null,
"e": 25548,
"s": 25368,
"text": "A parent class constructor is not inherited in child class and this is why super() is added automatically in child class constructor if there is no explicit call to super or this."
},
{
"code": null,
"e": 25850,
"s": 25548,
"text": "This article is contributed by Sajid Ali Khan. 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": 25975,
"s": 25850,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 25993,
"s": 25975,
"text": "Java-Constructors"
},
{
"code": null,
"e": 26010,
"s": 25993,
"text": "java-inheritance"
},
{
"code": null,
"e": 26026,
"s": 26010,
"text": "java-overriding"
},
{
"code": null,
"e": 26031,
"s": 26026,
"text": "Java"
},
{
"code": null,
"e": 26036,
"s": 26031,
"text": "Java"
},
{
"code": null,
"e": 26134,
"s": 26036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26149,
"s": 26134,
"text": "Arrays in Java"
},
{
"code": null,
"e": 26193,
"s": 26149,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 26215,
"s": 26193,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 26251,
"s": 26215,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 26276,
"s": 26251,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 26308,
"s": 26276,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26359,
"s": 26308,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26389,
"s": 26359,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26408,
"s": 26389,
"text": "Interfaces in Java"
}
] |
Embedding an online compiler into a website
|
09 Dec, 2020
How to add a JDoodle compiler into a website?
Using the JDoodle compiler we can write our code in C, C++, Java, and in many more programming languages, and then we can embed and easily run that program in our webpage by giving standard inputs, and we can give command line arguments also.
Steps to follow:
Step 1: Open the website JDoodle.com and sign in, if you don’t have an account then you must register first.
Step 2: Select any one programming language and write your code and save it. Click on editable share and copy the embed URL.
Step 3: On your website page insert the div and script tags as follows:
The below code will create a division and embed the compiler into a website page.
<div data-pym-src="paste copied URL here."></div>
The below code will include the JavaScript code from the JDoodle. Include the below code at the bottom of the website page.
<script src=”https://www.jdoodle.com/assets/jdoodle-pym.min.js” type=”text/javascript”></script>
Example: Following is an example of embedding a C++ compiler.
HTML
<!DOCTYPE html><html> <head> <title> Embedding an online compiler into a website </title></head> <body> <!-- It will create a division for compiler and embed that into web page--> <div data-pym-src="https://www.jdoodle.com/embed/v0/2IhG?stdin=1&arg=0"> </div> <!-- This script tag contains the javascript code in the written URL --> <script src="https://www.jdoodle.com/assets/jdoodle-pym.min.js" type="text/javascript"> </script></body> </html>
Output:
Note: We can also hide the stdin inputs and command-line arguments by putting ?stdin=0&arg=0 at the end of the URL in the <div> tag. Here, stdin=0 is to hide stdin inputs and arg=0 to hide command line arguments. In order to enable it, just change ‘0’ by ‘1’.
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Dec, 2020"
},
{
"code": null,
"e": 98,
"s": 52,
"text": "How to add a JDoodle compiler into a website?"
},
{
"code": null,
"e": 341,
"s": 98,
"text": "Using the JDoodle compiler we can write our code in C, C++, Java, and in many more programming languages, and then we can embed and easily run that program in our webpage by giving standard inputs, and we can give command line arguments also."
},
{
"code": null,
"e": 358,
"s": 341,
"text": "Steps to follow:"
},
{
"code": null,
"e": 467,
"s": 358,
"text": "Step 1: Open the website JDoodle.com and sign in, if you don’t have an account then you must register first."
},
{
"code": null,
"e": 592,
"s": 467,
"text": "Step 2: Select any one programming language and write your code and save it. Click on editable share and copy the embed URL."
},
{
"code": null,
"e": 664,
"s": 592,
"text": "Step 3: On your website page insert the div and script tags as follows:"
},
{
"code": null,
"e": 752,
"s": 664,
"text": "The below code will create a division and embed the compiler into a website page. "
},
{
"code": null,
"e": 802,
"s": 752,
"text": "<div data-pym-src=\"paste copied URL here.\"></div>"
},
{
"code": null,
"e": 926,
"s": 802,
"text": "The below code will include the JavaScript code from the JDoodle. Include the below code at the bottom of the website page."
},
{
"code": null,
"e": 1023,
"s": 926,
"text": "<script src=”https://www.jdoodle.com/assets/jdoodle-pym.min.js” type=”text/javascript”></script>"
},
{
"code": null,
"e": 1085,
"s": 1023,
"text": "Example: Following is an example of embedding a C++ compiler."
},
{
"code": null,
"e": 1090,
"s": 1085,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Embedding an online compiler into a website </title></head> <body> <!-- It will create a division for compiler and embed that into web page--> <div data-pym-src=\"https://www.jdoodle.com/embed/v0/2IhG?stdin=1&arg=0\"> </div> <!-- This script tag contains the javascript code in the written URL --> <script src=\"https://www.jdoodle.com/assets/jdoodle-pym.min.js\" type=\"text/javascript\"> </script></body> </html>",
"e": 1611,
"s": 1090,
"text": null
},
{
"code": null,
"e": 1619,
"s": 1611,
"text": "Output:"
},
{
"code": null,
"e": 1879,
"s": 1619,
"text": "Note: We can also hide the stdin inputs and command-line arguments by putting ?stdin=0&arg=0 at the end of the URL in the <div> tag. Here, stdin=0 is to hide stdin inputs and arg=0 to hide command line arguments. In order to enable it, just change ‘0’ by ‘1’."
},
{
"code": null,
"e": 1884,
"s": 1879,
"text": "HTML"
},
{
"code": null,
"e": 1901,
"s": 1884,
"text": "Web Technologies"
},
{
"code": null,
"e": 1906,
"s": 1901,
"text": "HTML"
}
] |
How to create an object from the given key-value pairs using JavaScript ?
|
12 Jan, 2022
In this article, we will learn to create an object from the given key-value pairs using JavaScript.
Problem Statement: You are given different key-value pair(s), in any form like an array, and using those key-value pairs you need to construct an object which will have those key-value pair(s).
Object{} => Object {
"0" : "Geeksforgeeks",
"1" : "Hello JavaScript",
"2" : "Hello React"
}
Approach: We first need to declare an empty object, with any suitable name, then by using various JavaScript techniques and methods, we need to insert the given key-value pairs into the previously created empty object.
Let us first try to understand that how we could create an empty object in JavaScript. Creating an empty object in JavaScript could be achieved in several ways.
Example 1:
let object = {};
console.log(object);
Output:
{}
Example 2:
let object = new Object();
console.log(object);
Output:
{}
Now after creating the object now we are going to analyze the approaches through which we could add the given key-value pair (s) in that previously created empty object.
Following are some approaches to achieve the mentioned target.
Example 1: This is the simplest as well as the native approach. In this approach, we will directly append the key-value pair(s) in that previously created empty object.
Javascript
<script> let object = {}; let firstKey = 0; let firstKeyValue = "GeeksforGeeks"; let secondKey = 1; let secondKeyValue = "Hello JavaScript"; let thirdKey = 2; let thirdKeyValue = "Hello React"; object[firstKey] = firstKeyValue; object[secondKey] = secondKeyValue; object[thirdKey] = thirdKeyValue; console.log(object);</script>
Output:
{ "0": "GeeksforGeeks", "1": "Hello JavaScript", "2": "Hello React" }
Example 2: In this second approach, we will use Object.assign() method which is the part of the Object superclass. This method will copy all the values and will append those values in the object as key-value pair(s).
Javascript
<script> let object = {}; let firstKey = 0; let firstKeyValue = "GeeksforGeeks"; let secondKey = 1; let secondKeyValue = "Hello JavaScript"; let thirdKey = 2; let thirdKeyValue = "Hello React"; Object.assign(object, { [firstKey]: firstKeyValue }); Object.assign(object, { [secondKey]: secondKeyValue }); Object.assign(object, { [thirdKey]: thirdKeyValue }); console.log(object);</script>
Output:
{ "0": "GeeksforGeeks", "1": "Hello JavaScript", "2": "Hello React" }
Example 3: In this third approach, we will consider that our keys and their corresponding values are present in an array. We will first run a for loop over the array, and then we will dynamically append our data from the arrays into an empty object as key-value pair(s).
Javascript
<script> let object={}; let keys = [0, 1, 2]; let values = ["GeeksforGeeks", "Hello JavaScript", "Hello React"]; for (let i = 0; i < keys.length; i++) { object[keys[i]] = values[i]; } console.log(object);</script>
Output:
{ "0": "GeeksforGeeks", "1": "Hello JavaScript", "2": "Hello React" }
javascript-object
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 153,
"s": 53,
"text": "In this article, we will learn to create an object from the given key-value pairs using JavaScript."
},
{
"code": null,
"e": 347,
"s": 153,
"text": "Problem Statement: You are given different key-value pair(s), in any form like an array, and using those key-value pairs you need to construct an object which will have those key-value pair(s)."
},
{
"code": null,
"e": 534,
"s": 347,
"text": "Object{} => Object {\n \"0\" : \"Geeksforgeeks\",\n \"1\" : \"Hello JavaScript\",\n \"2\" : \"Hello React\"\n }\n"
},
{
"code": null,
"e": 753,
"s": 534,
"text": "Approach: We first need to declare an empty object, with any suitable name, then by using various JavaScript techniques and methods, we need to insert the given key-value pairs into the previously created empty object."
},
{
"code": null,
"e": 915,
"s": 753,
"text": "Let us first try to understand that how we could create an empty object in JavaScript. Creating an empty object in JavaScript could be achieved in several ways. "
},
{
"code": null,
"e": 926,
"s": 915,
"text": "Example 1:"
},
{
"code": null,
"e": 975,
"s": 926,
"text": "let object = {};\nconsole.log(object);\nOutput:\n{}"
},
{
"code": null,
"e": 986,
"s": 975,
"text": "Example 2:"
},
{
"code": null,
"e": 1045,
"s": 986,
"text": "let object = new Object();\nconsole.log(object);\nOutput:\n{}"
},
{
"code": null,
"e": 1215,
"s": 1045,
"text": "Now after creating the object now we are going to analyze the approaches through which we could add the given key-value pair (s) in that previously created empty object."
},
{
"code": null,
"e": 1278,
"s": 1215,
"text": "Following are some approaches to achieve the mentioned target."
},
{
"code": null,
"e": 1447,
"s": 1278,
"text": "Example 1: This is the simplest as well as the native approach. In this approach, we will directly append the key-value pair(s) in that previously created empty object."
},
{
"code": null,
"e": 1458,
"s": 1447,
"text": "Javascript"
},
{
"code": "<script> let object = {}; let firstKey = 0; let firstKeyValue = \"GeeksforGeeks\"; let secondKey = 1; let secondKeyValue = \"Hello JavaScript\"; let thirdKey = 2; let thirdKeyValue = \"Hello React\"; object[firstKey] = firstKeyValue; object[secondKey] = secondKeyValue; object[thirdKey] = thirdKeyValue; console.log(object);</script>",
"e": 1801,
"s": 1458,
"text": null
},
{
"code": null,
"e": 1809,
"s": 1801,
"text": "Output:"
},
{
"code": null,
"e": 1879,
"s": 1809,
"text": "{ \"0\": \"GeeksforGeeks\", \"1\": \"Hello JavaScript\", \"2\": \"Hello React\" }"
},
{
"code": null,
"e": 2096,
"s": 1879,
"text": "Example 2: In this second approach, we will use Object.assign() method which is the part of the Object superclass. This method will copy all the values and will append those values in the object as key-value pair(s)."
},
{
"code": null,
"e": 2107,
"s": 2096,
"text": "Javascript"
},
{
"code": "<script> let object = {}; let firstKey = 0; let firstKeyValue = \"GeeksforGeeks\"; let secondKey = 1; let secondKeyValue = \"Hello JavaScript\"; let thirdKey = 2; let thirdKeyValue = \"Hello React\"; Object.assign(object, { [firstKey]: firstKeyValue }); Object.assign(object, { [secondKey]: secondKeyValue }); Object.assign(object, { [thirdKey]: thirdKeyValue }); console.log(object);</script>",
"e": 2511,
"s": 2107,
"text": null
},
{
"code": null,
"e": 2519,
"s": 2511,
"text": "Output:"
},
{
"code": null,
"e": 2589,
"s": 2519,
"text": "{ \"0\": \"GeeksforGeeks\", \"1\": \"Hello JavaScript\", \"2\": \"Hello React\" }"
},
{
"code": null,
"e": 2860,
"s": 2589,
"text": "Example 3: In this third approach, we will consider that our keys and their corresponding values are present in an array. We will first run a for loop over the array, and then we will dynamically append our data from the arrays into an empty object as key-value pair(s)."
},
{
"code": null,
"e": 2871,
"s": 2860,
"text": "Javascript"
},
{
"code": "<script> let object={}; let keys = [0, 1, 2]; let values = [\"GeeksforGeeks\", \"Hello JavaScript\", \"Hello React\"]; for (let i = 0; i < keys.length; i++) { object[keys[i]] = values[i]; } console.log(object);</script>",
"e": 3100,
"s": 2871,
"text": null
},
{
"code": null,
"e": 3108,
"s": 3100,
"text": "Output:"
},
{
"code": null,
"e": 3178,
"s": 3108,
"text": "{ \"0\": \"GeeksforGeeks\", \"1\": \"Hello JavaScript\", \"2\": \"Hello React\" }"
},
{
"code": null,
"e": 3196,
"s": 3178,
"text": "javascript-object"
},
{
"code": null,
"e": 3217,
"s": 3196,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 3224,
"s": 3217,
"text": "Picked"
},
{
"code": null,
"e": 3235,
"s": 3224,
"text": "JavaScript"
},
{
"code": null,
"e": 3252,
"s": 3235,
"text": "Web Technologies"
},
{
"code": null,
"e": 3350,
"s": 3252,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3411,
"s": 3350,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3483,
"s": 3411,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3523,
"s": 3483,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3564,
"s": 3523,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3616,
"s": 3564,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 3649,
"s": 3616,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3711,
"s": 3649,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3772,
"s": 3711,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3822,
"s": 3772,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to populate RecyclerView with Firebase data using FirebaseUI in Android Studio
|
23 Nov, 2021
Firebase is one of the most popular online databases in use today and will be the same for at least a few years to come. Firebase offers a Realtime Database that can be used to store and retrieve data in real-time to all users. In this post, let’s connect the Realtime Database with an Android application and show the data in RecyclerView using the FirebaseUI. FirebaseUI is an open-source library for Android that provides to quickly connect common UI elements to Firebase APIs. We are going to cover the following things in this article.
How to create a Firebase project and add some data manually to show in the app.How to create an Android project and add Firebase and FirebaseUI support in it.How to add RecyclerView in the android app and display the data in Firebase Realtime Database.
How to create a Firebase project and add some data manually to show in the app.
How to create an Android project and add Firebase and FirebaseUI support in it.
How to add RecyclerView in the android app and display the data in Firebase Realtime Database.
Step 1: Create a Firebase ProjectGo to https://console.firebase.google.com/u/0/Log in to Firebase with your Google account if are not already logged in.Click on create the project.
Go to https://console.firebase.google.com/u/0/Log in to Firebase with your Google account if are not already logged in.Click on create the project.
Go to https://console.firebase.google.com/u/0/
Log in to Firebase with your Google account if are not already logged in.
Click on create the project.
Step 2: Give a name to the projectWrite the name.Click on continue.
Write the name.Click on continue.
Write the name.
Click on continue.
Step 3: Disable Google Analytics(There is no need to do this for this project)Click on the toggle button.Click Continue. Firebase will create a project for you and open it for you.
Click on the toggle button.Click Continue.
Click on the toggle button.
Click Continue.
Firebase will create a project for you and open it for you.
Step 4: Create a Realtime Database:Go to Develop Option on Sidebar.Click on Database.Scroll down in a new screen and click on Create Database on Realtime Database.Select Start in Test mode (In order to get read and write access to the database).Click enable.
Go to Develop Option on Sidebar.Click on Database.Scroll down in a new screen and click on Create Database on Realtime Database.Select Start in Test mode (In order to get read and write access to the database).Click enable.
Go to Develop Option on Sidebar.
Click on Database.
Scroll down in a new screen and click on Create Database on Realtime Database.
Select Start in Test mode (In order to get read and write access to the database).
Click enable.
Step 5: Add data to the database using the ‘+’ symbol in the database in the same manner as given in the picture.Note:All data values are stored in a string format for ease.Key-value can be any string but should not include spaces ” “.The same sub-keys should be present parent keys so that they can read by Recycler View without any error.
Note:
All data values are stored in a string format for ease.
Key-value can be any string but should not include spaces ” “.
The same sub-keys should be present parent keys so that they can read by Recycler View without any error.
Step 1: Open Android Studio and create a new project named “RecyclerView” with an empty activity.
Step 2: Connect your Firebase project with your app.
Step 3: Add the following dependency in your app/build.gradle file in order to get the FirebaseUI and Firebase Realtime Database support in the app.dependencies { // Dependency FirebaseUI for Firebase Realtime Database implementation 'com.firebaseui:firebase-ui-database:6.2.1' // Dependency for Firebase REaltime Database implementation 'com.google.firebase:firebase-database:19.3.1' }
dependencies { // Dependency FirebaseUI for Firebase Realtime Database implementation 'com.firebaseui:firebase-ui-database:6.2.1' // Dependency for Firebase REaltime Database implementation 'com.google.firebase:firebase-database:19.3.1' }
Step 1: Add the following dependencies to get the support of Cardview in the app.dependencies { // This dependency includes all material components of the android app. implementation 'com.google.android.material:material:1.1.0' }
dependencies { // This dependency includes all material components of the android app. implementation 'com.google.android.material:material:1.1.0' }
Step 2: First, add Recycler View in the activity_main.xml and name it recycler1 paste the given code in the activity_main.xml file in order to do so.XMLXML<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#65E4A6"/> </androidx.constraintlayout.widget.ConstraintLayout>
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#65E4A6"/> </androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Now, let’s create another XML file in the layout directory to store the data from the database of a particular person. We will name the file as person.xml. Copy the following code in the created file.XMLXML<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginHorizontal="10dp" android:layout_marginTop="10dp" android:layout_marginBottom="20dp" android:scrollbars="vertical" app:cardCornerRadius="20dp"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:text="First name: " android:textStyle="bold" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/firstname" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:text="TextView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@+id/textView1" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:text="Last name:" android:textStyle="bold" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView1" /> <TextView android:id="@+id/lastname" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:text="TextView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@+id/textView2" app:layout_constraintTop_toBottomOf="@+id/firstname" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginBottom="16dp" android:text="Age" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView2" /> <TextView android:id="@+id/age" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:layout_marginBottom="16dp" android:text="TextView" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@+id/textView3" app:layout_constraintTop_toBottomOf="@+id/lastname" /> </androidx.constraintlayout.widget.ConstraintLayout></androidx.cardview.widget.CardView>
XML
<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginHorizontal="10dp" android:layout_marginTop="10dp" android:layout_marginBottom="20dp" android:scrollbars="vertical" app:cardCornerRadius="20dp"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:text="First name: " android:textStyle="bold" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/firstname" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:text="TextView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@+id/textView1" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:text="Last name:" android:textStyle="bold" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView1" /> <TextView android:id="@+id/lastname" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:text="TextView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@+id/textView2" app:layout_constraintTop_toBottomOf="@+id/firstname" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginBottom="16dp" android:text="Age" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView2" /> <TextView android:id="@+id/age" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:layout_marginBottom="16dp" android:text="TextView" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@+id/textView3" app:layout_constraintTop_toBottomOf="@+id/lastname" /> </androidx.constraintlayout.widget.ConstraintLayout></androidx.cardview.widget.CardView>
Step 4: After this, We have to create a java file to fetch and store data of a particular person from the database and give it to Recycler View one by one. Create person.java in the same folder in which MainActivity.java file is present. Paste the following code in the file.JavaJava// Your package name can be different depending// on your project namepackage com.example.recyclerview; public class person { // Variable to store data corresponding // to firstname keyword in database private String firstname; // Variable to store data corresponding // to lastname keyword in database private String lastname; // Variable to store data corresponding // to age keyword in database private String age; // Mandatory empty constructor // for use of FirebaseUI public person() {} // Getter and setter method public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getAge() { return age; } public void setAge(String age) { this.age = age; }}
Java
// Your package name can be different depending// on your project namepackage com.example.recyclerview; public class person { // Variable to store data corresponding // to firstname keyword in database private String firstname; // Variable to store data corresponding // to lastname keyword in database private String lastname; // Variable to store data corresponding // to age keyword in database private String age; // Mandatory empty constructor // for use of FirebaseUI public person() {} // Getter and setter method public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getAge() { return age; } public void setAge(String age) { this.age = age; }}
Step 5: In order to show the data from person.java in person.xml, we have to create an Adapter class. Create another java file named personAdapter.java in the same folder as MainActivity.java and paste the following code.JavaJavapackage com.example.recyclerview;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import com.firebase.ui.database.FirebaseRecyclerAdapter;import com.firebase.ui.database.FirebaseRecyclerOptions; // FirebaseRecyclerAdapter is a class provided by// FirebaseUI. it provides functions to bind, adapt and show// database contents in a Recycler Viewpublic class personAdapter extends FirebaseRecyclerAdapter< person, personAdapter.personsViewholder> { public personAdapter( @NonNull FirebaseRecyclerOptions<person> options) { super(options); } // Function to bind the view in Card view(here // "person.xml") iwth data in // model class(here "person.class") @Override protected void onBindViewHolder(@NonNull personsViewholder holder, int position, @NonNull person model) { // Add firstname from model class (here // "person.class")to appropriate view in Card // view (here "person.xml") holder.firstname.setText(model.getFirstname()); // Add lastname from model class (here // "person.class")to appropriate view in Card // view (here "person.xml") holder.lastname.setText(model.getLastname()); // Add age from model class (here // "person.class")to appropriate view in Card // view (here "person.xml") holder.age.setText(model.getAge()); } // Function to tell the class about the Card view (here // "person.xml")in // which the data will be shown @NonNull @Override public personsViewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.person, parent, false); return new personAdapter.personsViewholder(view); } // Sub Class to create references of the views in Crad // view (here "person.xml") class personsViewholder extends RecyclerView.ViewHolder { TextView firstname, lastname, age; public personsViewholder(@NonNull View itemView) { super(itemView); firstname = itemView.findViewById(R.id.firstname); lastname = itemView.findViewById(R.id.lastname); age = itemView.findViewById(R.id.age); } }}
Java
package com.example.recyclerview;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import com.firebase.ui.database.FirebaseRecyclerAdapter;import com.firebase.ui.database.FirebaseRecyclerOptions; // FirebaseRecyclerAdapter is a class provided by// FirebaseUI. it provides functions to bind, adapt and show// database contents in a Recycler Viewpublic class personAdapter extends FirebaseRecyclerAdapter< person, personAdapter.personsViewholder> { public personAdapter( @NonNull FirebaseRecyclerOptions<person> options) { super(options); } // Function to bind the view in Card view(here // "person.xml") iwth data in // model class(here "person.class") @Override protected void onBindViewHolder(@NonNull personsViewholder holder, int position, @NonNull person model) { // Add firstname from model class (here // "person.class")to appropriate view in Card // view (here "person.xml") holder.firstname.setText(model.getFirstname()); // Add lastname from model class (here // "person.class")to appropriate view in Card // view (here "person.xml") holder.lastname.setText(model.getLastname()); // Add age from model class (here // "person.class")to appropriate view in Card // view (here "person.xml") holder.age.setText(model.getAge()); } // Function to tell the class about the Card view (here // "person.xml")in // which the data will be shown @NonNull @Override public personsViewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.person, parent, false); return new personAdapter.personsViewholder(view); } // Sub Class to create references of the views in Crad // view (here "person.xml") class personsViewholder extends RecyclerView.ViewHolder { TextView firstname, lastname, age; public personsViewholder(@NonNull View itemView) { super(itemView); firstname = itemView.findViewById(R.id.firstname); lastname = itemView.findViewById(R.id.lastname); age = itemView.findViewById(R.id.age); } }}
Step 6: Then we have called the database and ask for data from it. This will be done in MainActivity.java itself.JavaJavapackage com.example.recyclerview;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import com.firebase.ui.database.FirebaseRecyclerOptions;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; personAdapter adapter; // Create Object of the Adapter class DatabaseReference mbase; // Create object of the // Firebase Realtime Database @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create a instance of the database and get // its reference mbase = FirebaseDatabase.getInstance().getReference(); recyclerView = findViewById(R.id.recycler1); // To display the Recycler view linearly recyclerView.setLayoutManager( new LinearLayoutManager(this)); // It is a class provide by the FirebaseUI to make a // query in the database to fetch appropriate data FirebaseRecyclerOptions<person> options = new FirebaseRecyclerOptions.Builder<person>() .setQuery(mbase, person.class) .build(); // Connecting object of required Adapter class to // the Adapter class itself adapter = new personAdapter(options); // Connecting Adapter class with the Recycler view*/ recyclerView.setAdapter(adapter); } // Function to tell the app to start getting // data from database on starting of the activity @Override protected void onStart() { super.onStart(); adapter.startListening(); } // Function to tell the app to stop getting // data from database on stopping of the activity @Override protected void onStop() { super.onStop(); adapter.stopListening(); }}
Java
package com.example.recyclerview;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import com.firebase.ui.database.FirebaseRecyclerOptions;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; personAdapter adapter; // Create Object of the Adapter class DatabaseReference mbase; // Create object of the // Firebase Realtime Database @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create a instance of the database and get // its reference mbase = FirebaseDatabase.getInstance().getReference(); recyclerView = findViewById(R.id.recycler1); // To display the Recycler view linearly recyclerView.setLayoutManager( new LinearLayoutManager(this)); // It is a class provide by the FirebaseUI to make a // query in the database to fetch appropriate data FirebaseRecyclerOptions<person> options = new FirebaseRecyclerOptions.Builder<person>() .setQuery(mbase, person.class) .build(); // Connecting object of required Adapter class to // the Adapter class itself adapter = new personAdapter(options); // Connecting Adapter class with the Recycler view*/ recyclerView.setAdapter(adapter); } // Function to tell the app to start getting // data from database on starting of the activity @Override protected void onStart() { super.onStart(); adapter.startListening(); } // Function to tell the app to stop getting // data from database on stopping of the activity @Override protected void onStop() { super.onStop(); adapter.stopListening(); }}
Step 7: Before running the project In AndroidManifest.xml, one needs to include below permission, in order to access the internet:“uses-permission android:name=”android.permission.INTERNET”
“uses-permission android:name=”android.permission.INTERNET”
Output:
varshagumber28
android
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 593,
"s": 52,
"text": "Firebase is one of the most popular online databases in use today and will be the same for at least a few years to come. Firebase offers a Realtime Database that can be used to store and retrieve data in real-time to all users. In this post, let’s connect the Realtime Database with an Android application and show the data in RecyclerView using the FirebaseUI. FirebaseUI is an open-source library for Android that provides to quickly connect common UI elements to Firebase APIs. We are going to cover the following things in this article."
},
{
"code": null,
"e": 846,
"s": 593,
"text": "How to create a Firebase project and add some data manually to show in the app.How to create an Android project and add Firebase and FirebaseUI support in it.How to add RecyclerView in the android app and display the data in Firebase Realtime Database."
},
{
"code": null,
"e": 926,
"s": 846,
"text": "How to create a Firebase project and add some data manually to show in the app."
},
{
"code": null,
"e": 1006,
"s": 926,
"text": "How to create an Android project and add Firebase and FirebaseUI support in it."
},
{
"code": null,
"e": 1101,
"s": 1006,
"text": "How to add RecyclerView in the android app and display the data in Firebase Realtime Database."
},
{
"code": null,
"e": 1282,
"s": 1101,
"text": "Step 1: Create a Firebase ProjectGo to https://console.firebase.google.com/u/0/Log in to Firebase with your Google account if are not already logged in.Click on create the project."
},
{
"code": null,
"e": 1430,
"s": 1282,
"text": "Go to https://console.firebase.google.com/u/0/Log in to Firebase with your Google account if are not already logged in.Click on create the project."
},
{
"code": null,
"e": 1477,
"s": 1430,
"text": "Go to https://console.firebase.google.com/u/0/"
},
{
"code": null,
"e": 1551,
"s": 1477,
"text": "Log in to Firebase with your Google account if are not already logged in."
},
{
"code": null,
"e": 1580,
"s": 1551,
"text": "Click on create the project."
},
{
"code": null,
"e": 1648,
"s": 1580,
"text": "Step 2: Give a name to the projectWrite the name.Click on continue."
},
{
"code": null,
"e": 1682,
"s": 1648,
"text": "Write the name.Click on continue."
},
{
"code": null,
"e": 1698,
"s": 1682,
"text": "Write the name."
},
{
"code": null,
"e": 1717,
"s": 1698,
"text": "Click on continue."
},
{
"code": null,
"e": 1904,
"s": 1717,
"text": "Step 3: Disable Google Analytics(There is no need to do this for this project)Click on the toggle button.Click Continue. Firebase will create a project for you and open it for you."
},
{
"code": null,
"e": 1947,
"s": 1904,
"text": "Click on the toggle button.Click Continue."
},
{
"code": null,
"e": 1975,
"s": 1947,
"text": "Click on the toggle button."
},
{
"code": null,
"e": 1991,
"s": 1975,
"text": "Click Continue."
},
{
"code": null,
"e": 2058,
"s": 1991,
"text": " Firebase will create a project for you and open it for you."
},
{
"code": null,
"e": 2317,
"s": 2058,
"text": "Step 4: Create a Realtime Database:Go to Develop Option on Sidebar.Click on Database.Scroll down in a new screen and click on Create Database on Realtime Database.Select Start in Test mode (In order to get read and write access to the database).Click enable."
},
{
"code": null,
"e": 2541,
"s": 2317,
"text": "Go to Develop Option on Sidebar.Click on Database.Scroll down in a new screen and click on Create Database on Realtime Database.Select Start in Test mode (In order to get read and write access to the database).Click enable."
},
{
"code": null,
"e": 2574,
"s": 2541,
"text": "Go to Develop Option on Sidebar."
},
{
"code": null,
"e": 2593,
"s": 2574,
"text": "Click on Database."
},
{
"code": null,
"e": 2672,
"s": 2593,
"text": "Scroll down in a new screen and click on Create Database on Realtime Database."
},
{
"code": null,
"e": 2755,
"s": 2672,
"text": "Select Start in Test mode (In order to get read and write access to the database)."
},
{
"code": null,
"e": 2769,
"s": 2755,
"text": "Click enable."
},
{
"code": null,
"e": 3110,
"s": 2769,
"text": "Step 5: Add data to the database using the ‘+’ symbol in the database in the same manner as given in the picture.Note:All data values are stored in a string format for ease.Key-value can be any string but should not include spaces ” “.The same sub-keys should be present parent keys so that they can read by Recycler View without any error."
},
{
"code": null,
"e": 3116,
"s": 3110,
"text": "Note:"
},
{
"code": null,
"e": 3172,
"s": 3116,
"text": "All data values are stored in a string format for ease."
},
{
"code": null,
"e": 3235,
"s": 3172,
"text": "Key-value can be any string but should not include spaces ” “."
},
{
"code": null,
"e": 3341,
"s": 3235,
"text": "The same sub-keys should be present parent keys so that they can read by Recycler View without any error."
},
{
"code": null,
"e": 3439,
"s": 3341,
"text": "Step 1: Open Android Studio and create a new project named “RecyclerView” with an empty activity."
},
{
"code": null,
"e": 3492,
"s": 3439,
"text": "Step 2: Connect your Firebase project with your app."
},
{
"code": null,
"e": 3894,
"s": 3492,
"text": "Step 3: Add the following dependency in your app/build.gradle file in order to get the FirebaseUI and Firebase Realtime Database support in the app.dependencies { // Dependency FirebaseUI for Firebase Realtime Database implementation 'com.firebaseui:firebase-ui-database:6.2.1' // Dependency for Firebase REaltime Database implementation 'com.google.firebase:firebase-database:19.3.1' }"
},
{
"code": "dependencies { // Dependency FirebaseUI for Firebase Realtime Database implementation 'com.firebaseui:firebase-ui-database:6.2.1' // Dependency for Firebase REaltime Database implementation 'com.google.firebase:firebase-database:19.3.1' }",
"e": 4148,
"s": 3894,
"text": null
},
{
"code": null,
"e": 4386,
"s": 4148,
"text": "Step 1: Add the following dependencies to get the support of Cardview in the app.dependencies { // This dependency includes all material components of the android app. implementation 'com.google.android.material:material:1.1.0' }"
},
{
"code": "dependencies { // This dependency includes all material components of the android app. implementation 'com.google.android.material:material:1.1.0' }",
"e": 4543,
"s": 4386,
"text": null
},
{
"code": null,
"e": 5332,
"s": 4543,
"text": "Step 2: First, add Recycler View in the activity_main.xml and name it recycler1 paste the given code in the activity_main.xml file in order to do so.XMLXML<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/recycler1\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#65E4A6\"/> </androidx.constraintlayout.widget.ConstraintLayout>"
},
{
"code": null,
"e": 5336,
"s": 5332,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/recycler1\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#65E4A6\"/> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 5970,
"s": 5336,
"text": null
},
{
"code": null,
"e": 9892,
"s": 5970,
"text": "Step 3: Now, let’s create another XML file in the layout directory to store the data from the database of a particular person. We will name the file as person.xml. Copy the following code in the created file.XMLXML<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginHorizontal=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"20dp\" android:scrollbars=\"vertical\" app:cardCornerRadius=\"20dp\"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <TextView android:id=\"@+id/textView1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:text=\"First name: \" android:textStyle=\"bold\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <TextView android:id=\"@+id/firstname\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:text=\"TextView\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toEndOf=\"@+id/textView1\" app:layout_constraintTop_toTopOf=\"parent\" /> <TextView android:id=\"@+id/textView2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:text=\"Last name:\" android:textStyle=\"bold\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView1\" /> <TextView android:id=\"@+id/lastname\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:text=\"TextView\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toEndOf=\"@+id/textView2\" app:layout_constraintTop_toBottomOf=\"@+id/firstname\" /> <TextView android:id=\"@+id/textView3\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginBottom=\"16dp\" android:text=\"Age\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView2\" /> <TextView android:id=\"@+id/age\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:layout_marginBottom=\"16dp\" android:text=\"TextView\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toEndOf=\"@+id/textView3\" app:layout_constraintTop_toBottomOf=\"@+id/lastname\" /> </androidx.constraintlayout.widget.ConstraintLayout></androidx.cardview.widget.CardView>"
},
{
"code": null,
"e": 9896,
"s": 9892,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginHorizontal=\"10dp\" android:layout_marginTop=\"10dp\" android:layout_marginBottom=\"20dp\" android:scrollbars=\"vertical\" app:cardCornerRadius=\"20dp\"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <TextView android:id=\"@+id/textView1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:text=\"First name: \" android:textStyle=\"bold\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <TextView android:id=\"@+id/firstname\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:text=\"TextView\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toEndOf=\"@+id/textView1\" app:layout_constraintTop_toTopOf=\"parent\" /> <TextView android:id=\"@+id/textView2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:text=\"Last name:\" android:textStyle=\"bold\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView1\" /> <TextView android:id=\"@+id/lastname\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:text=\"TextView\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toEndOf=\"@+id/textView2\" app:layout_constraintTop_toBottomOf=\"@+id/firstname\" /> <TextView android:id=\"@+id/textView3\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginBottom=\"16dp\" android:text=\"Age\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/textView2\" /> <TextView android:id=\"@+id/age\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:layout_marginBottom=\"16dp\" android:text=\"TextView\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toEndOf=\"@+id/textView3\" app:layout_constraintTop_toBottomOf=\"@+id/lastname\" /> </androidx.constraintlayout.widget.ConstraintLayout></androidx.cardview.widget.CardView>",
"e": 13604,
"s": 9896,
"text": null
},
{
"code": null,
"e": 14894,
"s": 13604,
"text": "Step 4: After this, We have to create a java file to fetch and store data of a particular person from the database and give it to Recycler View one by one. Create person.java in the same folder in which MainActivity.java file is present. Paste the following code in the file.JavaJava// Your package name can be different depending// on your project namepackage com.example.recyclerview; public class person { // Variable to store data corresponding // to firstname keyword in database private String firstname; // Variable to store data corresponding // to lastname keyword in database private String lastname; // Variable to store data corresponding // to age keyword in database private String age; // Mandatory empty constructor // for use of FirebaseUI public person() {} // Getter and setter method public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getAge() { return age; } public void setAge(String age) { this.age = age; }}"
},
{
"code": null,
"e": 14899,
"s": 14894,
"text": "Java"
},
{
"code": "// Your package name can be different depending// on your project namepackage com.example.recyclerview; public class person { // Variable to store data corresponding // to firstname keyword in database private String firstname; // Variable to store data corresponding // to lastname keyword in database private String lastname; // Variable to store data corresponding // to age keyword in database private String age; // Mandatory empty constructor // for use of FirebaseUI public person() {} // Getter and setter method public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getAge() { return age; } public void setAge(String age) { this.age = age; }}",
"e": 15906,
"s": 14899,
"text": null
},
{
"code": null,
"e": 18641,
"s": 15906,
"text": "Step 5: In order to show the data from person.java in person.xml, we have to create an Adapter class. Create another java file named personAdapter.java in the same folder as MainActivity.java and paste the following code.JavaJavapackage com.example.recyclerview;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import com.firebase.ui.database.FirebaseRecyclerAdapter;import com.firebase.ui.database.FirebaseRecyclerOptions; // FirebaseRecyclerAdapter is a class provided by// FirebaseUI. it provides functions to bind, adapt and show// database contents in a Recycler Viewpublic class personAdapter extends FirebaseRecyclerAdapter< person, personAdapter.personsViewholder> { public personAdapter( @NonNull FirebaseRecyclerOptions<person> options) { super(options); } // Function to bind the view in Card view(here // \"person.xml\") iwth data in // model class(here \"person.class\") @Override protected void onBindViewHolder(@NonNull personsViewholder holder, int position, @NonNull person model) { // Add firstname from model class (here // \"person.class\")to appropriate view in Card // view (here \"person.xml\") holder.firstname.setText(model.getFirstname()); // Add lastname from model class (here // \"person.class\")to appropriate view in Card // view (here \"person.xml\") holder.lastname.setText(model.getLastname()); // Add age from model class (here // \"person.class\")to appropriate view in Card // view (here \"person.xml\") holder.age.setText(model.getAge()); } // Function to tell the class about the Card view (here // \"person.xml\")in // which the data will be shown @NonNull @Override public personsViewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.person, parent, false); return new personAdapter.personsViewholder(view); } // Sub Class to create references of the views in Crad // view (here \"person.xml\") class personsViewholder extends RecyclerView.ViewHolder { TextView firstname, lastname, age; public personsViewholder(@NonNull View itemView) { super(itemView); firstname = itemView.findViewById(R.id.firstname); lastname = itemView.findViewById(R.id.lastname); age = itemView.findViewById(R.id.age); } }}"
},
{
"code": null,
"e": 18646,
"s": 18641,
"text": "Java"
},
{
"code": "package com.example.recyclerview;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import com.firebase.ui.database.FirebaseRecyclerAdapter;import com.firebase.ui.database.FirebaseRecyclerOptions; // FirebaseRecyclerAdapter is a class provided by// FirebaseUI. it provides functions to bind, adapt and show// database contents in a Recycler Viewpublic class personAdapter extends FirebaseRecyclerAdapter< person, personAdapter.personsViewholder> { public personAdapter( @NonNull FirebaseRecyclerOptions<person> options) { super(options); } // Function to bind the view in Card view(here // \"person.xml\") iwth data in // model class(here \"person.class\") @Override protected void onBindViewHolder(@NonNull personsViewholder holder, int position, @NonNull person model) { // Add firstname from model class (here // \"person.class\")to appropriate view in Card // view (here \"person.xml\") holder.firstname.setText(model.getFirstname()); // Add lastname from model class (here // \"person.class\")to appropriate view in Card // view (here \"person.xml\") holder.lastname.setText(model.getLastname()); // Add age from model class (here // \"person.class\")to appropriate view in Card // view (here \"person.xml\") holder.age.setText(model.getAge()); } // Function to tell the class about the Card view (here // \"person.xml\")in // which the data will be shown @NonNull @Override public personsViewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.person, parent, false); return new personAdapter.personsViewholder(view); } // Sub Class to create references of the views in Crad // view (here \"person.xml\") class personsViewholder extends RecyclerView.ViewHolder { TextView firstname, lastname, age; public personsViewholder(@NonNull View itemView) { super(itemView); firstname = itemView.findViewById(R.id.firstname); lastname = itemView.findViewById(R.id.lastname); age = itemView.findViewById(R.id.age); } }}",
"e": 21152,
"s": 18646,
"text": null
},
{
"code": null,
"e": 23423,
"s": 21152,
"text": "Step 6: Then we have called the database and ask for data from it. This will be done in MainActivity.java itself.JavaJavapackage com.example.recyclerview;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import com.firebase.ui.database.FirebaseRecyclerOptions;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; personAdapter adapter; // Create Object of the Adapter class DatabaseReference mbase; // Create object of the // Firebase Realtime Database @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create a instance of the database and get // its reference mbase = FirebaseDatabase.getInstance().getReference(); recyclerView = findViewById(R.id.recycler1); // To display the Recycler view linearly recyclerView.setLayoutManager( new LinearLayoutManager(this)); // It is a class provide by the FirebaseUI to make a // query in the database to fetch appropriate data FirebaseRecyclerOptions<person> options = new FirebaseRecyclerOptions.Builder<person>() .setQuery(mbase, person.class) .build(); // Connecting object of required Adapter class to // the Adapter class itself adapter = new personAdapter(options); // Connecting Adapter class with the Recycler view*/ recyclerView.setAdapter(adapter); } // Function to tell the app to start getting // data from database on starting of the activity @Override protected void onStart() { super.onStart(); adapter.startListening(); } // Function to tell the app to stop getting // data from database on stopping of the activity @Override protected void onStop() { super.onStop(); adapter.stopListening(); }}"
},
{
"code": null,
"e": 23428,
"s": 23423,
"text": "Java"
},
{
"code": "package com.example.recyclerview;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.Bundle;import com.firebase.ui.database.FirebaseRecyclerOptions;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; personAdapter adapter; // Create Object of the Adapter class DatabaseReference mbase; // Create object of the // Firebase Realtime Database @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create a instance of the database and get // its reference mbase = FirebaseDatabase.getInstance().getReference(); recyclerView = findViewById(R.id.recycler1); // To display the Recycler view linearly recyclerView.setLayoutManager( new LinearLayoutManager(this)); // It is a class provide by the FirebaseUI to make a // query in the database to fetch appropriate data FirebaseRecyclerOptions<person> options = new FirebaseRecyclerOptions.Builder<person>() .setQuery(mbase, person.class) .build(); // Connecting object of required Adapter class to // the Adapter class itself adapter = new personAdapter(options); // Connecting Adapter class with the Recycler view*/ recyclerView.setAdapter(adapter); } // Function to tell the app to start getting // data from database on starting of the activity @Override protected void onStart() { super.onStart(); adapter.startListening(); } // Function to tell the app to stop getting // data from database on stopping of the activity @Override protected void onStop() { super.onStop(); adapter.stopListening(); }}",
"e": 25578,
"s": 23428,
"text": null
},
{
"code": null,
"e": 25768,
"s": 25578,
"text": "Step 7: Before running the project In AndroidManifest.xml, one needs to include below permission, in order to access the internet:“uses-permission android:name=”android.permission.INTERNET”"
},
{
"code": null,
"e": 25828,
"s": 25768,
"text": "“uses-permission android:name=”android.permission.INTERNET”"
},
{
"code": null,
"e": 25836,
"s": 25828,
"text": "Output:"
},
{
"code": null,
"e": 25851,
"s": 25836,
"text": "varshagumber28"
},
{
"code": null,
"e": 25859,
"s": 25851,
"text": "android"
},
{
"code": null,
"e": 25864,
"s": 25859,
"text": "Java"
},
{
"code": null,
"e": 25869,
"s": 25864,
"text": "Java"
}
] |
Python | os.path.samefile() method
|
18 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.
os.path.samefile() method in Python is used to check whether the given two pathnames refer to the same file or directory or not. This is determined by comparing device number and i-node number of the given paths.This method make use of os.stat() method to get device number and i-node number of the given paths. So, an exception will be raised if somehow an os.stat() call fails on either pathname.
Syntax: os.path.samefile(path1, path2)
Parameter:path1: A path-like object representing the first file system path.path2: A path-like object representing the second file system path.
A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a Boolean value of class bool. This method returns True if both path refer to the same file otherwise returns False.
Code : Use of os.path.samefile() method to check whether given paths refer to same file or directory.
# Python program to explain os.path.samefile() method # importing os module import os # Pathpath1 = "/home / ihritik / Documents / file(original).txt" # Create a symbolic link sym_link = "/home / ihritik / Desktop / file(shortcut).txt"os.symlink(path1, sym_link) # Check whether the given# paths refer to the same# file or directory or notareSame = os.path.samefile(path1, sym_link) # Print the resultprint(areSame) # In above example, sym_link is # a symbolic link which refers# to path1, so os.path.samefile() method# will return True as both refer # to same file # First Pathpath2 = "/home / ihritik / GeeksForGeeks" # Second path# consider the current working directory# is "/home / ihritik"path3 = os.path.join(os.getcwd(), "GeeksForGeeks") # Check whether the given# paths refer to the same# file or directory or notareSame = os.path.samefile(path2, path3) # Print the resultprint(areSame)
True
True
Reference: https://docs.python.org/3/library/os.path.html
Python OS-path-module
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2019"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation."
},
{
"code": null,
"e": 738,
"s": 339,
"text": "os.path.samefile() method in Python is used to check whether the given two pathnames refer to the same file or directory or not. This is determined by comparing device number and i-node number of the given paths.This method make use of os.stat() method to get device number and i-node number of the given paths. So, an exception will be raised if somehow an os.stat() call fails on either pathname."
},
{
"code": null,
"e": 777,
"s": 738,
"text": "Syntax: os.path.samefile(path1, path2)"
},
{
"code": null,
"e": 921,
"s": 777,
"text": "Parameter:path1: A path-like object representing the first file system path.path2: A path-like object representing the second file system path."
},
{
"code": null,
"e": 996,
"s": 921,
"text": "A path-like object is either a string or bytes object representing a path."
},
{
"code": null,
"e": 1146,
"s": 996,
"text": "Return Type: This method returns a Boolean value of class bool. This method returns True if both path refer to the same file otherwise returns False."
},
{
"code": null,
"e": 1248,
"s": 1146,
"text": "Code : Use of os.path.samefile() method to check whether given paths refer to same file or directory."
},
{
"code": "# Python program to explain os.path.samefile() method # importing os module import os # Pathpath1 = \"/home / ihritik / Documents / file(original).txt\" # Create a symbolic link sym_link = \"/home / ihritik / Desktop / file(shortcut).txt\"os.symlink(path1, sym_link) # Check whether the given# paths refer to the same# file or directory or notareSame = os.path.samefile(path1, sym_link) # Print the resultprint(areSame) # In above example, sym_link is # a symbolic link which refers# to path1, so os.path.samefile() method# will return True as both refer # to same file # First Pathpath2 = \"/home / ihritik / GeeksForGeeks\" # Second path# consider the current working directory# is \"/home / ihritik\"path3 = os.path.join(os.getcwd(), \"GeeksForGeeks\") # Check whether the given# paths refer to the same# file or directory or notareSame = os.path.samefile(path2, path3) # Print the resultprint(areSame)",
"e": 2159,
"s": 1248,
"text": null
},
{
"code": null,
"e": 2170,
"s": 2159,
"text": "True\nTrue\n"
},
{
"code": null,
"e": 2228,
"s": 2170,
"text": "Reference: https://docs.python.org/3/library/os.path.html"
},
{
"code": null,
"e": 2250,
"s": 2228,
"text": "Python OS-path-module"
},
{
"code": null,
"e": 2267,
"s": 2250,
"text": "python-os-module"
},
{
"code": null,
"e": 2274,
"s": 2267,
"text": "Python"
},
{
"code": null,
"e": 2372,
"s": 2274,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2404,
"s": 2372,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2431,
"s": 2404,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2452,
"s": 2431,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2475,
"s": 2452,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2531,
"s": 2475,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2562,
"s": 2531,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2604,
"s": 2562,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2646,
"s": 2604,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2685,
"s": 2646,
"text": "Python | Get unique values from a list"
}
] |
Python | math.gcd() function
|
20 Mar, 2019
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.gcd() function compute the greatest common divisor of 2 numbers mentioned in its arguments.
Syntax: math.gcd(x, y)
Parameter:x : Non-negative integer whose gcd has to be computed.y : Non-negative integer whose gcd has to be computed.
Returns: An absolute/positive integer value after calculating the GCD of given parameters x and y.
Exceptions : When Both x and y are 0, function returns 0, If any number is a character, Type error is raised.
Code #1:
# Python code to demonstrate the working of gcd() # importing "math" for mathematical operations import math # prints 12 print ("The gcd of 60 and 48 is : ", end ="") print (math.gcd(60, 48))
The gcd of 60 and 48 is : 12
Code #2:
# Python code to demonstrate the working of gcd() # importing "math" for mathematical operations import math # prints gcd of x, yprint ("math.gcd(44, 12) : ", math.gcd(44, 12))print ("math.gcd(69, 23) : ", math.gcd(65, 45))
math.gcd(44, 12) : 4
math.gcd(69, 23) : 5
Code #3: Explaining Exception.
# Python code to demonstrate gcd() # method exceptions import math # prints 0 print ("The gcd of 0 and 0 is : ", end ="") print (math.gcd(0, 0)) # Produces error print ("\nThe gcd of a and 13 is : ", end ="") print (math.gcd('a', 13))
Output:
The gcd of 0 and 0 is : 0
The gcd of a and 13 is :
TypeError: 'str' object cannot be interpreted as an integer
Python math-library-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
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.gcd() function compute the greatest common divisor of 2 numbers mentioned in its arguments."
},
{
"code": null,
"e": 268,
"s": 245,
"text": "Syntax: math.gcd(x, y)"
},
{
"code": null,
"e": 387,
"s": 268,
"text": "Parameter:x : Non-negative integer whose gcd has to be computed.y : Non-negative integer whose gcd has to be computed."
},
{
"code": null,
"e": 486,
"s": 387,
"text": "Returns: An absolute/positive integer value after calculating the GCD of given parameters x and y."
},
{
"code": null,
"e": 596,
"s": 486,
"text": "Exceptions : When Both x and y are 0, function returns 0, If any number is a character, Type error is raised."
},
{
"code": null,
"e": 605,
"s": 596,
"text": "Code #1:"
},
{
"code": "# Python code to demonstrate the working of gcd() # importing \"math\" for mathematical operations import math # prints 12 print (\"The gcd of 60 and 48 is : \", end =\"\") print (math.gcd(60, 48)) ",
"e": 805,
"s": 605,
"text": null
},
{
"code": null,
"e": 835,
"s": 805,
"text": "The gcd of 60 and 48 is : 12\n"
},
{
"code": null,
"e": 845,
"s": 835,
"text": " Code #2:"
},
{
"code": "# Python code to demonstrate the working of gcd() # importing \"math\" for mathematical operations import math # prints gcd of x, yprint (\"math.gcd(44, 12) : \", math.gcd(44, 12))print (\"math.gcd(69, 23) : \", math.gcd(65, 45))",
"e": 1072,
"s": 845,
"text": null
},
{
"code": null,
"e": 1117,
"s": 1072,
"text": "math.gcd(44, 12) : 4\nmath.gcd(69, 23) : 5\n"
},
{
"code": null,
"e": 1148,
"s": 1117,
"text": "Code #3: Explaining Exception."
},
{
"code": "# Python code to demonstrate gcd() # method exceptions import math # prints 0 print (\"The gcd of 0 and 0 is : \", end =\"\") print (math.gcd(0, 0)) # Produces error print (\"\\nThe gcd of a and 13 is : \", end =\"\") print (math.gcd('a', 13)) ",
"e": 1392,
"s": 1148,
"text": null
},
{
"code": null,
"e": 1400,
"s": 1392,
"text": "Output:"
},
{
"code": null,
"e": 1513,
"s": 1400,
"text": "The gcd of 0 and 0 is : 0\n\nThe gcd of a and 13 is : \nTypeError: 'str' object cannot be interpreted as an integer"
},
{
"code": null,
"e": 1543,
"s": 1513,
"text": "Python math-library-functions"
},
{
"code": null,
"e": 1550,
"s": 1543,
"text": "Python"
},
{
"code": null,
"e": 1648,
"s": 1550,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1666,
"s": 1648,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1708,
"s": 1666,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1730,
"s": 1708,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1756,
"s": 1730,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1788,
"s": 1756,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1817,
"s": 1788,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1844,
"s": 1817,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1865,
"s": 1844,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1901,
"s": 1865,
"text": "Convert integer to string in Python"
}
] |
How to declare a global variable in PHP?
|
31 Jul, 2021
Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.
Syntax:
$variable_name = data;
Below programs illustrate how to declare global variable.
Example 1:
<?php// Demonstrate how to declare global variable // Declaring global variable$x = "Geeks";$y = "for";$z = "Geeks"; // Display value// Concatenating Stringecho $x.$y.$z; ?>
GeeksforGeeks
Accessing global variable inside function: The ways to access the global variable inside functions are:
Using global keyword
Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable. This array is also accessible from within functions and can be used to perform operations on global variables directly.
Example 2:
<?php// Demonstrate how to declare// global variable // Declaring global variable$x = "Geeks";$y = "for";$z = "Geeks";$a = 5;$b = 10; function concatenate() { // Using global keyword global $x, $y, $z; return $x.$y.$z;} function add() { // Using GLOBALS['var_name'] $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];} // Print resultecho concatenate();echo"\n";add();echo $b;?>
GeeksforGeeks
15
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
How to convert array to string in PHP ?
Comparing two dates in PHP
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
How to fetch data from localserver database and display on HTML table using PHP ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 329,
"s": 28,
"text": "Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition."
},
{
"code": null,
"e": 337,
"s": 329,
"text": "Syntax:"
},
{
"code": null,
"e": 360,
"s": 337,
"text": "$variable_name = data;"
},
{
"code": null,
"e": 418,
"s": 360,
"text": "Below programs illustrate how to declare global variable."
},
{
"code": null,
"e": 429,
"s": 418,
"text": "Example 1:"
},
{
"code": "<?php// Demonstrate how to declare global variable // Declaring global variable$x = \"Geeks\";$y = \"for\";$z = \"Geeks\"; // Display value// Concatenating Stringecho $x.$y.$z; ?>",
"e": 606,
"s": 429,
"text": null
},
{
"code": null,
"e": 621,
"s": 606,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 725,
"s": 621,
"text": "Accessing global variable inside function: The ways to access the global variable inside functions are:"
},
{
"code": null,
"e": 746,
"s": 725,
"text": "Using global keyword"
},
{
"code": null,
"e": 1005,
"s": 746,
"text": "Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable. This array is also accessible from within functions and can be used to perform operations on global variables directly."
},
{
"code": null,
"e": 1016,
"s": 1005,
"text": "Example 2:"
},
{
"code": "<?php// Demonstrate how to declare// global variable // Declaring global variable$x = \"Geeks\";$y = \"for\";$z = \"Geeks\";$a = 5;$b = 10; function concatenate() { // Using global keyword global $x, $y, $z; return $x.$y.$z;} function add() { // Using GLOBALS['var_name'] $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];} // Print resultecho concatenate();echo\"\\n\";add();echo $b;?>",
"e": 1409,
"s": 1016,
"text": null
},
{
"code": null,
"e": 1427,
"s": 1409,
"text": "GeeksforGeeks\n15\n"
},
{
"code": null,
"e": 1596,
"s": 1427,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 1603,
"s": 1596,
"text": "Picked"
},
{
"code": null,
"e": 1607,
"s": 1603,
"text": "PHP"
},
{
"code": null,
"e": 1620,
"s": 1607,
"text": "PHP Programs"
},
{
"code": null,
"e": 1637,
"s": 1620,
"text": "Web Technologies"
},
{
"code": null,
"e": 1664,
"s": 1637,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1668,
"s": 1664,
"text": "PHP"
},
{
"code": null,
"e": 1766,
"s": 1668,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1806,
"s": 1766,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 1851,
"s": 1806,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 1878,
"s": 1851,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 1930,
"s": 1878,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 1978,
"s": 1930,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 2018,
"s": 1978,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2045,
"s": 2018,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 2097,
"s": 2045,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 2145,
"s": 2097,
"text": "How to get parameters from a URL string in PHP?"
}
] |
Python | Switch widget in Kivy
|
03 Nov, 2021
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
???????? Kivy Tutorial – Learn Kivy with Examples.
The Switch widget is active or inactive, as a mechanical light switch. The user can swipe to the left/right to activate/deactivate it. The value represented by the switch is either True or False. That is the switch can be either in On position or Off position.To work with Switch you must have to import:
from kivy.uix.switch import Switch
Note: If you want to control the state with a single touch instead of a swipe, use the ToggleButton instead.
Basic Approach:
1) import kivy
2) import kivyApp
3) import Switch
4) import Gridlayout
5) import Label
6) Set minimum version(optional)
7) create Layout class(In this you create a switch)
8) create App class
9) return Layout/widget/Class(according to requirement)
10) Run an instance of the class
Implementation of the Approach:
Python3
# Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require('1.9.0') # The Switch widget is active or inactive# The state transition of a switch is from# either on to off or off to on.from kivy.uix.switch import Switch # The GridLayout arranges children in a matrix.# It takes the available space and# divides it into columns and rows,# then adds widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # The Label widget is for rendering text.from kivy.uix.label import Label # A Gridlayout with a label a switch# A class which contains all stuff about the switchclass SimpleSwitch(GridLayout): # Defining __init__ constructor def __init__(self, **kwargs): # super function can be used to gain access # to inherited methods from a parent or sibling class # that has been overwritten in a class object. super(SimpleSwitch, self).__init__(**kwargs) # no of columns self.cols = 2 # Adding label to the Switch self.add_widget(Label(text ="Switch")) # Initially switch is Off i.e active = False self.settings_sample = Switch(active = False) # Add widget self.add_widget(self.settings_sample) # Defining the App Classclass SwitchApp(App): # define build function def build(self): # return the switch class return SimpleSwitch() # Run the kivy appif __name__ == '__main__': SwitchApp().run()
Output:
Attaching Callback to Switch:
A switch can be attached with a call back to retrieve the value of the switch.
The state transition of a switch is from either ON to OFF or OFF to ON.
When switch makes any transition the callback is triggered and new state can be retrieved i.e came and any other action can be taken based on the state.
By default, the representation of the widget is static. The minimum size required is 83*32 pixels.
The entire widget is active, not just the part with graphics. As long as you swipe over the widget’s bounding box, it will work.
Now For attaching a callback you have to define a callback function and bind it with the switch. So below is the code how to Attach a callback:
Python3
# Program to Show how to attach a callback to switch # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require('1.9.0') # The Switch widget is active or inactive# The state transition of a switch is from# either on to off or off to on.from kivy.uix.switch import Switch # The GridLayout arranges children in a matrix.# It takes the available space and# divides it into columns and rows,# then adds widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # The Label widget is for rendering text.from kivy.uix.label import Label # A Gridlayout with a label a switch# A class which contains all stuff about the switchclass SimpleSwitch(GridLayout): # Defining __init__ constructor def __init__(self, **kwargs): # super function can be used to gain access # to inherited methods from a parent or sibling class # that has been overwritten in a class object. super(SimpleSwitch, self).__init__(**kwargs) # no of columns self.cols = 2 # Adding label to the Switch self.add_widget(Label(text ="Switch")) # Initially switch is Off i.e active = False self.settings_sample = Switch(active = False) # Add widget self.add_widget(self.settings_sample) # Arranging a callback to the switch # using bing function self.settings_sample.bind(active = switch_callback) # Callback for the switch state transition# Defining a Callback function# Contains Two parameter switchObject, switchValuedef switch_callback(switchObject, switchValue): # Switch value are True and False if(switchValue): print('Switch is ON:):):)') else: print('Switch is OFF:(:(:(') # Defining the App Classclass SwitchApp(App): # define build function def build(self): # return the switch class return SimpleSwitch() # Run the kivy appif __name__ == '__main__': SwitchApp().run()
Output:
kashishsoda
sweetyty
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Nov, 2021"
},
{
"code": null,
"e": 265,
"s": 28,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. "
},
{
"code": null,
"e": 316,
"s": 265,
"text": "???????? Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 625,
"s": 318,
"text": "The Switch widget is active or inactive, as a mechanical light switch. The user can swipe to the left/right to activate/deactivate it. The value represented by the switch is either True or False. That is the switch can be either in On position or Off position.To work with Switch you must have to import: "
},
{
"code": null,
"e": 660,
"s": 625,
"text": "from kivy.uix.switch import Switch"
},
{
"code": null,
"e": 770,
"s": 660,
"text": "Note: If you want to control the state with a single touch instead of a swipe, use the ToggleButton instead. "
},
{
"code": null,
"e": 1068,
"s": 770,
"text": "Basic Approach:\n\n1) import kivy\n2) import kivyApp\n3) import Switch\n4) import Gridlayout\n5) import Label\n6) Set minimum version(optional)\n7) create Layout class(In this you create a switch)\n8) create App class\n9) return Layout/widget/Class(according to requirement)\n10) Run an instance of the class"
},
{
"code": null,
"e": 1102,
"s": 1068,
"text": "Implementation of the Approach: "
},
{
"code": null,
"e": 1110,
"s": 1102,
"text": "Python3"
},
{
"code": "# Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require('1.9.0') # The Switch widget is active or inactive# The state transition of a switch is from# either on to off or off to on.from kivy.uix.switch import Switch # The GridLayout arranges children in a matrix.# It takes the available space and# divides it into columns and rows,# then adds widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # The Label widget is for rendering text.from kivy.uix.label import Label # A Gridlayout with a label a switch# A class which contains all stuff about the switchclass SimpleSwitch(GridLayout): # Defining __init__ constructor def __init__(self, **kwargs): # super function can be used to gain access # to inherited methods from a parent or sibling class # that has been overwritten in a class object. super(SimpleSwitch, self).__init__(**kwargs) # no of columns self.cols = 2 # Adding label to the Switch self.add_widget(Label(text =\"Switch\")) # Initially switch is Off i.e active = False self.settings_sample = Switch(active = False) # Add widget self.add_widget(self.settings_sample) # Defining the App Classclass SwitchApp(App): # define build function def build(self): # return the switch class return SimpleSwitch() # Run the kivy appif __name__ == '__main__': SwitchApp().run()",
"e": 2844,
"s": 1110,
"text": null
},
{
"code": null,
"e": 2854,
"s": 2844,
"text": "Output: "
},
{
"code": null,
"e": 2888,
"s": 2856,
"text": "Attaching Callback to Switch: "
},
{
"code": null,
"e": 2967,
"s": 2888,
"text": "A switch can be attached with a call back to retrieve the value of the switch."
},
{
"code": null,
"e": 3039,
"s": 2967,
"text": "The state transition of a switch is from either ON to OFF or OFF to ON."
},
{
"code": null,
"e": 3192,
"s": 3039,
"text": "When switch makes any transition the callback is triggered and new state can be retrieved i.e came and any other action can be taken based on the state."
},
{
"code": null,
"e": 3291,
"s": 3192,
"text": "By default, the representation of the widget is static. The minimum size required is 83*32 pixels."
},
{
"code": null,
"e": 3420,
"s": 3291,
"text": "The entire widget is active, not just the part with graphics. As long as you swipe over the widget’s bounding box, it will work."
},
{
"code": null,
"e": 3565,
"s": 3420,
"text": "Now For attaching a callback you have to define a callback function and bind it with the switch. So below is the code how to Attach a callback: "
},
{
"code": null,
"e": 3573,
"s": 3565,
"text": "Python3"
},
{
"code": "# Program to Show how to attach a callback to switch # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require('1.9.0') # The Switch widget is active or inactive# The state transition of a switch is from# either on to off or off to on.from kivy.uix.switch import Switch # The GridLayout arranges children in a matrix.# It takes the available space and# divides it into columns and rows,# then adds widgets to the resulting “cells”.from kivy.uix.gridlayout import GridLayout # The Label widget is for rendering text.from kivy.uix.label import Label # A Gridlayout with a label a switch# A class which contains all stuff about the switchclass SimpleSwitch(GridLayout): # Defining __init__ constructor def __init__(self, **kwargs): # super function can be used to gain access # to inherited methods from a parent or sibling class # that has been overwritten in a class object. super(SimpleSwitch, self).__init__(**kwargs) # no of columns self.cols = 2 # Adding label to the Switch self.add_widget(Label(text =\"Switch\")) # Initially switch is Off i.e active = False self.settings_sample = Switch(active = False) # Add widget self.add_widget(self.settings_sample) # Arranging a callback to the switch # using bing function self.settings_sample.bind(active = switch_callback) # Callback for the switch state transition# Defining a Callback function# Contains Two parameter switchObject, switchValuedef switch_callback(switchObject, switchValue): # Switch value are True and False if(switchValue): print('Switch is ON:):):)') else: print('Switch is OFF:(:(:(') # Defining the App Classclass SwitchApp(App): # define build function def build(self): # return the switch class return SimpleSwitch() # Run the kivy appif __name__ == '__main__': SwitchApp().run()",
"e": 5767,
"s": 3573,
"text": null
},
{
"code": null,
"e": 5777,
"s": 5767,
"text": "Output: "
},
{
"code": null,
"e": 5791,
"s": 5779,
"text": "kashishsoda"
},
{
"code": null,
"e": 5800,
"s": 5791,
"text": "sweetyty"
},
{
"code": null,
"e": 5811,
"s": 5800,
"text": "Python-gui"
},
{
"code": null,
"e": 5823,
"s": 5811,
"text": "Python-kivy"
},
{
"code": null,
"e": 5830,
"s": 5823,
"text": "Python"
},
{
"code": null,
"e": 5928,
"s": 5830,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5956,
"s": 5928,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 5978,
"s": 5956,
"text": "Python map() function"
},
{
"code": null,
"e": 6028,
"s": 5978,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 6072,
"s": 6028,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 6114,
"s": 6072,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 6136,
"s": 6114,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 6171,
"s": 6136,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 6197,
"s": 6171,
"text": "Python String | replace()"
},
{
"code": null,
"e": 6229,
"s": 6197,
"text": "How to Install PIP on Windows ?"
}
] |
Segregate even and odd numbers | Set 3
|
14 Jun, 2022
Given an array arr[] of integers, segregate even and odd numbers in the array. Such that all the even numbers should be present first, and then the odd numbers.
Examples:
Input: arr[] = 1 9 5 3 2 6 7 11Output: 2 6 5 3 1 9 7 11
Input: arr[] = 1 3 2 4 7 6 9 10Output: 2 4 6 10 7 1 9 3
We have discussed two different approaches in below posts:
Segregate Even and Odd numbersSegregate even and odd numbers | Set 2
Segregate Even and Odd numbers
Segregate even and odd numbers | Set 2
Brute-Force Solution:
As we need to maintain the order of elements then this can be done in the following steps :
Create a temporary array A of size n and an integer index which will keep the index of elements inserted .Initialize index with zero and iterate over the original array and if even number is found then put that number at A[index] and then increment the value of index .Again iterate over array and if an odd number is found then put it in A[index] and then increment the value of index.Iterate over the temporary array A and copy its values in the original array.
Create a temporary array A of size n and an integer index which will keep the index of elements inserted .
Initialize index with zero and iterate over the original array and if even number is found then put that number at A[index] and then increment the value of index .
Again iterate over array and if an odd number is found then put it in A[index] and then increment the value of index.
Iterate over the temporary array A and copy its values in the original array.
C++
Java
Python3
C#
Javascript
// C++ Implementation of the above approach#include <iostream>using namespace std;void arrayEvenAndOdd(int arr[], int n){ int a[n], index = 0; for (int i = 0; i < n; i++) { if (arr[i] % 2 == 0) { a[index] = arr[i]; index++; } } for (int i = 0; i < n; i++) { if (arr[i] % 2 != 0) { a[index] = arr[i]; index++; } } for (int i = 0; i < n; i++) { cout << a[i] << " "; } cout << endl;} // Driver codeint main(){ int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = sizeof(arr) / sizeof(int); // Function call arrayEvenAndOdd(arr, n); return 0;}
// Java Implementation of the above approachimport java.io.*;class GFG{public static void arrayEvenAndOdd(int arr[], int n){ int[] a; a = new int[n]; int index = 0; for (int i = 0; i < n; i++) { if (arr[i] % 2 == 0) { a[index] = arr[i]; index++; } } for (int i = 0; i < n; i++) { if (arr[i] % 2 != 0) { a[index] = arr[i]; index++; } } for (int i = 0; i < n; i++) { System.out.print(a[i] + " "); } System.out.println("");} // Driver code public static void main (String[] args) { int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = arr.length; // Function call arrayEvenAndOdd(arr, n); }} // This code is contributed by rohitsingh07052.
# Python3 implementation of the above approachdef arrayEvenAndOdd(arr, n): index = 0; a = [0 for i in range(n)] for i in range(n): if (arr[i] % 2 == 0): a[index] = arr[i] ind += 1 for i in range(n): if (arr[i] % 2 != 0): a[index] = arr[i] ind += 1 for i in range(n): print(a[i], end = " ") print() # Driver codearr = [ 1, 3, 2, 4, 7, 6, 9, 10 ]n = len(arr) # Function callarrayEvenAndOdd(arr, n) # This code is contributed by rohitsingh07052
// C# implementation of the above approachusing System; class GFG{ static void arrayEvenAndOdd(int[] arr, int n){ int[] a = new int[n]; int index = 0; for(int i = 0; i < n; i++) { if (arr[i] % 2 == 0) { a[index] = arr[i]; index++; } } for(int i = 0; i < n; i++) { if (arr[i] % 2 != 0) { a[index] = arr[i]; index++; } } for(int i = 0; i < n; i++) { Console.Write(a[i] + " "); }} // Driver codestatic public void Main(){ int[] arr = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = arr.Length; arrayEvenAndOdd(arr, n);}} // This code is contributed by Potta Lokesh
<script> // JavaScript Implementation of the above approach function arrayEvenAndOdd(arr, n){ let a= []; let index = 0; for (let i = 0; i < n; i++) { if (arr[i] % 2 == 0) { a[index] = arr[i]; index++; } } for (let i = 0; i < n; i++) { if (arr[i] % 2 != 0) { a[index] = arr[i]; index++; } } for (let i = 0; i < n; i++) { document.write(a[i] +" "); } document.write('\n');} // Driver code let arr = [ 1, 3, 2, 4, 7, 6, 9, 10 ];let n = arr.length; // Function callarrayEvenAndOdd(arr, n); </script>
2 4 6 10 1 3 7 9
Time complexity: O(n)Auxiliary space: O(n)
Efficient Approach:
The optimization for above approach is based on Lomuto’s Partition Scheme
Maintain a pointer to the position before first odd element in the array.Traverse the array and if even number is encountered then swap it with the first odd element.Continue the traversal.
Maintain a pointer to the position before first odd element in the array.
Traverse the array and if even number is encountered then swap it with the first odd element.
Continue the traversal.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP code to segregate even odd// numbers in an array#include <bits/stdc++.h>using namespace std; // Function to segregate even odd numbersvoid arrayEvenAndOdd(int arr[], int n){ int i = -1, j = 0; int t; while (j != n) { if (arr[j] % 2 == 0) { i++; // Swapping even and odd numbers swap(arr[i], arr[j]); } j++; } // Printing segregated array for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Driver codeint main(){ int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = sizeof(arr) / sizeof(int); arrayEvenAndOdd(arr, n); return 0;}
// java code to segregate even odd// numbers in an arraypublic class GFG { // Function to segregate even // odd numbers static void arrayEvenAndOdd( int arr[], int n) { int i = -1, j = 0; while (j != n) { if (arr[j] % 2 == 0) { i++; // Swapping even and // odd numbers int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } j++; } // Printing segregated array for (int k = 0; k < n; k++) System.out.print(arr[k] + " "); } // Driver code public static void main(String args[]) { int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = arr.length; arrayEvenAndOdd(arr, n); }} // This code is contributed by Sam007
# Python3 code to segregate even odd# numbers in an array # Function to segregate even odd numbersdef arrayEvenAndOdd(arr,n): i = -1 j= 0 while (j!=n): if (arr[j] % 2 ==0): i = i+1 # Swapping even and odd numbers arr[i],arr[j] = arr[j],arr[i] j = j+1 # Printing segregated array for i in arr: print (str(i) + " " ,end='') # Driver Codeif __name__=='__main__': arr = [ 1 ,3, 2, 4, 7, 6, 9, 10] n = len(arr) arrayEvenAndOdd(arr,n) # This code was contributed by# Yatin Gupta
// C# code to segregate even odd// numbers in an arrayusing System; class GFG { // Function to segregate even // odd numbers static void arrayEvenAndOdd( int []arr, int n) { int i = -1, j = 0; while (j != n) { if (arr[j] % 2 == 0) { i++; // Swapping even and // odd numbers int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } j++; } // Printing segregated array for (int k = 0; k < n; k++) Console.Write(arr[k] + " "); } // Driver code static void Main() { int []arr = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = arr.Length; arrayEvenAndOdd(arr, n); }} // This code is contributed by Sam007
<?php// PHP code to segregate even odd// numbers in an array // Function to segregate// even odd numbersfunction arrayEvenAndOdd($arr, $n){ $i = -1; $j = 0; $t; while ($j != $n) { if ($arr[$j] % 2 == 0) { $i++; // Swapping even and // odd numbers $x = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $x; } $j++; } // Printing segregated // array for ($i = 0; $i < $n; $i++) echo $arr[$i] . " ";} // Driver code $arr = array(1, 3, 2, 4, 7, 6, 9, 10); $n = sizeof($arr); arrayEvenAndOdd($arr, $n); // This code is contributed by Anuj_67?>
<script>// JavaScript code to segregate even odd// numbers in an array // Function to segregate even odd numbersfunction arrayEvenAndOdd(arr, n){ let i = -1, j = 0; let t; while (j != n) { if (arr[j] % 2 == 0) { i++; // Swapping even and odd numbers let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } j++; } // Printing segregated array for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Driver code let arr = [ 1, 3, 2, 4, 7, 6, 9, 10 ]; let n = arr.length; arrayEvenAndOdd(arr, n); // This code is contributed by Surbhi Tyagi </script>
2 4 6 10 7 1 9 3
Time Complexity : O(n) Auxiliary Space : O(1)
Sam007
vt_m
YatinGupta
nichil942singh
surbhityagi15
rohitsingh07052
lokeshpotta20
tarakki100
array-rearrange
Quick Sort
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 213,
"s": 52,
"text": "Given an array arr[] of integers, segregate even and odd numbers in the array. Such that all the even numbers should be present first, and then the odd numbers."
},
{
"code": null,
"e": 225,
"s": 213,
"text": "Examples: "
},
{
"code": null,
"e": 281,
"s": 225,
"text": "Input: arr[] = 1 9 5 3 2 6 7 11Output: 2 6 5 3 1 9 7 11"
},
{
"code": null,
"e": 338,
"s": 281,
"text": "Input: arr[] = 1 3 2 4 7 6 9 10Output: 2 4 6 10 7 1 9 3"
},
{
"code": null,
"e": 398,
"s": 338,
"text": "We have discussed two different approaches in below posts: "
},
{
"code": null,
"e": 467,
"s": 398,
"text": "Segregate Even and Odd numbersSegregate even and odd numbers | Set 2"
},
{
"code": null,
"e": 498,
"s": 467,
"text": "Segregate Even and Odd numbers"
},
{
"code": null,
"e": 537,
"s": 498,
"text": "Segregate even and odd numbers | Set 2"
},
{
"code": null,
"e": 559,
"s": 537,
"text": "Brute-Force Solution:"
},
{
"code": null,
"e": 651,
"s": 559,
"text": "As we need to maintain the order of elements then this can be done in the following steps :"
},
{
"code": null,
"e": 1115,
"s": 651,
"text": "Create a temporary array A of size n and an integer index which will keep the index of elements inserted .Initialize index with zero and iterate over the original array and if even number is found then put that number at A[index] and then increment the value of index .Again iterate over array and if an odd number is found then put it in A[index] and then increment the value of index.Iterate over the temporary array A and copy its values in the original array."
},
{
"code": null,
"e": 1222,
"s": 1115,
"text": "Create a temporary array A of size n and an integer index which will keep the index of elements inserted ."
},
{
"code": null,
"e": 1386,
"s": 1222,
"text": "Initialize index with zero and iterate over the original array and if even number is found then put that number at A[index] and then increment the value of index ."
},
{
"code": null,
"e": 1504,
"s": 1386,
"text": "Again iterate over array and if an odd number is found then put it in A[index] and then increment the value of index."
},
{
"code": null,
"e": 1582,
"s": 1504,
"text": "Iterate over the temporary array A and copy its values in the original array."
},
{
"code": null,
"e": 1586,
"s": 1582,
"text": "C++"
},
{
"code": null,
"e": 1591,
"s": 1586,
"text": "Java"
},
{
"code": null,
"e": 1599,
"s": 1591,
"text": "Python3"
},
{
"code": null,
"e": 1602,
"s": 1599,
"text": "C#"
},
{
"code": null,
"e": 1613,
"s": 1602,
"text": "Javascript"
},
{
"code": "// C++ Implementation of the above approach#include <iostream>using namespace std;void arrayEvenAndOdd(int arr[], int n){ int a[n], index = 0; for (int i = 0; i < n; i++) { if (arr[i] % 2 == 0) { a[index] = arr[i]; index++; } } for (int i = 0; i < n; i++) { if (arr[i] % 2 != 0) { a[index] = arr[i]; index++; } } for (int i = 0; i < n; i++) { cout << a[i] << \" \"; } cout << endl;} // Driver codeint main(){ int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = sizeof(arr) / sizeof(int); // Function call arrayEvenAndOdd(arr, n); return 0;}",
"e": 2291,
"s": 1613,
"text": null
},
{
"code": "// Java Implementation of the above approachimport java.io.*;class GFG{public static void arrayEvenAndOdd(int arr[], int n){ int[] a; a = new int[n]; int index = 0; for (int i = 0; i < n; i++) { if (arr[i] % 2 == 0) { a[index] = arr[i]; index++; } } for (int i = 0; i < n; i++) { if (arr[i] % 2 != 0) { a[index] = arr[i]; index++; } } for (int i = 0; i < n; i++) { System.out.print(a[i] + \" \"); } System.out.println(\"\");} // Driver code public static void main (String[] args) { int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = arr.length; // Function call arrayEvenAndOdd(arr, n); }} // This code is contributed by rohitsingh07052.",
"e": 3114,
"s": 2291,
"text": null
},
{
"code": "# Python3 implementation of the above approachdef arrayEvenAndOdd(arr, n): index = 0; a = [0 for i in range(n)] for i in range(n): if (arr[i] % 2 == 0): a[index] = arr[i] ind += 1 for i in range(n): if (arr[i] % 2 != 0): a[index] = arr[i] ind += 1 for i in range(n): print(a[i], end = \" \") print() # Driver codearr = [ 1, 3, 2, 4, 7, 6, 9, 10 ]n = len(arr) # Function callarrayEvenAndOdd(arr, n) # This code is contributed by rohitsingh07052",
"e": 3661,
"s": 3114,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ static void arrayEvenAndOdd(int[] arr, int n){ int[] a = new int[n]; int index = 0; for(int i = 0; i < n; i++) { if (arr[i] % 2 == 0) { a[index] = arr[i]; index++; } } for(int i = 0; i < n; i++) { if (arr[i] % 2 != 0) { a[index] = arr[i]; index++; } } for(int i = 0; i < n; i++) { Console.Write(a[i] + \" \"); }} // Driver codestatic public void Main(){ int[] arr = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = arr.Length; arrayEvenAndOdd(arr, n);}} // This code is contributed by Potta Lokesh",
"e": 4361,
"s": 3661,
"text": null
},
{
"code": "<script> // JavaScript Implementation of the above approach function arrayEvenAndOdd(arr, n){ let a= []; let index = 0; for (let i = 0; i < n; i++) { if (arr[i] % 2 == 0) { a[index] = arr[i]; index++; } } for (let i = 0; i < n; i++) { if (arr[i] % 2 != 0) { a[index] = arr[i]; index++; } } for (let i = 0; i < n; i++) { document.write(a[i] +\" \"); } document.write('\\n');} // Driver code let arr = [ 1, 3, 2, 4, 7, 6, 9, 10 ];let n = arr.length; // Function callarrayEvenAndOdd(arr, n); </script>",
"e": 4986,
"s": 4361,
"text": null
},
{
"code": null,
"e": 5004,
"s": 4986,
"text": "2 4 6 10 1 3 7 9 "
},
{
"code": null,
"e": 5048,
"s": 5004,
"text": "Time complexity: O(n)Auxiliary space: O(n) "
},
{
"code": null,
"e": 5068,
"s": 5048,
"text": "Efficient Approach:"
},
{
"code": null,
"e": 5143,
"s": 5068,
"text": "The optimization for above approach is based on Lomuto’s Partition Scheme "
},
{
"code": null,
"e": 5333,
"s": 5143,
"text": "Maintain a pointer to the position before first odd element in the array.Traverse the array and if even number is encountered then swap it with the first odd element.Continue the traversal."
},
{
"code": null,
"e": 5407,
"s": 5333,
"text": "Maintain a pointer to the position before first odd element in the array."
},
{
"code": null,
"e": 5501,
"s": 5407,
"text": "Traverse the array and if even number is encountered then swap it with the first odd element."
},
{
"code": null,
"e": 5525,
"s": 5501,
"text": "Continue the traversal."
},
{
"code": null,
"e": 5577,
"s": 5525,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 5581,
"s": 5577,
"text": "C++"
},
{
"code": null,
"e": 5586,
"s": 5581,
"text": "Java"
},
{
"code": null,
"e": 5594,
"s": 5586,
"text": "Python3"
},
{
"code": null,
"e": 5597,
"s": 5594,
"text": "C#"
},
{
"code": null,
"e": 5601,
"s": 5597,
"text": "PHP"
},
{
"code": null,
"e": 5612,
"s": 5601,
"text": "Javascript"
},
{
"code": "// CPP code to segregate even odd// numbers in an array#include <bits/stdc++.h>using namespace std; // Function to segregate even odd numbersvoid arrayEvenAndOdd(int arr[], int n){ int i = -1, j = 0; int t; while (j != n) { if (arr[j] % 2 == 0) { i++; // Swapping even and odd numbers swap(arr[i], arr[j]); } j++; } // Printing segregated array for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Driver codeint main(){ int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = sizeof(arr) / sizeof(int); arrayEvenAndOdd(arr, n); return 0;}",
"e": 6241,
"s": 5612,
"text": null
},
{
"code": "// java code to segregate even odd// numbers in an arraypublic class GFG { // Function to segregate even // odd numbers static void arrayEvenAndOdd( int arr[], int n) { int i = -1, j = 0; while (j != n) { if (arr[j] % 2 == 0) { i++; // Swapping even and // odd numbers int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } j++; } // Printing segregated array for (int k = 0; k < n; k++) System.out.print(arr[k] + \" \"); } // Driver code public static void main(String args[]) { int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = arr.length; arrayEvenAndOdd(arr, n); }} // This code is contributed by Sam007",
"e": 7145,
"s": 6241,
"text": null
},
{
"code": "# Python3 code to segregate even odd# numbers in an array # Function to segregate even odd numbersdef arrayEvenAndOdd(arr,n): i = -1 j= 0 while (j!=n): if (arr[j] % 2 ==0): i = i+1 # Swapping even and odd numbers arr[i],arr[j] = arr[j],arr[i] j = j+1 # Printing segregated array for i in arr: print (str(i) + \" \" ,end='') # Driver Codeif __name__=='__main__': arr = [ 1 ,3, 2, 4, 7, 6, 9, 10] n = len(arr) arrayEvenAndOdd(arr,n) # This code was contributed by# Yatin Gupta",
"e": 7723,
"s": 7145,
"text": null
},
{
"code": "// C# code to segregate even odd// numbers in an arrayusing System; class GFG { // Function to segregate even // odd numbers static void arrayEvenAndOdd( int []arr, int n) { int i = -1, j = 0; while (j != n) { if (arr[j] % 2 == 0) { i++; // Swapping even and // odd numbers int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } j++; } // Printing segregated array for (int k = 0; k < n; k++) Console.Write(arr[k] + \" \"); } // Driver code static void Main() { int []arr = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = arr.Length; arrayEvenAndOdd(arr, n); }} // This code is contributed by Sam007",
"e": 8604,
"s": 7723,
"text": null
},
{
"code": "<?php// PHP code to segregate even odd// numbers in an array // Function to segregate// even odd numbersfunction arrayEvenAndOdd($arr, $n){ $i = -1; $j = 0; $t; while ($j != $n) { if ($arr[$j] % 2 == 0) { $i++; // Swapping even and // odd numbers $x = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $x; } $j++; } // Printing segregated // array for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \";} // Driver code $arr = array(1, 3, 2, 4, 7, 6, 9, 10); $n = sizeof($arr); arrayEvenAndOdd($arr, $n); // This code is contributed by Anuj_67?>",
"e": 9278,
"s": 8604,
"text": null
},
{
"code": "<script>// JavaScript code to segregate even odd// numbers in an array // Function to segregate even odd numbersfunction arrayEvenAndOdd(arr, n){ let i = -1, j = 0; let t; while (j != n) { if (arr[j] % 2 == 0) { i++; // Swapping even and odd numbers let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } j++; } // Printing segregated array for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Driver code let arr = [ 1, 3, 2, 4, 7, 6, 9, 10 ]; let n = arr.length; arrayEvenAndOdd(arr, n); // This code is contributed by Surbhi Tyagi </script>",
"e": 9955,
"s": 9278,
"text": null
},
{
"code": null,
"e": 9973,
"s": 9955,
"text": "2 4 6 10 7 1 9 3 "
},
{
"code": null,
"e": 10020,
"s": 9973,
"text": "Time Complexity : O(n) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 10027,
"s": 10020,
"text": "Sam007"
},
{
"code": null,
"e": 10032,
"s": 10027,
"text": "vt_m"
},
{
"code": null,
"e": 10043,
"s": 10032,
"text": "YatinGupta"
},
{
"code": null,
"e": 10058,
"s": 10043,
"text": "nichil942singh"
},
{
"code": null,
"e": 10072,
"s": 10058,
"text": "surbhityagi15"
},
{
"code": null,
"e": 10088,
"s": 10072,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 10102,
"s": 10088,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 10113,
"s": 10102,
"text": "tarakki100"
},
{
"code": null,
"e": 10129,
"s": 10113,
"text": "array-rearrange"
},
{
"code": null,
"e": 10140,
"s": 10129,
"text": "Quick Sort"
},
{
"code": null,
"e": 10147,
"s": 10140,
"text": "Arrays"
},
{
"code": null,
"e": 10155,
"s": 10147,
"text": "Sorting"
},
{
"code": null,
"e": 10162,
"s": 10155,
"text": "Arrays"
},
{
"code": null,
"e": 10170,
"s": 10162,
"text": "Sorting"
},
{
"code": null,
"e": 10268,
"s": 10170,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10283,
"s": 10268,
"text": "Arrays in Java"
},
{
"code": null,
"e": 10329,
"s": 10283,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 10397,
"s": 10329,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 10441,
"s": 10397,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 10473,
"s": 10441,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 10484,
"s": 10473,
"text": "Merge Sort"
},
{
"code": null,
"e": 10506,
"s": 10484,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 10516,
"s": 10506,
"text": "QuickSort"
},
{
"code": null,
"e": 10531,
"s": 10516,
"text": "Insertion Sort"
}
] |
Introduction to ElectronJS
|
10 Aug, 2021
If you are interested in using Web Development skills for developing apps for different desktop platforms like Windows, Linux or macOS, Electron is the perfect framework that suits your needs. Let’s start with a brief introduction to Electron.
ElectronJS: Electron was developed lately in 2013 by the open-source and version control giant, GitHub. Electron uses NodeJs in its core to serve pages built on HTML and CSS as a desktop app. This implies that developers comfortable in HTML5 or Android Development can easily switch their platform to Electron.
The Electron app may be categorized into two main processes, namely, Main and Renderer process.
Performing Culture: There are two process in the Electron performing Culture:
Main Process The main process is responsible for creating windows by using BrowserWindow instances. Individual BrowserWIndow instance renderes a webpage in its renderer process. Destroying a BrowserWindow instance implies that the corresponding renderer process is also terminated.
Renderer Process There is a single main process which is responsible for maintaining multiple renderer processes. Each renderer process manages the webpage and its scripts running inside it.
Electron supports various APIs for both the main and renderer processes, which helps to interact with the desktop operating system and its resources.
Prerequisites: The main prerequisites which may be considered important for starting on with Electron are listed below.
HTML and CSS for User Interface.
JavaScript as a main language.
Node.js and npm
Installing Electron: Let’s start with the building blocks of development with Electron.
Step 1: Make sure node and npm are installed.node -vnpm -v
node -v
npm -v
Step 2: Inside of your working folder run the below command from your code editors integrated terminal after that have a look at a basic package.json file, which is used by npm to define properties and import libraries.npm install electron --save-dev { "name": "electronapp", "version": "1.0.0", "description": "Electron application", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "Electron" ], "author": "xyz", "devDependencies": { "electron": "^7.1.7" }}
npm install electron --save-dev
{ "name": "electronapp", "version": "1.0.0", "description": "Electron application", "main": "main.js", "scripts": { "start": "electron ." }, "keywords": [ "Electron" ], "author": "xyz", "devDependencies": { "electron": "^7.1.7" }}
Step 3: Now, let’s see a basic main.js file which acts as the main process.const { app, BrowserWindow } = require('electron') let win function createWindow () { // Create the browser window. win = new BrowserWindow({ width: 800, height: 600, icon: ( './icon.png'), webPreferences: { nodeIntegration: true } }) // and load the index.html of the app. win.loadFile('./index.html') //win.loadURL('https://google.com/') // Open the DevTools. win.webContents.openDevTools() // Emitted when the window is closed. win.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. win = null })} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.on('ready', createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (win === null) { createWindow() }})
const { app, BrowserWindow } = require('electron') let win function createWindow () { // Create the browser window. win = new BrowserWindow({ width: 800, height: 600, icon: ( './icon.png'), webPreferences: { nodeIntegration: true } }) // and load the index.html of the app. win.loadFile('./index.html') //win.loadURL('https://google.com/') // Open the DevTools. win.webContents.openDevTools() // Emitted when the window is closed. win.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. win = null })} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.on('ready', createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (win === null) { createWindow() }})
Step 4: The main process is done, let’s see a basic HTML code which acts as a renderer process.<!DOCTYPE HTML><html> <head> <title>my first electron app</title> </head> <body> <h1>my first electron app</h1> </body> </html>
<!DOCTYPE HTML><html> <head> <title>my first electron app</title> </head> <body> <h1>my first electron app</h1> </body> </html>
Step 5: This ends our coding part. Now, runningnpm install --unsafe-perm=truewill download necessary node_modules, required by electron to render a page.
npm install --unsafe-perm=true
will download necessary node_modules, required by electron to render a page.
Step 6: After this, we will launch the app using npm run start, start being the script which we have defined in package.json.Output:
References: https://electronjs.org/docs/tutorial/first-app#installing-electron
ElectronJS
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How do you run JavaScript script through the Terminal?
Form validation using HTML and JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 272,
"s": 28,
"text": "If you are interested in using Web Development skills for developing apps for different desktop platforms like Windows, Linux or macOS, Electron is the perfect framework that suits your needs. Let’s start with a brief introduction to Electron."
},
{
"code": null,
"e": 583,
"s": 272,
"text": "ElectronJS: Electron was developed lately in 2013 by the open-source and version control giant, GitHub. Electron uses NodeJs in its core to serve pages built on HTML and CSS as a desktop app. This implies that developers comfortable in HTML5 or Android Development can easily switch their platform to Electron."
},
{
"code": null,
"e": 679,
"s": 583,
"text": "The Electron app may be categorized into two main processes, namely, Main and Renderer process."
},
{
"code": null,
"e": 757,
"s": 679,
"text": "Performing Culture: There are two process in the Electron performing Culture:"
},
{
"code": null,
"e": 1039,
"s": 757,
"text": "Main Process The main process is responsible for creating windows by using BrowserWindow instances. Individual BrowserWIndow instance renderes a webpage in its renderer process. Destroying a BrowserWindow instance implies that the corresponding renderer process is also terminated."
},
{
"code": null,
"e": 1230,
"s": 1039,
"text": "Renderer Process There is a single main process which is responsible for maintaining multiple renderer processes. Each renderer process manages the webpage and its scripts running inside it."
},
{
"code": null,
"e": 1380,
"s": 1230,
"text": "Electron supports various APIs for both the main and renderer processes, which helps to interact with the desktop operating system and its resources."
},
{
"code": null,
"e": 1500,
"s": 1380,
"text": "Prerequisites: The main prerequisites which may be considered important for starting on with Electron are listed below."
},
{
"code": null,
"e": 1533,
"s": 1500,
"text": "HTML and CSS for User Interface."
},
{
"code": null,
"e": 1564,
"s": 1533,
"text": "JavaScript as a main language."
},
{
"code": null,
"e": 1580,
"s": 1564,
"text": "Node.js and npm"
},
{
"code": null,
"e": 1668,
"s": 1580,
"text": "Installing Electron: Let’s start with the building blocks of development with Electron."
},
{
"code": null,
"e": 1727,
"s": 1668,
"text": "Step 1: Make sure node and npm are installed.node -vnpm -v"
},
{
"code": null,
"e": 1735,
"s": 1727,
"text": "node -v"
},
{
"code": null,
"e": 1742,
"s": 1735,
"text": "npm -v"
},
{
"code": null,
"e": 2244,
"s": 1742,
"text": "Step 2: Inside of your working folder run the below command from your code editors integrated terminal after that have a look at a basic package.json file, which is used by npm to define properties and import libraries.npm install electron --save-dev { \"name\": \"electronapp\", \"version\": \"1.0.0\", \"description\": \"Electron application\", \"main\": \"main.js\", \"scripts\": { \"start\": \"electron .\" }, \"keywords\": [ \"Electron\" ], \"author\": \"xyz\", \"devDependencies\": { \"electron\": \"^7.1.7\" }}"
},
{
"code": null,
"e": 2277,
"s": 2244,
"text": "npm install electron --save-dev "
},
{
"code": "{ \"name\": \"electronapp\", \"version\": \"1.0.0\", \"description\": \"Electron application\", \"main\": \"main.js\", \"scripts\": { \"start\": \"electron .\" }, \"keywords\": [ \"Electron\" ], \"author\": \"xyz\", \"devDependencies\": { \"electron\": \"^7.1.7\" }}",
"e": 2528,
"s": 2277,
"text": null
},
{
"code": null,
"e": 3968,
"s": 2528,
"text": "Step 3: Now, let’s see a basic main.js file which acts as the main process.const { app, BrowserWindow } = require('electron') let win function createWindow () { // Create the browser window. win = new BrowserWindow({ width: 800, height: 600, icon: ( './icon.png'), webPreferences: { nodeIntegration: true } }) // and load the index.html of the app. win.loadFile('./index.html') //win.loadURL('https://google.com/') // Open the DevTools. win.webContents.openDevTools() // Emitted when the window is closed. win.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. win = null })} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.on('ready', createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (win === null) { createWindow() }})"
},
{
"code": "const { app, BrowserWindow } = require('electron') let win function createWindow () { // Create the browser window. win = new BrowserWindow({ width: 800, height: 600, icon: ( './icon.png'), webPreferences: { nodeIntegration: true } }) // and load the index.html of the app. win.loadFile('./index.html') //win.loadURL('https://google.com/') // Open the DevTools. win.webContents.openDevTools() // Emitted when the window is closed. win.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. win = null })} // This method will be called when Electron has finished// initialization and is ready to create browser windows.// Some APIs can only be used after this event occurs.app.on('ready', createWindow) // Quit when all windows are closed.app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() }}) app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (win === null) { createWindow() }})",
"e": 5333,
"s": 3968,
"text": null
},
{
"code": null,
"e": 5583,
"s": 5333,
"text": "Step 4: The main process is done, let’s see a basic HTML code which acts as a renderer process.<!DOCTYPE HTML><html> <head> <title>my first electron app</title> </head> <body> <h1>my first electron app</h1> </body> </html>"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title>my first electron app</title> </head> <body> <h1>my first electron app</h1> </body> </html>",
"e": 5738,
"s": 5583,
"text": null
},
{
"code": null,
"e": 5892,
"s": 5738,
"text": "Step 5: This ends our coding part. Now, runningnpm install --unsafe-perm=truewill download necessary node_modules, required by electron to render a page."
},
{
"code": "npm install --unsafe-perm=true",
"e": 5923,
"s": 5892,
"text": null
},
{
"code": null,
"e": 6000,
"s": 5923,
"text": "will download necessary node_modules, required by electron to render a page."
},
{
"code": null,
"e": 6133,
"s": 6000,
"text": "Step 6: After this, we will launch the app using npm run start, start being the script which we have defined in package.json.Output:"
},
{
"code": null,
"e": 6212,
"s": 6133,
"text": "References: https://electronjs.org/docs/tutorial/first-app#installing-electron"
},
{
"code": null,
"e": 6223,
"s": 6212,
"text": "ElectronJS"
},
{
"code": null,
"e": 6234,
"s": 6223,
"text": "JavaScript"
},
{
"code": null,
"e": 6253,
"s": 6234,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6270,
"s": 6253,
"text": "Web Technologies"
},
{
"code": null,
"e": 6368,
"s": 6270,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6429,
"s": 6368,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6501,
"s": 6429,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 6541,
"s": 6501,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 6596,
"s": 6541,
"text": "How do you run JavaScript script through the Terminal?"
},
{
"code": null,
"e": 6638,
"s": 6596,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 6688,
"s": 6638,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 6721,
"s": 6688,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 6783,
"s": 6721,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 6843,
"s": 6783,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)
|
02 Jun, 2022
We have discussed below data structures in the previous two sets. Set 1: Overview of Array, Linked List, Queue and Stack. Set 2: Overview of Binary Tree, BST, Heap and Hash. 9. Graph 10. Trie 11. Segment Tree 12. Suffix Tree
Graph: Graph is a data structure that consists of the following two components:
A finite set of vertices is also called nodes.A finite set of ordered pairs of the form (u, v) is called an edge. The pair is ordered because (u, v) is not the same as (v, u) in the case of a directed graph(di-graph). The pair of forms (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain weight/value/cost.
A finite set of vertices is also called nodes.
A finite set of ordered pairs of the form (u, v) is called an edge. The pair is ordered because (u, v) is not the same as (v, u) in the case of a directed graph(di-graph). The pair of forms (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain weight/value/cost.
V -> Number of Vertices. E -> Number of Edges. The graph can be classified on the basis of many things, below are the two most common classifications :
Direction: Undirected Graph: The graph in which all the edges are bidirectional.Directed Graph: The graph in which all the edges are unidirectional.Weight: Weighted Graph: The Graph in which weight is associated with the edges.Unweighted Graph: The Graph in which there is no weight associated with the edges.
Direction: Undirected Graph: The graph in which all the edges are bidirectional.Directed Graph: The graph in which all the edges are unidirectional.
Weight: Weighted Graph: The Graph in which weight is associated with the edges.Unweighted Graph: The Graph in which there is no weight associated with the edges.
Graphs can be represented in many ways, below are the two most common representations: Let us take the below example graph to see two representations of the graph.
Adjacency Matrix Representation of the above graph
Adjacency List Representation of the above Graph
Time Complexities in case of Adjacency Matrix :
Traversal :(By BFS or DFS) O(V^2)
Space : O(V^2)
Time Complexities in case of Adjacency List :
Traversal :(By BFS or DFS) O(V + E)
Space : O(V+E)
Examples: The most common example of the graph is to find the shortest path in any network. Used in google maps or bing. Another common use application of graphs is social networking websites where the friend suggestion depends on the number of intermediate suggestions and other things.
Trie
Trie is an efficient data structure for searching words in dictionaries, search complexity with Trie is linear in terms of word (or key) length to be searched. If we store keys in a binary search tree, a well-balanced BST will need time proportional to M * log N, where M is the maximum string length and N is the number of keys in the tree. Using trie, we can search the key in O(M) time. So it is much faster than BST. Hashing also provides word search in O(n) time on average. But the advantages of Trie are there are no collisions (like hashing) so the worst-case time complexity is O(n). Also, the most important thing is Prefix Search. With Trie, we can find all words beginning with a prefix (This is not possible with Hashing). The only problem with Tries is they require a lot of extra space. Tries are also known as radix trees or prefix trees.
The Trie structure can be defined as follows :
struct trie_node
{
int value; /* Used to mark leaf nodes */
trie_node_t *children[ALPHABET_SIZE];
};
root
/ \ \
t a b
| | |
h n y
| | \ |
e s y e
/ | |
i r w
| | |
r e e
|
r
The leaf nodes are in blue.
Insert time : O(M) where M is the length of the string.
Search time : O(M) where M is the length of the string.
Space : O(ALPHABET_SIZE * M * N) where N is number of
keys in trie, ALPHABET_SIZE is 26 if we are
only considering upper case Latin characters.
Deletion time: O(M)
Example: The most common use of Tries is to implement dictionaries due to prefix search capability. Tries are also well suited for implementing approximate matching algorithms, including those used in spell checking. It is also used for searching Contact from Mobile Contact list OR Phone Directory.
Segment Tree
This data structure is usually implemented when there are a lot of queries on a set of values. These queries involve minimum, maximum, sum, .. etc on an input range of a given set. Queries also involve updating values in the given set. Segment Trees are implemented using an array.
Construction of segment tree : O(N)
Query : O(log N)
Update : O(log N)
Space : O(N) [Exact space = 2*N-1]
Example: It is used when we need to find the Maximum/Minimum/Sum/Product of numbers in a range.
Suffix Tree
The suffix tree is mainly used to search for a pattern in a text. The idea is to preprocess the text so that the search operation can be done in time linear in terms of pattern length. The pattern searching algorithms like KMP, Z, etc take time proportional to text length. This is really a great improvement because the length of the pattern is generally much smaller than the text. Imagine we have stored the complete work of William Shakespeare and preprocessed it. You can search any string in the complete work in time just proportional to the length of the pattern. But using Suffix Tree may not be a good idea when text changes frequently like text editor, etc. A suffix tree is a compressed trie of all suffixes, so the following are very abstract steps to build a suffix tree from given text. 1) Generate all suffixes of the given text. 2) Consider all suffixes as individual words and build a compressed trie.
Example: Used to find all occurrences of the pattern in a string. It is also used to find the longest repeated substring (when the text doesn’t change often), the longest common substring and the longest palindrome in a string. This article is contributed by Abhiraj Smit. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
HenrySpivey
I_drink_and_i_know_things_
PreetamKalal
anikakapoor
sweetyty
vardaan
chaladiyogitha
Segment-Tree
Suffix-Tree
Trie
Advanced Data Structure
Segment-Tree
Trie
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jun, 2022"
},
{
"code": null,
"e": 277,
"s": 52,
"text": "We have discussed below data structures in the previous two sets. Set 1: Overview of Array, Linked List, Queue and Stack. Set 2: Overview of Binary Tree, BST, Heap and Hash. 9. Graph 10. Trie 11. Segment Tree 12. Suffix Tree"
},
{
"code": null,
"e": 357,
"s": 277,
"text": "Graph: Graph is a data structure that consists of the following two components:"
},
{
"code": null,
"e": 700,
"s": 357,
"text": "A finite set of vertices is also called nodes.A finite set of ordered pairs of the form (u, v) is called an edge. The pair is ordered because (u, v) is not the same as (v, u) in the case of a directed graph(di-graph). The pair of forms (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain weight/value/cost."
},
{
"code": null,
"e": 747,
"s": 700,
"text": "A finite set of vertices is also called nodes."
},
{
"code": null,
"e": 1044,
"s": 747,
"text": "A finite set of ordered pairs of the form (u, v) is called an edge. The pair is ordered because (u, v) is not the same as (v, u) in the case of a directed graph(di-graph). The pair of forms (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain weight/value/cost."
},
{
"code": null,
"e": 1196,
"s": 1044,
"text": "V -> Number of Vertices. E -> Number of Edges. The graph can be classified on the basis of many things, below are the two most common classifications :"
},
{
"code": null,
"e": 1506,
"s": 1196,
"text": "Direction: Undirected Graph: The graph in which all the edges are bidirectional.Directed Graph: The graph in which all the edges are unidirectional.Weight: Weighted Graph: The Graph in which weight is associated with the edges.Unweighted Graph: The Graph in which there is no weight associated with the edges."
},
{
"code": null,
"e": 1655,
"s": 1506,
"text": "Direction: Undirected Graph: The graph in which all the edges are bidirectional.Directed Graph: The graph in which all the edges are unidirectional."
},
{
"code": null,
"e": 1817,
"s": 1655,
"text": "Weight: Weighted Graph: The Graph in which weight is associated with the edges.Unweighted Graph: The Graph in which there is no weight associated with the edges."
},
{
"code": null,
"e": 1981,
"s": 1817,
"text": "Graphs can be represented in many ways, below are the two most common representations: Let us take the below example graph to see two representations of the graph."
},
{
"code": null,
"e": 2034,
"s": 1983,
"text": "Adjacency Matrix Representation of the above graph"
},
{
"code": null,
"e": 2083,
"s": 2034,
"text": "Adjacency List Representation of the above Graph"
},
{
"code": null,
"e": 2278,
"s": 2083,
"text": "Time Complexities in case of Adjacency Matrix :\nTraversal :(By BFS or DFS) O(V^2)\nSpace : O(V^2)\n\nTime Complexities in case of Adjacency List :\nTraversal :(By BFS or DFS) O(V + E)\nSpace : O(V+E)"
},
{
"code": null,
"e": 2566,
"s": 2278,
"text": "Examples: The most common example of the graph is to find the shortest path in any network. Used in google maps or bing. Another common use application of graphs is social networking websites where the friend suggestion depends on the number of intermediate suggestions and other things."
},
{
"code": null,
"e": 2571,
"s": 2566,
"text": "Trie"
},
{
"code": null,
"e": 3426,
"s": 2571,
"text": "Trie is an efficient data structure for searching words in dictionaries, search complexity with Trie is linear in terms of word (or key) length to be searched. If we store keys in a binary search tree, a well-balanced BST will need time proportional to M * log N, where M is the maximum string length and N is the number of keys in the tree. Using trie, we can search the key in O(M) time. So it is much faster than BST. Hashing also provides word search in O(n) time on average. But the advantages of Trie are there are no collisions (like hashing) so the worst-case time complexity is O(n). Also, the most important thing is Prefix Search. With Trie, we can find all words beginning with a prefix (This is not possible with Hashing). The only problem with Tries is they require a lot of extra space. Tries are also known as radix trees or prefix trees."
},
{
"code": null,
"e": 4283,
"s": 3426,
"text": "The Trie structure can be defined as follows :\nstruct trie_node\n{\n int value; /* Used to mark leaf nodes */\n trie_node_t *children[ALPHABET_SIZE];\n};\n\n\n root\n / \\ \\\n t a b\n | | |\n h n y\n | | \\ |\n e s y e\n / | |\n i r w\n | | |\n r e e\n |\n r\n\nThe leaf nodes are in blue.\n\nInsert time : O(M) where M is the length of the string.\nSearch time : O(M) where M is the length of the string.\nSpace : O(ALPHABET_SIZE * M * N) where N is number of \n keys in trie, ALPHABET_SIZE is 26 if we are \n only considering upper case Latin characters.\nDeletion time: O(M)"
},
{
"code": null,
"e": 4583,
"s": 4283,
"text": "Example: The most common use of Tries is to implement dictionaries due to prefix search capability. Tries are also well suited for implementing approximate matching algorithms, including those used in spell checking. It is also used for searching Contact from Mobile Contact list OR Phone Directory."
},
{
"code": null,
"e": 4596,
"s": 4583,
"text": "Segment Tree"
},
{
"code": null,
"e": 4879,
"s": 4596,
"text": "This data structure is usually implemented when there are a lot of queries on a set of values. These queries involve minimum, maximum, sum, .. etc on an input range of a given set. Queries also involve updating values in the given set. Segment Trees are implemented using an array. "
},
{
"code": null,
"e": 4985,
"s": 4879,
"text": "Construction of segment tree : O(N)\nQuery : O(log N)\nUpdate : O(log N)\nSpace : O(N) [Exact space = 2*N-1]"
},
{
"code": null,
"e": 5081,
"s": 4985,
"text": "Example: It is used when we need to find the Maximum/Minimum/Sum/Product of numbers in a range."
},
{
"code": null,
"e": 5093,
"s": 5081,
"text": "Suffix Tree"
},
{
"code": null,
"e": 6013,
"s": 5093,
"text": "The suffix tree is mainly used to search for a pattern in a text. The idea is to preprocess the text so that the search operation can be done in time linear in terms of pattern length. The pattern searching algorithms like KMP, Z, etc take time proportional to text length. This is really a great improvement because the length of the pattern is generally much smaller than the text. Imagine we have stored the complete work of William Shakespeare and preprocessed it. You can search any string in the complete work in time just proportional to the length of the pattern. But using Suffix Tree may not be a good idea when text changes frequently like text editor, etc. A suffix tree is a compressed trie of all suffixes, so the following are very abstract steps to build a suffix tree from given text. 1) Generate all suffixes of the given text. 2) Consider all suffixes as individual words and build a compressed trie."
},
{
"code": null,
"e": 6417,
"s": 6016,
"text": "Example: Used to find all occurrences of the pattern in a string. It is also used to find the longest repeated substring (when the text doesn’t change often), the longest common substring and the longest palindrome in a string. This article is contributed by Abhiraj Smit. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6429,
"s": 6417,
"text": "HenrySpivey"
},
{
"code": null,
"e": 6456,
"s": 6429,
"text": "I_drink_and_i_know_things_"
},
{
"code": null,
"e": 6469,
"s": 6456,
"text": "PreetamKalal"
},
{
"code": null,
"e": 6481,
"s": 6469,
"text": "anikakapoor"
},
{
"code": null,
"e": 6490,
"s": 6481,
"text": "sweetyty"
},
{
"code": null,
"e": 6498,
"s": 6490,
"text": "vardaan"
},
{
"code": null,
"e": 6513,
"s": 6498,
"text": "chaladiyogitha"
},
{
"code": null,
"e": 6526,
"s": 6513,
"text": "Segment-Tree"
},
{
"code": null,
"e": 6538,
"s": 6526,
"text": "Suffix-Tree"
},
{
"code": null,
"e": 6543,
"s": 6538,
"text": "Trie"
},
{
"code": null,
"e": 6567,
"s": 6543,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 6580,
"s": 6567,
"text": "Segment-Tree"
},
{
"code": null,
"e": 6585,
"s": 6580,
"text": "Trie"
}
] |
Disk Partitioning in Ubuntu using GParted
|
10 Sep, 2021
Disk Partitioning is a process of separating disks into one (or) more logical areas so that user and system work on them independently. When a partition is created, the disk will store the information about the location and size of partitions in the partition table. With the partition table, each partition can appear on the operating system as a logical disk, and users can read and write data on those disks. Learn more about Disk Partitioning in Linux
Disk Partitioning in Linux is done using command line programs like fdisk. GParted(GNOME Partition Editor) is a Graphical user program based on GTK which allows Disk Partitioning with just a click of the buttons. GParted is the official GNOME partition-editing application. GParted is used for creating, deleting, resizing, moving, checking, and copying disk partitions and manipulating file systems such as exfat, fat32/64, ext2/3/4, Linux-swap and more.
You can install GParted in Ubuntu with a single command using APT
sudo apt install gparted
You can verify whether GParted is successfully installed or not using the below command which gives an output similar to below image
sudo apt policy gparted
GParted is successfully installed
Note: It’s recommended to backup your data in the partition before using GParted
To open GParted , go to Activities in Ubuntu and click on the gparted icon. It will prompt for password as GParted requires sudo privileges.
GParted menu
The above image shows the GParted menu, like many programs, it has a file menu(GParted), edit menu, view menu, device & partition menu, and help menu. The icons below the menu bar represent the common operations performed by gparted
new – create a new partition
delete – delete an existing partition
resize/move – to resize a partition, either shrink(or)increase the size
copy/paste – used to copy/paste the text(or) information
undo – undo the previous action
apply – to perform the operation chosen from above, you have to click the apply icon to commit any selected operation in gparted
GParted
You can see all the partitions on my hard disk. It has a total of 7 partitions from /dev/sda[1-4] being used for Microsoft Windows and /dev/sda[5-7] being used by my Linux Distro. The lock icon between partition and name shows that these partitions can’t be modified while running. The partitions can be modified by using a Live CD (or) using another OS which doesn’t use these partitions.
GParted clearly shows us
Partition – the logical partition id in the partition table
Name – name of the partition
File System – type of the file system used by the partition which are like ntfs, fat32, ext4, linux-swap and more.
Mount point – the point where the partition is being mounted by the OS which is similar to root(/), home(/home)
Size(Used/Unused) – the size of the partition and used and free space in the partition
Flags – It tells what the partition is being used for, which are like hidden partition, swap partition, windows partition
Step 1: We will shrink /dev/sda4 by 10GB to create a new ext4 partition. Go on to /dev/sda4 and right-click on it and it opens an option menu like below.
Options Menu
The menu has options for
create/delete partitions
resize and move partitions
format partitions
name partitions and add flags
Changing UUID and more
Partition properties: To show more information about a partition click on the information option in the menu shown in the above picture
Step 2: Click on Resize/Move. It will open new windows to select the size to resize partitions. As we have taken the new partition size as 10GB, add 10000(GB converted into MiB) Free Space following option. Now click on Resize/Move
resize options
Step 3: Now click “apply icon” in GParted menu( it will in the top with icons representing actions), It will ask for confirmation
confirmation warning
After clicking on apply, the partition will be resized.
gparted will start rezising options
Step 4: If the resize is successful you will see a success message like below.
resize successful
You will see an unallocated space in the GPartered list
unallocated space
Click on the unallocated space and select new in GParted menu where we have selected in the apply icon. Select the options like size, name as file system and then click add
New partition option
Now click on the apply icon like before to apply the changes, and accept the warning
apply operations
If the operations are successful, you will see the message like before.
operations successful
We have successfully created a new /dev/sda8 partition using GParted
NEW Partition
You can choose the format of the file system when creating a new partition, if you choose to format an existing partition, select the partition you want to format and right-click on it to open the partition menu. Then go to the format option and click on the type of filesystem you want. After selecting, apply the changes just by clicking on the apply icon in the top menu.
formating a partition
Deleting a partition is simple. Select the partition you want to delete and click the delete icon on the top menu and then click apply icon. Deleting a partition will erase all the data in that partition, so be careful while using it.
gabaa406
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
Introduction to Linux Operating System
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 484,
"s": 28,
"text": "Disk Partitioning is a process of separating disks into one (or) more logical areas so that user and system work on them independently. When a partition is created, the disk will store the information about the location and size of partitions in the partition table. With the partition table, each partition can appear on the operating system as a logical disk, and users can read and write data on those disks. Learn more about Disk Partitioning in Linux"
},
{
"code": null,
"e": 940,
"s": 484,
"text": "Disk Partitioning in Linux is done using command line programs like fdisk. GParted(GNOME Partition Editor) is a Graphical user program based on GTK which allows Disk Partitioning with just a click of the buttons. GParted is the official GNOME partition-editing application. GParted is used for creating, deleting, resizing, moving, checking, and copying disk partitions and manipulating file systems such as exfat, fat32/64, ext2/3/4, Linux-swap and more."
},
{
"code": null,
"e": 1006,
"s": 940,
"text": "You can install GParted in Ubuntu with a single command using APT"
},
{
"code": null,
"e": 1031,
"s": 1006,
"text": "sudo apt install gparted"
},
{
"code": null,
"e": 1164,
"s": 1031,
"text": "You can verify whether GParted is successfully installed or not using the below command which gives an output similar to below image"
},
{
"code": null,
"e": 1188,
"s": 1164,
"text": "sudo apt policy gparted"
},
{
"code": null,
"e": 1222,
"s": 1188,
"text": "GParted is successfully installed"
},
{
"code": null,
"e": 1304,
"s": 1222,
"text": " Note: It’s recommended to backup your data in the partition before using GParted"
},
{
"code": null,
"e": 1446,
"s": 1304,
"text": "To open GParted , go to Activities in Ubuntu and click on the gparted icon. It will prompt for password as GParted requires sudo privileges. "
},
{
"code": null,
"e": 1459,
"s": 1446,
"text": "GParted menu"
},
{
"code": null,
"e": 1692,
"s": 1459,
"text": "The above image shows the GParted menu, like many programs, it has a file menu(GParted), edit menu, view menu, device & partition menu, and help menu. The icons below the menu bar represent the common operations performed by gparted"
},
{
"code": null,
"e": 1722,
"s": 1692,
"text": "new – create a new partition"
},
{
"code": null,
"e": 1760,
"s": 1722,
"text": "delete – delete an existing partition"
},
{
"code": null,
"e": 1832,
"s": 1760,
"text": "resize/move – to resize a partition, either shrink(or)increase the size"
},
{
"code": null,
"e": 1889,
"s": 1832,
"text": "copy/paste – used to copy/paste the text(or) information"
},
{
"code": null,
"e": 1921,
"s": 1889,
"text": "undo – undo the previous action"
},
{
"code": null,
"e": 2050,
"s": 1921,
"text": "apply – to perform the operation chosen from above, you have to click the apply icon to commit any selected operation in gparted"
},
{
"code": null,
"e": 2058,
"s": 2050,
"text": "GParted"
},
{
"code": null,
"e": 2448,
"s": 2058,
"text": "You can see all the partitions on my hard disk. It has a total of 7 partitions from /dev/sda[1-4] being used for Microsoft Windows and /dev/sda[5-7] being used by my Linux Distro. The lock icon between partition and name shows that these partitions can’t be modified while running. The partitions can be modified by using a Live CD (or) using another OS which doesn’t use these partitions."
},
{
"code": null,
"e": 2474,
"s": 2448,
"text": " GParted clearly shows us"
},
{
"code": null,
"e": 2534,
"s": 2474,
"text": "Partition – the logical partition id in the partition table"
},
{
"code": null,
"e": 2563,
"s": 2534,
"text": "Name – name of the partition"
},
{
"code": null,
"e": 2678,
"s": 2563,
"text": "File System – type of the file system used by the partition which are like ntfs, fat32, ext4, linux-swap and more."
},
{
"code": null,
"e": 2790,
"s": 2678,
"text": "Mount point – the point where the partition is being mounted by the OS which is similar to root(/), home(/home)"
},
{
"code": null,
"e": 2877,
"s": 2790,
"text": "Size(Used/Unused) – the size of the partition and used and free space in the partition"
},
{
"code": null,
"e": 2999,
"s": 2877,
"text": "Flags – It tells what the partition is being used for, which are like hidden partition, swap partition, windows partition"
},
{
"code": null,
"e": 3153,
"s": 2999,
"text": "Step 1: We will shrink /dev/sda4 by 10GB to create a new ext4 partition. Go on to /dev/sda4 and right-click on it and it opens an option menu like below."
},
{
"code": null,
"e": 3166,
"s": 3153,
"text": "Options Menu"
},
{
"code": null,
"e": 3191,
"s": 3166,
"text": "The menu has options for"
},
{
"code": null,
"e": 3216,
"s": 3191,
"text": "create/delete partitions"
},
{
"code": null,
"e": 3243,
"s": 3216,
"text": "resize and move partitions"
},
{
"code": null,
"e": 3261,
"s": 3243,
"text": "format partitions"
},
{
"code": null,
"e": 3291,
"s": 3261,
"text": "name partitions and add flags"
},
{
"code": null,
"e": 3314,
"s": 3291,
"text": "Changing UUID and more"
},
{
"code": null,
"e": 3450,
"s": 3314,
"text": "Partition properties: To show more information about a partition click on the information option in the menu shown in the above picture"
},
{
"code": null,
"e": 3682,
"s": 3450,
"text": "Step 2: Click on Resize/Move. It will open new windows to select the size to resize partitions. As we have taken the new partition size as 10GB, add 10000(GB converted into MiB) Free Space following option. Now click on Resize/Move"
},
{
"code": null,
"e": 3697,
"s": 3682,
"text": "resize options"
},
{
"code": null,
"e": 3827,
"s": 3697,
"text": "Step 3: Now click “apply icon” in GParted menu( it will in the top with icons representing actions), It will ask for confirmation"
},
{
"code": null,
"e": 3848,
"s": 3827,
"text": "confirmation warning"
},
{
"code": null,
"e": 3904,
"s": 3848,
"text": "After clicking on apply, the partition will be resized."
},
{
"code": null,
"e": 3940,
"s": 3904,
"text": "gparted will start rezising options"
},
{
"code": null,
"e": 4019,
"s": 3940,
"text": "Step 4: If the resize is successful you will see a success message like below."
},
{
"code": null,
"e": 4037,
"s": 4019,
"text": "resize successful"
},
{
"code": null,
"e": 4093,
"s": 4037,
"text": "You will see an unallocated space in the GPartered list"
},
{
"code": null,
"e": 4111,
"s": 4093,
"text": "unallocated space"
},
{
"code": null,
"e": 4284,
"s": 4111,
"text": "Click on the unallocated space and select new in GParted menu where we have selected in the apply icon. Select the options like size, name as file system and then click add"
},
{
"code": null,
"e": 4305,
"s": 4284,
"text": "New partition option"
},
{
"code": null,
"e": 4390,
"s": 4305,
"text": "Now click on the apply icon like before to apply the changes, and accept the warning"
},
{
"code": null,
"e": 4407,
"s": 4390,
"text": "apply operations"
},
{
"code": null,
"e": 4479,
"s": 4407,
"text": "If the operations are successful, you will see the message like before."
},
{
"code": null,
"e": 4501,
"s": 4479,
"text": "operations successful"
},
{
"code": null,
"e": 4570,
"s": 4501,
"text": "We have successfully created a new /dev/sda8 partition using GParted"
},
{
"code": null,
"e": 4584,
"s": 4570,
"text": "NEW Partition"
},
{
"code": null,
"e": 4959,
"s": 4584,
"text": "You can choose the format of the file system when creating a new partition, if you choose to format an existing partition, select the partition you want to format and right-click on it to open the partition menu. Then go to the format option and click on the type of filesystem you want. After selecting, apply the changes just by clicking on the apply icon in the top menu."
},
{
"code": null,
"e": 4981,
"s": 4959,
"text": "formating a partition"
},
{
"code": null,
"e": 5216,
"s": 4981,
"text": "Deleting a partition is simple. Select the partition you want to delete and click the delete icon on the top menu and then click apply icon. Deleting a partition will erase all the data in that partition, so be careful while using it."
},
{
"code": null,
"e": 5225,
"s": 5216,
"text": "gabaa406"
},
{
"code": null,
"e": 5237,
"s": 5225,
"text": "Linux-Tools"
},
{
"code": null,
"e": 5248,
"s": 5237,
"text": "Linux-Unix"
},
{
"code": null,
"e": 5346,
"s": 5248,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5372,
"s": 5346,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 5407,
"s": 5372,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 5444,
"s": 5407,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 5473,
"s": 5444,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 5510,
"s": 5473,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 5547,
"s": 5510,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 5581,
"s": 5547,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 5621,
"s": 5581,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 5660,
"s": 5621,
"text": "Introduction to Linux Operating System"
}
] |
Spring Batch - Basic Application
|
This chapter shows you the basic Spring Batch application. It will simply execute a tasklet to displays a message.
Our Spring Batch application contains the following files −
Configuration file − This is an XML file where we define the Job and the steps of the job. (If the application involves readers and writers too, then the configuration of readers and writers is also included in this file.)
Configuration file − This is an XML file where we define the Job and the steps of the job. (If the application involves readers and writers too, then the configuration of readers and writers is also included in this file.)
Context.xml − In this file, we will define the beans like job repository, job launcher and transaction manager.
Context.xml − In this file, we will define the beans like job repository, job launcher and transaction manager.
Tasklet class − In this class, we will write the processing code job (In this case, it displays a simple message)
Tasklet class − In this class, we will write the processing code job (In this case, it displays a simple message)
Launcher class − in this class, we will launch the Batch Application by running the Job launcher.
Launcher class − in this class, we will launch the Batch Application by running the Job launcher.
Following is the configuration file of our sample Spring Batch application.
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:batch = "http://www.springframework.org/schema/batch"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd ">
<import resource="context.xml" />
<!-- Defining a bean -->
<bean id = "tasklet" class = "a_sample.MyTasklet" />
<!-- Defining a job-->
<batch:job id = "helloWorldJob">
<!-- Defining a Step -->
<batch:step id = "step1">
<tasklet ref = "tasklet"/>
</batch:step>
</batch:job>
</beans>
Following is the context.xml of our Spring Batch application.
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<bean id = "jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name = "transactionManager" ref = "transactionManager" />
</bean>
<bean id = "transactionManager"
class = "org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
<bean id = "jobLauncher"
class = "org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name = "jobRepository" ref = "jobRepository" />
</bean>
</beans>
Following is the Tasklet class which displays a simple message.
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
public class MyTasklet implements Tasklet {
@Override
public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception {
System.out.println("Hello This is a sample example of spring batch");
return RepeatStatus.FINISHED;
}
}
Following is the code which launces the batch process.
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args)throws Exception {
// System.out.println("hello");
String[] springConfig = {"a_sample/job_hello_world.xml"};
// Creating the application context object
ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);
// Creating the job launcher
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
// Creating the job
Job job = (Job) context.getBean("helloWorldJob");
// Executing the JOB
JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
}
}
On executing, the above SpringBatch program will produce the following output −
Apr 24, 2017 4:40:54 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO:Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2ef1e4fa: startup date [Mon Apr 24 16:40:54 IST 2017]; root of context hierarchy
Apr 24, 2017 4:40:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions
Apr 24, 2017 4:40:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions
Apr 24, 2017 4:40:54 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
Apr 24, 2017 4:40:55 PM org.springframework.batch.core.launch.support.SimpleJobLauncher afterPropertiesSet
INFO: No TaskExecutor has been set, defaulting to synchronous executor.
Apr 24, 2017 4:40:55 PM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run
INFO: Job: [FlowJob: [name=helloWorldJob]] launched with the following parameters: [{}]
Apr 24, 2017 4:40:55 PM org.springframework.batch.core.job.SimpleStepHandler handleStep INFO: Executing step: [step1]
Hello This is a sample example of spring batch
Apr 24, 2017 4:40:55 PM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run
INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
Exit Status : COMPLETED
|
[
{
"code": null,
"e": 2177,
"s": 2062,
"text": "This chapter shows you the basic Spring Batch application. It will simply execute a tasklet to displays a message."
},
{
"code": null,
"e": 2237,
"s": 2177,
"text": "Our Spring Batch application contains the following files −"
},
{
"code": null,
"e": 2460,
"s": 2237,
"text": "Configuration file − This is an XML file where we define the Job and the steps of the job. (If the application involves readers and writers too, then the configuration of readers and writers is also included in this file.)"
},
{
"code": null,
"e": 2683,
"s": 2460,
"text": "Configuration file − This is an XML file where we define the Job and the steps of the job. (If the application involves readers and writers too, then the configuration of readers and writers is also included in this file.)"
},
{
"code": null,
"e": 2795,
"s": 2683,
"text": "Context.xml − In this file, we will define the beans like job repository, job launcher and transaction manager."
},
{
"code": null,
"e": 2907,
"s": 2795,
"text": "Context.xml − In this file, we will define the beans like job repository, job launcher and transaction manager."
},
{
"code": null,
"e": 3021,
"s": 2907,
"text": "Tasklet class − In this class, we will write the processing code job (In this case, it displays a simple message)"
},
{
"code": null,
"e": 3135,
"s": 3021,
"text": "Tasklet class − In this class, we will write the processing code job (In this case, it displays a simple message)"
},
{
"code": null,
"e": 3233,
"s": 3135,
"text": "Launcher class − in this class, we will launch the Batch Application by running the Job launcher."
},
{
"code": null,
"e": 3331,
"s": 3233,
"text": "Launcher class − in this class, we will launch the Batch Application by running the Job launcher."
},
{
"code": null,
"e": 3407,
"s": 3331,
"text": "Following is the configuration file of our sample Spring Batch application."
},
{
"code": null,
"e": 4210,
"s": 3407,
"text": "<beans xmlns = \"http://www.springframework.org/schema/beans\" \n xmlns:batch = \"http://www.springframework.org/schema/batch\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/batch \n http://www.springframework.org/schema/batch/spring-batch-2.2.xsd\n http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.2.xsd \"> \n <import resource=\"context.xml\" /> \n <!-- Defining a bean --> \n <bean id = \"tasklet\" class = \"a_sample.MyTasklet\" /> \n <!-- Defining a job--> \n <batch:job id = \"helloWorldJob\"> \n <!-- Defining a Step --> \n <batch:step id = \"step1\"> \n <tasklet ref = \"tasklet\"/> \n </batch:step> \n </batch:job> \n</beans> "
},
{
"code": null,
"e": 4272,
"s": 4210,
"text": "Following is the context.xml of our Spring Batch application."
},
{
"code": null,
"e": 5098,
"s": 4272,
"text": "<beans xmlns = \"http://www.springframework.org/schema/beans\" \n xmlns:xsi = http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.2.xsd\"> \n \n <bean id = \"jobRepository\" \n class=\"org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean\"> \n <property name = \"transactionManager\" ref = \"transactionManager\" /> \n </bean> \n \n <bean id = \"transactionManager\" \n class = \"org.springframework.batch.support.transaction.ResourcelessTransactionManager\" /> \n <bean id = \"jobLauncher\" \n class = \"org.springframework.batch.core.launch.support.SimpleJobLauncher\"> \n <property name = \"jobRepository\" ref = \"jobRepository\" /> \n </bean> \n</beans> "
},
{
"code": null,
"e": 5162,
"s": 5098,
"text": "Following is the Tasklet class which displays a simple message."
},
{
"code": null,
"e": 5682,
"s": 5162,
"text": "import org.springframework.batch.core.StepContribution; \nimport org.springframework.batch.core.scope.context.ChunkContext;\nimport org.springframework.batch.core.step.tasklet.Tasklet;\nimport org.springframework.batch.repeat.RepeatStatus; \n\npublic class MyTasklet implements Tasklet { \n \n @Override \n public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception { \n System.out.println(\"Hello This is a sample example of spring batch\"); \n return RepeatStatus.FINISHED; \n } \n} "
},
{
"code": null,
"e": 5737,
"s": 5682,
"text": "Following is the code which launces the batch process."
},
{
"code": null,
"e": 6809,
"s": 5737,
"text": "import org.springframework.batch.core.Job; \nimport org.springframework.batch.core.JobExecution; \nimport org.springframework.batch.core.JobParameters; \nimport org.springframework.batch.core.launch.JobLauncher; \nimport org.springframework.context.ApplicationContext; \nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class App { \n public static void main(String[] args)throws Exception { \n \n // System.out.println(\"hello\"); \n String[] springConfig = {\"a_sample/job_hello_world.xml\"}; \n \n // Creating the application context object \n ApplicationContext context = new ClassPathXmlApplicationContext(springConfig); \n \n // Creating the job launcher \n JobLauncher jobLauncher = (JobLauncher) context.getBean(\"jobLauncher\"); \n \n // Creating the job \n Job job = (Job) context.getBean(\"helloWorldJob\"); \n \n // Executing the JOB \n JobExecution execution = jobLauncher.run(job, new JobParameters()); \n System.out.println(\"Exit Status : \" + execution.getStatus()); \n } \n}"
},
{
"code": null,
"e": 6889,
"s": 6809,
"text": "On executing, the above SpringBatch program will produce the following output −"
}
] |
Check whether two points (x1, y1) and (x2, y2) lie on same side of a given line or not
|
19 Mar, 2021
Given three integers a, b and c which represents coefficients of the equation of a line a * x + b * y – c = 0. Given two integer points (x1, y1) and (x2, y2). The task is to determine whether the points (x1, y1) and (x2, y2) lie on the same side of the given line or not.Examples:
Input : a = 1, b = 1, c = 1, x1 = 1, y1 = 1, x2 = 1, y2 = 2 Output : yes On applying (x1, y1) and (x2, y2) on a * x + b * y – c, gives 1 and 2 respectively both of which have the same sign, hence both the points lie on same side of the line. Input : a = 1, b = 1, c = 1, x1 = 1, y1 = 1, x2 = 0, y2 = 0 Output : no
Approach : Apply both the points on given line equation and check if the obtained values belong to same parity or not.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if two points// lie on the same side or not#include <bits/stdc++.h>using namespace std; // Function to check if two points// lie on the same side or notbool pointsAreOnSameSideOfLine(int a, int b, int c, int x1, int y1, int x2, int y2){ int fx1; // Variable to store a * x1 + b * y1 - c int fx2; // Variable to store a * x2 + b * y2 - c fx1 = a * x1 + b * y1 - c; fx2 = a * x2 + b * y2 - c; // If fx1 and fx2 have same sign if ((fx1 * fx2) > 0) return true; return false;} // Driver codeint main(){ int a = 1, b = 1, c = 1; int x1 = 1, y1 = 1; int x2 = 2, y2 = 1; if (pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2)) cout << "Yes"; else cout << "No";}
// Java program to check if two points// lie on the same side or notimport java.util.*; class GFG{ // Function to check if two points// lie on the same side or notstatic boolean pointsAreOnSameSideOfLine(int a, int b, int c, int x1, int y1, int x2, int y2){ int fx1; // Variable to store a * x1 + b * y1 - c int fx2; // Variable to store a * x2 + b * y2 - c fx1 = a * x1 + b * y1 - c; fx2 = a * x2 + b * y2 - c; // If fx1 and fx2 have same sign if ((fx1 * fx2) > 0) return true; return false;} // Driver codepublic static void main(String[] args){ int a = 1, b = 1, c = 1; int x1 = 1, y1 = 1; int x2 = 2, y2 = 1; if (pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by 29AjayKumar
# Python3 program to check if two points# lie on the same side or not # Function to check if two points# lie on the same side or notdef pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2): fx1 = 0 # Variable to store a * x1 + b * y1 - c fx2 = 0 # Variable to store a * x2 + b * y2 - c fx1 = a * x1 + b * y1 - c fx2 = a * x2 + b * y2 - c # If fx1 and fx2 have same sign if ((fx1 * fx2) > 0): return True return False # Driver codea, b, c = 1, 1, 1x1, y1 = 1, 1x2, y2 = 2, 1 if (pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2)): print("Yes")else: print("No") # This code is contributed by Mohit Kumar
// C# program to check if two points// lie on the same side or notusing System;class GFG{ // Function to check if two points// lie on the same side or notstatic bool pointsAreOnSameSideOfLine(int a, int b, int c, int x1, int y1, int x2, int y2){ int fx1; // Variable to store a * x1 + b * y1 - c int fx2; // Variable to store a * x2 + b * y2 - c fx1 = a * x1 + b * y1 - c; fx2 = a * x2 + b * y2 - c; // If fx1 and fx2 have same sign if ((fx1 * fx2) > 0) return true; return false;} // Driver codepublic static void Main(){ int a = 1, b = 1, c = 1; int x1 = 1, y1 = 1; int x2 = 2, y2 = 1; if (pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by Code_Mech
<script> // Javascript program to check if two points // lie on the same side or not // Function to check if two points // lie on the same side or not function pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2) { let fx1; // Variable to store a * x1 + b * y1 - c let fx2; // Variable to store a * x2 + b * y2 - c fx1 = a * x1 + b * y1 - c; fx2 = a * x2 + b * y2 - c; // If fx1 and fx2 have same sign if ((fx1 * fx2) > 0) return true; return false; } let a = 1, b = 1, c = 1; let x1 = 1, y1 = 1; let x2 = 2, y2 = 1; if (pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2)) document.write("Yes"); else document.write("No"); // This code is contributed by divyesh072019.</script>
Yes
mohit kumar 29
29AjayKumar
Code_Mech
divyesh072019
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Optimum location of point to minimize total distance
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Check whether a given point lies inside a triangle or not
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": 53,
"s": 25,
"text": "\n19 Mar, 2021"
},
{
"code": null,
"e": 336,
"s": 53,
"text": "Given three integers a, b and c which represents coefficients of the equation of a line a * x + b * y – c = 0. Given two integer points (x1, y1) and (x2, y2). The task is to determine whether the points (x1, y1) and (x2, y2) lie on the same side of the given line or not.Examples: "
},
{
"code": null,
"e": 652,
"s": 336,
"text": "Input : a = 1, b = 1, c = 1, x1 = 1, y1 = 1, x2 = 1, y2 = 2 Output : yes On applying (x1, y1) and (x2, y2) on a * x + b * y – c, gives 1 and 2 respectively both of which have the same sign, hence both the points lie on same side of the line. Input : a = 1, b = 1, c = 1, x1 = 1, y1 = 1, x2 = 0, y2 = 0 Output : no "
},
{
"code": null,
"e": 825,
"s": 654,
"text": "Approach : Apply both the points on given line equation and check if the obtained values belong to same parity or not.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 829,
"s": 825,
"text": "C++"
},
{
"code": null,
"e": 834,
"s": 829,
"text": "Java"
},
{
"code": null,
"e": 842,
"s": 834,
"text": "Python3"
},
{
"code": null,
"e": 845,
"s": 842,
"text": "C#"
},
{
"code": null,
"e": 856,
"s": 845,
"text": "Javascript"
},
{
"code": "// C++ program to check if two points// lie on the same side or not#include <bits/stdc++.h>using namespace std; // Function to check if two points// lie on the same side or notbool pointsAreOnSameSideOfLine(int a, int b, int c, int x1, int y1, int x2, int y2){ int fx1; // Variable to store a * x1 + b * y1 - c int fx2; // Variable to store a * x2 + b * y2 - c fx1 = a * x1 + b * y1 - c; fx2 = a * x2 + b * y2 - c; // If fx1 and fx2 have same sign if ((fx1 * fx2) > 0) return true; return false;} // Driver codeint main(){ int a = 1, b = 1, c = 1; int x1 = 1, y1 = 1; int x2 = 2, y2 = 1; if (pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2)) cout << \"Yes\"; else cout << \"No\";}",
"e": 1622,
"s": 856,
"text": null
},
{
"code": "// Java program to check if two points// lie on the same side or notimport java.util.*; class GFG{ // Function to check if two points// lie on the same side or notstatic boolean pointsAreOnSameSideOfLine(int a, int b, int c, int x1, int y1, int x2, int y2){ int fx1; // Variable to store a * x1 + b * y1 - c int fx2; // Variable to store a * x2 + b * y2 - c fx1 = a * x1 + b * y1 - c; fx2 = a * x2 + b * y2 - c; // If fx1 and fx2 have same sign if ((fx1 * fx2) > 0) return true; return false;} // Driver codepublic static void main(String[] args){ int a = 1, b = 1, c = 1; int x1 = 1, y1 = 1; int x2 = 2, y2 = 1; if (pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by 29AjayKumar",
"e": 2575,
"s": 1622,
"text": null
},
{
"code": "# Python3 program to check if two points# lie on the same side or not # Function to check if two points# lie on the same side or notdef pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2): fx1 = 0 # Variable to store a * x1 + b * y1 - c fx2 = 0 # Variable to store a * x2 + b * y2 - c fx1 = a * x1 + b * y1 - c fx2 = a * x2 + b * y2 - c # If fx1 and fx2 have same sign if ((fx1 * fx2) > 0): return True return False # Driver codea, b, c = 1, 1, 1x1, y1 = 1, 1x2, y2 = 2, 1 if (pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2)): print(\"Yes\")else: print(\"No\") # This code is contributed by Mohit Kumar",
"e": 3242,
"s": 2575,
"text": null
},
{
"code": "// C# program to check if two points// lie on the same side or notusing System;class GFG{ // Function to check if two points// lie on the same side or notstatic bool pointsAreOnSameSideOfLine(int a, int b, int c, int x1, int y1, int x2, int y2){ int fx1; // Variable to store a * x1 + b * y1 - c int fx2; // Variable to store a * x2 + b * y2 - c fx1 = a * x1 + b * y1 - c; fx2 = a * x2 + b * y2 - c; // If fx1 and fx2 have same sign if ((fx1 * fx2) > 0) return true; return false;} // Driver codepublic static void Main(){ int a = 1, b = 1, c = 1; int x1 = 1, y1 = 1; int x2 = 2, y2 = 1; if (pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by Code_Mech",
"e": 4157,
"s": 3242,
"text": null
},
{
"code": "<script> // Javascript program to check if two points // lie on the same side or not // Function to check if two points // lie on the same side or not function pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2) { let fx1; // Variable to store a * x1 + b * y1 - c let fx2; // Variable to store a * x2 + b * y2 - c fx1 = a * x1 + b * y1 - c; fx2 = a * x2 + b * y2 - c; // If fx1 and fx2 have same sign if ((fx1 * fx2) > 0) return true; return false; } let a = 1, b = 1, c = 1; let x1 = 1, y1 = 1; let x2 = 2, y2 = 1; if (pointsAreOnSameSideOfLine(a, b, c, x1, y1, x2, y2)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by divyesh072019.</script>",
"e": 4961,
"s": 4157,
"text": null
},
{
"code": null,
"e": 4965,
"s": 4961,
"text": "Yes"
},
{
"code": null,
"e": 4982,
"s": 4967,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 4994,
"s": 4982,
"text": "29AjayKumar"
},
{
"code": null,
"e": 5004,
"s": 4994,
"text": "Code_Mech"
},
{
"code": null,
"e": 5018,
"s": 5004,
"text": "divyesh072019"
},
{
"code": null,
"e": 5028,
"s": 5018,
"text": "Geometric"
},
{
"code": null,
"e": 5041,
"s": 5028,
"text": "Mathematical"
},
{
"code": null,
"e": 5054,
"s": 5041,
"text": "Mathematical"
},
{
"code": null,
"e": 5064,
"s": 5054,
"text": "Geometric"
},
{
"code": null,
"e": 5162,
"s": 5064,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5211,
"s": 5162,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 5264,
"s": 5211,
"text": "Optimum location of point to minimize total distance"
},
{
"code": null,
"e": 5317,
"s": 5264,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 5368,
"s": 5317,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 5426,
"s": 5368,
"text": "Check whether a given point lies inside a triangle or not"
},
{
"code": null,
"e": 5456,
"s": 5426,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 5499,
"s": 5456,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5559,
"s": 5499,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 5574,
"s": 5559,
"text": "C++ Data Types"
}
] |
How to draw stacked bars in ggplot2 that show percentages in R ?
|
05 Nov, 2021
In this article, we are going to see how to draw stacked bars in ggplot2 that show percentages in R programming language.
The plyr package in R is used to split the data apart, perform operations with it, and then subsequently bring it back together again. It is used to perform data manipulation. This package can be downloaded and installed into the working space using the following command :
install.packages("plyr")
The ddply method in R is used to combine the results into a single data frame after the application of a function on each of the subsets of the data frame.
Syntax: ddply(.data, .variables, .fun = NULL)
Arguments :
data: The data frame to be used
variables: variables to split data frame by
fun: the function to be applied on the data frame
The function to be applied here can be the transform function, which can be used to append or remove or mutate columns in the data frame. It can be used to add more columns in the dataframe. The percentage column can be added to the data frame by calculating the fraction of each component in the dataframe.
The percentage column can then be used to append labels using “%” sign. The column is constructed using the paste0() method which is used to concatenate strings by combining the percentage with the corresponding “%” sign.
paste0(str1, str2)
The ggplot2 package is used for data visualization and depicting the plots. This package can be downloaded and installed into the working space using the following command :
install.packages("ggplot2")
The ggplot method in this package is used to construct various kinds of plots, like scatter plots, boxplots, etc. The plots take as input the data frame to be used and also supply aesthetic mappings using the x and y coordinates. Other arguments can be added by using the color specified by the grouping column.
Syntax: ggplot (data, mapping = aes(x= , y= , fill = ))
Arguments :
data: The data frame to be used
mapping: aesthetic mapping supplied by aes() method
The geom_bar() method in this package is used to make the height of the bar proportional to the number of cases in each group. It has the following syntax :
Syntax: geom_bar(position , stat = “identity” )
Arguments :
position: Position adjustment
The geom_text method can be used to add text to the stacked bars and stack them on top of one another. The label is assigned as the percentage label string computed. The label can be assigned using the label argument and its corresponding position. It can be further customized using the size parameter.
Syntax: geom_text(mapping = NULL, position , size)
Arguments :
mapping: Aesthetic mappings
position: The position adjustment to use for overlapping points on this layer
size: the size of the text added
Example:
R
# importing the required librarylibrary(plyr)library(ggplot2) # creating the data framedata_frame < - data.frame(stringsAsFactors=FALSE, col1=c(rep(5: 7, each=4)), col2=c(rep(1: 4, each=3)), col3=c(1: 12))# printing the data frameprint("original dataframe")print(data_frame) # adding thedata_frame = ddply(data_frame, .(col2), transform, percentage=col1/sum(col1) * 100) # adding the percentage labeldata_frame$prcntlabel = paste0(sprintf("%.0f", data_frame$percentage), "%") # printing the modified data frameprint("converted dataframe")print(data_frame) # adding graph of plotting dataggplot(data_frame, aes(x=factor(col2), y=col3, fill=col1)) +geom_bar(position=position_stack(), stat="identity") +geom_text(aes(label=prcntlabel), position=position_stack(vjust=0.5), size=2) +coord_flip()
Output
[1] "original dataframe"
col1 col2 col3
1 5 1 1
2 5 1 2
3 5 1 3
4 5 2 4
5 6 2 5
6 6 2 6
7 6 3 7
8 6 3 8
9 7 3 9
10 7 4 10
11 7 4 11
12 7 4 12
[1] "converted dataframe"
col1 col2 col3 percentage prcntlabel
1 5 1 1 33.33333 33%
2 5 1 2 33.33333 33%
3 5 1 3 33.33333 33%
4 5 2 4 29.41176 29%
5 6 2 5 35.29412 35%
6 6 2 6 35.29412 35%
7 6 3 7 31.57895 32%
8 6 3 8 31.57895 32%
9 7 3 9 36.84211 37%
10 7 4 10 33.33333 33%
11 7 4 11 33.33333 33%
12 7 4 12 33.33333 33%
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 150,
"s": 28,
"text": "In this article, we are going to see how to draw stacked bars in ggplot2 that show percentages in R programming language."
},
{
"code": null,
"e": 425,
"s": 150,
"text": "The plyr package in R is used to split the data apart, perform operations with it, and then subsequently bring it back together again. It is used to perform data manipulation. This package can be downloaded and installed into the working space using the following command : "
},
{
"code": null,
"e": 450,
"s": 425,
"text": "install.packages(\"plyr\")"
},
{
"code": null,
"e": 607,
"s": 450,
"text": "The ddply method in R is used to combine the results into a single data frame after the application of a function on each of the subsets of the data frame. "
},
{
"code": null,
"e": 654,
"s": 607,
"text": "Syntax: ddply(.data, .variables, .fun = NULL)"
},
{
"code": null,
"e": 667,
"s": 654,
"text": "Arguments : "
},
{
"code": null,
"e": 699,
"s": 667,
"text": "data: The data frame to be used"
},
{
"code": null,
"e": 743,
"s": 699,
"text": "variables: variables to split data frame by"
},
{
"code": null,
"e": 793,
"s": 743,
"text": "fun: the function to be applied on the data frame"
},
{
"code": null,
"e": 1102,
"s": 793,
"text": "The function to be applied here can be the transform function, which can be used to append or remove or mutate columns in the data frame. It can be used to add more columns in the dataframe. The percentage column can be added to the data frame by calculating the fraction of each component in the dataframe. "
},
{
"code": null,
"e": 1325,
"s": 1102,
"text": "The percentage column can then be used to append labels using “%” sign. The column is constructed using the paste0() method which is used to concatenate strings by combining the percentage with the corresponding “%” sign. "
},
{
"code": null,
"e": 1344,
"s": 1325,
"text": "paste0(str1, str2)"
},
{
"code": null,
"e": 1518,
"s": 1344,
"text": "The ggplot2 package is used for data visualization and depicting the plots. This package can be downloaded and installed into the working space using the following command :"
},
{
"code": null,
"e": 1546,
"s": 1518,
"text": "install.packages(\"ggplot2\")"
},
{
"code": null,
"e": 1859,
"s": 1546,
"text": "The ggplot method in this package is used to construct various kinds of plots, like scatter plots, boxplots, etc. The plots take as input the data frame to be used and also supply aesthetic mappings using the x and y coordinates. Other arguments can be added by using the color specified by the grouping column. "
},
{
"code": null,
"e": 1915,
"s": 1859,
"text": "Syntax: ggplot (data, mapping = aes(x= , y= , fill = ))"
},
{
"code": null,
"e": 1928,
"s": 1915,
"text": "Arguments : "
},
{
"code": null,
"e": 1960,
"s": 1928,
"text": "data: The data frame to be used"
},
{
"code": null,
"e": 2012,
"s": 1960,
"text": "mapping: aesthetic mapping supplied by aes() method"
},
{
"code": null,
"e": 2170,
"s": 2012,
"text": "The geom_bar() method in this package is used to make the height of the bar proportional to the number of cases in each group. It has the following syntax : "
},
{
"code": null,
"e": 2218,
"s": 2170,
"text": "Syntax: geom_bar(position , stat = “identity” )"
},
{
"code": null,
"e": 2231,
"s": 2218,
"text": "Arguments : "
},
{
"code": null,
"e": 2261,
"s": 2231,
"text": "position: Position adjustment"
},
{
"code": null,
"e": 2566,
"s": 2261,
"text": "The geom_text method can be used to add text to the stacked bars and stack them on top of one another. The label is assigned as the percentage label string computed. The label can be assigned using the label argument and its corresponding position. It can be further customized using the size parameter. "
},
{
"code": null,
"e": 2617,
"s": 2566,
"text": "Syntax: geom_text(mapping = NULL, position , size)"
},
{
"code": null,
"e": 2630,
"s": 2617,
"text": "Arguments : "
},
{
"code": null,
"e": 2658,
"s": 2630,
"text": "mapping: Aesthetic mappings"
},
{
"code": null,
"e": 2736,
"s": 2658,
"text": "position: The position adjustment to use for overlapping points on this layer"
},
{
"code": null,
"e": 2769,
"s": 2736,
"text": "size: the size of the text added"
},
{
"code": null,
"e": 2778,
"s": 2769,
"text": "Example:"
},
{
"code": null,
"e": 2780,
"s": 2778,
"text": "R"
},
{
"code": "# importing the required librarylibrary(plyr)library(ggplot2) # creating the data framedata_frame < - data.frame(stringsAsFactors=FALSE, col1=c(rep(5: 7, each=4)), col2=c(rep(1: 4, each=3)), col3=c(1: 12))# printing the data frameprint(\"original dataframe\")print(data_frame) # adding thedata_frame = ddply(data_frame, .(col2), transform, percentage=col1/sum(col1) * 100) # adding the percentage labeldata_frame$prcntlabel = paste0(sprintf(\"%.0f\", data_frame$percentage), \"%\") # printing the modified data frameprint(\"converted dataframe\")print(data_frame) # adding graph of plotting dataggplot(data_frame, aes(x=factor(col2), y=col3, fill=col1)) +geom_bar(position=position_stack(), stat=\"identity\") +geom_text(aes(label=prcntlabel), position=position_stack(vjust=0.5), size=2) +coord_flip()",
"e": 3738,
"s": 2780,
"text": null
},
{
"code": null,
"e": 3745,
"s": 3738,
"text": "Output"
},
{
"code": null,
"e": 4550,
"s": 3745,
"text": "[1] \"original dataframe\"\n col1 col2 col3\n1 5 1 1\n2 5 1 2\n3 5 1 3\n4 5 2 4\n5 6 2 5\n6 6 2 6\n7 6 3 7\n8 6 3 8\n9 7 3 9\n10 7 4 10\n11 7 4 11\n12 7 4 12\n[1] \"converted dataframe\"\n col1 col2 col3 percentage prcntlabel\n1 5 1 1 33.33333 33%\n2 5 1 2 33.33333 33%\n3 5 1 3 33.33333 33%\n4 5 2 4 29.41176 29%\n5 6 2 5 35.29412 35%\n6 6 2 6 35.29412 35%\n7 6 3 7 31.57895 32%\n8 6 3 8 31.57895 32%\n9 7 3 9 36.84211 37%\n10 7 4 10 33.33333 33%\n11 7 4 11 33.33333 33%\n12 7 4 12 33.33333 33%"
},
{
"code": null,
"e": 4557,
"s": 4550,
"text": "Picked"
},
{
"code": null,
"e": 4566,
"s": 4557,
"text": "R-ggplot"
},
{
"code": null,
"e": 4577,
"s": 4566,
"text": "R Language"
}
] |
How to replace dropdown-toggle icon with another default icon in Bootstrap ?
|
23 Feb, 2022
Bootstrap provides the option of adding a dropdown to our websites. The default icon on the dropdown button is the ‘downward solid arrow’ logo. Even though it serves its purpose, most of the modern-day websites nowadays use Bootstrap. Therefore, the icon might look very generic to the visitor.Program:
html
<!DOCTYPE html><html> <head> <title>Bootstrap dorpdown</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .container{ margin:20px; } h2{ color:green; } </style></head> <body> <div class="container"> <h2>GeeksforGeeks</h2> <p>A Computer Science Portal for Geeks</p> <div class="dropdown"> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> Dropdown </button> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Option A</a> <a class="dropdown-item" href="#">Option B</a> <a class="dropdown-item" href="#">Option C</a> <a class="dropdown-item" href="#">Option D</a> </div> </div> </div></body> </html>
Output:
However, it is possible to change the default Bootstrap icon to the icon of your choice. You can also make that icon toggleable, below steps will proceed to the solution.
Step 1: Go to an external icon website like Font Awesome. Embed its CDN link inside the <head> tag of the web-page.
<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”>
Step 2: Change the CSS of the dropdown-toggle to display:none. This will disappear the solid dropdown logo from the button. However, ‘!important’ must be added as well in order to see the changes on the webpage.
.dropdown-toggle::after {
display: none !important;
}
Step 3: After applying the CSS, copy the embed code of the icon that you want to display on the webpage from the external icon website and paste it inside the button tag. Like in this example, we are using the icon of ‘plus’ sign.
Step 4: The new icon will start getting displayed on the webpage.
Note: Below program code’s dropdown icon is also toggleable by adding a single line of jQuery code with one click function on the icon.Program: This example changing the default icon of Bootstrap dropdown icon.
html
<!DOCTYPE html><html> <head> <title>Bootstrap dorpdown</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .container{ margin:20px; } h2{ color:green; } .dropdown-toggle::after { display: none !important; } .fa { margin:2px; color:white; } </style></head><body> <div class="container"> <h2>GeeksforGeeks</h2> <p>A Computer Science Portal for Geeks</p> <div class="dropdown"> <!-- Dropdown button --> <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"> Dropdown <a href="javascript:void(0);" class="icon" onclick="geeksforgeeks()"> <!-- Changing the default icon with toggle--> <i onclick="myFunction(this)" class="fa fa-plus-circle"></i> </a> </button> <!-- Dropdown options --> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Option A</a> <a class="dropdown-item" href="#">Option B</a> <a class="dropdown-item" href="#">Option C</a> <a class="dropdown-item" href="#">Option D</a> </div> </div> </div> <script> // Function to toggle the plus menu into minus function myFunction(x) { x.classList.toggle("fa-minus-circle"); } </script></body> </html>
Output:
varshagumber28
sumitgumber28
Bootstrap-Misc
Picked
Bootstrap
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to change Bootstrap datepicker with specific date format ?
Tailwind CSS vs Bootstrap
Create a Homepage for Restaurant using HTML , CSS and Bootstrap
How to make Bootstrap table with sticky table head?
How to insert spaces/tabs in text using HTML/CSS?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 333,
"s": 28,
"text": "Bootstrap provides the option of adding a dropdown to our websites. The default icon on the dropdown button is the ‘downward solid arrow’ logo. Even though it serves its purpose, most of the modern-day websites nowadays use Bootstrap. Therefore, the icon might look very generic to the visitor.Program: "
},
{
"code": null,
"e": 338,
"s": 333,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bootstrap dorpdown</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .container{ margin:20px; } h2{ color:green; } </style></head> <body> <div class=\"container\"> <h2>GeeksforGeeks</h2> <p>A Computer Science Portal for Geeks</p> <div class=\"dropdown\"> <button type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\"> Dropdown </button> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Option A</a> <a class=\"dropdown-item\" href=\"#\">Option B</a> <a class=\"dropdown-item\" href=\"#\">Option C</a> <a class=\"dropdown-item\" href=\"#\">Option D</a> </div> </div> </div></body> </html>",
"e": 1688,
"s": 338,
"text": null
},
{
"code": null,
"e": 1698,
"s": 1688,
"text": "Output: "
},
{
"code": null,
"e": 1871,
"s": 1698,
"text": "However, it is possible to change the default Bootstrap icon to the icon of your choice. You can also make that icon toggleable, below steps will proceed to the solution. "
},
{
"code": null,
"e": 1989,
"s": 1871,
"text": "Step 1: Go to an external icon website like Font Awesome. Embed its CDN link inside the <head> tag of the web-page. "
},
{
"code": null,
"e": 2103,
"s": 1989,
"text": "<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”>"
},
{
"code": null,
"e": 2319,
"s": 2105,
"text": "Step 2: Change the CSS of the dropdown-toggle to display:none. This will disappear the solid dropdown logo from the button. However, ‘!important’ must be added as well in order to see the changes on the webpage. "
},
{
"code": null,
"e": 2377,
"s": 2319,
"text": ".dropdown-toggle::after {\n display: none !important;\n}"
},
{
"code": null,
"e": 2608,
"s": 2377,
"text": "Step 3: After applying the CSS, copy the embed code of the icon that you want to display on the webpage from the external icon website and paste it inside the button tag. Like in this example, we are using the icon of ‘plus’ sign."
},
{
"code": null,
"e": 2674,
"s": 2608,
"text": "Step 4: The new icon will start getting displayed on the webpage."
},
{
"code": null,
"e": 2887,
"s": 2674,
"text": "Note: Below program code’s dropdown icon is also toggleable by adding a single line of jQuery code with one click function on the icon.Program: This example changing the default icon of Bootstrap dropdown icon. "
},
{
"code": null,
"e": 2892,
"s": 2887,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Bootstrap dorpdown</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .container{ margin:20px; } h2{ color:green; } .dropdown-toggle::after { display: none !important; } .fa { margin:2px; color:white; } </style></head><body> <div class=\"container\"> <h2>GeeksforGeeks</h2> <p>A Computer Science Portal for Geeks</p> <div class=\"dropdown\"> <!-- Dropdown button --> <button type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\"> Dropdown <a href=\"javascript:void(0);\" class=\"icon\" onclick=\"geeksforgeeks()\"> <!-- Changing the default icon with toggle--> <i onclick=\"myFunction(this)\" class=\"fa fa-plus-circle\"></i> </a> </button> <!-- Dropdown options --> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Option A</a> <a class=\"dropdown-item\" href=\"#\">Option B</a> <a class=\"dropdown-item\" href=\"#\">Option C</a> <a class=\"dropdown-item\" href=\"#\">Option D</a> </div> </div> </div> <script> // Function to toggle the plus menu into minus function myFunction(x) { x.classList.toggle(\"fa-minus-circle\"); } </script></body> </html>",
"e": 5129,
"s": 2892,
"text": null
},
{
"code": null,
"e": 5139,
"s": 5129,
"text": "Output: "
},
{
"code": null,
"e": 5156,
"s": 5141,
"text": "varshagumber28"
},
{
"code": null,
"e": 5170,
"s": 5156,
"text": "sumitgumber28"
},
{
"code": null,
"e": 5185,
"s": 5170,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 5192,
"s": 5185,
"text": "Picked"
},
{
"code": null,
"e": 5202,
"s": 5192,
"text": "Bootstrap"
},
{
"code": null,
"e": 5221,
"s": 5202,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5238,
"s": 5221,
"text": "Web Technologies"
},
{
"code": null,
"e": 5265,
"s": 5238,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 5363,
"s": 5265,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5404,
"s": 5363,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 5467,
"s": 5404,
"text": "How to change Bootstrap datepicker with specific date format ?"
},
{
"code": null,
"e": 5493,
"s": 5467,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 5557,
"s": 5493,
"text": "Create a Homepage for Restaurant using HTML , CSS and Bootstrap"
},
{
"code": null,
"e": 5609,
"s": 5557,
"text": "How to make Bootstrap table with sticky table head?"
},
{
"code": null,
"e": 5659,
"s": 5609,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5692,
"s": 5659,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5754,
"s": 5692,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5787,
"s": 5754,
"text": "Node.js fs.readFileSync() Method"
}
] |
Quick Start to Gaussian Process Regression | by Hilarie Sit | Towards Data Science
|
Gaussian process regression (GPR) is a nonparametric, Bayesian approach to regression that is making waves in the area of machine learning. GPR has several benefits, working well on small datasets and having the ability to provide uncertainty measurements on the predictions.
Unlike many popular supervised machine learning algorithms that learn exact values for every parameter in a function, the Bayesian approach infers a probability distribution over all possible values. Let’s assume a linear function: y=wx+ε. How the Bayesian approach works is by specifying a prior distribution, p(w), on the parameter, w, and relocating probabilities based on evidence (i.e. observed data) using Bayes’ Rule:
The updated distribution p(w|y, X), called the posterior distribution, thus incorporates information from both the prior distribution and the dataset. To get predictions at unseen points of interest, x*, the predictive distribution can be calculated by weighting all possible predictions by their calculated posterior distribution [1]:
The prior and likelihood is usually assumed to be Gaussian for the integration to be tractable. Using that assumption and solving for the predictive distribution, we get a Gaussian distribution, from which we can obtain a point prediction using its mean and an uncertainty quantification using its variance.
Gaussian process regression is nonparametric (i.e. not limited by a functional form), so rather than calculating the probability distribution of parameters of a specific function, GPR calculates the probability distribution over all admissible functions that fit the data. However, similar to the above, we specify a prior (on the function space), calculate the posterior using the training data, and compute the predictive posterior distribution on our points of interest.
There are several libraries for efficient implementation of Gaussian process regression (e.g. scikit-learn, Gpytorch, GPy), but for simplicity, this guide will use scikit-learn’s Gaussian process package [2].
import sklearn.gaussian_process as gp
In GPR, we first assume a Gaussian process prior, which can be specified using a mean function, m(x), and covariance function, k(x, x’):
More specifically, a Gaussian process is like an infinite-dimensional multivariate Gaussian distribution, where any collection of the labels of the dataset are joint Gaussian distributed. Within this GP prior, we can incorporate prior knowledge about the space of functions through the selection of the mean and covariance functions. We can also easily incorporate independently, identically distributed (i.i.d) Gaussian noise, ε ∼ N(0, σ2), to the labels by summing the label distribution and noise distribution.
The dataset consists of observations, X, and their labels, y, split into “training” and “testing” subsets:
# X_tr <-- training observations [# points, # features]# y_tr <-- training labels [# points]# X_te <-- test observations [# points, # features]# y_te <-- test labels [# points]
From the Gaussian process prior, the collection of training points and test points are joint multivariate Gaussian distributed, and so we can write their distribution in this way [1]:
Here, K is the covariance kernel matrix where its entries correspond to the covariance function evaluated at observations. Written in this way, we can take the training subset to perform model selection.
The form of the mean function and covariance kernel function in the GP prior is chosen and tuned during model selection. The mean function is typically constant, either zero or the mean of the training dataset. There are many options for the covariance kernel function: it can have many forms as long as it follows the properties of a kernel (i.e. semi-positive definite and symmetric). Some common kernel functions include constant, linear, square exponential and Matern kernel, as well as a composition of multiple kernels.
A popular kernel is the composition of the constant kernel with the radial basis function (RBF) kernel, which encodes for smoothness of functions (i.e. similarity of inputs in space corresponds to the similarity of outputs):
This kernel has two hyperparameters: signal variance, σ2, and lengthscale, l. In scikit-learn, we can chose from a variety of kernels and specify the initial value and bounds on their hyperparameters.
kernel = gp.kernels.ConstantKernel(1.0, (1e-1, 1e3)) * gp.kernels.RBF(10.0, (1e-3, 1e3))
After specifying the kernel function, we can now specify other choices for the GP model in scikit-learn. For example, alpha is the variance of the i.i.d. noise on the labels, and normalize_y refers to the constant mean function — either zero if False or the training data mean if True.
model = gp.GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=10, alpha=0.1, normalize_y=True)
A popular approach to tune the hyperparameters of the covariance kernel function is to maximize the log marginal likelihood of the training data. A gradient-based optimizer is typically used for efficiency; if unspecified above, the default optimizer is ‘fmin_l_bfgs_b’. Because the log marginal likelihood is not necessarily convex, multiple restarts of the optimizer with different initializations is used (n_restarts_optimizer).
model.fit(X_tr, y_tr)params = model.kernel_.get_params()
The tuned hyperparameters of the kernel function can be obtained, if desired, by calling model.kernel_.get_params().
To calculate the predictive posterior distribution, the data and the test observation is conditioned out of the posterior distribution. Again, because we chose a Gaussian process prior, calculating the predictive distribution is tractable, and leads to normal distribution that can be completely described by the mean and covariance [1]:
The predictions are the means f_bar*, and variances can be obtained from the diagonal of the covariance matrix Σ*. Notice that calculation of the mean and variance requires the inversion of the K matrix, which scales with the number of training points cubed. Inference is simple to implement with sci-kit learn’s GPR predict function.
y_pred, std = model.predict(X_te, return_std=True)
Note that the standard deviation is returned, but the whole covariance matrix can be returned if return_cov=True. The 95% confidence interval can then be calculated: 1.96 times the standard deviation for a Gaussian.
To measure the performance of the regression model on the test observations, we can calculate the mean squared error (MSE) on the predictions.
MSE = ((y_pred-y_te)**2).mean()
References:
[1] Rasmussen, C. E., & Williams, C. K. I., Gaussian processes for machine learning (2016), The MIT Press
[2] Pedregosa, F., Varoquaux, G., Gramfort, A., Michel, V., Thirion, B., Grisel, O., et. al., Scikit-learn: Machine learning in python (2011), Journal of Machine Learning Research
|
[
{
"code": null,
"e": 448,
"s": 172,
"text": "Gaussian process regression (GPR) is a nonparametric, Bayesian approach to regression that is making waves in the area of machine learning. GPR has several benefits, working well on small datasets and having the ability to provide uncertainty measurements on the predictions."
},
{
"code": null,
"e": 873,
"s": 448,
"text": "Unlike many popular supervised machine learning algorithms that learn exact values for every parameter in a function, the Bayesian approach infers a probability distribution over all possible values. Let’s assume a linear function: y=wx+ε. How the Bayesian approach works is by specifying a prior distribution, p(w), on the parameter, w, and relocating probabilities based on evidence (i.e. observed data) using Bayes’ Rule:"
},
{
"code": null,
"e": 1209,
"s": 873,
"text": "The updated distribution p(w|y, X), called the posterior distribution, thus incorporates information from both the prior distribution and the dataset. To get predictions at unseen points of interest, x*, the predictive distribution can be calculated by weighting all possible predictions by their calculated posterior distribution [1]:"
},
{
"code": null,
"e": 1517,
"s": 1209,
"text": "The prior and likelihood is usually assumed to be Gaussian for the integration to be tractable. Using that assumption and solving for the predictive distribution, we get a Gaussian distribution, from which we can obtain a point prediction using its mean and an uncertainty quantification using its variance."
},
{
"code": null,
"e": 1991,
"s": 1517,
"text": "Gaussian process regression is nonparametric (i.e. not limited by a functional form), so rather than calculating the probability distribution of parameters of a specific function, GPR calculates the probability distribution over all admissible functions that fit the data. However, similar to the above, we specify a prior (on the function space), calculate the posterior using the training data, and compute the predictive posterior distribution on our points of interest."
},
{
"code": null,
"e": 2200,
"s": 1991,
"text": "There are several libraries for efficient implementation of Gaussian process regression (e.g. scikit-learn, Gpytorch, GPy), but for simplicity, this guide will use scikit-learn’s Gaussian process package [2]."
},
{
"code": null,
"e": 2238,
"s": 2200,
"text": "import sklearn.gaussian_process as gp"
},
{
"code": null,
"e": 2375,
"s": 2238,
"text": "In GPR, we first assume a Gaussian process prior, which can be specified using a mean function, m(x), and covariance function, k(x, x’):"
},
{
"code": null,
"e": 2889,
"s": 2375,
"text": "More specifically, a Gaussian process is like an infinite-dimensional multivariate Gaussian distribution, where any collection of the labels of the dataset are joint Gaussian distributed. Within this GP prior, we can incorporate prior knowledge about the space of functions through the selection of the mean and covariance functions. We can also easily incorporate independently, identically distributed (i.i.d) Gaussian noise, ε ∼ N(0, σ2), to the labels by summing the label distribution and noise distribution."
},
{
"code": null,
"e": 2996,
"s": 2889,
"text": "The dataset consists of observations, X, and their labels, y, split into “training” and “testing” subsets:"
},
{
"code": null,
"e": 3173,
"s": 2996,
"text": "# X_tr <-- training observations [# points, # features]# y_tr <-- training labels [# points]# X_te <-- test observations [# points, # features]# y_te <-- test labels [# points]"
},
{
"code": null,
"e": 3357,
"s": 3173,
"text": "From the Gaussian process prior, the collection of training points and test points are joint multivariate Gaussian distributed, and so we can write their distribution in this way [1]:"
},
{
"code": null,
"e": 3561,
"s": 3357,
"text": "Here, K is the covariance kernel matrix where its entries correspond to the covariance function evaluated at observations. Written in this way, we can take the training subset to perform model selection."
},
{
"code": null,
"e": 4087,
"s": 3561,
"text": "The form of the mean function and covariance kernel function in the GP prior is chosen and tuned during model selection. The mean function is typically constant, either zero or the mean of the training dataset. There are many options for the covariance kernel function: it can have many forms as long as it follows the properties of a kernel (i.e. semi-positive definite and symmetric). Some common kernel functions include constant, linear, square exponential and Matern kernel, as well as a composition of multiple kernels."
},
{
"code": null,
"e": 4312,
"s": 4087,
"text": "A popular kernel is the composition of the constant kernel with the radial basis function (RBF) kernel, which encodes for smoothness of functions (i.e. similarity of inputs in space corresponds to the similarity of outputs):"
},
{
"code": null,
"e": 4513,
"s": 4312,
"text": "This kernel has two hyperparameters: signal variance, σ2, and lengthscale, l. In scikit-learn, we can chose from a variety of kernels and specify the initial value and bounds on their hyperparameters."
},
{
"code": null,
"e": 4602,
"s": 4513,
"text": "kernel = gp.kernels.ConstantKernel(1.0, (1e-1, 1e3)) * gp.kernels.RBF(10.0, (1e-3, 1e3))"
},
{
"code": null,
"e": 4888,
"s": 4602,
"text": "After specifying the kernel function, we can now specify other choices for the GP model in scikit-learn. For example, alpha is the variance of the i.i.d. noise on the labels, and normalize_y refers to the constant mean function — either zero if False or the training data mean if True."
},
{
"code": null,
"e": 4993,
"s": 4888,
"text": "model = gp.GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=10, alpha=0.1, normalize_y=True)"
},
{
"code": null,
"e": 5425,
"s": 4993,
"text": "A popular approach to tune the hyperparameters of the covariance kernel function is to maximize the log marginal likelihood of the training data. A gradient-based optimizer is typically used for efficiency; if unspecified above, the default optimizer is ‘fmin_l_bfgs_b’. Because the log marginal likelihood is not necessarily convex, multiple restarts of the optimizer with different initializations is used (n_restarts_optimizer)."
},
{
"code": null,
"e": 5482,
"s": 5425,
"text": "model.fit(X_tr, y_tr)params = model.kernel_.get_params()"
},
{
"code": null,
"e": 5599,
"s": 5482,
"text": "The tuned hyperparameters of the kernel function can be obtained, if desired, by calling model.kernel_.get_params()."
},
{
"code": null,
"e": 5937,
"s": 5599,
"text": "To calculate the predictive posterior distribution, the data and the test observation is conditioned out of the posterior distribution. Again, because we chose a Gaussian process prior, calculating the predictive distribution is tractable, and leads to normal distribution that can be completely described by the mean and covariance [1]:"
},
{
"code": null,
"e": 6272,
"s": 5937,
"text": "The predictions are the means f_bar*, and variances can be obtained from the diagonal of the covariance matrix Σ*. Notice that calculation of the mean and variance requires the inversion of the K matrix, which scales with the number of training points cubed. Inference is simple to implement with sci-kit learn’s GPR predict function."
},
{
"code": null,
"e": 6323,
"s": 6272,
"text": "y_pred, std = model.predict(X_te, return_std=True)"
},
{
"code": null,
"e": 6539,
"s": 6323,
"text": "Note that the standard deviation is returned, but the whole covariance matrix can be returned if return_cov=True. The 95% confidence interval can then be calculated: 1.96 times the standard deviation for a Gaussian."
},
{
"code": null,
"e": 6682,
"s": 6539,
"text": "To measure the performance of the regression model on the test observations, we can calculate the mean squared error (MSE) on the predictions."
},
{
"code": null,
"e": 6714,
"s": 6682,
"text": "MSE = ((y_pred-y_te)**2).mean()"
},
{
"code": null,
"e": 6726,
"s": 6714,
"text": "References:"
},
{
"code": null,
"e": 6832,
"s": 6726,
"text": "[1] Rasmussen, C. E., & Williams, C. K. I., Gaussian processes for machine learning (2016), The MIT Press"
}
] |
SQL - UPDATE Query
|
The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows would be affected.
The basic syntax of the UPDATE query with a WHERE clause is as follows −
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using the AND or the OR operators.
Consider the 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 |
+----+----------+-----+-----------+----------+
The following query will update the ADDRESS for a customer whose ID number is 6 in the table.
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune'
WHERE ID = 6;
Now, the CUSTOMERS table would have 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 | Pune | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to modify all the ADDRESS and the SALARY column values in the CUSTOMERS table, you do not need to use the WHERE clause as the UPDATE query would be enough as shown in the following code block.
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;
Now, CUSTOMERS table would have the following records −
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 1 | Ramesh | 32 | Pune | 1000.00 |
| 2 | Khilan | 25 | Pune | 1000.00 |
| 3 | kaushik | 23 | Pune | 1000.00 |
| 4 | Chaitali | 25 | Pune | 1000.00 |
| 5 | Hardik | 27 | Pune | 1000.00 |
| 6 | Komal | 22 | Pune | 1000.00 |
| 7 | Muffy | 24 | Pune | 1000.00 |
+----+----------+-----+---------+---------+
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": 2647,
"s": 2453,
"text": "The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows would be affected."
},
{
"code": null,
"e": 2720,
"s": 2647,
"text": "The basic syntax of the UPDATE query with a WHERE clause is as follows −"
},
{
"code": null,
"e": 2819,
"s": 2720,
"text": "UPDATE table_name\nSET column1 = value1, column2 = value2...., columnN = valueN\nWHERE [condition];\n"
},
{
"code": null,
"e": 2893,
"s": 2819,
"text": "You can combine N number of conditions using the AND or the OR operators."
},
{
"code": null,
"e": 2953,
"s": 2893,
"text": "Consider the CUSTOMERS table having the following records −"
},
{
"code": null,
"e": 3470,
"s": 2953,
"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+----+----------+-----+-----------+----------+"
},
{
"code": null,
"e": 3564,
"s": 3470,
"text": "The following query will update the ADDRESS for a customer whose ID number is 6 in the table."
},
{
"code": null,
"e": 3621,
"s": 3564,
"text": "SQL> UPDATE CUSTOMERS\nSET ADDRESS = 'Pune'\nWHERE ID = 6;"
},
{
"code": null,
"e": 3681,
"s": 3621,
"text": "Now, the CUSTOMERS table would have the following records −"
},
{
"code": null,
"e": 4199,
"s": 3681,
"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 | Pune | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n"
},
{
"code": null,
"e": 4404,
"s": 4199,
"text": "If you want to modify all the ADDRESS and the SALARY column values in the CUSTOMERS table, you do not need to use the WHERE clause as the UPDATE query would be enough as shown in the following code block."
},
{
"code": null,
"e": 4466,
"s": 4404,
"text": "SQL> UPDATE CUSTOMERS\nSET ADDRESS = 'Pune', SALARY = 1000.00;"
},
{
"code": null,
"e": 4522,
"s": 4466,
"text": "Now, CUSTOMERS table would have the following records −"
},
{
"code": null,
"e": 5007,
"s": 4522,
"text": "+----+----------+-----+---------+---------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+---------+\n| 1 | Ramesh | 32 | Pune | 1000.00 |\n| 2 | Khilan | 25 | Pune | 1000.00 |\n| 3 | kaushik | 23 | Pune | 1000.00 |\n| 4 | Chaitali | 25 | Pune | 1000.00 |\n| 5 | Hardik | 27 | Pune | 1000.00 |\n| 6 | Komal | 22 | Pune | 1000.00 |\n| 7 | Muffy | 24 | Pune | 1000.00 |\n+----+----------+-----+---------+---------+\n"
},
{
"code": null,
"e": 5040,
"s": 5007,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5054,
"s": 5040,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5087,
"s": 5054,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5101,
"s": 5087,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5136,
"s": 5101,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5150,
"s": 5136,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5183,
"s": 5150,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5205,
"s": 5183,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5240,
"s": 5205,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5294,
"s": 5240,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 5327,
"s": 5294,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5355,
"s": 5327,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5362,
"s": 5355,
"text": " Print"
},
{
"code": null,
"e": 5373,
"s": 5362,
"text": " Add Notes"
}
] |
Optimized Space Invaders using Deep Q-learning: An Implementation in Tensorflow 2.0. | by Adrian Yijie Xu | Towards Data Science
|
Over the past few articles on GradientCrescent, we’ve spent a significant period of time exploring the field of online learning, a highly reactive family of reinforcement learning algorithms behind many of the latest achievements in general AI. Online learning belongs to the sample-based learning class of approaches, reliant allow for the determination of state values simply through repeated observations, eliminating the need for transition dynamics. Unlike their offline counterparts, online learning approaches allow for the incremental updates of the values of states and actions during an environmental episode, allowing for constant, incremental performance improvements to be observed.
Beyond Temporal Difference learning (TD), we’ve discussed the theory and practical implementations of Q-learning, an evolution of TD designed to allow for incremental estimations and improvement of state-action values. Q-learning has been made famous as becoming the backbone of reinforcement learning approaches to simulated game environments, such as those observed in OpenAI’s gyms. As we’ve already covered theoretical aspects of Q-learning in past articles, they will not be repeated here.
In our previous implementation of OpenAI’s Miss Pacman gym environment, we relied on a set of observation instances (states) of individual game frames as the inputs for our training process. However, this method is partially flawed, as it fails to take into account many of the idiosyncrasies of the Atari game environment, including:
The frame-skipping rendering of the game environment that’s observed in classic Atari games.
The presence of multiple fast-moving actors within the environment.
Frame-specific blinking observed in the agent and environment.
Together, these problems can serve to drastically reduce agent performance, as some instances of data essentially become out-of-domain, or completely irrelevant to the actual game environment. Furthermore, these problems would only become compounded with more complex game environments and real-world applications, such as in autonomous driving. This was observed in our previous implementation as a high level of variance and flat-lining in performance during training.
To overcome these problems, we can utilize a couple of techniques first introduced by the Deepmind team in 2015.
Frame stacking: the joining of several game frames together to provide a temporal reference of our game environment.
Frame composition: the element-wise maximization of two game frames together to provide a motion reference that also overcomes the issue of partial rendering.
Let’s implement examine the effects of these techniques on the more complex Atari Space Invader’s environment.
Our Google Colaboratory implementation is written in Python utilizing Tensorflow Core, and can be found on the GradientCrescent Github. We’ve converted our code to be TF2 compliant, using the new compat package. To start with, let’s briefly go over the actions required for our Q-learning implementation.
We define our Deep Q-learning neural network. This is a CNN that takes in-game screen images and outputs the probabilities of each of the actions, or Q-values, in the Ms-Pacman gamespace. To acquire a tensor of probabilities, we do not include any activation function in our final layer.As Q-learning requires us to have knowledge of both the current and next states, we need to start with data generation. We feed preprocessed input images of the game space, representing initial states s, into the network, and acquire the initial probability distribution of actions, or Q-values. Before training, these values will appear random and sub-optimal. Note that our preprocessing now includes stacking and composition as well.With our tensor of probabilities, we then select the action with the current highest probability using the argmax() function and use it to build an epsilon greedy policy.Using our policy, we’ll then select the action a, and evaluate our decision in the gym environment to receive information on the new state s’, the reward r, and whether the episode has been finished.We store this combination of information in a buffer in the list form <s,a,r,s’,d>, and repeat steps 2–4 for a preset number of times to build up a large enough buffer dataset.Once step 5 has finished, we move to generate our target y-values, R’ and A’, that are required for the loss calculation. While the former is simply discounted from R, we obtain the A’ by feeding S’ into our network.With all of our components in place, we can then calculate the loss to train our network.Once training has finished, we’ll evaluate the performance of our agent graphically and through a demonstration.
We define our Deep Q-learning neural network. This is a CNN that takes in-game screen images and outputs the probabilities of each of the actions, or Q-values, in the Ms-Pacman gamespace. To acquire a tensor of probabilities, we do not include any activation function in our final layer.
As Q-learning requires us to have knowledge of both the current and next states, we need to start with data generation. We feed preprocessed input images of the game space, representing initial states s, into the network, and acquire the initial probability distribution of actions, or Q-values. Before training, these values will appear random and sub-optimal. Note that our preprocessing now includes stacking and composition as well.
With our tensor of probabilities, we then select the action with the current highest probability using the argmax() function and use it to build an epsilon greedy policy.
Using our policy, we’ll then select the action a, and evaluate our decision in the gym environment to receive information on the new state s’, the reward r, and whether the episode has been finished.
We store this combination of information in a buffer in the list form <s,a,r,s’,d>, and repeat steps 2–4 for a preset number of times to build up a large enough buffer dataset.
Once step 5 has finished, we move to generate our target y-values, R’ and A’, that are required for the loss calculation. While the former is simply discounted from R, we obtain the A’ by feeding S’ into our network.
With all of our components in place, we can then calculate the loss to train our network.
Once training has finished, we’ll evaluate the performance of our agent graphically and through a demonstration.
For reference, let’s first demonstrate the results using the vanilla data input approach, which is essentially the same as that observed in our previous implementation for Miss Pacman. After training our agent for 800 episodes, we observe the following reward distribution.
Note how the variation in performance exhibits high variation, with a very limited amount of improvement observed after 650 episodes.
Likewise, the performance of our agent is less than stellar, with almost no evasion behavior being detected. If you look closely, you’ll notice the blinking in both the outgoing and incoming laser trails — this is an intentional part of the game environment, and results in certain frames having no projectiles in them at all, or only one set of projectiles visible. This means that elements of our input data are highly misleading, and negatively affect agent performance.
Let’s go over our improved implementation.
We start by importing all of the necessary packages, including the OpenAI gym environments and Tensorflow core.
import numpy as npimport gymimport tensorflow as tffrom tensorflow.contrib.layers import flatten, conv2d, fully_connectedfrom collections import deque, Counterimport randomfrom datetime import datetime
Next, we define a preprocessing function to crop the images from our gym environment and convert them into one-dimensional tensors. We’ve seen this before in our Pong automation implementation.
def preprocess_observation(obs): # Crop and resize the image img = obs[25:201:2, ::2] # Convert the image to greyscale img = img.mean(axis=2) # Improve image contrast img[img==color] = 0 # Next we normalize the image from -1 to +1 img = (img - 128) / 128 - 1 return img.reshape(88,80)
Next, let’s initialize the gym environment, and inspect a few screens of gameplay, and also understand the 9 actions available within the gamespace. Naturally, this information is not available to our agent.
env = gym.make(“SpaceInvaders-v0”)n_outputs = env.action_space.nprint(n_outputs)print(env.env.get_action_meanings())observation = env.reset()import tensorflow as tfimport matplotlib.pyplot as pltfor i in range(22):if i > 20:plt.imshow(observation)plt.show()observation, _, _, _ = env.step(1)
You should observe the following:
We can take this chance to compare our original and preprocessed input images:
Next, we introduce input stacking and input composition into our preprocessing pipeline. Upon a new episode, we start off by taking two of our input frames, and returning an element-wise maximum summation maxframe of the two (note that technically this is not necessary, as the two frames are the same, but serves for good practice). The stacked frames are stored in a deque, which automatically removes older entries as new entries are introduced. Initially, we copy the preprocessed maxframe to fill out our deque. As the episode progresses, we create new maxframes by taking the new frame, element-wise maximum summing it with the most recent entry in our deque, and then appending the new maxframe to our deque. We then stack the frames at the very end of the process.
stack_size = 4 # We stack 4 composite frames in total# Initialize deque with zero-images one array for each image. Deque is a special kind of queue that deletes last entry when new entry comes instacked_frames = deque([np.zeros((88,80), dtype=np.int) for i in range(stack_size)], maxlen=4)def stack_frames(stacked_frames, state, is_new_episode):# Preprocess frameframe = preprocess_observation(state) if is_new_episode: # Clear our stacked_frames stacked_frames = deque([np.zeros((88,80), dtype=np.int) for i in range(stack_size)], maxlen=4) # Because we’re in a new episode, copy the same frame 4x, apply elementwise maxima maxframe = np.maximum(frame,frame) stacked_frames.append(maxframe) stacked_frames.append(maxframe) stacked_frames.append(maxframe) stacked_frames.append(maxframe) # Stack the frames stacked_state = np.stack(stacked_frames, axis=2) else: #Since deque append adds t right, we can fetch rightmost element maxframe=np.maximum(stacked_frames[-1],frame) # Append frame to deque, automatically removes the oldest frame stacked_frames.append(maxframe) # Build the stacked state (first dimension specifies different frames) stacked_state = np.stack(stacked_frames, axis=2) return stacked_state, stacked_frames
Next, let’s define our model, a deep Q-network. This is essentially a three layer convolutional network that takes preprocessed input images, flattens and feeds them to a fully-connected layer, and outputs the probabilities of taking each action in the game space. As previously mentioned, there’s no activation layer here, as the presence of one would result in a binary output distribution.
def q_network(X, name_scope):# Initialize layersinitializer = tf.compat.v1.keras.initializers.VarianceScaling(scale=2.0)with tf.compat.v1.variable_scope(name_scope) as scope:# initialize the convolutional layerslayer_1 = conv2d(X, num_outputs=32, kernel_size=(8,8), stride=4, padding=’SAME’, weights_initializer=initializer)tf.compat.v1.summary.histogram(‘layer_1’,layer_1)layer_2 = conv2d(layer_1, num_outputs=64, kernel_size=(4,4), stride=2, padding=’SAME’, weights_initializer=initializer)tf.compat.v1.summary.histogram(‘layer_2’,layer_2)layer_3 = conv2d(layer_2, num_outputs=64, kernel_size=(3,3), stride=1, padding=’SAME’, weights_initializer=initializer)tf.compat.v1.summary.histogram(‘layer_3’,layer_3)flat = flatten(layer_3)fc = fully_connected(flat, num_outputs=128, weights_initializer=initializer)tf.compat.v1.summary.histogram(‘fc’,fc)#Add final output layeroutput = fully_connected(fc, num_outputs=n_outputs, activation_fn=None, weights_initializer=initializer)tf.compat.v1.summary.histogram(‘output’,output)vars = {v.name[len(scope.name):]: v for v in tf.compat.v1.get_collection(key=tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES, scope=scope.name)}#Return both variables and outputs togetherreturn vars, output
Let’s also take this chance to define our hyperparameters for our model and training process. Note that the X_shape is now (None, 88, 80, 4), on account of our stacked frames.
num_episodes = 800batch_size = 48input_shape = (None, 88, 80, 1)learning_rate = 0.001X_shape = (None, 88, 80, 4)discount_factor = 0.97global_step = 0copy_steps = 100steps_train = 4start_steps = 2000
Recall, that Q-learning requires us to select actions with the highest action values. To ensure that we still visit every single possible state-action combination, we’ll have our agent follow an epsilon-greedy policy, with an exploration rate of 5%. We’ll set this exploration rate to decay with time, as we eventually assume all combinations have already been explored — any exploration after that point would simply result in the forced selection of sub-optimal actions.
epsilon = 0.5eps_min = 0.05eps_max = 1.0eps_decay_steps = 500000#def epsilon_greedy(action, step): p = np.random.random(1).squeeze() #1D entries returned using squeeze epsilon = max(eps_min, eps_max — (eps_max-eps_min) * step/eps_decay_steps) #Decaying policy with more steps if np.random.rand() < epsilon: return np.random.randint(n_outputs) else: return action
Recall from the equations above, that the update function for Q-learning requires the following:
The current state s
The current action a
The reward following the current action r
The next state s’
The next action a’
To supply these parameters in meaningful quantities, we need to evaluate our current policy following a set of parameters and store all of the variables in a buffer, from which we’ll draw data in minibatches during training. Let’s go ahead and create our buffer and a simple sampling function:
buffer_len = 20000#Buffer is made from a deque — double ended queueexp_buffer = deque(maxlen=buffer_len)def sample_memories(batch_size): perm_batch = np.random.permutation(len(exp_buffer))[:batch_size] mem = np.array(exp_buffer)[perm_batch] return mem[:,0], mem[:,1], mem[:,2], mem[:,3], mem[:,4]
Next, let’s copy the weight parameters of our original network into a target network. This dual-network approach allows us to generate data during the training process using an existing policy while still optimizing our parameters for the next policy iteration.
# we build our Q network, which takes the input X and generates Q values for all the actions in the statemainQ, mainQ_outputs = q_network(X, ‘mainQ’)# similarly we build our target Q network, for policy evaluationtargetQ, targetQ_outputs = q_network(X, ‘targetQ’)copy_op = [tf.compat.v1.assign(main_name, targetQ[var_name]) for var_name, main_name in mainQ.items()]copy_target_to_main = tf.group(*copy_op)
Finally, we’ll also define our loss. This is simply the squared difference of our target action (with the highest action value) and our predicted action. We’ll use an ADAM optimizer to minimize our loss during training.
# define a placeholder for our output i.e actiony = tf.compat.v1.placeholder(tf.float32, shape=(None,1))# now we calculate the loss which is the difference between actual value and predicted valueloss = tf.reduce_mean(input_tensor=tf.square(y — Q_action))# we use adam optimizer for minimizing the lossoptimizer = tf.compat.v1.train.AdamOptimizer(learning_rate)training_op = optimizer.minimize(loss)init = tf.compat.v1.global_variables_initializer()loss_summary = tf.compat.v1.summary.scalar(‘LOSS’, loss)merge_summary = tf.compat.v1.summary.merge_all()file_writer = tf.compat.v1.summary.FileWriter(logdir, tf.compat.v1.get_default_graph())
With all of our code defined, let’s run our network and go over the training process. We’ve defined most of this in the initial summary, but let’s recall for posterity.
For each epoch, we feed an input image stack into our network to generate a probability distribution of the available actions, before using an epsilon-greedy policy to select the next action
We then input this into the network, and obtain information on the next state and accompanying rewards, and store this into our buffer. We update our stack and repeat this process over a number of pre-defined steps.
After our buffer is large enough, we feed the next states into our network in order to obtain the next action. We also calculate the next reward by discounting the current one
We generate our target y-values through the Q-learning update function, and train our network.
By minimizing the training loss, we update the network weight parameters to output improved state-action values for the next policy.
with tf.compat.v1.Session() as sess: init.run() # for each episode history = [] for i in range(num_episodes): done = False obs = env.reset() epoch = 0 episodic_reward = 0 actions_counter = Counter() episodic_loss = [] #First step, preprocess + initialize stack obs,stacked_frames= stack_frames(stacked_frames,obs,True) # while the state is not the terminal state while not done: #Data generation using the untrained network # feed the game screen and get the Q values for each action actions = mainQ_outputs.eval(feed_dict={X:[obs], in_training_mode:False}) # get the action action = np.argmax(actions, axis=-1) actions_counter[str(action)] += 1 # select the action using epsilon greedy policy action = epsilon_greedy(action, global_step) # now perform the action and move to the next state, next_obs, receive reward next_obs, reward, done, _ = env.step(action) #Updated stacked frames with new episode next_obs, stacked_frames = stack_frames(stacked_frames, next_obs, False) # Store this transition as an experience in the replay buffer! Quite important exp_buffer.append([obs, action, next_obs, reward, done]) # After certain steps, we train our Q network with samples from the experience replay buffer if global_step % steps_train == 0 and global_step > start_steps: #Our buffer should already contain everything preprocessed and stacked o_obs, o_act, o_next_obs, o_rew, o_done = sample_memories(batch_size) # states o_obs = [x for x in o_obs] # next states o_next_obs = [x for x in o_next_obs] # next actions next_act = mainQ_outputs.eval(feed_dict={X:o_next_obs, in_training_mode:False}) # discounted reward: these are our Y-values y_batch = o_rew + discount_factor * np.max(next_act, axis=-1) * (1-o_done) # merge all summaries and write to the file mrg_summary = merge_summary.eval(feed_dict={X:o_obs, y:np.expand_dims(y_batch, axis=-1), X_action:o_act, in_training_mode:False}) file_writer.add_summary(mrg_summary, global_step) # To calculate the loss, we run the previously defined functions mentioned while feeding inputs train_loss, _ = sess.run([loss, training_op], feed_dict={X:o_obs, y:np.expand_dims(y_batch, axis=-1), X_action:o_act, in_training_mode:True}) episodic_loss.append(train_loss) # after some interval we copy our main Q network weights to target Q network if (global_step+1) % copy_steps == 0 and global_step > start_steps: copy_target_to_main.run() obs = next_obs epoch += 1 global_step += 1 episodic_reward += rewardnext_obs=np.zeros(obs.shape)exp_buffer.append([obs, action, next_obs, reward, done])obs= env.reset()obs,stacked_frames= stack_frames(stacked_frames,obs,True)history.append(episodic_reward)print('Epochs per episode:', epoch, 'Episode Reward:', episodic_reward,"Episode number:", len(history))
Once training is complete, we can plot the reward distribution against incremental episodes. The first 800 episodes are shown below:
Notice how the core variation in reward distribution has decreased significantly, allowing for a much more consistent inter-episode distribution to be observed, and increases in performance to become more statistically significant. A visible increase in performance can be observed from 550 episodes onwards, a full 100 episodes earlier than that of the vanilla data approach, validating our hypothesis.
To evaluate our results within the confinement of the Colaboratory environment, we can record an entire episode and display it within a virtual display using a wrapped based on the IPython library:
“””Utility functions to enable video recording of gym environment and displaying it. To enable video, just do “env = wrap_env(env)””“”def show_video():mp4list = glob.glob(‘video/*.mp4’)if len(mp4list) > 0:mp4 = mp4list[0]video = io.open(mp4, ‘r+b’).read()encoded = base64.b64encode(video)ipythondisplay.display(HTML(data=’’’<video alt=”test” autoplayloop controls style=”height: 400px;”><source src=”data:video/mp4;base64,{0}” type=”video/mp4" /></video>’’’.format(encoded.decode(‘ascii’))))else:print(“Could not find video”) def wrap_env(env):env = Monitor(env, ‘./video’, force=True)return env
We then run a new session of our environment using our model and record it.
Evaluate model on openAi GYMenvironment = wrap_env(gym.make('SpaceInvaders-v0'))done = Falseobservation = environment.reset()new_observation = observationprev_input = Nonewith tf.compat.v1.Session() as sess: init.run() observation, stacked_frames = stack_frames(stacked_frames, observation, True) while True: #set input to network to be difference image # feed the game screen and get the Q values for each action actions = mainQ_outputs.eval(feed_dict={X:[observation], in_training_mode:False}) # get the action action = np.argmax(actions, axis=-1) actions_counter[str(action)] += 1 # select the action using epsilon greedy policy action = epsilon_greedy(action, global_step) environment.render() new_observation, stacked_frames = stack_frames(stacked_frames, new_observation, False) observation = new_observation # now perform the action and move to the next state, next_obs, receive reward new_observation, reward, done, _ = environment.step(action) if done: breakenvironment.close()show_video()
Let’s inspect a few rounds of gameplay.
Our agent has learned to behave both defensively and offensively, utilizing cover and evasion effectively. The drastic difference in behavior between the two episodes can be attributed to how Q-learning works —actions selected earlier on gain a Q-value, which tend to be favoured with an epsilon-greedy policy. With further training, we would expect these two behaviours to converge.
That wraps up this introduction to optimizing Q-learning. In our next article, we’ll take all we’ve learned and move on from the world of Atari to tackling one of the most well known FPS games in the world.
We hope you enjoyed this article, and hope you check out the many other articles on GradientCrescent, covering applied and theoretical aspects of AI. To stay up to date with the latest updates on GradientCrescent, please consider following the publication and following our Github repository.
References
Sutton et. al, Reinforcement Learning
White et. al, Fundamentals of Reinforcement Learning, University of Alberta
Silva et. al, Reinforcement Learning, UCL
Ravichandiran et. al, Hands-On Reinforcement Learning with Python
Takeshi et. al, Github
|
[
{
"code": null,
"e": 868,
"s": 172,
"text": "Over the past few articles on GradientCrescent, we’ve spent a significant period of time exploring the field of online learning, a highly reactive family of reinforcement learning algorithms behind many of the latest achievements in general AI. Online learning belongs to the sample-based learning class of approaches, reliant allow for the determination of state values simply through repeated observations, eliminating the need for transition dynamics. Unlike their offline counterparts, online learning approaches allow for the incremental updates of the values of states and actions during an environmental episode, allowing for constant, incremental performance improvements to be observed."
},
{
"code": null,
"e": 1363,
"s": 868,
"text": "Beyond Temporal Difference learning (TD), we’ve discussed the theory and practical implementations of Q-learning, an evolution of TD designed to allow for incremental estimations and improvement of state-action values. Q-learning has been made famous as becoming the backbone of reinforcement learning approaches to simulated game environments, such as those observed in OpenAI’s gyms. As we’ve already covered theoretical aspects of Q-learning in past articles, they will not be repeated here."
},
{
"code": null,
"e": 1698,
"s": 1363,
"text": "In our previous implementation of OpenAI’s Miss Pacman gym environment, we relied on a set of observation instances (states) of individual game frames as the inputs for our training process. However, this method is partially flawed, as it fails to take into account many of the idiosyncrasies of the Atari game environment, including:"
},
{
"code": null,
"e": 1791,
"s": 1698,
"text": "The frame-skipping rendering of the game environment that’s observed in classic Atari games."
},
{
"code": null,
"e": 1859,
"s": 1791,
"text": "The presence of multiple fast-moving actors within the environment."
},
{
"code": null,
"e": 1922,
"s": 1859,
"text": "Frame-specific blinking observed in the agent and environment."
},
{
"code": null,
"e": 2393,
"s": 1922,
"text": "Together, these problems can serve to drastically reduce agent performance, as some instances of data essentially become out-of-domain, or completely irrelevant to the actual game environment. Furthermore, these problems would only become compounded with more complex game environments and real-world applications, such as in autonomous driving. This was observed in our previous implementation as a high level of variance and flat-lining in performance during training."
},
{
"code": null,
"e": 2506,
"s": 2393,
"text": "To overcome these problems, we can utilize a couple of techniques first introduced by the Deepmind team in 2015."
},
{
"code": null,
"e": 2623,
"s": 2506,
"text": "Frame stacking: the joining of several game frames together to provide a temporal reference of our game environment."
},
{
"code": null,
"e": 2782,
"s": 2623,
"text": "Frame composition: the element-wise maximization of two game frames together to provide a motion reference that also overcomes the issue of partial rendering."
},
{
"code": null,
"e": 2893,
"s": 2782,
"text": "Let’s implement examine the effects of these techniques on the more complex Atari Space Invader’s environment."
},
{
"code": null,
"e": 3198,
"s": 2893,
"text": "Our Google Colaboratory implementation is written in Python utilizing Tensorflow Core, and can be found on the GradientCrescent Github. We’ve converted our code to be TF2 compliant, using the new compat package. To start with, let’s briefly go over the actions required for our Q-learning implementation."
},
{
"code": null,
"e": 4884,
"s": 3198,
"text": "We define our Deep Q-learning neural network. This is a CNN that takes in-game screen images and outputs the probabilities of each of the actions, or Q-values, in the Ms-Pacman gamespace. To acquire a tensor of probabilities, we do not include any activation function in our final layer.As Q-learning requires us to have knowledge of both the current and next states, we need to start with data generation. We feed preprocessed input images of the game space, representing initial states s, into the network, and acquire the initial probability distribution of actions, or Q-values. Before training, these values will appear random and sub-optimal. Note that our preprocessing now includes stacking and composition as well.With our tensor of probabilities, we then select the action with the current highest probability using the argmax() function and use it to build an epsilon greedy policy.Using our policy, we’ll then select the action a, and evaluate our decision in the gym environment to receive information on the new state s’, the reward r, and whether the episode has been finished.We store this combination of information in a buffer in the list form <s,a,r,s’,d>, and repeat steps 2–4 for a preset number of times to build up a large enough buffer dataset.Once step 5 has finished, we move to generate our target y-values, R’ and A’, that are required for the loss calculation. While the former is simply discounted from R, we obtain the A’ by feeding S’ into our network.With all of our components in place, we can then calculate the loss to train our network.Once training has finished, we’ll evaluate the performance of our agent graphically and through a demonstration."
},
{
"code": null,
"e": 5172,
"s": 4884,
"text": "We define our Deep Q-learning neural network. This is a CNN that takes in-game screen images and outputs the probabilities of each of the actions, or Q-values, in the Ms-Pacman gamespace. To acquire a tensor of probabilities, we do not include any activation function in our final layer."
},
{
"code": null,
"e": 5609,
"s": 5172,
"text": "As Q-learning requires us to have knowledge of both the current and next states, we need to start with data generation. We feed preprocessed input images of the game space, representing initial states s, into the network, and acquire the initial probability distribution of actions, or Q-values. Before training, these values will appear random and sub-optimal. Note that our preprocessing now includes stacking and composition as well."
},
{
"code": null,
"e": 5780,
"s": 5609,
"text": "With our tensor of probabilities, we then select the action with the current highest probability using the argmax() function and use it to build an epsilon greedy policy."
},
{
"code": null,
"e": 5980,
"s": 5780,
"text": "Using our policy, we’ll then select the action a, and evaluate our decision in the gym environment to receive information on the new state s’, the reward r, and whether the episode has been finished."
},
{
"code": null,
"e": 6157,
"s": 5980,
"text": "We store this combination of information in a buffer in the list form <s,a,r,s’,d>, and repeat steps 2–4 for a preset number of times to build up a large enough buffer dataset."
},
{
"code": null,
"e": 6374,
"s": 6157,
"text": "Once step 5 has finished, we move to generate our target y-values, R’ and A’, that are required for the loss calculation. While the former is simply discounted from R, we obtain the A’ by feeding S’ into our network."
},
{
"code": null,
"e": 6464,
"s": 6374,
"text": "With all of our components in place, we can then calculate the loss to train our network."
},
{
"code": null,
"e": 6577,
"s": 6464,
"text": "Once training has finished, we’ll evaluate the performance of our agent graphically and through a demonstration."
},
{
"code": null,
"e": 6851,
"s": 6577,
"text": "For reference, let’s first demonstrate the results using the vanilla data input approach, which is essentially the same as that observed in our previous implementation for Miss Pacman. After training our agent for 800 episodes, we observe the following reward distribution."
},
{
"code": null,
"e": 6985,
"s": 6851,
"text": "Note how the variation in performance exhibits high variation, with a very limited amount of improvement observed after 650 episodes."
},
{
"code": null,
"e": 7459,
"s": 6985,
"text": "Likewise, the performance of our agent is less than stellar, with almost no evasion behavior being detected. If you look closely, you’ll notice the blinking in both the outgoing and incoming laser trails — this is an intentional part of the game environment, and results in certain frames having no projectiles in them at all, or only one set of projectiles visible. This means that elements of our input data are highly misleading, and negatively affect agent performance."
},
{
"code": null,
"e": 7502,
"s": 7459,
"text": "Let’s go over our improved implementation."
},
{
"code": null,
"e": 7614,
"s": 7502,
"text": "We start by importing all of the necessary packages, including the OpenAI gym environments and Tensorflow core."
},
{
"code": null,
"e": 7816,
"s": 7614,
"text": "import numpy as npimport gymimport tensorflow as tffrom tensorflow.contrib.layers import flatten, conv2d, fully_connectedfrom collections import deque, Counterimport randomfrom datetime import datetime"
},
{
"code": null,
"e": 8010,
"s": 7816,
"text": "Next, we define a preprocessing function to crop the images from our gym environment and convert them into one-dimensional tensors. We’ve seen this before in our Pong automation implementation."
},
{
"code": null,
"e": 8304,
"s": 8010,
"text": "def preprocess_observation(obs): # Crop and resize the image img = obs[25:201:2, ::2] # Convert the image to greyscale img = img.mean(axis=2) # Improve image contrast img[img==color] = 0 # Next we normalize the image from -1 to +1 img = (img - 128) / 128 - 1 return img.reshape(88,80)"
},
{
"code": null,
"e": 8512,
"s": 8304,
"text": "Next, let’s initialize the gym environment, and inspect a few screens of gameplay, and also understand the 9 actions available within the gamespace. Naturally, this information is not available to our agent."
},
{
"code": null,
"e": 8804,
"s": 8512,
"text": "env = gym.make(“SpaceInvaders-v0”)n_outputs = env.action_space.nprint(n_outputs)print(env.env.get_action_meanings())observation = env.reset()import tensorflow as tfimport matplotlib.pyplot as pltfor i in range(22):if i > 20:plt.imshow(observation)plt.show()observation, _, _, _ = env.step(1)"
},
{
"code": null,
"e": 8838,
"s": 8804,
"text": "You should observe the following:"
},
{
"code": null,
"e": 8917,
"s": 8838,
"text": "We can take this chance to compare our original and preprocessed input images:"
},
{
"code": null,
"e": 9690,
"s": 8917,
"text": "Next, we introduce input stacking and input composition into our preprocessing pipeline. Upon a new episode, we start off by taking two of our input frames, and returning an element-wise maximum summation maxframe of the two (note that technically this is not necessary, as the two frames are the same, but serves for good practice). The stacked frames are stored in a deque, which automatically removes older entries as new entries are introduced. Initially, we copy the preprocessed maxframe to fill out our deque. As the episode progresses, we create new maxframes by taking the new frame, element-wise maximum summing it with the most recent entry in our deque, and then appending the new maxframe to our deque. We then stack the frames at the very end of the process."
},
{
"code": null,
"e": 10963,
"s": 9690,
"text": "stack_size = 4 # We stack 4 composite frames in total# Initialize deque with zero-images one array for each image. Deque is a special kind of queue that deletes last entry when new entry comes instacked_frames = deque([np.zeros((88,80), dtype=np.int) for i in range(stack_size)], maxlen=4)def stack_frames(stacked_frames, state, is_new_episode):# Preprocess frameframe = preprocess_observation(state) if is_new_episode: # Clear our stacked_frames stacked_frames = deque([np.zeros((88,80), dtype=np.int) for i in range(stack_size)], maxlen=4) # Because we’re in a new episode, copy the same frame 4x, apply elementwise maxima maxframe = np.maximum(frame,frame) stacked_frames.append(maxframe) stacked_frames.append(maxframe) stacked_frames.append(maxframe) stacked_frames.append(maxframe) # Stack the frames stacked_state = np.stack(stacked_frames, axis=2) else: #Since deque append adds t right, we can fetch rightmost element maxframe=np.maximum(stacked_frames[-1],frame) # Append frame to deque, automatically removes the oldest frame stacked_frames.append(maxframe) # Build the stacked state (first dimension specifies different frames) stacked_state = np.stack(stacked_frames, axis=2) return stacked_state, stacked_frames"
},
{
"code": null,
"e": 11356,
"s": 10963,
"text": "Next, let’s define our model, a deep Q-network. This is essentially a three layer convolutional network that takes preprocessed input images, flattens and feeds them to a fully-connected layer, and outputs the probabilities of taking each action in the game space. As previously mentioned, there’s no activation layer here, as the presence of one would result in a binary output distribution."
},
{
"code": null,
"e": 12582,
"s": 11356,
"text": "def q_network(X, name_scope):# Initialize layersinitializer = tf.compat.v1.keras.initializers.VarianceScaling(scale=2.0)with tf.compat.v1.variable_scope(name_scope) as scope:# initialize the convolutional layerslayer_1 = conv2d(X, num_outputs=32, kernel_size=(8,8), stride=4, padding=’SAME’, weights_initializer=initializer)tf.compat.v1.summary.histogram(‘layer_1’,layer_1)layer_2 = conv2d(layer_1, num_outputs=64, kernel_size=(4,4), stride=2, padding=’SAME’, weights_initializer=initializer)tf.compat.v1.summary.histogram(‘layer_2’,layer_2)layer_3 = conv2d(layer_2, num_outputs=64, kernel_size=(3,3), stride=1, padding=’SAME’, weights_initializer=initializer)tf.compat.v1.summary.histogram(‘layer_3’,layer_3)flat = flatten(layer_3)fc = fully_connected(flat, num_outputs=128, weights_initializer=initializer)tf.compat.v1.summary.histogram(‘fc’,fc)#Add final output layeroutput = fully_connected(fc, num_outputs=n_outputs, activation_fn=None, weights_initializer=initializer)tf.compat.v1.summary.histogram(‘output’,output)vars = {v.name[len(scope.name):]: v for v in tf.compat.v1.get_collection(key=tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES, scope=scope.name)}#Return both variables and outputs togetherreturn vars, output"
},
{
"code": null,
"e": 12758,
"s": 12582,
"text": "Let’s also take this chance to define our hyperparameters for our model and training process. Note that the X_shape is now (None, 88, 80, 4), on account of our stacked frames."
},
{
"code": null,
"e": 12957,
"s": 12758,
"text": "num_episodes = 800batch_size = 48input_shape = (None, 88, 80, 1)learning_rate = 0.001X_shape = (None, 88, 80, 4)discount_factor = 0.97global_step = 0copy_steps = 100steps_train = 4start_steps = 2000"
},
{
"code": null,
"e": 13430,
"s": 12957,
"text": "Recall, that Q-learning requires us to select actions with the highest action values. To ensure that we still visit every single possible state-action combination, we’ll have our agent follow an epsilon-greedy policy, with an exploration rate of 5%. We’ll set this exploration rate to decay with time, as we eventually assume all combinations have already been explored — any exploration after that point would simply result in the forced selection of sub-optimal actions."
},
{
"code": null,
"e": 13803,
"s": 13430,
"text": "epsilon = 0.5eps_min = 0.05eps_max = 1.0eps_decay_steps = 500000#def epsilon_greedy(action, step): p = np.random.random(1).squeeze() #1D entries returned using squeeze epsilon = max(eps_min, eps_max — (eps_max-eps_min) * step/eps_decay_steps) #Decaying policy with more steps if np.random.rand() < epsilon: return np.random.randint(n_outputs) else: return action"
},
{
"code": null,
"e": 13900,
"s": 13803,
"text": "Recall from the equations above, that the update function for Q-learning requires the following:"
},
{
"code": null,
"e": 13920,
"s": 13900,
"text": "The current state s"
},
{
"code": null,
"e": 13941,
"s": 13920,
"text": "The current action a"
},
{
"code": null,
"e": 13983,
"s": 13941,
"text": "The reward following the current action r"
},
{
"code": null,
"e": 14001,
"s": 13983,
"text": "The next state s’"
},
{
"code": null,
"e": 14020,
"s": 14001,
"text": "The next action a’"
},
{
"code": null,
"e": 14314,
"s": 14020,
"text": "To supply these parameters in meaningful quantities, we need to evaluate our current policy following a set of parameters and store all of the variables in a buffer, from which we’ll draw data in minibatches during training. Let’s go ahead and create our buffer and a simple sampling function:"
},
{
"code": null,
"e": 14614,
"s": 14314,
"text": "buffer_len = 20000#Buffer is made from a deque — double ended queueexp_buffer = deque(maxlen=buffer_len)def sample_memories(batch_size): perm_batch = np.random.permutation(len(exp_buffer))[:batch_size] mem = np.array(exp_buffer)[perm_batch] return mem[:,0], mem[:,1], mem[:,2], mem[:,3], mem[:,4]"
},
{
"code": null,
"e": 14876,
"s": 14614,
"text": "Next, let’s copy the weight parameters of our original network into a target network. This dual-network approach allows us to generate data during the training process using an existing policy while still optimizing our parameters for the next policy iteration."
},
{
"code": null,
"e": 15282,
"s": 14876,
"text": "# we build our Q network, which takes the input X and generates Q values for all the actions in the statemainQ, mainQ_outputs = q_network(X, ‘mainQ’)# similarly we build our target Q network, for policy evaluationtargetQ, targetQ_outputs = q_network(X, ‘targetQ’)copy_op = [tf.compat.v1.assign(main_name, targetQ[var_name]) for var_name, main_name in mainQ.items()]copy_target_to_main = tf.group(*copy_op)"
},
{
"code": null,
"e": 15502,
"s": 15282,
"text": "Finally, we’ll also define our loss. This is simply the squared difference of our target action (with the highest action value) and our predicted action. We’ll use an ADAM optimizer to minimize our loss during training."
},
{
"code": null,
"e": 16143,
"s": 15502,
"text": "# define a placeholder for our output i.e actiony = tf.compat.v1.placeholder(tf.float32, shape=(None,1))# now we calculate the loss which is the difference between actual value and predicted valueloss = tf.reduce_mean(input_tensor=tf.square(y — Q_action))# we use adam optimizer for minimizing the lossoptimizer = tf.compat.v1.train.AdamOptimizer(learning_rate)training_op = optimizer.minimize(loss)init = tf.compat.v1.global_variables_initializer()loss_summary = tf.compat.v1.summary.scalar(‘LOSS’, loss)merge_summary = tf.compat.v1.summary.merge_all()file_writer = tf.compat.v1.summary.FileWriter(logdir, tf.compat.v1.get_default_graph())"
},
{
"code": null,
"e": 16312,
"s": 16143,
"text": "With all of our code defined, let’s run our network and go over the training process. We’ve defined most of this in the initial summary, but let’s recall for posterity."
},
{
"code": null,
"e": 16503,
"s": 16312,
"text": "For each epoch, we feed an input image stack into our network to generate a probability distribution of the available actions, before using an epsilon-greedy policy to select the next action"
},
{
"code": null,
"e": 16719,
"s": 16503,
"text": "We then input this into the network, and obtain information on the next state and accompanying rewards, and store this into our buffer. We update our stack and repeat this process over a number of pre-defined steps."
},
{
"code": null,
"e": 16895,
"s": 16719,
"text": "After our buffer is large enough, we feed the next states into our network in order to obtain the next action. We also calculate the next reward by discounting the current one"
},
{
"code": null,
"e": 16990,
"s": 16895,
"text": "We generate our target y-values through the Q-learning update function, and train our network."
},
{
"code": null,
"e": 17123,
"s": 16990,
"text": "By minimizing the training loss, we update the network weight parameters to output improved state-action values for the next policy."
},
{
"code": null,
"e": 20048,
"s": 17123,
"text": "with tf.compat.v1.Session() as sess: init.run() # for each episode history = [] for i in range(num_episodes): done = False obs = env.reset() epoch = 0 episodic_reward = 0 actions_counter = Counter() episodic_loss = [] #First step, preprocess + initialize stack obs,stacked_frames= stack_frames(stacked_frames,obs,True) # while the state is not the terminal state while not done: #Data generation using the untrained network # feed the game screen and get the Q values for each action actions = mainQ_outputs.eval(feed_dict={X:[obs], in_training_mode:False}) # get the action action = np.argmax(actions, axis=-1) actions_counter[str(action)] += 1 # select the action using epsilon greedy policy action = epsilon_greedy(action, global_step) # now perform the action and move to the next state, next_obs, receive reward next_obs, reward, done, _ = env.step(action) #Updated stacked frames with new episode next_obs, stacked_frames = stack_frames(stacked_frames, next_obs, False) # Store this transition as an experience in the replay buffer! Quite important exp_buffer.append([obs, action, next_obs, reward, done]) # After certain steps, we train our Q network with samples from the experience replay buffer if global_step % steps_train == 0 and global_step > start_steps: #Our buffer should already contain everything preprocessed and stacked o_obs, o_act, o_next_obs, o_rew, o_done = sample_memories(batch_size) # states o_obs = [x for x in o_obs] # next states o_next_obs = [x for x in o_next_obs] # next actions next_act = mainQ_outputs.eval(feed_dict={X:o_next_obs, in_training_mode:False}) # discounted reward: these are our Y-values y_batch = o_rew + discount_factor * np.max(next_act, axis=-1) * (1-o_done) # merge all summaries and write to the file mrg_summary = merge_summary.eval(feed_dict={X:o_obs, y:np.expand_dims(y_batch, axis=-1), X_action:o_act, in_training_mode:False}) file_writer.add_summary(mrg_summary, global_step) # To calculate the loss, we run the previously defined functions mentioned while feeding inputs train_loss, _ = sess.run([loss, training_op], feed_dict={X:o_obs, y:np.expand_dims(y_batch, axis=-1), X_action:o_act, in_training_mode:True}) episodic_loss.append(train_loss) # after some interval we copy our main Q network weights to target Q network if (global_step+1) % copy_steps == 0 and global_step > start_steps: copy_target_to_main.run() obs = next_obs epoch += 1 global_step += 1 episodic_reward += rewardnext_obs=np.zeros(obs.shape)exp_buffer.append([obs, action, next_obs, reward, done])obs= env.reset()obs,stacked_frames= stack_frames(stacked_frames,obs,True)history.append(episodic_reward)print('Epochs per episode:', epoch, 'Episode Reward:', episodic_reward,\"Episode number:\", len(history))"
},
{
"code": null,
"e": 20181,
"s": 20048,
"text": "Once training is complete, we can plot the reward distribution against incremental episodes. The first 800 episodes are shown below:"
},
{
"code": null,
"e": 20585,
"s": 20181,
"text": "Notice how the core variation in reward distribution has decreased significantly, allowing for a much more consistent inter-episode distribution to be observed, and increases in performance to become more statistically significant. A visible increase in performance can be observed from 550 episodes onwards, a full 100 episodes earlier than that of the vanilla data approach, validating our hypothesis."
},
{
"code": null,
"e": 20783,
"s": 20585,
"text": "To evaluate our results within the confinement of the Colaboratory environment, we can record an entire episode and display it within a virtual display using a wrapped based on the IPython library:"
},
{
"code": null,
"e": 21382,
"s": 20783,
"text": "“””Utility functions to enable video recording of gym environment and displaying it. To enable video, just do “env = wrap_env(env)””“”def show_video():mp4list = glob.glob(‘video/*.mp4’)if len(mp4list) > 0:mp4 = mp4list[0]video = io.open(mp4, ‘r+b’).read()encoded = base64.b64encode(video)ipythondisplay.display(HTML(data=’’’<video alt=”test” autoplayloop controls style=”height: 400px;”><source src=”data:video/mp4;base64,{0}” type=”video/mp4\" /></video>’’’.format(encoded.decode(‘ascii’))))else:print(“Could not find video”) def wrap_env(env):env = Monitor(env, ‘./video’, force=True)return env"
},
{
"code": null,
"e": 21458,
"s": 21382,
"text": "We then run a new session of our environment using our model and record it."
},
{
"code": null,
"e": 22507,
"s": 21458,
"text": "Evaluate model on openAi GYMenvironment = wrap_env(gym.make('SpaceInvaders-v0'))done = Falseobservation = environment.reset()new_observation = observationprev_input = Nonewith tf.compat.v1.Session() as sess: init.run() observation, stacked_frames = stack_frames(stacked_frames, observation, True) while True: #set input to network to be difference image # feed the game screen and get the Q values for each action actions = mainQ_outputs.eval(feed_dict={X:[observation], in_training_mode:False}) # get the action action = np.argmax(actions, axis=-1) actions_counter[str(action)] += 1 # select the action using epsilon greedy policy action = epsilon_greedy(action, global_step) environment.render() new_observation, stacked_frames = stack_frames(stacked_frames, new_observation, False) observation = new_observation # now perform the action and move to the next state, next_obs, receive reward new_observation, reward, done, _ = environment.step(action) if done: breakenvironment.close()show_video()"
},
{
"code": null,
"e": 22547,
"s": 22507,
"text": "Let’s inspect a few rounds of gameplay."
},
{
"code": null,
"e": 22931,
"s": 22547,
"text": "Our agent has learned to behave both defensively and offensively, utilizing cover and evasion effectively. The drastic difference in behavior between the two episodes can be attributed to how Q-learning works —actions selected earlier on gain a Q-value, which tend to be favoured with an epsilon-greedy policy. With further training, we would expect these two behaviours to converge."
},
{
"code": null,
"e": 23138,
"s": 22931,
"text": "That wraps up this introduction to optimizing Q-learning. In our next article, we’ll take all we’ve learned and move on from the world of Atari to tackling one of the most well known FPS games in the world."
},
{
"code": null,
"e": 23431,
"s": 23138,
"text": "We hope you enjoyed this article, and hope you check out the many other articles on GradientCrescent, covering applied and theoretical aspects of AI. To stay up to date with the latest updates on GradientCrescent, please consider following the publication and following our Github repository."
},
{
"code": null,
"e": 23442,
"s": 23431,
"text": "References"
},
{
"code": null,
"e": 23480,
"s": 23442,
"text": "Sutton et. al, Reinforcement Learning"
},
{
"code": null,
"e": 23556,
"s": 23480,
"text": "White et. al, Fundamentals of Reinforcement Learning, University of Alberta"
},
{
"code": null,
"e": 23598,
"s": 23556,
"text": "Silva et. al, Reinforcement Learning, UCL"
},
{
"code": null,
"e": 23664,
"s": 23598,
"text": "Ravichandiran et. al, Hands-On Reinforcement Learning with Python"
}
] |
- GeeksforGeeks
|
26 Dec, 2018
Assume that to spell check a large file, 820,000,000 instructions are needed. The instructions in the program are broken down into 4 different classes, and each class requires N clock cycles to execute. Specific information is given in the table below. (Here, N is the same as in the MIPS multi-cycle datapath discussed in class.)
If the total execution time for this program is found to be 1.57 seconds, what is the clock cycle time of the computer on which it was run?
(A) 1.6 GHz(B) 1.82 GHz(C) 2.16 GHz(D) 3.32 GHzAnswer: (C)Explanation: We can apply the CPU time formula: CPU time = IC x CPIavg x CC Time, and solve for CC Time.820,000,000 * {3*(150,000,000 / 820,000,000) + 4*(185,000,000 / 820,000,000) + 5*(260,000,000 / 820,000,000) + 4*(225,000,000 / 820,000,000)} × N = 1.57s
Thus, the clock cycle time is 4.63 x 10-10s.
Which is equal to,
1 / (4.63 x 10-10)
= 0.215982721 x 1010
= 2.15982721 x 109 cycle per second
= 2.16 GHz
This is a 2.16 GHz machine.
So, option (C) is correct.Quiz of this Question
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
Infosys DSE Interview Experience | On-Campus 2021
HackWithInfy - A Coding Competition by Infosys
|
[
{
"code": null,
"e": 27219,
"s": 27191,
"text": "\n26 Dec, 2018"
},
{
"code": null,
"e": 27550,
"s": 27219,
"text": "Assume that to spell check a large file, 820,000,000 instructions are needed. The instructions in the program are broken down into 4 different classes, and each class requires N clock cycles to execute. Specific information is given in the table below. (Here, N is the same as in the MIPS multi-cycle datapath discussed in class.)"
},
{
"code": null,
"e": 27690,
"s": 27550,
"text": "If the total execution time for this program is found to be 1.57 seconds, what is the clock cycle time of the computer on which it was run?"
},
{
"code": null,
"e": 28006,
"s": 27690,
"text": "(A) 1.6 GHz(B) 1.82 GHz(C) 2.16 GHz(D) 3.32 GHzAnswer: (C)Explanation: We can apply the CPU time formula: CPU time = IC x CPIavg x CC Time, and solve for CC Time.820,000,000 * {3*(150,000,000 / 820,000,000) + 4*(185,000,000 / 820,000,000) + 5*(260,000,000 / 820,000,000) + 4*(225,000,000 / 820,000,000)} × N = 1.57s"
},
{
"code": null,
"e": 28051,
"s": 28006,
"text": "Thus, the clock cycle time is 4.63 x 10-10s."
},
{
"code": null,
"e": 28070,
"s": 28051,
"text": "Which is equal to,"
},
{
"code": null,
"e": 28159,
"s": 28070,
"text": "1 / (4.63 x 10-10) \n= 0.215982721 x 1010\n= 2.15982721 x 109 cycle per second\n= 2.16 GHz "
},
{
"code": null,
"e": 28187,
"s": 28159,
"text": "This is a 2.16 GHz machine."
},
{
"code": null,
"e": 28235,
"s": 28187,
"text": "So, option (C) is correct.Quiz of this Question"
},
{
"code": null,
"e": 28333,
"s": 28235,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 28342,
"s": 28333,
"text": "Comments"
},
{
"code": null,
"e": 28355,
"s": 28342,
"text": "Old Comments"
},
{
"code": null,
"e": 28408,
"s": 28355,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 28467,
"s": 28408,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 28528,
"s": 28467,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28566,
"s": 28528,
"text": "Array of Objects in C++ with Examples"
},
{
"code": null,
"e": 28628,
"s": 28566,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 28669,
"s": 28628,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 28712,
"s": 28669,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 28748,
"s": 28712,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 28798,
"s": 28748,
"text": "Infosys DSE Interview Experience | On-Campus 2021"
}
] |
Concrete Exceptions in Python
|
There are some common exceptions in python. These exceptions are usually raised in different programs. These may raise by the programmer explicitly, or the python interpreter can raise these type of exceptions implicitly. Some of these exceptions are −
The AssertionError may raise, when an assert statement fails. In python there are some, we can also set some assert statement in our code. The assert statement always must be true. if the condition fails, it will raise AssertionError.
class MyClass:
def __init__(self, x):
self.x = x
assert self.x > 50
myObj = MyClass(5)
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-21-71785acdf821> in <module>()
4 assert self.x > 50
5
----> 6 myObj = MyClass(5)
<ipython-input-21-71785acdf821> in __init__(self, x)
2 def __init__(self, x):
3 self.x = x
----> 4 assert self.x > 50
5
6 myObj = MyClass(5)
AssertionError:
The attribute error may raise, when we will try to access some attribute of a class, but it is not present in it.
class point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def getpoint(self):
print('x= ' + str(self.x))
print('y= ' + str(self.y))
print('z= ' + str(self.z))
pt = point(10, 20)
pt.getpoint()
x= 10
y= 20
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-15-f64eb52b2192> in <module>()
10
11 pt = point(10, 20)
---> 12 pt.getpoint()
<ipython-input-15-f64eb52b2192> in getpoint(self)
7 print('x= ' + str(self.x))
8 print('y= ' + str(self.y))
----> 9 print('z= ' + str(self.z))
10
11 pt = point(10, 20)
AttributeError: 'point' object has no attribute 'z'
The ImportError may occur when the import statement is facing some problem to import some module. It can also be raised, when the package name to a from statement is correct, but there is no module found as specified name.
from math import abcd def __init__(self, x=0, y=0):
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-23-ff4519a07c77> in <module>()
----> 1 from math import abcd
ImportError: cannot import name 'abcd'
It is a subclass of the ImportError. When a module is not located, this error may raise. It can also be raised when None is found in sys.modules.
import abcd
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-24-7b45aaa048eb> in <module>()
----> 1 import abcd
ModuleNotFoundError: No module named 'abcd'
The index error may raise when the subscript of a sequence (List, Tuple, Set etc) is out of range.
myList = [10, 20, 30, 40]
print(str(myList[5]))
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-29-a86bd85b04c9> in <module>()
1 myList = [10, 20, 30, 40]
----> 2 print(str(myList[5]))
IndexError: list index out of range
The RecursionError is a runtime error. When the maximum recursion depth is exceeded, then it will raised.
def myFunction():
myFunction()
myFunction()
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-39-8a59e0fb982f> in <module>()
2 myFunction()
3
----> 4 myFunction()
<ipython-input-39-8a59e0fb982f> in myFunction()
1 def myFunction():
----> 2 myFunction()
3
4 myFunction()
... last 1 frames repeated, from the frame below ...
<ipython-input-39-8a59e0fb982f> in myFunction()
1 def myFunction():
----> 2 myFunction()
3
4 myFunction()
RecursionError: maximum recursion depth exceeded
In python, we can get the StopIteration error by the inbuilt method called next(). When one iterator has no further element, then the next() method will raise the StopIteration error.
myList = [10, 20, 30, 40]
myIter = iter(myList)
while True:
print(next(myIter))
10
20
30
40
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-42-e608e2162645> in <module>()
2 myIter = iter(myList)
3 while True:
----> 4 print(next(myIter))
StopIteration:
When there are some invalid indentation in the python code, it will raise this kind of errors. It inherits the SyntaxError class of python.
for i in range(10):
print("The value of i: " + str(i))
File "<ipython-input-44-d436d50bbdc8>", line 2
print("The value of i: " + str(i))
^
IndentationError: expected an indented block
The TypeError may occur when an operation is performed on an object of inappropriate type. For example, if we provide a floating point number in array index, it will return a TypeError.
muList = [10, 20, 30, 40]
print(myList[1.25])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-46-e0a2a05cd4d4> in <module>()
1 muList = [10, 20, 30, 40]
----> 2 print(myList[1.25])
TypeError: list indices must be integers or slices, not float
When there is a situation where the denominator is 0 (zero) for a division problem, it will raise ZeroDivisionError.
print(5/0)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-48-fad870a50e27> in <module>()
----> 1 print(5/0)
ZeroDivisionError: division by zero
|
[
{
"code": null,
"e": 1316,
"s": 1062,
"text": "There are some common exceptions in python. These exceptions are usually raised in different programs. These may raise by the programmer explicitly, or the python interpreter can raise these type of exceptions implicitly. Some of these exceptions are − "
},
{
"code": null,
"e": 1551,
"s": 1316,
"text": "The AssertionError may raise, when an assert statement fails. In python there are some, we can also set some assert statement in our code. The assert statement always must be true. if the condition fails, it will raise AssertionError."
},
{
"code": null,
"e": 1654,
"s": 1551,
"text": "class MyClass:\n def __init__(self, x):\n self.x = x\n assert self.x > 50\n myObj = MyClass(5)"
},
{
"code": null,
"e": 2101,
"s": 1654,
"text": "---------------------------------------------------------------------------\nAssertionError Traceback (most recent call last)\n<ipython-input-21-71785acdf821> in <module>()\n 4 assert self.x > 50\n 5 \n----> 6 myObj = MyClass(5)\n\n<ipython-input-21-71785acdf821> in __init__(self, x)\n 2 def __init__(self, x):\n 3 self.x = x\n----> 4 assert self.x > 50\n 5 \n 6 myObj = MyClass(5)\n\nAssertionError:\n"
},
{
"code": null,
"e": 2215,
"s": 2101,
"text": "The attribute error may raise, when we will try to access some attribute of a class, but it is not present in it."
},
{
"code": null,
"e": 2459,
"s": 2215,
"text": "class point:\n def __init__(self, x=0, y=0):\n self.x = x\n self.y = y\n \n def getpoint(self):\n print('x= ' + str(self.x))\n print('y= ' + str(self.y))\n print('z= ' + str(self.z))\npt = point(10, 20)\npt.getpoint()"
},
{
"code": null,
"e": 2970,
"s": 2459,
"text": "x= 10\ny= 20\n---------------------------------------------------------------------------\nAttributeError Traceback (most recent call last)\n<ipython-input-15-f64eb52b2192> in <module>()\n 10 \n 11 pt = point(10, 20)\n---> 12 pt.getpoint()\n\n<ipython-input-15-f64eb52b2192> in getpoint(self)\n 7 print('x= ' + str(self.x))\n 8 print('y= ' + str(self.y))\n----> 9 print('z= ' + str(self.z))\n 10 \n 11 pt = point(10, 20)\n\nAttributeError: 'point' object has no attribute 'z'\n"
},
{
"code": null,
"e": 3193,
"s": 2970,
"text": "The ImportError may occur when the import statement is facing some problem to import some module. It can also be raised, when the package name to a from statement is correct, but there is no module found as specified name."
},
{
"code": null,
"e": 3248,
"s": 3193,
"text": "from math import abcd def __init__(self, x=0, y=0):"
},
{
"code": null,
"e": 3487,
"s": 3248,
"text": "---------------------------------------------------------------------------\nImportError Traceback (most recent call last)\n<ipython-input-23-ff4519a07c77> in <module>()\n----> 1 from math import abcd\n\nImportError: cannot import name 'abcd'\n"
},
{
"code": null,
"e": 3633,
"s": 3487,
"text": "It is a subclass of the ImportError. When a module is not located, this error may raise. It can also be raised when None is found in sys.modules."
},
{
"code": null,
"e": 3645,
"s": 3633,
"text": "import abcd"
},
{
"code": null,
"e": 3887,
"s": 3645,
"text": "---------------------------------------------------------------------------\nModuleNotFoundError Traceback (most recent call last)\n<ipython-input-24-7b45aaa048eb> in <module>()\n----> 1 import abcd\n\nModuleNotFoundError: No module named 'abcd'\n"
},
{
"code": null,
"e": 3986,
"s": 3887,
"text": "The index error may raise when the subscript of a sequence (List, Tuple, Set etc) is out of range."
},
{
"code": null,
"e": 4034,
"s": 3986,
"text": "myList = [10, 20, 30, 40]\nprint(str(myList[5]))"
},
{
"code": null,
"e": 4303,
"s": 4034,
"text": "---------------------------------------------------------------------------\nIndexError Traceback (most recent call last)\n<ipython-input-29-a86bd85b04c9> in <module>()\n 1 myList = [10, 20, 30, 40]\n----> 2 print(str(myList[5]))\n\nIndexError: list index out of range\n"
},
{
"code": null,
"e": 4409,
"s": 4303,
"text": "The RecursionError is a runtime error. When the maximum recursion depth is exceeded, then it will raised."
},
{
"code": null,
"e": 4456,
"s": 4409,
"text": "def myFunction():\n myFunction()\nmyFunction()"
},
{
"code": null,
"e": 5047,
"s": 4456,
"text": "---------------------------------------------------------------------------\nRecursionError Traceback (most recent call last)\n<ipython-input-39-8a59e0fb982f> in <module>()\n 2 myFunction()\n 3 \n----> 4 myFunction()\n\n<ipython-input-39-8a59e0fb982f> in myFunction()\n 1 def myFunction():\n----> 2 myFunction()\n 3 \n 4 myFunction()\n\n... last 1 frames repeated, from the frame below ...\n\n<ipython-input-39-8a59e0fb982f> in myFunction()\n 1 def myFunction():\n----> 2 myFunction()\n 3 \n 4 myFunction()\n\nRecursionError: maximum recursion depth exceeded\n"
},
{
"code": null,
"e": 5231,
"s": 5047,
"text": "In python, we can get the StopIteration error by the inbuilt method called next(). When one iterator has no further element, then the next() method will raise the StopIteration error."
},
{
"code": null,
"e": 5314,
"s": 5231,
"text": "myList = [10, 20, 30, 40]\nmyIter = iter(myList)\nwhile True:\n print(next(myIter))"
},
{
"code": null,
"e": 5596,
"s": 5314,
"text": "10\n20\n30\n40\n---------------------------------------------------------------------------\nStopIteration Traceback (most recent call last)\n<ipython-input-42-e608e2162645> in <module>()\n 2 myIter = iter(myList)\n 3 while True:\n----> 4 print(next(myIter))\n\nStopIteration: \n"
},
{
"code": null,
"e": 5736,
"s": 5596,
"text": "When there are some invalid indentation in the python code, it will raise this kind of errors. It inherits the SyntaxError class of python."
},
{
"code": null,
"e": 5794,
"s": 5736,
"text": "for i in range(10):\n print(\"The value of i: \" + str(i))"
},
{
"code": null,
"e": 5936,
"s": 5794,
"text": "File \"<ipython-input-44-d436d50bbdc8>\", line 2\n print(\"The value of i: \" + str(i))\n ^\nIndentationError: expected an indented block\n"
},
{
"code": null,
"e": 6122,
"s": 5936,
"text": "The TypeError may occur when an operation is performed on an object of inappropriate type. For example, if we provide a floating point number in array index, it will return a TypeError."
},
{
"code": null,
"e": 6168,
"s": 6122,
"text": "muList = [10, 20, 30, 40]\nprint(myList[1.25])"
},
{
"code": null,
"e": 6460,
"s": 6168,
"text": "---------------------------------------------------------------------------\nTypeError Traceback (most recent call last)\n<ipython-input-46-e0a2a05cd4d4> in <module>()\n 1 muList = [10, 20, 30, 40]\n----> 2 print(myList[1.25])\n\nTypeError: list indices must be integers or slices, not float\n"
},
{
"code": null,
"e": 6577,
"s": 6460,
"text": "When there is a situation where the denominator is 0 (zero) for a division problem, it will raise ZeroDivisionError."
},
{
"code": null,
"e": 6588,
"s": 6577,
"text": "print(5/0)"
},
{
"code": null,
"e": 6820,
"s": 6588,
"text": "---------------------------------------------------------------------------\nZeroDivisionError Traceback (most recent call last)\n<ipython-input-48-fad870a50e27> in <module>()\n----> 1 print(5/0)\n\nZeroDivisionError: division by zero\n"
}
] |
How to Create Animations in Python? - GeeksforGeeks
|
14 Sep, 2021
Animations are a great way to make Visualizations more attractive and user appealing. It helps us to demonstrate Data Visualization in a Meaningful Way. Python helps us to create Create Animation Visualization using existing powerful Python libraries. Matplotlib is a very popular Data Visualisation Library and is used commonly used for graphical representation of data and also for animations using inbuilt functions.
There are two ways of Creating Animation using Matplotlib:
Using pause() function
Using FuncAnimation() function
The pause() function in the pyplot module of the matplotlib library is used to pause for interval seconds mentioned in the argument. Consider the below example in which we will create a simple linear graph using matplotlib and show Animation in it:
Create 2 arrays, X and Y, and store values from 1 to 100.
Plot X and Y using plot() function.
Add pause() function with suitable time interval
Run the program and you’ll see the animation.
Python
from matplotlib import pyplot as plt x = []y = [] for i in range(100): x.append(i) y.append(i) # Mention x and y limits to define their range plt.xlim(0, 100) plt.ylim(0, 100) # Ploting graph plt.plot(x, y, color = 'green') plt.pause(0.01) plt.show()
Output :
Similarly, you can use the pause() function to create Animation in various plots.
This FuncAnimation() Function does not create the Animation on its own, but it creates Animation from series of Graphics that we pass.
Syntax: FuncAnimation(figure, animation_function, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)
Now there are Multiple types of Animation you can make using the FuncAnimation function:
In this example, we are creating a simple linear graph that will show an animation of a Line. Similarly, using FuncAnimation, we can create many types of Animated Visual Representations. We just need to define our animation in a function and then pass it to FuncAnimation with suitable parameters.
Python
from matplotlib import pyplot as pltfrom matplotlib.animation import FuncAnimationimport numpy as np x = []y = [] figure, ax = plt.subplots() # Setting limits for x and y axisax.set_xlim(0, 100)ax.set_ylim(0, 12) # Since plotting a single graphline, = ax.plot(0, 0) def animation_function(i): x.append(i * 15) y.append(i) line.set_xdata(x) line.set_ydata(y) return line, animation = FuncAnimation(figure, func = animation_function, frames = np.arange(0, 10, 0.1), interval = 10)plt.show()
Output:
In this example, we are creating a simple Bar Chart animation that will show an animation of each bar.
Python
from matplotlib import pyplot as pltfrom matplotlib.animation import FuncAnimation, writersimport numpy as np fig = plt.figure(figsize = (7,5))axes = fig.add_subplot(1,1,1)axes.set_ylim(0, 300)palette = ['blue', 'red', 'green', 'darkorange', 'maroon', 'black'] y1, y2, y3, y4, y5, y6 = [], [], [], [], [], [] def animation_function(i): y1 = i y2 = 5 * i y3 = 3 * i y4 = 2 * i y5 = 6 * i y6 = 3 * i plt.xlabel("Country") plt.ylabel("GDP of Country") plt.bar(["India", "China", "Germany", "USA", "Canada", "UK"], [y1, y2, y3, y4, y5, y6], color = palette) plt.title("Bar Chart Animation") animation = FuncAnimation(fig, animation_function, interval = 50)plt.show()
Output:
In this example, we will Animate Scatter Plot in python using the random function. We will be Iterating through the animation_func and while iterating we will plot random values of the x and y-axis.
Python
from matplotlib import pyplot as pltfrom matplotlib.animation import FuncAnimationimport randomimport numpy as np x = []y = []colors = []fig = plt.figure(figsize=(7,5)) def animation_func(i): x.append(random.randint(0,100)) y.append(random.randint(0,100)) colors.append(np.random.rand(1)) area = random.randint(0,30) * random.randint(0,30) plt.xlim(0,100) plt.ylim(0,100) plt.scatter(x, y, c = colors, s = area, alpha = 0.5) animation = FuncAnimation(fig, animation_func, interval = 100)plt.show()
Output:
Here we will plot a Bar Chart Race using Highest Population in a city Dataset.
Different cities will have a different bar and Bar Chart race will iterate from the year 1990 up to 2018.
We selected countries from which the topmost cities would be picked from the dataset with the highest population.
Dataset can be download from here: city_populations
Python
import pandas as pdimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerfrom matplotlib.animation import FuncAnimation df = pd.read_csv('city_populations.csv', usecols=['name', 'group', 'year', 'value']) colors = dict(zip(['India','Europe','Asia', 'Latin America','Middle East', 'North America','Africa'], ['#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#aafbff', '#f7bb5f', '#eafb50'])) group_lk = df.set_index('name')['group'].to_dict() def draw_barchart(year): dff = df[df['year'].eq(year)].sort_values(by='value', ascending=True).tail(10) ax.clear() ax.barh(dff['name'], dff['value'], color=[colors[group_lk[x]] for x in dff['name']]) dx = dff['value'].max() / 200 for i, (value, name) in enumerate(zip(dff['value'], dff['name'])): ax.text(value-dx, i, name, size=14, weight=600, ha='right', va='bottom') ax.text(value-dx, i-.25, group_lk[name], size=10, color='#444444', ha='right', va='baseline') ax.text(value+dx, i, f'{value:,.0f}', size=14, ha='left', va='center') # polished styles ax.text(1, 0.4, year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800) ax.text(0, 1.06, 'Population (thousands)', transform=ax.transAxes, size=12, color='#777777') ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) ax.xaxis.set_ticks_position('top') ax.tick_params(axis='x', colors='#777777', labelsize=12) ax.set_yticks([]) ax.margins(0, 0.01) ax.grid(which='major', axis='x', linestyle='-') ax.set_axisbelow(True) ax.text(0, 1.12, 'The most populous cities in the world from 1500 to 2018', transform=ax.transAxes, size=24, weight=600, ha='left') ax.text(1, 0, 'by @pratapvardhan; credit @jburnmurdoch', transform=ax.transAxes, ha='right', color='#777777', bbox=dict(facecolor='white', alpha=0.8, edgecolor='white')) plt.box(False) plt.show() fig, ax = plt.subplots(figsize=(15, 8))animator = FuncAnimation(fig, draw_barchart, frames = range(1990, 2019))plt.show()
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 24348,
"s": 23927,
"text": "Animations are a great way to make Visualizations more attractive and user appealing. It helps us to demonstrate Data Visualization in a Meaningful Way. Python helps us to create Create Animation Visualization using existing powerful Python libraries. Matplotlib is a very popular Data Visualisation Library and is used commonly used for graphical representation of data and also for animations using inbuilt functions. "
},
{
"code": null,
"e": 24408,
"s": 24348,
"text": "There are two ways of Creating Animation using Matplotlib: "
},
{
"code": null,
"e": 24431,
"s": 24408,
"text": "Using pause() function"
},
{
"code": null,
"e": 24462,
"s": 24431,
"text": "Using FuncAnimation() function"
},
{
"code": null,
"e": 24711,
"s": 24462,
"text": "The pause() function in the pyplot module of the matplotlib library is used to pause for interval seconds mentioned in the argument. Consider the below example in which we will create a simple linear graph using matplotlib and show Animation in it:"
},
{
"code": null,
"e": 24769,
"s": 24711,
"text": "Create 2 arrays, X and Y, and store values from 1 to 100."
},
{
"code": null,
"e": 24805,
"s": 24769,
"text": "Plot X and Y using plot() function."
},
{
"code": null,
"e": 24854,
"s": 24805,
"text": "Add pause() function with suitable time interval"
},
{
"code": null,
"e": 24900,
"s": 24854,
"text": "Run the program and you’ll see the animation."
},
{
"code": null,
"e": 24907,
"s": 24900,
"text": "Python"
},
{
"code": "from matplotlib import pyplot as plt x = []y = [] for i in range(100): x.append(i) y.append(i) # Mention x and y limits to define their range plt.xlim(0, 100) plt.ylim(0, 100) # Ploting graph plt.plot(x, y, color = 'green') plt.pause(0.01) plt.show()",
"e": 25193,
"s": 24907,
"text": null
},
{
"code": null,
"e": 25203,
"s": 25193,
"text": "Output : "
},
{
"code": null,
"e": 25285,
"s": 25203,
"text": "Similarly, you can use the pause() function to create Animation in various plots."
},
{
"code": null,
"e": 25420,
"s": 25285,
"text": "This FuncAnimation() Function does not create the Animation on its own, but it creates Animation from series of Graphics that we pass."
},
{
"code": null,
"e": 25564,
"s": 25420,
"text": "Syntax: FuncAnimation(figure, animation_function, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)"
},
{
"code": null,
"e": 25654,
"s": 25564,
"text": "Now there are Multiple types of Animation you can make using the FuncAnimation function: "
},
{
"code": null,
"e": 25952,
"s": 25654,
"text": "In this example, we are creating a simple linear graph that will show an animation of a Line. Similarly, using FuncAnimation, we can create many types of Animated Visual Representations. We just need to define our animation in a function and then pass it to FuncAnimation with suitable parameters."
},
{
"code": null,
"e": 25959,
"s": 25952,
"text": "Python"
},
{
"code": "from matplotlib import pyplot as pltfrom matplotlib.animation import FuncAnimationimport numpy as np x = []y = [] figure, ax = plt.subplots() # Setting limits for x and y axisax.set_xlim(0, 100)ax.set_ylim(0, 12) # Since plotting a single graphline, = ax.plot(0, 0) def animation_function(i): x.append(i * 15) y.append(i) line.set_xdata(x) line.set_ydata(y) return line, animation = FuncAnimation(figure, func = animation_function, frames = np.arange(0, 10, 0.1), interval = 10)plt.show()",
"e": 26549,
"s": 25959,
"text": null
},
{
"code": null,
"e": 26561,
"s": 26549,
"text": " Output:"
},
{
"code": null,
"e": 26665,
"s": 26561,
"text": "In this example, we are creating a simple Bar Chart animation that will show an animation of each bar. "
},
{
"code": null,
"e": 26672,
"s": 26665,
"text": "Python"
},
{
"code": "from matplotlib import pyplot as pltfrom matplotlib.animation import FuncAnimation, writersimport numpy as np fig = plt.figure(figsize = (7,5))axes = fig.add_subplot(1,1,1)axes.set_ylim(0, 300)palette = ['blue', 'red', 'green', 'darkorange', 'maroon', 'black'] y1, y2, y3, y4, y5, y6 = [], [], [], [], [], [] def animation_function(i): y1 = i y2 = 5 * i y3 = 3 * i y4 = 2 * i y5 = 6 * i y6 = 3 * i plt.xlabel(\"Country\") plt.ylabel(\"GDP of Country\") plt.bar([\"India\", \"China\", \"Germany\", \"USA\", \"Canada\", \"UK\"], [y1, y2, y3, y4, y5, y6], color = palette) plt.title(\"Bar Chart Animation\") animation = FuncAnimation(fig, animation_function, interval = 50)plt.show()",
"e": 27447,
"s": 26672,
"text": null
},
{
"code": null,
"e": 27455,
"s": 27447,
"text": "Output:"
},
{
"code": null,
"e": 27654,
"s": 27455,
"text": "In this example, we will Animate Scatter Plot in python using the random function. We will be Iterating through the animation_func and while iterating we will plot random values of the x and y-axis."
},
{
"code": null,
"e": 27661,
"s": 27654,
"text": "Python"
},
{
"code": "from matplotlib import pyplot as pltfrom matplotlib.animation import FuncAnimationimport randomimport numpy as np x = []y = []colors = []fig = plt.figure(figsize=(7,5)) def animation_func(i): x.append(random.randint(0,100)) y.append(random.randint(0,100)) colors.append(np.random.rand(1)) area = random.randint(0,30) * random.randint(0,30) plt.xlim(0,100) plt.ylim(0,100) plt.scatter(x, y, c = colors, s = area, alpha = 0.5) animation = FuncAnimation(fig, animation_func, interval = 100)plt.show()",
"e": 28209,
"s": 27661,
"text": null
},
{
"code": null,
"e": 28217,
"s": 28209,
"text": "Output:"
},
{
"code": null,
"e": 28296,
"s": 28217,
"text": "Here we will plot a Bar Chart Race using Highest Population in a city Dataset."
},
{
"code": null,
"e": 28402,
"s": 28296,
"text": "Different cities will have a different bar and Bar Chart race will iterate from the year 1990 up to 2018."
},
{
"code": null,
"e": 28516,
"s": 28402,
"text": "We selected countries from which the topmost cities would be picked from the dataset with the highest population."
},
{
"code": null,
"e": 28568,
"s": 28516,
"text": "Dataset can be download from here: city_populations"
},
{
"code": null,
"e": 28575,
"s": 28568,
"text": "Python"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerfrom matplotlib.animation import FuncAnimation df = pd.read_csv('city_populations.csv', usecols=['name', 'group', 'year', 'value']) colors = dict(zip(['India','Europe','Asia', 'Latin America','Middle East', 'North America','Africa'], ['#adb0ff', '#ffb3ff', '#90d595', '#e48381', '#aafbff', '#f7bb5f', '#eafb50'])) group_lk = df.set_index('name')['group'].to_dict() def draw_barchart(year): dff = df[df['year'].eq(year)].sort_values(by='value', ascending=True).tail(10) ax.clear() ax.barh(dff['name'], dff['value'], color=[colors[group_lk[x]] for x in dff['name']]) dx = dff['value'].max() / 200 for i, (value, name) in enumerate(zip(dff['value'], dff['name'])): ax.text(value-dx, i, name, size=14, weight=600, ha='right', va='bottom') ax.text(value-dx, i-.25, group_lk[name], size=10, color='#444444', ha='right', va='baseline') ax.text(value+dx, i, f'{value:,.0f}', size=14, ha='left', va='center') # polished styles ax.text(1, 0.4, year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800) ax.text(0, 1.06, 'Population (thousands)', transform=ax.transAxes, size=12, color='#777777') ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) ax.xaxis.set_ticks_position('top') ax.tick_params(axis='x', colors='#777777', labelsize=12) ax.set_yticks([]) ax.margins(0, 0.01) ax.grid(which='major', axis='x', linestyle='-') ax.set_axisbelow(True) ax.text(0, 1.12, 'The most populous cities in the world from 1500 to 2018', transform=ax.transAxes, size=24, weight=600, ha='left') ax.text(1, 0, 'by @pratapvardhan; credit @jburnmurdoch', transform=ax.transAxes, ha='right', color='#777777', bbox=dict(facecolor='white', alpha=0.8, edgecolor='white')) plt.box(False) plt.show() fig, ax = plt.subplots(figsize=(15, 8))animator = FuncAnimation(fig, draw_barchart, frames = range(1990, 2019))plt.show()",
"e": 31007,
"s": 28575,
"text": null
},
{
"code": null,
"e": 31015,
"s": 31007,
"text": "Output:"
},
{
"code": null,
"e": 31022,
"s": 31015,
"text": "Picked"
},
{
"code": null,
"e": 31040,
"s": 31022,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 31047,
"s": 31040,
"text": "Python"
},
{
"code": null,
"e": 31145,
"s": 31047,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31154,
"s": 31145,
"text": "Comments"
},
{
"code": null,
"e": 31167,
"s": 31154,
"text": "Old Comments"
},
{
"code": null,
"e": 31199,
"s": 31167,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31255,
"s": 31199,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 31297,
"s": 31255,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 31339,
"s": 31297,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 31375,
"s": 31339,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 31397,
"s": 31375,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 31436,
"s": 31397,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 31463,
"s": 31436,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 31494,
"s": 31463,
"text": "Python | os.path.join() method"
}
] |
Matplotlib.pyplot.psd() in Python - GeeksforGeeks
|
21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The csd() function in pyplot module of matplotlib library is used to plot the cross-spectral density.
Syntax: matplotlib.pyplot.csd(x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, return_line=None, \*, data=None, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
x: This parameter is a sequence of data.
Fs : This parameter is a scalar. Its default value is 2.
window: This parameter take a data segment as an argument and return the windowed version of the segment. Its default value is window_hanning()
sides: This parameter specifies which sides of the spectrum to return. This can have following values : ‘default’, ‘onesided’ and ‘twosided’.
pad_to : This parameter contains the integer value to which the data segment is padded.
NFFT : This parameter contains the number of data points used in each block for the FFT.
detrend : This parameter contains the function applied to each segment before fft-ing, designed to remove the mean or linear trend {‘none’, ‘mean’, ‘linear’}.
scale_by_freq : This parameter is allows for integration over the returned frequency values.
noverlap : This parameter is the number of points of overlap between blocks.
Fc : This parameter is the center frequency of x.
return_line : This parameter include the line object plotted in the returned values.
Returns: This returns the following:
Pxx:This returns the values for the power spectrum P_{xx} before scaling.
freqs :This returns the frequencies for the elements in Pxx.
line :This returns the line created by this function.
The resultant is (Pxx, freqs, line)
Below examples illustrate the matplotlib.pyplot.psd() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt dt = 0.01t = np.arange(0, 30, dt)nse1 = np.random.randn(len(t)) s1 = 1.5 * np.sin(2 * np.pi * 10 * t) + nse1 + np.cos(np.pi * t) plt.psd(s1**2, 512, 1./dt, color ="green")plt.xlabel('Frequency')plt.ylabel('PSD(db)') plt.suptitle('matplotlib.pyplot.psd() function \Example', fontweight ="bold") plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt dt = 0.01t = np.arange(0, 30, dt)nse1 = np.random.randn(len(t))r = np.exp(-t / 0.05) cnse1 = np.convolve(nse1, r, mode ='same')*dt s1 = np.cos(np.pi * t) + cnse1 + np.sin(2 * np.pi * 10 * t) plt.psd(s1, 2**14, dt)plt.ylabel('PSD(db)')plt.xlabel('Frequency')plt.title('matplotlib.pyplot.psd() Example\n', fontsize = 14, fontweight ='bold') plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24382,
"s": 24354,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 24577,
"s": 24382,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface."
},
{
"code": null,
"e": 24679,
"s": 24577,
"text": "The csd() function in pyplot module of matplotlib library is used to plot the cross-spectral density."
},
{
"code": null,
"e": 24876,
"s": 24679,
"text": "Syntax: matplotlib.pyplot.csd(x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, return_line=None, \\*, data=None, \\*\\*kwargs)"
},
{
"code": null,
"e": 24958,
"s": 24876,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 24999,
"s": 24958,
"text": "x: This parameter is a sequence of data."
},
{
"code": null,
"e": 25056,
"s": 24999,
"text": "Fs : This parameter is a scalar. Its default value is 2."
},
{
"code": null,
"e": 25200,
"s": 25056,
"text": "window: This parameter take a data segment as an argument and return the windowed version of the segment. Its default value is window_hanning()"
},
{
"code": null,
"e": 25342,
"s": 25200,
"text": "sides: This parameter specifies which sides of the spectrum to return. This can have following values : ‘default’, ‘onesided’ and ‘twosided’."
},
{
"code": null,
"e": 25430,
"s": 25342,
"text": "pad_to : This parameter contains the integer value to which the data segment is padded."
},
{
"code": null,
"e": 25519,
"s": 25430,
"text": "NFFT : This parameter contains the number of data points used in each block for the FFT."
},
{
"code": null,
"e": 25678,
"s": 25519,
"text": "detrend : This parameter contains the function applied to each segment before fft-ing, designed to remove the mean or linear trend {‘none’, ‘mean’, ‘linear’}."
},
{
"code": null,
"e": 25771,
"s": 25678,
"text": "scale_by_freq : This parameter is allows for integration over the returned frequency values."
},
{
"code": null,
"e": 25848,
"s": 25771,
"text": "noverlap : This parameter is the number of points of overlap between blocks."
},
{
"code": null,
"e": 25898,
"s": 25848,
"text": "Fc : This parameter is the center frequency of x."
},
{
"code": null,
"e": 25983,
"s": 25898,
"text": "return_line : This parameter include the line object plotted in the returned values."
},
{
"code": null,
"e": 26020,
"s": 25983,
"text": "Returns: This returns the following:"
},
{
"code": null,
"e": 26094,
"s": 26020,
"text": "Pxx:This returns the values for the power spectrum P_{xx} before scaling."
},
{
"code": null,
"e": 26155,
"s": 26094,
"text": "freqs :This returns the frequencies for the elements in Pxx."
},
{
"code": null,
"e": 26209,
"s": 26155,
"text": "line :This returns the line created by this function."
},
{
"code": null,
"e": 26245,
"s": 26209,
"text": "The resultant is (Pxx, freqs, line)"
},
{
"code": null,
"e": 26330,
"s": 26245,
"text": "Below examples illustrate the matplotlib.pyplot.psd() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 26342,
"s": 26330,
"text": "Example #1:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt dt = 0.01t = np.arange(0, 30, dt)nse1 = np.random.randn(len(t)) s1 = 1.5 * np.sin(2 * np.pi * 10 * t) + nse1 + np.cos(np.pi * t) plt.psd(s1**2, 512, 1./dt, color =\"green\")plt.xlabel('Frequency')plt.ylabel('PSD(db)') plt.suptitle('matplotlib.pyplot.psd() function \\Example', fontweight =\"bold\") plt.show()",
"e": 26747,
"s": 26342,
"text": null
},
{
"code": null,
"e": 26755,
"s": 26747,
"text": "Output:"
},
{
"code": null,
"e": 26767,
"s": 26755,
"text": "Example #2:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt dt = 0.01t = np.arange(0, 30, dt)nse1 = np.random.randn(len(t))r = np.exp(-t / 0.05) cnse1 = np.convolve(nse1, r, mode ='same')*dt s1 = np.cos(np.pi * t) + cnse1 + np.sin(2 * np.pi * 10 * t) plt.psd(s1, 2**14, dt)plt.ylabel('PSD(db)')plt.xlabel('Frequency')plt.title('matplotlib.pyplot.psd() Example\\n', fontsize = 14, fontweight ='bold') plt.show()",
"e": 27238,
"s": 26767,
"text": null
},
{
"code": null,
"e": 27246,
"s": 27238,
"text": "Output:"
},
{
"code": null,
"e": 27264,
"s": 27246,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27271,
"s": 27264,
"text": "Python"
},
{
"code": null,
"e": 27369,
"s": 27271,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27378,
"s": 27369,
"text": "Comments"
},
{
"code": null,
"e": 27391,
"s": 27378,
"text": "Old Comments"
},
{
"code": null,
"e": 27409,
"s": 27391,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27441,
"s": 27409,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27476,
"s": 27441,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27498,
"s": 27476,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27528,
"s": 27498,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27570,
"s": 27528,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27613,
"s": 27570,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27650,
"s": 27613,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27676,
"s": 27650,
"text": "Python String | replace()"
}
] |
How to align buttons in Card footer in Bootstrap ? - GeeksforGeeks
|
30 Jul, 2019
Alignment of buttons in the Card footer is so much easy when you are familiar with the float element. There is another way to align the left or right wherever you want to place the button in the footer of the card. In this article, you will learn how to align buttons in the footer section of a Bootstrap Card. Bootstrap’s cards provide a flexible and extensible content container with multiple variants and options.Structure of Bootstrap card:
Card Image
Card BodyCard TitleCard Text
Card Title
Card Text
Card FooterLeft ButtonCenter ButtonRight Button
Left Button
Center Button
Right Button
Example: Use float-left, float-right and float-right to align the buttons on the card.
<!DOCTYPE html><html lang="en"> <head> <title> How to align buttons in Card footer in Bootstrap ? </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> </head> <body> <!-- Create a card --> <div class="card" style="width: 22rem; margin:0 auto;"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title" style="color:green"> Card title </h5> <p class="card-text" style="color:green;"> This is just a simple card text inside card body </p> <p class="card-text" style="color:green;"> Welcome to geeksforgeeks </p> </div> <div class="card-footer text-center"> <p style="color:green;">We are inside card footer</p> <button class="btn btn-primary btn-sm float-left" id="left" style="color:white"> Left Button </button> <button class="btn btn-warning btn-sm" id="center" style="color:white"> Center Button </button> <button class="btn btn-danger btn-sm float-right" id="right" style="color:white"> Right Button </button> </div> </div></body> </html>
Output:
Example 2:
<!DOCTYPE html><html lang="en"> <head> <title> How to align buttons in Card footer in Bootstrap ? </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="card" style="width: 22rem; margin:0 auto;"> <div class="card-header text-success text-center"> <h3>GeekforGeeks</h3> </div> <div class="card-body text-center"> <h4 class="card-title ">Practice</h4> <p class="card-text"> Practice for Computer Science coding interview </p> <a href="#" class="btn btn-primary">Login/Sign UP</a> </div> <div class="card-footer text-center"> <button class="btn btn-theme float-left" type="button">< </button> <button class="btn btn-theme" type="button">+ </button> <button class="btn btn-theme float-right" type="button">> </button> </div> </div></body> </html>
Output:
Picked
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to set Bootstrap Timepicker using datetimepicker library ?
How to Show Images on Click using HTML ?
How to pass data into a bootstrap modal?
How to change the background color of the active nav-item?
Difference between Bootstrap 4 and Bootstrap 5
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Express.js express.Router() Function
|
[
{
"code": null,
"e": 24544,
"s": 24516,
"text": "\n30 Jul, 2019"
},
{
"code": null,
"e": 24989,
"s": 24544,
"text": "Alignment of buttons in the Card footer is so much easy when you are familiar with the float element. There is another way to align the left or right wherever you want to place the button in the footer of the card. In this article, you will learn how to align buttons in the footer section of a Bootstrap Card. Bootstrap’s cards provide a flexible and extensible content container with multiple variants and options.Structure of Bootstrap card:"
},
{
"code": null,
"e": 25000,
"s": 24989,
"text": "Card Image"
},
{
"code": null,
"e": 25029,
"s": 25000,
"text": "Card BodyCard TitleCard Text"
},
{
"code": null,
"e": 25040,
"s": 25029,
"text": "Card Title"
},
{
"code": null,
"e": 25050,
"s": 25040,
"text": "Card Text"
},
{
"code": null,
"e": 25098,
"s": 25050,
"text": "Card FooterLeft ButtonCenter ButtonRight Button"
},
{
"code": null,
"e": 25110,
"s": 25098,
"text": "Left Button"
},
{
"code": null,
"e": 25124,
"s": 25110,
"text": "Center Button"
},
{
"code": null,
"e": 25137,
"s": 25124,
"text": "Right Button"
},
{
"code": null,
"e": 25224,
"s": 25137,
"text": "Example: Use float-left, float-right and float-right to align the buttons on the card."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to align buttons in Card footer in Bootstrap ? </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src= \"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src= \"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> </head> <body> <!-- Create a card --> <div class=\"card\" style=\"width: 22rem; margin:0 auto;\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png\" alt=\"Card image cap\"> <div class=\"card-body\"> <h5 class=\"card-title\" style=\"color:green\"> Card title </h5> <p class=\"card-text\" style=\"color:green;\"> This is just a simple card text inside card body </p> <p class=\"card-text\" style=\"color:green;\"> Welcome to geeksforgeeks </p> </div> <div class=\"card-footer text-center\"> <p style=\"color:green;\">We are inside card footer</p> <button class=\"btn btn-primary btn-sm float-left\" id=\"left\" style=\"color:white\"> Left Button </button> <button class=\"btn btn-warning btn-sm\" id=\"center\" style=\"color:white\"> Center Button </button> <button class=\"btn btn-danger btn-sm float-right\" id=\"right\" style=\"color:white\"> Right Button </button> </div> </div></body> </html>",
"e": 27301,
"s": 25224,
"text": null
},
{
"code": null,
"e": 27309,
"s": 27301,
"text": "Output:"
},
{
"code": null,
"e": 27320,
"s": 27309,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to align buttons in Card footer in Bootstrap ? </title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\"href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"card\" style=\"width: 22rem; margin:0 auto;\"> <div class=\"card-header text-success text-center\"> <h3>GeekforGeeks</h3> </div> <div class=\"card-body text-center\"> <h4 class=\"card-title \">Practice</h4> <p class=\"card-text\"> Practice for Computer Science coding interview </p> <a href=\"#\" class=\"btn btn-primary\">Login/Sign UP</a> </div> <div class=\"card-footer text-center\"> <button class=\"btn btn-theme float-left\" type=\"button\">< </button> <button class=\"btn btn-theme\" type=\"button\">+ </button> <button class=\"btn btn-theme float-right\" type=\"button\">> </button> </div> </div></body> </html>",
"e": 28849,
"s": 27320,
"text": null
},
{
"code": null,
"e": 28857,
"s": 28849,
"text": "Output:"
},
{
"code": null,
"e": 28864,
"s": 28857,
"text": "Picked"
},
{
"code": null,
"e": 28874,
"s": 28864,
"text": "Bootstrap"
},
{
"code": null,
"e": 28891,
"s": 28874,
"text": "Web Technologies"
},
{
"code": null,
"e": 28918,
"s": 28891,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29016,
"s": 28918,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29025,
"s": 29016,
"text": "Comments"
},
{
"code": null,
"e": 29038,
"s": 29025,
"text": "Old Comments"
},
{
"code": null,
"e": 29101,
"s": 29038,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 29142,
"s": 29101,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 29183,
"s": 29142,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 29242,
"s": 29183,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 29289,
"s": 29242,
"text": "Difference between Bootstrap 4 and Bootstrap 5"
},
{
"code": null,
"e": 29322,
"s": 29289,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29365,
"s": 29322,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29427,
"s": 29365,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29477,
"s": 29427,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
ES6 - Array Method filter()
|
filter() method creates a new array with all elements that pass the test implemented by the provided function.
array.filter(callback[, thisObject]);
callback − Function to test for each element.
callback − Function to test for each element.
thisObject − Object to use as this when executing callback.
thisObject − Object to use as this when executing callback.
Returns created array.
function isBigEnough(element, index, array) {
return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].filter(isBigEnough);
console.log("Test Value : " + passed );
Test Value :12,130,44
32 Lectures
3.5 hours
Sharad Kumar
40 Lectures
5 hours
Richa Maheshwari
16 Lectures
1 hours
Anadi Sharma
50 Lectures
6.5 hours
Gowthami Swarna
14 Lectures
1 hours
Deepti Trivedi
31 Lectures
1.5 hours
Shweta
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2388,
"s": 2277,
"text": "filter() method creates a new array with all elements that pass the test implemented by the provided function."
},
{
"code": null,
"e": 2428,
"s": 2388,
"text": "array.filter(callback[, thisObject]); \n"
},
{
"code": null,
"e": 2474,
"s": 2428,
"text": "callback − Function to test for each element."
},
{
"code": null,
"e": 2520,
"s": 2474,
"text": "callback − Function to test for each element."
},
{
"code": null,
"e": 2580,
"s": 2520,
"text": "thisObject − Object to use as this when executing callback."
},
{
"code": null,
"e": 2640,
"s": 2580,
"text": "thisObject − Object to use as this when executing callback."
},
{
"code": null,
"e": 2663,
"s": 2640,
"text": "Returns created array."
},
{
"code": null,
"e": 2838,
"s": 2663,
"text": "function isBigEnough(element, index, array) { \n return (element >= 10); \n} \nvar passed = [12, 5, 8, 130, 44].filter(isBigEnough); \nconsole.log(\"Test Value : \" + passed ); "
},
{
"code": null,
"e": 2862,
"s": 2838,
"text": "Test Value :12,130,44 \n"
},
{
"code": null,
"e": 2897,
"s": 2862,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2911,
"s": 2897,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 2944,
"s": 2911,
"text": "\n 40 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 2962,
"s": 2944,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 2995,
"s": 2962,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3009,
"s": 2995,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3044,
"s": 3009,
"text": "\n 50 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3061,
"s": 3044,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 3094,
"s": 3061,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3110,
"s": 3094,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 3145,
"s": 3110,
"text": "\n 31 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3153,
"s": 3145,
"text": " Shweta"
},
{
"code": null,
"e": 3160,
"s": 3153,
"text": " Print"
},
{
"code": null,
"e": 3171,
"s": 3160,
"text": " Add Notes"
}
] |
Shallow copy vs Deep copy in Pandas Series - GeeksforGeeks
|
21 Sep, 2021
The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object’s indices and data and there are two ways to do so, namely Shallow Copy and Deep Copy.
These operations are done with the help of the library functions pandas.Series.copy(deep=False) for shallow copy and pandas.Series.copy(deep=True) for deep copy in Series.
Now, let’s understand what shallow copying is.
When a shallow copy of a Series or Series object is created, it doesn’t copy the indices and the data of the original object but it simply copies the references to its indices and data. As a result of which, a change made to one is reflected in the other one.
It refers to constructing a new collection object and then populating it with references to the child objects found in the original. The copying process does not recurse and therefore won’t create copies of the child objects themselves.
Example:
Python3
# program to depict shallow copy# in pandas series # import moduleimport pandas as pd # assign seriesser = pd.Series(['Mandy', 'Ron', 'Jacob', 'Bayek']) # shallow copycopyser = ser.copy(deep=False) # comparing shallow copied series# and original seriesprint('\nBefore Operation:\n', copyser == ser) # assignment operationcopyser[2] = 'Geeks' # comparing shallow copied series# and original seriesprint('\nAfter Operation:\n', copyser == ser) print('\nOriginal Dataframe after operation:\n', ser)
Output:
As we can see from the output of the above program, the changes applied to the shallow copied data frame gets automatically applied to the original series.
A deep copy of a Series or a Series object has its own copy of index and data. It is a process in which the copying process occurs recursively. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In the case of deep copy, a copy of an object is copied into another object. It means that any changes made to a copy of the object do not reflect in the original object.
Example:
Python3
# program to depict deep copy# in pandas series # import moduleimport pandas as pd # assign seriesser = pd.Series(['Mandy', 'Ron', 'Jacob', 'Bayek']) # shallow copycopyser = ser.copy(deep=True) # comparing deep copied series# and original seriesprint('\nBefore Operation:\n', copyser == ser) # assignment operationcopyser[2] = 'Geeks' # comparing deep copied series# and original seriesprint('\nAfter Operation:\n', copyser == ser) print('\nOriginal Dataframe after operation:\n', ser)
Output:
Here, the data inside the original objects are not recursively copied. That is, the data inside the data of the original objects still point to the same memory unit. For example, if the data in Series object contains any mutable data then it will be shared between it and its deep copy and any modification to one will be reflected in the other one.
anikaseth98
gabaa406
manikarora059
Python pandas-series
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Iterate over a list in Python
Read a file line by line in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Stack in Python
Bar Plot in Matplotlib
|
[
{
"code": null,
"e": 24048,
"s": 24020,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 24448,
"s": 24048,
"text": "The pandas library has mainly two data structures DataFrames and Series. These data structures are internally represented with index arrays, which label the data, and data arrays, which contain the actual data. Now, when we try to copy these data structures (DataFrames and Series) we essentially copy the object’s indices and data and there are two ways to do so, namely Shallow Copy and Deep Copy."
},
{
"code": null,
"e": 24620,
"s": 24448,
"text": "These operations are done with the help of the library functions pandas.Series.copy(deep=False) for shallow copy and pandas.Series.copy(deep=True) for deep copy in Series."
},
{
"code": null,
"e": 24667,
"s": 24620,
"text": "Now, let’s understand what shallow copying is."
},
{
"code": null,
"e": 24927,
"s": 24667,
"text": "When a shallow copy of a Series or Series object is created, it doesn’t copy the indices and the data of the original object but it simply copies the references to its indices and data. As a result of which, a change made to one is reflected in the other one."
},
{
"code": null,
"e": 25165,
"s": 24927,
"text": "It refers to constructing a new collection object and then populating it with references to the child objects found in the original. The copying process does not recurse and therefore won’t create copies of the child objects themselves. "
},
{
"code": null,
"e": 25174,
"s": 25165,
"text": "Example:"
},
{
"code": null,
"e": 25182,
"s": 25174,
"text": "Python3"
},
{
"code": "# program to depict shallow copy# in pandas series # import moduleimport pandas as pd # assign seriesser = pd.Series(['Mandy', 'Ron', 'Jacob', 'Bayek']) # shallow copycopyser = ser.copy(deep=False) # comparing shallow copied series# and original seriesprint('\\nBefore Operation:\\n', copyser == ser) # assignment operationcopyser[2] = 'Geeks' # comparing shallow copied series# and original seriesprint('\\nAfter Operation:\\n', copyser == ser) print('\\nOriginal Dataframe after operation:\\n', ser)",
"e": 25681,
"s": 25182,
"text": null
},
{
"code": null,
"e": 25689,
"s": 25681,
"text": "Output:"
},
{
"code": null,
"e": 25845,
"s": 25689,
"text": "As we can see from the output of the above program, the changes applied to the shallow copied data frame gets automatically applied to the original series."
},
{
"code": null,
"e": 26304,
"s": 25845,
"text": "A deep copy of a Series or a Series object has its own copy of index and data. It is a process in which the copying process occurs recursively. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In the case of deep copy, a copy of an object is copied into another object. It means that any changes made to a copy of the object do not reflect in the original object. "
},
{
"code": null,
"e": 26313,
"s": 26304,
"text": "Example:"
},
{
"code": null,
"e": 26321,
"s": 26313,
"text": "Python3"
},
{
"code": "# program to depict deep copy# in pandas series # import moduleimport pandas as pd # assign seriesser = pd.Series(['Mandy', 'Ron', 'Jacob', 'Bayek']) # shallow copycopyser = ser.copy(deep=True) # comparing deep copied series# and original seriesprint('\\nBefore Operation:\\n', copyser == ser) # assignment operationcopyser[2] = 'Geeks' # comparing deep copied series# and original seriesprint('\\nAfter Operation:\\n', copyser == ser) print('\\nOriginal Dataframe after operation:\\n', ser)",
"e": 26810,
"s": 26321,
"text": null
},
{
"code": null,
"e": 26818,
"s": 26810,
"text": "Output:"
},
{
"code": null,
"e": 27169,
"s": 26818,
"text": "Here, the data inside the original objects are not recursively copied. That is, the data inside the data of the original objects still point to the same memory unit. For example, if the data in Series object contains any mutable data then it will be shared between it and its deep copy and any modification to one will be reflected in the other one. "
},
{
"code": null,
"e": 27181,
"s": 27169,
"text": "anikaseth98"
},
{
"code": null,
"e": 27190,
"s": 27181,
"text": "gabaa406"
},
{
"code": null,
"e": 27204,
"s": 27190,
"text": "manikarora059"
},
{
"code": null,
"e": 27225,
"s": 27204,
"text": "Python pandas-series"
},
{
"code": null,
"e": 27239,
"s": 27225,
"text": "Python-pandas"
},
{
"code": null,
"e": 27263,
"s": 27239,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27270,
"s": 27263,
"text": "Python"
},
{
"code": null,
"e": 27289,
"s": 27270,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27387,
"s": 27289,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27396,
"s": 27387,
"text": "Comments"
},
{
"code": null,
"e": 27409,
"s": 27396,
"text": "Old Comments"
},
{
"code": null,
"e": 27427,
"s": 27409,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27449,
"s": 27427,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27479,
"s": 27449,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27514,
"s": 27479,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27535,
"s": 27514,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 27577,
"s": 27535,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27602,
"s": 27577,
"text": "sum() function in Python"
},
{
"code": null,
"e": 27634,
"s": 27602,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27650,
"s": 27634,
"text": "Stack in Python"
}
] |
How to sort date in excel using Pandas? - GeeksforGeeks
|
05 Sep, 2020
In these articles, We will discuss how to import an excel file in a single Dataframe and sort the Date in a given column on. Suppose our Excel file looks like these:
sample_date.xlsx
To get the excel file used click here.
Approach :
Import Pandas module
Make DataFrame from Excel file
sort the date column with DataFrame.sort_value() function
Display the Final DataFrame
Step 1: Importing pandas module and making DataFrame form excel.
Python3
# import moduleimport pandas as pd # making data frame from excel filedf = pd.read_excel('excel_work\sample_date.xlsx') print("Original DataFrame")df
Output :
Step 2: Sorting date with DataFrame.sort_value() function.
Python3
# sorting date with sort_value() functionFinal_result = df.sort_values('Joining Date') print(" Sorted Date DataFrame")Final_result
Output :
Python pandas-dataFrame-methods
Python pandas-io
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 24067,
"s": 23901,
"text": "In these articles, We will discuss how to import an excel file in a single Dataframe and sort the Date in a given column on. Suppose our Excel file looks like these:"
},
{
"code": null,
"e": 24084,
"s": 24067,
"text": "sample_date.xlsx"
},
{
"code": null,
"e": 24123,
"s": 24084,
"text": "To get the excel file used click here."
},
{
"code": null,
"e": 24134,
"s": 24123,
"text": "Approach :"
},
{
"code": null,
"e": 24155,
"s": 24134,
"text": "Import Pandas module"
},
{
"code": null,
"e": 24186,
"s": 24155,
"text": "Make DataFrame from Excel file"
},
{
"code": null,
"e": 24244,
"s": 24186,
"text": "sort the date column with DataFrame.sort_value() function"
},
{
"code": null,
"e": 24272,
"s": 24244,
"text": "Display the Final DataFrame"
},
{
"code": null,
"e": 24337,
"s": 24272,
"text": "Step 1: Importing pandas module and making DataFrame form excel."
},
{
"code": null,
"e": 24345,
"s": 24337,
"text": "Python3"
},
{
"code": "# import moduleimport pandas as pd # making data frame from excel filedf = pd.read_excel('excel_work\\sample_date.xlsx') print(\"Original DataFrame\")df",
"e": 24497,
"s": 24345,
"text": null
},
{
"code": null,
"e": 24506,
"s": 24497,
"text": "Output :"
},
{
"code": null,
"e": 24565,
"s": 24506,
"text": "Step 2: Sorting date with DataFrame.sort_value() function."
},
{
"code": null,
"e": 24573,
"s": 24565,
"text": "Python3"
},
{
"code": "# sorting date with sort_value() functionFinal_result = df.sort_values('Joining Date') print(\" Sorted Date DataFrame\")Final_result",
"e": 24705,
"s": 24573,
"text": null
},
{
"code": null,
"e": 24714,
"s": 24705,
"text": "Output :"
},
{
"code": null,
"e": 24746,
"s": 24714,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 24763,
"s": 24746,
"text": "Python pandas-io"
},
{
"code": null,
"e": 24777,
"s": 24763,
"text": "Python-pandas"
},
{
"code": null,
"e": 24784,
"s": 24777,
"text": "Python"
},
{
"code": null,
"e": 24882,
"s": 24784,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24891,
"s": 24882,
"text": "Comments"
},
{
"code": null,
"e": 24904,
"s": 24891,
"text": "Old Comments"
},
{
"code": null,
"e": 24925,
"s": 24904,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 24957,
"s": 24925,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 24980,
"s": 24957,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 25002,
"s": 24980,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25029,
"s": 25002,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 25045,
"s": 25029,
"text": "Deque in Python"
},
{
"code": null,
"e": 25087,
"s": 25045,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25143,
"s": 25087,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25188,
"s": 25143,
"text": "Python - Ways to remove duplicates from list"
}
] |
How to get property descriptors of an object in JavaScript ? - GeeksforGeeks
|
28 Nov, 2021
Here, we are going to discuss the property descriptors of an Object in JavaScript. The Object.getOwnPropertyDescriptor() method returns an object describing a specific property on a given object. A JavaScript object can be created in many ways and its properties can be called by using property descriptors for that object.
Syntax:
Object.getOwnPropertyDescriptor( obj, prop )
The Object.getOwnPropertyDescriptor() takes two parameters as input as described below:
obj: It refers to the object name whose properties are to be described.
prop: It defines the specific property in the object whose value is to be returned.
Return value: This method returns the property of the Object if it exists else it returns undefined.
Example: In the below example, an object Obj is created which consists of two properties property1 and property2. We use Object.getOwnPropertyDescriptor() property to return the attributes and values related to each property.
JavaScript
<script> // Object const Obj = { property1: "GeeksforGeeks", property2: 12 }; const descriptor1 = Object .getOwnPropertyDescriptor(Obj, 'property1'); const descriptor2 = Object .getOwnPropertyDescriptor(Obj, 'property2'); console.log(descriptor1.configurable); // expected output: true console.log(descriptor1.enumerable); // expected output: true console.log(descriptor1.value); // expected output: GeeksforGeeks console.log(descriptor2.value); // expected output: 12 </script>
Output:
true
true
GeeksforGeeks
12
A property descriptor of an object consists of some of the following attributes to define each property:
value: It is the value associated with the property that is called
writable: It indicates if the property can be changed or not. It only returns true if the property can be manipulated
enumerable: If the property is visible during enumeration of the properties of the corresponding object, then it returns true.
configurable: It indicates if the property descriptor can be changed or removed from the corresponding object.
Example: The below example describes the property attributes for property1 and property2 related to object Obj.
JavaScript
<script> const Obj = { property1: "GeeksforGeeks", property2: 12 }; const descriptor1 = Object .getOwnPropertyDescriptor(Obj, 'property1'); const descriptor2 = Object .getOwnPropertyDescriptor(Obj, 'property2'); console.log(descriptor1); console.log(descriptor2);</script>
Output:
{value: 'GeeksforGeeks', writable: true, enumerable: true, configurable: true}
configurable: true
enumerable: true
value: "GeeksforGeeks"
writable: true
[[Prototype]]: Object
{value: 12, writable: true, enumerable: true, configurable: true}
configurable: true
enumerable: true
value: 12
writable: true
[[Prototype]]: Object
JavaScript-Methods
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 25624,
"s": 25300,
"text": "Here, we are going to discuss the property descriptors of an Object in JavaScript. The Object.getOwnPropertyDescriptor() method returns an object describing a specific property on a given object. A JavaScript object can be created in many ways and its properties can be called by using property descriptors for that object."
},
{
"code": null,
"e": 25632,
"s": 25624,
"text": "Syntax:"
},
{
"code": null,
"e": 25677,
"s": 25632,
"text": "Object.getOwnPropertyDescriptor( obj, prop )"
},
{
"code": null,
"e": 25765,
"s": 25677,
"text": "The Object.getOwnPropertyDescriptor() takes two parameters as input as described below:"
},
{
"code": null,
"e": 25837,
"s": 25765,
"text": "obj: It refers to the object name whose properties are to be described."
},
{
"code": null,
"e": 25921,
"s": 25837,
"text": "prop: It defines the specific property in the object whose value is to be returned."
},
{
"code": null,
"e": 26023,
"s": 25921,
"text": "Return value: This method returns the property of the Object if it exists else it returns undefined. "
},
{
"code": null,
"e": 26250,
"s": 26023,
"text": "Example: In the below example, an object Obj is created which consists of two properties property1 and property2. We use Object.getOwnPropertyDescriptor() property to return the attributes and values related to each property."
},
{
"code": null,
"e": 26261,
"s": 26250,
"text": "JavaScript"
},
{
"code": "<script> // Object const Obj = { property1: \"GeeksforGeeks\", property2: 12 }; const descriptor1 = Object .getOwnPropertyDescriptor(Obj, 'property1'); const descriptor2 = Object .getOwnPropertyDescriptor(Obj, 'property2'); console.log(descriptor1.configurable); // expected output: true console.log(descriptor1.enumerable); // expected output: true console.log(descriptor1.value); // expected output: GeeksforGeeks console.log(descriptor2.value); // expected output: 12 </script>",
"e": 26822,
"s": 26261,
"text": null
},
{
"code": null,
"e": 26830,
"s": 26822,
"text": "Output:"
},
{
"code": null,
"e": 26857,
"s": 26830,
"text": "true\ntrue\nGeeksforGeeks\n12"
},
{
"code": null,
"e": 26962,
"s": 26857,
"text": "A property descriptor of an object consists of some of the following attributes to define each property:"
},
{
"code": null,
"e": 27029,
"s": 26962,
"text": "value: It is the value associated with the property that is called"
},
{
"code": null,
"e": 27147,
"s": 27029,
"text": "writable: It indicates if the property can be changed or not. It only returns true if the property can be manipulated"
},
{
"code": null,
"e": 27274,
"s": 27147,
"text": "enumerable: If the property is visible during enumeration of the properties of the corresponding object, then it returns true."
},
{
"code": null,
"e": 27385,
"s": 27274,
"text": "configurable: It indicates if the property descriptor can be changed or removed from the corresponding object."
},
{
"code": null,
"e": 27497,
"s": 27385,
"text": "Example: The below example describes the property attributes for property1 and property2 related to object Obj."
},
{
"code": null,
"e": 27508,
"s": 27497,
"text": "JavaScript"
},
{
"code": "<script> const Obj = { property1: \"GeeksforGeeks\", property2: 12 }; const descriptor1 = Object .getOwnPropertyDescriptor(Obj, 'property1'); const descriptor2 = Object .getOwnPropertyDescriptor(Obj, 'property2'); console.log(descriptor1); console.log(descriptor2);</script>",
"e": 27833,
"s": 27508,
"text": null
},
{
"code": null,
"e": 27841,
"s": 27833,
"text": "Output:"
},
{
"code": null,
"e": 28206,
"s": 27841,
"text": "{value: 'GeeksforGeeks', writable: true, enumerable: true, configurable: true}\n configurable: true\n enumerable: true\n value: \"GeeksforGeeks\"\n writable: true\n [[Prototype]]: Object\n\n{value: 12, writable: true, enumerable: true, configurable: true}\n configurable: true\n enumerable: true\n value: 12\n writable: true\n [[Prototype]]: Object"
},
{
"code": null,
"e": 28225,
"s": 28206,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 28246,
"s": 28225,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28253,
"s": 28246,
"text": "Picked"
},
{
"code": null,
"e": 28264,
"s": 28253,
"text": "JavaScript"
},
{
"code": null,
"e": 28281,
"s": 28264,
"text": "Web Technologies"
},
{
"code": null,
"e": 28379,
"s": 28281,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28388,
"s": 28379,
"text": "Comments"
},
{
"code": null,
"e": 28401,
"s": 28388,
"text": "Old Comments"
},
{
"code": null,
"e": 28462,
"s": 28401,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28503,
"s": 28462,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28557,
"s": 28503,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28597,
"s": 28557,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28645,
"s": 28597,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 28687,
"s": 28645,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28720,
"s": 28687,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28763,
"s": 28720,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28825,
"s": 28763,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
SQLite - CREATE Database
|
In SQLite, sqlite3 command is used to create a new SQLite database. You do not need to have any special privilege to create a database.
Following is the basic syntax of sqlite3 command to create a database: −
$sqlite3 DatabaseName.db
Always, database name should be unique within the RDBMS.
If you want to create a new database <testDB.db>, then SQLITE3 statement would be as follows −
$sqlite3 testDB.db
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
The above command will create a file testDB.db in the current directory. This file will be used as database by SQLite engine. If you have noticed while creating database, sqlite3 command will provide a sqlite> prompt after creating a database file successfully.
Once a database is created, you can verify it in the list of databases using the following SQLite .databases command.
sqlite>.databases
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
You will use SQLite .quit command to come out of the sqlite prompt as follows −
sqlite>.quit
$
You can use .dump dot command to export complete database in a text file using the following SQLite command at the command prompt.
$sqlite3 testDB.db .dump > testDB.sql
The above command will convert the entire contents of testDB.db database into SQLite statements and dump it into ASCII text file testDB.sql. You can perform restoration from the generated testDB.sql in a simple way as follows −
$sqlite3 testDB.db < testDB.sql
At this moment your database is empty, so you can try above two procedures once you have few tables and data in your database. For now, let's proceed to the next chapter.
25 Lectures
4.5 hours
Sandip Bhattacharya
17 Lectures
1 hours
Laurence Svekis
5 Lectures
51 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2774,
"s": 2638,
"text": "In SQLite, sqlite3 command is used to create a new SQLite database. You do not need to have any special privilege to create a database."
},
{
"code": null,
"e": 2847,
"s": 2774,
"text": "Following is the basic syntax of sqlite3 command to create a database: −"
},
{
"code": null,
"e": 2873,
"s": 2847,
"text": "$sqlite3 DatabaseName.db\n"
},
{
"code": null,
"e": 2930,
"s": 2873,
"text": "Always, database name should be unique within the RDBMS."
},
{
"code": null,
"e": 3025,
"s": 2930,
"text": "If you want to create a new database <testDB.db>, then SQLITE3 statement would be as follows −"
},
{
"code": null,
"e": 3170,
"s": 3025,
"text": "$sqlite3 testDB.db\nSQLite version 3.7.15.2 2013-01-09 11:53:05\nEnter \".help\" for instructions\nEnter SQL statements terminated with a \";\"\nsqlite>"
},
{
"code": null,
"e": 3432,
"s": 3170,
"text": "The above command will create a file testDB.db in the current directory. This file will be used as database by SQLite engine. If you have noticed while creating database, sqlite3 command will provide a sqlite> prompt after creating a database file successfully."
},
{
"code": null,
"e": 3551,
"s": 3432,
"text": "Once a database is created, you can verify it in the list of databases using the following SQLite .databases command."
},
{
"code": null,
"e": 3687,
"s": 3551,
"text": "sqlite>.databases\nseq name file\n--- --------------- ----------------------\n0 main /home/sqlite/testDB.db\n"
},
{
"code": null,
"e": 3767,
"s": 3687,
"text": "You will use SQLite .quit command to come out of the sqlite prompt as follows −"
},
{
"code": null,
"e": 3783,
"s": 3767,
"text": "sqlite>.quit\n$\n"
},
{
"code": null,
"e": 3914,
"s": 3783,
"text": "You can use .dump dot command to export complete database in a text file using the following SQLite command at the command prompt."
},
{
"code": null,
"e": 3952,
"s": 3914,
"text": "$sqlite3 testDB.db .dump > testDB.sql"
},
{
"code": null,
"e": 4180,
"s": 3952,
"text": "The above command will convert the entire contents of testDB.db database into SQLite statements and dump it into ASCII text file testDB.sql. You can perform restoration from the generated testDB.sql in a simple way as follows −"
},
{
"code": null,
"e": 4212,
"s": 4180,
"text": "$sqlite3 testDB.db < testDB.sql"
},
{
"code": null,
"e": 4383,
"s": 4212,
"text": "At this moment your database is empty, so you can try above two procedures once you have few tables and data in your database. For now, let's proceed to the next chapter."
},
{
"code": null,
"e": 4418,
"s": 4383,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4439,
"s": 4418,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 4472,
"s": 4439,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4489,
"s": 4472,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 4520,
"s": 4489,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 4533,
"s": 4520,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 4540,
"s": 4533,
"text": " Print"
},
{
"code": null,
"e": 4551,
"s": 4540,
"text": " Add Notes"
}
] |
MongoDB - Data Modelling
|
Data in MongoDB has a flexible schema.documents in the same collection. They do not need to have the same set of fields or structure Common fields in a collection’s documents may hold different types of data.
MongoDB provides two types of data models: — Embedded data model and Normalized data model. Based on the requirement, you can use either of the models while preparing your document.
In this model, you can have (embed) all the related data in a single document, it is also known as de-normalized data model.
For example, assume we are getting the details of employees in three different documents namely, Personal_details, Contact and, Address, you can embed all the three documents in a single one as shown below −
{
_id: ,
Emp_ID: "10025AE336"
Personal_details:{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26"
},
Contact: {
e-mail: "[email protected]",
phone: "9848022338"
},
Address: {
city: "Hyderabad",
Area: "Madapur",
State: "Telangana"
}
}
In this model, you can refer the sub documents in the original document, using references. For example, you can re-write the above document in the normalized model as:
Employee:
{
_id: <ObjectId101>,
Emp_ID: "10025AE336"
}
Personal_details:
{
_id: <ObjectId102>,
empDocID: " ObjectId101",
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26"
}
Contact:
{
_id: <ObjectId103>,
empDocID: " ObjectId101",
e-mail: "[email protected]",
phone: "9848022338"
}
Address:
{
_id: <ObjectId104>,
empDocID: " ObjectId101",
city: "Hyderabad",
Area: "Madapur",
State: "Telangana"
}
Design your schema according to user requirements.
Design your schema according to user requirements.
Combine objects into one document if you will use them together. Otherwise separate them (but make sure there should not be need of joins).
Combine objects into one document if you will use them together. Otherwise separate them (but make sure there should not be need of joins).
Duplicate the data (but limited) because disk space is cheap as compare to compute time.
Duplicate the data (but limited) because disk space is cheap as compare to compute time.
Do joins while write, not on read.
Do joins while write, not on read.
Optimize your schema for most frequent use cases.
Optimize your schema for most frequent use cases.
Do complex aggregation in the schema.
Do complex aggregation in the schema.
Suppose a client needs a database design for his blog/website and see the differences between RDBMS and MongoDB schema design. Website has the following requirements.
Every post has the unique title, description and url.
Every post has the unique title, description and url.
Every post can have one or more tags.
Every post can have one or more tags.
Every post has the name of its publisher and total number of likes.
Every post has the name of its publisher and total number of likes.
Every post has comments given by users along with their name, message, data-time and likes.
Every post has comments given by users along with their name, message, data-time and likes.
On each post, there can be zero or more comments.
On each post, there can be zero or more comments.
In RDBMS schema, design for above requirements will have minimum three tables.
While in MongoDB schema, design will have one collection post and the following structure −
{
_id: POST_ID
title: TITLE_OF_POST,
description: POST_DESCRIPTION,
by: POST_BY,
url: URL_OF_POST,
tags: [TAG1, TAG2, TAG3],
likes: TOTAL_LIKES,
comments: [
{
user:'COMMENT_BY',
message: TEXT,
dateCreated: DATE_TIME,
like: LIKES
},
{
user:'COMMENT_BY',
message: TEXT,
dateCreated: DATE_TIME,
like: LIKES
}
]
}
So while showing the data, in RDBMS you need to join three tables and in MongoDB, data will be shown from one collection only.
44 Lectures
3 hours
Arnab Chakraborty
54 Lectures
5.5 hours
Eduonix Learning Solutions
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
40 Lectures
2.5 hours
University Code
26 Lectures
8 hours
Bassir Jafarzadeh
70 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2762,
"s": 2553,
"text": "Data in MongoDB has a flexible schema.documents in the same collection. They do not need to have the same set of fields or structure Common fields in a collection’s documents may hold different types of data."
},
{
"code": null,
"e": 2944,
"s": 2762,
"text": "MongoDB provides two types of data models: — Embedded data model and Normalized data model. Based on the requirement, you can use either of the models while preparing your document."
},
{
"code": null,
"e": 3069,
"s": 2944,
"text": "In this model, you can have (embed) all the related data in a single document, it is also known as de-normalized data model."
},
{
"code": null,
"e": 3277,
"s": 3069,
"text": "For example, assume we are getting the details of employees in three different documents namely, Personal_details, Contact and, Address, you can embed all the three documents in a single one as shown below −"
},
{
"code": null,
"e": 3569,
"s": 3277,
"text": "{\n\t_id: ,\n\tEmp_ID: \"10025AE336\"\n\tPersonal_details:{\n\t\tFirst_Name: \"Radhika\",\n\t\tLast_Name: \"Sharma\",\n\t\tDate_Of_Birth: \"1995-09-26\"\n\t},\n\tContact: {\n\t\te-mail: \"[email protected]\",\n\t\tphone: \"9848022338\"\n\t},\n\tAddress: {\n\t\tcity: \"Hyderabad\",\n\t\tArea: \"Madapur\",\n\t\tState: \"Telangana\"\n\t}\n}"
},
{
"code": null,
"e": 3737,
"s": 3569,
"text": "In this model, you can refer the sub documents in the original document, using references. For example, you can re-write the above document in the normalized model as:"
},
{
"code": null,
"e": 3747,
"s": 3737,
"text": "Employee:"
},
{
"code": null,
"e": 3794,
"s": 3747,
"text": "{\n\t_id: <ObjectId101>,\n\tEmp_ID: \"10025AE336\"\n}"
},
{
"code": null,
"e": 3812,
"s": 3794,
"text": "Personal_details:"
},
{
"code": null,
"e": 3939,
"s": 3812,
"text": "{\n\t_id: <ObjectId102>,\n\tempDocID: \" ObjectId101\",\n\tFirst_Name: \"Radhika\",\n\tLast_Name: \"Sharma\",\n\tDate_Of_Birth: \"1995-09-26\"\n}"
},
{
"code": null,
"e": 3948,
"s": 3939,
"text": "Contact:"
},
{
"code": null,
"e": 4062,
"s": 3948,
"text": "{\n\t_id: <ObjectId103>,\n\tempDocID: \" ObjectId101\",\n\te-mail: \"[email protected]\",\n\tphone: \"9848022338\"\n}"
},
{
"code": null,
"e": 4071,
"s": 4062,
"text": "Address:"
},
{
"code": null,
"e": 4181,
"s": 4071,
"text": "{\n\t_id: <ObjectId104>,\n\tempDocID: \" ObjectId101\",\n\tcity: \"Hyderabad\",\n\tArea: \"Madapur\",\n\tState: \"Telangana\"\n}"
},
{
"code": null,
"e": 4232,
"s": 4181,
"text": "Design your schema according to user requirements."
},
{
"code": null,
"e": 4283,
"s": 4232,
"text": "Design your schema according to user requirements."
},
{
"code": null,
"e": 4423,
"s": 4283,
"text": "Combine objects into one document if you will use them together. Otherwise separate them (but make sure there should not be need of joins)."
},
{
"code": null,
"e": 4563,
"s": 4423,
"text": "Combine objects into one document if you will use them together. Otherwise separate them (but make sure there should not be need of joins)."
},
{
"code": null,
"e": 4652,
"s": 4563,
"text": "Duplicate the data (but limited) because disk space is cheap as compare to compute time."
},
{
"code": null,
"e": 4741,
"s": 4652,
"text": "Duplicate the data (but limited) because disk space is cheap as compare to compute time."
},
{
"code": null,
"e": 4776,
"s": 4741,
"text": "Do joins while write, not on read."
},
{
"code": null,
"e": 4811,
"s": 4776,
"text": "Do joins while write, not on read."
},
{
"code": null,
"e": 4861,
"s": 4811,
"text": "Optimize your schema for most frequent use cases."
},
{
"code": null,
"e": 4911,
"s": 4861,
"text": "Optimize your schema for most frequent use cases."
},
{
"code": null,
"e": 4949,
"s": 4911,
"text": "Do complex aggregation in the schema."
},
{
"code": null,
"e": 4987,
"s": 4949,
"text": "Do complex aggregation in the schema."
},
{
"code": null,
"e": 5154,
"s": 4987,
"text": "Suppose a client needs a database design for his blog/website and see the differences between RDBMS and MongoDB schema design. Website has the following requirements."
},
{
"code": null,
"e": 5208,
"s": 5154,
"text": "Every post has the unique title, description and url."
},
{
"code": null,
"e": 5262,
"s": 5208,
"text": "Every post has the unique title, description and url."
},
{
"code": null,
"e": 5300,
"s": 5262,
"text": "Every post can have one or more tags."
},
{
"code": null,
"e": 5338,
"s": 5300,
"text": "Every post can have one or more tags."
},
{
"code": null,
"e": 5406,
"s": 5338,
"text": "Every post has the name of its publisher and total number of likes."
},
{
"code": null,
"e": 5474,
"s": 5406,
"text": "Every post has the name of its publisher and total number of likes."
},
{
"code": null,
"e": 5566,
"s": 5474,
"text": "Every post has comments given by users along with their name, message, data-time and likes."
},
{
"code": null,
"e": 5658,
"s": 5566,
"text": "Every post has comments given by users along with their name, message, data-time and likes."
},
{
"code": null,
"e": 5708,
"s": 5658,
"text": "On each post, there can be zero or more comments."
},
{
"code": null,
"e": 5758,
"s": 5708,
"text": "On each post, there can be zero or more comments."
},
{
"code": null,
"e": 5837,
"s": 5758,
"text": "In RDBMS schema, design for above requirements will have minimum three tables."
},
{
"code": null,
"e": 5929,
"s": 5837,
"text": "While in MongoDB schema, design will have one collection post and the following structure −"
},
{
"code": null,
"e": 6366,
"s": 5929,
"text": "{\n _id: POST_ID\n title: TITLE_OF_POST, \n description: POST_DESCRIPTION,\n by: POST_BY,\n url: URL_OF_POST,\n tags: [TAG1, TAG2, TAG3],\n likes: TOTAL_LIKES, \n comments: [\t\n {\n user:'COMMENT_BY',\n message: TEXT,\n dateCreated: DATE_TIME,\n like: LIKES \n },\n {\n user:'COMMENT_BY',\n message: TEXT,\n dateCreated: DATE_TIME,\n like: LIKES\n }\n ]\n}"
},
{
"code": null,
"e": 6493,
"s": 6366,
"text": "So while showing the data, in RDBMS you need to join three tables and in MongoDB, data will be shown from one collection only."
},
{
"code": null,
"e": 6526,
"s": 6493,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6545,
"s": 6526,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6580,
"s": 6545,
"text": "\n 54 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6608,
"s": 6580,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6643,
"s": 6608,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6666,
"s": 6643,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 6701,
"s": 6666,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6718,
"s": 6701,
"text": " University Code"
},
{
"code": null,
"e": 6751,
"s": 6718,
"text": "\n 26 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6770,
"s": 6751,
"text": " Bassir Jafarzadeh"
},
{
"code": null,
"e": 6805,
"s": 6770,
"text": "\n 70 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6825,
"s": 6805,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 6832,
"s": 6825,
"text": " Print"
},
{
"code": null,
"e": 6843,
"s": 6832,
"text": " Add Notes"
}
] |
What are local variables and global variables in C++?
|
A scope is a region of the program and broadly speaking there are three places, where variables can be declared −
Inside a function or a block which is called local variables,
In the definition of function parameters which is called formal parameters.
Outside of all functions which are called global variables.
Local variables can be used only by statements that are inside that function or block of code. Local variables are not known to functions on their own.
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
This will give the output −
30
Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of your program. A global variable can be accessed by any function.
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
This will give the output −
30
A program can have the same name for local and global variables but the value of a local variable inside a function will take preference. For accessing the global variable with same rame, you'll have to use the scope resolution operator.
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
// Local variable declaration:
int g = 10;
cout << g; // Local
cout << ::g; // Global
return 0;
}
This will give the output −
10
20
|
[
{
"code": null,
"e": 1176,
"s": 1062,
"text": "A scope is a region of the program and broadly speaking there are three places, where variables can be declared −"
},
{
"code": null,
"e": 1239,
"s": 1176,
"text": " Inside a function or a block which is called local variables,"
},
{
"code": null,
"e": 1316,
"s": 1239,
"text": " In the definition of function parameters which is called formal parameters."
},
{
"code": null,
"e": 1377,
"s": 1316,
"text": " Outside of all functions which are called global variables."
},
{
"code": null,
"e": 1530,
"s": 1377,
"text": "Local variables can be used only by statements that are inside that function or block of code. Local variables are not known to functions on their own. "
},
{
"code": null,
"e": 1737,
"s": 1530,
"text": "#include <iostream>\nusing namespace std;\nint main () {\n // Local variable declaration:\n int a, b;\n int c;\n\n // actual initialization\n a = 10;\n b = 20;\n c = a + b;\n\n cout << c;\n return 0;\n}"
},
{
"code": null,
"e": 1765,
"s": 1737,
"text": "This will give the output −"
},
{
"code": null,
"e": 1768,
"s": 1765,
"text": "30"
},
{
"code": null,
"e": 1994,
"s": 1768,
"text": "Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of your program. A global variable can be accessed by any function. "
},
{
"code": null,
"e": 2230,
"s": 1994,
"text": "#include <iostream>\nusing namespace std;\n// Global variable declaration:\nint g;\nint main () {\n // Local variable declaration:\n int a, b;\n\n // actual initialization\n a = 10;\n b = 20;\n g = a + b;\n\n cout << g;\n return 0;\n}"
},
{
"code": null,
"e": 2258,
"s": 2230,
"text": "This will give the output −"
},
{
"code": null,
"e": 2261,
"s": 2258,
"text": "30"
},
{
"code": null,
"e": 2500,
"s": 2261,
"text": "A program can have the same name for local and global variables but the value of a local variable inside a function will take preference. For accessing the global variable with same rame, you'll have to use the scope resolution operator. "
},
{
"code": null,
"e": 2715,
"s": 2500,
"text": "#include <iostream>\nusing namespace std;\n// Global variable declaration:\nint g = 20;\nint main () {\n // Local variable declaration:\n int g = 10;\n\n cout << g; // Local\n cout << ::g; // Global\n return 0;\n}"
},
{
"code": null,
"e": 2743,
"s": 2715,
"text": "This will give the output −"
},
{
"code": null,
"e": 2749,
"s": 2743,
"text": "10\n20"
}
] |
How to Solve Python Coding Questions using Math | by Leihua Ye, PhD | Towards Data Science
|
1
2
3
4
5
6
7
8
9
10
Powered by Play.ht
Create audio with Play.ht
Powered by Play.ht
Python coding interviews come in different shapes and forms, and each type has its unique characteristics and approaches. For example, String Manipulation questions expect candidates to have a solid grasp of element retrieval and access. Data Type Switching questions test your understanding of the tradeoffs and unique traits with each type.
However, the math question is different. There is no consistent way of testing. Instead, you have to spot the data pattern and code it up in Python, which sounds daunting at first but totally doable after practice.
In this post, I elaborate and live-code 5 real interview questions and help you better understand how math works in Python.
- Given two non-negative integers low and high. - Return the count of odd numbers between low and high (inclusive).- https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/
Microsoft asks this question. As a warm-up, this question appears to be too trivial to be included in data science or soft engineering interviews. However, it is deceivingly difficult if you don’t know the mathematical shortcut.
My first instinct is to iterate over the range of low and high bounds, inclusive, and count the number of odd numbers using a for loop.
The Python implementation works as follows.
3
As expected, it works well for a narrow range but super slow for a wide range. You can try this test case: countOdds(3,7222222222222222), which takes forever to complete.
As the featured theme of today’s blog post, we learn how to spot patterns in the data and use mathematic procedures to solve the questions at hand.
To calculate the odd numbers within the range of low and high, it is equal to the odd count up to the upper bound deducts by the odd number to the lower bound.
In math, the result = the count of odd until high — the count of odd until low.
Further, there are 50% odd, and 50% even numbers up to a number. For example, there are 4 odd and 4 even numbers for the range between 0 and 8.
The general Python implementation is as follows:
3611111111111110
The second approach returns the result instantly, even for a wide range. For questions that require math calculations, the priority is to analyze the pattern and find its mathematic equivalence. We have to practice a lot to be comfortable with the underlying thinking.
- You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.- Given n, find the total number of full staircase rows that can be formed.- n is a non-negative integer and fits within the range of a 32-bit signed integer.- https://leetcode.com/problems/arranging-coins/
Bloomberg includes this question. In total, there are n coins, and we try to put k number of coins in k-th row. I draw a simple diagram for visual aid.
If n = 8, and we put 1 on the first row, 2 on the second, 3 on the third, and 2 on the fourth. Since only the first three rows are full staircases, the function should return 3.
The interesting pattern is that there is a 1 unit increase from i-th full staircases to (i+1)th full staircases. In high school, we learned this type of sequence is called an arithmetic sequence or arithmetic progression. So, for the k-th complete staircase, the total number of coins = k*(k+1)/2.
Don’t worry if you can’t remember the formula. I Googled it while writing this post.
The next step is to find a way to maximize the number of complete staircases and minimize the distance between the coin count and n, which can be achieved using a binary search.
towardsdatascience.com
3
This is a standard implementation of a binary search, and the only catch is to be able to come up with the summation formula for an arithmetic sequence.
- A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).- Write a function to determine if a number is strobogrammatic. The number is represented as a string.- https://leetcode.com/problems/strobogrammatic-number/
Facebook asks this question. It would be helpful to write out some numbers and rotate them 180 degrees.
Original 180 degrees rotation 0 0 1 1 2 invalid 3 invalid 4 invalid 5 invalid 6 9 7 invalid 8 8 9 6
From 0 to 9, there are only 5 valid digits and 5 invalid digits after 180-degree rotation. For these valid digits, only 0, 1, and 8 stay the same after rotation, and the other two, 6 and 9, change values.
On the one hand, it would not be a valid number after rotations if the number contains any invalid digits.
On the other hand, we return the “mirrored” value for the valid digits (0, 1, 6, 8, and 9). We can create a dictionary and take advantage of its key-value pair feature to return the value.
Dictionary has a unique key-value pair feature, which comes in handy under a lot of scenarios. Take a look here:
towardsdatascience.com
In Python, we can do the following:
True
There are two catches. First, num is stored as a string, not an integer, and we have to be careful with accessing the string element. Second, digits change their positions after rotations, and so we have to use the reversed() method to read from the last (rightmost) digit backward, e.g., 169 → 691.
The rest is self-evident.
- The set S originally contains numbers from 1 to n. - But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.- Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.- https://leetcode.com/problems/set-mismatch/
Amazon asks this question. Simply puts, a number is repeated twice, and another number is missing in a sequence of numbers. Our job is to find them both.
It is possible to solve this question using non-math approaches, but the downside is the use of extra memory utilization, which may be prohibited in technical interviews. So, we will solve it using the mathematical approach.
#1 To find the repeated numberThe go-to data type is a set, which does not allow duplicates. By changing the data type to a set, we can get rid of the duplicated case. Then, take the difference between the total sum of the original array and the set. #2 To find the missing number Like the first step, we use a set to remove the duplicate and take the difference between the sum of the range up to n and the set.
In Python, we can do the following code.
[1, 2]
It works.
As a side note, combining a set with another function/method in Python, e.g., len() and sum(), is a powerful way of examining changes after taking out the replicates.
- Given an integer n, return true if it is a power of three. Otherwise, return false.- An integer n is a power of three, if there exists an integer x such that n == 3^x.- https://leetcode.com/problems/power-of-three/
Goldman Sachs and Hulu include this interview question. There are two approaches. First, we can use a while loop to divide the number by 3, and the remaining part should be 1 if it is a power of three. Second, we can use recursion. Here, I present both solutions for comparisons.
For this question, the math part is easy. We only have to keep in mind that the reminder should equal 1 for power numbers.
True
We need to specify the base condition for the second approach. For power numbers, the remaining part is equal to 0; for others, the remaining part isn’t 0.
False
The complete Python code is available on my Github.
Math can be handy for programming in Python.
The most challenging part is to spot the pattern and code it up.
To find patterns, writing out a few examples helps.
How about special cases? What to do for duplicates? A set can be helpful!
Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees.
leihua-ye.medium.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Please find me on LinkedIn and Youtube.
Also, check my other posts on Artificial Intelligence and Machine Learning.
|
[
{
"code": null,
"e": 174,
"s": 172,
"text": "1"
},
{
"code": null,
"e": 176,
"s": 174,
"text": "2"
},
{
"code": null,
"e": 178,
"s": 176,
"text": "3"
},
{
"code": null,
"e": 180,
"s": 178,
"text": "4"
},
{
"code": null,
"e": 182,
"s": 180,
"text": "5"
},
{
"code": null,
"e": 184,
"s": 182,
"text": "6"
},
{
"code": null,
"e": 186,
"s": 184,
"text": "7"
},
{
"code": null,
"e": 188,
"s": 186,
"text": "8"
},
{
"code": null,
"e": 190,
"s": 188,
"text": "9"
},
{
"code": null,
"e": 193,
"s": 190,
"text": "10"
},
{
"code": null,
"e": 212,
"s": 193,
"text": "Powered by Play.ht"
},
{
"code": null,
"e": 238,
"s": 212,
"text": "Create audio with Play.ht"
},
{
"code": null,
"e": 257,
"s": 238,
"text": "Powered by Play.ht"
},
{
"code": null,
"e": 600,
"s": 257,
"text": "Python coding interviews come in different shapes and forms, and each type has its unique characteristics and approaches. For example, String Manipulation questions expect candidates to have a solid grasp of element retrieval and access. Data Type Switching questions test your understanding of the tradeoffs and unique traits with each type."
},
{
"code": null,
"e": 815,
"s": 600,
"text": "However, the math question is different. There is no consistent way of testing. Instead, you have to spot the data pattern and code it up in Python, which sounds daunting at first but totally doable after practice."
},
{
"code": null,
"e": 939,
"s": 815,
"text": "In this post, I elaborate and live-code 5 real interview questions and help you better understand how math works in Python."
},
{
"code": null,
"e": 1126,
"s": 939,
"text": "- Given two non-negative integers low and high. - Return the count of odd numbers between low and high (inclusive).- https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/"
},
{
"code": null,
"e": 1355,
"s": 1126,
"text": "Microsoft asks this question. As a warm-up, this question appears to be too trivial to be included in data science or soft engineering interviews. However, it is deceivingly difficult if you don’t know the mathematical shortcut."
},
{
"code": null,
"e": 1491,
"s": 1355,
"text": "My first instinct is to iterate over the range of low and high bounds, inclusive, and count the number of odd numbers using a for loop."
},
{
"code": null,
"e": 1535,
"s": 1491,
"text": "The Python implementation works as follows."
},
{
"code": null,
"e": 1537,
"s": 1535,
"text": "3"
},
{
"code": null,
"e": 1708,
"s": 1537,
"text": "As expected, it works well for a narrow range but super slow for a wide range. You can try this test case: countOdds(3,7222222222222222), which takes forever to complete."
},
{
"code": null,
"e": 1856,
"s": 1708,
"text": "As the featured theme of today’s blog post, we learn how to spot patterns in the data and use mathematic procedures to solve the questions at hand."
},
{
"code": null,
"e": 2016,
"s": 1856,
"text": "To calculate the odd numbers within the range of low and high, it is equal to the odd count up to the upper bound deducts by the odd number to the lower bound."
},
{
"code": null,
"e": 2096,
"s": 2016,
"text": "In math, the result = the count of odd until high — the count of odd until low."
},
{
"code": null,
"e": 2240,
"s": 2096,
"text": "Further, there are 50% odd, and 50% even numbers up to a number. For example, there are 4 odd and 4 even numbers for the range between 0 and 8."
},
{
"code": null,
"e": 2289,
"s": 2240,
"text": "The general Python implementation is as follows:"
},
{
"code": null,
"e": 2306,
"s": 2289,
"text": "3611111111111110"
},
{
"code": null,
"e": 2575,
"s": 2306,
"text": "The second approach returns the result instantly, even for a wide range. For questions that require math calculations, the priority is to analyze the pattern and find its mathematic equivalence. We have to practice a lot to be comfortable with the underlying thinking."
},
{
"code": null,
"e": 2903,
"s": 2575,
"text": "- You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.- Given n, find the total number of full staircase rows that can be formed.- n is a non-negative integer and fits within the range of a 32-bit signed integer.- https://leetcode.com/problems/arranging-coins/"
},
{
"code": null,
"e": 3055,
"s": 2903,
"text": "Bloomberg includes this question. In total, there are n coins, and we try to put k number of coins in k-th row. I draw a simple diagram for visual aid."
},
{
"code": null,
"e": 3233,
"s": 3055,
"text": "If n = 8, and we put 1 on the first row, 2 on the second, 3 on the third, and 2 on the fourth. Since only the first three rows are full staircases, the function should return 3."
},
{
"code": null,
"e": 3531,
"s": 3233,
"text": "The interesting pattern is that there is a 1 unit increase from i-th full staircases to (i+1)th full staircases. In high school, we learned this type of sequence is called an arithmetic sequence or arithmetic progression. So, for the k-th complete staircase, the total number of coins = k*(k+1)/2."
},
{
"code": null,
"e": 3616,
"s": 3531,
"text": "Don’t worry if you can’t remember the formula. I Googled it while writing this post."
},
{
"code": null,
"e": 3794,
"s": 3616,
"text": "The next step is to find a way to maximize the number of complete staircases and minimize the distance between the coin count and n, which can be achieved using a binary search."
},
{
"code": null,
"e": 3817,
"s": 3794,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3819,
"s": 3817,
"text": "3"
},
{
"code": null,
"e": 3972,
"s": 3819,
"text": "This is a standard implementation of a binary search, and the only catch is to be able to come up with the summation formula for an arithmetic sequence."
},
{
"code": null,
"e": 4238,
"s": 3972,
"text": "- A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).- Write a function to determine if a number is strobogrammatic. The number is represented as a string.- https://leetcode.com/problems/strobogrammatic-number/"
},
{
"code": null,
"e": 4342,
"s": 4238,
"text": "Facebook asks this question. It would be helpful to write out some numbers and rotate them 180 degrees."
},
{
"code": null,
"e": 4613,
"s": 4342,
"text": "Original 180 degrees rotation 0 0 1 1 2 invalid 3 invalid 4 invalid 5 invalid 6 9 7 invalid 8 8 9 6 "
},
{
"code": null,
"e": 4818,
"s": 4613,
"text": "From 0 to 9, there are only 5 valid digits and 5 invalid digits after 180-degree rotation. For these valid digits, only 0, 1, and 8 stay the same after rotation, and the other two, 6 and 9, change values."
},
{
"code": null,
"e": 4925,
"s": 4818,
"text": "On the one hand, it would not be a valid number after rotations if the number contains any invalid digits."
},
{
"code": null,
"e": 5114,
"s": 4925,
"text": "On the other hand, we return the “mirrored” value for the valid digits (0, 1, 6, 8, and 9). We can create a dictionary and take advantage of its key-value pair feature to return the value."
},
{
"code": null,
"e": 5227,
"s": 5114,
"text": "Dictionary has a unique key-value pair feature, which comes in handy under a lot of scenarios. Take a look here:"
},
{
"code": null,
"e": 5250,
"s": 5227,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5286,
"s": 5250,
"text": "In Python, we can do the following:"
},
{
"code": null,
"e": 5291,
"s": 5286,
"text": "True"
},
{
"code": null,
"e": 5591,
"s": 5291,
"text": "There are two catches. First, num is stored as a string, not an integer, and we have to be careful with accessing the string element. Second, digits change their positions after rotations, and so we have to use the reversed() method to read from the last (rightmost) digit backward, e.g., 169 → 691."
},
{
"code": null,
"e": 5617,
"s": 5591,
"text": "The rest is self-evident."
},
{
"code": null,
"e": 6115,
"s": 5617,
"text": "- The set S originally contains numbers from 1 to n. - But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.- Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.- https://leetcode.com/problems/set-mismatch/"
},
{
"code": null,
"e": 6269,
"s": 6115,
"text": "Amazon asks this question. Simply puts, a number is repeated twice, and another number is missing in a sequence of numbers. Our job is to find them both."
},
{
"code": null,
"e": 6494,
"s": 6269,
"text": "It is possible to solve this question using non-math approaches, but the downside is the use of extra memory utilization, which may be prohibited in technical interviews. So, we will solve it using the mathematical approach."
},
{
"code": null,
"e": 6907,
"s": 6494,
"text": "#1 To find the repeated numberThe go-to data type is a set, which does not allow duplicates. By changing the data type to a set, we can get rid of the duplicated case. Then, take the difference between the total sum of the original array and the set. #2 To find the missing number Like the first step, we use a set to remove the duplicate and take the difference between the sum of the range up to n and the set."
},
{
"code": null,
"e": 6948,
"s": 6907,
"text": "In Python, we can do the following code."
},
{
"code": null,
"e": 6955,
"s": 6948,
"text": "[1, 2]"
},
{
"code": null,
"e": 6965,
"s": 6955,
"text": "It works."
},
{
"code": null,
"e": 7132,
"s": 6965,
"text": "As a side note, combining a set with another function/method in Python, e.g., len() and sum(), is a powerful way of examining changes after taking out the replicates."
},
{
"code": null,
"e": 7349,
"s": 7132,
"text": "- Given an integer n, return true if it is a power of three. Otherwise, return false.- An integer n is a power of three, if there exists an integer x such that n == 3^x.- https://leetcode.com/problems/power-of-three/"
},
{
"code": null,
"e": 7629,
"s": 7349,
"text": "Goldman Sachs and Hulu include this interview question. There are two approaches. First, we can use a while loop to divide the number by 3, and the remaining part should be 1 if it is a power of three. Second, we can use recursion. Here, I present both solutions for comparisons."
},
{
"code": null,
"e": 7752,
"s": 7629,
"text": "For this question, the math part is easy. We only have to keep in mind that the reminder should equal 1 for power numbers."
},
{
"code": null,
"e": 7757,
"s": 7752,
"text": "True"
},
{
"code": null,
"e": 7913,
"s": 7757,
"text": "We need to specify the base condition for the second approach. For power numbers, the remaining part is equal to 0; for others, the remaining part isn’t 0."
},
{
"code": null,
"e": 7919,
"s": 7913,
"text": "False"
},
{
"code": null,
"e": 7971,
"s": 7919,
"text": "The complete Python code is available on my Github."
},
{
"code": null,
"e": 8016,
"s": 7971,
"text": "Math can be handy for programming in Python."
},
{
"code": null,
"e": 8081,
"s": 8016,
"text": "The most challenging part is to spot the pattern and code it up."
},
{
"code": null,
"e": 8133,
"s": 8081,
"text": "To find patterns, writing out a few examples helps."
},
{
"code": null,
"e": 8207,
"s": 8133,
"text": "How about special cases? What to do for duplicates? A set can be helpful!"
},
{
"code": null,
"e": 8419,
"s": 8207,
"text": "Medium recently evolved its Writer Partner Program, which supports ordinary writers like myself. If you are not a subscriber yet and sign up via the following link, I’ll receive a portion of the membership fees."
},
{
"code": null,
"e": 8440,
"s": 8419,
"text": "leihua-ye.medium.com"
},
{
"code": null,
"e": 8463,
"s": 8440,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8486,
"s": 8463,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8509,
"s": 8486,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8549,
"s": 8509,
"text": "Please find me on LinkedIn and Youtube."
}
] |
Building custom-trained object detection models in Python | by Alan Bi | Towards Data Science
|
These days, machine learning and computer vision are all the craze. We’ve all seen the news about self-driving cars and facial recognition and probably imagined how cool it’d be to build our own computer vision models. However, it’s not always easy to break into the field, especially without a strong math background. Libraries like PyTorch and TensorFlow can be tedious to learn if all you want to do is experiment with something small.
In this tutorial, I present a simple way for anyone to build fully-functional object detection models with just a few lines of code. More specifically, we’ll be using Detecto, a Python package built on top of PyTorch that makes the process easy and open to programmers at all levels.
github.com
To demonstrate how simple it is to use Detecto, let’s load in a pre-trained model and run inference on the following image:
First, download the Detecto package using pip:
pip3 install detecto
Then, save the image above as “fruit.jpg” and create a Python file in the same folder as the image. Inside the Python file, write these 5 lines of code:
After running this file (it may take a few seconds if you don’t have a CUDA-enabled GPU on your computer; more on that later), you should see something similar to the plot below:
Awesome! We did all that with just 5 lines of code. Here’s what we did in each:
Imported Detecto’s modulesRead in an imageInitialized a pre-trained modelGenerated the top predictions on our imagePlotted our predictions
Imported Detecto’s modules
Read in an image
Initialized a pre-trained model
Generated the top predictions on our image
Plotted our predictions
Detecto uses a Faster R-CNN ResNet-50 FPN from PyTorch’s model zoo, which is able to detect about 80 different objects such as animals, vehicles, kitchen appliances, etc. However, what if you wanted to detect custom objects, like Coke vs. Pepsi cans, or zebras vs. giraffes?
You’ll be glad to know that training a Detecto model on a custom dataset is just as easy; again, all you need is 5 lines of code, as well as either an existing dataset or some time spent labeling images.
In this tutorial, we’ll start from scratch by building our own dataset. I recommend that you do the same, but if you want to skip this step, you can download a sample dataset here (modified from Stanford’s Dog Dataset).
For our dataset, we’ll be training our model to detect an underwater alien, bat, and witch from the RoboSub competition, as shown below:
Ideally, you’ll want at least 100 images of each class. The good thing is that you can have multiple objects in each image, so you could theoretically get away with 100 total images if each image contains every class of object you want to detect. Also, if you have video footage, Detecto makes it easy to split that footage into images that you can then use for your dataset:
The code above takes every 4th frame in “video.mp4” and saves it as a JPEG file in the “frames” folder.
Once you’ve produced your training dataset, you should have a folder that looks something like the following:
images/| image0.jpg| image1.jpg| image2.jpg| ...
If you want, you can also have a second folder containing a set of validation images.
Now comes the time-consuming part: labeling. Detecto supports the PASCAL VOC format, in which you have XML files containing label and position data for each object in your images. To create these XML files, you can use the open-source LabelImg tool as follows:
pip3 install labelImg # Download LabelImg using piplabelImg # Launch the application
You should now see a window pop up. On the left, click the “Open Dir” button and select the folder of images that you want to label. If things worked correctly, you should see something like this:
To draw a bounding box, click the icon in the left menu bar (or use the keyboard shortcut “w”). You can then drag a box around your objects and write/select a label:
When you’ve finished labeling an image, use CTRL+S or CMD+S to save your XML file (for simplicity and speed, you can just use the default file location and name that they auto-fill). To label the next image, click “Next Image” (or use the keyboard shortcut “d”).
Once you’re done with the entire dataset, your folder should look something like this:
images/| image0.jpg| image0.xml| image1.jpg| image1.xml| ...
We’re almost ready to start training our object detection model!
First, check whether your computer has a CUDA-enabled GPU. Since deep learning uses a lot of processing power, training on a typical CPU can be very slow. Thankfully, most modern deep learning frameworks like PyTorch and Tensorflow can run on GPUs, making things much faster. Make sure you have PyTorch downloaded (you should already have it if you installed Detecto), and then run the following 2 lines of code:
If it prints True, great! You can skip to the next section. If it prints False, don’t fret. Follow the below steps to create a Google Colaboratory notebook, an online coding environment that comes with a free, usable GPU. For this tutorial, you’ll just be working from within a Google Drive folder rather than on your computer.
Log in to Google DriveCreate a folder called “Detecto Tutorial” and navigate into this folderUpload your training images (and/or validation images) to this folderRight-click, go to “More”, and click “Google Colaboratory”:
Log in to Google Drive
Create a folder called “Detecto Tutorial” and navigate into this folder
Upload your training images (and/or validation images) to this folder
Right-click, go to “More”, and click “Google Colaboratory”:
You should now see an interface like this:
5. Give your notebook a name if you want, and then go to Edit ->Notebook settings -> Hardware accelerator and select GPU
6. Type the following code to “mount” your Drive, change directory to the current folder, and install Detecto:
To make sure everything worked, you can create a new code cell and type !ls to check that you’re in the right directory.
Finally, we can now train a model on our custom dataset! As promised, this is the easy part. All it takes is 4 lines of code:
Let’s again break down what we’ve done with each line of code:
Imported Detecto’s modulesCreated a Dataset from the “images” folder (containing our JPEG and XML files)Initialized a model to detect our custom objects (alien, bat, and witch)Trained our model on the dataset
Imported Detecto’s modules
Created a Dataset from the “images” folder (containing our JPEG and XML files)
Initialized a model to detect our custom objects (alien, bat, and witch)
Trained our model on the dataset
This can take anywhere from 10 minutes to 1+ hours to run depending on the size of your dataset, so make sure your program doesn’t exit immediately after finishing the above statements (i.e. you’re using a Jupyter/Colab notebook that preserves state while active).
Now that you have a trained model, let’s test it on some images. To read images from a file path, you can use the read_image function from the detecto.utils module (you could also use an image from the Dataset you created above):
As you can see, the model’s predict method returns a tuple of 3 elements: labels, boxes, and scores. In the above example, the model predicted an alien (labels[0]) at the coordinates [569, 204, 1003, 658] (boxes[0]) with a confidence level of 0.995 (scores[0]).
From these predictions, we can plot the results using the detecto.visualize module. For example:
Running the above code with the image and predictions you received should produce something that looks like this:
If you have a video, you can run object detection on it:
This takes in a video file called “input.mp4” and produces an “output.avi” file with the given model’s predictions. If you open this file with VLC or some other video player, you should see some promising results!
Lastly, you can save and load models from files, allowing you to save your progress and come back to it later:
You’ll be happy to know that Detecto isn’t just limited to 5 lines of code. Let’s say for example that the model didn’t do as well as you hoped. We can try to increase its performance by augmenting our dataset with torchvision transforms and defining a custom DataLoader:
This code applies random horizontal flips and saturation effects on images in our dataset, increasing the diversity of our data. We then define a DataLoader object with batch_size=2; we’ll pass this to model.fit instead of the Dataset to tell our model to train on batches of 2 images rather than the default of 1.
If you created a separate validation dataset earlier, now is the time to load it in during training. By providing a validation dataset, the fit method returns a list of the losses at each epoch, and if verbose=True, then it will also print these out during the training process itself. The following code block demonstrates this as well as customizes several other training parameters:
The resulting plot of the losses should be more or less decreasing:
For even more flexibility and control over your model, you can bypass Detecto altogether; the model.get_internal_model method returns the underlying torchvision model used, which you can mess around with as much as you see fit.
In this tutorial, we showed that computer vision and object detection don’t need to be challenging. All you need is a bit of time and patience to come up with a labeled dataset.
If you’re interested in further exploration, check out Detecto on GitHub or visit the documentation for more tutorials and use cases!
|
[
{
"code": null,
"e": 611,
"s": 172,
"text": "These days, machine learning and computer vision are all the craze. We’ve all seen the news about self-driving cars and facial recognition and probably imagined how cool it’d be to build our own computer vision models. However, it’s not always easy to break into the field, especially without a strong math background. Libraries like PyTorch and TensorFlow can be tedious to learn if all you want to do is experiment with something small."
},
{
"code": null,
"e": 895,
"s": 611,
"text": "In this tutorial, I present a simple way for anyone to build fully-functional object detection models with just a few lines of code. More specifically, we’ll be using Detecto, a Python package built on top of PyTorch that makes the process easy and open to programmers at all levels."
},
{
"code": null,
"e": 906,
"s": 895,
"text": "github.com"
},
{
"code": null,
"e": 1030,
"s": 906,
"text": "To demonstrate how simple it is to use Detecto, let’s load in a pre-trained model and run inference on the following image:"
},
{
"code": null,
"e": 1077,
"s": 1030,
"text": "First, download the Detecto package using pip:"
},
{
"code": null,
"e": 1098,
"s": 1077,
"text": "pip3 install detecto"
},
{
"code": null,
"e": 1251,
"s": 1098,
"text": "Then, save the image above as “fruit.jpg” and create a Python file in the same folder as the image. Inside the Python file, write these 5 lines of code:"
},
{
"code": null,
"e": 1430,
"s": 1251,
"text": "After running this file (it may take a few seconds if you don’t have a CUDA-enabled GPU on your computer; more on that later), you should see something similar to the plot below:"
},
{
"code": null,
"e": 1510,
"s": 1430,
"text": "Awesome! We did all that with just 5 lines of code. Here’s what we did in each:"
},
{
"code": null,
"e": 1649,
"s": 1510,
"text": "Imported Detecto’s modulesRead in an imageInitialized a pre-trained modelGenerated the top predictions on our imagePlotted our predictions"
},
{
"code": null,
"e": 1676,
"s": 1649,
"text": "Imported Detecto’s modules"
},
{
"code": null,
"e": 1693,
"s": 1676,
"text": "Read in an image"
},
{
"code": null,
"e": 1725,
"s": 1693,
"text": "Initialized a pre-trained model"
},
{
"code": null,
"e": 1768,
"s": 1725,
"text": "Generated the top predictions on our image"
},
{
"code": null,
"e": 1792,
"s": 1768,
"text": "Plotted our predictions"
},
{
"code": null,
"e": 2067,
"s": 1792,
"text": "Detecto uses a Faster R-CNN ResNet-50 FPN from PyTorch’s model zoo, which is able to detect about 80 different objects such as animals, vehicles, kitchen appliances, etc. However, what if you wanted to detect custom objects, like Coke vs. Pepsi cans, or zebras vs. giraffes?"
},
{
"code": null,
"e": 2271,
"s": 2067,
"text": "You’ll be glad to know that training a Detecto model on a custom dataset is just as easy; again, all you need is 5 lines of code, as well as either an existing dataset or some time spent labeling images."
},
{
"code": null,
"e": 2491,
"s": 2271,
"text": "In this tutorial, we’ll start from scratch by building our own dataset. I recommend that you do the same, but if you want to skip this step, you can download a sample dataset here (modified from Stanford’s Dog Dataset)."
},
{
"code": null,
"e": 2628,
"s": 2491,
"text": "For our dataset, we’ll be training our model to detect an underwater alien, bat, and witch from the RoboSub competition, as shown below:"
},
{
"code": null,
"e": 3004,
"s": 2628,
"text": "Ideally, you’ll want at least 100 images of each class. The good thing is that you can have multiple objects in each image, so you could theoretically get away with 100 total images if each image contains every class of object you want to detect. Also, if you have video footage, Detecto makes it easy to split that footage into images that you can then use for your dataset:"
},
{
"code": null,
"e": 3108,
"s": 3004,
"text": "The code above takes every 4th frame in “video.mp4” and saves it as a JPEG file in the “frames” folder."
},
{
"code": null,
"e": 3218,
"s": 3108,
"text": "Once you’ve produced your training dataset, you should have a folder that looks something like the following:"
},
{
"code": null,
"e": 3275,
"s": 3218,
"text": "images/| image0.jpg| image1.jpg| image2.jpg| ..."
},
{
"code": null,
"e": 3361,
"s": 3275,
"text": "If you want, you can also have a second folder containing a set of validation images."
},
{
"code": null,
"e": 3622,
"s": 3361,
"text": "Now comes the time-consuming part: labeling. Detecto supports the PASCAL VOC format, in which you have XML files containing label and position data for each object in your images. To create these XML files, you can use the open-source LabelImg tool as follows:"
},
{
"code": null,
"e": 3726,
"s": 3622,
"text": "pip3 install labelImg # Download LabelImg using piplabelImg # Launch the application"
},
{
"code": null,
"e": 3923,
"s": 3726,
"text": "You should now see a window pop up. On the left, click the “Open Dir” button and select the folder of images that you want to label. If things worked correctly, you should see something like this:"
},
{
"code": null,
"e": 4089,
"s": 3923,
"text": "To draw a bounding box, click the icon in the left menu bar (or use the keyboard shortcut “w”). You can then drag a box around your objects and write/select a label:"
},
{
"code": null,
"e": 4352,
"s": 4089,
"text": "When you’ve finished labeling an image, use CTRL+S or CMD+S to save your XML file (for simplicity and speed, you can just use the default file location and name that they auto-fill). To label the next image, click “Next Image” (or use the keyboard shortcut “d”)."
},
{
"code": null,
"e": 4439,
"s": 4352,
"text": "Once you’re done with the entire dataset, your folder should look something like this:"
},
{
"code": null,
"e": 4510,
"s": 4439,
"text": "images/| image0.jpg| image0.xml| image1.jpg| image1.xml| ..."
},
{
"code": null,
"e": 4575,
"s": 4510,
"text": "We’re almost ready to start training our object detection model!"
},
{
"code": null,
"e": 4988,
"s": 4575,
"text": "First, check whether your computer has a CUDA-enabled GPU. Since deep learning uses a lot of processing power, training on a typical CPU can be very slow. Thankfully, most modern deep learning frameworks like PyTorch and Tensorflow can run on GPUs, making things much faster. Make sure you have PyTorch downloaded (you should already have it if you installed Detecto), and then run the following 2 lines of code:"
},
{
"code": null,
"e": 5316,
"s": 4988,
"text": "If it prints True, great! You can skip to the next section. If it prints False, don’t fret. Follow the below steps to create a Google Colaboratory notebook, an online coding environment that comes with a free, usable GPU. For this tutorial, you’ll just be working from within a Google Drive folder rather than on your computer."
},
{
"code": null,
"e": 5538,
"s": 5316,
"text": "Log in to Google DriveCreate a folder called “Detecto Tutorial” and navigate into this folderUpload your training images (and/or validation images) to this folderRight-click, go to “More”, and click “Google Colaboratory”:"
},
{
"code": null,
"e": 5561,
"s": 5538,
"text": "Log in to Google Drive"
},
{
"code": null,
"e": 5633,
"s": 5561,
"text": "Create a folder called “Detecto Tutorial” and navigate into this folder"
},
{
"code": null,
"e": 5703,
"s": 5633,
"text": "Upload your training images (and/or validation images) to this folder"
},
{
"code": null,
"e": 5763,
"s": 5703,
"text": "Right-click, go to “More”, and click “Google Colaboratory”:"
},
{
"code": null,
"e": 5806,
"s": 5763,
"text": "You should now see an interface like this:"
},
{
"code": null,
"e": 5927,
"s": 5806,
"text": "5. Give your notebook a name if you want, and then go to Edit ->Notebook settings -> Hardware accelerator and select GPU"
},
{
"code": null,
"e": 6038,
"s": 5927,
"text": "6. Type the following code to “mount” your Drive, change directory to the current folder, and install Detecto:"
},
{
"code": null,
"e": 6159,
"s": 6038,
"text": "To make sure everything worked, you can create a new code cell and type !ls to check that you’re in the right directory."
},
{
"code": null,
"e": 6285,
"s": 6159,
"text": "Finally, we can now train a model on our custom dataset! As promised, this is the easy part. All it takes is 4 lines of code:"
},
{
"code": null,
"e": 6348,
"s": 6285,
"text": "Let’s again break down what we’ve done with each line of code:"
},
{
"code": null,
"e": 6557,
"s": 6348,
"text": "Imported Detecto’s modulesCreated a Dataset from the “images” folder (containing our JPEG and XML files)Initialized a model to detect our custom objects (alien, bat, and witch)Trained our model on the dataset"
},
{
"code": null,
"e": 6584,
"s": 6557,
"text": "Imported Detecto’s modules"
},
{
"code": null,
"e": 6663,
"s": 6584,
"text": "Created a Dataset from the “images” folder (containing our JPEG and XML files)"
},
{
"code": null,
"e": 6736,
"s": 6663,
"text": "Initialized a model to detect our custom objects (alien, bat, and witch)"
},
{
"code": null,
"e": 6769,
"s": 6736,
"text": "Trained our model on the dataset"
},
{
"code": null,
"e": 7034,
"s": 6769,
"text": "This can take anywhere from 10 minutes to 1+ hours to run depending on the size of your dataset, so make sure your program doesn’t exit immediately after finishing the above statements (i.e. you’re using a Jupyter/Colab notebook that preserves state while active)."
},
{
"code": null,
"e": 7264,
"s": 7034,
"text": "Now that you have a trained model, let’s test it on some images. To read images from a file path, you can use the read_image function from the detecto.utils module (you could also use an image from the Dataset you created above):"
},
{
"code": null,
"e": 7526,
"s": 7264,
"text": "As you can see, the model’s predict method returns a tuple of 3 elements: labels, boxes, and scores. In the above example, the model predicted an alien (labels[0]) at the coordinates [569, 204, 1003, 658] (boxes[0]) with a confidence level of 0.995 (scores[0])."
},
{
"code": null,
"e": 7623,
"s": 7526,
"text": "From these predictions, we can plot the results using the detecto.visualize module. For example:"
},
{
"code": null,
"e": 7737,
"s": 7623,
"text": "Running the above code with the image and predictions you received should produce something that looks like this:"
},
{
"code": null,
"e": 7794,
"s": 7737,
"text": "If you have a video, you can run object detection on it:"
},
{
"code": null,
"e": 8008,
"s": 7794,
"text": "This takes in a video file called “input.mp4” and produces an “output.avi” file with the given model’s predictions. If you open this file with VLC or some other video player, you should see some promising results!"
},
{
"code": null,
"e": 8119,
"s": 8008,
"text": "Lastly, you can save and load models from files, allowing you to save your progress and come back to it later:"
},
{
"code": null,
"e": 8391,
"s": 8119,
"text": "You’ll be happy to know that Detecto isn’t just limited to 5 lines of code. Let’s say for example that the model didn’t do as well as you hoped. We can try to increase its performance by augmenting our dataset with torchvision transforms and defining a custom DataLoader:"
},
{
"code": null,
"e": 8706,
"s": 8391,
"text": "This code applies random horizontal flips and saturation effects on images in our dataset, increasing the diversity of our data. We then define a DataLoader object with batch_size=2; we’ll pass this to model.fit instead of the Dataset to tell our model to train on batches of 2 images rather than the default of 1."
},
{
"code": null,
"e": 9092,
"s": 8706,
"text": "If you created a separate validation dataset earlier, now is the time to load it in during training. By providing a validation dataset, the fit method returns a list of the losses at each epoch, and if verbose=True, then it will also print these out during the training process itself. The following code block demonstrates this as well as customizes several other training parameters:"
},
{
"code": null,
"e": 9160,
"s": 9092,
"text": "The resulting plot of the losses should be more or less decreasing:"
},
{
"code": null,
"e": 9388,
"s": 9160,
"text": "For even more flexibility and control over your model, you can bypass Detecto altogether; the model.get_internal_model method returns the underlying torchvision model used, which you can mess around with as much as you see fit."
},
{
"code": null,
"e": 9566,
"s": 9388,
"text": "In this tutorial, we showed that computer vision and object detection don’t need to be challenging. All you need is a bit of time and patience to come up with a labeled dataset."
}
] |
Can we define constructor inside an interface in java?
|
No, you cannot have a constructor within an interface in Java.
You can have only public, static, final variables and, public, abstract, methods as of Java7.
You can have only public, static, final variables and, public, abstract, methods as of Java7.
From Java8 onwards interfaces allow default methods and static methods.
From Java8 onwards interfaces allow default methods and static methods.
From Java9 onwards interfaces allow private and private static methods.
From Java9 onwards interfaces allow private and private static methods.
Moreover, all the methods you define (except above mentioned) in an interface should be implemented by another class (overridden). But, you cannot override constructors in Java.
Still if you try to define constructors in an interface it generates a compile time error.
In the following Java program, we are trying to define a constructor within an interface.
public interface MyInterface{
public abstract MyInterface();
/*{
System.out.println("This is the constructor of the interface");
}*/
public static final int num = 10;
public abstract void demo();
}
On compiling, the above program generates the following error
MyInterface.java:2: error: expected
public abstract MyInterface();
^
1 error
In short, it does not accept methods without return type in an interface. If you add return type to the MyInterface() method then it is considered as a normal method and the program gets compiled without errors.
public interface MyInterface {
public abstract void MyInterface();
public static final int num = 10;
public abstract void demo();
}
|
[
{
"code": null,
"e": 1125,
"s": 1062,
"text": "No, you cannot have a constructor within an interface in Java."
},
{
"code": null,
"e": 1219,
"s": 1125,
"text": "You can have only public, static, final variables and, public, abstract, methods as of Java7."
},
{
"code": null,
"e": 1313,
"s": 1219,
"text": "You can have only public, static, final variables and, public, abstract, methods as of Java7."
},
{
"code": null,
"e": 1385,
"s": 1313,
"text": "From Java8 onwards interfaces allow default methods and static methods."
},
{
"code": null,
"e": 1457,
"s": 1385,
"text": "From Java8 onwards interfaces allow default methods and static methods."
},
{
"code": null,
"e": 1529,
"s": 1457,
"text": "From Java9 onwards interfaces allow private and private static methods."
},
{
"code": null,
"e": 1601,
"s": 1529,
"text": "From Java9 onwards interfaces allow private and private static methods."
},
{
"code": null,
"e": 1779,
"s": 1601,
"text": "Moreover, all the methods you define (except above mentioned) in an interface should be implemented by another class (overridden). But, you cannot override constructors in Java."
},
{
"code": null,
"e": 1870,
"s": 1779,
"text": "Still if you try to define constructors in an interface it generates a compile time error."
},
{
"code": null,
"e": 1960,
"s": 1870,
"text": "In the following Java program, we are trying to define a constructor within an interface."
},
{
"code": null,
"e": 2179,
"s": 1960,
"text": "public interface MyInterface{\n public abstract MyInterface();\n /*{\n System.out.println(\"This is the constructor of the interface\");\n }*/\n public static final int num = 10;\n public abstract void demo();\n}"
},
{
"code": null,
"e": 2241,
"s": 2179,
"text": "On compiling, the above program generates the following error"
},
{
"code": null,
"e": 2321,
"s": 2241,
"text": "MyInterface.java:2: error: expected\n public abstract MyInterface();\n^\n1 error"
},
{
"code": null,
"e": 2533,
"s": 2321,
"text": "In short, it does not accept methods without return type in an interface. If you add return type to the MyInterface() method then it is considered as a normal method and the program gets compiled without errors."
},
{
"code": null,
"e": 2674,
"s": 2533,
"text": "public interface MyInterface {\n public abstract void MyInterface();\n public static final int num = 10;\n public abstract void demo();\n}"
}
] |
Longest palindromic String formed using concatenation of given strings in any order - GeeksforGeeks
|
26 May, 2021
Given an array of strings arr[] of the same length, the task is to find the longest palindromic string that can be made using the concatenation of strings in any order.
Examples:
Input: arr[] = {“aba”, “aba”} Output: abaaba
Input: arr[] = {“abc”, “dba”, “kop”, “cba”, “abd”} Output: abcdbaabdcba
Approach:
Find all the pairs of strings which are reverse of each other and store them in two different arrays pair1[] and pair2 separately and delete those pairs from the original array.
Find any palindromic string s1 in the array.
Join all the strings together of the array pair1[] into s2
Join all the strings together of the array pair2[] in reverse order into s3
Concatenate the strings s2 + s1 + s3 together to get longest palindromic string.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ implementation to find the longest// palindromic String formed using// concatenation of given strings in any order #include <bits/stdc++.h>using namespace std; // Function to find the longest palindromic// from given array of stringsvoid longestPalindrome(string a[], int n){ string pair1[n]; string pair2[n]; int r = 0; // Loop to find the pair of strings // which are reverse of each other for (int i = 0; i < n; i++) { string s = a[i]; reverse(s.begin(), s.end()); for (int j = i + 1; j < n; j++) { if (a[i] != "" && a[j] != "") { if (s == a[j]) { pair1[r] = a[i]; pair2[r++] = a[j]; a[i] = ""; a[j] = ""; break; } } } } string s1 = ""; // Loop to find if any palindromic // string is still left in the array for (int i = 0; i < n; i++) { string s = a[i]; reverse(a[i].begin(), a[i].end()); if (a[i] != "") { if (a[i] == s) { s1 = a[i]; break; } } } string ans = ""; // Update the answer with // all strings of pair1 for (int i = 0; i < r; i++) { ans = ans + pair1[i]; } // Update the answer with // palindromic string s1 if (s1 != "") { ans = ans + s1; } // Update the answer with // all strings of pair2 for (int j = r - 1; j >= 0; j--) { ans = ans + pair2[j]; } cout << ans << endl;} // Driver Codeint main(){ string a1[2] = { "aba", "aba" }; int n1 = sizeof(a1) / sizeof(a1[0]); longestPalindrome(a1, n1); string a2[5] = { "abc", "dba", "kop", "abd", "cba" }; int n2 = sizeof(a2) / sizeof(a2[0]); longestPalindrome(a2, n2);}
// Java implementation to find the longest// palindromic String formed using// concatenation of given Strings in any orderclass GFG{ // Function to find the longest palindromic// from given array of Stringsstatic void longestPalindrome(String a[], int n){ String []pair1 = new String[n]; String []pair2 = new String[n]; int r = 0; // Loop to find the pair of Strings // which are reverse of each other for (int i = 0; i < n; i++) { String s = a[i]; s = reverse(s); for (int j = i + 1; j < n; j++) { if (a[i] != "" && a[j] != "") { if (s.equals(a[j])) { pair1[r] = a[i]; pair2[r++] = a[j]; a[i] = ""; a[j] = ""; break; } } } } String s1 = ""; // Loop to find if any palindromic // String is still left in the array for (int i = 0; i < n; i++) { String s = a[i]; a[i] = reverse(a[i]); if (a[i] != "") { if (a[i].equals(s)) { s1 = a[i]; break; } } } String ans = ""; // Update the answer with // all Strings of pair1 for (int i = 0; i < r; i++) { ans = ans + pair1[i]; } // Update the answer with // palindromic String s1 if (s1 != "") { ans = ans + s1; } // Update the answer with // all Strings of pair2 for (int j = r - 1; j >= 0; j--) { ans = ans + pair2[j]; } System.out.print(ans +"\n");}static String reverse(String input){ char[] a = input.toCharArray(); int l, r = a.length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Driver Codepublic static void main(String[] args){ String []a1 = { "aba", "aba" }; int n1 = a1.length; longestPalindrome(a1, n1); String []a2 = { "abc", "dba", "kop", "abd", "cba" }; int n2 = a2.length; longestPalindrome(a2, n2);}} // This code is contributed by Rajput-Ji
# Python3 implementation to find the longest# palindromic String formed using# concatenation of given strings in any order # Function to find the longest palindromic# from given array of stringsdef longestPalindrome(a, n): pair1 = [0]*n pair2 = [0]*n r = 0 # Loop to find the pair of strings # which are reverse of each other for i in range(n): s = a[i] s = s[::-1] for j in range(i + 1, n): if (a[i] != "" and a[j] != ""): if (s == a[j]): pair1[r] = a[i] pair2[r] = a[j] r += 1 a[i] = "" a[j] = "" break s1 = "" # Loop to find if any palindromic # is still left in the array for i in range(n): s = a[i] a[i] = a[i][::-1] if (a[i] != ""): if (a[i] == s): s1 = a[i] break ans = "" # Update the answer with # all strings of pair1 for i in range(r): ans = ans + pair1[i] # Update the answer with # palindromic s1 if (s1 != ""): ans = ans + s1 # Update the answer with # all strings of pair2 for j in range(r - 1, -1, -1): ans = ans + pair2[j] print(ans) # Driver Codea1 = ["aba", "aba"]n1 = len(a1)longestPalindrome(a1, n1) a2 = ["abc", "dba", "kop","abd", "cba"]n2 = len(a2)longestPalindrome(a2, n2) # This code is contributed by mohit kumar 29
// C# implementation to find the longest// palindromic String formed using// concatenation of given Strings in any orderusing System; class GFG{ // Function to find the longest palindromic// from given array of Stringsstatic void longestPalindrome(String []a, int n){ String []pair1 = new String[n]; String []pair2 = new String[n]; int r = 0; // Loop to find the pair of Strings // which are reverse of each other for (int i = 0; i < n; i++) { String s = a[i]; s = reverse(s); for (int j = i + 1; j < n; j++) { if (a[i] != "" && a[j] != "") { if (s.Equals(a[j])) { pair1[r] = a[i]; pair2[r++] = a[j]; a[i] = ""; a[j] = ""; break; } } } } String s1 = ""; // Loop to find if any palindromic // String is still left in the array for (int i = 0; i < n; i++) { String s = a[i]; a[i] = reverse(a[i]); if (a[i] != "") { if (a[i].Equals(s)) { s1 = a[i]; break; } } } String ans = ""; // Update the answer with // all Strings of pair1 for (int i = 0; i < r; i++) { ans = ans + pair1[i]; } // Update the answer with // palindromic String s1 if (s1 != "") { ans = ans + s1; } // Update the answer with // all Strings of pair2 for (int j = r - 1; j >= 0; j--) { ans = ans + pair2[j]; } Console.Write(ans +"\n");}static String reverse(String input){ char[] a = input.ToCharArray(); int l, r = a.Length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join("",a);} // Driver Codepublic static void Main(String[] args){ String []a1 = { "aba", "aba" }; int n1 = a1.Length; longestPalindrome(a1, n1); String []a2 = { "abc", "dba", "kop", "abd", "cba" }; int n2 = a2.Length; longestPalindrome(a2, n2);}} // This code is contributed by 29AjayKumar
<script> // Javascript implementation to find the longest// palindromic String formed using// concatenation of given strings in any order // Function to find the longest palindromic// from given array of stringsfunction longestPalindrome(a, n){ var pair1 = Array(n); var pair2 = Array(n); var r = 0; // Loop to find the pair of strings // which are reverse of each other for(var i = 0; i < n; i++) { var s = a[i]; s = s.split('').reverse().join(''); for(var j = i + 1; j < n; j++) { if (a[i] != "" && a[j] != "") { if (s == a[j]) { pair1[r] = a[i]; pair2[r++] = a[j]; a[i] = ""; a[j] = ""; break; } } } } var s1 = ""; // Loop to find if any palindromic // string is still left in the array for(var i = 0; i < n; i++) { var s = a[i]; a[i] = a[i].split('').reverse().join(''); if (a[i] != "") { if (a[i] == s) { s1 = a[i]; break; } } } var ans = ""; // Update the answer with // all strings of pair1 for(var i = 0; i < r; i++) { ans = ans + pair1[i]; } // Update the answer with // palindromic string s1 if (s1 != "") { ans = ans + s1; } // Update the answer with // all strings of pair2 for(var j = r - 1; j >= 0; j--) { ans = ans + pair2[j]; } document.write(ans + "<br>");} // Driver Codevar a1 = [ "aba", "aba" ];var n1 = a1.length;longestPalindrome(a1, n1); var a2 = [ "abc", "dba", "kop", "abd", "cba" ];var n2 = a2.length;longestPalindrome(a2, n2); // This code is contributed by rrrtnx </script>
abaaba
abcdbaabdcba
mohit kumar 29
Rajput-Ji
29AjayKumar
nidhi_biet
rrrtnx
palindrome
Arrays
Strings
Arrays
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 26237,
"s": 26067,
"text": "Given an array of strings arr[] of the same length, the task is to find the longest palindromic string that can be made using the concatenation of strings in any order. "
},
{
"code": null,
"e": 26247,
"s": 26237,
"text": "Examples:"
},
{
"code": null,
"e": 26292,
"s": 26247,
"text": "Input: arr[] = {“aba”, “aba”} Output: abaaba"
},
{
"code": null,
"e": 26366,
"s": 26292,
"text": "Input: arr[] = {“abc”, “dba”, “kop”, “cba”, “abd”} Output: abcdbaabdcba "
},
{
"code": null,
"e": 26378,
"s": 26366,
"text": "Approach: "
},
{
"code": null,
"e": 26556,
"s": 26378,
"text": "Find all the pairs of strings which are reverse of each other and store them in two different arrays pair1[] and pair2 separately and delete those pairs from the original array."
},
{
"code": null,
"e": 26601,
"s": 26556,
"text": "Find any palindromic string s1 in the array."
},
{
"code": null,
"e": 26660,
"s": 26601,
"text": "Join all the strings together of the array pair1[] into s2"
},
{
"code": null,
"e": 26736,
"s": 26660,
"text": "Join all the strings together of the array pair2[] in reverse order into s3"
},
{
"code": null,
"e": 26817,
"s": 26736,
"text": "Concatenate the strings s2 + s1 + s3 together to get longest palindromic string."
},
{
"code": null,
"e": 26868,
"s": 26817,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 26872,
"s": 26868,
"text": "C++"
},
{
"code": null,
"e": 26877,
"s": 26872,
"text": "Java"
},
{
"code": null,
"e": 26885,
"s": 26877,
"text": "Python3"
},
{
"code": null,
"e": 26888,
"s": 26885,
"text": "C#"
},
{
"code": null,
"e": 26899,
"s": 26888,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the longest// palindromic String formed using// concatenation of given strings in any order #include <bits/stdc++.h>using namespace std; // Function to find the longest palindromic// from given array of stringsvoid longestPalindrome(string a[], int n){ string pair1[n]; string pair2[n]; int r = 0; // Loop to find the pair of strings // which are reverse of each other for (int i = 0; i < n; i++) { string s = a[i]; reverse(s.begin(), s.end()); for (int j = i + 1; j < n; j++) { if (a[i] != \"\" && a[j] != \"\") { if (s == a[j]) { pair1[r] = a[i]; pair2[r++] = a[j]; a[i] = \"\"; a[j] = \"\"; break; } } } } string s1 = \"\"; // Loop to find if any palindromic // string is still left in the array for (int i = 0; i < n; i++) { string s = a[i]; reverse(a[i].begin(), a[i].end()); if (a[i] != \"\") { if (a[i] == s) { s1 = a[i]; break; } } } string ans = \"\"; // Update the answer with // all strings of pair1 for (int i = 0; i < r; i++) { ans = ans + pair1[i]; } // Update the answer with // palindromic string s1 if (s1 != \"\") { ans = ans + s1; } // Update the answer with // all strings of pair2 for (int j = r - 1; j >= 0; j--) { ans = ans + pair2[j]; } cout << ans << endl;} // Driver Codeint main(){ string a1[2] = { \"aba\", \"aba\" }; int n1 = sizeof(a1) / sizeof(a1[0]); longestPalindrome(a1, n1); string a2[5] = { \"abc\", \"dba\", \"kop\", \"abd\", \"cba\" }; int n2 = sizeof(a2) / sizeof(a2[0]); longestPalindrome(a2, n2);}",
"e": 28756,
"s": 26899,
"text": null
},
{
"code": "// Java implementation to find the longest// palindromic String formed using// concatenation of given Strings in any orderclass GFG{ // Function to find the longest palindromic// from given array of Stringsstatic void longestPalindrome(String a[], int n){ String []pair1 = new String[n]; String []pair2 = new String[n]; int r = 0; // Loop to find the pair of Strings // which are reverse of each other for (int i = 0; i < n; i++) { String s = a[i]; s = reverse(s); for (int j = i + 1; j < n; j++) { if (a[i] != \"\" && a[j] != \"\") { if (s.equals(a[j])) { pair1[r] = a[i]; pair2[r++] = a[j]; a[i] = \"\"; a[j] = \"\"; break; } } } } String s1 = \"\"; // Loop to find if any palindromic // String is still left in the array for (int i = 0; i < n; i++) { String s = a[i]; a[i] = reverse(a[i]); if (a[i] != \"\") { if (a[i].equals(s)) { s1 = a[i]; break; } } } String ans = \"\"; // Update the answer with // all Strings of pair1 for (int i = 0; i < r; i++) { ans = ans + pair1[i]; } // Update the answer with // palindromic String s1 if (s1 != \"\") { ans = ans + s1; } // Update the answer with // all Strings of pair2 for (int j = r - 1; j >= 0; j--) { ans = ans + pair2[j]; } System.out.print(ans +\"\\n\");}static String reverse(String input){ char[] a = input.toCharArray(); int l, r = a.length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Driver Codepublic static void main(String[] args){ String []a1 = { \"aba\", \"aba\" }; int n1 = a1.length; longestPalindrome(a1, n1); String []a2 = { \"abc\", \"dba\", \"kop\", \"abd\", \"cba\" }; int n2 = a2.length; longestPalindrome(a2, n2);}} // This code is contributed by Rajput-Ji",
"e": 30953,
"s": 28756,
"text": null
},
{
"code": "# Python3 implementation to find the longest# palindromic String formed using# concatenation of given strings in any order # Function to find the longest palindromic# from given array of stringsdef longestPalindrome(a, n): pair1 = [0]*n pair2 = [0]*n r = 0 # Loop to find the pair of strings # which are reverse of each other for i in range(n): s = a[i] s = s[::-1] for j in range(i + 1, n): if (a[i] != \"\" and a[j] != \"\"): if (s == a[j]): pair1[r] = a[i] pair2[r] = a[j] r += 1 a[i] = \"\" a[j] = \"\" break s1 = \"\" # Loop to find if any palindromic # is still left in the array for i in range(n): s = a[i] a[i] = a[i][::-1] if (a[i] != \"\"): if (a[i] == s): s1 = a[i] break ans = \"\" # Update the answer with # all strings of pair1 for i in range(r): ans = ans + pair1[i] # Update the answer with # palindromic s1 if (s1 != \"\"): ans = ans + s1 # Update the answer with # all strings of pair2 for j in range(r - 1, -1, -1): ans = ans + pair2[j] print(ans) # Driver Codea1 = [\"aba\", \"aba\"]n1 = len(a1)longestPalindrome(a1, n1) a2 = [\"abc\", \"dba\", \"kop\",\"abd\", \"cba\"]n2 = len(a2)longestPalindrome(a2, n2) # This code is contributed by mohit kumar 29",
"e": 32418,
"s": 30953,
"text": null
},
{
"code": "// C# implementation to find the longest// palindromic String formed using// concatenation of given Strings in any orderusing System; class GFG{ // Function to find the longest palindromic// from given array of Stringsstatic void longestPalindrome(String []a, int n){ String []pair1 = new String[n]; String []pair2 = new String[n]; int r = 0; // Loop to find the pair of Strings // which are reverse of each other for (int i = 0; i < n; i++) { String s = a[i]; s = reverse(s); for (int j = i + 1; j < n; j++) { if (a[i] != \"\" && a[j] != \"\") { if (s.Equals(a[j])) { pair1[r] = a[i]; pair2[r++] = a[j]; a[i] = \"\"; a[j] = \"\"; break; } } } } String s1 = \"\"; // Loop to find if any palindromic // String is still left in the array for (int i = 0; i < n; i++) { String s = a[i]; a[i] = reverse(a[i]); if (a[i] != \"\") { if (a[i].Equals(s)) { s1 = a[i]; break; } } } String ans = \"\"; // Update the answer with // all Strings of pair1 for (int i = 0; i < r; i++) { ans = ans + pair1[i]; } // Update the answer with // palindromic String s1 if (s1 != \"\") { ans = ans + s1; } // Update the answer with // all Strings of pair2 for (int j = r - 1; j >= 0; j--) { ans = ans + pair2[j]; } Console.Write(ans +\"\\n\");}static String reverse(String input){ char[] a = input.ToCharArray(); int l, r = a.Length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join(\"\",a);} // Driver Codepublic static void Main(String[] args){ String []a1 = { \"aba\", \"aba\" }; int n1 = a1.Length; longestPalindrome(a1, n1); String []a2 = { \"abc\", \"dba\", \"kop\", \"abd\", \"cba\" }; int n2 = a2.Length; longestPalindrome(a2, n2);}} // This code is contributed by 29AjayKumar",
"e": 34633,
"s": 32418,
"text": null
},
{
"code": "<script> // Javascript implementation to find the longest// palindromic String formed using// concatenation of given strings in any order // Function to find the longest palindromic// from given array of stringsfunction longestPalindrome(a, n){ var pair1 = Array(n); var pair2 = Array(n); var r = 0; // Loop to find the pair of strings // which are reverse of each other for(var i = 0; i < n; i++) { var s = a[i]; s = s.split('').reverse().join(''); for(var j = i + 1; j < n; j++) { if (a[i] != \"\" && a[j] != \"\") { if (s == a[j]) { pair1[r] = a[i]; pair2[r++] = a[j]; a[i] = \"\"; a[j] = \"\"; break; } } } } var s1 = \"\"; // Loop to find if any palindromic // string is still left in the array for(var i = 0; i < n; i++) { var s = a[i]; a[i] = a[i].split('').reverse().join(''); if (a[i] != \"\") { if (a[i] == s) { s1 = a[i]; break; } } } var ans = \"\"; // Update the answer with // all strings of pair1 for(var i = 0; i < r; i++) { ans = ans + pair1[i]; } // Update the answer with // palindromic string s1 if (s1 != \"\") { ans = ans + s1; } // Update the answer with // all strings of pair2 for(var j = r - 1; j >= 0; j--) { ans = ans + pair2[j]; } document.write(ans + \"<br>\");} // Driver Codevar a1 = [ \"aba\", \"aba\" ];var n1 = a1.length;longestPalindrome(a1, n1); var a2 = [ \"abc\", \"dba\", \"kop\", \"abd\", \"cba\" ];var n2 = a2.length;longestPalindrome(a2, n2); // This code is contributed by rrrtnx </script>",
"e": 36488,
"s": 34633,
"text": null
},
{
"code": null,
"e": 36508,
"s": 36488,
"text": "abaaba\nabcdbaabdcba"
},
{
"code": null,
"e": 36525,
"s": 36510,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 36535,
"s": 36525,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 36547,
"s": 36535,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36558,
"s": 36547,
"text": "nidhi_biet"
},
{
"code": null,
"e": 36565,
"s": 36558,
"text": "rrrtnx"
},
{
"code": null,
"e": 36576,
"s": 36565,
"text": "palindrome"
},
{
"code": null,
"e": 36583,
"s": 36576,
"text": "Arrays"
},
{
"code": null,
"e": 36591,
"s": 36583,
"text": "Strings"
},
{
"code": null,
"e": 36598,
"s": 36591,
"text": "Arrays"
},
{
"code": null,
"e": 36606,
"s": 36598,
"text": "Strings"
},
{
"code": null,
"e": 36617,
"s": 36606,
"text": "palindrome"
},
{
"code": null,
"e": 36715,
"s": 36617,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36742,
"s": 36715,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 36773,
"s": 36742,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 36798,
"s": 36773,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 36836,
"s": 36798,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 36857,
"s": 36836,
"text": "Next Greater Element"
},
{
"code": null,
"e": 36882,
"s": 36857,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 36942,
"s": 36882,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 36957,
"s": 36942,
"text": "C++ Data Types"
},
{
"code": null,
"e": 36991,
"s": 36957,
"text": "Longest Common Subsequence | DP-4"
}
] |
How to count files in a directory using PHP? - GeeksforGeeks
|
07 Jan, 2022
PHP contains many functions like count(), iterator_count(), glob(), openddir(), readdir(), scandir() and FilesystemIterator() to count number of files in a directory.count() Function: The count() functions is an array function which is used to count all elements in an array or something in an object. This function uses COUNT_RECURSIVE as a mode to recursively count the array that is useful for counting all the elements of a multidimensional array.Syntax:
int count( mixed $array_or_countable, int $mode = COUNT_NORMAL )
glob() Function: The glob() function is a Filesystem function that searches all possible pathnames matching pattern according to the rules used by the libc glob() function.Syntax:
glob( string $pattern, int $flags = 0 )
Program 1: This program uses glob() and count() function to count all files within the directory.
php
<?php // Set the current working directory$directory = getcwd()."/"; // Initialize filecount variable$filecount = 0; $files2 = glob( $directory ."*" ); if( $files2 ) { $filecount = count($files2);} echo $filecount . "files "; ?>
Output:
20 files
openddir() Function: The openddir() function is used to open a directory handle. The path of the directory to be opened is sent as a parameter to the opendir() function and it returns a directory handle resource on success, or FALSE on failure.Syntax:
opendir( string $path, resource $context )
readdir() Function: The readdir() function is a directory function which reads the entries from directory handle those are returned in the order in which they are stored by the filesystem.Syntax:
readdir( resource $dir_handle )
Program 2: This program uses openddir() and readdir() function to count all files within the directory.
php
<?php // Set the current working directory$dir = getcwd(); // Initialize the counter variable to 0$i = 0; if( $handle = opendir($dir) ) { while( ($file = readdir($handle)) !== false ) { if( !in_array($file, array('.', '..')) && !is_dir($dir.$file)) $i++; }} // Display resultecho "$i files"; ?>
Output:
20 files
scandir() Function: The scandir() function is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.Syntax:
scandir( string $directory, int $sorting_order = SCANDIR_SORT_ASCENDING, resource $context )
Program 3: This program uses scandir() and count() function to count all files within the directory.
php
<?php // Set the current working directory$directory = getcwd()."/"; // Returns array of files$files1 = scandir($directory); // Count number of files and store them to variable$num_files = count($files1) - 2; echo $num_files . " files"; ?>
Output:
20 files
FilesystemIterator() Function: The FilesystemIterator::__construct() function is used to create a new filesystem iterator from the path.Syntax:
FilesystemIterator::__construct( string $path,
int $flags = FilesystemIterator::KEY_AS_PATHNAME
| FilesystemIterator::CURRENT_AS_FILEINFO
| FilesystemIterator::SKIP_DOTS )
iterator_count() Function: The iterator_count() function is SPL is used to count the iterator elements.Syntax:
int iterator_count( $iterator )
Program 4: This program uses FilesystemIterator() and iterator_count() function to count all files within the directory.
php
<?php $fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS); printf("%d files", iterator_count($fi)); ?>
Output:
20 files
sagar0719kumar
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to receive JSON POST with PHP ?
How to pass JavaScript variables to PHP ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
|
[
{
"code": null,
"e": 25699,
"s": 25671,
"text": "\n07 Jan, 2022"
},
{
"code": null,
"e": 26159,
"s": 25699,
"text": "PHP contains many functions like count(), iterator_count(), glob(), openddir(), readdir(), scandir() and FilesystemIterator() to count number of files in a directory.count() Function: The count() functions is an array function which is used to count all elements in an array or something in an object. This function uses COUNT_RECURSIVE as a mode to recursively count the array that is useful for counting all the elements of a multidimensional array.Syntax: "
},
{
"code": null,
"e": 26224,
"s": 26159,
"text": "int count( mixed $array_or_countable, int $mode = COUNT_NORMAL )"
},
{
"code": null,
"e": 26406,
"s": 26224,
"text": "glob() Function: The glob() function is a Filesystem function that searches all possible pathnames matching pattern according to the rules used by the libc glob() function.Syntax: "
},
{
"code": null,
"e": 26446,
"s": 26406,
"text": "glob( string $pattern, int $flags = 0 )"
},
{
"code": null,
"e": 26546,
"s": 26446,
"text": "Program 1: This program uses glob() and count() function to count all files within the directory. "
},
{
"code": null,
"e": 26550,
"s": 26546,
"text": "php"
},
{
"code": "<?php // Set the current working directory$directory = getcwd().\"/\"; // Initialize filecount variable$filecount = 0; $files2 = glob( $directory .\"*\" ); if( $files2 ) { $filecount = count($files2);} echo $filecount . \"files \"; ?>",
"e": 26782,
"s": 26550,
"text": null
},
{
"code": null,
"e": 26791,
"s": 26782,
"text": "Output: "
},
{
"code": null,
"e": 26800,
"s": 26791,
"text": "20 files"
},
{
"code": null,
"e": 27054,
"s": 26800,
"text": "openddir() Function: The openddir() function is used to open a directory handle. The path of the directory to be opened is sent as a parameter to the opendir() function and it returns a directory handle resource on success, or FALSE on failure.Syntax: "
},
{
"code": null,
"e": 27097,
"s": 27054,
"text": "opendir( string $path, resource $context )"
},
{
"code": null,
"e": 27295,
"s": 27097,
"text": "readdir() Function: The readdir() function is a directory function which reads the entries from directory handle those are returned in the order in which they are stored by the filesystem.Syntax: "
},
{
"code": null,
"e": 27327,
"s": 27295,
"text": "readdir( resource $dir_handle )"
},
{
"code": null,
"e": 27432,
"s": 27327,
"text": "Program 2: This program uses openddir() and readdir() function to count all files within the directory. "
},
{
"code": null,
"e": 27436,
"s": 27432,
"text": "php"
},
{
"code": "<?php // Set the current working directory$dir = getcwd(); // Initialize the counter variable to 0$i = 0; if( $handle = opendir($dir) ) { while( ($file = readdir($handle)) !== false ) { if( !in_array($file, array('.', '..')) && !is_dir($dir.$file)) $i++; }} // Display resultecho \"$i files\"; ?>",
"e": 27760,
"s": 27436,
"text": null
},
{
"code": null,
"e": 27769,
"s": 27760,
"text": "Output: "
},
{
"code": null,
"e": 27778,
"s": 27769,
"text": "20 files"
},
{
"code": null,
"e": 28008,
"s": 27778,
"text": "scandir() Function: The scandir() function is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.Syntax: "
},
{
"code": null,
"e": 28101,
"s": 28008,
"text": "scandir( string $directory, int $sorting_order = SCANDIR_SORT_ASCENDING, resource $context )"
},
{
"code": null,
"e": 28203,
"s": 28101,
"text": "Program 3: This program uses scandir() and count() function to count all files within the directory. "
},
{
"code": null,
"e": 28207,
"s": 28203,
"text": "php"
},
{
"code": "<?php // Set the current working directory$directory = getcwd().\"/\"; // Returns array of files$files1 = scandir($directory); // Count number of files and store them to variable$num_files = count($files1) - 2; echo $num_files . \" files\"; ?>",
"e": 28449,
"s": 28207,
"text": null
},
{
"code": null,
"e": 28458,
"s": 28449,
"text": "Output: "
},
{
"code": null,
"e": 28467,
"s": 28458,
"text": "20 files"
},
{
"code": null,
"e": 28613,
"s": 28467,
"text": "FilesystemIterator() Function: The FilesystemIterator::__construct() function is used to create a new filesystem iterator from the path.Syntax: "
},
{
"code": null,
"e": 28806,
"s": 28613,
"text": "FilesystemIterator::__construct( string $path, \n int $flags = FilesystemIterator::KEY_AS_PATHNAME \n | FilesystemIterator::CURRENT_AS_FILEINFO \n | FilesystemIterator::SKIP_DOTS )"
},
{
"code": null,
"e": 28919,
"s": 28806,
"text": "iterator_count() Function: The iterator_count() function is SPL is used to count the iterator elements.Syntax: "
},
{
"code": null,
"e": 28951,
"s": 28919,
"text": "int iterator_count( $iterator )"
},
{
"code": null,
"e": 29072,
"s": 28951,
"text": "Program 4: This program uses FilesystemIterator() and iterator_count() function to count all files within the directory."
},
{
"code": null,
"e": 29076,
"s": 29072,
"text": "php"
},
{
"code": "<?php $fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS); printf(\"%d files\", iterator_count($fi)); ?>",
"e": 29196,
"s": 29076,
"text": null
},
{
"code": null,
"e": 29206,
"s": 29196,
"text": "Output: "
},
{
"code": null,
"e": 29216,
"s": 29206,
"text": "20 files "
},
{
"code": null,
"e": 29231,
"s": 29216,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 29238,
"s": 29231,
"text": "Picked"
},
{
"code": null,
"e": 29242,
"s": 29238,
"text": "PHP"
},
{
"code": null,
"e": 29255,
"s": 29242,
"text": "PHP Programs"
},
{
"code": null,
"e": 29272,
"s": 29255,
"text": "Web Technologies"
},
{
"code": null,
"e": 29299,
"s": 29272,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29303,
"s": 29299,
"text": "PHP"
},
{
"code": null,
"e": 29401,
"s": 29303,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29451,
"s": 29401,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 29491,
"s": 29451,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 29536,
"s": 29491,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 29572,
"s": 29536,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 29614,
"s": 29572,
"text": "How to pass JavaScript variables to PHP ?"
},
{
"code": null,
"e": 29664,
"s": 29614,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 29704,
"s": 29664,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 29756,
"s": 29704,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 29798,
"s": 29756,
"text": "How to pass JavaScript variables to PHP ?"
}
] |
Matplotlib.axes.Axes.get_legend_handles_labels() in Python - GeeksforGeeks
|
19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.get_legend_handles_labels() function in axes module of matplotlib library is used to return the handles and labels for legend.
Syntax: Axes.get_legend_handles_labels(self)
Parameters: This method does not accepts any parameters.
Return: This function return the handles and labels for legend.
Below examples illustrate the matplotlib.axes.Axes.get_legend_handles_labels() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np fig, ax = plt.subplots()ax.plot([1, 6, 3, 8, 34, 13, 56, 67], color ="green") h, l = ax.get_legend_handles_labels()# print(h, l)text ="Legend is present"if h ==[]: text ="No legend present"else: text+="and labels are : "+str(l) ax.text(2.5, 60, text, fontweight ="bold")fig.suptitle('matplotlib.axes.Axes.get_legend_handles_labels()\ function Example\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npnp.random.seed(19680801)import matplotlib.pyplot as plt fig, ax = plt.subplots()for color in [ 'tab:green', 'tab:blue', 'tab:orange']: n = 70 x, y = np.random.rand(2, n) scale = 1000.0 * np.random.rand(n) ax.scatter(x, y, c = color, s = scale, label = color, alpha = 0.35) ax.legend()ax.grid(True) h, l = ax.get_legend_handles_labels()print(h, l)text =" Legend is present"if h ==[]: text ="No legend present"else: text+=" and labels are : \n"+str(l) ax.text(0.15, 0.45, text, fontweight ="bold")fig.suptitle('matplotlib.axes.Axes.get_legend_handles_labels()\ function Example\n', fontweight ="bold")fig.canvas.draw()plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 25837,
"s": 25537,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute."
},
{
"code": null,
"e": 25973,
"s": 25837,
"text": "The Axes.get_legend_handles_labels() function in axes module of matplotlib library is used to return the handles and labels for legend."
},
{
"code": null,
"e": 26018,
"s": 25973,
"text": "Syntax: Axes.get_legend_handles_labels(self)"
},
{
"code": null,
"e": 26075,
"s": 26018,
"text": "Parameters: This method does not accepts any parameters."
},
{
"code": null,
"e": 26139,
"s": 26075,
"text": "Return: This function return the handles and labels for legend."
},
{
"code": null,
"e": 26247,
"s": 26139,
"text": "Below examples illustrate the matplotlib.axes.Axes.get_legend_handles_labels() function in matplotlib.axes:"
},
{
"code": null,
"e": 26258,
"s": 26247,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib function import matplotlib.pyplot as pltimport numpy as np fig, ax = plt.subplots()ax.plot([1, 6, 3, 8, 34, 13, 56, 67], color =\"green\") h, l = ax.get_legend_handles_labels()# print(h, l)text =\"Legend is present\"if h ==[]: text =\"No legend present\"else: text+=\"and labels are : \"+str(l) ax.text(2.5, 60, text, fontweight =\"bold\")fig.suptitle('matplotlib.axes.Axes.get_legend_handles_labels()\\ function Example\\n', fontweight =\"bold\")fig.canvas.draw()plt.show()",
"e": 26767,
"s": 26258,
"text": null
},
{
"code": null,
"e": 26775,
"s": 26767,
"text": "Output:"
},
{
"code": null,
"e": 26786,
"s": 26775,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib functionimport numpy as npnp.random.seed(19680801)import matplotlib.pyplot as plt fig, ax = plt.subplots()for color in [ 'tab:green', 'tab:blue', 'tab:orange']: n = 70 x, y = np.random.rand(2, n) scale = 1000.0 * np.random.rand(n) ax.scatter(x, y, c = color, s = scale, label = color, alpha = 0.35) ax.legend()ax.grid(True) h, l = ax.get_legend_handles_labels()print(h, l)text =\" Legend is present\"if h ==[]: text =\"No legend present\"else: text+=\" and labels are : \\n\"+str(l) ax.text(0.15, 0.45, text, fontweight =\"bold\")fig.suptitle('matplotlib.axes.Axes.get_legend_handles_labels()\\ function Example\\n', fontweight =\"bold\")fig.canvas.draw()plt.show()",
"e": 27518,
"s": 26786,
"text": null
},
{
"code": null,
"e": 27526,
"s": 27518,
"text": "Output:"
},
{
"code": null,
"e": 27544,
"s": 27526,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27551,
"s": 27544,
"text": "Python"
},
{
"code": null,
"e": 27649,
"s": 27551,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27681,
"s": 27649,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27723,
"s": 27681,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27765,
"s": 27723,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27792,
"s": 27765,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27848,
"s": 27792,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27887,
"s": 27848,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27909,
"s": 27887,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27940,
"s": 27909,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27969,
"s": 27940,
"text": "Create a directory in Python"
}
] |
random.betavariate() method in Python - GeeksforGeeks
|
17 May, 2020
betavariate() is an inbuilt method of the random module. It is used to return a random floating point number with beta distribution. The returned value is between 0 and 1.
Syntax : random.betavariate(alpha, beta)
Parameters :alpha : greater than 0beta : greater than 0
Returns : a random beta distribution floating number between 0 and 1
Example 1:
# import the random moduleimport random # determining the values of the parametersalpha = 5beta = 10 # using the betavariate() methodprint(random.betavariate(alpha, beta))
Output :
0.5148685287422776
Example 2: We can generate the number multiple times and plot a graph to observe the beta distribution.
# import the required librariesimport randomimport matplotlib.pyplot as plt # store the random numbers in a # listnums = []low = 10high = 100mode = 20 for i in range(100): temp = random.betavariate(5, 10) nums.append(temp) # plotting a graphplt.plot(nums)plt.show()
Output :
Python-random
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
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 25047,
"s": 25019,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 25219,
"s": 25047,
"text": "betavariate() is an inbuilt method of the random module. It is used to return a random floating point number with beta distribution. The returned value is between 0 and 1."
},
{
"code": null,
"e": 25260,
"s": 25219,
"text": "Syntax : random.betavariate(alpha, beta)"
},
{
"code": null,
"e": 25316,
"s": 25260,
"text": "Parameters :alpha : greater than 0beta : greater than 0"
},
{
"code": null,
"e": 25385,
"s": 25316,
"text": "Returns : a random beta distribution floating number between 0 and 1"
},
{
"code": null,
"e": 25396,
"s": 25385,
"text": "Example 1:"
},
{
"code": "# import the random moduleimport random # determining the values of the parametersalpha = 5beta = 10 # using the betavariate() methodprint(random.betavariate(alpha, beta))",
"e": 25570,
"s": 25396,
"text": null
},
{
"code": null,
"e": 25579,
"s": 25570,
"text": "Output :"
},
{
"code": null,
"e": 25598,
"s": 25579,
"text": "0.5148685287422776"
},
{
"code": null,
"e": 25702,
"s": 25598,
"text": "Example 2: We can generate the number multiple times and plot a graph to observe the beta distribution."
},
{
"code": "# import the required librariesimport randomimport matplotlib.pyplot as plt # store the random numbers in a # listnums = []low = 10high = 100mode = 20 for i in range(100): temp = random.betavariate(5, 10) nums.append(temp) # plotting a graphplt.plot(nums)plt.show()",
"e": 25983,
"s": 25702,
"text": null
},
{
"code": null,
"e": 25992,
"s": 25983,
"text": "Output :"
},
{
"code": null,
"e": 26006,
"s": 25992,
"text": "Python-random"
},
{
"code": null,
"e": 26013,
"s": 26006,
"text": "Python"
},
{
"code": null,
"e": 26111,
"s": 26013,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26139,
"s": 26111,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 26189,
"s": 26139,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 26211,
"s": 26189,
"text": "Python map() function"
},
{
"code": null,
"e": 26255,
"s": 26211,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 26273,
"s": 26255,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26296,
"s": 26273,
"text": "Taking input in Python"
},
{
"code": null,
"e": 26331,
"s": 26296,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26363,
"s": 26331,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26385,
"s": 26363,
"text": "Enumerate() in Python"
}
] |
PyQt5 - Change state of Radio Button - GeeksforGeeks
|
22 Apr, 2020
In this article we will see how to change the state of radio button. Although with the help of setChecked method we can we make the radio button checked but when we use this method on the checked radio button there will be no change in the state of radio button.
In order to change the state of radio button when push button is pressed we have to do the following –
1. Create a radio button2. Create a push button3. Connect a method to push button such that when push button get pressed method get called4. In the calling method with the help of nextCheckState method change the state of radio button.
Below is the implement.
# 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, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a radio button self.radio_button = QRadioButton(self) # setting geometry of radio button self.radio_button.setGeometry(200, 150, 120, 40) # setting text to radio button self.radio_button.setText("Radio Button") # creating push button push = QPushButton("Press", self) # setting geometry of push button push.setGeometry(200, 200, 100, 40) # connect method to push button push.clicked.connect(self.method) def method(self): # changing the state of radio button self.radio_button.nextCheckState() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
output :
Python-gui
Python-PyQt
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": "\n22 Apr, 2020"
},
{
"code": null,
"e": 25800,
"s": 25537,
"text": "In this article we will see how to change the state of radio button. Although with the help of setChecked method we can we make the radio button checked but when we use this method on the checked radio button there will be no change in the state of radio button."
},
{
"code": null,
"e": 25903,
"s": 25800,
"text": "In order to change the state of radio button when push button is pressed we have to do the following –"
},
{
"code": null,
"e": 26139,
"s": 25903,
"text": "1. Create a radio button2. Create a push button3. Connect a method to push button such that when push button get pressed method get called4. In the calling method with the help of nextCheckState method change the state of radio button."
},
{
"code": null,
"e": 26163,
"s": 26139,
"text": "Below is the implement."
},
{
"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, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a radio button self.radio_button = QRadioButton(self) # setting geometry of radio button self.radio_button.setGeometry(200, 150, 120, 40) # setting text to radio button self.radio_button.setText(\"Radio Button\") # creating push button push = QPushButton(\"Press\", self) # setting geometry of push button push.setGeometry(200, 200, 100, 40) # connect method to push button push.clicked.connect(self.method) def method(self): # changing the state of radio button self.radio_button.nextCheckState() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27450,
"s": 26163,
"text": null
},
{
"code": null,
"e": 27459,
"s": 27450,
"text": "output :"
},
{
"code": null,
"e": 27470,
"s": 27459,
"text": "Python-gui"
},
{
"code": null,
"e": 27482,
"s": 27470,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27489,
"s": 27482,
"text": "Python"
},
{
"code": null,
"e": 27587,
"s": 27489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27619,
"s": 27587,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27661,
"s": 27619,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27703,
"s": 27661,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27730,
"s": 27703,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27786,
"s": 27730,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27808,
"s": 27786,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27847,
"s": 27808,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27878,
"s": 27847,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27907,
"s": 27878,
"text": "Create a directory in Python"
}
] |
Wipro interview questions for laterals | Set 1 - GeeksforGeeks
|
22 Aug, 2018
25 question1hr timeAll Are MCQ:1 mark each, no negative marksDomain: C language
1)
int main(){ int i; i = 0; if (x=0) { printf("x is zero"); } else { printf("x is not zero"); }}
2)
int main(){ int i = -3; printf("%d n", (++i + ++i));}
3)
int main(){ int x = 0xF01DEAD; printf("%X n",(x>>1)<<1);}
4)
int main(){ char* s1 ; char* s2 ; s1 = "FIRST NAME"; s2 = "LAST NAME"; strcpy(s1,s2); printf("%s %s n",s1,s2);}
5)
int main{ struct Student { int a; char b; char c; float f; }s1; printf("%dn",sizeof(s1));}
6)
int main{ struct Student { short a[5]; union Student { long c; float f; }u1; }s1; printf("%dn",sizeof(s1));}
7)
int main(){ for (i=0; i<=2; i++) for (j=0; j<=i; j++) for(k=0; k<=j; k++) printf(""hello world");}
8)
int main(){ for (count=5; sum+=--count; ) printf("%d n",sum);}
9)
int main(){ int i=0; while (i<10); print("hello world")'}
10)
int main(){ (x && (x&(x-1))) --- indicates what?}
some more on pointers, preprocessors and static
If you like GeeksQuiz and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Wipro
Wipro-interview-experience
Interview Experiences
Wipro
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Amazon Interview Experience for SDE-1 (Off-Campus) 2022
Amazon Interview Experience
Amazon Interview Experience for SDE-1
Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1 (On-Campus)
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
EPAM Interview Experience (Off-Campus)
|
[
{
"code": null,
"e": 26287,
"s": 26259,
"text": "\n22 Aug, 2018"
},
{
"code": null,
"e": 26367,
"s": 26287,
"text": "25 question1hr timeAll Are MCQ:1 mark each, no negative marksDomain: C language"
},
{
"code": null,
"e": 26370,
"s": 26367,
"text": "1)"
},
{
"code": "int main(){ int i; i = 0; if (x=0) { printf(\"x is zero\"); } else { printf(\"x is not zero\"); }}",
"e": 26503,
"s": 26370,
"text": null
},
{
"code": null,
"e": 26506,
"s": 26503,
"text": "2)"
},
{
"code": "int main(){ int i = -3; printf(\"%d n\", (++i + ++i));}",
"e": 26566,
"s": 26506,
"text": null
},
{
"code": null,
"e": 26569,
"s": 26566,
"text": "3)"
},
{
"code": "int main(){ int x = 0xF01DEAD; printf(\"%X n\",(x>>1)<<1);}",
"e": 26633,
"s": 26569,
"text": null
},
{
"code": null,
"e": 26636,
"s": 26633,
"text": "4)"
},
{
"code": "int main(){ char* s1 ; char* s2 ; s1 = \"FIRST NAME\"; s2 = \"LAST NAME\"; strcpy(s1,s2); printf(\"%s %s n\",s1,s2);}",
"e": 26766,
"s": 26636,
"text": null
},
{
"code": null,
"e": 26769,
"s": 26766,
"text": "5)"
},
{
"code": "int main{ struct Student { int a; char b; char c; float f; }s1; printf(\"%dn\",sizeof(s1));}",
"e": 26900,
"s": 26769,
"text": null
},
{
"code": null,
"e": 26903,
"s": 26900,
"text": "6)"
},
{
"code": "int main{ struct Student { short a[5]; union Student { long c; float f; }u1; }s1; printf(\"%dn\",sizeof(s1));}",
"e": 27074,
"s": 26903,
"text": null
},
{
"code": null,
"e": 27077,
"s": 27074,
"text": "7)"
},
{
"code": "int main(){ for (i=0; i<=2; i++) for (j=0; j<=i; j++) for(k=0; k<=j; k++) printf(\"\"hello world\");}",
"e": 27204,
"s": 27077,
"text": null
},
{
"code": null,
"e": 27207,
"s": 27204,
"text": "8)"
},
{
"code": "int main(){ for (count=5; sum+=--count; ) printf(\"%d n\",sum);}",
"e": 27280,
"s": 27207,
"text": null
},
{
"code": null,
"e": 27283,
"s": 27280,
"text": "9)"
},
{
"code": "int main(){ int i=0; while (i<10); print(\"hello world\")'}",
"e": 27354,
"s": 27283,
"text": null
},
{
"code": null,
"e": 27358,
"s": 27354,
"text": "10)"
},
{
"code": "int main(){ (x && (x&(x-1))) --- indicates what?}",
"e": 27413,
"s": 27358,
"text": null
},
{
"code": null,
"e": 27461,
"s": 27413,
"text": "some more on pointers, preprocessors and static"
},
{
"code": null,
"e": 27678,
"s": 27461,
"text": "If you like GeeksQuiz and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27684,
"s": 27678,
"text": "Wipro"
},
{
"code": null,
"e": 27711,
"s": 27684,
"text": "Wipro-interview-experience"
},
{
"code": null,
"e": 27733,
"s": 27711,
"text": "Interview Experiences"
},
{
"code": null,
"e": 27739,
"s": 27733,
"text": "Wipro"
},
{
"code": null,
"e": 27837,
"s": 27739,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27888,
"s": 27837,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 27930,
"s": 27888,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 27986,
"s": 27930,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022"
},
{
"code": null,
"e": 28014,
"s": 27986,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 28052,
"s": 28014,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 28129,
"s": 28052,
"text": "Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)"
},
{
"code": null,
"e": 28175,
"s": 28129,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 28225,
"s": 28175,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 28297,
"s": 28225,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
}
] |
Python unittest - assertEqual() function - GeeksforGeeks
|
29 Aug, 2020
assertEqual() in Python is a unittest library function that is used in unit testing to check the equality of two values. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both input values are equal assertEqual() will return true else return false.
Syntax: assertEqual(firstValue, secondValue, message)
Parameters: assertEqual() accept three parameter which are listed below with explanation:
firstValue variable of any type which is used in the comparison by function
secondValue: variable of any type which is used in the comparison by function
message: a string sentence as a message which got displayed when the test case got failed.
Listed below are two different examples illustrating the positive and negative test case for given assert function:
Example 1: Negative Test case
Python3
# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function to test equality of two value def test_negative(self): firstValue = "geeks" secondValue = "gfg" # error message in case if test case got failed message = "First value and second value are not equal !" # assertEqual() to check equality of first & second value self.assertEqual(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()
Output:
F
======================================================================
FAIL: test_negative (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "p1.py", line 12, in test_negative
self.assertEqual(firstValue, secondValue, message)
AssertionError: 'geeks' != 'gfg'
- geeks
+ gfg
: First value and second value are not equal!
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
Example 2: Positive Test case
Python3
# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function to test equality of two value def test_positive(self): firstValue = "geeks" secondValue = "geeks" # error message in case if test case got failed message = "First value and second value are not equal !" # assertEqual() to check equality of first & second value self.assertEqual(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Reference: https://docs.python.org/3/library/unittest.html
Python unittest-library
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": 25755,
"s": 25727,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 26071,
"s": 25755,
"text": "assertEqual() in Python is a unittest library function that is used in unit testing to check the equality of two values. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both input values are equal assertEqual() will return true else return false."
},
{
"code": null,
"e": 26125,
"s": 26071,
"text": "Syntax: assertEqual(firstValue, secondValue, message)"
},
{
"code": null,
"e": 26215,
"s": 26125,
"text": "Parameters: assertEqual() accept three parameter which are listed below with explanation:"
},
{
"code": null,
"e": 26292,
"s": 26215,
"text": "firstValue variable of any type which is used in the comparison by function"
},
{
"code": null,
"e": 26370,
"s": 26292,
"text": "secondValue: variable of any type which is used in the comparison by function"
},
{
"code": null,
"e": 26461,
"s": 26370,
"text": "message: a string sentence as a message which got displayed when the test case got failed."
},
{
"code": null,
"e": 26577,
"s": 26461,
"text": "Listed below are two different examples illustrating the positive and negative test case for given assert function:"
},
{
"code": null,
"e": 26607,
"s": 26577,
"text": "Example 1: Negative Test case"
},
{
"code": null,
"e": 26615,
"s": 26607,
"text": "Python3"
},
{
"code": "# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function to test equality of two value def test_negative(self): firstValue = \"geeks\" secondValue = \"gfg\" # error message in case if test case got failed message = \"First value and second value are not equal !\" # assertEqual() to check equality of first & second value self.assertEqual(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()",
"e": 27113,
"s": 26615,
"text": null
},
{
"code": null,
"e": 27121,
"s": 27113,
"text": "Output:"
},
{
"code": null,
"e": 27655,
"s": 27121,
"text": "F\n======================================================================\nFAIL: test_negative (__main__.TestStringMethods)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"p1.py\", line 12, in test_negative\n self.assertEqual(firstValue, secondValue, message)\nAssertionError: 'geeks' != 'gfg'\n- geeks\n+ gfg\n : First value and second value are not equal!\n\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nFAILED (failures=1)\n"
},
{
"code": null,
"e": 27685,
"s": 27655,
"text": "Example 2: Positive Test case"
},
{
"code": null,
"e": 27693,
"s": 27685,
"text": "Python3"
},
{
"code": "# unit test caseimport unittest class TestStringMethods(unittest.TestCase): # test function to test equality of two value def test_positive(self): firstValue = \"geeks\" secondValue = \"geeks\" # error message in case if test case got failed message = \"First value and second value are not equal !\" # assertEqual() to check equality of first & second value self.assertEqual(firstValue, secondValue, message) if __name__ == '__main__': unittest.main()",
"e": 28193,
"s": 27693,
"text": null
},
{
"code": null,
"e": 28201,
"s": 28193,
"text": "Output:"
},
{
"code": null,
"e": 28302,
"s": 28201,
"text": ".\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n\n\n"
},
{
"code": null,
"e": 28361,
"s": 28302,
"text": "Reference: https://docs.python.org/3/library/unittest.html"
},
{
"code": null,
"e": 28385,
"s": 28361,
"text": "Python unittest-library"
},
{
"code": null,
"e": 28392,
"s": 28385,
"text": "Python"
},
{
"code": null,
"e": 28490,
"s": 28392,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28508,
"s": 28490,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28543,
"s": 28508,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28575,
"s": 28543,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28597,
"s": 28575,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28639,
"s": 28597,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28669,
"s": 28639,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28695,
"s": 28669,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28724,
"s": 28695,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28768,
"s": 28724,
"text": "Reading and Writing to text files in Python"
}
] |
Image Slider in Android using ViewPager - GeeksforGeeks
|
15 Sep, 2020
When talking about Android Apps, the first thing that comes to mind is variety. There are so many varieties of Android apps providing the user with beautiful dynamic UI. One such feature is to navigate in the Android Apps using the left and right swipes as opposed to clicking on Buttons. Not only does it look more simple and elegant but also provides ease of access to the user. There are many apps that use this swipe feature to swipe through different activities in the app. For example, the popular chatting app, Snapchat, uses it to swipe through lenses, chats, and stories. Here let’s discuss how to create an Image Slider using ViewPager. ViewPager is a class in Java that is used in conjunction with Fragments. It is mostly used for designing the UI of the app. A sample GIF is given below to get an idea about what we are going to do in this article.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Designing the UI
Below is the code for the activity_main.xml file. We have added only a ViewPager to show the images. Below is the complete code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- viewpager to show images --> <androidx.viewpager.widget.ViewPager android:id="@+id/viewPagerMain" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout>
Create a new Layout Resource File item.xml inside the app -> res -> layout folder. Add only an ImageView. Below is the code of the item.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- image viwer to view the images --> <ImageView android:id="@+id/imageViewMain" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
Step 3: Coding Part
First, create an Adapter for the ViewPager and named it as ViewPagerAdapter class below is the complete code of ViewPagerAdapter.java class. Comments are added inside the code to understand each line of the code.
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import androidx.annotation.NonNull;import androidx.viewpager.widget.PagerAdapter;import java.util.Objects; class ViewPagerAdapter extends PagerAdapter { // Context object Context context; // Array of images int[] images; // Layout Inflater LayoutInflater mLayoutInflater; // Viewpager Constructor public ViewPagerAdapter(Context context, int[] images) { this.context = context; this.images = images; mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // return the number of images return images.length; } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == ((LinearLayout) object); } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, final int position) { // inflating the item.xml View itemView = mLayoutInflater.inflate(R.layout.item, container, false); // referencing the image view from the item.xml file ImageView imageView = (ImageView) itemView.findViewById(R.id.imageViewMain); // setting the image in the imageView imageView.setImageResource(images[position]); // Adding the View Objects.requireNonNull(container).addView(itemView); return itemView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((LinearLayout) object); }}
After creating the Adapter for the ViewPager, reference the ViewPager from the XML and set the adapter to it in the MainActivity.java file. Create an array of integer which contains the images which we will show in the ViewPager. Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand each line of the code.
Java
import androidx.appcompat.app.AppCompatActivity;import androidx.viewpager.widget.ViewPager;import android.os.Bundle; public class MainActivity extends AppCompatActivity { // creating object of ViewPager ViewPager mViewPager; // images array int[] images = {R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a8}; // Creating Object of ViewPagerAdapter ViewPagerAdapter mViewPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing the ViewPager Object mViewPager = (ViewPager)findViewById(R.id.viewPagerMain); // Initializing the ViewPagerAdapter mViewPagerAdapter = new ViewPagerAdapter(MainActivity.this, images); // Adding the Adapter to the ViewPager mViewPager.setAdapter(mViewPagerAdapter); }}
Additional Links:
Download the Full Project From the Link
Download Images Using in This Project
Download The App
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
Services in Android with Example
Android RecyclerView in Kotlin
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 25839,
"s": 25811,
"text": "\n15 Sep, 2020"
},
{
"code": null,
"e": 26700,
"s": 25839,
"text": "When talking about Android Apps, the first thing that comes to mind is variety. There are so many varieties of Android apps providing the user with beautiful dynamic UI. One such feature is to navigate in the Android Apps using the left and right swipes as opposed to clicking on Buttons. Not only does it look more simple and elegant but also provides ease of access to the user. There are many apps that use this swipe feature to swipe through different activities in the app. For example, the popular chatting app, Snapchat, uses it to swipe through lenses, chats, and stories. Here let’s discuss how to create an Image Slider using ViewPager. ViewPager is a class in Java that is used in conjunction with Fragments. It is mostly used for designing the UI of the app. A sample GIF is given below to get an idea about what we are going to do in this article."
},
{
"code": null,
"e": 26729,
"s": 26700,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26891,
"s": 26729,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 26916,
"s": 26891,
"text": "Step 2: Designing the UI"
},
{
"code": null,
"e": 27076,
"s": 26916,
"text": "Below is the code for the activity_main.xml file. We have added only a ViewPager to show the images. Below is the complete code for the activity_main.xml file."
},
{
"code": null,
"e": 27080,
"s": 27076,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- viewpager to show images --> <androidx.viewpager.widget.ViewPager android:id=\"@+id/viewPagerMain\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"/> </RelativeLayout>",
"e": 27575,
"s": 27080,
"text": null
},
{
"code": null,
"e": 27721,
"s": 27575,
"text": "Create a new Layout Resource File item.xml inside the app -> res -> layout folder. Add only an ImageView. Below is the code of the item.xml file."
},
{
"code": null,
"e": 27725,
"s": 27721,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!-- image viwer to view the images --> <ImageView android:id=\"@+id/imageViewMain\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"/> </LinearLayout>",
"e": 28123,
"s": 27725,
"text": null
},
{
"code": null,
"e": 28143,
"s": 28123,
"text": "Step 3: Coding Part"
},
{
"code": null,
"e": 28356,
"s": 28143,
"text": "First, create an Adapter for the ViewPager and named it as ViewPagerAdapter class below is the complete code of ViewPagerAdapter.java class. Comments are added inside the code to understand each line of the code."
},
{
"code": null,
"e": 28361,
"s": 28356,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import androidx.annotation.NonNull;import androidx.viewpager.widget.PagerAdapter;import java.util.Objects; class ViewPagerAdapter extends PagerAdapter { // Context object Context context; // Array of images int[] images; // Layout Inflater LayoutInflater mLayoutInflater; // Viewpager Constructor public ViewPagerAdapter(Context context, int[] images) { this.context = context; this.images = images; mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // return the number of images return images.length; } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == ((LinearLayout) object); } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, final int position) { // inflating the item.xml View itemView = mLayoutInflater.inflate(R.layout.item, container, false); // referencing the image view from the item.xml file ImageView imageView = (ImageView) itemView.findViewById(R.id.imageViewMain); // setting the image in the imageView imageView.setImageResource(images[position]); // Adding the View Objects.requireNonNull(container).addView(itemView); return itemView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((LinearLayout) object); }}",
"e": 30139,
"s": 28361,
"text": null
},
{
"code": null,
"e": 30500,
"s": 30139,
"text": "After creating the Adapter for the ViewPager, reference the ViewPager from the XML and set the adapter to it in the MainActivity.java file. Create an array of integer which contains the images which we will show in the ViewPager. Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand each line of the code."
},
{
"code": null,
"e": 30505,
"s": 30500,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import androidx.viewpager.widget.ViewPager;import android.os.Bundle; public class MainActivity extends AppCompatActivity { // creating object of ViewPager ViewPager mViewPager; // images array int[] images = {R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a8}; // Creating Object of ViewPagerAdapter ViewPagerAdapter mViewPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initializing the ViewPager Object mViewPager = (ViewPager)findViewById(R.id.viewPagerMain); // Initializing the ViewPagerAdapter mViewPagerAdapter = new ViewPagerAdapter(MainActivity.this, images); // Adding the Adapter to the ViewPager mViewPager.setAdapter(mViewPagerAdapter); }}",
"e": 31505,
"s": 30505,
"text": null
},
{
"code": null,
"e": 31523,
"s": 31505,
"text": "Additional Links:"
},
{
"code": null,
"e": 31563,
"s": 31523,
"text": "Download the Full Project From the Link"
},
{
"code": null,
"e": 31602,
"s": 31563,
"text": "Download Images Using in This Project "
},
{
"code": null,
"e": 31619,
"s": 31602,
"text": "Download The App"
},
{
"code": null,
"e": 31627,
"s": 31619,
"text": "android"
},
{
"code": null,
"e": 31635,
"s": 31627,
"text": "Android"
},
{
"code": null,
"e": 31640,
"s": 31635,
"text": "Java"
},
{
"code": null,
"e": 31645,
"s": 31640,
"text": "Java"
},
{
"code": null,
"e": 31653,
"s": 31645,
"text": "Android"
},
{
"code": null,
"e": 31751,
"s": 31653,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31809,
"s": 31751,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 31852,
"s": 31809,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 31890,
"s": 31852,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 31923,
"s": 31890,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 31954,
"s": 31923,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 31969,
"s": 31954,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32013,
"s": 31969,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 32035,
"s": 32013,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 32086,
"s": 32035,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Python | SymPy Permutation.index() method - GeeksforGeeks
|
27 Aug, 2019
Permutation.index() : index() is a sympy Python library function that returns the index value of the permutation in argument.
Index of a permutation = Sum of all subscripts j such that permutation[j] is greater than permutation[j+1].
Syntax :sympy.combinatorics.permutations.Permutation.index()
Return :index value of the permutation
Code #1 : index() Example
# Python code explaining# SymPy.Permutation.index() # importing SymPy librariesfrom sympy.combinatorics.partitions import Partitionfrom sympy.combinatorics.permutations import Permutation # Using from sympy.combinatorics.permutations.Permutation.index() method # creating Permutationa = Permutation([[2, 0], [3, 1]]) b = Permutation([1, 3, 5, 4, 2, 0]) print ("Permutation a - index form : ", a.index())print ("Permutation b - index form : ", b.index())
Output :
Permutation a – index form : 1Permutation b – index form : 9
Code #2 : index() Example – 2D Permutation
# Python code explaining# SymPy.Permutation.index() # importing SymPy librariesfrom sympy.combinatorics.partitions import Partitionfrom sympy.combinatorics.permutations import Permutation # Using from sympy.combinatorics.permutations.Permutation.index() method # creating Permutationa = Permutation([[2, 4, 0], [3, 1, 2], [1, 5, 6]]) print ("Permutation a - index form : ", a.index())
Output :
Permutation a – index form : 8
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n27 Aug, 2019"
},
{
"code": null,
"e": 25663,
"s": 25537,
"text": "Permutation.index() : index() is a sympy Python library function that returns the index value of the permutation in argument."
},
{
"code": null,
"e": 25771,
"s": 25663,
"text": "Index of a permutation = Sum of all subscripts j such that permutation[j] is greater than permutation[j+1]."
},
{
"code": null,
"e": 25832,
"s": 25771,
"text": "Syntax :sympy.combinatorics.permutations.Permutation.index()"
},
{
"code": null,
"e": 25871,
"s": 25832,
"text": "Return :index value of the permutation"
},
{
"code": null,
"e": 25897,
"s": 25871,
"text": "Code #1 : index() Example"
},
{
"code": "# Python code explaining# SymPy.Permutation.index() # importing SymPy librariesfrom sympy.combinatorics.partitions import Partitionfrom sympy.combinatorics.permutations import Permutation # Using from sympy.combinatorics.permutations.Permutation.index() method # creating Permutationa = Permutation([[2, 0], [3, 1]]) b = Permutation([1, 3, 5, 4, 2, 0]) print (\"Permutation a - index form : \", a.index())print (\"Permutation b - index form : \", b.index())",
"e": 26359,
"s": 25897,
"text": null
},
{
"code": null,
"e": 26368,
"s": 26359,
"text": "Output :"
},
{
"code": null,
"e": 26429,
"s": 26368,
"text": "Permutation a – index form : 1Permutation b – index form : 9"
},
{
"code": null,
"e": 26472,
"s": 26429,
"text": "Code #2 : index() Example – 2D Permutation"
},
{
"code": "# Python code explaining# SymPy.Permutation.index() # importing SymPy librariesfrom sympy.combinatorics.partitions import Partitionfrom sympy.combinatorics.permutations import Permutation # Using from sympy.combinatorics.permutations.Permutation.index() method # creating Permutationa = Permutation([[2, 4, 0], [3, 1, 2], [1, 5, 6]]) print (\"Permutation a - index form : \", a.index())",
"e": 26897,
"s": 26472,
"text": null
},
{
"code": null,
"e": 26906,
"s": 26897,
"text": "Output :"
},
{
"code": null,
"e": 26937,
"s": 26906,
"text": "Permutation a – index form : 8"
},
{
"code": null,
"e": 26943,
"s": 26937,
"text": "SymPy"
},
{
"code": null,
"e": 26950,
"s": 26943,
"text": "Python"
},
{
"code": null,
"e": 27048,
"s": 26950,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27080,
"s": 27048,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27122,
"s": 27080,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27164,
"s": 27122,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27191,
"s": 27164,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27247,
"s": 27191,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27286,
"s": 27247,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27308,
"s": 27286,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27339,
"s": 27308,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27368,
"s": 27339,
"text": "Create a directory in Python"
}
] |
Java Program to Implement Binomial Heap - GeeksforGeeks
|
11 Oct, 2021
A Binomial Heap is a set of Binomial Trees where each Binomial Tree follows Min Heap property. And there can be at most one Binomial Tree of any degree. It is explained to depth in the below illustration as follows:
Illustration:
There are 2 binomial heaps been depicted below out here saw follows:
BINOMIAL HEAP 1
12------------10--------------------20
/ \ / | \
15 50 70 50 40
| / | |
30 80 85 65
|
100
A Binomial Heap with 13 nodes. It is a collection of 3
Binomial Trees of orders 0, 2 and 3 from left to right.
BINOMIAL HEAP 2
10--------------------20
/ \ / | \
15 50 70 50 40
| / | |
30 80 85 65
|
100
A Binomial Heap with 12 nodes. It is a collection of 2
Binomial Trees of orders 2 and 3 from left to right.
Let us now do discuss the binary representation of a number and binomial heaps. A Binomial Heap with n nodes has the number of Binomial Trees equal to the number of set bits in the binary representation of n.
For example, let n be 13, there are 3 set bits in the binary representation of n (00001101), hence 3 Binomial Trees. We can also relate the degree of these Binomial Trees with positions of set bits. With this relation, we can conclude that there are O(Logn) Binomial Trees in a Binomial Heap with ‘n’ nodes.
Operations of the binomial heap are as follows:
Insert(K): Insert an element K into the binomial heapDelete(k): Deletes the element k from the heapgetSize(): Returns the size of the heapmakeEmpty(): Makes the binomial heap empty by deleting all the elementscheckEmpty(): Check if the binomial heap is empty or notdisplayHeap(): Prints the binomial heap
Insert(K): Insert an element K into the binomial heap
Delete(k): Deletes the element k from the heap
getSize(): Returns the size of the heap
makeEmpty(): Makes the binomial heap empty by deleting all the elements
checkEmpty(): Check if the binomial heap is empty or not
displayHeap(): Prints the binomial heap
Implementation:
Example
Java
// Java Program to Implement Binomial Heap // Importing required classesimport java.io.*; // Class 1// BinomialHeapNodeclass BinomialHeapNode { int key, degree; BinomialHeapNode parent; BinomialHeapNode sibling; BinomialHeapNode child; // Constructor of this class public BinomialHeapNode(int k) { key = k; degree = 0; parent = null; sibling = null; child = null; } // Method 1 // To reverse public BinomialHeapNode reverse(BinomialHeapNode sibl) { BinomialHeapNode ret; if (sibling != null) ret = sibling.reverse(this); else ret = this; sibling = sibl; return ret; } // Method 2 // To find minimum node public BinomialHeapNode findMinNode() { // this keyword refers to current instance itself BinomialHeapNode x = this, y = this; int min = x.key; while (x != null) { if (x.key < min) { y = x; min = x.key; } x = x.sibling; } return y; } // Method 3 // To find node with key value public BinomialHeapNode findANodeWithKey(int value) { BinomialHeapNode temp = this, node = null; while (temp != null) { if (temp.key == value) { node = temp; break; } if (temp.child == null) temp = temp.sibling; else { node = temp.child.findANodeWithKey(value); if (node == null) temp = temp.sibling; else break; } } return node; } // Method 4 // To get the size public int getSize() { return ( 1 + ((child == null) ? 0 : child.getSize()) + ((sibling == null) ? 0 : sibling.getSize())); }} // Class 2// BinomialHeapclass BinomialHeap { // Member variables of this class private BinomialHeapNode Nodes; private int size; // Constructor of this class public BinomialHeap() { Nodes = null; size = 0; } // Checking if heap is empty public boolean isEmpty() { return Nodes == null; } // Method 1 // To get the size public int getSize() { return size; } // Method 2 // Clear heap public void makeEmpty() { Nodes = null; size = 0; } // Method 3 // To insert public void insert(int value) { if (value > 0) { BinomialHeapNode temp = new BinomialHeapNode(value); if (Nodes == null) { Nodes = temp; size = 1; } else { unionNodes(temp); size++; } } } // Method 4 // To unite two binomial heaps private void merge(BinomialHeapNode binHeap) { BinomialHeapNode temp1 = Nodes, temp2 = binHeap; while ((temp1 != null) && (temp2 != null)) { if (temp1.degree == temp2.degree) { BinomialHeapNode tmp = temp2; temp2 = temp2.sibling; tmp.sibling = temp1.sibling; temp1.sibling = tmp; temp1 = tmp.sibling; } else { if (temp1.degree < temp2.degree) { if ((temp1.sibling == null) || (temp1.sibling.degree > temp2.degree)) { BinomialHeapNode tmp = temp2; temp2 = temp2.sibling; tmp.sibling = temp1.sibling; temp1.sibling = tmp; temp1 = tmp.sibling; } else { temp1 = temp1.sibling; } } else { BinomialHeapNode tmp = temp1; temp1 = temp2; temp2 = temp2.sibling; temp1.sibling = tmp; if (tmp == Nodes) { Nodes = temp1; } else { } } } } if (temp1 == null) { temp1 = Nodes; while (temp1.sibling != null) { temp1 = temp1.sibling; } temp1.sibling = temp2; } else { } } // Method 5 // For union of nodes private void unionNodes(BinomialHeapNode binHeap) { merge(binHeap); BinomialHeapNode prevTemp = null, temp = Nodes, nextTemp = Nodes.sibling; while (nextTemp != null) { if ((temp.degree != nextTemp.degree) || ((nextTemp.sibling != null) && (nextTemp.sibling.degree == temp.degree))) { prevTemp = temp; temp = nextTemp; } else { if (temp.key <= nextTemp.key) { temp.sibling = nextTemp.sibling; nextTemp.parent = temp; nextTemp.sibling = temp.child; temp.child = nextTemp; temp.degree++; } else { if (prevTemp == null) { Nodes = nextTemp; } else { prevTemp.sibling = nextTemp; } temp.parent = nextTemp; temp.sibling = nextTemp.child; nextTemp.child = temp; nextTemp.degree++; temp = nextTemp; } } nextTemp = temp.sibling; } } // Method 6 // To return minimum key public int findMinimum() { return Nodes.findMinNode().key; } // Method 7 // To delete a particular element */ public void delete(int value) { if ((Nodes != null) && (Nodes.findANodeWithKey(value) != null)) { decreaseKeyValue(value, findMinimum() - 1); extractMin(); } } // Method 8 // To decrease key with a given value */ public void decreaseKeyValue(int old_value, int new_value) { BinomialHeapNode temp = Nodes.findANodeWithKey(old_value); if (temp == null) return; temp.key = new_value; BinomialHeapNode tempParent = temp.parent; while ((tempParent != null) && (temp.key < tempParent.key)) { int z = temp.key; temp.key = tempParent.key; tempParent.key = z; temp = tempParent; tempParent = tempParent.parent; } } // Method 9 // To extract the node with the minimum key public int extractMin() { if (Nodes == null) return -1; BinomialHeapNode temp = Nodes, prevTemp = null; BinomialHeapNode minNode = Nodes.findMinNode(); while (temp.key != minNode.key) { prevTemp = temp; temp = temp.sibling; } if (prevTemp == null) { Nodes = temp.sibling; } else { prevTemp.sibling = temp.sibling; } temp = temp.child; BinomialHeapNode fakeNode = temp; while (temp != null) { temp.parent = null; temp = temp.sibling; } if ((Nodes == null) && (fakeNode == null)) { size = 0; } else { if ((Nodes == null) && (fakeNode != null)) { Nodes = fakeNode.reverse(null); size = Nodes.getSize(); } else { if ((Nodes != null) && (fakeNode == null)) { size = Nodes.getSize(); } else { unionNodes(fakeNode.reverse(null)); size = Nodes.getSize(); } } } return minNode.key; } // Method 10 // To display heap public void displayHeap() { System.out.print("\nHeap : "); displayHeap(Nodes); System.out.println("\n"); } private void displayHeap(BinomialHeapNode r) { if (r != null) { displayHeap(r.child); System.out.print(r.key + " "); displayHeap(r.sibling); } }} // Class 3// Main classpublic class GFG { public static void main(String[] args) { // Make object of BinomialHeap BinomialHeap binHeap = new BinomialHeap(); // Inserting in the binomial heap // Custom input integer values binHeap.insert(12); binHeap.insert(8); binHeap.insert(5); binHeap.insert(15); binHeap.insert(7); binHeap.insert(2); binHeap.insert(9); // Size of binomial heap System.out.println("Size of the binomial heap is " + binHeap.getSize()); // Displaying the binomial heap binHeap.displayHeap(); // Deletion in binomial heap binHeap.delete(15); binHeap.delete(8); // Size of binomial heap System.out.println("Size of the binomial heap is " + binHeap.getSize()); // Displaying the binomial heap binHeap.displayHeap(); // Making the heap empty binHeap.makeEmpty(); // checking if heap is empty System.out.println(binHeap.isEmpty()); }}
Size of the binomial heap is 7
Heap : 9 7 2 12 8 15 5
Size of the binomial heap is 5
Heap : 7 9 5 12 2
true
kalrap615
surindertarika1234
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?
Program to print ASCII Value of a character
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 25443,
"s": 25225,
"text": " A Binomial Heap is a set of Binomial Trees where each Binomial Tree follows Min Heap property. And there can be at most one Binomial Tree of any degree. It is explained to depth in the below illustration as follows:"
},
{
"code": null,
"e": 25457,
"s": 25443,
"text": "Illustration:"
},
{
"code": null,
"e": 25527,
"s": 25457,
"text": "There are 2 binomial heaps been depicted below out here saw follows: "
},
{
"code": null,
"e": 26251,
"s": 25527,
"text": " BINOMIAL HEAP 1\n \n 12------------10--------------------20\n / \\ / | \\\n 15 50 70 50 40\n | / | | \n 30 80 85 65 \n |\n 100\nA Binomial Heap with 13 nodes. It is a collection of 3 \nBinomial Trees of orders 0, 2 and 3 from left to right. \n\n\nBINOMIAL HEAP 2 \n\n 10--------------------20\n / \\ / | \\\n15 50 70 50 40\n| / | | \n30 80 85 65 \n |\n 100\nA Binomial Heap with 12 nodes. It is a collection of 2 \nBinomial Trees of orders 2 and 3 from left to right. "
},
{
"code": null,
"e": 26461,
"s": 26251,
"text": "Let us now do discuss the binary representation of a number and binomial heaps. A Binomial Heap with n nodes has the number of Binomial Trees equal to the number of set bits in the binary representation of n. "
},
{
"code": null,
"e": 26771,
"s": 26461,
"text": "For example, let n be 13, there are 3 set bits in the binary representation of n (00001101), hence 3 Binomial Trees. We can also relate the degree of these Binomial Trees with positions of set bits. With this relation, we can conclude that there are O(Logn) Binomial Trees in a Binomial Heap with ‘n’ nodes. "
},
{
"code": null,
"e": 26819,
"s": 26771,
"text": "Operations of the binomial heap are as follows:"
},
{
"code": null,
"e": 27124,
"s": 26819,
"text": "Insert(K): Insert an element K into the binomial heapDelete(k): Deletes the element k from the heapgetSize(): Returns the size of the heapmakeEmpty(): Makes the binomial heap empty by deleting all the elementscheckEmpty(): Check if the binomial heap is empty or notdisplayHeap(): Prints the binomial heap"
},
{
"code": null,
"e": 27178,
"s": 27124,
"text": "Insert(K): Insert an element K into the binomial heap"
},
{
"code": null,
"e": 27225,
"s": 27178,
"text": "Delete(k): Deletes the element k from the heap"
},
{
"code": null,
"e": 27265,
"s": 27225,
"text": "getSize(): Returns the size of the heap"
},
{
"code": null,
"e": 27337,
"s": 27265,
"text": "makeEmpty(): Makes the binomial heap empty by deleting all the elements"
},
{
"code": null,
"e": 27394,
"s": 27337,
"text": "checkEmpty(): Check if the binomial heap is empty or not"
},
{
"code": null,
"e": 27434,
"s": 27394,
"text": "displayHeap(): Prints the binomial heap"
},
{
"code": null,
"e": 27450,
"s": 27434,
"text": "Implementation:"
},
{
"code": null,
"e": 27458,
"s": 27450,
"text": "Example"
},
{
"code": null,
"e": 27463,
"s": 27458,
"text": "Java"
},
{
"code": "// Java Program to Implement Binomial Heap // Importing required classesimport java.io.*; // Class 1// BinomialHeapNodeclass BinomialHeapNode { int key, degree; BinomialHeapNode parent; BinomialHeapNode sibling; BinomialHeapNode child; // Constructor of this class public BinomialHeapNode(int k) { key = k; degree = 0; parent = null; sibling = null; child = null; } // Method 1 // To reverse public BinomialHeapNode reverse(BinomialHeapNode sibl) { BinomialHeapNode ret; if (sibling != null) ret = sibling.reverse(this); else ret = this; sibling = sibl; return ret; } // Method 2 // To find minimum node public BinomialHeapNode findMinNode() { // this keyword refers to current instance itself BinomialHeapNode x = this, y = this; int min = x.key; while (x != null) { if (x.key < min) { y = x; min = x.key; } x = x.sibling; } return y; } // Method 3 // To find node with key value public BinomialHeapNode findANodeWithKey(int value) { BinomialHeapNode temp = this, node = null; while (temp != null) { if (temp.key == value) { node = temp; break; } if (temp.child == null) temp = temp.sibling; else { node = temp.child.findANodeWithKey(value); if (node == null) temp = temp.sibling; else break; } } return node; } // Method 4 // To get the size public int getSize() { return ( 1 + ((child == null) ? 0 : child.getSize()) + ((sibling == null) ? 0 : sibling.getSize())); }} // Class 2// BinomialHeapclass BinomialHeap { // Member variables of this class private BinomialHeapNode Nodes; private int size; // Constructor of this class public BinomialHeap() { Nodes = null; size = 0; } // Checking if heap is empty public boolean isEmpty() { return Nodes == null; } // Method 1 // To get the size public int getSize() { return size; } // Method 2 // Clear heap public void makeEmpty() { Nodes = null; size = 0; } // Method 3 // To insert public void insert(int value) { if (value > 0) { BinomialHeapNode temp = new BinomialHeapNode(value); if (Nodes == null) { Nodes = temp; size = 1; } else { unionNodes(temp); size++; } } } // Method 4 // To unite two binomial heaps private void merge(BinomialHeapNode binHeap) { BinomialHeapNode temp1 = Nodes, temp2 = binHeap; while ((temp1 != null) && (temp2 != null)) { if (temp1.degree == temp2.degree) { BinomialHeapNode tmp = temp2; temp2 = temp2.sibling; tmp.sibling = temp1.sibling; temp1.sibling = tmp; temp1 = tmp.sibling; } else { if (temp1.degree < temp2.degree) { if ((temp1.sibling == null) || (temp1.sibling.degree > temp2.degree)) { BinomialHeapNode tmp = temp2; temp2 = temp2.sibling; tmp.sibling = temp1.sibling; temp1.sibling = tmp; temp1 = tmp.sibling; } else { temp1 = temp1.sibling; } } else { BinomialHeapNode tmp = temp1; temp1 = temp2; temp2 = temp2.sibling; temp1.sibling = tmp; if (tmp == Nodes) { Nodes = temp1; } else { } } } } if (temp1 == null) { temp1 = Nodes; while (temp1.sibling != null) { temp1 = temp1.sibling; } temp1.sibling = temp2; } else { } } // Method 5 // For union of nodes private void unionNodes(BinomialHeapNode binHeap) { merge(binHeap); BinomialHeapNode prevTemp = null, temp = Nodes, nextTemp = Nodes.sibling; while (nextTemp != null) { if ((temp.degree != nextTemp.degree) || ((nextTemp.sibling != null) && (nextTemp.sibling.degree == temp.degree))) { prevTemp = temp; temp = nextTemp; } else { if (temp.key <= nextTemp.key) { temp.sibling = nextTemp.sibling; nextTemp.parent = temp; nextTemp.sibling = temp.child; temp.child = nextTemp; temp.degree++; } else { if (prevTemp == null) { Nodes = nextTemp; } else { prevTemp.sibling = nextTemp; } temp.parent = nextTemp; temp.sibling = nextTemp.child; nextTemp.child = temp; nextTemp.degree++; temp = nextTemp; } } nextTemp = temp.sibling; } } // Method 6 // To return minimum key public int findMinimum() { return Nodes.findMinNode().key; } // Method 7 // To delete a particular element */ public void delete(int value) { if ((Nodes != null) && (Nodes.findANodeWithKey(value) != null)) { decreaseKeyValue(value, findMinimum() - 1); extractMin(); } } // Method 8 // To decrease key with a given value */ public void decreaseKeyValue(int old_value, int new_value) { BinomialHeapNode temp = Nodes.findANodeWithKey(old_value); if (temp == null) return; temp.key = new_value; BinomialHeapNode tempParent = temp.parent; while ((tempParent != null) && (temp.key < tempParent.key)) { int z = temp.key; temp.key = tempParent.key; tempParent.key = z; temp = tempParent; tempParent = tempParent.parent; } } // Method 9 // To extract the node with the minimum key public int extractMin() { if (Nodes == null) return -1; BinomialHeapNode temp = Nodes, prevTemp = null; BinomialHeapNode minNode = Nodes.findMinNode(); while (temp.key != minNode.key) { prevTemp = temp; temp = temp.sibling; } if (prevTemp == null) { Nodes = temp.sibling; } else { prevTemp.sibling = temp.sibling; } temp = temp.child; BinomialHeapNode fakeNode = temp; while (temp != null) { temp.parent = null; temp = temp.sibling; } if ((Nodes == null) && (fakeNode == null)) { size = 0; } else { if ((Nodes == null) && (fakeNode != null)) { Nodes = fakeNode.reverse(null); size = Nodes.getSize(); } else { if ((Nodes != null) && (fakeNode == null)) { size = Nodes.getSize(); } else { unionNodes(fakeNode.reverse(null)); size = Nodes.getSize(); } } } return minNode.key; } // Method 10 // To display heap public void displayHeap() { System.out.print(\"\\nHeap : \"); displayHeap(Nodes); System.out.println(\"\\n\"); } private void displayHeap(BinomialHeapNode r) { if (r != null) { displayHeap(r.child); System.out.print(r.key + \" \"); displayHeap(r.sibling); } }} // Class 3// Main classpublic class GFG { public static void main(String[] args) { // Make object of BinomialHeap BinomialHeap binHeap = new BinomialHeap(); // Inserting in the binomial heap // Custom input integer values binHeap.insert(12); binHeap.insert(8); binHeap.insert(5); binHeap.insert(15); binHeap.insert(7); binHeap.insert(2); binHeap.insert(9); // Size of binomial heap System.out.println(\"Size of the binomial heap is \" + binHeap.getSize()); // Displaying the binomial heap binHeap.displayHeap(); // Deletion in binomial heap binHeap.delete(15); binHeap.delete(8); // Size of binomial heap System.out.println(\"Size of the binomial heap is \" + binHeap.getSize()); // Displaying the binomial heap binHeap.displayHeap(); // Making the heap empty binHeap.makeEmpty(); // checking if heap is empty System.out.println(binHeap.isEmpty()); }}",
"e": 37103,
"s": 27463,
"text": null
},
{
"code": null,
"e": 37220,
"s": 37106,
"text": "Size of the binomial heap is 7\n\nHeap : 9 7 2 12 8 15 5 \n\nSize of the binomial heap is 5\n\nHeap : 7 9 5 12 2 \n\ntrue"
},
{
"code": null,
"e": 37232,
"s": 37222,
"text": "kalrap615"
},
{
"code": null,
"e": 37251,
"s": 37232,
"text": "surindertarika1234"
},
{
"code": null,
"e": 37258,
"s": 37251,
"text": "Picked"
},
{
"code": null,
"e": 37263,
"s": 37258,
"text": "Java"
},
{
"code": null,
"e": 37277,
"s": 37263,
"text": "Java Programs"
},
{
"code": null,
"e": 37282,
"s": 37277,
"text": "Java"
},
{
"code": null,
"e": 37380,
"s": 37282,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37395,
"s": 37380,
"text": "Stream In Java"
},
{
"code": null,
"e": 37416,
"s": 37395,
"text": "Constructors in Java"
},
{
"code": null,
"e": 37435,
"s": 37416,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 37465,
"s": 37435,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 37511,
"s": 37465,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 37537,
"s": 37511,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 37571,
"s": 37537,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 37618,
"s": 37571,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 37650,
"s": 37618,
"text": "How to Iterate HashMap in Java?"
}
] |
C++ Program To Add Two Numbers Represented By Linked Lists- Set 1 - GeeksforGeeks
|
20 Dec, 2021
Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers.
Example:
Input: List1: 5->6->3 // represents number 563 List2: 8->4->2 // represents number 842 Output: Resultant list: 1->4->0->5 // represents number 1405 Explanation: 563 + 842 = 1405
Input: List1: 7->5->9->4->6 // represents number 75946List2: 8->4 // represents number 84Output: Resultant list: 7->6->0->3->0// represents number 76030Explanation: 75946+84=76030
Method 1:Approach: Traverse both lists and One by one pick nodes of both lists and add the values. If the sum is more than 10 then make carry as 1 and reduce sum. If one list has more elements than the other then consider the remaining values of this list as 0. The steps are:
Traverse the two linked lists from start to endAdd the two digits each from respective linked lists.If one of the lists has reached the end then take 0 as its digit.Continue it until both the end of the lists.If the sum of two digits is greater than 9 then set carry as 1 and the current digit as sum % 10
Traverse the two linked lists from start to end
Add the two digits each from respective linked lists.
If one of the lists has reached the end then take 0 as its digit.
Continue it until both the end of the lists.
If the sum of two digits is greater than 9 then set carry as 1 and the current digit as sum % 10
Below is the implementation of this approach.
C++
// C++ program to add two numbers// represented by linked list#include <bits/stdc++.h>using namespace std; // Linked list node class Node { public: int data; Node* next;}; /* Function to create a new node with given data */Node* newNode(int data){ Node* new_node = new Node(); new_node->data = data; new_node->next = NULL; return new_node;} /* Function to insert a node at the beginning of the Singly Linked List */void push(Node** head_ref, int new_data){ // Allocate node Node* new_node = newNode(new_data); // link the old list off the // new node new_node->next = (*head_ref); // Move the head to point to the // new node (*head_ref) = new_node;} /* Adds contents of two linked lists and return the head node of resultant list */Node* addTwoLists(Node* first, Node* second){ // res is head node of the resultant // list Node* res = NULL; Node *temp, *prev = NULL; int carry = 0, sum; // while both lists exist while (first != NULL || second != NULL) { // Calculate value of next digit in // resultant list. The next digit is // sum of following things // (i) Carry // (ii) Next digit of first // list (if there is a next digit) // (ii) Next digit of second // list (if there is a next digit) sum = carry + (first ? first->data : 0) + (second ? second->data : 0); // Update carry for next calculation carry = (sum >= 10) ? 1 : 0; // Update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data temp = newNode(sum); // If this is the first node then // set it as head of the resultant list if (res == NULL) res = temp; // If this is not the first // node then connect it to the rest. else prev->next = temp; // Set prev for next insertion prev = temp; // Move first and second // pointers to next nodes if (first) first = first->next; if (second) second = second->next; } if (carry > 0) temp->next = newNode(carry); // return head of the resultant // list return res;} // A utility function to print a // linked listvoid printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; } cout << endl;} // Driver codeint main(void){ Node* res = NULL; Node* first = NULL; Node* second = NULL; // Create first list // 7->5->9->4->6 push(&first, 6); push(&first, 4); push(&first, 9); push(&first, 5); push(&first, 7); printf("First List is "); printList(first); // Create second list 8->4 push(&second, 4); push(&second, 8); cout << "Second List is "; printList(second); // Add the two lists and see // result res = addTwoLists(first, second); cout << "Resultant list is "; printList(res); return 0;}// This code is contributed by rathbhupendra
Output:
First List is 7 5 9 4 6
Second List is 8 4
Resultant list is 5 0 0 5 6
Complexity Analysis:
Time Complexity: O(m + n), where m and n are numbers of nodes in first and second lists respectively. The lists need to be traversed only once.
Space Complexity: O(m + n). A temporary linked list is needed to store the output number
Method 2(Using STL): Using stack data structureApproach:
1. Create 3 stacks namely s1,s2,s3.
2. Fill s1 with Nodes of list1 and fill s2 with nodes of list2.
3. Fill s3 by creating new nodes and setting the data of new nodes to the
sum of s1.top(), s2.top() and carry until list1 and list2 are empty .
4. If the sum >9, set carry 1
5. Else set carry 0.
6. Create a Node(say prev) that will contain the head of the sum List.
7. Link all the elements of s3 from top to bottom.
8. return prev.
C++
// C++ program to add two numbers represented // by Linked Lists using Stack#include <bits/stdc++.h>using namespace std;class Node { public: int data; Node* next;};Node* newnode(int data){ Node* x = new Node(); x->data = data; return x;}// Function that returns the sum of two // numbers represented by linked listsNode* addTwoNumbers(Node* l1, Node* l2){ Node* prev = NULL; // Create 3 stacks stack<Node*> s1, s2, s3; // Fill first stack with first // List Elements while (l1 != NULL) { s1.push(l1); l1 = l1->next; } // Fill second stack with second // List Elements while (l2 != NULL) { s2.push(l2); l2 = l2->next; } int carry = 0; // Fill the third stack with the // sum of first and second stack while (!s1.empty() && !s2.empty()) { int sum = (s1.top()->data + s2.top()->data + carry); Node* temp = newnode(sum % 10); s3.push(temp); if (sum > 9) { carry = 1; } else { carry = 0; } s1.pop(); s2.pop(); } while (!s1.empty()) { int sum = carry + s1.top()->data; Node* temp = newnode(sum % 10); s3.push(temp); if (sum > 9) { carry = 1; } else { carry = 0; } s1.pop(); } while (!s2.empty()) { int sum = carry + s2.top()->data; Node* temp = newnode(sum % 10); s3.push(temp); if (sum > 9) { carry = 1; } else { carry = 0; } s2.pop(); } // If carry is still present create a // new node with value 1 and push it // to the third stack if (carry == 1) { Node* temp = newnode(1); s3.push(temp); } // Link all the elements inside // third stack with each other if (!s3.empty()) prev = s3.top(); while (!s3.empty()) { Node* temp = s3.top(); s3.pop(); if (s3.size() == 0) { temp->next = NULL; } else { temp->next = s3.top(); } } return prev;} // Utility functions// Function that displays the Listvoid Display(Node* head){ if (head == NULL) { return; } while (head->next != NULL) { cout << head->data << " -> "; head = head->next; } cout << head->data << endl;} // Function that adds element at // the end of the Linked Listvoid push(Node** head_ref, int d){ Node* new_node = newnode(d); new_node->next = NULL; if (*head_ref == NULL) { new_node->next = *head_ref; *head_ref = new_node; return; } Node* last = *head_ref; while (last->next != NULL && last != NULL) { last = last->next; } last->next = new_node; return;} // Driver codeint main(){ // Creating two lists first list // 9 -> 5 -> 0 // second List = 6 -> 7 Node* first = NULL; Node* second = NULL; Node* sum = NULL; push(&first, 9); push(&first, 5); push(&first, 0); push(&second, 6); push(&second, 7); cout << "First List : "; Display(first); cout << "Second List : "; Display(second); sum = addTwoNumbers(first, second); cout << "Sum List : "; Display(sum); return 0;}
Output:
First List : 9 -> 5 -> 0
Second List : 6 -> 7
Sum List : 1 -> 0 -> 1 -> 7
Another Approach with time complexity O(N):The given approach works as following steps:
First, we calculate sizes of both the linked lists, size1 and size2, respectively.Then we traverse the bigger linked list, if any, and decrement till size of both become same.Now we traverse both linked lists till end.Now the backtracking occurs while performing addition.Finally, the head node is returned of the linked list containing the answer.
First, we calculate sizes of both the linked lists, size1 and size2, respectively.
Then we traverse the bigger linked list, if any, and decrement till size of both become same.
Now we traverse both linked lists till end.
Now the backtracking occurs while performing addition.
Finally, the head node is returned of the linked list containing the answer.
C++
// C++ program to implement // the above approach#include <iostream>using namespace std; struct Node { int data; struct Node* next;}; // Recursive functionNode* addition(Node* temp1, Node* temp2, int size1, int size2){ // Creating a new Node Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Base case if (temp1->next == NULL && temp2->next == NULL) { // Addition of current nodes which is // the last nodes of both linked lists newNode->data = (temp1->data + temp2->data); // Set this current node's link null newNode->next = NULL; // Return the current node return newNode; } // Creating a node that contains sum // of previously added number Node* returnedNode = (struct Node*)malloc(sizeof(struct Node)); // If sizes are same then we move in // both linked list if (size2 == size1) { // Recursively call the function // move ahead in both linked list returnedNode = addition(temp1->next, temp2->next, size1 - 1, size2 - 1); // Add the current nodes and append the carry newNode->data = (temp1->data + temp2->data) + ((returnedNode->data) / 10); } // Or else we just move in big linked // list else { // Recursively call the function // move ahead in big linked list returnedNode = addition(temp1, temp2->next, size1, size2 - 1); // Add the current node and carry newNode->data = (temp2->data) + ((returnedNode->data) / 10); } // This node contains previously added // numbers so we need to set only // rightmost digit of it returnedNode->data = (returnedNode->data) % 10; // Set the returned node to the // current nod newNode->next = returnedNode; // return the current node return newNode;} // Function to add two numbers represented // by nexted list.struct Node* addTwoLists(struct Node* head1, struct Node* head2){ struct Node *temp1, *temp2, *ans = NULL; temp1 = head1; temp2 = head2; int size1 = 0, size2 = 0; // calculating the size of first // linked list while (temp1 != NULL) { temp1 = temp1->next; size1++; } // Calculating the size of second // linked list while (temp2 != NULL) { temp2 = temp2->next; size2++; } Node* returnedNode = (struct Node*)malloc(sizeof(struct Node)); // Traverse the bigger linked list if (size2 > size1) { returnedNode = addition(head1, head2, size1, size2); } else { returnedNode = addition(head2, head1, size2, size1); } // Creating new node if head node is >10 if (returnedNode->data >= 10) { ans = (struct Node*)malloc(sizeof(struct Node)); ans->data = (returnedNode->data) / 10; returnedNode->data = returnedNode->data % 10; ans->next = returnedNode; } else ans = returnedNode; // Return the head node of linked list // that contains answer return ans;} void Display(Node* head){ if (head == NULL) { return; } while (head->next != NULL) { cout << head->data << " -> "; head = head->next; } cout << head->data << endl;} // Function that adds element at the // end of the Linked Listvoid push(Node** head_ref, int d){ Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = d; new_node->next = NULL; if (*head_ref == NULL) { new_node->next = *head_ref; *head_ref = new_node; return; } Node* last = *head_ref; while (last->next != NULL && last != NULL) { last = last->next; } last->next = new_node; return;} // Driver codeint main(){ // Creating two lists Node* first = NULL; Node* second = NULL; Node* sum = NULL; push(&first, 5); push(&first, 6); push(&first, 3); push(&second, 8); push(&second, 4); push(&second, 2); cout << "First List : "; Display(first); cout << "Second List : "; Display(second); sum = addTwoLists(first, second); cout << "Sum List : "; Display(sum); return 0;}// This code is contributed by Dharmik Parmar
Output:
First List : 5 -> 6 -> 3
Second List : 8 -> 4 -> 2
Sum List : 1 -> 4 -> 0 -> 5
Related Article: Add two numbers represented by linked lists | Set 2
Please refer complete article on Add two numbers represented by linked lists | Set 1 for more details!
Accolite
Amazon
Flipkart
Linked Lists
MakeMyTrip
Microsoft
Qualcomm
Snapdeal
C++
C++ Programs
Linked List
Flipkart
Accolite
Amazon
Microsoft
Snapdeal
MakeMyTrip
Qualcomm
Linked List
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Program to print ASCII Value of a character
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 25421,
"s": 25393,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 25585,
"s": 25421,
"text": "Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers."
},
{
"code": null,
"e": 25594,
"s": 25585,
"text": "Example:"
},
{
"code": null,
"e": 25954,
"s": 25594,
"text": "Input: List1: 5->6->3 // represents number 563 List2: 8->4->2 // represents number 842 Output: Resultant list: 1->4->0->5 // represents number 1405 Explanation: 563 + 842 = 1405\n\nInput: List1: 7->5->9->4->6 // represents number 75946List2: 8->4 // represents number 84Output: Resultant list: 7->6->0->3->0// represents number 76030Explanation: 75946+84=76030\n"
},
{
"code": null,
"e": 26231,
"s": 25954,
"text": "Method 1:Approach: Traverse both lists and One by one pick nodes of both lists and add the values. If the sum is more than 10 then make carry as 1 and reduce sum. If one list has more elements than the other then consider the remaining values of this list as 0. The steps are:"
},
{
"code": null,
"e": 26537,
"s": 26231,
"text": "Traverse the two linked lists from start to endAdd the two digits each from respective linked lists.If one of the lists has reached the end then take 0 as its digit.Continue it until both the end of the lists.If the sum of two digits is greater than 9 then set carry as 1 and the current digit as sum % 10"
},
{
"code": null,
"e": 26585,
"s": 26537,
"text": "Traverse the two linked lists from start to end"
},
{
"code": null,
"e": 26639,
"s": 26585,
"text": "Add the two digits each from respective linked lists."
},
{
"code": null,
"e": 26705,
"s": 26639,
"text": "If one of the lists has reached the end then take 0 as its digit."
},
{
"code": null,
"e": 26750,
"s": 26705,
"text": "Continue it until both the end of the lists."
},
{
"code": null,
"e": 26847,
"s": 26750,
"text": "If the sum of two digits is greater than 9 then set carry as 1 and the current digit as sum % 10"
},
{
"code": null,
"e": 26894,
"s": 26847,
"text": "Below is the implementation of this approach. "
},
{
"code": null,
"e": 26898,
"s": 26894,
"text": "C++"
},
{
"code": "// C++ program to add two numbers// represented by linked list#include <bits/stdc++.h>using namespace std; // Linked list node class Node { public: int data; Node* next;}; /* Function to create a new node with given data */Node* newNode(int data){ Node* new_node = new Node(); new_node->data = data; new_node->next = NULL; return new_node;} /* Function to insert a node at the beginning of the Singly Linked List */void push(Node** head_ref, int new_data){ // Allocate node Node* new_node = newNode(new_data); // link the old list off the // new node new_node->next = (*head_ref); // Move the head to point to the // new node (*head_ref) = new_node;} /* Adds contents of two linked lists and return the head node of resultant list */Node* addTwoLists(Node* first, Node* second){ // res is head node of the resultant // list Node* res = NULL; Node *temp, *prev = NULL; int carry = 0, sum; // while both lists exist while (first != NULL || second != NULL) { // Calculate value of next digit in // resultant list. The next digit is // sum of following things // (i) Carry // (ii) Next digit of first // list (if there is a next digit) // (ii) Next digit of second // list (if there is a next digit) sum = carry + (first ? first->data : 0) + (second ? second->data : 0); // Update carry for next calculation carry = (sum >= 10) ? 1 : 0; // Update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data temp = newNode(sum); // If this is the first node then // set it as head of the resultant list if (res == NULL) res = temp; // If this is not the first // node then connect it to the rest. else prev->next = temp; // Set prev for next insertion prev = temp; // Move first and second // pointers to next nodes if (first) first = first->next; if (second) second = second->next; } if (carry > 0) temp->next = newNode(carry); // return head of the resultant // list return res;} // A utility function to print a // linked listvoid printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; } cout << endl;} // Driver codeint main(void){ Node* res = NULL; Node* first = NULL; Node* second = NULL; // Create first list // 7->5->9->4->6 push(&first, 6); push(&first, 4); push(&first, 9); push(&first, 5); push(&first, 7); printf(\"First List is \"); printList(first); // Create second list 8->4 push(&second, 4); push(&second, 8); cout << \"Second List is \"; printList(second); // Add the two lists and see // result res = addTwoLists(first, second); cout << \"Resultant list is \"; printList(res); return 0;}// This code is contributed by rathbhupendra",
"e": 30039,
"s": 26898,
"text": null
},
{
"code": null,
"e": 30047,
"s": 30039,
"text": "Output:"
},
{
"code": null,
"e": 30121,
"s": 30047,
"text": "First List is 7 5 9 4 6 \nSecond List is 8 4 \nResultant list is 5 0 0 5 6 "
},
{
"code": null,
"e": 30143,
"s": 30121,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 30287,
"s": 30143,
"text": "Time Complexity: O(m + n), where m and n are numbers of nodes in first and second lists respectively. The lists need to be traversed only once."
},
{
"code": null,
"e": 30376,
"s": 30287,
"text": "Space Complexity: O(m + n). A temporary linked list is needed to store the output number"
},
{
"code": null,
"e": 30433,
"s": 30376,
"text": "Method 2(Using STL): Using stack data structureApproach:"
},
{
"code": null,
"e": 30870,
"s": 30433,
"text": "1. Create 3 stacks namely s1,s2,s3.\n2. Fill s1 with Nodes of list1 and fill s2 with nodes of list2.\n3. Fill s3 by creating new nodes and setting the data of new nodes to the \n sum of s1.top(), s2.top() and carry until list1 and list2 are empty .\n4. If the sum >9, set carry 1\n5. Else set carry 0.\n6. Create a Node(say prev) that will contain the head of the sum List.\n7. Link all the elements of s3 from top to bottom.\n8. return prev."
},
{
"code": null,
"e": 30874,
"s": 30870,
"text": "C++"
},
{
"code": "// C++ program to add two numbers represented // by Linked Lists using Stack#include <bits/stdc++.h>using namespace std;class Node { public: int data; Node* next;};Node* newnode(int data){ Node* x = new Node(); x->data = data; return x;}// Function that returns the sum of two // numbers represented by linked listsNode* addTwoNumbers(Node* l1, Node* l2){ Node* prev = NULL; // Create 3 stacks stack<Node*> s1, s2, s3; // Fill first stack with first // List Elements while (l1 != NULL) { s1.push(l1); l1 = l1->next; } // Fill second stack with second // List Elements while (l2 != NULL) { s2.push(l2); l2 = l2->next; } int carry = 0; // Fill the third stack with the // sum of first and second stack while (!s1.empty() && !s2.empty()) { int sum = (s1.top()->data + s2.top()->data + carry); Node* temp = newnode(sum % 10); s3.push(temp); if (sum > 9) { carry = 1; } else { carry = 0; } s1.pop(); s2.pop(); } while (!s1.empty()) { int sum = carry + s1.top()->data; Node* temp = newnode(sum % 10); s3.push(temp); if (sum > 9) { carry = 1; } else { carry = 0; } s1.pop(); } while (!s2.empty()) { int sum = carry + s2.top()->data; Node* temp = newnode(sum % 10); s3.push(temp); if (sum > 9) { carry = 1; } else { carry = 0; } s2.pop(); } // If carry is still present create a // new node with value 1 and push it // to the third stack if (carry == 1) { Node* temp = newnode(1); s3.push(temp); } // Link all the elements inside // third stack with each other if (!s3.empty()) prev = s3.top(); while (!s3.empty()) { Node* temp = s3.top(); s3.pop(); if (s3.size() == 0) { temp->next = NULL; } else { temp->next = s3.top(); } } return prev;} // Utility functions// Function that displays the Listvoid Display(Node* head){ if (head == NULL) { return; } while (head->next != NULL) { cout << head->data << \" -> \"; head = head->next; } cout << head->data << endl;} // Function that adds element at // the end of the Linked Listvoid push(Node** head_ref, int d){ Node* new_node = newnode(d); new_node->next = NULL; if (*head_ref == NULL) { new_node->next = *head_ref; *head_ref = new_node; return; } Node* last = *head_ref; while (last->next != NULL && last != NULL) { last = last->next; } last->next = new_node; return;} // Driver codeint main(){ // Creating two lists first list // 9 -> 5 -> 0 // second List = 6 -> 7 Node* first = NULL; Node* second = NULL; Node* sum = NULL; push(&first, 9); push(&first, 5); push(&first, 0); push(&second, 6); push(&second, 7); cout << \"First List : \"; Display(first); cout << \"Second List : \"; Display(second); sum = addTwoNumbers(first, second); cout << \"Sum List : \"; Display(sum); return 0;}",
"e": 34261,
"s": 30874,
"text": null
},
{
"code": null,
"e": 34269,
"s": 34261,
"text": "Output:"
},
{
"code": null,
"e": 34343,
"s": 34269,
"text": "First List : 9 -> 5 -> 0\nSecond List : 6 -> 7\nSum List : 1 -> 0 -> 1 -> 7"
},
{
"code": null,
"e": 34431,
"s": 34343,
"text": "Another Approach with time complexity O(N):The given approach works as following steps:"
},
{
"code": null,
"e": 34780,
"s": 34431,
"text": "First, we calculate sizes of both the linked lists, size1 and size2, respectively.Then we traverse the bigger linked list, if any, and decrement till size of both become same.Now we traverse both linked lists till end.Now the backtracking occurs while performing addition.Finally, the head node is returned of the linked list containing the answer."
},
{
"code": null,
"e": 34863,
"s": 34780,
"text": "First, we calculate sizes of both the linked lists, size1 and size2, respectively."
},
{
"code": null,
"e": 34957,
"s": 34863,
"text": "Then we traverse the bigger linked list, if any, and decrement till size of both become same."
},
{
"code": null,
"e": 35001,
"s": 34957,
"text": "Now we traverse both linked lists till end."
},
{
"code": null,
"e": 35056,
"s": 35001,
"text": "Now the backtracking occurs while performing addition."
},
{
"code": null,
"e": 35133,
"s": 35056,
"text": "Finally, the head node is returned of the linked list containing the answer."
},
{
"code": null,
"e": 35137,
"s": 35133,
"text": "C++"
},
{
"code": "// C++ program to implement // the above approach#include <iostream>using namespace std; struct Node { int data; struct Node* next;}; // Recursive functionNode* addition(Node* temp1, Node* temp2, int size1, int size2){ // Creating a new Node Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Base case if (temp1->next == NULL && temp2->next == NULL) { // Addition of current nodes which is // the last nodes of both linked lists newNode->data = (temp1->data + temp2->data); // Set this current node's link null newNode->next = NULL; // Return the current node return newNode; } // Creating a node that contains sum // of previously added number Node* returnedNode = (struct Node*)malloc(sizeof(struct Node)); // If sizes are same then we move in // both linked list if (size2 == size1) { // Recursively call the function // move ahead in both linked list returnedNode = addition(temp1->next, temp2->next, size1 - 1, size2 - 1); // Add the current nodes and append the carry newNode->data = (temp1->data + temp2->data) + ((returnedNode->data) / 10); } // Or else we just move in big linked // list else { // Recursively call the function // move ahead in big linked list returnedNode = addition(temp1, temp2->next, size1, size2 - 1); // Add the current node and carry newNode->data = (temp2->data) + ((returnedNode->data) / 10); } // This node contains previously added // numbers so we need to set only // rightmost digit of it returnedNode->data = (returnedNode->data) % 10; // Set the returned node to the // current nod newNode->next = returnedNode; // return the current node return newNode;} // Function to add two numbers represented // by nexted list.struct Node* addTwoLists(struct Node* head1, struct Node* head2){ struct Node *temp1, *temp2, *ans = NULL; temp1 = head1; temp2 = head2; int size1 = 0, size2 = 0; // calculating the size of first // linked list while (temp1 != NULL) { temp1 = temp1->next; size1++; } // Calculating the size of second // linked list while (temp2 != NULL) { temp2 = temp2->next; size2++; } Node* returnedNode = (struct Node*)malloc(sizeof(struct Node)); // Traverse the bigger linked list if (size2 > size1) { returnedNode = addition(head1, head2, size1, size2); } else { returnedNode = addition(head2, head1, size2, size1); } // Creating new node if head node is >10 if (returnedNode->data >= 10) { ans = (struct Node*)malloc(sizeof(struct Node)); ans->data = (returnedNode->data) / 10; returnedNode->data = returnedNode->data % 10; ans->next = returnedNode; } else ans = returnedNode; // Return the head node of linked list // that contains answer return ans;} void Display(Node* head){ if (head == NULL) { return; } while (head->next != NULL) { cout << head->data << \" -> \"; head = head->next; } cout << head->data << endl;} // Function that adds element at the // end of the Linked Listvoid push(Node** head_ref, int d){ Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = d; new_node->next = NULL; if (*head_ref == NULL) { new_node->next = *head_ref; *head_ref = new_node; return; } Node* last = *head_ref; while (last->next != NULL && last != NULL) { last = last->next; } last->next = new_node; return;} // Driver codeint main(){ // Creating two lists Node* first = NULL; Node* second = NULL; Node* sum = NULL; push(&first, 5); push(&first, 6); push(&first, 3); push(&second, 8); push(&second, 4); push(&second, 2); cout << \"First List : \"; Display(first); cout << \"Second List : \"; Display(second); sum = addTwoLists(first, second); cout << \"Sum List : \"; Display(sum); return 0;}// This code is contributed by Dharmik Parmar",
"e": 39632,
"s": 35137,
"text": null
},
{
"code": null,
"e": 39640,
"s": 39632,
"text": "Output:"
},
{
"code": null,
"e": 39719,
"s": 39640,
"text": "First List : 5 -> 6 -> 3\nSecond List : 8 -> 4 -> 2\nSum List : 1 -> 4 -> 0 -> 5"
},
{
"code": null,
"e": 39788,
"s": 39719,
"text": "Related Article: Add two numbers represented by linked lists | Set 2"
},
{
"code": null,
"e": 39891,
"s": 39788,
"text": "Please refer complete article on Add two numbers represented by linked lists | Set 1 for more details!"
},
{
"code": null,
"e": 39900,
"s": 39891,
"text": "Accolite"
},
{
"code": null,
"e": 39907,
"s": 39900,
"text": "Amazon"
},
{
"code": null,
"e": 39916,
"s": 39907,
"text": "Flipkart"
},
{
"code": null,
"e": 39929,
"s": 39916,
"text": "Linked Lists"
},
{
"code": null,
"e": 39940,
"s": 39929,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 39950,
"s": 39940,
"text": "Microsoft"
},
{
"code": null,
"e": 39959,
"s": 39950,
"text": "Qualcomm"
},
{
"code": null,
"e": 39968,
"s": 39959,
"text": "Snapdeal"
},
{
"code": null,
"e": 39972,
"s": 39968,
"text": "C++"
},
{
"code": null,
"e": 39985,
"s": 39972,
"text": "C++ Programs"
},
{
"code": null,
"e": 39997,
"s": 39985,
"text": "Linked List"
},
{
"code": null,
"e": 40006,
"s": 39997,
"text": "Flipkart"
},
{
"code": null,
"e": 40015,
"s": 40006,
"text": "Accolite"
},
{
"code": null,
"e": 40022,
"s": 40015,
"text": "Amazon"
},
{
"code": null,
"e": 40032,
"s": 40022,
"text": "Microsoft"
},
{
"code": null,
"e": 40041,
"s": 40032,
"text": "Snapdeal"
},
{
"code": null,
"e": 40052,
"s": 40041,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 40061,
"s": 40052,
"text": "Qualcomm"
},
{
"code": null,
"e": 40073,
"s": 40061,
"text": "Linked List"
},
{
"code": null,
"e": 40077,
"s": 40073,
"text": "CPP"
},
{
"code": null,
"e": 40175,
"s": 40077,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40203,
"s": 40175,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 40223,
"s": 40203,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 40247,
"s": 40223,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 40280,
"s": 40247,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 40324,
"s": 40280,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 40359,
"s": 40324,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 40403,
"s": 40359,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 40429,
"s": 40403,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 40488,
"s": 40429,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Set all even bits of a number - GeeksforGeeks
|
03 May, 2021
Given a number, the task is to set all even bit of a number. Positions of bits are counted from LSB (least significant bit) to MSB (Most significant bit). Position of LSB is considered as 1.
Examples :
Input : 20
Output : 30
Binary representation of 20 is
10100. After setting
even bits, we get 11110
Input : 10
Output : 10
Method 1:- 1. First generate a number that contains even position bits. 2. Take OR with the original number. Note that 1 | 1 = 1 and 1 | 0 = 1.
Let’s understand this approach with below code.
C++
Java
Python3
C#
PHP
Javascript
// Simple CPP program to set all even// bits of a number#include <iostream>using namespace std; // Sets even bits of n and returns// modified number.int evenbitsetnumber(int n){ // Generate 101010...10 number and // store in res. int count = 0, res = 0; for (int temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return OR number return (n | res);} int main(){ int n = 10; cout << evenbitsetnumber(n); return 0;}
// Simple Java program to set all even// bits of a numberclass GFG{ // Sets even bits of n and returns // modified number. static int evenbitsetnumber(int n) { // Generate 101010...10 number and // store in res. int count = 0, res = 0; for (int temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return OR number return (n | res); } // Driver code public static void main(String[] args) { int n = 4; System.out.println(evenbitsetnumber(n)); }} // This code is contributed// by prerna saini.
# Simple Python program to set all even# bits of a number # Sets even bits of n and returns# modified number.def evenbitsetnumber(n): # Generate 101010...10 number and # store in res. count = 0 res = 0 temp = n while(temp > 0): # if bit is even then generate # number and or with res if (count % 2 == 1): res |= (1 << count) count+=1 temp >>= 1 # return OR number return (n | res) n = 10print(evenbitsetnumber(n)) # This code is contributed# by Smitha Dinesh Semwal
// Simple C# program to set// all even bits of a numberusing System; class GFG{ // Sets even bits of n and // returns modified number. static int evenbitsetnumber(int n) { // Generate 101010...10 number // and store in res. int count = 0, res = 0; for (int temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return OR number return (n | res); } // Driver code public static void Main() { int n = 4; Console.WriteLine(evenbitsetnumber(n)); }} // This code is contributed by vt_m.
<?php// Simple php program to set// all even bits of a number // Sets even bits of n and// returns modified number.function evenbitsetnumber($n){ // Generate 101010...10 number // and store in res. $count = 0; $res = 0; for ($temp = $n; $temp > 0; $temp >>= 1) { // if bit is even then generate // number and or with res if ($count % 2 == 1) $res |= (1 << $count); $count++; } // return OR number return ($n | $res);} //Driver Code $n = 10; echo evenbitsetnumber($n); //This Code is contributed by mits?>
<script> // JavaScript program to set all even// bits of a number // Sets even bits of n and returns// modified number.function evenbitsetnumber(n){ // Generate 101010...10 number and // store in res. let count = 0, res = 0; for(let temp = n; temp > 0; temp >>= 1) { // If bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // Return OR number return (n | res);} // Driver Codelet n = 10; document.write(evenbitsetnumber(n)); // This code is contributed by avijitmondal1998 </script>
10
Method 2 (A O(1) solution for 32 bit numbers)
C++
Java
Python3
C#
PHP
Javascript
// Efficient CPP program to set all even// bits of a number#include <iostream>using namespace std; // return msb set numberint getmsb(int n){ // set all bits n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return msb // increment n by 1 // and shift by 1 return (n + 1) >> 1;} // return even seted numberint getevenbits(int n){ // get msb here n = getmsb(n); // generate even bits like 101010.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // if bits is odd then shift by 1 if (n & 1) n = n >> 1; // return even set bits number return n;} // set all even bits hereint setallevenbits(int n){ // take or with even set bits number return n | getevenbits(n);} int main(){ int n = 10; cout << setallevenbits(n); return 0;}
// Efficient Java program to// set all even bits of a numberimport java.io.*; class GFG{ // return msb set numberstatic int getmsb(int n){ // set all bits n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return msb // increment n by 1 // and shift by 1 return (n + 1) >> 1;} // return even seted numberstatic int getevenbits(int n){ // get msb here n = getmsb(n); // generate even // bits like 101010.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // if bits is odd // then shift by 1 if ((n & 1) == 1) n = n >> 1; // return even // set bits number return n;} // set all even bits herestatic int setallevenbits(int n){ // take or with even // set bits number return n | getevenbits(n);} // Driver Codepublic static void main (String[] args){ int n = 10; System.out.println(setallevenbits(n));}} // This code is contributed by ajit
# Efficient Python 3# program to set all even# bits of a number # return msb set numberdef getmsb(n): # set all bits n |= n >> 1 n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 # return msb # increment n by 1 # and shift by 1 return (n + 1) >> 1 # return even seted numberdef getevenbits(n): # get msb here n = getmsb(n) # generate even bits like 101010.. n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 # if bits is odd then shift by 1 if (n & 1): n = n >> 1 # return even set bits number return n # set all even bits heredef setallevenbits(n): # take or with even set bits number return n | getevenbits(n) n = 10print(setallevenbits(n)) # This code is contributed by# Smitha Dinesh Semwal
// Efficient C# program to// set all even bits of a numberusing System; class GFG{ // return msb set numberstatic int getmsb(int n){ // set all bits n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return msb // increment n by 1 // and shift by 1 return (n + 1) >> 1;} // return even seted numberstatic int getevenbits(int n){ // get msb here n = getmsb(n); // generate even // bits like 101010.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // if bits is odd // then shift by 1 if ((n & 1) == 1) n = n >> 1; // return even // set bits number return n;} // set all even bits herestatic int setallevenbits(int n){ // take or with even // set bits number return n | getevenbits(n);} // Driver Codepublic static void Main (){ int n = 10; Console.WriteLine(setallevenbits(n));}} // This code is contributed by aj_36
<?php// Efficient php program to set// all even bits of a number // return msb set numberfunction getmsb($n){ // set all bits $n |= $n >> 1; $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // return msb // increment n by 1 // and shift by 1 return ($n + 1) >> 1;} // return even seted numberfunction getevenbits($n){ // get msb here $n = getmsb($n); // generate even bits // like 101010.. $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // if bits is odd then // shift by 1 if ($n & 1) $n = $n >> 1; // return even set // bits number return $n;} // set all even bits herefunction setallevenbits($n){ // take or with even // set bits number return $n | getevenbits($n);} //Driver code $n = 10; echo setallevenbits($n); //This code is contributed by mits?>
<script> // Efficient Javascript program to// set all even bits of a number // Return msb set numberfunction getmsb(n){ // Set all bits n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Return msb // increment n by 1 // and shift by 1 return (n + 1) >> 1;} // Return even seted numberfunction getevenbits(n){ // Get msb here n = getmsb(n); // Generate even // bits like 101010.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // If bits is odd // then shift by 1 if ((n & 1) == 1) n = n >> 1; // Return even // set bits number return n;} // Set all even bits herefunction setallevenbits(n){ // Take or with even // set bits number return n | getevenbits(n);} // Driver codelet n = 10; document.write(setallevenbits(n)); // This code is contributed by decode2207 </script>
10
Mithun Kumar
jit_t
avijitmondal1998
decode2207
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Cyclic Redundancy Check and Modulo-2 Division
Add two numbers without using arithmetic operators
Josephus problem | Set 1 (A O(n) Solution)
Bit Fields in C
Set, Clear and Toggle a given bit of a number in C
Find the element that appears once
Bits manipulation (Important tactics)
C++ bitset and its application
1's and 2's complement of a Binary Number
|
[
{
"code": null,
"e": 26515,
"s": 26487,
"text": "\n03 May, 2021"
},
{
"code": null,
"e": 26706,
"s": 26515,
"text": "Given a number, the task is to set all even bit of a number. Positions of bits are counted from LSB (least significant bit) to MSB (Most significant bit). Position of LSB is considered as 1."
},
{
"code": null,
"e": 26718,
"s": 26706,
"text": "Examples : "
},
{
"code": null,
"e": 26842,
"s": 26718,
"text": "Input : 20 \nOutput : 30\nBinary representation of 20 is\n10100. After setting\neven bits, we get 11110\n\nInput : 10\nOutput : 10"
},
{
"code": null,
"e": 26986,
"s": 26842,
"text": "Method 1:- 1. First generate a number that contains even position bits. 2. Take OR with the original number. Note that 1 | 1 = 1 and 1 | 0 = 1."
},
{
"code": null,
"e": 27034,
"s": 26986,
"text": "Let’s understand this approach with below code."
},
{
"code": null,
"e": 27038,
"s": 27034,
"text": "C++"
},
{
"code": null,
"e": 27043,
"s": 27038,
"text": "Java"
},
{
"code": null,
"e": 27051,
"s": 27043,
"text": "Python3"
},
{
"code": null,
"e": 27054,
"s": 27051,
"text": "C#"
},
{
"code": null,
"e": 27058,
"s": 27054,
"text": "PHP"
},
{
"code": null,
"e": 27069,
"s": 27058,
"text": "Javascript"
},
{
"code": "// Simple CPP program to set all even// bits of a number#include <iostream>using namespace std; // Sets even bits of n and returns// modified number.int evenbitsetnumber(int n){ // Generate 101010...10 number and // store in res. int count = 0, res = 0; for (int temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return OR number return (n | res);} int main(){ int n = 10; cout << evenbitsetnumber(n); return 0;}",
"e": 27651,
"s": 27069,
"text": null
},
{
"code": "// Simple Java program to set all even// bits of a numberclass GFG{ // Sets even bits of n and returns // modified number. static int evenbitsetnumber(int n) { // Generate 101010...10 number and // store in res. int count = 0, res = 0; for (int temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return OR number return (n | res); } // Driver code public static void main(String[] args) { int n = 4; System.out.println(evenbitsetnumber(n)); }} // This code is contributed// by prerna saini.",
"e": 28417,
"s": 27651,
"text": null
},
{
"code": "# Simple Python program to set all even# bits of a number # Sets even bits of n and returns# modified number.def evenbitsetnumber(n): # Generate 101010...10 number and # store in res. count = 0 res = 0 temp = n while(temp > 0): # if bit is even then generate # number and or with res if (count % 2 == 1): res |= (1 << count) count+=1 temp >>= 1 # return OR number return (n | res) n = 10print(evenbitsetnumber(n)) # This code is contributed# by Smitha Dinesh Semwal",
"e": 28965,
"s": 28417,
"text": null
},
{
"code": "// Simple C# program to set// all even bits of a numberusing System; class GFG{ // Sets even bits of n and // returns modified number. static int evenbitsetnumber(int n) { // Generate 101010...10 number // and store in res. int count = 0, res = 0; for (int temp = n; temp > 0; temp >>= 1) { // if bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // return OR number return (n | res); } // Driver code public static void Main() { int n = 4; Console.WriteLine(evenbitsetnumber(n)); }} // This code is contributed by vt_m.",
"e": 29721,
"s": 28965,
"text": null
},
{
"code": "<?php// Simple php program to set// all even bits of a number // Sets even bits of n and// returns modified number.function evenbitsetnumber($n){ // Generate 101010...10 number // and store in res. $count = 0; $res = 0; for ($temp = $n; $temp > 0; $temp >>= 1) { // if bit is even then generate // number and or with res if ($count % 2 == 1) $res |= (1 << $count); $count++; } // return OR number return ($n | $res);} //Driver Code $n = 10; echo evenbitsetnumber($n); //This Code is contributed by mits?>",
"e": 30311,
"s": 29721,
"text": null
},
{
"code": "<script> // JavaScript program to set all even// bits of a number // Sets even bits of n and returns// modified number.function evenbitsetnumber(n){ // Generate 101010...10 number and // store in res. let count = 0, res = 0; for(let temp = n; temp > 0; temp >>= 1) { // If bit is even then generate // number and or with res if (count % 2 == 1) res |= (1 << count); count++; } // Return OR number return (n | res);} // Driver Codelet n = 10; document.write(evenbitsetnumber(n)); // This code is contributed by avijitmondal1998 </script>",
"e": 30943,
"s": 30311,
"text": null
},
{
"code": null,
"e": 30946,
"s": 30943,
"text": "10"
},
{
"code": null,
"e": 30995,
"s": 30948,
"text": "Method 2 (A O(1) solution for 32 bit numbers) "
},
{
"code": null,
"e": 30999,
"s": 30995,
"text": "C++"
},
{
"code": null,
"e": 31004,
"s": 30999,
"text": "Java"
},
{
"code": null,
"e": 31012,
"s": 31004,
"text": "Python3"
},
{
"code": null,
"e": 31015,
"s": 31012,
"text": "C#"
},
{
"code": null,
"e": 31019,
"s": 31015,
"text": "PHP"
},
{
"code": null,
"e": 31030,
"s": 31019,
"text": "Javascript"
},
{
"code": "// Efficient CPP program to set all even// bits of a number#include <iostream>using namespace std; // return msb set numberint getmsb(int n){ // set all bits n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return msb // increment n by 1 // and shift by 1 return (n + 1) >> 1;} // return even seted numberint getevenbits(int n){ // get msb here n = getmsb(n); // generate even bits like 101010.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // if bits is odd then shift by 1 if (n & 1) n = n >> 1; // return even set bits number return n;} // set all even bits hereint setallevenbits(int n){ // take or with even set bits number return n | getevenbits(n);} int main(){ int n = 10; cout << setallevenbits(n); return 0;}",
"e": 31868,
"s": 31030,
"text": null
},
{
"code": "// Efficient Java program to// set all even bits of a numberimport java.io.*; class GFG{ // return msb set numberstatic int getmsb(int n){ // set all bits n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return msb // increment n by 1 // and shift by 1 return (n + 1) >> 1;} // return even seted numberstatic int getevenbits(int n){ // get msb here n = getmsb(n); // generate even // bits like 101010.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // if bits is odd // then shift by 1 if ((n & 1) == 1) n = n >> 1; // return even // set bits number return n;} // set all even bits herestatic int setallevenbits(int n){ // take or with even // set bits number return n | getevenbits(n);} // Driver Codepublic static void main (String[] args){ int n = 10; System.out.println(setallevenbits(n));}} // This code is contributed by ajit",
"e": 32831,
"s": 31868,
"text": null
},
{
"code": "# Efficient Python 3# program to set all even# bits of a number # return msb set numberdef getmsb(n): # set all bits n |= n >> 1 n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 # return msb # increment n by 1 # and shift by 1 return (n + 1) >> 1 # return even seted numberdef getevenbits(n): # get msb here n = getmsb(n) # generate even bits like 101010.. n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 # if bits is odd then shift by 1 if (n & 1): n = n >> 1 # return even set bits number return n # set all even bits heredef setallevenbits(n): # take or with even set bits number return n | getevenbits(n) n = 10print(setallevenbits(n)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 33617,
"s": 32831,
"text": null
},
{
"code": "// Efficient C# program to// set all even bits of a numberusing System; class GFG{ // return msb set numberstatic int getmsb(int n){ // set all bits n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // return msb // increment n by 1 // and shift by 1 return (n + 1) >> 1;} // return even seted numberstatic int getevenbits(int n){ // get msb here n = getmsb(n); // generate even // bits like 101010.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // if bits is odd // then shift by 1 if ((n & 1) == 1) n = n >> 1; // return even // set bits number return n;} // set all even bits herestatic int setallevenbits(int n){ // take or with even // set bits number return n | getevenbits(n);} // Driver Codepublic static void Main (){ int n = 10; Console.WriteLine(setallevenbits(n));}} // This code is contributed by aj_36",
"e": 34562,
"s": 33617,
"text": null
},
{
"code": "<?php// Efficient php program to set// all even bits of a number // return msb set numberfunction getmsb($n){ // set all bits $n |= $n >> 1; $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // return msb // increment n by 1 // and shift by 1 return ($n + 1) >> 1;} // return even seted numberfunction getevenbits($n){ // get msb here $n = getmsb($n); // generate even bits // like 101010.. $n |= $n >> 2; $n |= $n >> 4; $n |= $n >> 8; $n |= $n >> 16; // if bits is odd then // shift by 1 if ($n & 1) $n = $n >> 1; // return even set // bits number return $n;} // set all even bits herefunction setallevenbits($n){ // take or with even // set bits number return $n | getevenbits($n);} //Driver code $n = 10; echo setallevenbits($n); //This code is contributed by mits?>",
"e": 35447,
"s": 34562,
"text": null
},
{
"code": "<script> // Efficient Javascript program to// set all even bits of a number // Return msb set numberfunction getmsb(n){ // Set all bits n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // Return msb // increment n by 1 // and shift by 1 return (n + 1) >> 1;} // Return even seted numberfunction getevenbits(n){ // Get msb here n = getmsb(n); // Generate even // bits like 101010.. n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; // If bits is odd // then shift by 1 if ((n & 1) == 1) n = n >> 1; // Return even // set bits number return n;} // Set all even bits herefunction setallevenbits(n){ // Take or with even // set bits number return n | getevenbits(n);} // Driver codelet n = 10; document.write(setallevenbits(n)); // This code is contributed by decode2207 </script>",
"e": 36352,
"s": 35447,
"text": null
},
{
"code": null,
"e": 36355,
"s": 36352,
"text": "10"
},
{
"code": null,
"e": 36370,
"s": 36357,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 36376,
"s": 36370,
"text": "jit_t"
},
{
"code": null,
"e": 36393,
"s": 36376,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 36404,
"s": 36393,
"text": "decode2207"
},
{
"code": null,
"e": 36414,
"s": 36404,
"text": "Bit Magic"
},
{
"code": null,
"e": 36424,
"s": 36414,
"text": "Bit Magic"
},
{
"code": null,
"e": 36522,
"s": 36424,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36552,
"s": 36522,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 36598,
"s": 36552,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 36649,
"s": 36598,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 36692,
"s": 36649,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 36708,
"s": 36692,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 36759,
"s": 36708,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 36794,
"s": 36759,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 36832,
"s": 36794,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 36863,
"s": 36832,
"text": "C++ bitset and its application"
}
] |
Gaussian Filter Generation in C++ - GeeksforGeeks
|
28 Feb, 2022
Gaussian Filtering is widely used in the field of image processing. It is used to reduce the noise of an image. In this article we will generate a 2D Gaussian Kernel. The 2D Gaussian Kernel follows the below given Gaussian Distribution. Where, y is the distance along vertical axis from the origin, x is the distance along horizontal axis from the origin and σ is the standard deviation.
Implementation in C++
// C++ program to generate Gaussian filter#include <cmath>#include <iomanip>#include <iostream>using namespace std; // Function to create Gaussian filtervoid FilterCreation(double GKernel[][5]){ // initialising standard deviation to 1.0 double sigma = 1.0; double r, s = 2.0 * sigma * sigma; // sum is for normalization double sum = 0.0; // generating 5x5 kernel for (int x = -2; x <= 2; x++) { for (int y = -2; y <= 2; y++) { r = sqrt(x * x + y * y); GKernel[x + 2][y + 2] = (exp(-(r * r) / s)) / (M_PI * s); sum += GKernel[x + 2][y + 2]; } } // normalising the Kernel for (int i = 0; i < 5; ++i) for (int j = 0; j < 5; ++j) GKernel[i][j] /= sum;} // Driver program to test above functionint main(){ double GKernel[5][5]; FilterCreation(GKernel); for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) cout << GKernel[i][j] << "\t"; cout << endl; }}
Output:
0.00296902 0.0133062 0.0219382 0.0133062 0.00296902
0.0133062 0.0596343 0.0983203 0.0596343 0.0133062
0.0219382 0.0983203 0.162103 0.0983203 0.0219382
0.0133062 0.0596343 0.0983203 0.0596343 0.0133062
0.00296902 0.0133062 0.0219382 0.0133062 0.00296902
References: https://en.wikipedia.org/wiki/Gaussian_filterThis 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
gabaa406
surinderdawra388
Image-Processing
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Print all possible combinations of r elements in a given array of size n
Sieve of Eratosthenes
Operators in C / C++
Program for factorial of a number
Find minimum number of coins that make a given value
Program for Decimal to Binary Conversion
|
[
{
"code": null,
"e": 26059,
"s": 26031,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 26447,
"s": 26059,
"text": "Gaussian Filtering is widely used in the field of image processing. It is used to reduce the noise of an image. In this article we will generate a 2D Gaussian Kernel. The 2D Gaussian Kernel follows the below given Gaussian Distribution. Where, y is the distance along vertical axis from the origin, x is the distance along horizontal axis from the origin and σ is the standard deviation."
},
{
"code": null,
"e": 26470,
"s": 26447,
"text": "Implementation in C++ "
},
{
"code": "// C++ program to generate Gaussian filter#include <cmath>#include <iomanip>#include <iostream>using namespace std; // Function to create Gaussian filtervoid FilterCreation(double GKernel[][5]){ // initialising standard deviation to 1.0 double sigma = 1.0; double r, s = 2.0 * sigma * sigma; // sum is for normalization double sum = 0.0; // generating 5x5 kernel for (int x = -2; x <= 2; x++) { for (int y = -2; y <= 2; y++) { r = sqrt(x * x + y * y); GKernel[x + 2][y + 2] = (exp(-(r * r) / s)) / (M_PI * s); sum += GKernel[x + 2][y + 2]; } } // normalising the Kernel for (int i = 0; i < 5; ++i) for (int j = 0; j < 5; ++j) GKernel[i][j] /= sum;} // Driver program to test above functionint main(){ double GKernel[5][5]; FilterCreation(GKernel); for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) cout << GKernel[i][j] << \"\\t\"; cout << endl; }}",
"e": 27460,
"s": 26470,
"text": null
},
{
"code": null,
"e": 27469,
"s": 27460,
"text": "Output: "
},
{
"code": null,
"e": 27798,
"s": 27469,
"text": "0.00296902 0.0133062 0.0219382 0.0133062 0.00296902 \n0.0133062 0.0596343 0.0983203 0.0596343 0.0133062 \n0.0219382 0.0983203 0.162103 0.0983203 0.0219382 \n0.0133062 0.0596343 0.0983203 0.0596343 0.0133062 \n0.00296902 0.0133062 0.0219382 0.0133062 0.00296902"
},
{
"code": null,
"e": 28277,
"s": 27798,
"text": "References: https://en.wikipedia.org/wiki/Gaussian_filterThis 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": 28283,
"s": 28277,
"text": "jit_t"
},
{
"code": null,
"e": 28292,
"s": 28283,
"text": "gabaa406"
},
{
"code": null,
"e": 28309,
"s": 28292,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28326,
"s": 28309,
"text": "Image-Processing"
},
{
"code": null,
"e": 28339,
"s": 28326,
"text": "Mathematical"
},
{
"code": null,
"e": 28352,
"s": 28339,
"text": "Mathematical"
},
{
"code": null,
"e": 28450,
"s": 28352,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28474,
"s": 28450,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 28517,
"s": 28474,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 28531,
"s": 28517,
"text": "Prime Numbers"
},
{
"code": null,
"e": 28573,
"s": 28531,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 28646,
"s": 28573,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 28668,
"s": 28646,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 28689,
"s": 28668,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 28723,
"s": 28689,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 28776,
"s": 28723,
"text": "Find minimum number of coins that make a given value"
}
] |
Java program to print Even length words in a String - GeeksforGeeks
|
28 Feb, 2020
Given a string str, write a Java program to print all words with even length in the given string.
Examples:
Input: s = "This is a java language"
Output: This
is
java
language
Input: s = "i am GFG"
Output: am
Approach:
Take the string
Break the string into words with the help of split() method in String class. It takes the string by which the sentence is to be broken. So here ” “(space) is passed as the parameter. As a result, the words of the string are split and returned as a string arrayString[] words = str.split(" ");
String[] words = str.split(" ");
Traverse each word in the string array returned with the help of Foreach loop in Java.for(String word : words)
{ }
for(String word : words)
{ }
Calculate the length of each word using String.length() function.int lengthOfWord = word.length();
int lengthOfWord = word.length();
If the length is even, then print the word.
Below is the implementation of the above approach:
// Java program to print// even length words in a string class GfG { public static void printWords(String s) { // Splits Str into all possible tokens for (String word : s.split(" ")) // if length is even if (word.length() % 2 == 0) // Print the word System.out.println(word); } // Driver Code public static void main(String[] args) { String s = "i am Geeks for Geeks and a Geek"; printWords(s); }}
am
Geek
Java-String-Programs
Java
Java Programs
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 26010,
"s": 25982,
"text": "\n28 Feb, 2020"
},
{
"code": null,
"e": 26108,
"s": 26010,
"text": "Given a string str, write a Java program to print all words with even length in the given string."
},
{
"code": null,
"e": 26118,
"s": 26108,
"text": "Examples:"
},
{
"code": null,
"e": 26245,
"s": 26118,
"text": "Input: s = \"This is a java language\"\nOutput: This\n is\n java\n language \n\nInput: s = \"i am GFG\"\nOutput: am\n"
},
{
"code": null,
"e": 26255,
"s": 26245,
"text": "Approach:"
},
{
"code": null,
"e": 26271,
"s": 26255,
"text": "Take the string"
},
{
"code": null,
"e": 26565,
"s": 26271,
"text": "Break the string into words with the help of split() method in String class. It takes the string by which the sentence is to be broken. So here ” “(space) is passed as the parameter. As a result, the words of the string are split and returned as a string arrayString[] words = str.split(\" \");\n"
},
{
"code": null,
"e": 26599,
"s": 26565,
"text": "String[] words = str.split(\" \");\n"
},
{
"code": null,
"e": 26715,
"s": 26599,
"text": "Traverse each word in the string array returned with the help of Foreach loop in Java.for(String word : words)\n{ }\n"
},
{
"code": null,
"e": 26745,
"s": 26715,
"text": "for(String word : words)\n{ }\n"
},
{
"code": null,
"e": 26845,
"s": 26745,
"text": "Calculate the length of each word using String.length() function.int lengthOfWord = word.length();\n"
},
{
"code": null,
"e": 26880,
"s": 26845,
"text": "int lengthOfWord = word.length();\n"
},
{
"code": null,
"e": 26924,
"s": 26880,
"text": "If the length is even, then print the word."
},
{
"code": null,
"e": 26975,
"s": 26924,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to print// even length words in a string class GfG { public static void printWords(String s) { // Splits Str into all possible tokens for (String word : s.split(\" \")) // if length is even if (word.length() % 2 == 0) // Print the word System.out.println(word); } // Driver Code public static void main(String[] args) { String s = \"i am Geeks for Geeks and a Geek\"; printWords(s); }}",
"e": 27485,
"s": 26975,
"text": null
},
{
"code": null,
"e": 27494,
"s": 27485,
"text": "am\nGeek\n"
},
{
"code": null,
"e": 27515,
"s": 27494,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 27520,
"s": 27515,
"text": "Java"
},
{
"code": null,
"e": 27534,
"s": 27520,
"text": "Java Programs"
},
{
"code": null,
"e": 27542,
"s": 27534,
"text": "Strings"
},
{
"code": null,
"e": 27550,
"s": 27542,
"text": "Strings"
},
{
"code": null,
"e": 27555,
"s": 27550,
"text": "Java"
},
{
"code": null,
"e": 27653,
"s": 27555,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27704,
"s": 27653,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27734,
"s": 27704,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27749,
"s": 27734,
"text": "Stream In Java"
},
{
"code": null,
"e": 27768,
"s": 27749,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27799,
"s": 27768,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27827,
"s": 27799,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 27871,
"s": 27827,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 27897,
"s": 27871,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27931,
"s": 27897,
"text": "Convert Double to Integer in Java"
}
] |
Find Equal (or Middle) Point in a sorted array with duplicates - GeeksforGeeks
|
19 May, 2021
Given a sorted array of n size, the task is to find whether an element exists in the array from where the number of smaller elements is equal to the number of greater elements.If Equal Point appears multiple times in input array, return the index of its first occurrence. If doesn’t exist, return -1.Examples :
Input : arr[] = {1, 2, 3, 3, 3, 3}
Output : 1
Equal Point is arr[1] which is 2. Number of
elements smaller than 2 and greater than 2
are same.
Input : arr[] = {1, 2, 3, 3, 3, 3, 4, 4}
Output : Equal Point does not exist.
Input : arr[] = {1, 2, 3, 4, 4, 5, 6, 6, 6, 7}
Output : 3
First occurrence of equal point is arr[3]
A Naive approach is to take every element and count how many elements are smaller than that and then greater element. Then compare if both are equal or not.An Efficient approach is to create an auxiliary array and store all distinct elements in it. If the count of distinct elements is even, then Equal Point does not exist. If count is odd, then the equal point is the middle point of the auxiliary array.Below is implementation of above idea.
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to find Equal point in a sorted array// which may have many duplicates.#include <bits/stdc++.h>using namespace std; // Returns value of Equal point in a sorted array arr[]// It returns -1 if there is no Equal Point.int findEqualPoint(int arr[], int n){ // To store first indexes of distinct elements of arr[] int distArr[n]; // Traverse input array and store indexes of first // occurrences of distinct elements in distArr[] int i = 0, di = 0; while (i < n) { // This element must be first occurrence of a // number (this is made sure by below loop), // so add it to distinct array. distArr[di++] = i++; // Avoid all copies of arr[i] and move to next // distinct element. while (i<n && arr[i] == arr[i-1]) i++; } // di now has total number of distinct elements. // If di is odd, then equal point exists and is at // di/2, otherwise return -1. return (di & 1)? distArr[di>>1] : -1;} // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 4, 5, 6, 6, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); int index = findEqualPoint(arr, n); if (index != -1) cout << "Equal Point = " << arr[index] ; else cout << "Equal Point does not exists"; return 0;}
//Java program to find Equal point in a sorted array// which may have many duplicates. class Test{ // Returns value of Equal point in a sorted array arr[] // It returns -1 if there is no Equal Point. static int findEqualPoint(int arr[], int n) { // To store first indexes of distinct elements of arr[] int distArr[] = new int[n]; // Traverse input array and store indexes of first // occurrences of distinct elements in distArr[] int i = 0, di = 0; while (i < n) { // This element must be first occurrence of a // number (this is made sure by below loop), // so add it to distinct array. distArr[di++] = i++; // Avoid all copies of arr[i] and move to next // distinct element. while (i<n && arr[i] == arr[i-1]) i++; } // di now has total number of distinct elements. // If di is odd, then equal point exists and is at // di/2, otherwise return -1. return (di & 1)!=0 ? distArr[di>>1] : -1; } // Driver method public static void main(String args[]) { int arr[] = {1, 2, 3, 4, 4, 5, 6, 6, 6, 7}; int index = findEqualPoint(arr, arr.length); System.out.println(index != -1 ? "Equal Point = " + arr[index] : "Equal Point does not exists"); }}
# Python 3 program to find# Equal point in a sorted# array which may have# many duplicates. # Returns value of Equal# point in a sorted array# arr[]. It returns -1 if# there is no Equal Point.def findEqualPoint(arr, n): # To store first indexes of # distinct elements of arr[] distArr = [0] * n # Traverse input array and # store indexes of first # occurrences of distinct # elements in distArr[] i = 0 di = 0 while (i < n): # This element must be # first occurrence of a # number (this is made # sure by below loop), # so add it to distinct array. distArr[di] = i di += 1 i += 1 # Avoid all copies of # arr[i] and move to # next distinct element. while (i < n and arr[i] == arr[i - 1]): i += 1 # di now has total number # of distinct elements. # If di is odd, then equal # point exists and is at # di/2, otherwise return -1. return distArr[di >> 1] if (di & 1) else -1 # Driver codearr = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7]n = len(arr)index = findEqualPoint(arr, n)if (index != -1): print("Equal Point = " , arr[index])else: print("Equal Point does " + "not exists") # This code is contributed# by Smitha
// C# program to find Equal// point in a sorted array// which may have many duplicates.using System; class GFG{ // Returns value of Equal point // in a sorted array arr[] // It returns -1 if there // is no Equal Point. static int findEqualPoint(int []arr, int n) { // To store first indexes of // distinct elements of arr[] int []distArr = new int[n]; // Traverse input array and // store indexes of first // occurrences of distinct // elements in distArr[] int i = 0, di = 0; while (i < n) { // This element must be // first occurrence of a // number (this is made // sure by below loop), // so add it to distinct array. distArr[di++] = i++; // Avoid all copies of // arr[i] and move to // next distinct element. while (i < n && arr[i] == arr[i - 1]) i++; } // di now has total number // of distinct elements. // If di is odd, then equal // point exists and is at // di/2, otherwise return -1. return (di & 1) != 0 ? distArr[di >> 1] : -1; } // Driver Code public static void Main() { int []arr = {1, 2, 3, 4, 4, 5, 6, 6, 6, 7}; int index = findEqualPoint(arr, arr.Length); Console.Write(index != -1 ? "Equal Point = " + arr[index] : "Equal Point does not exists"); }}
<?php// PHP program to find Equal point in a// sorted array which may have many// duplicates. // Returns value of Equal point in a// sorted array arr[] It returns -1// if there is no Equal Point.function findEqualPoint( $arr, $n){ // To store first indexes of distinct // elements of arr[] $distArr = array(); // Traverse input array and store // indexes of first occurrences of // distinct elements in distArr[] $i = 0; $di = 0; while ($i < $n) { // This element must be first // occurrence of a number (this // is made sure by below loop), // so add it to distinct array. $distArr[$di++] = $i++; // Avoid all copies of arr[i] // and move to next distinct // element. while ($i < $n and $arr[$i] == $arr[$i-1]) $i++; } // di now has total number of // distinct elements. If di is odd, // then equal point exists and is // at di/2, otherwise return -1. return ($di & 1)? $distArr[$di>>1] : -1;} // Driver code$arr = array(1, 2, 3, 4, 4, 5, 6, 6, 6, 7);$n = count($arr);$index = findEqualPoint($arr, $n);if ($index != -1) echo "Equal Point = " , $arr[$index] ;else echo "Equal Point does not exists"; // This code is contributed by anuj_67.?>
<script> // JavaScript program to find Equal // point in a sorted array // which may have many duplicates. // Returns value of Equal point // in a sorted array arr[] // It returns -1 if there // is no Equal Point. function findEqualPoint(arr, n) { // To store first indexes of // distinct elements of arr[] let distArr = new Array(n); distArr.fill(0); // Traverse input array and // store indexes of first // occurrences of distinct // elements in distArr[] let i = 0, di = 0; while (i < n) { // This element must be // first occurrence of a // number (this is made // sure by below loop), // so add it to distinct array. distArr[di++] = i++; // Avoid all copies of // arr[i] and move to // next distinct element. while (i < n && arr[i] == arr[i - 1]) i++; } // di now has total number // of distinct elements. // If di is odd, then equal // point exists and is at // di/2, otherwise return -1. return (di & 1) != 0 ? distArr[di >> 1] : -1; } let arr = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7]; let index = findEqualPoint(arr, arr.length); document.write(index != -1 ? "Equal Point = " + arr[index] : "Equal Point does not exists"); </script>
Output:
Equal Point = 4
Time Complexity : O(n) Auxiliary Space : O(n)Space Optimization : We can reduce extra space by traversing the array twice instead of once.
Count total distinct elements by doing a traversal of input array. Let this count be distCount.If distCount is even, return -1.If distCount is odd, traverse the array again and stop at distCount/2 and return this index.
Count total distinct elements by doing a traversal of input array. Let this count be distCount.
If distCount is even, return -1.
If distCount is odd, traverse the array again and stop at distCount/2 and return this index.
Thanks to Pavan Kumar J S for suggesting this space-optimized approach.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.
nitin mittal
vt_m
Smitha Dinesh Semwal
shubham_singh
Mukul Mahaliyan
decode2207
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
|
[
{
"code": null,
"e": 26193,
"s": 26165,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 26506,
"s": 26193,
"text": "Given a sorted array of n size, the task is to find whether an element exists in the array from where the number of smaller elements is equal to the number of greater elements.If Equal Point appears multiple times in input array, return the index of its first occurrence. If doesn’t exist, return -1.Examples : "
},
{
"code": null,
"e": 26832,
"s": 26506,
"text": "Input : arr[] = {1, 2, 3, 3, 3, 3}\nOutput : 1\nEqual Point is arr[1] which is 2. Number of\nelements smaller than 2 and greater than 2 \nare same.\n\nInput : arr[] = {1, 2, 3, 3, 3, 3, 4, 4}\nOutput : Equal Point does not exist.\n\nInput : arr[] = {1, 2, 3, 4, 4, 5, 6, 6, 6, 7}\nOutput : 3\nFirst occurrence of equal point is arr[3]"
},
{
"code": null,
"e": 27281,
"s": 26834,
"text": "A Naive approach is to take every element and count how many elements are smaller than that and then greater element. Then compare if both are equal or not.An Efficient approach is to create an auxiliary array and store all distinct elements in it. If the count of distinct elements is even, then Equal Point does not exist. If count is odd, then the equal point is the middle point of the auxiliary array.Below is implementation of above idea. "
},
{
"code": null,
"e": 27285,
"s": 27281,
"text": "C++"
},
{
"code": null,
"e": 27290,
"s": 27285,
"text": "Java"
},
{
"code": null,
"e": 27299,
"s": 27290,
"text": "Python 3"
},
{
"code": null,
"e": 27302,
"s": 27299,
"text": "C#"
},
{
"code": null,
"e": 27306,
"s": 27302,
"text": "PHP"
},
{
"code": null,
"e": 27317,
"s": 27306,
"text": "Javascript"
},
{
"code": "// C++ program to find Equal point in a sorted array// which may have many duplicates.#include <bits/stdc++.h>using namespace std; // Returns value of Equal point in a sorted array arr[]// It returns -1 if there is no Equal Point.int findEqualPoint(int arr[], int n){ // To store first indexes of distinct elements of arr[] int distArr[n]; // Traverse input array and store indexes of first // occurrences of distinct elements in distArr[] int i = 0, di = 0; while (i < n) { // This element must be first occurrence of a // number (this is made sure by below loop), // so add it to distinct array. distArr[di++] = i++; // Avoid all copies of arr[i] and move to next // distinct element. while (i<n && arr[i] == arr[i-1]) i++; } // di now has total number of distinct elements. // If di is odd, then equal point exists and is at // di/2, otherwise return -1. return (di & 1)? distArr[di>>1] : -1;} // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 4, 5, 6, 6, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); int index = findEqualPoint(arr, n); if (index != -1) cout << \"Equal Point = \" << arr[index] ; else cout << \"Equal Point does not exists\"; return 0;}",
"e": 28614,
"s": 27317,
"text": null
},
{
"code": "//Java program to find Equal point in a sorted array// which may have many duplicates. class Test{ // Returns value of Equal point in a sorted array arr[] // It returns -1 if there is no Equal Point. static int findEqualPoint(int arr[], int n) { // To store first indexes of distinct elements of arr[] int distArr[] = new int[n]; // Traverse input array and store indexes of first // occurrences of distinct elements in distArr[] int i = 0, di = 0; while (i < n) { // This element must be first occurrence of a // number (this is made sure by below loop), // so add it to distinct array. distArr[di++] = i++; // Avoid all copies of arr[i] and move to next // distinct element. while (i<n && arr[i] == arr[i-1]) i++; } // di now has total number of distinct elements. // If di is odd, then equal point exists and is at // di/2, otherwise return -1. return (di & 1)!=0 ? distArr[di>>1] : -1; } // Driver method public static void main(String args[]) { int arr[] = {1, 2, 3, 4, 4, 5, 6, 6, 6, 7}; int index = findEqualPoint(arr, arr.length); System.out.println(index != -1 ? \"Equal Point = \" + arr[index] : \"Equal Point does not exists\"); }}",
"e": 30045,
"s": 28614,
"text": null
},
{
"code": "# Python 3 program to find# Equal point in a sorted# array which may have# many duplicates. # Returns value of Equal# point in a sorted array# arr[]. It returns -1 if# there is no Equal Point.def findEqualPoint(arr, n): # To store first indexes of # distinct elements of arr[] distArr = [0] * n # Traverse input array and # store indexes of first # occurrences of distinct # elements in distArr[] i = 0 di = 0 while (i < n): # This element must be # first occurrence of a # number (this is made # sure by below loop), # so add it to distinct array. distArr[di] = i di += 1 i += 1 # Avoid all copies of # arr[i] and move to # next distinct element. while (i < n and arr[i] == arr[i - 1]): i += 1 # di now has total number # of distinct elements. # If di is odd, then equal # point exists and is at # di/2, otherwise return -1. return distArr[di >> 1] if (di & 1) else -1 # Driver codearr = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7]n = len(arr)index = findEqualPoint(arr, n)if (index != -1): print(\"Equal Point = \" , arr[index])else: print(\"Equal Point does \" + \"not exists\") # This code is contributed# by Smitha",
"e": 31361,
"s": 30045,
"text": null
},
{
"code": "// C# program to find Equal// point in a sorted array// which may have many duplicates.using System; class GFG{ // Returns value of Equal point // in a sorted array arr[] // It returns -1 if there // is no Equal Point. static int findEqualPoint(int []arr, int n) { // To store first indexes of // distinct elements of arr[] int []distArr = new int[n]; // Traverse input array and // store indexes of first // occurrences of distinct // elements in distArr[] int i = 0, di = 0; while (i < n) { // This element must be // first occurrence of a // number (this is made // sure by below loop), // so add it to distinct array. distArr[di++] = i++; // Avoid all copies of // arr[i] and move to // next distinct element. while (i < n && arr[i] == arr[i - 1]) i++; } // di now has total number // of distinct elements. // If di is odd, then equal // point exists and is at // di/2, otherwise return -1. return (di & 1) != 0 ? distArr[di >> 1] : -1; } // Driver Code public static void Main() { int []arr = {1, 2, 3, 4, 4, 5, 6, 6, 6, 7}; int index = findEqualPoint(arr, arr.Length); Console.Write(index != -1 ? \"Equal Point = \" + arr[index] : \"Equal Point does not exists\"); }}",
"e": 32982,
"s": 31361,
"text": null
},
{
"code": "<?php// PHP program to find Equal point in a// sorted array which may have many// duplicates. // Returns value of Equal point in a// sorted array arr[] It returns -1// if there is no Equal Point.function findEqualPoint( $arr, $n){ // To store first indexes of distinct // elements of arr[] $distArr = array(); // Traverse input array and store // indexes of first occurrences of // distinct elements in distArr[] $i = 0; $di = 0; while ($i < $n) { // This element must be first // occurrence of a number (this // is made sure by below loop), // so add it to distinct array. $distArr[$di++] = $i++; // Avoid all copies of arr[i] // and move to next distinct // element. while ($i < $n and $arr[$i] == $arr[$i-1]) $i++; } // di now has total number of // distinct elements. If di is odd, // then equal point exists and is // at di/2, otherwise return -1. return ($di & 1)? $distArr[$di>>1] : -1;} // Driver code$arr = array(1, 2, 3, 4, 4, 5, 6, 6, 6, 7);$n = count($arr);$index = findEqualPoint($arr, $n);if ($index != -1) echo \"Equal Point = \" , $arr[$index] ;else echo \"Equal Point does not exists\"; // This code is contributed by anuj_67.?>",
"e": 34273,
"s": 32982,
"text": null
},
{
"code": "<script> // JavaScript program to find Equal // point in a sorted array // which may have many duplicates. // Returns value of Equal point // in a sorted array arr[] // It returns -1 if there // is no Equal Point. function findEqualPoint(arr, n) { // To store first indexes of // distinct elements of arr[] let distArr = new Array(n); distArr.fill(0); // Traverse input array and // store indexes of first // occurrences of distinct // elements in distArr[] let i = 0, di = 0; while (i < n) { // This element must be // first occurrence of a // number (this is made // sure by below loop), // so add it to distinct array. distArr[di++] = i++; // Avoid all copies of // arr[i] and move to // next distinct element. while (i < n && arr[i] == arr[i - 1]) i++; } // di now has total number // of distinct elements. // If di is odd, then equal // point exists and is at // di/2, otherwise return -1. return (di & 1) != 0 ? distArr[di >> 1] : -1; } let arr = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7]; let index = findEqualPoint(arr, arr.length); document.write(index != -1 ? \"Equal Point = \" + arr[index] : \"Equal Point does not exists\"); </script>",
"e": 35814,
"s": 34273,
"text": null
},
{
"code": null,
"e": 35824,
"s": 35814,
"text": "Output: "
},
{
"code": null,
"e": 35840,
"s": 35824,
"text": "Equal Point = 4"
},
{
"code": null,
"e": 35981,
"s": 35840,
"text": "Time Complexity : O(n) Auxiliary Space : O(n)Space Optimization : We can reduce extra space by traversing the array twice instead of once. "
},
{
"code": null,
"e": 36201,
"s": 35981,
"text": "Count total distinct elements by doing a traversal of input array. Let this count be distCount.If distCount is even, return -1.If distCount is odd, traverse the array again and stop at distCount/2 and return this index."
},
{
"code": null,
"e": 36297,
"s": 36201,
"text": "Count total distinct elements by doing a traversal of input array. Let this count be distCount."
},
{
"code": null,
"e": 36330,
"s": 36297,
"text": "If distCount is even, return -1."
},
{
"code": null,
"e": 36423,
"s": 36330,
"text": "If distCount is odd, traverse the array again and stop at distCount/2 and return this index."
},
{
"code": null,
"e": 36916,
"s": 36423,
"text": "Thanks to Pavan Kumar J S for suggesting this space-optimized approach.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": 36929,
"s": 36916,
"text": "nitin mittal"
},
{
"code": null,
"e": 36934,
"s": 36929,
"text": "vt_m"
},
{
"code": null,
"e": 36955,
"s": 36934,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 36969,
"s": 36955,
"text": "shubham_singh"
},
{
"code": null,
"e": 36985,
"s": 36969,
"text": "Mukul Mahaliyan"
},
{
"code": null,
"e": 36996,
"s": 36985,
"text": "decode2207"
},
{
"code": null,
"e": 37003,
"s": 36996,
"text": "Arrays"
},
{
"code": null,
"e": 37010,
"s": 37003,
"text": "Arrays"
},
{
"code": null,
"e": 37108,
"s": 37010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37176,
"s": 37108,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 37220,
"s": 37176,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 37268,
"s": 37220,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 37291,
"s": 37268,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 37323,
"s": 37291,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 37337,
"s": 37323,
"text": "Linear Search"
},
{
"code": null,
"e": 37358,
"s": 37337,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 37443,
"s": 37358,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 37488,
"s": 37443,
"text": "Python | Using 2D arrays/lists the right way"
}
] |
Stack size() method in Java with Example - GeeksforGeeks
|
24 Dec, 2018
The Java.util.Stack.size() method in Java is used to get the size of the Stack or the number of elements present in the Stack.
Syntax:
Stack.size()
Parameters: The method does not take any parameter.
Return Value: The method returns the size or the number of elements present in the Stack.
Below programs illustrate the Java.util.Stack.size() method:
Program 1: Stack with string elements.
// Java code to illustrate size()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add("Welcome"); stack.add("To"); stack.add("Geeks"); stack.add("4"); stack.add("Geeks"); // Displaying the Stack System.out.println("Stack: " + stack); // Displaying the size of Stack System.out.println("The size is: " + stack.size()); }}
Stack: [Welcome, To, Geeks, 4, Geeks]
The size is: 5
Program 2: Stack with integer elements.
// Java code to illustrate size()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements into the Stack stack.add(10); stack.add(15); stack.add(30); stack.add(20); stack.add(5); // Displaying the Stack System.out.println("Stack: " + stack); // Displaying the size of Stack System.out.println("The size is: " + stack.size()); }}
Stack: [10, 15, 30, 20, 5]
The size is: 5
Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Reverse a string in Java
Arrays.sort() in Java with examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 25821,
"s": 25793,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 25948,
"s": 25821,
"text": "The Java.util.Stack.size() method in Java is used to get the size of the Stack or the number of elements present in the Stack."
},
{
"code": null,
"e": 25956,
"s": 25948,
"text": "Syntax:"
},
{
"code": null,
"e": 25969,
"s": 25956,
"text": "Stack.size()"
},
{
"code": null,
"e": 26021,
"s": 25969,
"text": "Parameters: The method does not take any parameter."
},
{
"code": null,
"e": 26111,
"s": 26021,
"text": "Return Value: The method returns the size or the number of elements present in the Stack."
},
{
"code": null,
"e": 26172,
"s": 26111,
"text": "Below programs illustrate the Java.util.Stack.size() method:"
},
{
"code": null,
"e": 26211,
"s": 26172,
"text": "Program 1: Stack with string elements."
},
{
"code": "// Java code to illustrate size()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add(\"Welcome\"); stack.add(\"To\"); stack.add(\"Geeks\"); stack.add(\"4\"); stack.add(\"Geeks\"); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Displaying the size of Stack System.out.println(\"The size is: \" + stack.size()); }}",
"e": 26796,
"s": 26211,
"text": null
},
{
"code": null,
"e": 26850,
"s": 26796,
"text": "Stack: [Welcome, To, Geeks, 4, Geeks]\nThe size is: 5\n"
},
{
"code": null,
"e": 26890,
"s": 26850,
"text": "Program 2: Stack with integer elements."
},
{
"code": "// Java code to illustrate size()import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements into the Stack stack.add(10); stack.add(15); stack.add(30); stack.add(20); stack.add(5); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Displaying the size of Stack System.out.println(\"The size is: \" + stack.size()); }}",
"e": 27456,
"s": 26890,
"text": null
},
{
"code": null,
"e": 27499,
"s": 27456,
"text": "Stack: [10, 15, 30, 20, 5]\nThe size is: 5\n"
},
{
"code": null,
"e": 27519,
"s": 27499,
"text": "Java - util package"
},
{
"code": null,
"e": 27536,
"s": 27519,
"text": "Java-Collections"
},
{
"code": null,
"e": 27551,
"s": 27536,
"text": "Java-Functions"
},
{
"code": null,
"e": 27562,
"s": 27551,
"text": "Java-Stack"
},
{
"code": null,
"e": 27567,
"s": 27562,
"text": "Java"
},
{
"code": null,
"e": 27572,
"s": 27567,
"text": "Java"
},
{
"code": null,
"e": 27589,
"s": 27572,
"text": "Java-Collections"
},
{
"code": null,
"e": 27687,
"s": 27589,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27702,
"s": 27687,
"text": "Arrays in Java"
},
{
"code": null,
"e": 27746,
"s": 27702,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 27768,
"s": 27746,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 27819,
"s": 27768,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27849,
"s": 27819,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27874,
"s": 27849,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27910,
"s": 27874,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 27925,
"s": 27910,
"text": "Stream In Java"
},
{
"code": null,
"e": 27944,
"s": 27925,
"text": "Interfaces in Java"
}
] |
C++ Program For Printing Nth Node From The End Of A Linked List - GeeksforGeeks
|
08 Dec, 2021
Given a Linked List and a number n, write a function that returns the value at the n’th node from the end of the Linked List.For example, if the input is below list and n = 3, then output is “B”
Method 1 (Use length of linked list):
Calculate the length of Linked List. Let the length be len.Print the (len – n + 1)th node from the beginning of the Linked List.
Calculate the length of Linked List. Let the length be len.
Print the (len – n + 1)th node from the beginning of the Linked List.
Double pointer concept : First pointer is used to store the address of the variable and second pointer used to store the address of the first pointer. If we wish to change the value of a variable by a function, we pass pointer to it. And if we wish to change value of a pointer (i. e., it should start pointing to something else), we pass pointer to a pointer.
Below is the implementation of the above approach:
C++14
// C++ program to find n'th node from // end#include <bits/stdc++.h>using namespace std; // Link list node struct Node { int data; struct Node* next;}; /* Function to get the nth node from the last of a linked list*/void printNthFromLast(struct Node* head, int n){ int len = 0, i; struct Node* temp = head; // count the number of nodes in // Linked List while (temp != NULL) { temp = temp->next; len++; } // check if value of n is not // more than length of the // linked list if (len < n) return; temp = head; // get the (len-n+1)th node from // the beginning for (i = 1; i < len - n + 1; i++) temp = temp->next; cout << temp->data; return;} void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = new Node(); // Put in the data new_node->data = new_data; // Link the old list off the // new node new_node->next = (*head_ref); // Move the head to point to // the new node (*head_ref) = new_node;} // Driver Codeint main(){ // Start with the empty list struct Node* head = NULL; // Create linked 35->15->4->20 push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 35); printNthFromLast(head, 4); return 0;}
Output:
35
C++
void printNthFromLast(struct Node* head, int n){ int i = 0; if (head == NULL) return; printNthFromLast(head->next, n); if (++i == n) cout<<head->data;}
Time Complexity: O(n) where n is the length of linked list. Method 2 (Use two pointers) Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First, move the reference pointer to n nodes from head. Now move both pointers one by one until the reference pointer reaches the end. Now the main pointer will point to nth node from the end. Return the main pointer.Below image is a dry run of the above approach:
Below is the implementation of the above approach:
C++
// Simple C++ program to // find n'th node from end#include<bits/stdc++.h>using namespace std; /* Link list node */struct Node{ int data; struct Node* next;}; /* Function to get the nth node from the last of a linked list*/void printNthFromLast(struct Node *head, int n){ struct Node *main_ptr = head; struct Node *ref_ptr = head; int count = 0; if(head != NULL) { while( count < n ) { if(ref_ptr == NULL) { printf("%d is greater than the no. of " "nodes in list", n); return; } ref_ptr = ref_ptr->next; count++; } /* End of while*/ if(ref_ptr == NULL) { head = head->next; if(head != NULL) printf("Node no. %d from last is %d ", n, main_ptr->data); } else { while(ref_ptr != NULL) { main_ptr = main_ptr->next; ref_ptr = ref_ptr->next; } printf("Node no. %d from last is %d ", n, main_ptr->data); } }} // Function to pushvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 35); printNthFromLast(head, 4);}
Node no. 4 from last is 35
Time Complexity: O(n) where n is the length of linked list.Please refer complete article on Program for n’th node from the end of a Linked List for more details!
Accolite
Adobe
Amazon
Citicorp
Epic Systems
FactSet
Hike
Linked Lists
MAQ Software
Monotype Solutions
Qualcomm
Snapdeal
C++
C++ Programs
Linked List
Accolite
Amazon
Snapdeal
FactSet
Hike
MAQ Software
Adobe
Qualcomm
Epic Systems
Citicorp
Monotype Solutions
Linked List
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Iterators in C++ STL
Operator Overloading in C++
Friend class and function in C++
Polymorphism in C++
Inline Functions in C++
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
C++ program for hashing with chaining
cin in C++
|
[
{
"code": null,
"e": 23785,
"s": 23757,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 23980,
"s": 23785,
"text": "Given a Linked List and a number n, write a function that returns the value at the n’th node from the end of the Linked List.For example, if the input is below list and n = 3, then output is “B”"
},
{
"code": null,
"e": 24019,
"s": 23980,
"text": "Method 1 (Use length of linked list): "
},
{
"code": null,
"e": 24149,
"s": 24019,
"text": "Calculate the length of Linked List. Let the length be len.Print the (len – n + 1)th node from the beginning of the Linked List. "
},
{
"code": null,
"e": 24209,
"s": 24149,
"text": "Calculate the length of Linked List. Let the length be len."
},
{
"code": null,
"e": 24280,
"s": 24209,
"text": "Print the (len – n + 1)th node from the beginning of the Linked List. "
},
{
"code": null,
"e": 24641,
"s": 24280,
"text": "Double pointer concept : First pointer is used to store the address of the variable and second pointer used to store the address of the first pointer. If we wish to change the value of a variable by a function, we pass pointer to it. And if we wish to change value of a pointer (i. e., it should start pointing to something else), we pass pointer to a pointer."
},
{
"code": null,
"e": 24692,
"s": 24641,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 24698,
"s": 24692,
"text": "C++14"
},
{
"code": "// C++ program to find n'th node from // end#include <bits/stdc++.h>using namespace std; // Link list node struct Node { int data; struct Node* next;}; /* Function to get the nth node from the last of a linked list*/void printNthFromLast(struct Node* head, int n){ int len = 0, i; struct Node* temp = head; // count the number of nodes in // Linked List while (temp != NULL) { temp = temp->next; len++; } // check if value of n is not // more than length of the // linked list if (len < n) return; temp = head; // get the (len-n+1)th node from // the beginning for (i = 1; i < len - n + 1; i++) temp = temp->next; cout << temp->data; return;} void push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = new Node(); // Put in the data new_node->data = new_data; // Link the old list off the // new node new_node->next = (*head_ref); // Move the head to point to // the new node (*head_ref) = new_node;} // Driver Codeint main(){ // Start with the empty list struct Node* head = NULL; // Create linked 35->15->4->20 push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 35); printNthFromLast(head, 4); return 0;}",
"e": 26060,
"s": 24698,
"text": null
},
{
"code": null,
"e": 26068,
"s": 26060,
"text": "Output:"
},
{
"code": null,
"e": 26071,
"s": 26068,
"text": "35"
},
{
"code": null,
"e": 26075,
"s": 26071,
"text": "C++"
},
{
"code": "void printNthFromLast(struct Node* head, int n){ int i = 0; if (head == NULL) return; printNthFromLast(head->next, n); if (++i == n) cout<<head->data;}",
"e": 26253,
"s": 26075,
"text": null
},
{
"code": null,
"e": 26720,
"s": 26253,
"text": "Time Complexity: O(n) where n is the length of linked list. Method 2 (Use two pointers) Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First, move the reference pointer to n nodes from head. Now move both pointers one by one until the reference pointer reaches the end. Now the main pointer will point to nth node from the end. Return the main pointer.Below image is a dry run of the above approach: "
},
{
"code": null,
"e": 26773,
"s": 26720,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26777,
"s": 26773,
"text": "C++"
},
{
"code": "// Simple C++ program to // find n'th node from end#include<bits/stdc++.h>using namespace std; /* Link list node */struct Node{ int data; struct Node* next;}; /* Function to get the nth node from the last of a linked list*/void printNthFromLast(struct Node *head, int n){ struct Node *main_ptr = head; struct Node *ref_ptr = head; int count = 0; if(head != NULL) { while( count < n ) { if(ref_ptr == NULL) { printf(\"%d is greater than the no. of \" \"nodes in list\", n); return; } ref_ptr = ref_ptr->next; count++; } /* End of while*/ if(ref_ptr == NULL) { head = head->next; if(head != NULL) printf(\"Node no. %d from last is %d \", n, main_ptr->data); } else { while(ref_ptr != NULL) { main_ptr = main_ptr->next; ref_ptr = ref_ptr->next; } printf(\"Node no. %d from last is %d \", n, main_ptr->data); } }} // Function to pushvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 35); printNthFromLast(head, 4);}",
"e": 28334,
"s": 26777,
"text": null
},
{
"code": null,
"e": 28362,
"s": 28334,
"text": "Node no. 4 from last is 35 "
},
{
"code": null,
"e": 28524,
"s": 28362,
"text": "Time Complexity: O(n) where n is the length of linked list.Please refer complete article on Program for n’th node from the end of a Linked List for more details!"
},
{
"code": null,
"e": 28533,
"s": 28524,
"text": "Accolite"
},
{
"code": null,
"e": 28539,
"s": 28533,
"text": "Adobe"
},
{
"code": null,
"e": 28546,
"s": 28539,
"text": "Amazon"
},
{
"code": null,
"e": 28555,
"s": 28546,
"text": "Citicorp"
},
{
"code": null,
"e": 28568,
"s": 28555,
"text": "Epic Systems"
},
{
"code": null,
"e": 28576,
"s": 28568,
"text": "FactSet"
},
{
"code": null,
"e": 28581,
"s": 28576,
"text": "Hike"
},
{
"code": null,
"e": 28594,
"s": 28581,
"text": "Linked Lists"
},
{
"code": null,
"e": 28607,
"s": 28594,
"text": "MAQ Software"
},
{
"code": null,
"e": 28626,
"s": 28607,
"text": "Monotype Solutions"
},
{
"code": null,
"e": 28635,
"s": 28626,
"text": "Qualcomm"
},
{
"code": null,
"e": 28644,
"s": 28635,
"text": "Snapdeal"
},
{
"code": null,
"e": 28648,
"s": 28644,
"text": "C++"
},
{
"code": null,
"e": 28661,
"s": 28648,
"text": "C++ Programs"
},
{
"code": null,
"e": 28673,
"s": 28661,
"text": "Linked List"
},
{
"code": null,
"e": 28682,
"s": 28673,
"text": "Accolite"
},
{
"code": null,
"e": 28689,
"s": 28682,
"text": "Amazon"
},
{
"code": null,
"e": 28698,
"s": 28689,
"text": "Snapdeal"
},
{
"code": null,
"e": 28706,
"s": 28698,
"text": "FactSet"
},
{
"code": null,
"e": 28711,
"s": 28706,
"text": "Hike"
},
{
"code": null,
"e": 28724,
"s": 28711,
"text": "MAQ Software"
},
{
"code": null,
"e": 28730,
"s": 28724,
"text": "Adobe"
},
{
"code": null,
"e": 28739,
"s": 28730,
"text": "Qualcomm"
},
{
"code": null,
"e": 28752,
"s": 28739,
"text": "Epic Systems"
},
{
"code": null,
"e": 28761,
"s": 28752,
"text": "Citicorp"
},
{
"code": null,
"e": 28780,
"s": 28761,
"text": "Monotype Solutions"
},
{
"code": null,
"e": 28792,
"s": 28780,
"text": "Linked List"
},
{
"code": null,
"e": 28796,
"s": 28792,
"text": "CPP"
},
{
"code": null,
"e": 28894,
"s": 28796,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28903,
"s": 28894,
"text": "Comments"
},
{
"code": null,
"e": 28916,
"s": 28903,
"text": "Old Comments"
},
{
"code": null,
"e": 28937,
"s": 28916,
"text": "Iterators in C++ STL"
},
{
"code": null,
"e": 28965,
"s": 28937,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28998,
"s": 28965,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 29018,
"s": 28998,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 29042,
"s": 29018,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 29077,
"s": 29042,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 29136,
"s": 29077,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 29162,
"s": 29136,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 29200,
"s": 29162,
"text": "C++ program for hashing with chaining"
}
] |
C++ program to implement Half Adder - GeeksforGeeks
|
26 Aug, 2021
Prerequisite : Half Adder in Digital Logic
We are given with two inputs A and B. Our task is to implement Half Adder circuit and print the outputs sum and carry of two inputs.
Introduction :
The Half adder is a combinational circuit which add two1-bit binary numbers which are augend and addend to give the output value along with the carry. The half adder has two input states and two output states. The two outputs are Sum and Carry.
Here we have two inputs A, B and two outputs sum, carry. And the truth table for Half Adder is
Logical Expression :
Sum = A XOR B
Carry = A AND B
Examples :
Input : A=0, B= 0
Output: Sum=0, Carry=0
Explanation: Here from logical expression Sum = A XOR B i.e 0 XOR 0 = 0, and Carry=A AND B i.e 0 AND 0 = 0.
Input : A=1, B= 0
Output: Sum=1, Carry=0
Explanation: Here from logical expression Sum=A XOR B i.e 1 XOR 0 =1 , Carry=A AND B i.e 1 AND 0 = 0.
Approach :
Initialize the variables Sum and Carry for storing outputs.
First we will take two inputs A and B.
By applying A XOR B we get the value of Sum.
By applying A AND B we get the value of Carry.
C++
// C++ program for above approach#include <bits/stdc++.h>using namespace std;// Function to print Sum and Carryvoid Half_Adder(int A,int B){ //initialize the variables Sum and Carry int Sum , Carry; // Calculating value of sum by applying A XOR B Sum = A ^ B; // Calculating value of Carry by applying A AND B Carry = A & B; // printing the values cout<<"Sum = "<< Sum << endl; cout<<"Carry = "<<Carry<< endl;}//Driver codeint main() { int A = 1; int B = 0; // calling the function Half_Adder(A,B); return 0;}
Sum = 1
Carry = 0
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to memory and memory units
Ring Counter in Digital Logic
n-bit Johnson Counter in Digital Logic
Transmission Impairment in Data Communication
Half Subtractor in Digital Logic
Analog to Digital Conversion
Differences between Synchronous and Asynchronous Counter
Ripple Counter in Digital Logic
Properties of Boolean Algebra
Floating Point Representation - Basics
|
[
{
"code": null,
"e": 24382,
"s": 24354,
"text": "\n26 Aug, 2021"
},
{
"code": null,
"e": 24425,
"s": 24382,
"text": "Prerequisite : Half Adder in Digital Logic"
},
{
"code": null,
"e": 24558,
"s": 24425,
"text": "We are given with two inputs A and B. Our task is to implement Half Adder circuit and print the outputs sum and carry of two inputs."
},
{
"code": null,
"e": 24575,
"s": 24558,
"text": "Introduction : "
},
{
"code": null,
"e": 24821,
"s": 24575,
"text": "The Half adder is a combinational circuit which add two1-bit binary numbers which are augend and addend to give the output value along with the carry. The half adder has two input states and two output states. The two outputs are Sum and Carry."
},
{
"code": null,
"e": 24917,
"s": 24821,
"text": "Here we have two inputs A, B and two outputs sum, carry. And the truth table for Half Adder is "
},
{
"code": null,
"e": 24939,
"s": 24917,
"text": "Logical Expression : "
},
{
"code": null,
"e": 24955,
"s": 24939,
"text": "Sum = A XOR B "
},
{
"code": null,
"e": 24972,
"s": 24955,
"text": "Carry = A AND B "
},
{
"code": null,
"e": 24983,
"s": 24972,
"text": "Examples :"
},
{
"code": null,
"e": 25008,
"s": 24983,
"text": " Input : A=0, B= 0"
},
{
"code": null,
"e": 25038,
"s": 25008,
"text": " Output: Sum=0, Carry=0"
},
{
"code": null,
"e": 25156,
"s": 25038,
"text": " Explanation: Here from logical expression Sum = A XOR B i.e 0 XOR 0 = 0, and Carry=A AND B i.e 0 AND 0 = 0."
},
{
"code": null,
"e": 25181,
"s": 25156,
"text": " Input : A=1, B= 0"
},
{
"code": null,
"e": 25211,
"s": 25181,
"text": " Output: Sum=1, Carry=0"
},
{
"code": null,
"e": 25326,
"s": 25211,
"text": " Explanation: Here from logical expression Sum=A XOR B i.e 1 XOR 0 =1 , Carry=A AND B i.e 1 AND 0 = 0."
},
{
"code": null,
"e": 25337,
"s": 25326,
"text": "Approach :"
},
{
"code": null,
"e": 25397,
"s": 25337,
"text": "Initialize the variables Sum and Carry for storing outputs."
},
{
"code": null,
"e": 25436,
"s": 25397,
"text": "First we will take two inputs A and B."
},
{
"code": null,
"e": 25482,
"s": 25436,
"text": "By applying A XOR B we get the value of Sum."
},
{
"code": null,
"e": 25530,
"s": 25482,
"text": "By applying A AND B we get the value of Carry."
},
{
"code": null,
"e": 25534,
"s": 25530,
"text": "C++"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std;// Function to print Sum and Carryvoid Half_Adder(int A,int B){ //initialize the variables Sum and Carry int Sum , Carry; // Calculating value of sum by applying A XOR B Sum = A ^ B; // Calculating value of Carry by applying A AND B Carry = A & B; // printing the values cout<<\"Sum = \"<< Sum << endl; cout<<\"Carry = \"<<Carry<< endl;}//Driver codeint main() { int A = 1; int B = 0; // calling the function Half_Adder(A,B); return 0;}",
"e": 26098,
"s": 25534,
"text": null
},
{
"code": null,
"e": 26116,
"s": 26098,
"text": "Sum = 1\nCarry = 0"
},
{
"code": null,
"e": 26151,
"s": 26116,
"text": "Digital Electronics & Logic Design"
},
{
"code": null,
"e": 26249,
"s": 26151,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26258,
"s": 26249,
"text": "Comments"
},
{
"code": null,
"e": 26271,
"s": 26258,
"text": "Old Comments"
},
{
"code": null,
"e": 26311,
"s": 26271,
"text": "Introduction to memory and memory units"
},
{
"code": null,
"e": 26341,
"s": 26311,
"text": "Ring Counter in Digital Logic"
},
{
"code": null,
"e": 26380,
"s": 26341,
"text": "n-bit Johnson Counter in Digital Logic"
},
{
"code": null,
"e": 26426,
"s": 26380,
"text": "Transmission Impairment in Data Communication"
},
{
"code": null,
"e": 26459,
"s": 26426,
"text": "Half Subtractor in Digital Logic"
},
{
"code": null,
"e": 26488,
"s": 26459,
"text": "Analog to Digital Conversion"
},
{
"code": null,
"e": 26545,
"s": 26488,
"text": "Differences between Synchronous and Asynchronous Counter"
},
{
"code": null,
"e": 26577,
"s": 26545,
"text": "Ripple Counter in Digital Logic"
},
{
"code": null,
"e": 26607,
"s": 26577,
"text": "Properties of Boolean Algebra"
}
] |
Create PySpark dataframe from dictionary - GeeksforGeeks
|
30 May, 2021
In this article, we are going to discuss the creation of Pyspark dataframe from the dictionary. To do this spark.createDataFrame() method method is used. This method takes two argument data and columns. The data attribute will contain the dataframe and the columns attribute will contain the list of columns name.
Example 1: Python code to create the student address details and convert them to dataframe
Python3
# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of college data with dictionarydata = [{'student_id': 12, 'name': 'sravan', 'address': 'kakumanu'}] # creating a dataframedataframe = spark.createDataFrame(data) # show data framedataframe.show()
Output:
Example2: Create three dictionaries and pass them to the data frame in pyspark
Python3
# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of college data with dictionary # with three dictionariesdata = [{'student_id': 12, 'name': 'sravan', 'address': 'kakumanu'}, {'student_id': 14, 'name': 'jyothika', 'address': 'tenali'}, {'student_id': 11, 'name': 'deepika', 'address': 'repalle'}] # creating a dataframedataframe = spark.createDataFrame(data) # show data framedataframe.show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 24526,
"s": 24212,
"text": "In this article, we are going to discuss the creation of Pyspark dataframe from the dictionary. To do this spark.createDataFrame() method method is used. This method takes two argument data and columns. The data attribute will contain the dataframe and the columns attribute will contain the list of columns name."
},
{
"code": null,
"e": 24617,
"s": 24526,
"text": "Example 1: Python code to create the student address details and convert them to dataframe"
},
{
"code": null,
"e": 24625,
"s": 24617,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of college data with dictionarydata = [{'student_id': 12, 'name': 'sravan', 'address': 'kakumanu'}] # creating a dataframedataframe = spark.createDataFrame(data) # show data framedataframe.show()",
"e": 25073,
"s": 24625,
"text": null
},
{
"code": null,
"e": 25081,
"s": 25073,
"text": "Output:"
},
{
"code": null,
"e": 25160,
"s": 25081,
"text": "Example2: Create three dictionaries and pass them to the data frame in pyspark"
},
{
"code": null,
"e": 25168,
"s": 25160,
"text": "Python3"
},
{
"code": "# importing moduleimport pyspark # importing sparksession from # pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving # an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of college data with dictionary # with three dictionariesdata = [{'student_id': 12, 'name': 'sravan', 'address': 'kakumanu'}, {'student_id': 14, 'name': 'jyothika', 'address': 'tenali'}, {'student_id': 11, 'name': 'deepika', 'address': 'repalle'}] # creating a dataframedataframe = spark.createDataFrame(data) # show data framedataframe.show()",
"e": 25771,
"s": 25168,
"text": null
},
{
"code": null,
"e": 25779,
"s": 25771,
"text": "Output:"
},
{
"code": null,
"e": 25786,
"s": 25779,
"text": "Picked"
},
{
"code": null,
"e": 25801,
"s": 25786,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 25808,
"s": 25801,
"text": "Python"
},
{
"code": null,
"e": 25906,
"s": 25808,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25915,
"s": 25906,
"text": "Comments"
},
{
"code": null,
"e": 25928,
"s": 25915,
"text": "Old Comments"
},
{
"code": null,
"e": 25960,
"s": 25928,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26016,
"s": 25960,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26037,
"s": 26016,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26076,
"s": 26037,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26118,
"s": 26076,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26145,
"s": 26118,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26176,
"s": 26145,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26218,
"s": 26176,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26254,
"s": 26218,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Spring JDBC - StoredProcedure Class
|
The org.springframework.jdbc.core.StoredProcedure class is the superclass for object abstractions of RDBMS stored procedures. This class is abstract and it is intended that subclasses will provide a typed method for invocation that delegates to the supplied execute(java.lang.Object...) method. The inherited SQL property is the name of the stored procedure in the RDBMS.
Following is the declaration for org.springframework.jdbc.core.StoredProcedure class −
public abstract class StoredProcedure
extends SqlCall
Following example will demonstrate how to call a stored procedure using Spring StoredProcedure. We'll read one of the available records in Student Table by calling a stored procedure. We'll pass an id and receive a student record.
class StudentProcedure extends StoredProcedure{
public StudentProcedure(DataSource dataSource, String procedureName){
super(dataSource,procedureName);
declareParameter(new SqlParameter("in_id", Types.INTEGER));
declareParameter(new SqlOutParameter("out_name", Types.VARCHAR));
declareParameter(new SqlOutParameter("out_age", Types.INTEGER));
compile();
}
public Student execute(Integer id){
Map<String, Object> out = super.execute(id);
Student student = new Student();
student.setId(id);
student.setName((String) out.get("out_name"));
student.setAge((Integer) out.get("out_age"));
return student;
}
}
Where,
StoredProcedure − StoredProcedure object to represent a stored procedure.
StoredProcedure − StoredProcedure object to represent a stored procedure.
StudentProcedure − StudentProcedure object extends StoredProcedure to declare input, output variable, and map result to Student object.
StudentProcedure − StudentProcedure object extends StoredProcedure to declare input, output variable, and map result to Student object.
student − Student object.
student − Student object.
To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will call a stored procedure. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
Following is the content of the Data Access Object interface file StudentDAO.java.
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
public interface StudentDAO {
/**
* This is the method to be used to initialize
* database resources ie. connection.
*/
public void setDataSource(DataSource ds);
/**
* This is the method to be used to list down
* a record from the Student table corresponding
* to a passed student id.
*/
public Student getStudent(Integer id);
}
Following is the content of the Student.java file.
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
Following is the content of the StudentMapper.java file.
package com.tutorialspoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class StudentMapper implements RowMapper<Student> {
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
return student;
}
}
Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO.
package com.tutorialspoint;
import java.sql.Types;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.object.StoredProcedure;
public class StudentJDBCTemplate implements StudentDao {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public Student getStudent(Integer id) {
StudentProcedure studentProcedure = new StudentProcedure(dataSource, "getRecord");
return studentProcedure.execute(id);
}
}
class StudentProcedure extends StoredProcedure {
public StudentProcedure(DataSource dataSource, String procedureName) {
super(dataSource,procedureName);
declareParameter(new SqlParameter("in_id", Types.INTEGER));
declareParameter(new SqlOutParameter("out_name", Types.VARCHAR));
declareParameter(new SqlOutParameter("out_age", Types.INTEGER));
compile();
}
public Student execute(Integer id){
Map<String, Object> out = super.execute(id);
Student student = new Student();
student.setId(id);
student.setName((String) out.get("out_name"));
student.setAge((Integer) out.get("out_age"));
return student;
}
}
The code you write for the execution of the call involves creating an SqlParameterSource containing the IN parameter. It's important to match the name provided for the input value with that of the parameter name declared in the stored procedure. The execute method takes the IN parameters and returns a Map containing any out parameters keyed by the name as specified in the stored procedure.
Following is the content of the MainApp.java file.
package com.tutorialspoint;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.StudentJDBCTemplate;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
Student student = studentJDBCTemplate.getStudent(1);
System.out.print("ID : " + student.getId() );
System.out.print(", Name : " + student.getName() );
System.out.println(", Age : " + student.getAge());
}
}
Following is the configuration file Beans.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<!-- Initialization for data source -->
<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.cj.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "admin"/>
</bean>
<!-- Definition for studentJDBCTemplate bean -->
<bean id = "studentJDBCTemplate"
class = "com.tutorialspoint.StudentJDBCTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message.
ID : 1, Name : Zara, Age : 10
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2768,
"s": 2396,
"text": "The org.springframework.jdbc.core.StoredProcedure class is the superclass for object abstractions of RDBMS stored procedures. This class is abstract and it is intended that subclasses will provide a typed method for invocation that delegates to the supplied execute(java.lang.Object...) method. The inherited SQL property is the name of the stored procedure in the RDBMS."
},
{
"code": null,
"e": 2855,
"s": 2768,
"text": "Following is the declaration for org.springframework.jdbc.core.StoredProcedure class −"
},
{
"code": null,
"e": 2913,
"s": 2855,
"text": "public abstract class StoredProcedure\n extends SqlCall\n"
},
{
"code": null,
"e": 3144,
"s": 2913,
"text": "Following example will demonstrate how to call a stored procedure using Spring StoredProcedure. We'll read one of the available records in Student Table by calling a stored procedure. We'll pass an id and receive a student record."
},
{
"code": null,
"e": 3826,
"s": 3144,
"text": "class StudentProcedure extends StoredProcedure{\n public StudentProcedure(DataSource dataSource, String procedureName){\n super(dataSource,procedureName);\n declareParameter(new SqlParameter(\"in_id\", Types.INTEGER));\n declareParameter(new SqlOutParameter(\"out_name\", Types.VARCHAR));\n declareParameter(new SqlOutParameter(\"out_age\", Types.INTEGER));\n compile();\n }\n public Student execute(Integer id){\n Map<String, Object> out = super.execute(id);\n Student student = new Student();\n student.setId(id);\n student.setName((String) out.get(\"out_name\"));\n student.setAge((Integer) out.get(\"out_age\"));\n return student; \t\n }\n}"
},
{
"code": null,
"e": 3833,
"s": 3826,
"text": "Where,"
},
{
"code": null,
"e": 3907,
"s": 3833,
"text": "StoredProcedure − StoredProcedure object to represent a stored procedure."
},
{
"code": null,
"e": 3981,
"s": 3907,
"text": "StoredProcedure − StoredProcedure object to represent a stored procedure."
},
{
"code": null,
"e": 4117,
"s": 3981,
"text": "StudentProcedure − StudentProcedure object extends StoredProcedure to declare input, output variable, and map result to Student object."
},
{
"code": null,
"e": 4253,
"s": 4117,
"text": "StudentProcedure − StudentProcedure object extends StoredProcedure to declare input, output variable, and map result to Student object."
},
{
"code": null,
"e": 4279,
"s": 4253,
"text": "student − Student object."
},
{
"code": null,
"e": 4305,
"s": 4279,
"text": "student − Student object."
},
{
"code": null,
"e": 4557,
"s": 4305,
"text": "To understand the above-mentioned concepts related to Spring JDBC, let us write an example which will call a stored procedure. To write our example, let us have a working Eclipse IDE in place and use the following steps to create a Spring application."
},
{
"code": null,
"e": 4640,
"s": 4557,
"text": "Following is the content of the Data Access Object interface file StudentDAO.java."
},
{
"code": null,
"e": 5107,
"s": 4640,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport javax.sql.DataSource;\n\npublic interface StudentDAO {\n /** \n * This is the method to be used to initialize\n * database resources ie. connection.\n */\n public void setDataSource(DataSource ds);\n \n /** \n * This is the method to be used to list down\n * a record from the Student table corresponding\n * to a passed student id.\n */\n public Student getStudent(Integer id); \n}"
},
{
"code": null,
"e": 5158,
"s": 5107,
"text": "Following is the content of the Student.java file."
},
{
"code": null,
"e": 5630,
"s": 5158,
"text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n private Integer id;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n return age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n return name;\n }\n public void setId(Integer id) {\n this.id = id;\n }\n public Integer getId() {\n return id;\n }\n}"
},
{
"code": null,
"e": 5687,
"s": 5630,
"text": "Following is the content of the StudentMapper.java file."
},
{
"code": null,
"e": 6145,
"s": 5687,
"text": "package com.tutorialspoint;\n\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport org.springframework.jdbc.core.RowMapper;\n\npublic class StudentMapper implements RowMapper<Student> {\n public Student mapRow(ResultSet rs, int rowNum) throws SQLException {\n Student student = new Student();\n student.setId(rs.getInt(\"id\"));\n student.setName(rs.getString(\"name\"));\n student.setAge(rs.getInt(\"age\"));\n return student;\n }\n}"
},
{
"code": null,
"e": 6255,
"s": 6145,
"text": "Following is the implementation class file StudentJDBCTemplate.java for the defined DAO interface StudentDAO."
},
{
"code": null,
"e": 7909,
"s": 6255,
"text": "package com.tutorialspoint;\n\nimport java.sql.Types;\nimport java.util.List;\nimport java.util.Map;\nimport javax.sql.DataSource;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.jdbc.core.SqlOutParameter;\nimport org.springframework.jdbc.core.SqlParameter;\nimport org.springframework.jdbc.core.namedparam.MapSqlParameterSource;\nimport org.springframework.jdbc.core.namedparam.SqlParameterSource;\nimport org.springframework.jdbc.object.StoredProcedure;\n\npublic class StudentJDBCTemplate implements StudentDao {\n private DataSource dataSource;\n private JdbcTemplate jdbcTemplateObject;\n \n public void setDataSource(DataSource dataSource) {\n this.dataSource = dataSource;\n this.jdbcTemplateObject = new JdbcTemplate(dataSource);\n }\n public Student getStudent(Integer id) { \n StudentProcedure studentProcedure = new StudentProcedure(dataSource, \"getRecord\");\n return studentProcedure.execute(id); \n } \n}\nclass StudentProcedure extends StoredProcedure {\n public StudentProcedure(DataSource dataSource, String procedureName) {\n super(dataSource,procedureName);\n declareParameter(new SqlParameter(\"in_id\", Types.INTEGER));\n declareParameter(new SqlOutParameter(\"out_name\", Types.VARCHAR));\n declareParameter(new SqlOutParameter(\"out_age\", Types.INTEGER));\n compile();\n }\n public Student execute(Integer id){\n Map<String, Object> out = super.execute(id);\n Student student = new Student();\n student.setId(id);\n student.setName((String) out.get(\"out_name\"));\n student.setAge((Integer) out.get(\"out_age\"));\n return student; \t\n }\n}"
},
{
"code": null,
"e": 8302,
"s": 7909,
"text": "The code you write for the execution of the call involves creating an SqlParameterSource containing the IN parameter. It's important to match the name provided for the input value with that of the parameter name declared in the stored procedure. The execute method takes the IN parameters and returns a Map containing any out parameters keyed by the name as specified in the stored procedure."
},
{
"code": null,
"e": 8353,
"s": 8302,
"text": "Following is the content of the MainApp.java file."
},
{
"code": null,
"e": 9077,
"s": 8353,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\nimport com.tutorialspoint.StudentJDBCTemplate;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean(\"studentJDBCTemplate\");\n Student student = studentJDBCTemplate.getStudent(1);\n System.out.print(\"ID : \" + student.getId() );\n System.out.print(\", Name : \" + student.getName() );\n System.out.println(\", Age : \" + student.getAge()); \n }\n}"
},
{
"code": null,
"e": 9124,
"s": 9077,
"text": "Following is the configuration file Beans.xml."
},
{
"code": null,
"e": 10077,
"s": 9124,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \">\n\n <!-- Initialization for data source -->\n <bean id = \"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\">\n <property name = \"driverClassName\" value = \"com.mysql.cj.jdbc.Driver\"/>\n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/TEST\"/>\n <property name = \"username\" value = \"root\"/>\n <property name = \"password\" value = \"admin\"/>\n </bean>\n\n <!-- Definition for studentJDBCTemplate bean -->\n <bean id = \"studentJDBCTemplate\" \n class = \"com.tutorialspoint.StudentJDBCTemplate\">\n <property name = \"dataSource\" ref = \"dataSource\" /> \n </bean> \n</beans>"
},
{
"code": null,
"e": 10255,
"s": 10077,
"text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message."
},
{
"code": null,
"e": 10286,
"s": 10255,
"text": "ID : 1, Name : Zara, Age : 10\n"
},
{
"code": null,
"e": 10293,
"s": 10286,
"text": " Print"
},
{
"code": null,
"e": 10304,
"s": 10293,
"text": " Add Notes"
}
] |
GraphQL - Environment Setup
|
In this chapter, we will learn about the environmental setup for GraphQL. To execute the examples in this tutorial you will need the following −
A computer running Linux, macOS, or Windows.
A computer running Linux, macOS, or Windows.
A web browser, preferably the latest version of Google Chrome.
A web browser, preferably the latest version of Google Chrome.
A recent version of Node.js installed. The latest LTS version is recommended.
A recent version of Node.js installed. The latest LTS version is recommended.
Visual Studio Code with extension GraphQL for VSCode installed or any code editor of your choice.
Visual Studio Code with extension GraphQL for VSCode installed or any code editor of your choice.
We will go through a detailed step-wise approach to build GraphQL server with Nodejs as shown below −
After installing NodeJs, verify the version of node and npm using following commands on the terminal −
C:\Users\Admin>node -v
v8.11.3
C:\Users\Admin>npm -v
5.6.0
The root folder of project can be named as test-app.
Open the folder using visual studio code editor by using the instructions below −
C:\Users\Admin>mkdir test-app
C:\Users\Admin>cd test-app
C:\Users\Admin\test-app>code.
Create a package.json file which will contain all the dependencies of the GraphQL server application.
{
"name": "hello-world-server",
"private": true,
"scripts": {
"start": "nodemon --ignore data/ server.js"
},
"dependencies": {
"apollo-server-express": "^1.4.0",
"body-parser": "^1.18.3",
"cors": "^2.8.4",
"express": "^4.16.3",
"graphql": "^0.13.2",
"graphql-tools": "^3.1.1"
},
"devDependencies": {
"nodemon": "1.17.1"
}
}
Install the dependencies by using the command as given below −
C:\Users\Admin\test-app>npm install
In this step, we use flat files to store and retrieve data. Create a folder data and add two files students.json and colleges.json.
Following is the colleges.json file −
[
{
"id": "col-101",
"name": "AMU",
"location": "Uttar Pradesh",
"rating":5.0
},
{
"id": "col-102",
"name": "CUSAT",
"location": "Kerala",
"rating":4.5
}
]
Following is the students.json file −
[
{
"id": "S1001",
"firstName":"Mohtashim",
"lastName":"Mohammad",
"email": "[email protected]",
"password": "pass123",
"collegeId": "col-102"
},
{
"id": "S1002",
"email": "[email protected]",
"firstName":"Kannan",
"lastName":"Sudhakaran",
"password": "pass123",
"collegeId": "col-101"
},
{
"id": "S1003",
"email": "[email protected]",
"firstName":"Kiran",
"lastName":"Panigrahi",
"password": "pass123",
"collegeId": "col-101"
}
]
We need to create a datastore that loads the data folder contents. In this case, we need collection variables, students and colleges. Whenever the application needs data, it makes use of these collection variables.
Create file db.js with in the project folder as follows −
const { DataStore } = require('notarealdb');
const store = new DataStore('./data');
module.exports = {
students:store.collection('students'),
colleges:store.collection('colleges')
};
Create a schema file in the current project folder and add the following contents −
type Query {
test: String
}
Create a resolver file in the current project folder and add the following contents −
const Query = {
test: () => 'Test Success, GraphQL server is up & running !!'
}
module.exports = {Query}
Create a server file and configure GraphQL as follows −
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const db = require('./db');
const port = process.env.PORT || 9000;
const app = express();
const fs = require('fs')
const typeDefs = fs.readFileSync('./schema.graphql',{encoding:'utf-8'})
const resolvers = require('./resolvers')
const {makeExecutableSchema} = require('graphql-tools')
const schema = makeExecutableSchema({typeDefs, resolvers})
app.use(cors(), bodyParser.json());
const {graphiqlExpress,graphqlExpress} = require('apollo-server-express')
app.use('/graphql',graphqlExpress({schema}))
app.use('/graphiql',graphiqlExpress({endpointURL:'/graphql'}))
app.listen(
port, () => console.info(
`Server started on port ${port}`
)
);
Verify the folder structure of project test-app as follows −
test-app /
-->package.json
-->db.js
-->data
students.json
colleges.json
-->resolvers.js
-->schema.graphql
-->server.js
Run the command npm start as given below −
C:\Users\Admin\test-app>npm start
The server is running in 9000 port, so we can test the application using GraphiQL tool. Open the browser and enter the URL http://localhost:9000/graphiql. Type the following query in the editor −
{
Test
}
The response from the server is given below −
{
"data": {
"test": "Test Success, GraphQL server is running !!"
}
}
43 Lectures
3 hours
Nilay Mehta
53 Lectures
3 hours
Asfend Yar
17 Lectures
2 hours
Mohd Raqif Warsi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2096,
"s": 1951,
"text": "In this chapter, we will learn about the environmental setup for GraphQL. To execute the examples in this tutorial you will need the following −"
},
{
"code": null,
"e": 2141,
"s": 2096,
"text": "A computer running Linux, macOS, or Windows."
},
{
"code": null,
"e": 2186,
"s": 2141,
"text": "A computer running Linux, macOS, or Windows."
},
{
"code": null,
"e": 2249,
"s": 2186,
"text": "A web browser, preferably the latest version of Google Chrome."
},
{
"code": null,
"e": 2312,
"s": 2249,
"text": "A web browser, preferably the latest version of Google Chrome."
},
{
"code": null,
"e": 2390,
"s": 2312,
"text": "A recent version of Node.js installed. The latest LTS version is recommended."
},
{
"code": null,
"e": 2468,
"s": 2390,
"text": "A recent version of Node.js installed. The latest LTS version is recommended."
},
{
"code": null,
"e": 2566,
"s": 2468,
"text": "Visual Studio Code with extension GraphQL for VSCode installed or any code editor of your choice."
},
{
"code": null,
"e": 2664,
"s": 2566,
"text": "Visual Studio Code with extension GraphQL for VSCode installed or any code editor of your choice."
},
{
"code": null,
"e": 2766,
"s": 2664,
"text": "We will go through a detailed step-wise approach to build GraphQL server with Nodejs as shown below −"
},
{
"code": null,
"e": 2869,
"s": 2766,
"text": "After installing NodeJs, verify the version of node and npm using following commands on the terminal −"
},
{
"code": null,
"e": 2930,
"s": 2869,
"text": "C:\\Users\\Admin>node -v\nv8.11.3\n\nC:\\Users\\Admin>npm -v\n5.6.0\n"
},
{
"code": null,
"e": 2983,
"s": 2930,
"text": "The root folder of project can be named as test-app."
},
{
"code": null,
"e": 3065,
"s": 2983,
"text": "Open the folder using visual studio code editor by using the instructions below −"
},
{
"code": null,
"e": 3153,
"s": 3065,
"text": "C:\\Users\\Admin>mkdir test-app\nC:\\Users\\Admin>cd test-app\nC:\\Users\\Admin\\test-app>code.\n"
},
{
"code": null,
"e": 3255,
"s": 3153,
"text": "Create a package.json file which will contain all the dependencies of the GraphQL server application."
},
{
"code": null,
"e": 3659,
"s": 3255,
"text": "{\n \"name\": \"hello-world-server\",\n \"private\": true,\n \"scripts\": {\n \"start\": \"nodemon --ignore data/ server.js\"\n },\n \n \"dependencies\": {\n \"apollo-server-express\": \"^1.4.0\",\n \"body-parser\": \"^1.18.3\",\n \"cors\": \"^2.8.4\",\n \"express\": \"^4.16.3\",\n \"graphql\": \"^0.13.2\",\n \"graphql-tools\": \"^3.1.1\"\n },\n \n \"devDependencies\": {\n \"nodemon\": \"1.17.1\"\n }\n}"
},
{
"code": null,
"e": 3722,
"s": 3659,
"text": "Install the dependencies by using the command as given below −"
},
{
"code": null,
"e": 3759,
"s": 3722,
"text": "C:\\Users\\Admin\\test-app>npm install\n"
},
{
"code": null,
"e": 3891,
"s": 3759,
"text": "In this step, we use flat files to store and retrieve data. Create a folder data and add two files students.json and colleges.json."
},
{
"code": null,
"e": 3929,
"s": 3891,
"text": "Following is the colleges.json file −"
},
{
"code": null,
"e": 4149,
"s": 3929,
"text": "[\n {\n \"id\": \"col-101\",\n \"name\": \"AMU\",\n \"location\": \"Uttar Pradesh\",\n \"rating\":5.0\n },\n \n {\n \"id\": \"col-102\",\n \"name\": \"CUSAT\",\n \"location\": \"Kerala\",\n \"rating\":4.5\n }\n]"
},
{
"code": null,
"e": 4187,
"s": 4149,
"text": "Following is the students.json file −"
},
{
"code": null,
"e": 4805,
"s": 4187,
"text": "[\n {\n \"id\": \"S1001\",\n \"firstName\":\"Mohtashim\",\n \"lastName\":\"Mohammad\",\n \"email\": \"[email protected]\",\n \"password\": \"pass123\",\n \"collegeId\": \"col-102\"\n },\n \n {\n \"id\": \"S1002\",\n \"email\": \"[email protected]\",\n \"firstName\":\"Kannan\",\n \"lastName\":\"Sudhakaran\",\n \"password\": \"pass123\",\n \"collegeId\": \"col-101\"\n },\n \n {\n \"id\": \"S1003\",\n \"email\": \"[email protected]\",\n \"firstName\":\"Kiran\",\n \"lastName\":\"Panigrahi\",\n \"password\": \"pass123\",\n \"collegeId\": \"col-101\"\n }\n]"
},
{
"code": null,
"e": 5020,
"s": 4805,
"text": "We need to create a datastore that loads the data folder contents. In this case, we need collection variables, students and colleges. Whenever the application needs data, it makes use of these collection variables."
},
{
"code": null,
"e": 5078,
"s": 5020,
"text": "Create file db.js with in the project folder as follows −"
},
{
"code": null,
"e": 5269,
"s": 5078,
"text": "const { DataStore } = require('notarealdb');\n\nconst store = new DataStore('./data');\n\nmodule.exports = {\n students:store.collection('students'),\n colleges:store.collection('colleges')\n};"
},
{
"code": null,
"e": 5353,
"s": 5269,
"text": "Create a schema file in the current project folder and add the following contents −"
},
{
"code": null,
"e": 5385,
"s": 5353,
"text": "type Query {\n test: String\n}"
},
{
"code": null,
"e": 5471,
"s": 5385,
"text": "Create a resolver file in the current project folder and add the following contents −"
},
{
"code": null,
"e": 5579,
"s": 5471,
"text": "const Query = {\n test: () => 'Test Success, GraphQL server is up & running !!'\n}\nmodule.exports = {Query}"
},
{
"code": null,
"e": 5635,
"s": 5579,
"text": "Create a server file and configure GraphQL as follows −"
},
{
"code": null,
"e": 6400,
"s": 5635,
"text": "const bodyParser = require('body-parser');\nconst cors = require('cors');\nconst express = require('express');\nconst db = require('./db');\n\nconst port = process.env.PORT || 9000;\nconst app = express();\n\nconst fs = require('fs')\nconst typeDefs = fs.readFileSync('./schema.graphql',{encoding:'utf-8'})\nconst resolvers = require('./resolvers')\n\nconst {makeExecutableSchema} = require('graphql-tools')\nconst schema = makeExecutableSchema({typeDefs, resolvers})\n\napp.use(cors(), bodyParser.json());\n\nconst {graphiqlExpress,graphqlExpress} = require('apollo-server-express')\napp.use('/graphql',graphqlExpress({schema}))\napp.use('/graphiql',graphiqlExpress({endpointURL:'/graphql'}))\n\napp.listen(\n port, () => console.info(\n `Server started on port ${port}`\n )\n);"
},
{
"code": null,
"e": 6461,
"s": 6400,
"text": "Verify the folder structure of project test-app as follows −"
},
{
"code": null,
"e": 6611,
"s": 6461,
"text": "test-app /\n -->package.json\n -->db.js\n -->data\n students.json\n colleges.json\n -->resolvers.js\n -->schema.graphql\n -->server.js\n"
},
{
"code": null,
"e": 6654,
"s": 6611,
"text": "Run the command npm start as given below −"
},
{
"code": null,
"e": 6689,
"s": 6654,
"text": "C:\\Users\\Admin\\test-app>npm start\n"
},
{
"code": null,
"e": 6885,
"s": 6689,
"text": "The server is running in 9000 port, so we can test the application using GraphiQL tool. Open the browser and enter the URL http://localhost:9000/graphiql. Type the following query in the editor −"
},
{
"code": null,
"e": 6899,
"s": 6885,
"text": "{\n Test \n}\n"
},
{
"code": null,
"e": 6945,
"s": 6899,
"text": "The response from the server is given below −"
},
{
"code": null,
"e": 7027,
"s": 6945,
"text": "{\n \"data\": {\n \"test\": \"Test Success, GraphQL server is running !!\"\n }\n}\n"
},
{
"code": null,
"e": 7060,
"s": 7027,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7073,
"s": 7060,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 7106,
"s": 7073,
"text": "\n 53 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7118,
"s": 7106,
"text": " Asfend Yar"
},
{
"code": null,
"e": 7151,
"s": 7118,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7169,
"s": 7151,
"text": " Mohd Raqif Warsi"
},
{
"code": null,
"e": 7176,
"s": 7169,
"text": " Print"
},
{
"code": null,
"e": 7187,
"s": 7176,
"text": " Add Notes"
}
] |
How to Containerize Models Trained in Spark: MLLib, ONNX and more | by Facundo Santiago | Towards Data Science
|
If we shall name two trends in modern applications, one should mention containers and machine learning. More and more applications are taking advantage of containerized microservices architectures in order to enable improved elasticity, fault-tolerance, and scalability — whether or on-premise or in the cloud. At the same time, achine Learning have increasingly become a basic requirement in any application.
However, the two things do not always get on each other, and this is the case of Spark. Spark is now-a-days the industry defacto standard for big data analytics, either by using Cloudera, Azure Databricks, AWS EMR, or whatever. But what about if you want to use the model you trained in Spark somewhere else outside the cluster?
There are a couple of options for this:
If you trained your model using TensorFlow, PyTorch, Scikit-Learn, or so, then you can package your model in different portable formats. Since these frameworks don’t depend directly on Spark, you are good to go. I won’t talk about this option in this post.If you trained your model using MLLib (like in the namespace pyspark.ml.*), then you can export your model to a portable format, like ONNX, and then use the ONNX runtime to run the model. This has some limitations since not all the models in MLLib support ONNX currently.If you trained your model using MLLib, then you can persist your model and load it from inside the container by creating a cluster-less Spark context object.(Updated Feb-2022) Use MLFlow to persist you model and package it using the MLModel specification. MLFlow currently supports Spark and it is able to package your model using the MLModel specification. You can use MLFlow to deploy you model wherever you want. For more details about this strategy see my post: Effortless deployments using MLFlow.
If you trained your model using TensorFlow, PyTorch, Scikit-Learn, or so, then you can package your model in different portable formats. Since these frameworks don’t depend directly on Spark, you are good to go. I won’t talk about this option in this post.
If you trained your model using MLLib (like in the namespace pyspark.ml.*), then you can export your model to a portable format, like ONNX, and then use the ONNX runtime to run the model. This has some limitations since not all the models in MLLib support ONNX currently.
If you trained your model using MLLib, then you can persist your model and load it from inside the container by creating a cluster-less Spark context object.
(Updated Feb-2022) Use MLFlow to persist you model and package it using the MLModel specification. MLFlow currently supports Spark and it is able to package your model using the MLModel specification. You can use MLFlow to deploy you model wherever you want. For more details about this strategy see my post: Effortless deployments using MLFlow.
ONNX is an open-standard for serialization and specification of a machine learning model. Since the format describes the computation graph (input, output and operations), it is self-contained. It is focused on deep-learning and it is championed mainly by Microsoft and Facebook. Supported in many frameworks like TensorFlow and PyTorch.
In Spark, an ML model is represented by aTransformer which transforms an inputDataFrame with features into another DataFrame with predictions. A Transformer can also output another set of features. Since in Machine Learning you usually have to perform several steps to produce the desired prediction, Spark has aPipelineModelobject which is a sequence of steps or Transformers(note that the pipeline object is a bit more complex, but for the sake of simplicity of this post, we will assume it as that). It chains multiple Transformers together to specify a ML workflow.
Consider the following example from spark.apache.org where we have a PipelineModelwith 3 stages: A tokenizer (which takes text and return words), a Hashing function (which takes words and returns vectors) and a Logistic Regression Model (which takes features and return predictions).
You get a PipelineModel by training a Pipeline using the method fit(). Here you have an example:
tokenizer = Tokenizer(inputCol="text", outputCol="words")hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features")lr = LogisticRegression(maxIter=10, regParam=0.01)pipeline = Pipeline(stages=[tokenizer, hashingTF, lr])model = pipeline.fit(training)
Now the question is, how to run this PipelineModel object outside Spark?
ONNX is designed for deep-learning models, however, it supports in some extends more “traditional” machine learning techniques. Spark is commonly used for those more traditional approaches. In Spark this includes:
Vectorizers and encodings (String indexing, OneHotEncoding, Word2Vec)
Scalers (Scalers, Inputer, Binarizer, Bucketizer)
Models: Linear models, Random Forest, Gradient Boosted, Naive Bayes, SVM, PCA
To export your model to an ONNX format, you need to install first onnxmltools which is available right now only for PySpark. Depending on the platform you are using the way you will install the library. In my case, I’m using Azure Databricks, so I will install this library using the Install library option in the cluster.
Once the library is installed, then you can export your pipeline model into ONNX by:
from onnxmltools import convert_sparkmlfrom onnxmltools.convert.sparkml.utils import buildInitialTypesSimpleinitial_types = buildInitialTypesSimple(test_df.drop("label"))onnx_model = convert_sparkml(model, 'Pyspark model', initial_types, spark_session = spark)
Where,
the buildInitialTypesSimple function creates a list of all the expected inputs from the model (features). It takes a sample DataFrame as parameter. In my case, I’m using the test_df dataframe and dropping the label column to retain only all the features.
model is the name of the fitted Pipeline (PipelineModel)
‘Pyspark model’ is the description of the model
initial_types are the expected input feature names an types. This can be supplied, as I said, by using the buildInitialTypesSimplefunction, or by constructing by hand, like [ (‘education’, StringTensorType([1, 1]))]
spark_session=sparkpass the SparkSession context to the method.
Note: This last parameter isn’t documented in the GitHub repository but after some debuging I needed to specify it to avoid a null spark context being used. In my case I’m using Azure Databricks, so I don’t know if this is specific to Databricks or not.
Once the model is converted, you can persist it into a file by:
with open(os.path.join("/tmp/", "model.onnx"), "wb") as f: f.write(onnx_model.SerializeToString())
You can load this model easily using ONNX runtime in Python like:
import onnxruntime session = onnxruntime.InferenceSession(model_file_path, None)output = session.get_outputs()[0]inputs = session.get_inputs()input_data= {i.name: v for i, v in zip(inputs, input_sample.values.reshape(len(inputs),1,1).astype(np.float32))}}results = session.run([output.name], input_data)
Note: input_data is a dictionary with keys as feature names, and Tensors (1,1) as values. The reshape function transform the input to an array of Tensor with shape (feature_count,1,1), which is expected. It is also important to cast the values as float32.
You then can ship this model in a docker container with Python and the following libraries installed:
onnxruntime
Your scoring file will load the model using the onnxruntime.InferenceSession() method. You usually perform this once. Your scoring routine will call session.run() on the other hand.
I have a sample scoring file in the following GitHub link.
By the time writing this post, the following features are missing in the Spark to ONNX converter:
Missing exporters for Feature Hashing, TFIDF, RFormula, NGram, SQLTransformer and some models (clustering, FP, ALS, etc)
Support only for PySpark
Some issues: Tokenizer is not supported in the ONNX specification
Another way to run a PipelineModel inside of a container is to export the model and create a Spark context inside of the container even when there is not cluster available.
If you want to persist this PipelineModel, the object implements the interface MLWritable, which exponses the method save(path) and write().overwrite().save(path). This method saves the model in a folder structure like the following:
In this structure, the PipelineModel is persisted inside a folder structure where all the steps in the pipeline are detailed. In this case, this model I created has 2 stages: a VectorAssembler and a GradientBoostedRegressor. Opposite as what you may be used to, all the structure is required to load and restore the trained model. If you are using a model registry, like MLFlow or Azure Machine Learning Services, I suggest you zip the directory in an archive. The following line helps to do so:
import shutilmodel.write().overwrite().save(model_path)path_drv = shutil.make_archive(model_name, format='zip', base_dir=model_path)
Please notice that shutil.make_archive will create the file in the driver node in its local file system.
Since you will be loading the Spark model directly, you will need to install pyspark Python library in the container image. Then in your scoring script you will create a spark session, unpack the archive in a folder and load the PipelineModel object.
import pysparkfrom pyspark.ml import PipelineModelspark = pyspark.sql.SparkSession .builder.appName("pyspark_runtime").getOrCreate()model_unpacked = "./" + model_nameshutil.unpack_archive(model_path, model_unpacked)trainedModel = PipelineModel.load(model_unpacked)
The variables spark and trainedModel have to be available in all the routines. Personally, I declare those two as global variables.
Then, you run your model by:
input_df = spark.createDataFrame(pandas_df)predictions = trainedModel.transform(input_df).collect()preds = [x['prediction'] for x in predictioprint('[INFO] Results was ' + json.dumps(preds))
I have a sample scoring file in the following GitHub link.
We reviewed in this post two different ways to port models trained inside a Spark cluster to run them inside a container. Using the open-standard ONNX or loading the persisted model in an Spark context. You can check the GitHub repository if you want to see the complete code for the examples. There is also a Databricks notebook to generate both the ONNX file and the MLLib zip file. Hope it helps.
|
[
{
"code": null,
"e": 582,
"s": 172,
"text": "If we shall name two trends in modern applications, one should mention containers and machine learning. More and more applications are taking advantage of containerized microservices architectures in order to enable improved elasticity, fault-tolerance, and scalability — whether or on-premise or in the cloud. At the same time, achine Learning have increasingly become a basic requirement in any application."
},
{
"code": null,
"e": 911,
"s": 582,
"text": "However, the two things do not always get on each other, and this is the case of Spark. Spark is now-a-days the industry defacto standard for big data analytics, either by using Cloudera, Azure Databricks, AWS EMR, or whatever. But what about if you want to use the model you trained in Spark somewhere else outside the cluster?"
},
{
"code": null,
"e": 951,
"s": 911,
"text": "There are a couple of options for this:"
},
{
"code": null,
"e": 1981,
"s": 951,
"text": "If you trained your model using TensorFlow, PyTorch, Scikit-Learn, or so, then you can package your model in different portable formats. Since these frameworks don’t depend directly on Spark, you are good to go. I won’t talk about this option in this post.If you trained your model using MLLib (like in the namespace pyspark.ml.*), then you can export your model to a portable format, like ONNX, and then use the ONNX runtime to run the model. This has some limitations since not all the models in MLLib support ONNX currently.If you trained your model using MLLib, then you can persist your model and load it from inside the container by creating a cluster-less Spark context object.(Updated Feb-2022) Use MLFlow to persist you model and package it using the MLModel specification. MLFlow currently supports Spark and it is able to package your model using the MLModel specification. You can use MLFlow to deploy you model wherever you want. For more details about this strategy see my post: Effortless deployments using MLFlow."
},
{
"code": null,
"e": 2238,
"s": 1981,
"text": "If you trained your model using TensorFlow, PyTorch, Scikit-Learn, or so, then you can package your model in different portable formats. Since these frameworks don’t depend directly on Spark, you are good to go. I won’t talk about this option in this post."
},
{
"code": null,
"e": 2510,
"s": 2238,
"text": "If you trained your model using MLLib (like in the namespace pyspark.ml.*), then you can export your model to a portable format, like ONNX, and then use the ONNX runtime to run the model. This has some limitations since not all the models in MLLib support ONNX currently."
},
{
"code": null,
"e": 2668,
"s": 2510,
"text": "If you trained your model using MLLib, then you can persist your model and load it from inside the container by creating a cluster-less Spark context object."
},
{
"code": null,
"e": 3014,
"s": 2668,
"text": "(Updated Feb-2022) Use MLFlow to persist you model and package it using the MLModel specification. MLFlow currently supports Spark and it is able to package your model using the MLModel specification. You can use MLFlow to deploy you model wherever you want. For more details about this strategy see my post: Effortless deployments using MLFlow."
},
{
"code": null,
"e": 3351,
"s": 3014,
"text": "ONNX is an open-standard for serialization and specification of a machine learning model. Since the format describes the computation graph (input, output and operations), it is self-contained. It is focused on deep-learning and it is championed mainly by Microsoft and Facebook. Supported in many frameworks like TensorFlow and PyTorch."
},
{
"code": null,
"e": 3921,
"s": 3351,
"text": "In Spark, an ML model is represented by aTransformer which transforms an inputDataFrame with features into another DataFrame with predictions. A Transformer can also output another set of features. Since in Machine Learning you usually have to perform several steps to produce the desired prediction, Spark has aPipelineModelobject which is a sequence of steps or Transformers(note that the pipeline object is a bit more complex, but for the sake of simplicity of this post, we will assume it as that). It chains multiple Transformers together to specify a ML workflow."
},
{
"code": null,
"e": 4205,
"s": 3921,
"text": "Consider the following example from spark.apache.org where we have a PipelineModelwith 3 stages: A tokenizer (which takes text and return words), a Hashing function (which takes words and returns vectors) and a Logistic Regression Model (which takes features and return predictions)."
},
{
"code": null,
"e": 4302,
"s": 4205,
"text": "You get a PipelineModel by training a Pipeline using the method fit(). Here you have an example:"
},
{
"code": null,
"e": 4572,
"s": 4302,
"text": "tokenizer = Tokenizer(inputCol=\"text\", outputCol=\"words\")hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol=\"features\")lr = LogisticRegression(maxIter=10, regParam=0.01)pipeline = Pipeline(stages=[tokenizer, hashingTF, lr])model = pipeline.fit(training)"
},
{
"code": null,
"e": 4645,
"s": 4572,
"text": "Now the question is, how to run this PipelineModel object outside Spark?"
},
{
"code": null,
"e": 4859,
"s": 4645,
"text": "ONNX is designed for deep-learning models, however, it supports in some extends more “traditional” machine learning techniques. Spark is commonly used for those more traditional approaches. In Spark this includes:"
},
{
"code": null,
"e": 4929,
"s": 4859,
"text": "Vectorizers and encodings (String indexing, OneHotEncoding, Word2Vec)"
},
{
"code": null,
"e": 4979,
"s": 4929,
"text": "Scalers (Scalers, Inputer, Binarizer, Bucketizer)"
},
{
"code": null,
"e": 5057,
"s": 4979,
"text": "Models: Linear models, Random Forest, Gradient Boosted, Naive Bayes, SVM, PCA"
},
{
"code": null,
"e": 5380,
"s": 5057,
"text": "To export your model to an ONNX format, you need to install first onnxmltools which is available right now only for PySpark. Depending on the platform you are using the way you will install the library. In my case, I’m using Azure Databricks, so I will install this library using the Install library option in the cluster."
},
{
"code": null,
"e": 5465,
"s": 5380,
"text": "Once the library is installed, then you can export your pipeline model into ONNX by:"
},
{
"code": null,
"e": 5726,
"s": 5465,
"text": "from onnxmltools import convert_sparkmlfrom onnxmltools.convert.sparkml.utils import buildInitialTypesSimpleinitial_types = buildInitialTypesSimple(test_df.drop(\"label\"))onnx_model = convert_sparkml(model, 'Pyspark model', initial_types, spark_session = spark)"
},
{
"code": null,
"e": 5733,
"s": 5726,
"text": "Where,"
},
{
"code": null,
"e": 5988,
"s": 5733,
"text": "the buildInitialTypesSimple function creates a list of all the expected inputs from the model (features). It takes a sample DataFrame as parameter. In my case, I’m using the test_df dataframe and dropping the label column to retain only all the features."
},
{
"code": null,
"e": 6045,
"s": 5988,
"text": "model is the name of the fitted Pipeline (PipelineModel)"
},
{
"code": null,
"e": 6093,
"s": 6045,
"text": "‘Pyspark model’ is the description of the model"
},
{
"code": null,
"e": 6309,
"s": 6093,
"text": "initial_types are the expected input feature names an types. This can be supplied, as I said, by using the buildInitialTypesSimplefunction, or by constructing by hand, like [ (‘education’, StringTensorType([1, 1]))]"
},
{
"code": null,
"e": 6373,
"s": 6309,
"text": "spark_session=sparkpass the SparkSession context to the method."
},
{
"code": null,
"e": 6627,
"s": 6373,
"text": "Note: This last parameter isn’t documented in the GitHub repository but after some debuging I needed to specify it to avoid a null spark context being used. In my case I’m using Azure Databricks, so I don’t know if this is specific to Databricks or not."
},
{
"code": null,
"e": 6691,
"s": 6627,
"text": "Once the model is converted, you can persist it into a file by:"
},
{
"code": null,
"e": 6793,
"s": 6691,
"text": "with open(os.path.join(\"/tmp/\", \"model.onnx\"), \"wb\") as f: f.write(onnx_model.SerializeToString())"
},
{
"code": null,
"e": 6859,
"s": 6793,
"text": "You can load this model easily using ONNX runtime in Python like:"
},
{
"code": null,
"e": 7163,
"s": 6859,
"text": "import onnxruntime session = onnxruntime.InferenceSession(model_file_path, None)output = session.get_outputs()[0]inputs = session.get_inputs()input_data= {i.name: v for i, v in zip(inputs, input_sample.values.reshape(len(inputs),1,1).astype(np.float32))}}results = session.run([output.name], input_data)"
},
{
"code": null,
"e": 7419,
"s": 7163,
"text": "Note: input_data is a dictionary with keys as feature names, and Tensors (1,1) as values. The reshape function transform the input to an array of Tensor with shape (feature_count,1,1), which is expected. It is also important to cast the values as float32."
},
{
"code": null,
"e": 7521,
"s": 7419,
"text": "You then can ship this model in a docker container with Python and the following libraries installed:"
},
{
"code": null,
"e": 7533,
"s": 7521,
"text": "onnxruntime"
},
{
"code": null,
"e": 7715,
"s": 7533,
"text": "Your scoring file will load the model using the onnxruntime.InferenceSession() method. You usually perform this once. Your scoring routine will call session.run() on the other hand."
},
{
"code": null,
"e": 7774,
"s": 7715,
"text": "I have a sample scoring file in the following GitHub link."
},
{
"code": null,
"e": 7872,
"s": 7774,
"text": "By the time writing this post, the following features are missing in the Spark to ONNX converter:"
},
{
"code": null,
"e": 7993,
"s": 7872,
"text": "Missing exporters for Feature Hashing, TFIDF, RFormula, NGram, SQLTransformer and some models (clustering, FP, ALS, etc)"
},
{
"code": null,
"e": 8018,
"s": 7993,
"text": "Support only for PySpark"
},
{
"code": null,
"e": 8084,
"s": 8018,
"text": "Some issues: Tokenizer is not supported in the ONNX specification"
},
{
"code": null,
"e": 8257,
"s": 8084,
"text": "Another way to run a PipelineModel inside of a container is to export the model and create a Spark context inside of the container even when there is not cluster available."
},
{
"code": null,
"e": 8491,
"s": 8257,
"text": "If you want to persist this PipelineModel, the object implements the interface MLWritable, which exponses the method save(path) and write().overwrite().save(path). This method saves the model in a folder structure like the following:"
},
{
"code": null,
"e": 8987,
"s": 8491,
"text": "In this structure, the PipelineModel is persisted inside a folder structure where all the steps in the pipeline are detailed. In this case, this model I created has 2 stages: a VectorAssembler and a GradientBoostedRegressor. Opposite as what you may be used to, all the structure is required to load and restore the trained model. If you are using a model registry, like MLFlow or Azure Machine Learning Services, I suggest you zip the directory in an archive. The following line helps to do so:"
},
{
"code": null,
"e": 9120,
"s": 8987,
"text": "import shutilmodel.write().overwrite().save(model_path)path_drv = shutil.make_archive(model_name, format='zip', base_dir=model_path)"
},
{
"code": null,
"e": 9225,
"s": 9120,
"text": "Please notice that shutil.make_archive will create the file in the driver node in its local file system."
},
{
"code": null,
"e": 9476,
"s": 9225,
"text": "Since you will be loading the Spark model directly, you will need to install pyspark Python library in the container image. Then in your scoring script you will create a spark session, unpack the archive in a folder and load the PipelineModel object."
},
{
"code": null,
"e": 9755,
"s": 9476,
"text": "import pysparkfrom pyspark.ml import PipelineModelspark = pyspark.sql.SparkSession .builder.appName(\"pyspark_runtime\").getOrCreate()model_unpacked = \"./\" + model_nameshutil.unpack_archive(model_path, model_unpacked)trainedModel = PipelineModel.load(model_unpacked)"
},
{
"code": null,
"e": 9887,
"s": 9755,
"text": "The variables spark and trainedModel have to be available in all the routines. Personally, I declare those two as global variables."
},
{
"code": null,
"e": 9916,
"s": 9887,
"text": "Then, you run your model by:"
},
{
"code": null,
"e": 10107,
"s": 9916,
"text": "input_df = spark.createDataFrame(pandas_df)predictions = trainedModel.transform(input_df).collect()preds = [x['prediction'] for x in predictioprint('[INFO] Results was ' + json.dumps(preds))"
},
{
"code": null,
"e": 10166,
"s": 10107,
"text": "I have a sample scoring file in the following GitHub link."
}
] |
Trade and Invest Smarter — The Reinforcement Learning Way | by Adam King | Towards Data Science
|
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
Winning high stakes poker tournaments, out-playing world-class StarCraft players, and autonomously driving Tesla’s futuristic sports cars. What do they all have in common? Each of these extremely complex tasks were long thought to be impossible by machines, until recent advancements in deep reinforcement learning showed they were possible, today.
Reinforcement learning is beginning to take over the world.
A little over two months ago, I decided I wanted to take part in the revolution, so I set out on a journey to create a profitable Bitcoin trading strategy using state-of-the-art deep reinforcement learning algorithms. While I made quite a bit of progress on that front, I realized that the tooling for this sort of project can be quite daunting to wrap your head around, and as such, it is very easy to get lost in the details.
In between optimizing my previous project for distributed high-performance computing (HPC) systems; getting lost in endless pipelines of data and feature optimizations; and running my head in circles around efficient model set-up, tuning, training, and evaluation; I realized that there had to be a better way of doing things. After countless hours of researching existing projects, spending endless nights watching PyData conference talks, and having many back-and-forth conversations with the hundreds of members of the RL trading Discord community, I realized there weren’t any existing solutions that were all that good.
There were many bits and pieces of great reinforcement learning trading systems spread across the inter-webs, but nothing solid and complete. For this reason, I’ve decided to create an open source Python framework for getting any trading strategy from idea to production, efficiently, using deep reinforcement learning.
Enter TensorTrade. The idea was to create a highly modular framework for building efficient reinforcement learning trading strategies in a composable, maintainable way. Sounds like a mouthful of buzz-words if you ask me, so let’s get into the meat.
We're so pumped to have you!
Already have an account? Sign In
Table of Contents
Overview
RL Primer
Getting Started
Installation
TensorTrade Components
Trading Environments
Exchanges
Feature Pipelines
Action Strategies
Reward Strategies
Learning Agents
Stable Baselines
Tensorforce
Trading Strategies
Putting it All Together
Creating an Environment
Defining the Agent
Training a Strategy
Saving and Restoring
Tuning Your Strategy
Strategy Evaluation
Live Trading
The Future
Final Thoughts
Contributing
References
TensorTrade is an open source Python framework for training, evaluating, and deploying robust trading strategies using deep reinforcement learning. The framework focuses on being highly composable and extensible, to allow the system to scale from simple trading strategies on a single CPU, to complex investment strategies run on a distribution of HPC machines.
Under the hood, the framework uses many of the APIs from existing machine learning libraries to maintain high quality data pipelines and learning models. One of the main goals of TensorTrade is to enable fast experimentation with algorithmic trading strategies, by leveraging the existing tools and pipelines provided by numpy, pandas, gym, keras, and tensorflow.
Every piece of the framework is split up into re-usable components, allowing you to take advantage of the general use components built by the community, while keeping your proprietary features private. The aim is to simplify the process of testing and deploying robust trading agents using deep reinforcement learning, to allow you and I to focus on creating profitable strategies.
In case your reinforcement learning chops are a bit rusty, let’s quickly go over the basic concepts.
Reinforcement learning (RL) is an area of machine learning concerned with how software agents ought to take actions in an environment so as to maximize some notion of cumulative reward.
Every reinforcement learning problem starts out with an environment and one or more agents that can interact with the environment.
The agent will first observe the environment, then build a model of the current state and the expected value of actions within that environment. Based on that model, the agent will then take the action it has deemed as having the highest expected value.
Based on the effects of the chosen action within the environment, the agent will be rewarded by an amount corresponding to the actual value of that action. The reinforcement learning agent can then, through the process of trial and error (i.e. learning through reinforcement), improve its underlying model and learn to take more rewarding actions over time.
If you still need a bit of refreshment on the subject, there is a link to an article titled Introduction to Deep Reinforcement Learning in the references for this article, which goes much more in-depth into the details. Let’s move on.
The following tutorial should provide enough examples to get you started with creating simple trading strategies using TensorTrade, although you will quickly see the framework is capable of handling much more complex configurations.
You can follow along with Google Colab or the tutorial on Github.
TensorTrade requires Python 3.6 or later, so make sure you’re using a valid version before pip installing the framework.
pip install git+https://github.com/notadamking/tensortrade.git
To follow this entire tutorial, you will need to install some extra dependencies, such as tensorflow, tensorforce, stable-baselines, ccxt, ta, and stochastic.
pip install git+https://github.com/notadamking/tensortrade.git#egg=tensortrade[tf,tensorforce,baselines,ccxt,ta,fbm] -U
That’s all the installation necessary! Let’s get into the code.
TensorTrade is built around modular components that together make up a trading strategy. Trading strategies combine reinforcement learning agents with composable trading logic in the form of a gym environment. A trading environment is made up of a set of modular components that can be mixed and matched to create highly diverse trading and investment strategies. I will explain this in further detail later, but for now it is enough to know the basics.
Just like electrical components, the purpose of TensorTrade components is to be able to mix and match them as necessary.
The code snippets in this section should serve as guidelines for creating new strategies and components. There will likely be missing implementation details that will become more clear in a later section, as more components are defined.
A trading environment is a reinforcement learning environment that follows OpenAI’s gym.Env specification. This allows us to leverage many of the existing reinforcement learning models in our trading agent, if we’d like.
Trading environments are fully configurable gym environments with highly composable Exchange, FeaturePipeline, ActionScheme, and RewardScheme components.
The Exchange provides observations to the environment and executes the agent’s trades.
The FeaturePipeline optionally transforms the exchange output into a more meaningful set of features before it is passed to the agent.
The ActionScheme converts the agent’s actions into executable trades.
The RewardScheme calculates the reward for each time step based on the agent’s performance.
If it seems a bit complicated now, it’s really not. That’s all there is to it, now it’s just a matter of composing each of these components into a complete environment.
When the reset method of a TradingEnvironment is called, all of the child components will also be reset. The internal state of each exchange, feature pipeline, transformer, action scheme, and reward scheme will be set back to their default values, ready for the next episode.
Let’s begin with an example environment. As mentioned before, initializing a TradingEnvironment requires an exchange, an action scheme, and a reward scheme, the feature pipeline is optional.
from tensortrade.environments import TradingEnvironmentenvironment = TradingEnvironment(exchange=exchange, action_scheme=action_scheme, reward_scheme=reward_scheme, feature_pipeline=feature_pipeline)
While the recommended use case is to plug a trading environment into a trading strategy, you can obviously use the trading environment separately, any way you’d otherwise use a gym environment.
Exchanges determine the universe of tradable instruments within a trading environment, return observations to the environment on each time step, and execute trades made within the environment. There are two types of exchanges: live and simulated.
Live exchanges are implementations of Exchange backed by live pricing data and a live trade execution engine. For example, CCXTExchange is a live exchange, which is capable of returning pricing data and executing trades on hundreds of live cryptocurrency exchanges, such as Binance and Coinbase.
import ccxtfrom tensortrade.exchanges.live import CCXTExchangecoinbase = ccxt.coinbasepro()exchange = CCXTExchange(exchange=coinbase, base_instrument='USD')
There are also exchanges for stock and ETF trading, such as RobinhoodExchange and InteractiveBrokersExchange, but these are still works in progress.
Simulated exchanges, on the other hand, are implementations of Exchange backed by simulated pricing data and trade execution.
For example, FBMExchange is a simulated exchange, which generates pricing and volume data using fractional brownian motion (FBM). Since its price is simulated, the trades it executes must be simulated as well. The exchange uses a simple slippage model to simulate price and volume slippage on trades, though like almost everything in TensorTrade, this slippage model can easily be swapped out for something more complex.
from tensortrade.exchanges.simulated import FBMExchangeexchange = FBMExchange(base_instrument='BTC', timeframe='1h')
Though the FBMExchange generates fake price and volume data using a stochastic model, it is simply an implementation of SimulatedExchange. Under the hood, SimulatedExchange only requires a data_frame of price history to generate its simulations. This data_frame can either be provided by a coded implementation such as FBMExchange, or at runtime such as in the following example.
import pandas as pdfrom tensortrade.exchanges.simulated import SimulatedExchangedf = pd.read_csv('./data/btc_ohclv_1h.csv')exchange = SimulatedExchange(data_frame=df, base_instrument='USD')
Feature pipelines are meant for transforming observations from the environment into meaningful features for an agent to learn from. If a pipeline has been added to a particular exchange, then observations will be passed through the FeaturePipeline before being output to the environment. For example, a feature pipeline could normalize all price values, make a time series stationary, add a moving average column, and remove an unnecessary column, all before the observation is returned to the agent.
Feature pipelines can be initialized with an arbitrary number of comma-separated transformers. Each FeatureTransformer needs to be initialized with the set of columns to transform, or if nothing is passed, all input columns will be transformed.
Each feature transformer has a transform method, which will transform a single observation (a pandas.DataFrame) from a larger data set, keeping any necessary state in memory to transform the next frame. For this reason, it is often necessary to reset the FeatureTransformer periodically. This is done automatically each time the parent FeaturePipeline or Exchange is reset.
Let’s create an example pipeline and add it to our existing exchange.
from tensortrade.features import FeaturePipelinefrom tensortrade.features.scalers import MinMaxNormalizerfrom tensortrade.features.stationarity import FractionalDifferencefrom tensortrade.features.indicators import SimpleMovingAverageprice_columns = ["open", "high", "low", "close"]normalize_price = MinMaxNormalizer(price_columns)moving_averages = SimpleMovingAverage(price_columns)difference_all = FractionalDifference(difference_order=0.6)feature_pipeline = FeaturePipeline(steps=[normalize_price, moving_averages, difference_all])exchange.feature_pipeline = feature_pipeline
This feature pipeline normalizes the price values between 0 and 1, before adding some moving average columns and making the entire time series stationary by fractionally differencing consecutive values.
Action schemes define the action space of the environment and convert an agent’s actions into executable trades. For example, if we were using a discrete action space of 3 actions (0 = hold, 1 = buy 100%, 2 = sell 100%), our learning agent does not need to know that returning an action of 1 is equivalent to buying an instrument. Rather, our agent needs to know the reward for returning an action of 1 in specific circumstances, and can leave the implementation details of converting actions to trades to the ActionScheme.
Each action scheme has a get_trade method, which will transform the agent’s specified action into an executable Trade. It is often necessary to store additional state within the scheme, for example to keep track of the currently traded position. This state should be reset each time the action scheme’s reset method is called, which is done automatically when the parent TradingEnvironment is reset.
from tensortrade.actions import DiscreteActionsaction_scheme = DiscreteActions(n_actions=20, instrument_symbol='BTC')
This discrete action scheme uses 20 discrete actions, which equates to 4 discrete amounts for each of the 5 trade types (market buy/sell, limit buy/sell, and hold). E.g. [0,5,10,15]=hold, 1=market buy 25%, 2=market sell 25%, 3=limit buy 25%, 4=limit sell 25%, 6=market buy 50%, 7=market sell 50%, etc...
Reward schemes receive the trade taken at each time step and return a float, corresponding to the benefit of that specific action. For example, if the action taken this step was a sell that resulted in positive profits, our RewardScheme could return a positive number to encourage more trades like this. On the other hand, if the action was a sell that resulted in a loss, the scheme could return a negative reward to teach the agent not to make similar actions in the future.
A version of this example algorithm is implemented in the SimpleProfit component, however more complex strategies can obviously be used instead.
Each reward scheme has a get_reward method, which takes in the trade executed at each time step and returns a float corresponding to the value of that action. As with action schemes, it is often necessary to store additional state within a reward scheme for various reasons. This state should be reset each time the reward scheme’s reset method is called, which is done automatically when the parent TradingEnvironment is reset.
from tensortrade.rewards import SimpleProfitreward_scheme = SimpleProfit()
The simple profit scheme returns a reward of -1 for not holding a trade, 1 for holding a trade, 2 for purchasing an instrument, and a value corresponding to the (positive/negative) profit earned by a trade if an instrument was sold.
Up until this point, we haven’t seen the “deep” part of the deep reinforcement learning framework. This is where learning agents come in. Learning agents are where the math (read: magic) happens.
At each time step, the agent takes the observation from the environment as input, runs it through its underlying model (a neural network most of the time), and outputs the action to take. For example, the observation might be the previous open, high, low, and close price from the exchange. The learning model would take these values as input and output a value corresponding to the action to take, such as buy, sell, or hold.
It is important to remember the learning model has no intuition of the prices or trades being represented by these values. Rather, the model is simply learning which values to output for specific input values or sequences of input values, to earn the highest reward.
In this example, we will be using the Stable Baselines library to provide learning agents to our trading strategy, however, the TensorTrade framework is compatible with many reinforcement learning libraries such as Tensorforce, Ray’s RLLib, OpenAI’s Baselines, Intel’s Coach, or anything from the TensorFlow line such as TF Agents.
It is possible that custom TensorTrade learning agents will be added to this framework in the future, though it will always be a goal of the framework to be interoperable with as many existing reinforcement learning libraries as possible, since there is so much concurrent growth in the space.
But for now, Stable Baselines is simple and powerful enough for our needs.
from stable_baselines.common.policies import MlpLnLstmPolicyfrom stable_baselines import PPO2model = PPO2policy = MlpLnLstmPolicyparams = { "learning_rate": 1e-5 }agent = model(policy, environment, model_kwargs=params)
Note: Stable Baselines is not required to use TensorTrade though it is required for this tutorial. This example uses a GPU-enabled Proximal Policy Optimization model with a layer-normalized LSTM perceptron network. If you would like to know more about Stable Baselines, you can view the Documentation.
Tensorforce
I will also quickly cover the Tensorforce library to show how simple it is to switch between reinforcement learning frameworks.
from tensorforce.agents import Agentagent_spec = { "type": "ppo_agent", "step_optimizer": { "type": "adam", "learning_rate": 1e-4 }, "discount": 0.99, "likelihood_ratio_clipping": 0.2,}network_spec = [ dict(type='dense', size=64, activation="tanh"), dict(type='dense', size=32, activation="tanh")]agent = Agent.from_spec(spec=agent_spec, kwargs=dict(network=network_spec, states=environment.states, actions=environment.actions))
If you would like to know more about Tensorforce agents, you can view the Documentation.
A TradingStrategy consists of a learning agent and one or more trading environments to tune, train, and evaluate on. If only one environment is provided, it will be used for tuning, training, and evaluating. Otherwise, a separate environment may be provided at each step.
from tensortrade.strategies import TensorforceTradingStrategy, StableBaselinesTradingStrategya_strategy = TensorforceTradingStrategy(environment=environment, agent_spec=agent_spec, network_spec=network_spec)b_strategy = StableBaselinesTradingStrategy(environment=environment, model=PPO2, policy=MlpLnLSTMPolicy)
Don’t worry if you don’t understand the strategy initialization just yet, it will be explained in more detail later.
Now that we know about each component that makes up a TradingStrategy, let’s build and evaluate one.
For a quick recap, a TradingStrategy is made up of a TradingEnvironment and a learning agent. A TradingEnvironment is a gym environment that takes an Exchange, an ActionScheme, a RewardScheme, and an optional FeaturePipeline, and returns observations and rewards that the learning agent can be trained and evaluated on.
The first step is to create a TradingEnvironment using the components outlined above.
from tensortrade.exchanges.simulated import FBMExchangefrom tensortrade.features.scalers import MinMaxNormalizerfrom tensortrade.features.stationarity import FractionalDifferencefrom tensortrade.features import FeaturePipelinefrom tensortrade.rewards import SimpleProfitfrom tensortrade.actions import DiscreteActionsfrom tensortrade.environments import TradingEnvironmentnormalize_price = MinMaxNormalizer(["open", "high", "low", "close"])difference = FractionalDifference(difference_order=0.6)feature_pipeline = FeaturePipeline(steps=[normalize_price, difference])exchange = FBMExchange(timeframe='1h', base_instrument='BTC', feature_pipeline=feature_pipeline)reward_scheme = SimpleProfit()action_scheme = DiscreteActions(n_actions=20, instrument_symbol='ETH/BTC')environment = TradingEnvironment(exchange=exchange, action_scheme=action_scheme, reward_scheme=reward_scheme, feature_pipeline=feature_pipeline)
Simple enough, now environment is a gym environment that can be used by any compatible trading strategy or learning agent.
Now that the environment is set up, it’s time to create our learning agent. Again, we will be using Stable Baselines for this, but feel free to drop in any other reinforcement learning agent here.
Since we are using StableBaselinesTradingStrategy, all we need to do is provide a model type and a policy type for the underlying neural network to be trained. For this example, we will be using a simple proximal policy optimization (PPO) model and a layer-normalized LSTM policy network.
For more examples of model and policy specifications, see the Stable Baselines Documentation.
from stable_baselines.common.policies import MlpLnLstmPolicyfrom stable_baselines import PPO2model = PPO2policy = MlpLnLstmPolicyparams = { "learning_rate": 1e-5 }
Creating our trading strategy is as simple as plugging in our agent and the environment.
from tensortrade.strategies import StableBaselinesTradingStrategystrategy = StableBaselinesTradingStrategy(environment=environment, model=model, policy=policy, model_kwargs=params)
Then to train the strategy (i.e. train the agent on the current environment), all we need to do is call strategy.run() with the total number of steps or episodes you’d like to run.
performance = strategy.run(steps=100000, episode_callback=stop_early_callback)
And voila! Three hours and thousands of print statements later, you will see the results of how your agent has done!
If this feedback loop is a bit slow for you, you can pass a callback function to run, which will be called at the end of each episode. The callback function will pass in a data frame containing the agent’s performance that episode, and expects a bool in return. If True, the agent will continue training, otherwise, the agent will stop and return its overall performance.
All trading strategies are capable of saving their agent to a file, for later restoring. The environment is not saved, as it does not have state that we care about preserving. To save our TensorflowTradingStrategy to a file, we just need to provide the path of the file to our strategy.
strategy.save_agent(path="../agents/ppo_btc_1h")
To restore the agent from the file, we first need to instantiate our strategy, before calling restore_agent.
from tensortrade.strategies import StableBaselinesTradingStrategystrategy = StableBaselinesTradingStrategy(environment=environment, model=model, policy=policy, model_kwargs=params)strategy.restore_agent(path="../agents/ppo_btc/1h")
Our strategy is now restored back to its previous state, and ready to be used again.
Sometimes a trading strategy will require tuning a set of hyper-parameters, or features, on an environment to achieve maximum performance. In this case, each TradingStrategy provides an optionally implementable tune method.
Tuning a model is similar to training a model, however in addition to adjusting and saving the weights and biases of the best performing model, the strategy also adjusts and persists the hyper-parameters that produced that model.
from tensortrade.environments import TradingEnvironmentfrom tensortrade.exchanges.simulated import FBMExchangeexchange = FBMExchange(timeframe='1h', base_instrument='BTC', feature_pipeline=feature_pipeline)environment = TradingEnvironment(exchange=exchange, action_scheme=action_scheme, reward_scheme=reward_scheme)strategy.environment = environmenttuned_performance = strategy.tune(episodes=10)
In this case, the agent will be trained for 10 episodes, with a different set of hyper-parameters each episode. The best set will be saved within the strategy, and used any time strategy.run() is called thereafter.
Now that we’ve tuned and trained our agent, it’s time to see how well it performs. To evaluate our strategy’s performance on unseen data, we will need to run it on a new environment backed by such data.
from pandas import pdfrom tensortrade.environments import TradingEnvironmentfrom tensortrade.exchanges.simulated import SimulatedExchangedf = pd.read_csv('./btc_ohlcv_1h.csv')exchange = SimulatedExchange(data_frame=df, base_instrument='BTC', feature_pipeline=feature_pipeline)environment = TradingEnvironment(exchange=exchange, action_scheme=action_scheme, reward_scheme=reward_scheme)strategy.environment = environmenttest_performance = strategy.run(episodes=1, testing=True)
When complete, strategy.run returns a Pandas data frame of the agent’s performance, including the net worth and balance of the agent at each time step.
Once you’ve built a profitable trading strategy, trained an agent to trade it properly, and ensured its “generalize-ability” to new data sets, all there is left to do is profit. Using a live exchange such as CCXTExchange, you can plug your strategy in and let it run!
While the gambler in you may enjoy starting a strategy and letting it run without bounds, the more risk averse of you can use a trade_callback, which will be called each time the strategy makes a trade. This callback function, similar to the episode callback, will pass in a data frame containing the agent’s overall performance, and expects a bool in return. If True, the agent will continue trading, otherwise, the agent will stop and return its performance over the session.
import ccxtfrom tensortrade.environments import TradingEnvironmentfrom tensortrade.strategies import StableBaselinesTradingStrategyfrom tensortrade.exchanges.live import CCXTExchangecoinbase = ccxt.coinbasepro(...)exchange = CCXTExchange(exchange=coinbase, timeframe='1h', base_instrument='USD', feature_pipeline=feature_pipeline)environment = TradingEnvironment(exchange=exchange, action_scheme=action_scheme, reward_scheme=reward_scheme)strategy.environment = environmentstrategy.restore_agent(path="../agents/ppo_btc/1h")live_performance = strategy.run(steps=0, trade_callback=episode_cb)
Passing steps=0 instructs the strategy to run until otherwise stopped.
That’s all there is to it! As you can see, it is quite simple to build complex trading strategies using simple components and deep reinforcement learning. So what are you waiting for? Dive in, get your hands dirty, and see what’s possible using TensorTrade.
Currently, the framework is in its early stages. The focus so far has been to get a working prototype, with all of the necessary building blocks to create highly profitable strategies. The next step is to build a roadmap for the future, and decide which upcoming building blocks are important to the community.
Soon, we will see highly informative visualizations of the environments added to the framework, as well as much more in-depth strategies on more exchanges, trading more instruments.
The sky is the limit. The groundwork (i.e. framework) has been laid, it’s now up to the community to decide what’s next. I hope that you will be a part of it.
TensorTrade is a powerful framework capable of building highly modular, high performance trading systems. It is fairly simple and easy to experiment with new trading and investment strategies, while allowing you to leverage components from one strategy in another. But don’t take my word for it, create a strategy of your own and start teaching your robots to take over the world!
While this tutorial should be enough to get you started, there is still quite a lot more to learn if you want to create a profitable trading strategy. I encourage you to head over to the Github and dive into the codebase, or take a look at our documentation at tensortrade.org. There is also quite an active Discord community with nearly 1000 total members, so if you have questions, feedback, or feature requests, feel free to drop them there!
I’ve gotten the project to a highly usable state. Though, my time is limited, and I believe there are many of you out there who could make valuable contributions to the open source codebase. So if you are a developer or data scientist with an interest in building state-of-the-art trading systems, I’d love to see you open a pull request, even if its just a simple test case!
Others have asked how they can contribute to the project without writing code. There are currently three ways that you can do that.
Write code or documentation for the TensorTrade framework. Many issues on the Github are funded through Gitcoin smart contracts, so you can actually get paid to contribute. To date, almost 10 ETH (~$2000 USD), donated by the community has used to pay open source developers for their contributions to the framework.Fund this project with either Bitcoin or Ethereum. These donations are used to fund our Gitcoin smart contracts, which allows anyone who contributes quality code and documentation to get paid for their contributions.Sponsor me on Github. Github is currently matching all donations 1:1, up to $5,000, so there has never been a better time to sponsor my work and the TensorTrade’s development. All sponsorships go directly towards the funding of the open source development of the framework.
Write code or documentation for the TensorTrade framework. Many issues on the Github are funded through Gitcoin smart contracts, so you can actually get paid to contribute. To date, almost 10 ETH (~$2000 USD), donated by the community has used to pay open source developers for their contributions to the framework.
Fund this project with either Bitcoin or Ethereum. These donations are used to fund our Gitcoin smart contracts, which allows anyone who contributes quality code and documentation to get paid for their contributions.
Sponsor me on Github. Github is currently matching all donations 1:1, up to $5,000, so there has never been a better time to sponsor my work and the TensorTrade’s development. All sponsorships go directly towards the funding of the open source development of the framework.
Thanks for reading! As always, all of the code for this tutorial can be found on my GitHub. Leave a comment below if you have any questions or feedback, I’d love to hear from you! I can also be reached on Twitter at @notadamking.
You can also sponsor me on Github Sponsors or Patreon via the links below.
github.com
patreon.com
[1.] Introduction to Deep Reinforcement Learning Hui, Jonathan. “RL- Introduction to Deep Reinforcement Learning.” Medium, 7 Jan. 2019, https://medium.com/@jonathan_hui/rl-introduction-to-deep-reinforcement-learning-35c25e04c199.
[2.] Policy Gradient AlgorithmsWeng, Lilian. “Policy Gradient Algorithms.” Lil’Log, 8 Apr. 2018, https://lilianweng.github.io/lil-log/2018/04/08/policy-gradient-algorithms.html#reinforce.
[3.] Clean Code: A Handbook of Agile Software CraftsmanshipMartin, Robert C. Clean Code: a Handbook of Agile Software Craftsmanship. Prentice Hall, 2010.
[4.] Advances in Financial Machine LearningPrado Marcos López de. Advances in Financial Machine Learning. Wiley, 2018.
|
[
{
"code": null,
"e": 347,
"s": 47,
"text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details."
},
{
"code": null,
"e": 696,
"s": 347,
"text": "Winning high stakes poker tournaments, out-playing world-class StarCraft players, and autonomously driving Tesla’s futuristic sports cars. What do they all have in common? Each of these extremely complex tasks were long thought to be impossible by machines, until recent advancements in deep reinforcement learning showed they were possible, today."
},
{
"code": null,
"e": 756,
"s": 696,
"text": "Reinforcement learning is beginning to take over the world."
},
{
"code": null,
"e": 1184,
"s": 756,
"text": "A little over two months ago, I decided I wanted to take part in the revolution, so I set out on a journey to create a profitable Bitcoin trading strategy using state-of-the-art deep reinforcement learning algorithms. While I made quite a bit of progress on that front, I realized that the tooling for this sort of project can be quite daunting to wrap your head around, and as such, it is very easy to get lost in the details."
},
{
"code": null,
"e": 1809,
"s": 1184,
"text": "In between optimizing my previous project for distributed high-performance computing (HPC) systems; getting lost in endless pipelines of data and feature optimizations; and running my head in circles around efficient model set-up, tuning, training, and evaluation; I realized that there had to be a better way of doing things. After countless hours of researching existing projects, spending endless nights watching PyData conference talks, and having many back-and-forth conversations with the hundreds of members of the RL trading Discord community, I realized there weren’t any existing solutions that were all that good."
},
{
"code": null,
"e": 2129,
"s": 1809,
"text": "There were many bits and pieces of great reinforcement learning trading systems spread across the inter-webs, but nothing solid and complete. For this reason, I’ve decided to create an open source Python framework for getting any trading strategy from idea to production, efficiently, using deep reinforcement learning."
},
{
"code": null,
"e": 2378,
"s": 2129,
"text": "Enter TensorTrade. The idea was to create a highly modular framework for building efficient reinforcement learning trading strategies in a composable, maintainable way. Sounds like a mouthful of buzz-words if you ask me, so let’s get into the meat."
},
{
"code": null,
"e": 2407,
"s": 2378,
"text": "We're so pumped to have you!"
},
{
"code": null,
"e": 2442,
"s": 2407,
"text": "\nAlready have an account? Sign In\n"
},
{
"code": null,
"e": 2460,
"s": 2442,
"text": "Table of Contents"
},
{
"code": null,
"e": 2469,
"s": 2460,
"text": "Overview"
},
{
"code": null,
"e": 2479,
"s": 2469,
"text": "RL Primer"
},
{
"code": null,
"e": 2495,
"s": 2479,
"text": "Getting Started"
},
{
"code": null,
"e": 2508,
"s": 2495,
"text": "Installation"
},
{
"code": null,
"e": 2531,
"s": 2508,
"text": "TensorTrade Components"
},
{
"code": null,
"e": 2552,
"s": 2531,
"text": "Trading Environments"
},
{
"code": null,
"e": 2562,
"s": 2552,
"text": "Exchanges"
},
{
"code": null,
"e": 2580,
"s": 2562,
"text": "Feature Pipelines"
},
{
"code": null,
"e": 2598,
"s": 2580,
"text": "Action Strategies"
},
{
"code": null,
"e": 2616,
"s": 2598,
"text": "Reward Strategies"
},
{
"code": null,
"e": 2632,
"s": 2616,
"text": "Learning Agents"
},
{
"code": null,
"e": 2649,
"s": 2632,
"text": "Stable Baselines"
},
{
"code": null,
"e": 2661,
"s": 2649,
"text": "Tensorforce"
},
{
"code": null,
"e": 2680,
"s": 2661,
"text": "Trading Strategies"
},
{
"code": null,
"e": 2704,
"s": 2680,
"text": "Putting it All Together"
},
{
"code": null,
"e": 2728,
"s": 2704,
"text": "Creating an Environment"
},
{
"code": null,
"e": 2747,
"s": 2728,
"text": "Defining the Agent"
},
{
"code": null,
"e": 2767,
"s": 2747,
"text": "Training a Strategy"
},
{
"code": null,
"e": 2788,
"s": 2767,
"text": "Saving and Restoring"
},
{
"code": null,
"e": 2809,
"s": 2788,
"text": "Tuning Your Strategy"
},
{
"code": null,
"e": 2829,
"s": 2809,
"text": "Strategy Evaluation"
},
{
"code": null,
"e": 2842,
"s": 2829,
"text": "Live Trading"
},
{
"code": null,
"e": 2853,
"s": 2842,
"text": "The Future"
},
{
"code": null,
"e": 2868,
"s": 2853,
"text": "Final Thoughts"
},
{
"code": null,
"e": 2881,
"s": 2868,
"text": "Contributing"
},
{
"code": null,
"e": 2892,
"s": 2881,
"text": "References"
},
{
"code": null,
"e": 3254,
"s": 2892,
"text": "TensorTrade is an open source Python framework for training, evaluating, and deploying robust trading strategies using deep reinforcement learning. The framework focuses on being highly composable and extensible, to allow the system to scale from simple trading strategies on a single CPU, to complex investment strategies run on a distribution of HPC machines."
},
{
"code": null,
"e": 3618,
"s": 3254,
"text": "Under the hood, the framework uses many of the APIs from existing machine learning libraries to maintain high quality data pipelines and learning models. One of the main goals of TensorTrade is to enable fast experimentation with algorithmic trading strategies, by leveraging the existing tools and pipelines provided by numpy, pandas, gym, keras, and tensorflow."
},
{
"code": null,
"e": 4000,
"s": 3618,
"text": "Every piece of the framework is split up into re-usable components, allowing you to take advantage of the general use components built by the community, while keeping your proprietary features private. The aim is to simplify the process of testing and deploying robust trading agents using deep reinforcement learning, to allow you and I to focus on creating profitable strategies."
},
{
"code": null,
"e": 4101,
"s": 4000,
"text": "In case your reinforcement learning chops are a bit rusty, let’s quickly go over the basic concepts."
},
{
"code": null,
"e": 4287,
"s": 4101,
"text": "Reinforcement learning (RL) is an area of machine learning concerned with how software agents ought to take actions in an environment so as to maximize some notion of cumulative reward."
},
{
"code": null,
"e": 4418,
"s": 4287,
"text": "Every reinforcement learning problem starts out with an environment and one or more agents that can interact with the environment."
},
{
"code": null,
"e": 4672,
"s": 4418,
"text": "The agent will first observe the environment, then build a model of the current state and the expected value of actions within that environment. Based on that model, the agent will then take the action it has deemed as having the highest expected value."
},
{
"code": null,
"e": 5030,
"s": 4672,
"text": "Based on the effects of the chosen action within the environment, the agent will be rewarded by an amount corresponding to the actual value of that action. The reinforcement learning agent can then, through the process of trial and error (i.e. learning through reinforcement), improve its underlying model and learn to take more rewarding actions over time."
},
{
"code": null,
"e": 5265,
"s": 5030,
"text": "If you still need a bit of refreshment on the subject, there is a link to an article titled Introduction to Deep Reinforcement Learning in the references for this article, which goes much more in-depth into the details. Let’s move on."
},
{
"code": null,
"e": 5498,
"s": 5265,
"text": "The following tutorial should provide enough examples to get you started with creating simple trading strategies using TensorTrade, although you will quickly see the framework is capable of handling much more complex configurations."
},
{
"code": null,
"e": 5564,
"s": 5498,
"text": "You can follow along with Google Colab or the tutorial on Github."
},
{
"code": null,
"e": 5685,
"s": 5564,
"text": "TensorTrade requires Python 3.6 or later, so make sure you’re using a valid version before pip installing the framework."
},
{
"code": null,
"e": 5748,
"s": 5685,
"text": "pip install git+https://github.com/notadamking/tensortrade.git"
},
{
"code": null,
"e": 5907,
"s": 5748,
"text": "To follow this entire tutorial, you will need to install some extra dependencies, such as tensorflow, tensorforce, stable-baselines, ccxt, ta, and stochastic."
},
{
"code": null,
"e": 6027,
"s": 5907,
"text": "pip install git+https://github.com/notadamking/tensortrade.git#egg=tensortrade[tf,tensorforce,baselines,ccxt,ta,fbm] -U"
},
{
"code": null,
"e": 6091,
"s": 6027,
"text": "That’s all the installation necessary! Let’s get into the code."
},
{
"code": null,
"e": 6545,
"s": 6091,
"text": "TensorTrade is built around modular components that together make up a trading strategy. Trading strategies combine reinforcement learning agents with composable trading logic in the form of a gym environment. A trading environment is made up of a set of modular components that can be mixed and matched to create highly diverse trading and investment strategies. I will explain this in further detail later, but for now it is enough to know the basics."
},
{
"code": null,
"e": 6666,
"s": 6545,
"text": "Just like electrical components, the purpose of TensorTrade components is to be able to mix and match them as necessary."
},
{
"code": null,
"e": 6903,
"s": 6666,
"text": "The code snippets in this section should serve as guidelines for creating new strategies and components. There will likely be missing implementation details that will become more clear in a later section, as more components are defined."
},
{
"code": null,
"e": 7124,
"s": 6903,
"text": "A trading environment is a reinforcement learning environment that follows OpenAI’s gym.Env specification. This allows us to leverage many of the existing reinforcement learning models in our trading agent, if we’d like."
},
{
"code": null,
"e": 7278,
"s": 7124,
"text": "Trading environments are fully configurable gym environments with highly composable Exchange, FeaturePipeline, ActionScheme, and RewardScheme components."
},
{
"code": null,
"e": 7365,
"s": 7278,
"text": "The Exchange provides observations to the environment and executes the agent’s trades."
},
{
"code": null,
"e": 7500,
"s": 7365,
"text": "The FeaturePipeline optionally transforms the exchange output into a more meaningful set of features before it is passed to the agent."
},
{
"code": null,
"e": 7570,
"s": 7500,
"text": "The ActionScheme converts the agent’s actions into executable trades."
},
{
"code": null,
"e": 7662,
"s": 7570,
"text": "The RewardScheme calculates the reward for each time step based on the agent’s performance."
},
{
"code": null,
"e": 7831,
"s": 7662,
"text": "If it seems a bit complicated now, it’s really not. That’s all there is to it, now it’s just a matter of composing each of these components into a complete environment."
},
{
"code": null,
"e": 8107,
"s": 7831,
"text": "When the reset method of a TradingEnvironment is called, all of the child components will also be reset. The internal state of each exchange, feature pipeline, transformer, action scheme, and reward scheme will be set back to their default values, ready for the next episode."
},
{
"code": null,
"e": 8298,
"s": 8107,
"text": "Let’s begin with an example environment. As mentioned before, initializing a TradingEnvironment requires an exchange, an action scheme, and a reward scheme, the feature pipeline is optional."
},
{
"code": null,
"e": 8594,
"s": 8298,
"text": "from tensortrade.environments import TradingEnvironmentenvironment = TradingEnvironment(exchange=exchange, action_scheme=action_scheme, reward_scheme=reward_scheme, feature_pipeline=feature_pipeline)"
},
{
"code": null,
"e": 8788,
"s": 8594,
"text": "While the recommended use case is to plug a trading environment into a trading strategy, you can obviously use the trading environment separately, any way you’d otherwise use a gym environment."
},
{
"code": null,
"e": 9035,
"s": 8788,
"text": "Exchanges determine the universe of tradable instruments within a trading environment, return observations to the environment on each time step, and execute trades made within the environment. There are two types of exchanges: live and simulated."
},
{
"code": null,
"e": 9331,
"s": 9035,
"text": "Live exchanges are implementations of Exchange backed by live pricing data and a live trade execution engine. For example, CCXTExchange is a live exchange, which is capable of returning pricing data and executing trades on hundreds of live cryptocurrency exchanges, such as Binance and Coinbase."
},
{
"code": null,
"e": 9488,
"s": 9331,
"text": "import ccxtfrom tensortrade.exchanges.live import CCXTExchangecoinbase = ccxt.coinbasepro()exchange = CCXTExchange(exchange=coinbase, base_instrument='USD')"
},
{
"code": null,
"e": 9637,
"s": 9488,
"text": "There are also exchanges for stock and ETF trading, such as RobinhoodExchange and InteractiveBrokersExchange, but these are still works in progress."
},
{
"code": null,
"e": 9763,
"s": 9637,
"text": "Simulated exchanges, on the other hand, are implementations of Exchange backed by simulated pricing data and trade execution."
},
{
"code": null,
"e": 10184,
"s": 9763,
"text": "For example, FBMExchange is a simulated exchange, which generates pricing and volume data using fractional brownian motion (FBM). Since its price is simulated, the trades it executes must be simulated as well. The exchange uses a simple slippage model to simulate price and volume slippage on trades, though like almost everything in TensorTrade, this slippage model can easily be swapped out for something more complex."
},
{
"code": null,
"e": 10301,
"s": 10184,
"text": "from tensortrade.exchanges.simulated import FBMExchangeexchange = FBMExchange(base_instrument='BTC', timeframe='1h')"
},
{
"code": null,
"e": 10681,
"s": 10301,
"text": "Though the FBMExchange generates fake price and volume data using a stochastic model, it is simply an implementation of SimulatedExchange. Under the hood, SimulatedExchange only requires a data_frame of price history to generate its simulations. This data_frame can either be provided by a coded implementation such as FBMExchange, or at runtime such as in the following example."
},
{
"code": null,
"e": 10871,
"s": 10681,
"text": "import pandas as pdfrom tensortrade.exchanges.simulated import SimulatedExchangedf = pd.read_csv('./data/btc_ohclv_1h.csv')exchange = SimulatedExchange(data_frame=df, base_instrument='USD')"
},
{
"code": null,
"e": 11372,
"s": 10871,
"text": "Feature pipelines are meant for transforming observations from the environment into meaningful features for an agent to learn from. If a pipeline has been added to a particular exchange, then observations will be passed through the FeaturePipeline before being output to the environment. For example, a feature pipeline could normalize all price values, make a time series stationary, add a moving average column, and remove an unnecessary column, all before the observation is returned to the agent."
},
{
"code": null,
"e": 11617,
"s": 11372,
"text": "Feature pipelines can be initialized with an arbitrary number of comma-separated transformers. Each FeatureTransformer needs to be initialized with the set of columns to transform, or if nothing is passed, all input columns will be transformed."
},
{
"code": null,
"e": 11991,
"s": 11617,
"text": "Each feature transformer has a transform method, which will transform a single observation (a pandas.DataFrame) from a larger data set, keeping any necessary state in memory to transform the next frame. For this reason, it is often necessary to reset the FeatureTransformer periodically. This is done automatically each time the parent FeaturePipeline or Exchange is reset."
},
{
"code": null,
"e": 12061,
"s": 11991,
"text": "Let’s create an example pipeline and add it to our existing exchange."
},
{
"code": null,
"e": 12722,
"s": 12061,
"text": "from tensortrade.features import FeaturePipelinefrom tensortrade.features.scalers import MinMaxNormalizerfrom tensortrade.features.stationarity import FractionalDifferencefrom tensortrade.features.indicators import SimpleMovingAverageprice_columns = [\"open\", \"high\", \"low\", \"close\"]normalize_price = MinMaxNormalizer(price_columns)moving_averages = SimpleMovingAverage(price_columns)difference_all = FractionalDifference(difference_order=0.6)feature_pipeline = FeaturePipeline(steps=[normalize_price, moving_averages, difference_all])exchange.feature_pipeline = feature_pipeline"
},
{
"code": null,
"e": 12925,
"s": 12722,
"text": "This feature pipeline normalizes the price values between 0 and 1, before adding some moving average columns and making the entire time series stationary by fractionally differencing consecutive values."
},
{
"code": null,
"e": 13449,
"s": 12925,
"text": "Action schemes define the action space of the environment and convert an agent’s actions into executable trades. For example, if we were using a discrete action space of 3 actions (0 = hold, 1 = buy 100%, 2 = sell 100%), our learning agent does not need to know that returning an action of 1 is equivalent to buying an instrument. Rather, our agent needs to know the reward for returning an action of 1 in specific circumstances, and can leave the implementation details of converting actions to trades to the ActionScheme."
},
{
"code": null,
"e": 13849,
"s": 13449,
"text": "Each action scheme has a get_trade method, which will transform the agent’s specified action into an executable Trade. It is often necessary to store additional state within the scheme, for example to keep track of the currently traded position. This state should be reset each time the action scheme’s reset method is called, which is done automatically when the parent TradingEnvironment is reset."
},
{
"code": null,
"e": 14004,
"s": 13849,
"text": "from tensortrade.actions import DiscreteActionsaction_scheme = DiscreteActions(n_actions=20, instrument_symbol='BTC')"
},
{
"code": null,
"e": 14308,
"s": 14004,
"text": "This discrete action scheme uses 20 discrete actions, which equates to 4 discrete amounts for each of the 5 trade types (market buy/sell, limit buy/sell, and hold). E.g. [0,5,10,15]=hold, 1=market buy 25%, 2=market sell 25%, 3=limit buy 25%, 4=limit sell 25%, 6=market buy 50%, 7=market sell 50%, etc..."
},
{
"code": null,
"e": 14785,
"s": 14308,
"text": "Reward schemes receive the trade taken at each time step and return a float, corresponding to the benefit of that specific action. For example, if the action taken this step was a sell that resulted in positive profits, our RewardScheme could return a positive number to encourage more trades like this. On the other hand, if the action was a sell that resulted in a loss, the scheme could return a negative reward to teach the agent not to make similar actions in the future."
},
{
"code": null,
"e": 14930,
"s": 14785,
"text": "A version of this example algorithm is implemented in the SimpleProfit component, however more complex strategies can obviously be used instead."
},
{
"code": null,
"e": 15359,
"s": 14930,
"text": "Each reward scheme has a get_reward method, which takes in the trade executed at each time step and returns a float corresponding to the value of that action. As with action schemes, it is often necessary to store additional state within a reward scheme for various reasons. This state should be reset each time the reward scheme’s reset method is called, which is done automatically when the parent TradingEnvironment is reset."
},
{
"code": null,
"e": 15434,
"s": 15359,
"text": "from tensortrade.rewards import SimpleProfitreward_scheme = SimpleProfit()"
},
{
"code": null,
"e": 15667,
"s": 15434,
"text": "The simple profit scheme returns a reward of -1 for not holding a trade, 1 for holding a trade, 2 for purchasing an instrument, and a value corresponding to the (positive/negative) profit earned by a trade if an instrument was sold."
},
{
"code": null,
"e": 15863,
"s": 15667,
"text": "Up until this point, we haven’t seen the “deep” part of the deep reinforcement learning framework. This is where learning agents come in. Learning agents are where the math (read: magic) happens."
},
{
"code": null,
"e": 16290,
"s": 15863,
"text": "At each time step, the agent takes the observation from the environment as input, runs it through its underlying model (a neural network most of the time), and outputs the action to take. For example, the observation might be the previous open, high, low, and close price from the exchange. The learning model would take these values as input and output a value corresponding to the action to take, such as buy, sell, or hold."
},
{
"code": null,
"e": 16557,
"s": 16290,
"text": "It is important to remember the learning model has no intuition of the prices or trades being represented by these values. Rather, the model is simply learning which values to output for specific input values or sequences of input values, to earn the highest reward."
},
{
"code": null,
"e": 16889,
"s": 16557,
"text": "In this example, we will be using the Stable Baselines library to provide learning agents to our trading strategy, however, the TensorTrade framework is compatible with many reinforcement learning libraries such as Tensorforce, Ray’s RLLib, OpenAI’s Baselines, Intel’s Coach, or anything from the TensorFlow line such as TF Agents."
},
{
"code": null,
"e": 17183,
"s": 16889,
"text": "It is possible that custom TensorTrade learning agents will be added to this framework in the future, though it will always be a goal of the framework to be interoperable with as many existing reinforcement learning libraries as possible, since there is so much concurrent growth in the space."
},
{
"code": null,
"e": 17258,
"s": 17183,
"text": "But for now, Stable Baselines is simple and powerful enough for our needs."
},
{
"code": null,
"e": 17477,
"s": 17258,
"text": "from stable_baselines.common.policies import MlpLnLstmPolicyfrom stable_baselines import PPO2model = PPO2policy = MlpLnLstmPolicyparams = { \"learning_rate\": 1e-5 }agent = model(policy, environment, model_kwargs=params)"
},
{
"code": null,
"e": 17779,
"s": 17477,
"text": "Note: Stable Baselines is not required to use TensorTrade though it is required for this tutorial. This example uses a GPU-enabled Proximal Policy Optimization model with a layer-normalized LSTM perceptron network. If you would like to know more about Stable Baselines, you can view the Documentation."
},
{
"code": null,
"e": 17791,
"s": 17779,
"text": "Tensorforce"
},
{
"code": null,
"e": 17919,
"s": 17791,
"text": "I will also quickly cover the Tensorforce library to show how simple it is to switch between reinforcement learning frameworks."
},
{
"code": null,
"e": 18476,
"s": 17919,
"text": "from tensorforce.agents import Agentagent_spec = { \"type\": \"ppo_agent\", \"step_optimizer\": { \"type\": \"adam\", \"learning_rate\": 1e-4 }, \"discount\": 0.99, \"likelihood_ratio_clipping\": 0.2,}network_spec = [ dict(type='dense', size=64, activation=\"tanh\"), dict(type='dense', size=32, activation=\"tanh\")]agent = Agent.from_spec(spec=agent_spec, kwargs=dict(network=network_spec, states=environment.states, actions=environment.actions))"
},
{
"code": null,
"e": 18565,
"s": 18476,
"text": "If you would like to know more about Tensorforce agents, you can view the Documentation."
},
{
"code": null,
"e": 18837,
"s": 18565,
"text": "A TradingStrategy consists of a learning agent and one or more trading environments to tune, train, and evaluate on. If only one environment is provided, it will be used for tuning, training, and evaluating. Otherwise, a separate environment may be provided at each step."
},
{
"code": null,
"e": 19347,
"s": 18837,
"text": "from tensortrade.strategies import TensorforceTradingStrategy, StableBaselinesTradingStrategya_strategy = TensorforceTradingStrategy(environment=environment, agent_spec=agent_spec, network_spec=network_spec)b_strategy = StableBaselinesTradingStrategy(environment=environment, model=PPO2, policy=MlpLnLSTMPolicy)"
},
{
"code": null,
"e": 19464,
"s": 19347,
"text": "Don’t worry if you don’t understand the strategy initialization just yet, it will be explained in more detail later."
},
{
"code": null,
"e": 19565,
"s": 19464,
"text": "Now that we know about each component that makes up a TradingStrategy, let’s build and evaluate one."
},
{
"code": null,
"e": 19885,
"s": 19565,
"text": "For a quick recap, a TradingStrategy is made up of a TradingEnvironment and a learning agent. A TradingEnvironment is a gym environment that takes an Exchange, an ActionScheme, a RewardScheme, and an optional FeaturePipeline, and returns observations and rewards that the learning agent can be trained and evaluated on."
},
{
"code": null,
"e": 19971,
"s": 19885,
"text": "The first step is to create a TradingEnvironment using the components outlined above."
},
{
"code": null,
"e": 21096,
"s": 19971,
"text": "from tensortrade.exchanges.simulated import FBMExchangefrom tensortrade.features.scalers import MinMaxNormalizerfrom tensortrade.features.stationarity import FractionalDifferencefrom tensortrade.features import FeaturePipelinefrom tensortrade.rewards import SimpleProfitfrom tensortrade.actions import DiscreteActionsfrom tensortrade.environments import TradingEnvironmentnormalize_price = MinMaxNormalizer([\"open\", \"high\", \"low\", \"close\"])difference = FractionalDifference(difference_order=0.6)feature_pipeline = FeaturePipeline(steps=[normalize_price, difference])exchange = FBMExchange(timeframe='1h', base_instrument='BTC', feature_pipeline=feature_pipeline)reward_scheme = SimpleProfit()action_scheme = DiscreteActions(n_actions=20, instrument_symbol='ETH/BTC')environment = TradingEnvironment(exchange=exchange, action_scheme=action_scheme, reward_scheme=reward_scheme, feature_pipeline=feature_pipeline)"
},
{
"code": null,
"e": 21219,
"s": 21096,
"text": "Simple enough, now environment is a gym environment that can be used by any compatible trading strategy or learning agent."
},
{
"code": null,
"e": 21416,
"s": 21219,
"text": "Now that the environment is set up, it’s time to create our learning agent. Again, we will be using Stable Baselines for this, but feel free to drop in any other reinforcement learning agent here."
},
{
"code": null,
"e": 21705,
"s": 21416,
"text": "Since we are using StableBaselinesTradingStrategy, all we need to do is provide a model type and a policy type for the underlying neural network to be trained. For this example, we will be using a simple proximal policy optimization (PPO) model and a layer-normalized LSTM policy network."
},
{
"code": null,
"e": 21799,
"s": 21705,
"text": "For more examples of model and policy specifications, see the Stable Baselines Documentation."
},
{
"code": null,
"e": 21963,
"s": 21799,
"text": "from stable_baselines.common.policies import MlpLnLstmPolicyfrom stable_baselines import PPO2model = PPO2policy = MlpLnLstmPolicyparams = { \"learning_rate\": 1e-5 }"
},
{
"code": null,
"e": 22052,
"s": 21963,
"text": "Creating our trading strategy is as simple as plugging in our agent and the environment."
},
{
"code": null,
"e": 22356,
"s": 22052,
"text": "from tensortrade.strategies import StableBaselinesTradingStrategystrategy = StableBaselinesTradingStrategy(environment=environment, model=model, policy=policy, model_kwargs=params)"
},
{
"code": null,
"e": 22537,
"s": 22356,
"text": "Then to train the strategy (i.e. train the agent on the current environment), all we need to do is call strategy.run() with the total number of steps or episodes you’d like to run."
},
{
"code": null,
"e": 22642,
"s": 22537,
"text": "performance = strategy.run(steps=100000, episode_callback=stop_early_callback)"
},
{
"code": null,
"e": 22759,
"s": 22642,
"text": "And voila! Three hours and thousands of print statements later, you will see the results of how your agent has done!"
},
{
"code": null,
"e": 23131,
"s": 22759,
"text": "If this feedback loop is a bit slow for you, you can pass a callback function to run, which will be called at the end of each episode. The callback function will pass in a data frame containing the agent’s performance that episode, and expects a bool in return. If True, the agent will continue training, otherwise, the agent will stop and return its overall performance."
},
{
"code": null,
"e": 23418,
"s": 23131,
"text": "All trading strategies are capable of saving their agent to a file, for later restoring. The environment is not saved, as it does not have state that we care about preserving. To save our TensorflowTradingStrategy to a file, we just need to provide the path of the file to our strategy."
},
{
"code": null,
"e": 23467,
"s": 23418,
"text": "strategy.save_agent(path=\"../agents/ppo_btc_1h\")"
},
{
"code": null,
"e": 23576,
"s": 23467,
"text": "To restore the agent from the file, we first need to instantiate our strategy, before calling restore_agent."
},
{
"code": null,
"e": 23931,
"s": 23576,
"text": "from tensortrade.strategies import StableBaselinesTradingStrategystrategy = StableBaselinesTradingStrategy(environment=environment, model=model, policy=policy, model_kwargs=params)strategy.restore_agent(path=\"../agents/ppo_btc/1h\")"
},
{
"code": null,
"e": 24016,
"s": 23931,
"text": "Our strategy is now restored back to its previous state, and ready to be used again."
},
{
"code": null,
"e": 24240,
"s": 24016,
"text": "Sometimes a trading strategy will require tuning a set of hyper-parameters, or features, on an environment to achieve maximum performance. In this case, each TradingStrategy provides an optionally implementable tune method."
},
{
"code": null,
"e": 24470,
"s": 24240,
"text": "Tuning a model is similar to training a model, however in addition to adjusting and saving the weights and biases of the best performing model, the strategy also adjusts and persists the hyper-parameters that produced that model."
},
{
"code": null,
"e": 24974,
"s": 24470,
"text": "from tensortrade.environments import TradingEnvironmentfrom tensortrade.exchanges.simulated import FBMExchangeexchange = FBMExchange(timeframe='1h', base_instrument='BTC', feature_pipeline=feature_pipeline)environment = TradingEnvironment(exchange=exchange, action_scheme=action_scheme, reward_scheme=reward_scheme)strategy.environment = environmenttuned_performance = strategy.tune(episodes=10)"
},
{
"code": null,
"e": 25189,
"s": 24974,
"text": "In this case, the agent will be trained for 10 episodes, with a different set of hyper-parameters each episode. The best set will be saved within the strategy, and used any time strategy.run() is called thereafter."
},
{
"code": null,
"e": 25392,
"s": 25189,
"text": "Now that we’ve tuned and trained our agent, it’s time to see how well it performs. To evaluate our strategy’s performance on unseen data, we will need to run it on a new environment backed by such data."
},
{
"code": null,
"e": 25990,
"s": 25392,
"text": "from pandas import pdfrom tensortrade.environments import TradingEnvironmentfrom tensortrade.exchanges.simulated import SimulatedExchangedf = pd.read_csv('./btc_ohlcv_1h.csv')exchange = SimulatedExchange(data_frame=df, base_instrument='BTC', feature_pipeline=feature_pipeline)environment = TradingEnvironment(exchange=exchange, action_scheme=action_scheme, reward_scheme=reward_scheme)strategy.environment = environmenttest_performance = strategy.run(episodes=1, testing=True)"
},
{
"code": null,
"e": 26142,
"s": 25990,
"text": "When complete, strategy.run returns a Pandas data frame of the agent’s performance, including the net worth and balance of the agent at each time step."
},
{
"code": null,
"e": 26410,
"s": 26142,
"text": "Once you’ve built a profitable trading strategy, trained an agent to trade it properly, and ensured its “generalize-ability” to new data sets, all there is left to do is profit. Using a live exchange such as CCXTExchange, you can plug your strategy in and let it run!"
},
{
"code": null,
"e": 26888,
"s": 26410,
"text": "While the gambler in you may enjoy starting a strategy and letting it run without bounds, the more risk averse of you can use a trade_callback, which will be called each time the strategy makes a trade. This callback function, similar to the episode callback, will pass in a data frame containing the agent’s overall performance, and expects a bool in return. If True, the agent will continue trading, otherwise, the agent will stop and return its performance over the session."
},
{
"code": null,
"e": 27614,
"s": 26888,
"text": "import ccxtfrom tensortrade.environments import TradingEnvironmentfrom tensortrade.strategies import StableBaselinesTradingStrategyfrom tensortrade.exchanges.live import CCXTExchangecoinbase = ccxt.coinbasepro(...)exchange = CCXTExchange(exchange=coinbase, timeframe='1h', base_instrument='USD', feature_pipeline=feature_pipeline)environment = TradingEnvironment(exchange=exchange, action_scheme=action_scheme, reward_scheme=reward_scheme)strategy.environment = environmentstrategy.restore_agent(path=\"../agents/ppo_btc/1h\")live_performance = strategy.run(steps=0, trade_callback=episode_cb)"
},
{
"code": null,
"e": 27685,
"s": 27614,
"text": "Passing steps=0 instructs the strategy to run until otherwise stopped."
},
{
"code": null,
"e": 27943,
"s": 27685,
"text": "That’s all there is to it! As you can see, it is quite simple to build complex trading strategies using simple components and deep reinforcement learning. So what are you waiting for? Dive in, get your hands dirty, and see what’s possible using TensorTrade."
},
{
"code": null,
"e": 28254,
"s": 27943,
"text": "Currently, the framework is in its early stages. The focus so far has been to get a working prototype, with all of the necessary building blocks to create highly profitable strategies. The next step is to build a roadmap for the future, and decide which upcoming building blocks are important to the community."
},
{
"code": null,
"e": 28436,
"s": 28254,
"text": "Soon, we will see highly informative visualizations of the environments added to the framework, as well as much more in-depth strategies on more exchanges, trading more instruments."
},
{
"code": null,
"e": 28595,
"s": 28436,
"text": "The sky is the limit. The groundwork (i.e. framework) has been laid, it’s now up to the community to decide what’s next. I hope that you will be a part of it."
},
{
"code": null,
"e": 28976,
"s": 28595,
"text": "TensorTrade is a powerful framework capable of building highly modular, high performance trading systems. It is fairly simple and easy to experiment with new trading and investment strategies, while allowing you to leverage components from one strategy in another. But don’t take my word for it, create a strategy of your own and start teaching your robots to take over the world!"
},
{
"code": null,
"e": 29421,
"s": 28976,
"text": "While this tutorial should be enough to get you started, there is still quite a lot more to learn if you want to create a profitable trading strategy. I encourage you to head over to the Github and dive into the codebase, or take a look at our documentation at tensortrade.org. There is also quite an active Discord community with nearly 1000 total members, so if you have questions, feedback, or feature requests, feel free to drop them there!"
},
{
"code": null,
"e": 29797,
"s": 29421,
"text": "I’ve gotten the project to a highly usable state. Though, my time is limited, and I believe there are many of you out there who could make valuable contributions to the open source codebase. So if you are a developer or data scientist with an interest in building state-of-the-art trading systems, I’d love to see you open a pull request, even if its just a simple test case!"
},
{
"code": null,
"e": 29929,
"s": 29797,
"text": "Others have asked how they can contribute to the project without writing code. There are currently three ways that you can do that."
},
{
"code": null,
"e": 30734,
"s": 29929,
"text": "Write code or documentation for the TensorTrade framework. Many issues on the Github are funded through Gitcoin smart contracts, so you can actually get paid to contribute. To date, almost 10 ETH (~$2000 USD), donated by the community has used to pay open source developers for their contributions to the framework.Fund this project with either Bitcoin or Ethereum. These donations are used to fund our Gitcoin smart contracts, which allows anyone who contributes quality code and documentation to get paid for their contributions.Sponsor me on Github. Github is currently matching all donations 1:1, up to $5,000, so there has never been a better time to sponsor my work and the TensorTrade’s development. All sponsorships go directly towards the funding of the open source development of the framework."
},
{
"code": null,
"e": 31050,
"s": 30734,
"text": "Write code or documentation for the TensorTrade framework. Many issues on the Github are funded through Gitcoin smart contracts, so you can actually get paid to contribute. To date, almost 10 ETH (~$2000 USD), donated by the community has used to pay open source developers for their contributions to the framework."
},
{
"code": null,
"e": 31267,
"s": 31050,
"text": "Fund this project with either Bitcoin or Ethereum. These donations are used to fund our Gitcoin smart contracts, which allows anyone who contributes quality code and documentation to get paid for their contributions."
},
{
"code": null,
"e": 31541,
"s": 31267,
"text": "Sponsor me on Github. Github is currently matching all donations 1:1, up to $5,000, so there has never been a better time to sponsor my work and the TensorTrade’s development. All sponsorships go directly towards the funding of the open source development of the framework."
},
{
"code": null,
"e": 31771,
"s": 31541,
"text": "Thanks for reading! As always, all of the code for this tutorial can be found on my GitHub. Leave a comment below if you have any questions or feedback, I’d love to hear from you! I can also be reached on Twitter at @notadamking."
},
{
"code": null,
"e": 31846,
"s": 31771,
"text": "You can also sponsor me on Github Sponsors or Patreon via the links below."
},
{
"code": null,
"e": 31857,
"s": 31846,
"text": "github.com"
},
{
"code": null,
"e": 31869,
"s": 31857,
"text": "patreon.com"
},
{
"code": null,
"e": 32099,
"s": 31869,
"text": "[1.] Introduction to Deep Reinforcement Learning Hui, Jonathan. “RL- Introduction to Deep Reinforcement Learning.” Medium, 7 Jan. 2019, https://medium.com/@jonathan_hui/rl-introduction-to-deep-reinforcement-learning-35c25e04c199."
},
{
"code": null,
"e": 32287,
"s": 32099,
"text": "[2.] Policy Gradient AlgorithmsWeng, Lilian. “Policy Gradient Algorithms.” Lil’Log, 8 Apr. 2018, https://lilianweng.github.io/lil-log/2018/04/08/policy-gradient-algorithms.html#reinforce."
},
{
"code": null,
"e": 32441,
"s": 32287,
"text": "[3.] Clean Code: A Handbook of Agile Software CraftsmanshipMartin, Robert C. Clean Code: a Handbook of Agile Software Craftsmanship. Prentice Hall, 2010."
}
] |
How to get smooth interpolation when using pcolormesh (Matplotlib)?
|
To get smooth interpolation when using pcolormesh, we can use shading="gouraud" class by name.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create data, x and y using numpy meshgrid.
Create data, x and y using numpy meshgrid.
Create a pseudocolor plot with a non-regular rectangular grid using pcolormesh() method.
Create a pseudocolor plot with a non-regular rectangular grid using pcolormesh() method.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pylab as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.random((3, 3))
x = np.arange(0, 3, 1)
y = np.arange(0, 3, 1)
x, y = np.meshgrid(x, y)
plt.pcolormesh(x, y, data, cmap='RdBu', shading='gouraud')
plt.show()
|
[
{
"code": null,
"e": 1157,
"s": 1062,
"text": "To get smooth interpolation when using pcolormesh, we can use shading=\"gouraud\" class by name."
},
{
"code": null,
"e": 1233,
"s": 1157,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1309,
"s": 1233,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1352,
"s": 1309,
"text": "Create data, x and y using numpy meshgrid."
},
{
"code": null,
"e": 1395,
"s": 1352,
"text": "Create data, x and y using numpy meshgrid."
},
{
"code": null,
"e": 1484,
"s": 1395,
"text": "Create a pseudocolor plot with a non-regular rectangular grid using pcolormesh() method."
},
{
"code": null,
"e": 1573,
"s": 1484,
"text": "Create a pseudocolor plot with a non-regular rectangular grid using pcolormesh() method."
},
{
"code": null,
"e": 1615,
"s": 1573,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1657,
"s": 1615,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1971,
"s": 1657,
"text": "import matplotlib.pylab as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndata = np.random.random((3, 3))\nx = np.arange(0, 3, 1)\ny = np.arange(0, 3, 1)\nx, y = np.meshgrid(x, y)\n\nplt.pcolormesh(x, y, data, cmap='RdBu', shading='gouraud')\n\nplt.show()"
}
] |
Set size() method in Java with Example - GeeksforGeeks
|
31 Dec, 2018
The java.util.Set.size() method is used to get the size of the Set or the number of elements present in the Set.
Syntax:
int size()
Parameters: This method does not takes any parameter.
Return Value: The method returns the size or the number of elements present in the Set.
Below program illustrate the java.util.Set.size() method:
// Java code to illustrate Set.size() method import java.util.*; public class SetDemo { public static void main(String args[]) { // Creating an empty Set Set<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add("Welcome"); set.add("To"); set.add("Geeks"); set.add("4"); set.add("Geeks"); // Displaying the Set System.out.println("Set: " + set); // Displaying the size of the Set System.out.println("The size of the set is: " + set.size()); }}
Set: [4, Geeks, Welcome, To]
The size of the set is: 4
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#size()
Java-Collections
Java-Functions
java-set
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
|
[
{
"code": null,
"e": 24461,
"s": 24433,
"text": "\n31 Dec, 2018"
},
{
"code": null,
"e": 24574,
"s": 24461,
"text": "The java.util.Set.size() method is used to get the size of the Set or the number of elements present in the Set."
},
{
"code": null,
"e": 24582,
"s": 24574,
"text": "Syntax:"
},
{
"code": null,
"e": 24594,
"s": 24582,
"text": "int size()\n"
},
{
"code": null,
"e": 24648,
"s": 24594,
"text": "Parameters: This method does not takes any parameter."
},
{
"code": null,
"e": 24736,
"s": 24648,
"text": "Return Value: The method returns the size or the number of elements present in the Set."
},
{
"code": null,
"e": 24794,
"s": 24736,
"text": "Below program illustrate the java.util.Set.size() method:"
},
{
"code": "// Java code to illustrate Set.size() method import java.util.*; public class SetDemo { public static void main(String args[]) { // Creating an empty Set Set<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add(\"Welcome\"); set.add(\"To\"); set.add(\"Geeks\"); set.add(\"4\"); set.add(\"Geeks\"); // Displaying the Set System.out.println(\"Set: \" + set); // Displaying the size of the Set System.out.println(\"The size of the set is: \" + set.size()); }}",
"e": 25379,
"s": 24794,
"text": null
},
{
"code": null,
"e": 25435,
"s": 25379,
"text": "Set: [4, Geeks, Welcome, To]\nThe size of the set is: 4\n"
},
{
"code": null,
"e": 25514,
"s": 25435,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#size()"
},
{
"code": null,
"e": 25531,
"s": 25514,
"text": "Java-Collections"
},
{
"code": null,
"e": 25546,
"s": 25531,
"text": "Java-Functions"
},
{
"code": null,
"e": 25555,
"s": 25546,
"text": "java-set"
},
{
"code": null,
"e": 25560,
"s": 25555,
"text": "Java"
},
{
"code": null,
"e": 25565,
"s": 25560,
"text": "Java"
},
{
"code": null,
"e": 25582,
"s": 25565,
"text": "Java-Collections"
},
{
"code": null,
"e": 25680,
"s": 25582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25689,
"s": 25680,
"text": "Comments"
},
{
"code": null,
"e": 25702,
"s": 25689,
"text": "Old Comments"
},
{
"code": null,
"e": 25753,
"s": 25702,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 25783,
"s": 25753,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 25814,
"s": 25783,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 25833,
"s": 25814,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 25851,
"s": 25833,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 25871,
"s": 25851,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 25903,
"s": 25871,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 25927,
"s": 25903,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 25946,
"s": 25927,
"text": "LinkedList in Java"
}
] |
Difference between DELETE and TRUNCATE - GeeksforGeeks
|
12 Jan, 2022
1. DELETE : DELETE is a DML(Data Manipulation Language) command and is used when we specify the row(tuple) that we want to remove or delete from the table or relation. The DELETE command can contain a WHERE clause. If the WHERE clause is used with the DELETE command then it removes or deletes only those rows(tuple) that satisfy the condition otherwise by default it removes all the tuples(rows) from the table. Remember that DELETE logs the row deletions.
Syntax of DELETE command :
DELETE FROM TableName
WHERE condition;
2. TRUNCATE : TRUNCATE is a DDL(Data Definition Language) command and is used to delete all the rows or tuples from a table. Unlike the DELETE command, the TRUNCATE command does not contain a WHERE clause. In the TRUNCATE command, the transaction log for each deleted data page is not recorded. Unlike the DELETE command, the TRUNCATE command is fast. We cannot roll back the data after using the TRUNCATE command.
Syntax of TRUNCATE command:-
TRUNCATE TABLE TableName;
Let’s see the difference between DELETE and TRUNCATE command:-
MKS075
kumarsanu805128
gbothra38
azamh64
SQL-Clauses
DBMS
Difference Between
GATE CS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of B-Tree
Difference between Clustered and Non-clustered index
CTE in SQL
Introduction of ER Model
SQL | Views
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
|
[
{
"code": null,
"e": 24072,
"s": 24044,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 24531,
"s": 24072,
"text": "1. DELETE : DELETE is a DML(Data Manipulation Language) command and is used when we specify the row(tuple) that we want to remove or delete from the table or relation. The DELETE command can contain a WHERE clause. If the WHERE clause is used with the DELETE command then it removes or deletes only those rows(tuple) that satisfy the condition otherwise by default it removes all the tuples(rows) from the table. Remember that DELETE logs the row deletions."
},
{
"code": null,
"e": 24559,
"s": 24531,
"text": "Syntax of DELETE command : "
},
{
"code": null,
"e": 24600,
"s": 24559,
"text": "DELETE FROM TableName \nWHERE condition; "
},
{
"code": null,
"e": 25016,
"s": 24600,
"text": "2. TRUNCATE : TRUNCATE is a DDL(Data Definition Language) command and is used to delete all the rows or tuples from a table. Unlike the DELETE command, the TRUNCATE command does not contain a WHERE clause. In the TRUNCATE command, the transaction log for each deleted data page is not recorded. Unlike the DELETE command, the TRUNCATE command is fast. We cannot roll back the data after using the TRUNCATE command. "
},
{
"code": null,
"e": 25046,
"s": 25016,
"text": "Syntax of TRUNCATE command:- "
},
{
"code": null,
"e": 25074,
"s": 25046,
"text": "TRUNCATE TABLE TableName; "
},
{
"code": null,
"e": 25138,
"s": 25074,
"text": "Let’s see the difference between DELETE and TRUNCATE command:- "
},
{
"code": null,
"e": 25145,
"s": 25138,
"text": "MKS075"
},
{
"code": null,
"e": 25161,
"s": 25145,
"text": "kumarsanu805128"
},
{
"code": null,
"e": 25171,
"s": 25161,
"text": "gbothra38"
},
{
"code": null,
"e": 25179,
"s": 25171,
"text": "azamh64"
},
{
"code": null,
"e": 25191,
"s": 25179,
"text": "SQL-Clauses"
},
{
"code": null,
"e": 25196,
"s": 25191,
"text": "DBMS"
},
{
"code": null,
"e": 25215,
"s": 25196,
"text": "Difference Between"
},
{
"code": null,
"e": 25223,
"s": 25215,
"text": "GATE CS"
},
{
"code": null,
"e": 25227,
"s": 25223,
"text": "SQL"
},
{
"code": null,
"e": 25232,
"s": 25227,
"text": "DBMS"
},
{
"code": null,
"e": 25236,
"s": 25232,
"text": "SQL"
},
{
"code": null,
"e": 25334,
"s": 25236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25357,
"s": 25334,
"text": "Introduction of B-Tree"
},
{
"code": null,
"e": 25410,
"s": 25357,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 25421,
"s": 25410,
"text": "CTE in SQL"
},
{
"code": null,
"e": 25446,
"s": 25421,
"text": "Introduction of ER Model"
},
{
"code": null,
"e": 25458,
"s": 25446,
"text": "SQL | Views"
},
{
"code": null,
"e": 25489,
"s": 25458,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 25529,
"s": 25489,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 25561,
"s": 25529,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 25622,
"s": 25561,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
How to find the number of links in a document in JavaScript?
|
Javascript DOM has provided many properties to get the details regarding a document. It has provided a method called document.links.length to get the number of links that a document contains. This method won't disturb the code's normal functionality.
In the following example, there are three links provided in the code. Using the DOM property document.links.length the number of links were displayed in the output as shown.
Live Demo
<html>
<body>
<a href="https://www.tutorialspoint.com/javascript/index.htm">Javascript</a><br>
<a href="https://www.tutorialspoint.com/php/index.htm">Php</a><br>
<a href="https://www.tutorialspoint.com/java8/index.htm">Php</a><br>
<p id="links"></p>
<script>
document.getElementById("links").innerHTML =
"The number of links are: " + document.links.length;
</script>
</body>
</html>
Javascript
Php
Java
The number of links are: 3
In the following example, there are two links provided in the code. Using the DOM property document.links.length the number of links were displayed in the output as shown.
Live Demo
<html>
<body>
<a href="https://www.tutorialspoint.com/javascript/index.htm">Javascript</a><br>
<a href="https://www.tutorialspoint.com/bitcoin/index.htm">Bitcoin</a></br>
<script>
document.write("The number of links are: " + document.links.length);
</script>
</body>
</html>
Javascript
Bitcoin
The number of links are: 2
|
[
{
"code": null,
"e": 1313,
"s": 1062,
"text": "Javascript DOM has provided many properties to get the details regarding a document. It has provided a method called document.links.length to get the number of links that a document contains. This method won't disturb the code's normal functionality."
},
{
"code": null,
"e": 1487,
"s": 1313,
"text": "In the following example, there are three links provided in the code. Using the DOM property document.links.length the number of links were displayed in the output as shown."
},
{
"code": null,
"e": 1497,
"s": 1487,
"text": "Live Demo"
},
{
"code": null,
"e": 1895,
"s": 1497,
"text": "<html>\n<body>\n <a href=\"https://www.tutorialspoint.com/javascript/index.htm\">Javascript</a><br>\n <a href=\"https://www.tutorialspoint.com/php/index.htm\">Php</a><br>\n <a href=\"https://www.tutorialspoint.com/java8/index.htm\">Php</a><br>\n<p id=\"links\"></p>\n<script>\n document.getElementById(\"links\").innerHTML =\n \"The number of links are: \" + document.links.length;\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1942,
"s": 1895,
"text": "Javascript\nPhp\nJava\nThe number of links are: 3"
},
{
"code": null,
"e": 2114,
"s": 1942,
"text": "In the following example, there are two links provided in the code. Using the DOM property document.links.length the number of links were displayed in the output as shown."
},
{
"code": null,
"e": 2124,
"s": 2114,
"text": "Live Demo"
},
{
"code": null,
"e": 2408,
"s": 2124,
"text": "<html>\n<body>\n <a href=\"https://www.tutorialspoint.com/javascript/index.htm\">Javascript</a><br>\n <a href=\"https://www.tutorialspoint.com/bitcoin/index.htm\">Bitcoin</a></br>\n<script>\n document.write(\"The number of links are: \" + document.links.length);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2454,
"s": 2408,
"text": "Javascript\nBitcoin\nThe number of links are: 2"
}
] |
K-th lexicographically smallest unique substring of a given string - GeeksforGeeks
|
25 May, 2021
Given a string S. The task is to print the K-th lexicographically the smallest one among the different substrings of s.A substring of s is a string obtained by taking out a non-empty contiguous part in s. For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z, and an empty string are not. Also, we say that substrings are different when they are different as strings.
Examples:
Input: str = “aba”, k = 4 Output: b All unique substrings are a, ab, aba, b, ba. Thus the 4th lexicographically smallest substring is b.
Input: str = “geeksforgeeks”, k = 5 Output: eeksf
Approach: For an arbitrary string t, each of its proper suffixes is lexicographically smaller than t, and the lexicographic rank of t is at least |t|. Thus, the length of the answer is at most K. Generate all substrings of s whose lengths are at most K. Sort them, unique them, and print the K-th one, where N = |S|.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; void kThLexString(string st, int k, int n){ // Set to store the unique substring set<string> z; for(int i = 0; i < n; i++) { // String to create each substring string pp; for(int j = i; j < i + k; j++) { if (j >= n) break; pp += st[j]; // Adding to set z.insert(pp); } } // Converting set into a list vector<string> fin(z.begin(), z.end()); // Sorting the strings int the list // into lexicographical order sort(fin.begin(), fin.end()); // Printing kth substring cout << fin[k - 1];} // Driver codeint main(){ string s = "geeksforgeeks"; int k = 5; int n = s.length(); kThLexString(s, k, n);} // This code is contributed by yatinagg
// Java implementation of// the above approachimport java.util.*;class GFG{ public static void kThLexString(String st, int k, int n){ // Set to store the unique substring Set<String> z = new HashSet<String>(); for(int i = 0; i < n; i++) { // String to create each substring String pp = ""; for(int j = i; j < i + k; j++) { if (j >= n) break; pp += st.charAt(j); // Adding to set z.add(pp); } } // Converting set into a list Vector<String> fin = new Vector<String>(); fin.addAll(z); // Sorting the strings int the list // into lexicographical order Collections.sort(fin); // Printing kth substring System.out.print(fin.get(k - 1));} // Driver Codepublic static void main(String[] args){ String s = "geeksforgeeks"; int k = 5; int n = s.length(); kThLexString(s, k, n);}} // This code is contributed by divyeshrabadiya07
# Python3 implementation of the above approachdef kThLexString(st, k, n): # Set to store the unique substring z = set() for i in range(n): # String to create each substring pp = "" for j in range(i, i + k): if (j >= n): break pp += s[j] # adding to set z.add(pp) # converting set into a list fin = list(z) # sorting the strings int the list # into lexicographical order fin.sort() # printing kth substring print(fin[k - 1]) s = "geeksforgeeks" k = 5 n = len(s)kThLexString(s, k, n)
// C# implementation of// the above approachusing System;using System.Collections.Generic;using System.Collections; class GFG{ public static void kThLexString(string st, int k, int n){ // Set to store the unique substring HashSet<string> z = new HashSet<string>(); for(int i = 0; i < n; i++) { // String to create each substring string pp = ""; for(int j = i; j < i + k; j++) { if (j >= n) break; pp += st[j]; // Adding to set z.Add(pp); } } // Converting set into a list ArrayList fin = new ArrayList(); foreach(string s in z) { fin.Add(s); } // Sorting the strings int the list // into lexicographical order fin.Sort(); // Printing kth substring Console.Write(fin[k - 1]);} // Driver Codepublic static void Main(string[] args){ string s = "geeksforgeeks"; int k = 5; int n = s.Length; kThLexString(s, k, n);}} // This code is contributed by rutvik_56
<script> // JavaScript implementation of the above approach function kThLexString(st, k, n){ // Set to store the unique substring var z = new Set(); for(var i = 0; i < n; i++) { // String to create each substring var pp = ""; for(var j = i; j < i + k; j++) { if (j >= n) break; pp += st[j]; // Adding to set z.add(pp); } } var fin = []; z.forEach(element => { fin.push(element); }); fin.sort(); // Printing kth substring document.write( fin[k-1]);} // Driver code var s = "geeksforgeeks";var k = 5;var n = s.length;kThLexString(s, k, n); </script>
eeksf
yatinagg
divyeshrabadiya07
rutvik_56
famously
lexicographic-ordering
substring
Greedy
Sorting
Strings
Strings
Greedy
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum
Program for First Fit algorithm in Memory Management
Optimal Page Replacement Algorithm
Program for Best Fit algorithm in Memory Management
Bin Packing Problem (Minimize number of used Bins)
|
[
{
"code": null,
"e": 24929,
"s": 24901,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 25320,
"s": 24929,
"text": "Given a string S. The task is to print the K-th lexicographically the smallest one among the different substrings of s.A substring of s is a string obtained by taking out a non-empty contiguous part in s. For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z, and an empty string are not. Also, we say that substrings are different when they are different as strings."
},
{
"code": null,
"e": 25330,
"s": 25320,
"text": "Examples:"
},
{
"code": null,
"e": 25467,
"s": 25330,
"text": "Input: str = “aba”, k = 4 Output: b All unique substrings are a, ab, aba, b, ba. Thus the 4th lexicographically smallest substring is b."
},
{
"code": null,
"e": 25517,
"s": 25467,
"text": "Input: str = “geeksforgeeks”, k = 5 Output: eeksf"
},
{
"code": null,
"e": 25835,
"s": 25517,
"text": "Approach: For an arbitrary string t, each of its proper suffixes is lexicographically smaller than t, and the lexicographic rank of t is at least |t|. Thus, the length of the answer is at most K. Generate all substrings of s whose lengths are at most K. Sort them, unique them, and print the K-th one, where N = |S|. "
},
{
"code": null,
"e": 25887,
"s": 25835,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25891,
"s": 25887,
"text": "C++"
},
{
"code": null,
"e": 25896,
"s": 25891,
"text": "Java"
},
{
"code": null,
"e": 25904,
"s": 25896,
"text": "Python3"
},
{
"code": null,
"e": 25907,
"s": 25904,
"text": "C#"
},
{
"code": null,
"e": 25918,
"s": 25907,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; void kThLexString(string st, int k, int n){ // Set to store the unique substring set<string> z; for(int i = 0; i < n; i++) { // String to create each substring string pp; for(int j = i; j < i + k; j++) { if (j >= n) break; pp += st[j]; // Adding to set z.insert(pp); } } // Converting set into a list vector<string> fin(z.begin(), z.end()); // Sorting the strings int the list // into lexicographical order sort(fin.begin(), fin.end()); // Printing kth substring cout << fin[k - 1];} // Driver codeint main(){ string s = \"geeksforgeeks\"; int k = 5; int n = s.length(); kThLexString(s, k, n);} // This code is contributed by yatinagg",
"e": 26819,
"s": 25918,
"text": null
},
{
"code": "// Java implementation of// the above approachimport java.util.*;class GFG{ public static void kThLexString(String st, int k, int n){ // Set to store the unique substring Set<String> z = new HashSet<String>(); for(int i = 0; i < n; i++) { // String to create each substring String pp = \"\"; for(int j = i; j < i + k; j++) { if (j >= n) break; pp += st.charAt(j); // Adding to set z.add(pp); } } // Converting set into a list Vector<String> fin = new Vector<String>(); fin.addAll(z); // Sorting the strings int the list // into lexicographical order Collections.sort(fin); // Printing kth substring System.out.print(fin.get(k - 1));} // Driver Codepublic static void main(String[] args){ String s = \"geeksforgeeks\"; int k = 5; int n = s.length(); kThLexString(s, k, n);}} // This code is contributed by divyeshrabadiya07",
"e": 27828,
"s": 26819,
"text": null
},
{
"code": "# Python3 implementation of the above approachdef kThLexString(st, k, n): # Set to store the unique substring z = set() for i in range(n): # String to create each substring pp = \"\" for j in range(i, i + k): if (j >= n): break pp += s[j] # adding to set z.add(pp) # converting set into a list fin = list(z) # sorting the strings int the list # into lexicographical order fin.sort() # printing kth substring print(fin[k - 1]) s = \"geeksforgeeks\" k = 5 n = len(s)kThLexString(s, k, n)",
"e": 28433,
"s": 27828,
"text": null
},
{
"code": "// C# implementation of// the above approachusing System;using System.Collections.Generic;using System.Collections; class GFG{ public static void kThLexString(string st, int k, int n){ // Set to store the unique substring HashSet<string> z = new HashSet<string>(); for(int i = 0; i < n; i++) { // String to create each substring string pp = \"\"; for(int j = i; j < i + k; j++) { if (j >= n) break; pp += st[j]; // Adding to set z.Add(pp); } } // Converting set into a list ArrayList fin = new ArrayList(); foreach(string s in z) { fin.Add(s); } // Sorting the strings int the list // into lexicographical order fin.Sort(); // Printing kth substring Console.Write(fin[k - 1]);} // Driver Codepublic static void Main(string[] args){ string s = \"geeksforgeeks\"; int k = 5; int n = s.Length; kThLexString(s, k, n);}} // This code is contributed by rutvik_56",
"e": 29560,
"s": 28433,
"text": null
},
{
"code": "<script> // JavaScript implementation of the above approach function kThLexString(st, k, n){ // Set to store the unique substring var z = new Set(); for(var i = 0; i < n; i++) { // String to create each substring var pp = \"\"; for(var j = i; j < i + k; j++) { if (j >= n) break; pp += st[j]; // Adding to set z.add(pp); } } var fin = []; z.forEach(element => { fin.push(element); }); fin.sort(); // Printing kth substring document.write( fin[k-1]);} // Driver code var s = \"geeksforgeeks\";var k = 5;var n = s.length;kThLexString(s, k, n); </script>",
"e": 30277,
"s": 29560,
"text": null
},
{
"code": null,
"e": 30283,
"s": 30277,
"text": "eeksf"
},
{
"code": null,
"e": 30294,
"s": 30285,
"text": "yatinagg"
},
{
"code": null,
"e": 30312,
"s": 30294,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 30322,
"s": 30312,
"text": "rutvik_56"
},
{
"code": null,
"e": 30331,
"s": 30322,
"text": "famously"
},
{
"code": null,
"e": 30354,
"s": 30331,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 30364,
"s": 30354,
"text": "substring"
},
{
"code": null,
"e": 30371,
"s": 30364,
"text": "Greedy"
},
{
"code": null,
"e": 30379,
"s": 30371,
"text": "Sorting"
},
{
"code": null,
"e": 30387,
"s": 30379,
"text": "Strings"
},
{
"code": null,
"e": 30395,
"s": 30387,
"text": "Strings"
},
{
"code": null,
"e": 30402,
"s": 30395,
"text": "Greedy"
},
{
"code": null,
"e": 30410,
"s": 30402,
"text": "Sorting"
},
{
"code": null,
"e": 30508,
"s": 30410,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30517,
"s": 30508,
"text": "Comments"
},
{
"code": null,
"e": 30530,
"s": 30517,
"text": "Old Comments"
},
{
"code": null,
"e": 30621,
"s": 30530,
"text": "Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum"
},
{
"code": null,
"e": 30674,
"s": 30621,
"text": "Program for First Fit algorithm in Memory Management"
},
{
"code": null,
"e": 30709,
"s": 30674,
"text": "Optimal Page Replacement Algorithm"
},
{
"code": null,
"e": 30761,
"s": 30709,
"text": "Program for Best Fit algorithm in Memory Management"
}
] |
5 Jupyter Extensions to Improve your Productivity | by Cornellius Yudha Wijaya | Towards Data Science
|
Jupyter Notebook is a popular IDE for many data experts for analyzing data and developing machine learning models because of its useability and utility. The Notebook is already a beginner-friendly IDE to use and could be extended even more to improve your data activity productivity with a bit of tweak.
For the above reasons, I want to outline my five Jupyter extensions to improve your productivity in this article. Let's get into it!
Have you been in a situation where your Jupyter Notebook became slow or crashed because of memory issues? This case often happens when we explore big data or heavy modelling computation processes that take a huge chunk of memory.
To control the memory issues, we could use the jupyter-resource-usage extensions to display the memory usage in our Notebook. This extension work is simple; all the resources in your current notebook servers and children would be displayed on the top right side. Let's try to install the extensions.
pip install jupyter-resource-usage
When you have finished installing the package, try to restart the Jupyter and access your Jupyter Notebook. The memory display should be available in your Notebook now.
If you want to limit the allocated resources, you could control them using various methods explained here.
Every time you work in a new environment or develop a new project, you must import all the required package. It is not a dealbreaker, but sometimes it isn't enjoyable to import all the packages all over again. This is why pyforest were developed.
The pyforest extensions is an auto-import popular python package from Bamboolib developer. This extension transform your workflow to automatically importing the so popular packages such as pandas, numpy, sklearnAnd many more. You can check the list here.
Let's try to install the pyforest extension.
pip install --upgrade pyforestpython -m pyforest install_extensions
After you have finished installing the package, you should restart the Jupyter for pyforest auto-import to take place. Let's see if the extension has taken place or not.
As you can see from the above image, I did not import any seaborn or pandas package, but I could automatically use it in my Jupyter Notebook. The pyforest extension would automatically import this package with the popular abbreviation (seaborn as sns, pandas as pd, etc.).
You don't need to worry about memory allocation because pyforest did not import all the packages initially but only the required package when you execute the code that uses the particular package.
Like the name imply, jupyter-themes is a Jupyter Notebook extension to change the theme. This extension also changes our plotting, markdown, pandas dataframe, and many more. So, the themes change is not limited only to the Jupyter Notebook background.
Let's try to install the jupyter-themes. You could use the following code to install the package.
pip install jupyterthemes
After installation, you could access the jupyter-themes via CLI to change the Jupyter Notebook theme. First, let's see what themes are available using the following code in our command prompt.
jt -l
There are nine themes available in default for us to select. Let's try one of the themes, let's say the 'chesterish'.
jt -t chesterish
To see the changes in your Jupyter Notebook, you need to restart the server. After that, you will see your Notebook similar to the below image.
If you want to reset the theme into the default one, you could reset it by using the following code.
jt -r
You could still do many things with jupyter-theme, such as controlling the colour, cell width, hiding the specific toolbar, and many more. You could read all the commands on their page.
The jupyter-notify extension is a Jupyter Notebook extension to notify us when our cell has done running. This extension is useful when running a time-consuming modelling process or cleaning activity and you want to do something else while waiting.
First, we need to install the package by using the following code.
pip install jupyternotify
After installing this package, you need to load the notification in your Jupyter Notebook by running the following magic command code.
%load_ext jupyternotify
The setup is ready; let's try to run the Notebook and get notified. We would use the following code, for example.
%%notifyimport timetime.sleep(2)print('Finish Trying Notifiy')
Using the magic command %%notify in the cell, we would get notified similar to the image above when we had finished running the code. If you want to have a specific message in your notification, you could add the message just like the example below.
%%notify -m "Execution done"time.sleep(2)print('Finish Trying Notifiy')
Adding the -m parameter after the magic command would allow you to edit the message. It would be helpful if you need to be notified of particular messages.
The watermark extension is a magic command that allowed us to print the hardware, version, time, and much more information via the Jupyter Notebook environment. It is helpful if we need the information quickly during our exploration.
To install the package, we need to use the following code.
pip install watermark
After installing the package, we could load the extension in our Notebook by running the following code.
%load_ext watermark
Let's try the extension in our Jupyter Notebook. First, we could run the following code to get our hardware information.
%watermark
In default, the magic command %watermark would give us the hardware information. We could acquire much information using watermark, for example, the package version we have imported in our Jupyter Notebook environment.
%watermark --iversion
If you want to know all the available commands to use, you could visit the main page.
Jupyter Notebook is one of the most used IDE for data experts, and to increase the productivity using this IDE, I have outlined my five extensions; they are:
jupyter-resource-usagepyforestjupyter-themesjupyter-notifywatermark
jupyter-resource-usage
pyforest
jupyter-themes
jupyter-notify
watermark
I hope it helps!
Visit me on my LinkedIn or Twitter.
If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here.
If you are not subscribed as a Medium Member, please consider subscribing through my referral.
|
[
{
"code": null,
"e": 476,
"s": 172,
"text": "Jupyter Notebook is a popular IDE for many data experts for analyzing data and developing machine learning models because of its useability and utility. The Notebook is already a beginner-friendly IDE to use and could be extended even more to improve your data activity productivity with a bit of tweak."
},
{
"code": null,
"e": 609,
"s": 476,
"text": "For the above reasons, I want to outline my five Jupyter extensions to improve your productivity in this article. Let's get into it!"
},
{
"code": null,
"e": 839,
"s": 609,
"text": "Have you been in a situation where your Jupyter Notebook became slow or crashed because of memory issues? This case often happens when we explore big data or heavy modelling computation processes that take a huge chunk of memory."
},
{
"code": null,
"e": 1139,
"s": 839,
"text": "To control the memory issues, we could use the jupyter-resource-usage extensions to display the memory usage in our Notebook. This extension work is simple; all the resources in your current notebook servers and children would be displayed on the top right side. Let's try to install the extensions."
},
{
"code": null,
"e": 1174,
"s": 1139,
"text": "pip install jupyter-resource-usage"
},
{
"code": null,
"e": 1343,
"s": 1174,
"text": "When you have finished installing the package, try to restart the Jupyter and access your Jupyter Notebook. The memory display should be available in your Notebook now."
},
{
"code": null,
"e": 1450,
"s": 1343,
"text": "If you want to limit the allocated resources, you could control them using various methods explained here."
},
{
"code": null,
"e": 1697,
"s": 1450,
"text": "Every time you work in a new environment or develop a new project, you must import all the required package. It is not a dealbreaker, but sometimes it isn't enjoyable to import all the packages all over again. This is why pyforest were developed."
},
{
"code": null,
"e": 1952,
"s": 1697,
"text": "The pyforest extensions is an auto-import popular python package from Bamboolib developer. This extension transform your workflow to automatically importing the so popular packages such as pandas, numpy, sklearnAnd many more. You can check the list here."
},
{
"code": null,
"e": 1997,
"s": 1952,
"text": "Let's try to install the pyforest extension."
},
{
"code": null,
"e": 2065,
"s": 1997,
"text": "pip install --upgrade pyforestpython -m pyforest install_extensions"
},
{
"code": null,
"e": 2235,
"s": 2065,
"text": "After you have finished installing the package, you should restart the Jupyter for pyforest auto-import to take place. Let's see if the extension has taken place or not."
},
{
"code": null,
"e": 2508,
"s": 2235,
"text": "As you can see from the above image, I did not import any seaborn or pandas package, but I could automatically use it in my Jupyter Notebook. The pyforest extension would automatically import this package with the popular abbreviation (seaborn as sns, pandas as pd, etc.)."
},
{
"code": null,
"e": 2705,
"s": 2508,
"text": "You don't need to worry about memory allocation because pyforest did not import all the packages initially but only the required package when you execute the code that uses the particular package."
},
{
"code": null,
"e": 2957,
"s": 2705,
"text": "Like the name imply, jupyter-themes is a Jupyter Notebook extension to change the theme. This extension also changes our plotting, markdown, pandas dataframe, and many more. So, the themes change is not limited only to the Jupyter Notebook background."
},
{
"code": null,
"e": 3055,
"s": 2957,
"text": "Let's try to install the jupyter-themes. You could use the following code to install the package."
},
{
"code": null,
"e": 3081,
"s": 3055,
"text": "pip install jupyterthemes"
},
{
"code": null,
"e": 3274,
"s": 3081,
"text": "After installation, you could access the jupyter-themes via CLI to change the Jupyter Notebook theme. First, let's see what themes are available using the following code in our command prompt."
},
{
"code": null,
"e": 3280,
"s": 3274,
"text": "jt -l"
},
{
"code": null,
"e": 3398,
"s": 3280,
"text": "There are nine themes available in default for us to select. Let's try one of the themes, let's say the 'chesterish'."
},
{
"code": null,
"e": 3415,
"s": 3398,
"text": "jt -t chesterish"
},
{
"code": null,
"e": 3559,
"s": 3415,
"text": "To see the changes in your Jupyter Notebook, you need to restart the server. After that, you will see your Notebook similar to the below image."
},
{
"code": null,
"e": 3660,
"s": 3559,
"text": "If you want to reset the theme into the default one, you could reset it by using the following code."
},
{
"code": null,
"e": 3666,
"s": 3660,
"text": "jt -r"
},
{
"code": null,
"e": 3852,
"s": 3666,
"text": "You could still do many things with jupyter-theme, such as controlling the colour, cell width, hiding the specific toolbar, and many more. You could read all the commands on their page."
},
{
"code": null,
"e": 4101,
"s": 3852,
"text": "The jupyter-notify extension is a Jupyter Notebook extension to notify us when our cell has done running. This extension is useful when running a time-consuming modelling process or cleaning activity and you want to do something else while waiting."
},
{
"code": null,
"e": 4168,
"s": 4101,
"text": "First, we need to install the package by using the following code."
},
{
"code": null,
"e": 4194,
"s": 4168,
"text": "pip install jupyternotify"
},
{
"code": null,
"e": 4329,
"s": 4194,
"text": "After installing this package, you need to load the notification in your Jupyter Notebook by running the following magic command code."
},
{
"code": null,
"e": 4353,
"s": 4329,
"text": "%load_ext jupyternotify"
},
{
"code": null,
"e": 4467,
"s": 4353,
"text": "The setup is ready; let's try to run the Notebook and get notified. We would use the following code, for example."
},
{
"code": null,
"e": 4530,
"s": 4467,
"text": "%%notifyimport timetime.sleep(2)print('Finish Trying Notifiy')"
},
{
"code": null,
"e": 4780,
"s": 4530,
"text": "Using the magic command %%notify in the cell, we would get notified similar to the image above when we had finished running the code. If you want to have a specific message in your notification, you could add the message just like the example below."
},
{
"code": null,
"e": 4852,
"s": 4780,
"text": "%%notify -m \"Execution done\"time.sleep(2)print('Finish Trying Notifiy')"
},
{
"code": null,
"e": 5008,
"s": 4852,
"text": "Adding the -m parameter after the magic command would allow you to edit the message. It would be helpful if you need to be notified of particular messages."
},
{
"code": null,
"e": 5242,
"s": 5008,
"text": "The watermark extension is a magic command that allowed us to print the hardware, version, time, and much more information via the Jupyter Notebook environment. It is helpful if we need the information quickly during our exploration."
},
{
"code": null,
"e": 5301,
"s": 5242,
"text": "To install the package, we need to use the following code."
},
{
"code": null,
"e": 5323,
"s": 5301,
"text": "pip install watermark"
},
{
"code": null,
"e": 5428,
"s": 5323,
"text": "After installing the package, we could load the extension in our Notebook by running the following code."
},
{
"code": null,
"e": 5448,
"s": 5428,
"text": "%load_ext watermark"
},
{
"code": null,
"e": 5569,
"s": 5448,
"text": "Let's try the extension in our Jupyter Notebook. First, we could run the following code to get our hardware information."
},
{
"code": null,
"e": 5580,
"s": 5569,
"text": "%watermark"
},
{
"code": null,
"e": 5799,
"s": 5580,
"text": "In default, the magic command %watermark would give us the hardware information. We could acquire much information using watermark, for example, the package version we have imported in our Jupyter Notebook environment."
},
{
"code": null,
"e": 5821,
"s": 5799,
"text": "%watermark --iversion"
},
{
"code": null,
"e": 5907,
"s": 5821,
"text": "If you want to know all the available commands to use, you could visit the main page."
},
{
"code": null,
"e": 6065,
"s": 5907,
"text": "Jupyter Notebook is one of the most used IDE for data experts, and to increase the productivity using this IDE, I have outlined my five extensions; they are:"
},
{
"code": null,
"e": 6133,
"s": 6065,
"text": "jupyter-resource-usagepyforestjupyter-themesjupyter-notifywatermark"
},
{
"code": null,
"e": 6156,
"s": 6133,
"text": "jupyter-resource-usage"
},
{
"code": null,
"e": 6165,
"s": 6156,
"text": "pyforest"
},
{
"code": null,
"e": 6180,
"s": 6165,
"text": "jupyter-themes"
},
{
"code": null,
"e": 6195,
"s": 6180,
"text": "jupyter-notify"
},
{
"code": null,
"e": 6205,
"s": 6195,
"text": "watermark"
},
{
"code": null,
"e": 6222,
"s": 6205,
"text": "I hope it helps!"
},
{
"code": null,
"e": 6258,
"s": 6222,
"text": "Visit me on my LinkedIn or Twitter."
},
{
"code": null,
"e": 6428,
"s": 6258,
"text": "If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here."
}
] |
Remove consecutive vowels from string
|
02 Jun, 2022
Given a string s of lowercase letters, we need to remove consecutive vowels from the stringNote : Sentence should not contain two consecutive vowels ( a, e, i, o, u).Examples :
Input: geeks for geeks
Output: geks for geks
Input : your article is in queue
Output : your article is in qu
Approach: Iterate string using a loop and check for the repetitiveness of vowels in a given sentence and in case if consecutive vowels are found then delete the vowel till coming next consonant and printing the updated string.
C++
Java
Python3
C#
PHP
Javascript
// C++ program for printing sentence// without repetitive vowels#include <bits/stdc++.h>using namespace std; // function which returns True or False// for occurrence of a vowelbool is_vow(char c){ // this compares vowel with // character 'c' return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u');} // function to print resultant stringvoid removeVowels(string str){ // print 1st character printf("%c", str[0]); // loop to check for each character for (int i = 1; str[i]; i++) // comparison of consecutive characters if ((!is_vow(str[i - 1])) || (!is_vow(str[i]))) printf("%c", str[i]);} // Driver Codeint main(){ char str[] = " geeks for geeks"; removeVowels(str);} // This code is contributed by Abhinav96
// Java program for printing sentence// without repetitive vowelsimport java.io.*;import java.util.*;import java.lang.*; class GFG{ // function which returns // True or False for // occurrence of a vowel static boolean is_vow(char c) { // this compares vowel // with character 'c' return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u'); } // function to print // resultant string static void removeVowels(String str) { // print 1st character System.out.print(str.charAt(0)); // loop to check for // each character for (int i = 1; i < str.length(); i++) // comparison of // consecutive characters if ((!is_vow(str.charAt(i - 1))) || (!is_vow(str.charAt(i)))) System.out.print(str.charAt(i)); } // Driver Code public static void main(String[] args) { String str = "geeks for geeks"; removeVowels(str); }}
# Python3 implementation for printing# sentence without repetitive vowels # function which returns True or False# for occurrence of a voweldef is_vow(c): # this compares vowel with # character 'c' return ((c == 'a') or (c == 'e') or (c == 'i') or (c == 'o') or (c == 'u')); # function to print resultant stringdef removeVowels(str): # print 1st character print(str[0], end = ""); # loop to check for each character for i in range(1,len(str)): # comparison of consecutive # characters if ((is_vow(str[i - 1]) != True) or (is_vow(str[i]) != True)): print(str[i], end = ""); # Driver codestr= " geeks for geeks";removeVowels(str); # This code is contributed by mits
// C# program for printing sentence// without repetitive vowelsusing System; class GFG{ // function which returns // True or False for // occurrence of a vowel static bool is_vow(char c) { // this compares vowel // with character 'c' return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u'); } // function to print // resultant string static void removeVowels(string str) { // print 1st character Console.Write(str[0]); // loop to check for // each character for (int i = 1; i < str.Length; i++) // comparison of // consecutive characters if ((!is_vow(str[i - 1])) || (!is_vow(str[i]))) Console.Write(str[i]); } // Driver Code static void Main() { string str = "geeks for geeks"; removeVowels(str); }} // This code is contributed// by Manish Shaw(manishshaw1)
<?php// PHP implementation for printing// sentence without repetitive vowels // function which returns True or False// for occurrence of a vowelfunction is_vow($c){ // this compares vowel with // character 'c' return ($c == 'a') || ($c == 'e') || ($c == 'i') || ($c == 'o') || ($c == 'u');} // function to print resultant stringfunction removeVowels($str){ // print 1st character printf($str[0]); // loop to check for each character for ($i = 1; $i < strlen($str); $i++) // comparison of consecutive // characters if ((!is_vow($str[$i - 1])) || (!is_vow($str[$i]))) printf($str[$i]);} // Driver code$str= " geeks for geeks";removeVowels($str); // This code is contributed by mits?>
<script> // JavaScript program for printing sentence// without repetitive vowels // function which returns True or False// for occurrence of a vowelfunction is_vow(c){ // this compares vowel with // character 'c' return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u');} // function to print resultant stringfunction removeVowels(str){ // print 1st character document.write(str[0]); // loop to check for each character for (let i = 1; i<str.length; i++) // comparison of consecutive characters if ((!is_vow(str[i - 1])) || (!is_vow(str[i]))) document.write(str[i]);} // Driver Codelet str = " geeks for geeks";removeVowels(str); // This code is contributed by shinjanpatra </script>
geks for geks
Time Complexity: O(n), where n is the length of the string
Space Complexity: O(n), where n is the length of the string
Remove consecutive vowels from string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersRemove consecutive vowels from string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:04•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Q_hsm2Qh9SE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Mithun Kumar
manishshaw1
sumitgumber28
shinjanpatra
rohitmishra051000
vowel-consonant
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction To PYTHON
Interfaces in Java
Operator Overloading in C++
Polymorphism in C++
Types of Operating Systems
Write a program to reverse an array or string
Write a program to print all permutations of a given string
Different Methods to Reverse a String in C++
Check for Balanced Brackets in an expression (well-formedness) using Stack
Longest Common Subsequence | DP-4
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jun, 2022"
},
{
"code": null,
"e": 233,
"s": 54,
"text": "Given a string s of lowercase letters, we need to remove consecutive vowels from the stringNote : Sentence should not contain two consecutive vowels ( a, e, i, o, u).Examples : "
},
{
"code": null,
"e": 344,
"s": 233,
"text": "Input: geeks for geeks\nOutput: geks for geks\n\nInput : your article is in queue \nOutput : your article is in qu"
},
{
"code": null,
"e": 575,
"s": 346,
"text": "Approach: Iterate string using a loop and check for the repetitiveness of vowels in a given sentence and in case if consecutive vowels are found then delete the vowel till coming next consonant and printing the updated string. "
},
{
"code": null,
"e": 579,
"s": 575,
"text": "C++"
},
{
"code": null,
"e": 584,
"s": 579,
"text": "Java"
},
{
"code": null,
"e": 592,
"s": 584,
"text": "Python3"
},
{
"code": null,
"e": 595,
"s": 592,
"text": "C#"
},
{
"code": null,
"e": 599,
"s": 595,
"text": "PHP"
},
{
"code": null,
"e": 610,
"s": 599,
"text": "Javascript"
},
{
"code": "// C++ program for printing sentence// without repetitive vowels#include <bits/stdc++.h>using namespace std; // function which returns True or False// for occurrence of a vowelbool is_vow(char c){ // this compares vowel with // character 'c' return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u');} // function to print resultant stringvoid removeVowels(string str){ // print 1st character printf(\"%c\", str[0]); // loop to check for each character for (int i = 1; str[i]; i++) // comparison of consecutive characters if ((!is_vow(str[i - 1])) || (!is_vow(str[i]))) printf(\"%c\", str[i]);} // Driver Codeint main(){ char str[] = \" geeks for geeks\"; removeVowels(str);} // This code is contributed by Abhinav96",
"e": 1422,
"s": 610,
"text": null
},
{
"code": "// Java program for printing sentence// without repetitive vowelsimport java.io.*;import java.util.*;import java.lang.*; class GFG{ // function which returns // True or False for // occurrence of a vowel static boolean is_vow(char c) { // this compares vowel // with character 'c' return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u'); } // function to print // resultant string static void removeVowels(String str) { // print 1st character System.out.print(str.charAt(0)); // loop to check for // each character for (int i = 1; i < str.length(); i++) // comparison of // consecutive characters if ((!is_vow(str.charAt(i - 1))) || (!is_vow(str.charAt(i)))) System.out.print(str.charAt(i)); } // Driver Code public static void main(String[] args) { String str = \"geeks for geeks\"; removeVowels(str); }}",
"e": 2486,
"s": 1422,
"text": null
},
{
"code": "# Python3 implementation for printing# sentence without repetitive vowels # function which returns True or False# for occurrence of a voweldef is_vow(c): # this compares vowel with # character 'c' return ((c == 'a') or (c == 'e') or (c == 'i') or (c == 'o') or (c == 'u')); # function to print resultant stringdef removeVowels(str): # print 1st character print(str[0], end = \"\"); # loop to check for each character for i in range(1,len(str)): # comparison of consecutive # characters if ((is_vow(str[i - 1]) != True) or (is_vow(str[i]) != True)): print(str[i], end = \"\"); # Driver codestr= \" geeks for geeks\";removeVowels(str); # This code is contributed by mits",
"e": 3252,
"s": 2486,
"text": null
},
{
"code": "// C# program for printing sentence// without repetitive vowelsusing System; class GFG{ // function which returns // True or False for // occurrence of a vowel static bool is_vow(char c) { // this compares vowel // with character 'c' return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u'); } // function to print // resultant string static void removeVowels(string str) { // print 1st character Console.Write(str[0]); // loop to check for // each character for (int i = 1; i < str.Length; i++) // comparison of // consecutive characters if ((!is_vow(str[i - 1])) || (!is_vow(str[i]))) Console.Write(str[i]); } // Driver Code static void Main() { string str = \"geeks for geeks\"; removeVowels(str); }} // This code is contributed// by Manish Shaw(manishshaw1)",
"e": 4255,
"s": 3252,
"text": null
},
{
"code": "<?php// PHP implementation for printing// sentence without repetitive vowels // function which returns True or False// for occurrence of a vowelfunction is_vow($c){ // this compares vowel with // character 'c' return ($c == 'a') || ($c == 'e') || ($c == 'i') || ($c == 'o') || ($c == 'u');} // function to print resultant stringfunction removeVowels($str){ // print 1st character printf($str[0]); // loop to check for each character for ($i = 1; $i < strlen($str); $i++) // comparison of consecutive // characters if ((!is_vow($str[$i - 1])) || (!is_vow($str[$i]))) printf($str[$i]);} // Driver code$str= \" geeks for geeks\";removeVowels($str); // This code is contributed by mits?>",
"e": 5036,
"s": 4255,
"text": null
},
{
"code": "<script> // JavaScript program for printing sentence// without repetitive vowels // function which returns True or False// for occurrence of a vowelfunction is_vow(c){ // this compares vowel with // character 'c' return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u');} // function to print resultant stringfunction removeVowels(str){ // print 1st character document.write(str[0]); // loop to check for each character for (let i = 1; i<str.length; i++) // comparison of consecutive characters if ((!is_vow(str[i - 1])) || (!is_vow(str[i]))) document.write(str[i]);} // Driver Codelet str = \" geeks for geeks\";removeVowels(str); // This code is contributed by shinjanpatra </script>",
"e": 5811,
"s": 5036,
"text": null
},
{
"code": null,
"e": 5825,
"s": 5811,
"text": "geks for geks"
},
{
"code": null,
"e": 5886,
"s": 5827,
"text": "Time Complexity: O(n), where n is the length of the string"
},
{
"code": null,
"e": 5946,
"s": 5886,
"text": "Space Complexity: O(n), where n is the length of the string"
},
{
"code": null,
"e": 6838,
"s": 5946,
"text": "Remove consecutive vowels from string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersRemove consecutive vowels from string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:04•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Q_hsm2Qh9SE\" 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": 6851,
"s": 6838,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 6863,
"s": 6851,
"text": "manishshaw1"
},
{
"code": null,
"e": 6877,
"s": 6863,
"text": "sumitgumber28"
},
{
"code": null,
"e": 6890,
"s": 6877,
"text": "shinjanpatra"
},
{
"code": null,
"e": 6908,
"s": 6890,
"text": "rohitmishra051000"
},
{
"code": null,
"e": 6924,
"s": 6908,
"text": "vowel-consonant"
},
{
"code": null,
"e": 6943,
"s": 6924,
"text": "School Programming"
},
{
"code": null,
"e": 6951,
"s": 6943,
"text": "Strings"
},
{
"code": null,
"e": 6959,
"s": 6951,
"text": "Strings"
},
{
"code": null,
"e": 7057,
"s": 6959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7080,
"s": 7057,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 7099,
"s": 7080,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 7127,
"s": 7099,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 7147,
"s": 7127,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 7174,
"s": 7147,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 7220,
"s": 7174,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 7280,
"s": 7220,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 7325,
"s": 7280,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 7400,
"s": 7325,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Control Statements in R Programming
|
01 Jun, 2020
Control statements are expressions used to control the execution and flow of the program based on the conditions provided in the statements. These structures are used to make a decision after assessing the variable. In this article, we’ll discuss all the control statements with the examples.
In R programming, there are 8 types of control statements as follows:
if condition
if-else condition
for loop
nested loops
while loop
repeat and break statement
return statement
next statement
This control structure checks the expression provided in parenthesis is true or not. If true, the execution of the statements in braces {} continues.
Syntax:
if(expression){
statements
....
....
}
Example:
x <- 100 if(x > 10){print(paste(x, "is greater than 10"))}
Output:
[1] "100 is greater than 10"
It is similar to if condition but when the test expression in if condition fails, then statements in else condition are executed.
Syntax:
if(expression){
statements
....
....
}
else{
statements
....
....
}
Example:
x <- 5 # Check value is less than or greater than 10if(x > 10){ print(paste(x, "is greater than 10"))}else{ print(paste(x, "is less than 10"))}
Output:
[1] "5 is less than 10"
It is a type of loop or sequence of statements executed repeatedly until exit condition is reached.
Syntax:
for(value in vector){
statements
....
....
}
Example:
x <- letters[4:10] for(i in x){ print(i)}
Output:
[1] "d"
[1] "e"
[1] "f"
[1] "g"
[1] "h"
[1] "i"
[1] "j"
Nested loops are similar to simple loops. Nested means loops inside loop. Moreover, nested loops are used to manipulate the matrix.
Example:
# Defining matrixm <- matrix(2:15, 2) for (r in seq(nrow(m))) { for (c in seq(ncol(m))) { print(m[r, c]) }}
Output:
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
[1] 12
[1] 14
[1] 3
[1] 5
[1] 7
[1] 9
[1] 11
[1] 13
[1] 15
while loop is another kind of loop iterated until a condition is satisfied. The testing expression is checked first before executing the body of loop.
Syntax:
while(expression){
statement
....
....
}
Example:
x = 1 # Print 1 to 5while(x <= 5){ print(x) x = x + 1}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
repeat is a loop which can be iterated many number of times but there is no exit condition to come out from the loop. So, break statement is used to exit from the loop. break statement can be used in any type of loop to exit from the loop.
Syntax:
repeat {
statements
....
....
if(expression) {
break
}
}
Example:
x = 1 # Print 1 to 5repeat{ print(x) x = x + 1 if(x > 5){ break }}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
return statement is used to return the result of an executed function and returns control to the calling function.
Syntax:
return(expression)
Example:
# Checks value is either positive, negative or zerofunc <- function(x){ if(x > 0){ return("Positive") }else if(x < 0){ return("Negative") }else{ return("Zero") }} func(1)func(0)func(-1)
Output:
[1] "Positive"
[1] "Zero"
[1] "Negative"
next statement is used to skip the current iteration without executing the further statements and continues the next iteration cycle without terminating the loop.
Example:
# Defining vectorx <- 1:10 # Print even numbersfor(i in x){ if(i%%2 != 0){ next #Jumps to next loop } print(i)}
Output:
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
How to Split Column Into Multiple Columns in R DataFrame?
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Convert Factor to Numeric and Numeric to Factor in R Programming
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 346,
"s": 53,
"text": "Control statements are expressions used to control the execution and flow of the program based on the conditions provided in the statements. These structures are used to make a decision after assessing the variable. In this article, we’ll discuss all the control statements with the examples."
},
{
"code": null,
"e": 416,
"s": 346,
"text": "In R programming, there are 8 types of control statements as follows:"
},
{
"code": null,
"e": 429,
"s": 416,
"text": "if condition"
},
{
"code": null,
"e": 447,
"s": 429,
"text": "if-else condition"
},
{
"code": null,
"e": 456,
"s": 447,
"text": "for loop"
},
{
"code": null,
"e": 469,
"s": 456,
"text": "nested loops"
},
{
"code": null,
"e": 480,
"s": 469,
"text": "while loop"
},
{
"code": null,
"e": 507,
"s": 480,
"text": "repeat and break statement"
},
{
"code": null,
"e": 524,
"s": 507,
"text": "return statement"
},
{
"code": null,
"e": 539,
"s": 524,
"text": "next statement"
},
{
"code": null,
"e": 690,
"s": 539,
"text": "This control structure checks the expression provided in parenthesis is true or not. If true, the execution of the statements in braces {} continues. "
},
{
"code": null,
"e": 698,
"s": 690,
"text": "Syntax:"
},
{
"code": null,
"e": 750,
"s": 698,
"text": "if(expression){\n statements\n ....\n ....\n}\n"
},
{
"code": null,
"e": 759,
"s": 750,
"text": "Example:"
},
{
"code": "x <- 100 if(x > 10){print(paste(x, \"is greater than 10\"))}",
"e": 819,
"s": 759,
"text": null
},
{
"code": null,
"e": 827,
"s": 819,
"text": "Output:"
},
{
"code": null,
"e": 857,
"s": 827,
"text": "[1] \"100 is greater than 10\"\n"
},
{
"code": null,
"e": 987,
"s": 857,
"text": "It is similar to if condition but when the test expression in if condition fails, then statements in else condition are executed."
},
{
"code": null,
"e": 995,
"s": 987,
"text": "Syntax:"
},
{
"code": null,
"e": 1088,
"s": 995,
"text": "if(expression){\n statements\n ....\n ....\n}\nelse{\n statements\n ....\n ....\n}\n"
},
{
"code": null,
"e": 1097,
"s": 1088,
"text": "Example:"
},
{
"code": "x <- 5 # Check value is less than or greater than 10if(x > 10){ print(paste(x, \"is greater than 10\"))}else{ print(paste(x, \"is less than 10\"))}",
"e": 1244,
"s": 1097,
"text": null
},
{
"code": null,
"e": 1252,
"s": 1244,
"text": "Output:"
},
{
"code": null,
"e": 1277,
"s": 1252,
"text": "[1] \"5 is less than 10\"\n"
},
{
"code": null,
"e": 1377,
"s": 1277,
"text": "It is a type of loop or sequence of statements executed repeatedly until exit condition is reached."
},
{
"code": null,
"e": 1385,
"s": 1377,
"text": "Syntax:"
},
{
"code": null,
"e": 1443,
"s": 1385,
"text": "for(value in vector){\n statements\n ....\n ....\n}\n"
},
{
"code": null,
"e": 1452,
"s": 1443,
"text": "Example:"
},
{
"code": "x <- letters[4:10] for(i in x){ print(i)}",
"e": 1496,
"s": 1452,
"text": null
},
{
"code": null,
"e": 1504,
"s": 1496,
"text": "Output:"
},
{
"code": null,
"e": 1561,
"s": 1504,
"text": "[1] \"d\"\n[1] \"e\"\n[1] \"f\"\n[1] \"g\"\n[1] \"h\"\n[1] \"i\"\n[1] \"j\"\n"
},
{
"code": null,
"e": 1693,
"s": 1561,
"text": "Nested loops are similar to simple loops. Nested means loops inside loop. Moreover, nested loops are used to manipulate the matrix."
},
{
"code": null,
"e": 1702,
"s": 1693,
"text": "Example:"
},
{
"code": "# Defining matrixm <- matrix(2:15, 2) for (r in seq(nrow(m))) { for (c in seq(ncol(m))) { print(m[r, c]) }}",
"e": 1816,
"s": 1702,
"text": null
},
{
"code": null,
"e": 1825,
"s": 1816,
"text": " Output:"
},
{
"code": null,
"e": 1916,
"s": 1825,
"text": "[1] 2\n[1] 4\n[1] 6\n[1] 8\n[1] 10\n[1] 12\n[1] 14\n[1] 3\n[1] 5\n[1] 7\n[1] 9\n[1] 11\n[1] 13\n[1] 15\n"
},
{
"code": null,
"e": 2067,
"s": 1916,
"text": "while loop is another kind of loop iterated until a condition is satisfied. The testing expression is checked first before executing the body of loop."
},
{
"code": null,
"e": 2075,
"s": 2067,
"text": "Syntax:"
},
{
"code": null,
"e": 2129,
"s": 2075,
"text": "while(expression){\n statement\n ....\n ....\n}\n"
},
{
"code": null,
"e": 2138,
"s": 2129,
"text": "Example:"
},
{
"code": "x = 1 # Print 1 to 5while(x <= 5){ print(x) x = x + 1}",
"e": 2196,
"s": 2138,
"text": null
},
{
"code": null,
"e": 2204,
"s": 2196,
"text": "Output:"
},
{
"code": null,
"e": 2235,
"s": 2204,
"text": "[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5\n"
},
{
"code": null,
"e": 2475,
"s": 2235,
"text": "repeat is a loop which can be iterated many number of times but there is no exit condition to come out from the loop. So, break statement is used to exit from the loop. break statement can be used in any type of loop to exit from the loop."
},
{
"code": null,
"e": 2483,
"s": 2475,
"text": "Syntax:"
},
{
"code": null,
"e": 2564,
"s": 2483,
"text": "repeat { \n statements\n ....\n .... \n if(expression) {\n break\n }\n}\n"
},
{
"code": null,
"e": 2573,
"s": 2564,
"text": "Example:"
},
{
"code": "x = 1 # Print 1 to 5repeat{ print(x) x = x + 1 if(x > 5){ break }}",
"e": 2649,
"s": 2573,
"text": null
},
{
"code": null,
"e": 2658,
"s": 2649,
"text": " Output:"
},
{
"code": null,
"e": 2689,
"s": 2658,
"text": "[1] 1\n[1] 2\n[1] 3\n[1] 4\n[1] 5\n"
},
{
"code": null,
"e": 2804,
"s": 2689,
"text": "return statement is used to return the result of an executed function and returns control to the calling function."
},
{
"code": null,
"e": 2812,
"s": 2804,
"text": "Syntax:"
},
{
"code": null,
"e": 2832,
"s": 2812,
"text": "return(expression)\n"
},
{
"code": null,
"e": 2841,
"s": 2832,
"text": "Example:"
},
{
"code": "# Checks value is either positive, negative or zerofunc <- function(x){ if(x > 0){ return(\"Positive\") }else if(x < 0){ return(\"Negative\") }else{ return(\"Zero\") }} func(1)func(0)func(-1)",
"e": 3041,
"s": 2841,
"text": null
},
{
"code": null,
"e": 3049,
"s": 3041,
"text": "Output:"
},
{
"code": null,
"e": 3091,
"s": 3049,
"text": "[1] \"Positive\"\n[1] \"Zero\"\n[1] \"Negative\"\n"
},
{
"code": null,
"e": 3254,
"s": 3091,
"text": "next statement is used to skip the current iteration without executing the further statements and continues the next iteration cycle without terminating the loop."
},
{
"code": null,
"e": 3263,
"s": 3254,
"text": "Example:"
},
{
"code": "# Defining vectorx <- 1:10 # Print even numbersfor(i in x){ if(i%%2 != 0){ next #Jumps to next loop } print(i)}",
"e": 3382,
"s": 3263,
"text": null
},
{
"code": null,
"e": 3390,
"s": 3382,
"text": "Output:"
},
{
"code": null,
"e": 3422,
"s": 3390,
"text": "[1] 2\n[1] 4\n[1] 6\n[1] 8\n[1] 10\n"
},
{
"code": null,
"e": 3433,
"s": 3422,
"text": "R Language"
},
{
"code": null,
"e": 3531,
"s": 3433,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3576,
"s": 3531,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 3628,
"s": 3576,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 3686,
"s": 3628,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 3744,
"s": 3686,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3796,
"s": 3744,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 3828,
"s": 3796,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 3891,
"s": 3828,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 3926,
"s": 3891,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 3970,
"s": 3926,
"text": "How to change Row Names of DataFrame in R ?"
}
] |
How to traverse a C++ set in reverse direction
|
05 Dec, 2018
Given a Set, the task is to traverse this Set in reverse order.
Examples:
Input: set = [10 20 30 70 80 90 100 40 50 60]
Output: 100 90 80 70 60 50 40 30 20 10
Input: set = [1 2 3 4 5]
Output: 5 4 3 2 1
Approach:To traverse a Set in reverse order, a reverse_iterator can be declared on it and it can be used to traverse the set from the last element to the first element with the help of rbegin() and rend() functions.
Get the set.Declare the reverse iterator on this set.Traverse the set from the last element to the first element with the help of rbegin() and rend() functions.
Get the set.
Declare the reverse iterator on this set.
Traverse the set from the last element to the first element with the help of rbegin() and rend() functions.
Below is the implementation of the above approach:
Program:
#include <bits/stdc++.h>using namespace std; int main(){ // Get the set int arr[] = { 14, 12, 15, 11, 10 }; // initializes the set from an array set<int> s(arr, arr + sizeof(arr) / sizeof(arr[0])); // declare iterator on set set<int>::iterator it; cout << "Elements of Set in normal order:\n"; // prints all elements in normal order // using begin() and end() methods for (it = s.begin(); it != s.end(); it++) cout << *it << " "; // declare reverse_iterator on set set<int>::reverse_iterator rit; cout << "\nElements of Set in reverse order:\n"; // prints all elements in reverse order // using rbegin() and rend() methods for (rit = s.rbegin(); rit != s.rend(); rit++) cout << *rit << " "; return 0;}
Elements of Set in normal order:
10 11 12 14 15
Elements of Set in reverse order:
15 14 12 11 10
cpp-set
Picked
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Queue in C++ Standard Template Library (STL)
std::find in C++
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
vector insert() function in C++ STL
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 92,
"s": 28,
"text": "Given a Set, the task is to traverse this Set in reverse order."
},
{
"code": null,
"e": 102,
"s": 92,
"text": "Examples:"
},
{
"code": null,
"e": 233,
"s": 102,
"text": "Input: set = [10 20 30 70 80 90 100 40 50 60]\nOutput: 100 90 80 70 60 50 40 30 20 10 \n\nInput: set = [1 2 3 4 5]\nOutput: 5 4 3 2 1\n"
},
{
"code": null,
"e": 449,
"s": 233,
"text": "Approach:To traverse a Set in reverse order, a reverse_iterator can be declared on it and it can be used to traverse the set from the last element to the first element with the help of rbegin() and rend() functions."
},
{
"code": null,
"e": 610,
"s": 449,
"text": "Get the set.Declare the reverse iterator on this set.Traverse the set from the last element to the first element with the help of rbegin() and rend() functions."
},
{
"code": null,
"e": 623,
"s": 610,
"text": "Get the set."
},
{
"code": null,
"e": 665,
"s": 623,
"text": "Declare the reverse iterator on this set."
},
{
"code": null,
"e": 773,
"s": 665,
"text": "Traverse the set from the last element to the first element with the help of rbegin() and rend() functions."
},
{
"code": null,
"e": 824,
"s": 773,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 833,
"s": 824,
"text": "Program:"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int main(){ // Get the set int arr[] = { 14, 12, 15, 11, 10 }; // initializes the set from an array set<int> s(arr, arr + sizeof(arr) / sizeof(arr[0])); // declare iterator on set set<int>::iterator it; cout << \"Elements of Set in normal order:\\n\"; // prints all elements in normal order // using begin() and end() methods for (it = s.begin(); it != s.end(); it++) cout << *it << \" \"; // declare reverse_iterator on set set<int>::reverse_iterator rit; cout << \"\\nElements of Set in reverse order:\\n\"; // prints all elements in reverse order // using rbegin() and rend() methods for (rit = s.rbegin(); rit != s.rend(); rit++) cout << *rit << \" \"; return 0;}",
"e": 1619,
"s": 833,
"text": null
},
{
"code": null,
"e": 1718,
"s": 1619,
"text": "Elements of Set in normal order:\n10 11 12 14 15 \nElements of Set in reverse order:\n15 14 12 11 10\n"
},
{
"code": null,
"e": 1726,
"s": 1718,
"text": "cpp-set"
},
{
"code": null,
"e": 1733,
"s": 1726,
"text": "Picked"
},
{
"code": null,
"e": 1737,
"s": 1733,
"text": "STL"
},
{
"code": null,
"e": 1741,
"s": 1737,
"text": "C++"
},
{
"code": null,
"e": 1745,
"s": 1741,
"text": "STL"
},
{
"code": null,
"e": 1749,
"s": 1745,
"text": "CPP"
},
{
"code": null,
"e": 1847,
"s": 1749,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1871,
"s": 1847,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1891,
"s": 1871,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 1935,
"s": 1891,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1968,
"s": 1935,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 1993,
"s": 1968,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2038,
"s": 1993,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2055,
"s": 2038,
"text": "std::find in C++"
},
{
"code": null,
"e": 2103,
"s": 2055,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2147,
"s": 2103,
"text": "List in C++ Standard Template Library (STL)"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.