title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to find the href and target attributes in a link in JavaScript? | Javascript has provided document.href and document.target to get the href and target attributes in a link. A link is usually placed in a <p> tag and inside it, an anchor tag is provided, which in turn contains href and target attributes. Let's discuss them individually.
To get the href attribute, document.href must be used. In the following example, the href attribute consists of a link called "http://www.tutorialspoint.com/", which will be displayed once the program is executed.
Live Demo
<html>
<body>
<p><a id="myId" href="http://www.tutorialspoint.com/">tutorialspoint</a></p>
<script>
var ref = document.getElementById("myId").href;
document.write(ref);
</script>
</body>
</html>
tutorialspoint
http://www.tutorialspoint.com/
To get the target attribute, document.target must be used. In the following example, the target attribute "_union" was displayed when the program was executed.
Live Demo
<html>
<body>
<p><a id="myId" target="_union" href="http://www.tutorialspoint.com/">tutorialspoint</a></p>
<script>
var ref = document.getElementById("myId").target;
document.write(ref);
</script>
</body>
</html>
tutorialspoint
_union | [
{
"code": null,
"e": 1333,
"s": 1062,
"text": "Javascript has provided document.href and document.target to get the href and target attributes in a link. A link is usually placed in a <p> tag and inside it, an anchor tag is provided, which in turn contains href and target attributes. Let's discuss them individually."
},
{
"code": null,
"e": 1547,
"s": 1333,
"text": "To get the href attribute, document.href must be used. In the following example, the href attribute consists of a link called \"http://www.tutorialspoint.com/\", which will be displayed once the program is executed."
},
{
"code": null,
"e": 1557,
"s": 1547,
"text": "Live Demo"
},
{
"code": null,
"e": 1758,
"s": 1557,
"text": "<html>\n<body>\n<p><a id=\"myId\" href=\"http://www.tutorialspoint.com/\">tutorialspoint</a></p>\n<script>\n var ref = document.getElementById(\"myId\").href;\n document.write(ref);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 1805,
"s": 1758,
"text": "tutorialspoint\n\nhttp://www.tutorialspoint.com/"
},
{
"code": null,
"e": 1965,
"s": 1805,
"text": "To get the target attribute, document.target must be used. In the following example, the target attribute \"_union\" was displayed when the program was executed."
},
{
"code": null,
"e": 1975,
"s": 1965,
"text": "Live Demo"
},
{
"code": null,
"e": 2194,
"s": 1975,
"text": "<html>\n<body>\n<p><a id=\"myId\" target=\"_union\" href=\"http://www.tutorialspoint.com/\">tutorialspoint</a></p>\n<script>\n var ref = document.getElementById(\"myId\").target;\n document.write(ref);\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2217,
"s": 2194,
"text": "tutorialspoint\n\n_union"
}
] |
Call Stored Procedures within a Stored Procedure with IF Logic? | To call stored procedures within a stored procedure, the syntax is as follows −
If yourInputValue > 100 then
call yourProcedureName1();
else
call yourProcedureName2();
end If ;
END
Let us implement the above syntax. In order to implement the above concept, let us create a stored procedure −
mysql> delimiter //
mysql> create procedure Hello_Stored_Procedure()
-> BEGIN
-> select 'Hello World!!!';
-> END
-> //
Query OK, 0 rows affected (0.18 sec)
The query to create the second stored procedure is as follows −
mysql> create procedure Hi_Stored_Procedure()
-> BEGIN
-> select 'Hi!!!';
-> END
-> //
Query OK, 0 rows affected (0.17 sec)
Here is the query to call stored procedures within a stored procedure with IF logic −
mysql> DELIMITER //
mysql> create procedure test(IN input int)
-> BEGIN
-> If input > 100 then
-> call Hello_Stored_Procedure();
-> else
-> call Hi_Stored_Procedure();
-> end If ;
-> END
-> //
Query OK, 0 rows affected (0.18 sec)
Now you can call the stored procedure with the help of call −
mysql> delimiter ;
mysql> call test(110);
This will produce the following output −
+----------------+
| Hello World!!! |
+----------------+
| Hello World!!! |
+----------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.02 sec) | [
{
"code": null,
"e": 1142,
"s": 1062,
"text": "To call stored procedures within a stored procedure, the syntax is as follows −"
},
{
"code": null,
"e": 1261,
"s": 1142,
"text": "If yourInputValue > 100 then\n call yourProcedureName1();\n else\n call yourProcedureName2();\n end If ;\n END"
},
{
"code": null,
"e": 1372,
"s": 1261,
"text": "Let us implement the above syntax. In order to implement the above concept, let us create a stored procedure −"
},
{
"code": null,
"e": 1540,
"s": 1372,
"text": "mysql> delimiter //\nmysql> create procedure Hello_Stored_Procedure()\n -> BEGIN\n -> select 'Hello World!!!';\n -> END\n -> //\nQuery OK, 0 rows affected (0.18 sec)"
},
{
"code": null,
"e": 1604,
"s": 1540,
"text": "The query to create the second stored procedure is as follows −"
},
{
"code": null,
"e": 1740,
"s": 1604,
"text": "mysql> create procedure Hi_Stored_Procedure()\n -> BEGIN\n -> select 'Hi!!!';\n -> END\n -> //\nQuery OK, 0 rows affected (0.17 sec)"
},
{
"code": null,
"e": 1826,
"s": 1740,
"text": "Here is the query to call stored procedures within a stored procedure with IF logic −"
},
{
"code": null,
"e": 2080,
"s": 1826,
"text": "mysql> DELIMITER //\nmysql> create procedure test(IN input int)\n -> BEGIN\n -> If input > 100 then\n -> call Hello_Stored_Procedure();\n -> else\n -> call Hi_Stored_Procedure();\n -> end If ;\n -> END\n -> //\nQuery OK, 0 rows affected (0.18 sec)"
},
{
"code": null,
"e": 2142,
"s": 2080,
"text": "Now you can call the stored procedure with the help of call −"
},
{
"code": null,
"e": 2184,
"s": 2142,
"text": "mysql> delimiter ;\nmysql> call test(110);"
},
{
"code": null,
"e": 2225,
"s": 2184,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2381,
"s": 2225,
"text": "+----------------+\n| Hello World!!! |\n+----------------+\n| Hello World!!! |\n+----------------+\n1 row in set (0.00 sec)\nQuery OK, 0 rows affected (0.02 sec)"
}
] |
Drawing a cross on an image with OpenCV - GeeksforGeeks | 18 Apr, 2022
In this article, we are going to discuss how to draw a cross on an image using OpenCV-Python. We can draw an overlay of two lines one above another to make a cross on an image.
To draw a line on OpenCV, the below function is used.
Syntax: cv2.line(image, starting Point, ending Point, color, thickness)
Parameters:
Image – The source image on which you need to draw the shape.
startingPoint – The coordinates of the image where the line should start. Which is represented by a tuple of co-ordinates (x-axis, y-axis), basically the pixel’s location from where to start.
endingPoint – The coordinates of the image where the line should end. Which is represented by a tuple of co-ordinates (x-axis, y-axis).
Color – Color of the line drawn on the image. Represented by BGR color values on a tuple in which each value is between 0 – 255(255,0,0) for BLUE(0,255,0) for GREEN(0,0,255) for RED]
(255,0,0) for BLUE
(0,255,0) for GREEN
(0,0,255) for RED]
Thickness – Thickness of the drawn line in pixels.
To draw a cross on an image we first need to import the necessary libraries,
OpenCV
NumPy
Then read the image on which you are going to draw the shape, and then call the line function on OpenCV to draw a line across the given coordinates of the x-axis and y-axis which are basically the starting and ending pixel’s location on the image. In OpenCV, for some reason, the x and y planes are straight opposite to the normal cartesian planes we use. Where the x-axis is at the top edge and the y-axis is at the left edge of an image but upside down which implies the increase in the x-axis means moving towards the right of the image and increase in the y-axis means moving down the image.
And to get the image’s width and height we need to call a simple function in OpenCV which will return the shape of the image and from that, we can get the width and height of the image and we can use it on the program. Simply call the .shape method on the image to get the dimensions.
The program to draw a cross on an image,
Python3
# Importing the necessary librariesimport cv2import numpy # Reading the imageimage = cv2.imread('image.png') # Getting the height and width of the imageheight = image.shape[0]width = image.shape[1] # Drawing the linescv2.line(image, (0, 0), (width, height), (0, 0, 255), 5)cv2.line(image, (width, 0), (0, height), (0, 0, 255), 5) # Showing the imagecv2.imshow('image', image) cv2.waitKey(0)cv2.destroyAllWindows()
Output:
Note: You can mention the starting and ending pixel of your choice to make the cross small and large according to your needs
Now let’s see how to draw an image on a video from a live camera feed of our machine. For this, we first need to initiate our live webcam, and then we need to capture an image every millisecond and show it one another one to get a video from our webcam and then add the overlay lines on every single frame that we capture from the webcam every single millisecond to achieve the result.
Note: To know more about using a webcam with OpenCV refer – Accessing webcam using Python-OpenCV
Python3
# Importing the librariesimport cv2import numpy # Initiating the webcamvid = cv2.VideoCapture(0) # Capturing frames and showing as a videowhile(True): ret, frame = vid.read() # Getting the width and height of the feed height = int(vid.get(4)) width = int(vid.get(3)) # Drawing cross on the webcam feed cv2.line(frame, (0, 0), (width, height), (0, 0, 255), 5) cv2.line(frame, (width, 0), (0, height), (0, 0, 255), 5) # Showing the video cv2.imshow('LIVE', frame) # Making sure that we have a key to break the while loop # Which checks for the ascii value of the key pressed if cv2.waitKey(1) & 0xFF == ord('q'): break# At last release the cameravid.release()cv2.destroyAllWindows()
Output:
We can do many things with the base we just learned. We can make wonders in OpenCV. Now for example we can create across by just manually selecting the area in an image. All we have to do is manually select the image’s area where we need to draw the cross. For this, we are going to use selectROI() function from OpenCV which will return the coordinates of the selected range of interest in the image Using those coordinates we can draw the cross and show the output.
Syntax: cv2.selectROI(Window_name, source image)
Parameter:
window_name: name of the window where selection process will be shown.
source image: image to select a ROI.
showCrosshair: if true crosshair of the selection rectangle will be displayed.
fromCenter: if true origin of selection will match initial mouse position
Example:
Python3
# Importing the modulesimport cv2import numpy # Reading the imageimage = cv2.imread('image.png') # Function to manually select the arear = cv2.selectROI("select the area", image) # Calculating the coordinates with the coordinates# returned by the functionopposite_x = int(r[2]) - int(r[0])bottom_y = int(r[1]) + (int(r[3]) - int(r[1])) # Drawing the cross by the calculated and# obtained coordinatescv2.line(image, (int(r[0]), int(r[1])), (int(r[2]), int(r[3])), (0, 0, 255), 5)cv2.line(image, (opposite_x, int(r[1])), (int(r[0]), bottom_y), (0, 0, 255), 5) # Showing the imagecv2.imshow('image', image) cv2.waitKey(0)cv2.destroyAllWindows()
Output:
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 24080,
"s": 23901,
"text": "In this article, we are going to discuss how to draw a cross on an image using OpenCV-Python. We can draw an overlay of two lines one above another to make a cross on an image. "
},
{
"code": null,
"e": 24134,
"s": 24080,
"text": "To draw a line on OpenCV, the below function is used."
},
{
"code": null,
"e": 24206,
"s": 24134,
"text": "Syntax: cv2.line(image, starting Point, ending Point, color, thickness)"
},
{
"code": null,
"e": 24220,
"s": 24206,
"text": "Parameters: "
},
{
"code": null,
"e": 24282,
"s": 24220,
"text": "Image – The source image on which you need to draw the shape."
},
{
"code": null,
"e": 24474,
"s": 24282,
"text": "startingPoint – The coordinates of the image where the line should start. Which is represented by a tuple of co-ordinates (x-axis, y-axis), basically the pixel’s location from where to start."
},
{
"code": null,
"e": 24610,
"s": 24474,
"text": "endingPoint – The coordinates of the image where the line should end. Which is represented by a tuple of co-ordinates (x-axis, y-axis)."
},
{
"code": null,
"e": 24793,
"s": 24610,
"text": "Color – Color of the line drawn on the image. Represented by BGR color values on a tuple in which each value is between 0 – 255(255,0,0) for BLUE(0,255,0) for GREEN(0,0,255) for RED]"
},
{
"code": null,
"e": 24812,
"s": 24793,
"text": "(255,0,0) for BLUE"
},
{
"code": null,
"e": 24832,
"s": 24812,
"text": "(0,255,0) for GREEN"
},
{
"code": null,
"e": 24851,
"s": 24832,
"text": "(0,0,255) for RED]"
},
{
"code": null,
"e": 24902,
"s": 24851,
"text": "Thickness – Thickness of the drawn line in pixels."
},
{
"code": null,
"e": 24979,
"s": 24902,
"text": "To draw a cross on an image we first need to import the necessary libraries,"
},
{
"code": null,
"e": 24986,
"s": 24979,
"text": "OpenCV"
},
{
"code": null,
"e": 24992,
"s": 24986,
"text": "NumPy"
},
{
"code": null,
"e": 25588,
"s": 24992,
"text": "Then read the image on which you are going to draw the shape, and then call the line function on OpenCV to draw a line across the given coordinates of the x-axis and y-axis which are basically the starting and ending pixel’s location on the image. In OpenCV, for some reason, the x and y planes are straight opposite to the normal cartesian planes we use. Where the x-axis is at the top edge and the y-axis is at the left edge of an image but upside down which implies the increase in the x-axis means moving towards the right of the image and increase in the y-axis means moving down the image."
},
{
"code": null,
"e": 25873,
"s": 25588,
"text": "And to get the image’s width and height we need to call a simple function in OpenCV which will return the shape of the image and from that, we can get the width and height of the image and we can use it on the program. Simply call the .shape method on the image to get the dimensions."
},
{
"code": null,
"e": 25914,
"s": 25873,
"text": "The program to draw a cross on an image,"
},
{
"code": null,
"e": 25922,
"s": 25914,
"text": "Python3"
},
{
"code": "# Importing the necessary librariesimport cv2import numpy # Reading the imageimage = cv2.imread('image.png') # Getting the height and width of the imageheight = image.shape[0]width = image.shape[1] # Drawing the linescv2.line(image, (0, 0), (width, height), (0, 0, 255), 5)cv2.line(image, (width, 0), (0, height), (0, 0, 255), 5) # Showing the imagecv2.imshow('image', image) cv2.waitKey(0)cv2.destroyAllWindows()",
"e": 26336,
"s": 25922,
"text": null
},
{
"code": null,
"e": 26344,
"s": 26336,
"text": "Output:"
},
{
"code": null,
"e": 26469,
"s": 26344,
"text": "Note: You can mention the starting and ending pixel of your choice to make the cross small and large according to your needs"
},
{
"code": null,
"e": 26855,
"s": 26469,
"text": "Now let’s see how to draw an image on a video from a live camera feed of our machine. For this, we first need to initiate our live webcam, and then we need to capture an image every millisecond and show it one another one to get a video from our webcam and then add the overlay lines on every single frame that we capture from the webcam every single millisecond to achieve the result."
},
{
"code": null,
"e": 26952,
"s": 26855,
"text": "Note: To know more about using a webcam with OpenCV refer – Accessing webcam using Python-OpenCV"
},
{
"code": null,
"e": 26960,
"s": 26952,
"text": "Python3"
},
{
"code": "# Importing the librariesimport cv2import numpy # Initiating the webcamvid = cv2.VideoCapture(0) # Capturing frames and showing as a videowhile(True): ret, frame = vid.read() # Getting the width and height of the feed height = int(vid.get(4)) width = int(vid.get(3)) # Drawing cross on the webcam feed cv2.line(frame, (0, 0), (width, height), (0, 0, 255), 5) cv2.line(frame, (width, 0), (0, height), (0, 0, 255), 5) # Showing the video cv2.imshow('LIVE', frame) # Making sure that we have a key to break the while loop # Which checks for the ascii value of the key pressed if cv2.waitKey(1) & 0xFF == ord('q'): break# At last release the cameravid.release()cv2.destroyAllWindows()",
"e": 27688,
"s": 26960,
"text": null
},
{
"code": null,
"e": 27696,
"s": 27688,
"text": "Output:"
},
{
"code": null,
"e": 28166,
"s": 27696,
"text": "We can do many things with the base we just learned. We can make wonders in OpenCV. Now for example we can create across by just manually selecting the area in an image. All we have to do is manually select the image’s area where we need to draw the cross. For this, we are going to use selectROI() function from OpenCV which will return the coordinates of the selected range of interest in the image Using those coordinates we can draw the cross and show the output. "
},
{
"code": null,
"e": 28215,
"s": 28166,
"text": "Syntax: cv2.selectROI(Window_name, source image)"
},
{
"code": null,
"e": 28226,
"s": 28215,
"text": "Parameter:"
},
{
"code": null,
"e": 28298,
"s": 28226,
"text": "window_name: name of the window where selection process will be shown."
},
{
"code": null,
"e": 28336,
"s": 28298,
"text": "source image: image to select a ROI."
},
{
"code": null,
"e": 28415,
"s": 28336,
"text": "showCrosshair: if true crosshair of the selection rectangle will be displayed."
},
{
"code": null,
"e": 28489,
"s": 28415,
"text": "fromCenter: if true origin of selection will match initial mouse position"
},
{
"code": null,
"e": 28498,
"s": 28489,
"text": "Example:"
},
{
"code": null,
"e": 28506,
"s": 28498,
"text": "Python3"
},
{
"code": "# Importing the modulesimport cv2import numpy # Reading the imageimage = cv2.imread('image.png') # Function to manually select the arear = cv2.selectROI(\"select the area\", image) # Calculating the coordinates with the coordinates# returned by the functionopposite_x = int(r[2]) - int(r[0])bottom_y = int(r[1]) + (int(r[3]) - int(r[1])) # Drawing the cross by the calculated and# obtained coordinatescv2.line(image, (int(r[0]), int(r[1])), (int(r[2]), int(r[3])), (0, 0, 255), 5)cv2.line(image, (opposite_x, int(r[1])), (int(r[0]), bottom_y), (0, 0, 255), 5) # Showing the imagecv2.imshow('image', image) cv2.waitKey(0)cv2.destroyAllWindows()",
"e": 29148,
"s": 28506,
"text": null
},
{
"code": null,
"e": 29156,
"s": 29148,
"text": "Output:"
},
{
"code": null,
"e": 29163,
"s": 29156,
"text": "Picked"
},
{
"code": null,
"e": 29177,
"s": 29163,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 29184,
"s": 29177,
"text": "Python"
},
{
"code": null,
"e": 29282,
"s": 29184,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29291,
"s": 29282,
"text": "Comments"
},
{
"code": null,
"e": 29304,
"s": 29291,
"text": "Old Comments"
},
{
"code": null,
"e": 29336,
"s": 29304,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29392,
"s": 29336,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29434,
"s": 29392,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29476,
"s": 29434,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29512,
"s": 29476,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 29534,
"s": 29512,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29573,
"s": 29534,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29600,
"s": 29573,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29631,
"s": 29600,
"text": "Python | os.path.join() method"
}
] |
java.time.Duration.ofSeconds() Method Example | The java.time.Duration.ofSeconds(long seconds) method obtains a Duration representing a number of standard seconds.
Following is the declaration for java.time.Duration.ofSeconds(long seconds) method.
public static Duration ofSeconds(long seconds)
seconds − the number of seconds, positive or negative.
a Duration, not null.
ArithmeticException − if the input seconds exceeds the capacity of Duration.
The following example shows the usage of java.time.Duration.ofSeconds(long seconds) method.
package com.tutorialspoint;
import java.time.Duration;
public class DurationDemo {
public static void main(String[] args) {
Duration duration = Duration.ofSeconds(2);
System.out.println(duration.getSeconds());
}
}
Let us compile and run the above program, this will produce the following result −
2
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2031,
"s": 1915,
"text": "The java.time.Duration.ofSeconds(long seconds) method obtains a Duration representing a number of standard seconds."
},
{
"code": null,
"e": 2115,
"s": 2031,
"text": "Following is the declaration for java.time.Duration.ofSeconds(long seconds) method."
},
{
"code": null,
"e": 2163,
"s": 2115,
"text": "public static Duration ofSeconds(long seconds)\n"
},
{
"code": null,
"e": 2218,
"s": 2163,
"text": "seconds − the number of seconds, positive or negative."
},
{
"code": null,
"e": 2240,
"s": 2218,
"text": "a Duration, not null."
},
{
"code": null,
"e": 2317,
"s": 2240,
"text": "ArithmeticException − if the input seconds exceeds the capacity of Duration."
},
{
"code": null,
"e": 2409,
"s": 2317,
"text": "The following example shows the usage of java.time.Duration.ofSeconds(long seconds) method."
},
{
"code": null,
"e": 2650,
"s": 2409,
"text": "package com.tutorialspoint;\n\nimport java.time.Duration;\n\npublic class DurationDemo {\n public static void main(String[] args) {\n\n Duration duration = Duration.ofSeconds(2);\n System.out.println(duration.getSeconds()); \n }\n}"
},
{
"code": null,
"e": 2733,
"s": 2650,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 2736,
"s": 2733,
"text": "2\n"
},
{
"code": null,
"e": 2743,
"s": 2736,
"text": " Print"
},
{
"code": null,
"e": 2754,
"s": 2743,
"text": " Add Notes"
}
] |
Removing redundant elements from array altogether - JavaScript | We are required to write a function that takes in an array and returns a new array that have all duplicate values removed from it. The values that appeared more than once in the original array should not even appear for once in the new array.
For example, if the input is −
const arr = [763,55,43,22,32,43,763,43];
The output should be −
const output = [55, 22, 32];
We will be using the following two methods −
Array.prototype.indexOf() −It returns the index of first occurrence of searched string if it exists, otherwise -1.
It returns the index of first occurrence of searched string if it exists, otherwise -1.
Array.prototype.lastIndexOf()It returns the index of last occurrence of searched string if it exists, otherwise -1.
It returns the index of last occurrence of searched string if it exists, otherwise -1.
Following is the code −
const arr = [763,55,43,22,32,43,763,43];
const deleteDuplicate = (arr) => {
const output = arr.filter((item, index, array) => {
return array.indexOf(item) === array.lastIndexOf(item);
});
return output;
};
console.log(deleteDuplicate(arr));
This will produce the following output in console −
[ 55, 22, 32 ] | [
{
"code": null,
"e": 1305,
"s": 1062,
"text": "We are required to write a function that takes in an array and returns a new array that have all duplicate values removed from it. The values that appeared more than once in the original array should not even appear for once in the new array."
},
{
"code": null,
"e": 1336,
"s": 1305,
"text": "For example, if the input is −"
},
{
"code": null,
"e": 1377,
"s": 1336,
"text": "const arr = [763,55,43,22,32,43,763,43];"
},
{
"code": null,
"e": 1400,
"s": 1377,
"text": "The output should be −"
},
{
"code": null,
"e": 1429,
"s": 1400,
"text": "const output = [55, 22, 32];"
},
{
"code": null,
"e": 1474,
"s": 1429,
"text": "We will be using the following two methods −"
},
{
"code": null,
"e": 1589,
"s": 1474,
"text": "Array.prototype.indexOf() −It returns the index of first occurrence of searched string if it exists, otherwise -1."
},
{
"code": null,
"e": 1677,
"s": 1589,
"text": "It returns the index of first occurrence of searched string if it exists, otherwise -1."
},
{
"code": null,
"e": 1793,
"s": 1677,
"text": "Array.prototype.lastIndexOf()It returns the index of last occurrence of searched string if it exists, otherwise -1."
},
{
"code": null,
"e": 1880,
"s": 1793,
"text": "It returns the index of last occurrence of searched string if it exists, otherwise -1."
},
{
"code": null,
"e": 1904,
"s": 1880,
"text": "Following is the code −"
},
{
"code": null,
"e": 2160,
"s": 1904,
"text": "const arr = [763,55,43,22,32,43,763,43];\nconst deleteDuplicate = (arr) => {\n const output = arr.filter((item, index, array) => {\n return array.indexOf(item) === array.lastIndexOf(item);\n });\n return output;\n};\nconsole.log(deleteDuplicate(arr));"
},
{
"code": null,
"e": 2212,
"s": 2160,
"text": "This will produce the following output in console −"
},
{
"code": null,
"e": 2227,
"s": 2212,
"text": "[ 55, 22, 32 ]"
}
] |
How To Build A Real-time Data Pipeline For An Online Store Using Apache Beam, Pub/Sub, and SQL | by Aakash Rathor | Towards Data Science | It is fascinating to see how malleable our data is becoming. Nowadays we have tools to convert highly nested and complex log data to simple rows format, tools to store and process petabytes of transaction data, and tools to capture raw data as soon as it gets generated, to process and provide useful insights from it.
In this article, I would like to share one such step-by-step process of generating, ingesting, processing, and finally utilizing real-time data from our own virtual online store.
Google Cloud Platform account (If you don’t have an account sign up here for a 3-month free trial with $300 credit to use).Linux OS.Python 3.
Google Cloud Platform account (If you don’t have an account sign up here for a 3-month free trial with $300 credit to use).
Linux OS.
Python 3.
Pub/Sub is a messaging service available in the Google Cloud Platform. It can be considered as a managed version of Apache Kafka or Rabbitmq.
A messaging service basically de-couples the system which produces data(virtual store application in our case) from the system which processes the data(Apache beam on Dataflow in our case).
First, we need to create a service account in GCP which will allow us to access Pub/Sub from our application and Apache beam:
Login into your GCP console and select the IAM & Admin from the left menu:
Select the Service Accounts option and create a new service account:
Provide the Pub/Sub Admin role to our service account:
And finally, Create a key and download the private key JSON file for later use:
Next, we will create a topic in Pub/Sub to publish our virtual store data into it and a subscriber to pull data from it using Apache Beam.
Select Pub/Sub from the left menu of the GCP console.
Select Topics from the sub-menu. From the top, select CREATE TOPIC. Enter a suitable name and click CREATE TOPIC.
Now, select the Subscriptions option from the left and from the top, select CREATE SUBSCRIPTION. Enter a suitable name, select the topic from the drop-down (we created in the previous step) to which the subscriber will listen for the stream of data. After that click Create at the end, keeping other options as it is.
Now we will create a virtual online store that will push the transaction data into the pub/sub Topic that we have created in previous steps.
I have used Dash which is a tool created by Plotly to quickly build a web application using different prebuild UI components like button, text input, etc. A complete tutorial to build a web application is out of this article’s scope since our main focus is to build a realtime pipeline. So you can just download the complete application from the GitHub repo Here.
The only thing important is the script which publishes our data into the Pub/Sub topic:
Let's start our online virtual store, after downloading the project from the Git create a virtual python environment and install all the packages using the requirement .txt file. Now open the folder in the terminal and run app.py file. You will see the below output:
Go to your web browser and open localhost:8085. You will see the virtual store home page.
Now the fun part lets order a few items and see how our data is getting published into the pub/sub topic and then pulled by the subscriber, that we have created earlier. Add some quantity for each item and click Submit:
You can see in the terminal some transaction data in JSON format is getting printed every time you place an order. Same JSON data is pushed to the Pub/Sub Topic also. Let’s pull the data from our subscriber, go to the pub/sub dashboard in GCP select the Subscriptions option from the left menu after that click on VIEW MESSAGES from the top and then click Pull to see the published data:
At this stage, we are getting the data in real-time from our virtual online store to our Pub/Sub subscriber. Now we are going to write our pipeline in Apache Beam to unnest the data and convert it into row like format to store it in MySQL server. And finally, we will run our pipeline using GCP Dataflow runner.
Before we start writing our data pipeline let’s create a cloud SQL instance in GCP which will be our final destination to store processed data, you can use other cloud SQL services as well, I have written my pipeline for MySQL server.
From the GCP console, select the SQL option from the left menu:
Select CREATE INSTANCE:
Select MySQL:
Enter Instance Name and Password for the root user, leave other settings to default and click Create, Now sit back and relax it will take 5–10 min to start the instance:
After the DB is up and running we need to create a database and table. Connect with your MySQL instance using any SQL client and run below queries:
CREATE DATABASE virtual_store;CREATE TABLE transaction_data(`id` int(11) NOT NULL AUTO_INCREMENT,`order_id` VARCHAR(255),`timestamp` INT(11),`item_id` VARCHAR(255),`item_name` VARCHAR(255),`category_name` VARCHAR(255),`item_price` FLOAT,`item_qty` INT,PRIMARY KEY(`id`));
Till now have created our source (Pub/Sub Subscriber ) and Sink (MySQL), now we will create our data pipeline.
Representation of directory for our pipeline is given below, you can clone the complete directory from my GitHub repo here:
├── dataflow_pipeline│ ├── mainPipeline.py│ ├── pipeline_config.py│ ├── requirement.txt│ └── setup.py
Let's start first with the configuration file pipeline_config.py ,this file contains all the configuration like Pub/Sub subscriber details, service account key path, MySQL DB connection details, and table details.
Next is the main pipeline file, mainPipeline.py , this is the entry point for different runners (local, Dataflow, etc) for running the pipeline. In this pipeline script, we are reading data from the Pub/Sub, unnesting the data, and storing the final data in a relational database. Later we will visualize it using Google Data studio. Let's look at the code:
First, let's run our pipeline in local:
python mainPipeline.py
You will see the below output, this means our pipeline is now listening to Pub/Sub for incoming data.
Let’s place some orders from our virtual online store and see the output of the pipeline.
After clicking submit you will immediately see the output in the pipeline terminal:
As you can see our input was nested data in which all the items are nested in a single object, but our pipeline unnested the data into row level.
Let’s check our database table:
As expected our single order is transformed into item wise row-level data and inserted in our database on the fly, in real-time.
Now we will run our pipeline in GCP Dataflow, for this, we need to run below command:
python mainPipeline.py --runner DataflowRunner \--project hadooptest-223316 \--temp_location gs://dataflow-stag-bucket/ \--requirements_file requirement.txt \--setup_file ./setup.py
Make sure you create a staging bucket in GCP as I did and provide the link in the above command under “temp_location” option and also create a setup.py in your directory with the below content, this will prevent ModuleNotFoundError.
Sit back and relax it will take 5–10 min to start the pipeline in GCP dataflow. Now go to the GCP Dataflow dashboard to check if the server started or not.
you can also see the different stages of the pipeline, click on the running job to see the details.
Place some orders from the virtual store and test if the data is coming in DB or not. In my case, it is working as expected. Rows of data in MySQL table is getting inserted in real-time:
Note: Closing our local terminal from which we deployed the pipeline in GCP won’t affect the pipeline running in Dataflow on GCP. Make sure to terminate the pipeline from the GCP as well.
Google Data Studio is a free tool for visualizing data. It enables users to create an interactive and effective reporting dashboard very quickly from different data sources.
Let's connect our sink (MySQL server) to the Data Studio and create a dashboard on the top of our real-time data.
Go to https://datastudio.google.com. Click on Create and select Data source.
Give a name to your source at the top left corner and select Cloud SQL for MYSQL as source (If your MySQL database is not in GCP select only MySQL)
Enter your DB credentials and click Authenticate. After that select CUSTOM QUERY, enter the query and select Connect at the top right corner.
Data Studio will connect to the cloud SQL instance and show us the schema of our table. Now click on CREATE REPORT at the top right corner:
Add charts and graphs as per your requirements. You can learn more about data studio here:
I have created a basic, 2 chart dashboard which shows Item wise quantity sold and Item wise sales.
My final Dashboard, which gets updated as soon as the orders are getting placed:
In this article, I explained how real-time pipeline works. We have created all the components of a data pipeline, a source application which generates data in real-time, a buffer which ingests the data, an actual pipeline in Google cloud Platform which processes the data, a sink to store the processed data, and finally a dashboard to visualize our final data.
Please leave your comment about this article below and in case you are facing issues in any of the steps specified above you can reach out to me through Instagram and LinkedIn. | [
{
"code": null,
"e": 490,
"s": 171,
"text": "It is fascinating to see how malleable our data is becoming. Nowadays we have tools to convert highly nested and complex log data to simple rows format, tools to store and process petabytes of transaction data, and tools to capture raw data as soon as it gets generated, to process and provide useful insights from it."
},
{
"code": null,
"e": 669,
"s": 490,
"text": "In this article, I would like to share one such step-by-step process of generating, ingesting, processing, and finally utilizing real-time data from our own virtual online store."
},
{
"code": null,
"e": 811,
"s": 669,
"text": "Google Cloud Platform account (If you don’t have an account sign up here for a 3-month free trial with $300 credit to use).Linux OS.Python 3."
},
{
"code": null,
"e": 935,
"s": 811,
"text": "Google Cloud Platform account (If you don’t have an account sign up here for a 3-month free trial with $300 credit to use)."
},
{
"code": null,
"e": 945,
"s": 935,
"text": "Linux OS."
},
{
"code": null,
"e": 955,
"s": 945,
"text": "Python 3."
},
{
"code": null,
"e": 1097,
"s": 955,
"text": "Pub/Sub is a messaging service available in the Google Cloud Platform. It can be considered as a managed version of Apache Kafka or Rabbitmq."
},
{
"code": null,
"e": 1287,
"s": 1097,
"text": "A messaging service basically de-couples the system which produces data(virtual store application in our case) from the system which processes the data(Apache beam on Dataflow in our case)."
},
{
"code": null,
"e": 1413,
"s": 1287,
"text": "First, we need to create a service account in GCP which will allow us to access Pub/Sub from our application and Apache beam:"
},
{
"code": null,
"e": 1488,
"s": 1413,
"text": "Login into your GCP console and select the IAM & Admin from the left menu:"
},
{
"code": null,
"e": 1557,
"s": 1488,
"text": "Select the Service Accounts option and create a new service account:"
},
{
"code": null,
"e": 1612,
"s": 1557,
"text": "Provide the Pub/Sub Admin role to our service account:"
},
{
"code": null,
"e": 1692,
"s": 1612,
"text": "And finally, Create a key and download the private key JSON file for later use:"
},
{
"code": null,
"e": 1831,
"s": 1692,
"text": "Next, we will create a topic in Pub/Sub to publish our virtual store data into it and a subscriber to pull data from it using Apache Beam."
},
{
"code": null,
"e": 1885,
"s": 1831,
"text": "Select Pub/Sub from the left menu of the GCP console."
},
{
"code": null,
"e": 1999,
"s": 1885,
"text": "Select Topics from the sub-menu. From the top, select CREATE TOPIC. Enter a suitable name and click CREATE TOPIC."
},
{
"code": null,
"e": 2317,
"s": 1999,
"text": "Now, select the Subscriptions option from the left and from the top, select CREATE SUBSCRIPTION. Enter a suitable name, select the topic from the drop-down (we created in the previous step) to which the subscriber will listen for the stream of data. After that click Create at the end, keeping other options as it is."
},
{
"code": null,
"e": 2458,
"s": 2317,
"text": "Now we will create a virtual online store that will push the transaction data into the pub/sub Topic that we have created in previous steps."
},
{
"code": null,
"e": 2822,
"s": 2458,
"text": "I have used Dash which is a tool created by Plotly to quickly build a web application using different prebuild UI components like button, text input, etc. A complete tutorial to build a web application is out of this article’s scope since our main focus is to build a realtime pipeline. So you can just download the complete application from the GitHub repo Here."
},
{
"code": null,
"e": 2910,
"s": 2822,
"text": "The only thing important is the script which publishes our data into the Pub/Sub topic:"
},
{
"code": null,
"e": 3177,
"s": 2910,
"text": "Let's start our online virtual store, after downloading the project from the Git create a virtual python environment and install all the packages using the requirement .txt file. Now open the folder in the terminal and run app.py file. You will see the below output:"
},
{
"code": null,
"e": 3267,
"s": 3177,
"text": "Go to your web browser and open localhost:8085. You will see the virtual store home page."
},
{
"code": null,
"e": 3487,
"s": 3267,
"text": "Now the fun part lets order a few items and see how our data is getting published into the pub/sub topic and then pulled by the subscriber, that we have created earlier. Add some quantity for each item and click Submit:"
},
{
"code": null,
"e": 3875,
"s": 3487,
"text": "You can see in the terminal some transaction data in JSON format is getting printed every time you place an order. Same JSON data is pushed to the Pub/Sub Topic also. Let’s pull the data from our subscriber, go to the pub/sub dashboard in GCP select the Subscriptions option from the left menu after that click on VIEW MESSAGES from the top and then click Pull to see the published data:"
},
{
"code": null,
"e": 4187,
"s": 3875,
"text": "At this stage, we are getting the data in real-time from our virtual online store to our Pub/Sub subscriber. Now we are going to write our pipeline in Apache Beam to unnest the data and convert it into row like format to store it in MySQL server. And finally, we will run our pipeline using GCP Dataflow runner."
},
{
"code": null,
"e": 4422,
"s": 4187,
"text": "Before we start writing our data pipeline let’s create a cloud SQL instance in GCP which will be our final destination to store processed data, you can use other cloud SQL services as well, I have written my pipeline for MySQL server."
},
{
"code": null,
"e": 4486,
"s": 4422,
"text": "From the GCP console, select the SQL option from the left menu:"
},
{
"code": null,
"e": 4510,
"s": 4486,
"text": "Select CREATE INSTANCE:"
},
{
"code": null,
"e": 4524,
"s": 4510,
"text": "Select MySQL:"
},
{
"code": null,
"e": 4694,
"s": 4524,
"text": "Enter Instance Name and Password for the root user, leave other settings to default and click Create, Now sit back and relax it will take 5–10 min to start the instance:"
},
{
"code": null,
"e": 4842,
"s": 4694,
"text": "After the DB is up and running we need to create a database and table. Connect with your MySQL instance using any SQL client and run below queries:"
},
{
"code": null,
"e": 5114,
"s": 4842,
"text": "CREATE DATABASE virtual_store;CREATE TABLE transaction_data(`id` int(11) NOT NULL AUTO_INCREMENT,`order_id` VARCHAR(255),`timestamp` INT(11),`item_id` VARCHAR(255),`item_name` VARCHAR(255),`category_name` VARCHAR(255),`item_price` FLOAT,`item_qty` INT,PRIMARY KEY(`id`));"
},
{
"code": null,
"e": 5225,
"s": 5114,
"text": "Till now have created our source (Pub/Sub Subscriber ) and Sink (MySQL), now we will create our data pipeline."
},
{
"code": null,
"e": 5349,
"s": 5225,
"text": "Representation of directory for our pipeline is given below, you can clone the complete directory from my GitHub repo here:"
},
{
"code": null,
"e": 5459,
"s": 5349,
"text": "├── dataflow_pipeline│ ├── mainPipeline.py│ ├── pipeline_config.py│ ├── requirement.txt│ └── setup.py"
},
{
"code": null,
"e": 5673,
"s": 5459,
"text": "Let's start first with the configuration file pipeline_config.py ,this file contains all the configuration like Pub/Sub subscriber details, service account key path, MySQL DB connection details, and table details."
},
{
"code": null,
"e": 6031,
"s": 5673,
"text": "Next is the main pipeline file, mainPipeline.py , this is the entry point for different runners (local, Dataflow, etc) for running the pipeline. In this pipeline script, we are reading data from the Pub/Sub, unnesting the data, and storing the final data in a relational database. Later we will visualize it using Google Data studio. Let's look at the code:"
},
{
"code": null,
"e": 6071,
"s": 6031,
"text": "First, let's run our pipeline in local:"
},
{
"code": null,
"e": 6094,
"s": 6071,
"text": "python mainPipeline.py"
},
{
"code": null,
"e": 6196,
"s": 6094,
"text": "You will see the below output, this means our pipeline is now listening to Pub/Sub for incoming data."
},
{
"code": null,
"e": 6286,
"s": 6196,
"text": "Let’s place some orders from our virtual online store and see the output of the pipeline."
},
{
"code": null,
"e": 6370,
"s": 6286,
"text": "After clicking submit you will immediately see the output in the pipeline terminal:"
},
{
"code": null,
"e": 6516,
"s": 6370,
"text": "As you can see our input was nested data in which all the items are nested in a single object, but our pipeline unnested the data into row level."
},
{
"code": null,
"e": 6548,
"s": 6516,
"text": "Let’s check our database table:"
},
{
"code": null,
"e": 6677,
"s": 6548,
"text": "As expected our single order is transformed into item wise row-level data and inserted in our database on the fly, in real-time."
},
{
"code": null,
"e": 6763,
"s": 6677,
"text": "Now we will run our pipeline in GCP Dataflow, for this, we need to run below command:"
},
{
"code": null,
"e": 6945,
"s": 6763,
"text": "python mainPipeline.py --runner DataflowRunner \\--project hadooptest-223316 \\--temp_location gs://dataflow-stag-bucket/ \\--requirements_file requirement.txt \\--setup_file ./setup.py"
},
{
"code": null,
"e": 7178,
"s": 6945,
"text": "Make sure you create a staging bucket in GCP as I did and provide the link in the above command under “temp_location” option and also create a setup.py in your directory with the below content, this will prevent ModuleNotFoundError."
},
{
"code": null,
"e": 7334,
"s": 7178,
"text": "Sit back and relax it will take 5–10 min to start the pipeline in GCP dataflow. Now go to the GCP Dataflow dashboard to check if the server started or not."
},
{
"code": null,
"e": 7434,
"s": 7334,
"text": "you can also see the different stages of the pipeline, click on the running job to see the details."
},
{
"code": null,
"e": 7621,
"s": 7434,
"text": "Place some orders from the virtual store and test if the data is coming in DB or not. In my case, it is working as expected. Rows of data in MySQL table is getting inserted in real-time:"
},
{
"code": null,
"e": 7809,
"s": 7621,
"text": "Note: Closing our local terminal from which we deployed the pipeline in GCP won’t affect the pipeline running in Dataflow on GCP. Make sure to terminate the pipeline from the GCP as well."
},
{
"code": null,
"e": 7983,
"s": 7809,
"text": "Google Data Studio is a free tool for visualizing data. It enables users to create an interactive and effective reporting dashboard very quickly from different data sources."
},
{
"code": null,
"e": 8097,
"s": 7983,
"text": "Let's connect our sink (MySQL server) to the Data Studio and create a dashboard on the top of our real-time data."
},
{
"code": null,
"e": 8174,
"s": 8097,
"text": "Go to https://datastudio.google.com. Click on Create and select Data source."
},
{
"code": null,
"e": 8322,
"s": 8174,
"text": "Give a name to your source at the top left corner and select Cloud SQL for MYSQL as source (If your MySQL database is not in GCP select only MySQL)"
},
{
"code": null,
"e": 8464,
"s": 8322,
"text": "Enter your DB credentials and click Authenticate. After that select CUSTOM QUERY, enter the query and select Connect at the top right corner."
},
{
"code": null,
"e": 8604,
"s": 8464,
"text": "Data Studio will connect to the cloud SQL instance and show us the schema of our table. Now click on CREATE REPORT at the top right corner:"
},
{
"code": null,
"e": 8695,
"s": 8604,
"text": "Add charts and graphs as per your requirements. You can learn more about data studio here:"
},
{
"code": null,
"e": 8794,
"s": 8695,
"text": "I have created a basic, 2 chart dashboard which shows Item wise quantity sold and Item wise sales."
},
{
"code": null,
"e": 8875,
"s": 8794,
"text": "My final Dashboard, which gets updated as soon as the orders are getting placed:"
},
{
"code": null,
"e": 9237,
"s": 8875,
"text": "In this article, I explained how real-time pipeline works. We have created all the components of a data pipeline, a source application which generates data in real-time, a buffer which ingests the data, an actual pipeline in Google cloud Platform which processes the data, a sink to store the processed data, and finally a dashboard to visualize our final data."
}
] |
Deploy your Python app with AWS Fargate — A Tutorial | by Daniel Deutsch | Towards Data Science | About this article
What AWS infrastructure type should I use
AWS account
Set up AWS credentials
Set up credentials with users and roles in IAM
Create a Repository in Elastic Container Registry (ECR)
Configure a cluster
Create task to run Docker container in AWS
Execute Task
Expose defined port within webpage
Watch your app online
Bonus: Investigate Errors
Disclaimer
About
In this article, I will go over the steps to launch a sample web app within AWS. In my last articles, I talked about creating an own web app with python and also how to deploy it with AWS Lambda:
Develop and sell a machine learning app
Develop and sell a python app
Now I want to test out another infrastructure type. This article assumes that you are familiar with building and containerizing a web app. In a python setting, I always use Flask and Docker (see previous articles). However, this article focuses on the “devops” perspective of deploying such an app. There are still more aspects that I will cover in the following articles, like setting up a proper domain name and use additional services like load balancing.
I use AWS because I already got into it in my last projects and find it well documented and intuitive to handle even though there are so many options to choose from.
As you can see from the table of contents the main parts of this article will be:
set up and connect local development with AWS credentials
create a repository in an Elastic Container Registry (AWS ECR)
create cluster and task to run a docker container in the cloud
Here is a fantastic article I want to recommend: https://medium.com/thundra/getting-it-right-between-ec2-fargate-and-lambda-bb42220b8c79
He summarized it perfectly in my opinion. So what I want is to deploy my container, but do not want to get any deeper into the infrastructure. That’s why I go with AWS Fargate.
First, you need to create an AWS account. They will guide you through the process and there are no difficulties to be expected.
If you having trouble in the credentials section, check out this article for reference.
First, you need to get an AWS access key id and access key
I break it down as simple as possible:
At the IAM Dashboard, click the “Add User” button.Give the user a name and select the Access Type for Programmatic access.In the Set permissions screen, select the the permission for AmazonEC2ContainerRegistryReadOnly, AmazonEC2ContainerRegistryFullAccess, AmazonEC2ContainerRegistryPowerUser.Tags are optional.Review the user details.Copy and save the user’s keys in a secure location as they will be needed in later stages.
At the IAM Dashboard, click the “Add User” button.
Give the user a name and select the Access Type for Programmatic access.
In the Set permissions screen, select the the permission for AmazonEC2ContainerRegistryReadOnly, AmazonEC2ContainerRegistryFullAccess, AmazonEC2ContainerRegistryPowerUser.
Tags are optional.
Review the user details.
Copy and save the user’s keys in a secure location as they will be needed in later stages.
Create a .aws/credentials folder in your root with
mkdir ~/.awscode ~/.aws/credentials
and paste your credentials from AWS
[dev]aws_access_key_id = YOUR_KEYaws_secret_access_key = YOUR_KEY
Same with the config
code ~/.aws/config[default]region = YOUR_REGION (eg. eu-central-1)
Note that code is for opening a folder with vscode, my editor of choice.
Save the AWS access key id and secret access key assigned to the User you created in the file ~/.aws/credentials. Note the .aws/ directory needs to be in your home directory and the credentials file has no file extension.
Search for ECR and then you will get to the page where you can create your new repository.
Afterward, you have your new repo visible:
Next, we want to get the push commands:
Just follow those instructions to set up your local repo for the AWS connection. Be aware that you are at the root of your project so everything works out smoothly.
Make sure that you have installed the AWS CLI or just follow the installing according to the official docs.
If you have problems here, just google the error message. Often there is an issue with policies and your user. This SO question helped me: https://stackoverflow.com/questions/38587325/aws-ecr-getauthorizationtoken
After executing the push commands you will have the image online:
Next, go to “clusters” (under Amazon ECS not EKS!) in the menu.
Choose “Network only” template
add a name
create
In this section, I sometimes got buggy error messages. If this happens to you you can simply re-create the cluster. If everything is set up correctly it should work.
Go to “task definitions” and create a new task with Fargate compatibility.
then
add a name
specify task size (I use the smallest options)
add container
add the name of your container
copy the image address you got from the CLI command where the image is pushed
add the exposed port (specified in your Dockerfile)
Then create the task
Now you should have defined a task within Fargate and connected your container.
Now you can run your defined task:
Select Fargate as lunch type and add the provided dropdown options within the form (cluster VPC and subnets)
Afterward, you can run the task and it should work like this:
As we defined a specific port we now need to expose it through the security tab.
Click your defined task
Click on ENI Id to get to the network interface
Click on your network ID
Go to “security groups”
Add your port as custom tcp in inbound rules
In the task tab, you will see your public IP displayed. Simply navigate to the page with the corresponding port and you will see your website
The IP address shown in the screenshot is not working anymore to avoid AWS costs. However, this article is part of a larger project, which I will launch under www.shouldibuycryptoart.com. The app is under development. If you wish to follow its development feel free to reach out to me or follow me social media accounts.
Due to some specific flags, I run on my local container development I get some errors for specific functions within my app.
In your task overview under containers, you can check the logs in cloudwatch. Click on the link and it shows you why your app crashes:
Now you can debug your app.
Happy coding!
I am not associated with any of the services I use in this article.
I do not consider myself an expert. I merely document things besides doing other things. Therefore the content does not represent the quality of any of my professional work, nor does it fully reflect my view on things. If you have the feeling that I am missing important steps or neglected something, consider pointing it out in the comment section or get in touch with me.
This was written on 6.3.2021. I cannot monitor all of my articles. There is a high probability that when you read this article the tips are outdated and the processes have changed.
I am always happy for constructive input and how to improve.
Daniel is an artist, entrepreneur, software developer, and business law graduate. His knowledge and interests currently revolve around programming machine learning applications and all their related aspects. To the core, he considers himself a problem solver of complex environments, which is reflected in his various projects. | [
{
"code": null,
"e": 191,
"s": 172,
"text": "About this article"
},
{
"code": null,
"e": 233,
"s": 191,
"text": "What AWS infrastructure type should I use"
},
{
"code": null,
"e": 245,
"s": 233,
"text": "AWS account"
},
{
"code": null,
"e": 268,
"s": 245,
"text": "Set up AWS credentials"
},
{
"code": null,
"e": 315,
"s": 268,
"text": "Set up credentials with users and roles in IAM"
},
{
"code": null,
"e": 371,
"s": 315,
"text": "Create a Repository in Elastic Container Registry (ECR)"
},
{
"code": null,
"e": 391,
"s": 371,
"text": "Configure a cluster"
},
{
"code": null,
"e": 434,
"s": 391,
"text": "Create task to run Docker container in AWS"
},
{
"code": null,
"e": 447,
"s": 434,
"text": "Execute Task"
},
{
"code": null,
"e": 482,
"s": 447,
"text": "Expose defined port within webpage"
},
{
"code": null,
"e": 504,
"s": 482,
"text": "Watch your app online"
},
{
"code": null,
"e": 530,
"s": 504,
"text": "Bonus: Investigate Errors"
},
{
"code": null,
"e": 541,
"s": 530,
"text": "Disclaimer"
},
{
"code": null,
"e": 547,
"s": 541,
"text": "About"
},
{
"code": null,
"e": 743,
"s": 547,
"text": "In this article, I will go over the steps to launch a sample web app within AWS. In my last articles, I talked about creating an own web app with python and also how to deploy it with AWS Lambda:"
},
{
"code": null,
"e": 783,
"s": 743,
"text": "Develop and sell a machine learning app"
},
{
"code": null,
"e": 813,
"s": 783,
"text": "Develop and sell a python app"
},
{
"code": null,
"e": 1272,
"s": 813,
"text": "Now I want to test out another infrastructure type. This article assumes that you are familiar with building and containerizing a web app. In a python setting, I always use Flask and Docker (see previous articles). However, this article focuses on the “devops” perspective of deploying such an app. There are still more aspects that I will cover in the following articles, like setting up a proper domain name and use additional services like load balancing."
},
{
"code": null,
"e": 1438,
"s": 1272,
"text": "I use AWS because I already got into it in my last projects and find it well documented and intuitive to handle even though there are so many options to choose from."
},
{
"code": null,
"e": 1520,
"s": 1438,
"text": "As you can see from the table of contents the main parts of this article will be:"
},
{
"code": null,
"e": 1578,
"s": 1520,
"text": "set up and connect local development with AWS credentials"
},
{
"code": null,
"e": 1641,
"s": 1578,
"text": "create a repository in an Elastic Container Registry (AWS ECR)"
},
{
"code": null,
"e": 1704,
"s": 1641,
"text": "create cluster and task to run a docker container in the cloud"
},
{
"code": null,
"e": 1841,
"s": 1704,
"text": "Here is a fantastic article I want to recommend: https://medium.com/thundra/getting-it-right-between-ec2-fargate-and-lambda-bb42220b8c79"
},
{
"code": null,
"e": 2018,
"s": 1841,
"text": "He summarized it perfectly in my opinion. So what I want is to deploy my container, but do not want to get any deeper into the infrastructure. That’s why I go with AWS Fargate."
},
{
"code": null,
"e": 2146,
"s": 2018,
"text": "First, you need to create an AWS account. They will guide you through the process and there are no difficulties to be expected."
},
{
"code": null,
"e": 2234,
"s": 2146,
"text": "If you having trouble in the credentials section, check out this article for reference."
},
{
"code": null,
"e": 2293,
"s": 2234,
"text": "First, you need to get an AWS access key id and access key"
},
{
"code": null,
"e": 2332,
"s": 2293,
"text": "I break it down as simple as possible:"
},
{
"code": null,
"e": 2758,
"s": 2332,
"text": "At the IAM Dashboard, click the “Add User” button.Give the user a name and select the Access Type for Programmatic access.In the Set permissions screen, select the the permission for AmazonEC2ContainerRegistryReadOnly, AmazonEC2ContainerRegistryFullAccess, AmazonEC2ContainerRegistryPowerUser.Tags are optional.Review the user details.Copy and save the user’s keys in a secure location as they will be needed in later stages."
},
{
"code": null,
"e": 2809,
"s": 2758,
"text": "At the IAM Dashboard, click the “Add User” button."
},
{
"code": null,
"e": 2882,
"s": 2809,
"text": "Give the user a name and select the Access Type for Programmatic access."
},
{
"code": null,
"e": 3054,
"s": 2882,
"text": "In the Set permissions screen, select the the permission for AmazonEC2ContainerRegistryReadOnly, AmazonEC2ContainerRegistryFullAccess, AmazonEC2ContainerRegistryPowerUser."
},
{
"code": null,
"e": 3073,
"s": 3054,
"text": "Tags are optional."
},
{
"code": null,
"e": 3098,
"s": 3073,
"text": "Review the user details."
},
{
"code": null,
"e": 3189,
"s": 3098,
"text": "Copy and save the user’s keys in a secure location as they will be needed in later stages."
},
{
"code": null,
"e": 3240,
"s": 3189,
"text": "Create a .aws/credentials folder in your root with"
},
{
"code": null,
"e": 3276,
"s": 3240,
"text": "mkdir ~/.awscode ~/.aws/credentials"
},
{
"code": null,
"e": 3312,
"s": 3276,
"text": "and paste your credentials from AWS"
},
{
"code": null,
"e": 3378,
"s": 3312,
"text": "[dev]aws_access_key_id = YOUR_KEYaws_secret_access_key = YOUR_KEY"
},
{
"code": null,
"e": 3399,
"s": 3378,
"text": "Same with the config"
},
{
"code": null,
"e": 3466,
"s": 3399,
"text": "code ~/.aws/config[default]region = YOUR_REGION (eg. eu-central-1)"
},
{
"code": null,
"e": 3539,
"s": 3466,
"text": "Note that code is for opening a folder with vscode, my editor of choice."
},
{
"code": null,
"e": 3761,
"s": 3539,
"text": "Save the AWS access key id and secret access key assigned to the User you created in the file ~/.aws/credentials. Note the .aws/ directory needs to be in your home directory and the credentials file has no file extension."
},
{
"code": null,
"e": 3852,
"s": 3761,
"text": "Search for ECR and then you will get to the page where you can create your new repository."
},
{
"code": null,
"e": 3895,
"s": 3852,
"text": "Afterward, you have your new repo visible:"
},
{
"code": null,
"e": 3935,
"s": 3895,
"text": "Next, we want to get the push commands:"
},
{
"code": null,
"e": 4100,
"s": 3935,
"text": "Just follow those instructions to set up your local repo for the AWS connection. Be aware that you are at the root of your project so everything works out smoothly."
},
{
"code": null,
"e": 4208,
"s": 4100,
"text": "Make sure that you have installed the AWS CLI or just follow the installing according to the official docs."
},
{
"code": null,
"e": 4422,
"s": 4208,
"text": "If you have problems here, just google the error message. Often there is an issue with policies and your user. This SO question helped me: https://stackoverflow.com/questions/38587325/aws-ecr-getauthorizationtoken"
},
{
"code": null,
"e": 4488,
"s": 4422,
"text": "After executing the push commands you will have the image online:"
},
{
"code": null,
"e": 4552,
"s": 4488,
"text": "Next, go to “clusters” (under Amazon ECS not EKS!) in the menu."
},
{
"code": null,
"e": 4583,
"s": 4552,
"text": "Choose “Network only” template"
},
{
"code": null,
"e": 4594,
"s": 4583,
"text": "add a name"
},
{
"code": null,
"e": 4601,
"s": 4594,
"text": "create"
},
{
"code": null,
"e": 4767,
"s": 4601,
"text": "In this section, I sometimes got buggy error messages. If this happens to you you can simply re-create the cluster. If everything is set up correctly it should work."
},
{
"code": null,
"e": 4842,
"s": 4767,
"text": "Go to “task definitions” and create a new task with Fargate compatibility."
},
{
"code": null,
"e": 4847,
"s": 4842,
"text": "then"
},
{
"code": null,
"e": 4858,
"s": 4847,
"text": "add a name"
},
{
"code": null,
"e": 4905,
"s": 4858,
"text": "specify task size (I use the smallest options)"
},
{
"code": null,
"e": 4919,
"s": 4905,
"text": "add container"
},
{
"code": null,
"e": 4950,
"s": 4919,
"text": "add the name of your container"
},
{
"code": null,
"e": 5028,
"s": 4950,
"text": "copy the image address you got from the CLI command where the image is pushed"
},
{
"code": null,
"e": 5080,
"s": 5028,
"text": "add the exposed port (specified in your Dockerfile)"
},
{
"code": null,
"e": 5101,
"s": 5080,
"text": "Then create the task"
},
{
"code": null,
"e": 5181,
"s": 5101,
"text": "Now you should have defined a task within Fargate and connected your container."
},
{
"code": null,
"e": 5216,
"s": 5181,
"text": "Now you can run your defined task:"
},
{
"code": null,
"e": 5325,
"s": 5216,
"text": "Select Fargate as lunch type and add the provided dropdown options within the form (cluster VPC and subnets)"
},
{
"code": null,
"e": 5387,
"s": 5325,
"text": "Afterward, you can run the task and it should work like this:"
},
{
"code": null,
"e": 5468,
"s": 5387,
"text": "As we defined a specific port we now need to expose it through the security tab."
},
{
"code": null,
"e": 5492,
"s": 5468,
"text": "Click your defined task"
},
{
"code": null,
"e": 5540,
"s": 5492,
"text": "Click on ENI Id to get to the network interface"
},
{
"code": null,
"e": 5565,
"s": 5540,
"text": "Click on your network ID"
},
{
"code": null,
"e": 5589,
"s": 5565,
"text": "Go to “security groups”"
},
{
"code": null,
"e": 5634,
"s": 5589,
"text": "Add your port as custom tcp in inbound rules"
},
{
"code": null,
"e": 5776,
"s": 5634,
"text": "In the task tab, you will see your public IP displayed. Simply navigate to the page with the corresponding port and you will see your website"
},
{
"code": null,
"e": 6097,
"s": 5776,
"text": "The IP address shown in the screenshot is not working anymore to avoid AWS costs. However, this article is part of a larger project, which I will launch under www.shouldibuycryptoart.com. The app is under development. If you wish to follow its development feel free to reach out to me or follow me social media accounts."
},
{
"code": null,
"e": 6221,
"s": 6097,
"text": "Due to some specific flags, I run on my local container development I get some errors for specific functions within my app."
},
{
"code": null,
"e": 6356,
"s": 6221,
"text": "In your task overview under containers, you can check the logs in cloudwatch. Click on the link and it shows you why your app crashes:"
},
{
"code": null,
"e": 6384,
"s": 6356,
"text": "Now you can debug your app."
},
{
"code": null,
"e": 6398,
"s": 6384,
"text": "Happy coding!"
},
{
"code": null,
"e": 6466,
"s": 6398,
"text": "I am not associated with any of the services I use in this article."
},
{
"code": null,
"e": 6840,
"s": 6466,
"text": "I do not consider myself an expert. I merely document things besides doing other things. Therefore the content does not represent the quality of any of my professional work, nor does it fully reflect my view on things. If you have the feeling that I am missing important steps or neglected something, consider pointing it out in the comment section or get in touch with me."
},
{
"code": null,
"e": 7021,
"s": 6840,
"text": "This was written on 6.3.2021. I cannot monitor all of my articles. There is a high probability that when you read this article the tips are outdated and the processes have changed."
},
{
"code": null,
"e": 7082,
"s": 7021,
"text": "I am always happy for constructive input and how to improve."
}
] |
Selenium - Webdriver | WebDriver is a tool for automating testing web applications. It is popularly known as Selenium 2.0. WebDriver uses a different underlying framework, while Selenium RC uses JavaScript Selenium-Core embedded within the browser which has got some limitations. WebDriver interacts directly with the browser without any intermediary, unlike Selenium RC that depends on a server. It is used in the following context −
Multi-browser testing including improved functionality for browsers which is not well-supported by Selenium RC (Selenium 1.0).
Multi-browser testing including improved functionality for browsers which is not well-supported by Selenium RC (Selenium 1.0).
Handling multiple frames, multiple browser windows, popups, and alerts.
Handling multiple frames, multiple browser windows, popups, and alerts.
Complex page navigation.
Complex page navigation.
Advanced user navigation such as drag-and-drop.
Advanced user navigation such as drag-and-drop.
AJAX-based UI elements.
AJAX-based UI elements.
WebDriver is best explained with a simple architecture diagram as shown below.
Let us understand how to work with WebDriver. For demonstration, we would use https://www.calculator.net/. We will perform a "Percent Calculator" which is located under "Math Calculator". We have already downloaded the required WebDriver JAR's. Refer the chapter "Environmental Setup" for details.
Step 1 − Launch "Eclipse" from the Extracted Eclipse folder.
Step 2 − Select the Workspace by clicking the 'Browse' button.
Step 3 − Now create a 'New Project' from 'File' menu.
Step 4 − Enter the Project Name and Click 'Next'.
Step 5 − Go to Libraries Tab and select all the JAR's that we have downloaded. Add reference to all the JAR's of Selenium WebDriver Library folder and also selenium-java-2.42.2.jar and selenium-java-2.42.2-srcs.jar.
Step 6 − The Package is created as shown below.
Step 7 − Now right-click on the package and select 'New' >> 'Class' to create a 'class'.
Step 8 − Now name the class and make it the main function.
Step 9 − The class outline is shown as below.
Step 10 − Now it is time to code. The following script is easier to understand, as it has comments embedded in it to explain the steps clearly. Please take a look at the chapter "Locators" to understand how to capture object properties.
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class webdriverdemo {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
//Puts an Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch website
driver.navigate().to("http://www.calculator.net/");
//Maximize the browser
driver.manage().window().maximize();
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[3]/a")).click();
// Click on Percent Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[4]/div[3]/a")).click();
// Enter value 10 in the first number of the percent Calculator
driver.findElement(By.id("cpar1")).sendKeys("10");
// Enter value 50 in the second number of the percent Calculator
driver.findElement(By.id("cpar2")).sendKeys("50");
// Click Calculate Button
driver.findElement(By.xpath(".//*[@id = 'content']/table/tbody/tr[2]/td/input[2]")).click();
// Get the Result Text based on its xpath
String result =
driver.findElement(By.xpath(".//*[@id = 'content']/p[2]/font/b")).getText();
// Print a Log In message to the screen
System.out.println(" The Result is " + result);
//Close the Browser.
driver.close();
}
}
Step 11 − The output of the above script would be printed in Console.
The following table lists some of the most frequently used commands in WebDriver along with their syntax.
driver.get("URL")
To navigate to an application.
element.sendKeys("inputtext")
Enter some text into an input box.
element.clear()
Clear the contents from the input box.
select.deselectAll()
Deselect all OPTIONs from the first SELECT on the page.
select.selectByVisibleText("some text")
Select the OPTION with the input specified by the user.
driver.switchTo().window("windowName")
Move the focus from one window to another.
driver.switchTo().frame("frameName")
Swing from frame to frame.
driver.switchTo().alert()
Helps in handling alerts.
driver.navigate().to("URL")
Navigate to the URL.
driver.navigate().forward()
To navigate forward.
driver.navigate().back()
To navigate back.
driver.close()
Closes the current browser associated with the driver.
driver.quit()
Quits the driver and closes all the associated window of that driver.
driver.refresh()
Refreshes the current page.
46 Lectures
5.5 hours
Aditya Dua
296 Lectures
146 hours
Arun Motoori
411 Lectures
38.5 hours
In28Minutes Official
22 Lectures
7 hours
Arun Motoori
118 Lectures
17 hours
Arun Motoori
278 Lectures
38.5 hours
Lets Kode It
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2288,
"s": 1875,
"text": "WebDriver is a tool for automating testing web applications. It is popularly known as Selenium 2.0. WebDriver uses a different underlying framework, while Selenium RC uses JavaScript Selenium-Core embedded within the browser which has got some limitations. WebDriver interacts directly with the browser without any intermediary, unlike Selenium RC that depends on a server. It is used in the following context −"
},
{
"code": null,
"e": 2416,
"s": 2288,
"text": "Multi-browser testing including improved functionality for browsers which is not well-supported by Selenium RC (Selenium 1.0)."
},
{
"code": null,
"e": 2544,
"s": 2416,
"text": "Multi-browser testing including improved functionality for browsers which is not well-supported by Selenium RC (Selenium 1.0)."
},
{
"code": null,
"e": 2616,
"s": 2544,
"text": "Handling multiple frames, multiple browser windows, popups, and alerts."
},
{
"code": null,
"e": 2688,
"s": 2616,
"text": "Handling multiple frames, multiple browser windows, popups, and alerts."
},
{
"code": null,
"e": 2713,
"s": 2688,
"text": "Complex page navigation."
},
{
"code": null,
"e": 2738,
"s": 2713,
"text": "Complex page navigation."
},
{
"code": null,
"e": 2786,
"s": 2738,
"text": "Advanced user navigation such as drag-and-drop."
},
{
"code": null,
"e": 2834,
"s": 2786,
"text": "Advanced user navigation such as drag-and-drop."
},
{
"code": null,
"e": 2858,
"s": 2834,
"text": "AJAX-based UI elements."
},
{
"code": null,
"e": 2882,
"s": 2858,
"text": "AJAX-based UI elements."
},
{
"code": null,
"e": 2961,
"s": 2882,
"text": "WebDriver is best explained with a simple architecture diagram as shown below."
},
{
"code": null,
"e": 3259,
"s": 2961,
"text": "Let us understand how to work with WebDriver. For demonstration, we would use https://www.calculator.net/. We will perform a \"Percent Calculator\" which is located under \"Math Calculator\". We have already downloaded the required WebDriver JAR's. Refer the chapter \"Environmental Setup\" for details."
},
{
"code": null,
"e": 3320,
"s": 3259,
"text": "Step 1 − Launch \"Eclipse\" from the Extracted Eclipse folder."
},
{
"code": null,
"e": 3383,
"s": 3320,
"text": "Step 2 − Select the Workspace by clicking the 'Browse' button."
},
{
"code": null,
"e": 3437,
"s": 3383,
"text": "Step 3 − Now create a 'New Project' from 'File' menu."
},
{
"code": null,
"e": 3487,
"s": 3437,
"text": "Step 4 − Enter the Project Name and Click 'Next'."
},
{
"code": null,
"e": 3703,
"s": 3487,
"text": "Step 5 − Go to Libraries Tab and select all the JAR's that we have downloaded. Add reference to all the JAR's of Selenium WebDriver Library folder and also selenium-java-2.42.2.jar and selenium-java-2.42.2-srcs.jar."
},
{
"code": null,
"e": 3751,
"s": 3703,
"text": "Step 6 − The Package is created as shown below."
},
{
"code": null,
"e": 3840,
"s": 3751,
"text": "Step 7 − Now right-click on the package and select 'New' >> 'Class' to create a 'class'."
},
{
"code": null,
"e": 3899,
"s": 3840,
"text": "Step 8 − Now name the class and make it the main function."
},
{
"code": null,
"e": 3945,
"s": 3899,
"text": "Step 9 − The class outline is shown as below."
},
{
"code": null,
"e": 4182,
"s": 3945,
"text": "Step 10 − Now it is time to code. The following script is easier to understand, as it has comments embedded in it to explain the steps clearly. Please take a look at the chapter \"Locators\" to understand how to capture object properties."
},
{
"code": null,
"e": 5731,
"s": 4182,
"text": "import java.util.concurrent.TimeUnit;\n\nimport org.openqa.selenium.*;\nimport org.openqa.selenium.firefox.FirefoxDriver;\n\npublic class webdriverdemo {\n public static void main(String[] args) {\n \n WebDriver driver = new FirefoxDriver();\n //Puts an Implicit wait, Will wait for 10 seconds before throwing exception\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n \n //Launch website\n driver.navigate().to(\"http://www.calculator.net/\");\n \n //Maximize the browser\n driver.manage().window().maximize();\n \n // Click on Math Calculators\n driver.findElement(By.xpath(\".//*[@id = 'menu']/div[3]/a\")).click();\n \n // Click on Percent Calculators\n driver.findElement(By.xpath(\".//*[@id = 'menu']/div[4]/div[3]/a\")).click();\n \n // Enter value 10 in the first number of the percent Calculator\n driver.findElement(By.id(\"cpar1\")).sendKeys(\"10\");\n \n // Enter value 50 in the second number of the percent Calculator\n driver.findElement(By.id(\"cpar2\")).sendKeys(\"50\");\n \n // Click Calculate Button\n driver.findElement(By.xpath(\".//*[@id = 'content']/table/tbody/tr[2]/td/input[2]\")).click();\n\n \n // Get the Result Text based on its xpath\n String result =\n driver.findElement(By.xpath(\".//*[@id = 'content']/p[2]/font/b\")).getText();\n\n \n // Print a Log In message to the screen\n System.out.println(\" The Result is \" + result);\n \n //Close the Browser.\n driver.close();\n }\n}"
},
{
"code": null,
"e": 5801,
"s": 5731,
"text": "Step 11 − The output of the above script would be printed in Console."
},
{
"code": null,
"e": 5907,
"s": 5801,
"text": "The following table lists some of the most frequently used commands in WebDriver along with their syntax."
},
{
"code": null,
"e": 5925,
"s": 5907,
"text": "driver.get(\"URL\")"
},
{
"code": null,
"e": 5956,
"s": 5925,
"text": "To navigate to an application."
},
{
"code": null,
"e": 5986,
"s": 5956,
"text": "element.sendKeys(\"inputtext\")"
},
{
"code": null,
"e": 6021,
"s": 5986,
"text": "Enter some text into an input box."
},
{
"code": null,
"e": 6037,
"s": 6021,
"text": "element.clear()"
},
{
"code": null,
"e": 6076,
"s": 6037,
"text": "Clear the contents from the input box."
},
{
"code": null,
"e": 6097,
"s": 6076,
"text": "select.deselectAll()"
},
{
"code": null,
"e": 6153,
"s": 6097,
"text": "Deselect all OPTIONs from the first SELECT on the page."
},
{
"code": null,
"e": 6193,
"s": 6153,
"text": "select.selectByVisibleText(\"some text\")"
},
{
"code": null,
"e": 6249,
"s": 6193,
"text": "Select the OPTION with the input specified by the user."
},
{
"code": null,
"e": 6288,
"s": 6249,
"text": "driver.switchTo().window(\"windowName\")"
},
{
"code": null,
"e": 6331,
"s": 6288,
"text": "Move the focus from one window to another."
},
{
"code": null,
"e": 6368,
"s": 6331,
"text": "driver.switchTo().frame(\"frameName\")"
},
{
"code": null,
"e": 6395,
"s": 6368,
"text": "Swing from frame to frame."
},
{
"code": null,
"e": 6421,
"s": 6395,
"text": "driver.switchTo().alert()"
},
{
"code": null,
"e": 6447,
"s": 6421,
"text": "Helps in handling alerts."
},
{
"code": null,
"e": 6475,
"s": 6447,
"text": "driver.navigate().to(\"URL\")"
},
{
"code": null,
"e": 6496,
"s": 6475,
"text": "Navigate to the URL."
},
{
"code": null,
"e": 6524,
"s": 6496,
"text": "driver.navigate().forward()"
},
{
"code": null,
"e": 6545,
"s": 6524,
"text": "To navigate forward."
},
{
"code": null,
"e": 6570,
"s": 6545,
"text": "driver.navigate().back()"
},
{
"code": null,
"e": 6588,
"s": 6570,
"text": "To navigate back."
},
{
"code": null,
"e": 6603,
"s": 6588,
"text": "driver.close()"
},
{
"code": null,
"e": 6658,
"s": 6603,
"text": "Closes the current browser associated with the driver."
},
{
"code": null,
"e": 6672,
"s": 6658,
"text": "driver.quit()"
},
{
"code": null,
"e": 6742,
"s": 6672,
"text": "Quits the driver and closes all the associated window of that driver."
},
{
"code": null,
"e": 6759,
"s": 6742,
"text": "driver.refresh()"
},
{
"code": null,
"e": 6787,
"s": 6759,
"text": "Refreshes the current page."
},
{
"code": null,
"e": 6822,
"s": 6787,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6834,
"s": 6822,
"text": " Aditya Dua"
},
{
"code": null,
"e": 6870,
"s": 6834,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 6884,
"s": 6870,
"text": " Arun Motoori"
},
{
"code": null,
"e": 6921,
"s": 6884,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 6943,
"s": 6921,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 6976,
"s": 6943,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6990,
"s": 6976,
"text": " Arun Motoori"
},
{
"code": null,
"e": 7025,
"s": 6990,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 7039,
"s": 7025,
"text": " Arun Motoori"
},
{
"code": null,
"e": 7076,
"s": 7039,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 7090,
"s": 7076,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7097,
"s": 7090,
"text": " Print"
},
{
"code": null,
"e": 7108,
"s": 7097,
"text": " Add Notes"
}
] |
JS++ | Virtual Methods - GeeksforGeeks | 30 Aug, 2018
As we mentioned in the previous section, if we want runtime polymorphism, using casts can lead to unclean code.
By way of example, let’s change our main.jspp code so that all our animals are inside an array. From there, we will loop over the array to render the animal. Open main.jspp and change the code to:
import Animals;
Animal[] animals = [
new Cat("Kitty"),
new Cat("Kat"),
new Dog("Fido"),
new Panda(),
new Rhino()
];
foreach(Animal animal in animals) {
if (animal instanceof Cat) {
((Cat) animal).render();
}
else if (animal instanceof Dog) {
((Dog) animal).render();
}
else {
animal.render();
}
}
Now our code is even less elegant than our original code that just instantiated the animals, specified the most specific type, and called render().
However, this code can be massively simplified until it becomes elegant. In fact, we can reduce the ‘foreach’ loop down to one statement. The answer: virtual methods.
Virtual methods enable “late binding.” In other words, the specific method to call is resolved at runtime instead of compile time. We don’t need all the ‘instanceof’ checks, all the casts, and all the ‘if’ statements as we saw in the code above. We can achieve something much more elegant.
First, open Animal.jspp and change the ‘render’ method to include the ‘virtual’ modifier:
external $;
module Animals
{
class Animal
{
protected var $element;
protected Animal(string iconClassName) {
string elementHTML = makeElementHTML(iconClassName);
$element = $(elementHTML);
}
public virtual void render() {
$("#content").append($element);
}
private string makeElementHTML(string iconClassName) {
string result = '<div class="animal">';
result += '<i class="icofont ' + iconClassName + '"></i>';
result += "</div>";
return result;
}
}
}
Save Animal.jspp. That’s the only change we need to make.
However, just making our method virtual isn’t enough. In Cat.jspp and Dog.jspp, we are using the ‘overwrite’ modifier on their ‘render’ methods. The ‘overwrite’ modifier specifies compile-time resolution. We want runtime resolution. All we have to do is change Cat.jspp and Dog.jspp to use the ‘override’ modifier instead of the ‘overwrite’ modifier. For the sake of brevity, I will only show the change to Cat.jspp but you need to make the change to Dog.jspp as well:
external $;
module Animals
{
class Cat : Animal
{
string _name;
Cat(string name) {
super("icofont-animal-cat");
_name = name;
}
override void render() {
$element.attr("title", _name);
super.render();
}
}
}
That’s it. All we had to do was change modifiers. Now we can finally edit main.jspp so there is only one statement inside the loop:
import Animals;
Animal[] animals = [
new Cat("Kitty"),
new Cat("Kat"),
new Dog("Fido"),
new Panda(),
new Rhino()
];
foreach(Animal animal in animals) {
animal.render();
}
Compile your code and open index.html. Everything should work. Now we’ve been able to massively simplify our code and still get the expected behavior. Specifically, we reduced the code of our ‘foreach’ loop down from:
foreach(Animal animal in animals) {
if (animal instanceof Cat) {
((Cat) animal).render();
}
else if (animal instanceof Dog) {
((Dog) animal).render();
}
else {
animal.render();
}
}
To this:
foreach(Animal animal in animals) {
animal.render();
}
The reason we’ve been able to simplify our code so dramatically is because marking a method as ‘virtual’ signifies potential runtime polymorphism. Together with the ‘override’ modifier, the compiler knows we want late binding on the ‘render’ method so the “late” binding happens exactly when it’s needed: the ‘render’ method will be resolved at runtime if and only when it needs to be resolved (inside the ‘foreach’ loop).
JS++
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
JS++ | Getters and Setters
JS++ | Conditional Statements
JS++ | Inheritance
JS++ | Variables and Data Types
JS++ | Abstract Classes and Methods
JS++ | The 'final' Modifier
JS++ | Classes, OOP, and User-defined Types
JS++ | How to install JS++ on different Operating Systems
JS++ | Event Handlers
JS++ | Static Members and "Application-Global" Data | [
{
"code": null,
"e": 23601,
"s": 23573,
"text": "\n30 Aug, 2018"
},
{
"code": null,
"e": 23713,
"s": 23601,
"text": "As we mentioned in the previous section, if we want runtime polymorphism, using casts can lead to unclean code."
},
{
"code": null,
"e": 23910,
"s": 23713,
"text": "By way of example, let’s change our main.jspp code so that all our animals are inside an array. From there, we will loop over the array to render the animal. Open main.jspp and change the code to:"
},
{
"code": null,
"e": 24278,
"s": 23910,
"text": "import Animals;\n\nAnimal[] animals = [\n new Cat(\"Kitty\"),\n new Cat(\"Kat\"),\n new Dog(\"Fido\"),\n new Panda(),\n new Rhino()\n];\n\nforeach(Animal animal in animals) {\n if (animal instanceof Cat) {\n ((Cat) animal).render();\n }\n else if (animal instanceof Dog) {\n ((Dog) animal).render();\n }\n else {\n animal.render();\n }\n}\n"
},
{
"code": null,
"e": 24426,
"s": 24278,
"text": "Now our code is even less elegant than our original code that just instantiated the animals, specified the most specific type, and called render()."
},
{
"code": null,
"e": 24593,
"s": 24426,
"text": "However, this code can be massively simplified until it becomes elegant. In fact, we can reduce the ‘foreach’ loop down to one statement. The answer: virtual methods."
},
{
"code": null,
"e": 24883,
"s": 24593,
"text": "Virtual methods enable “late binding.” In other words, the specific method to call is resolved at runtime instead of compile time. We don’t need all the ‘instanceof’ checks, all the casts, and all the ‘if’ statements as we saw in the code above. We can achieve something much more elegant."
},
{
"code": null,
"e": 24973,
"s": 24883,
"text": "First, open Animal.jspp and change the ‘render’ method to include the ‘virtual’ modifier:"
},
{
"code": null,
"e": 25581,
"s": 24973,
"text": "external $;\n\nmodule Animals\n{\n class Animal\n {\n protected var $element;\n\n protected Animal(string iconClassName) {\n string elementHTML = makeElementHTML(iconClassName);\n $element = $(elementHTML);\n }\n\n public virtual void render() {\n $(\"#content\").append($element);\n }\n\n private string makeElementHTML(string iconClassName) {\n string result = '<div class=\"animal\">';\n result += '<i class=\"icofont ' + iconClassName + '\"></i>';\n result += \"</div>\";\n return result;\n }\n }\n}\n"
},
{
"code": null,
"e": 25639,
"s": 25581,
"text": "Save Animal.jspp. That’s the only change we need to make."
},
{
"code": null,
"e": 26108,
"s": 25639,
"text": "However, just making our method virtual isn’t enough. In Cat.jspp and Dog.jspp, we are using the ‘overwrite’ modifier on their ‘render’ methods. The ‘overwrite’ modifier specifies compile-time resolution. We want runtime resolution. All we have to do is change Cat.jspp and Dog.jspp to use the ‘override’ modifier instead of the ‘overwrite’ modifier. For the sake of brevity, I will only show the change to Cat.jspp but you need to make the change to Dog.jspp as well:"
},
{
"code": null,
"e": 26418,
"s": 26108,
"text": "external $;\n\nmodule Animals\n{\n class Cat : Animal\n {\n string _name;\n\n Cat(string name) {\n super(\"icofont-animal-cat\");\n _name = name;\n }\n\n override void render() {\n $element.attr(\"title\", _name);\n super.render();\n }\n }\n}\n"
},
{
"code": null,
"e": 26550,
"s": 26418,
"text": "That’s it. All we had to do was change modifiers. Now we can finally edit main.jspp so there is only one statement inside the loop:"
},
{
"code": null,
"e": 26748,
"s": 26550,
"text": "import Animals;\n\nAnimal[] animals = [\n new Cat(\"Kitty\"),\n new Cat(\"Kat\"),\n new Dog(\"Fido\"),\n new Panda(),\n new Rhino()\n];\n\nforeach(Animal animal in animals) {\n animal.render();\n}\n"
},
{
"code": null,
"e": 26966,
"s": 26748,
"text": "Compile your code and open index.html. Everything should work. Now we’ve been able to massively simplify our code and still get the expected behavior. Specifically, we reduced the code of our ‘foreach’ loop down from:"
},
{
"code": null,
"e": 27196,
"s": 26966,
"text": "foreach(Animal animal in animals) {\n if (animal instanceof Cat) {\n ((Cat) animal).render();\n }\n else if (animal instanceof Dog) {\n ((Dog) animal).render();\n }\n else {\n animal.render();\n }\n}\n"
},
{
"code": null,
"e": 27205,
"s": 27196,
"text": "To this:"
},
{
"code": null,
"e": 27265,
"s": 27205,
"text": "foreach(Animal animal in animals) {\n animal.render();\n}\n"
},
{
"code": null,
"e": 27688,
"s": 27265,
"text": "The reason we’ve been able to simplify our code so dramatically is because marking a method as ‘virtual’ signifies potential runtime polymorphism. Together with the ‘override’ modifier, the compiler knows we want late binding on the ‘render’ method so the “late” binding happens exactly when it’s needed: the ‘render’ method will be resolved at runtime if and only when it needs to be resolved (inside the ‘foreach’ loop)."
},
{
"code": null,
"e": 27693,
"s": 27688,
"text": "JS++"
},
{
"code": null,
"e": 27791,
"s": 27693,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27800,
"s": 27791,
"text": "Comments"
},
{
"code": null,
"e": 27813,
"s": 27800,
"text": "Old Comments"
},
{
"code": null,
"e": 27840,
"s": 27813,
"text": "JS++ | Getters and Setters"
},
{
"code": null,
"e": 27870,
"s": 27840,
"text": "JS++ | Conditional Statements"
},
{
"code": null,
"e": 27889,
"s": 27870,
"text": "JS++ | Inheritance"
},
{
"code": null,
"e": 27921,
"s": 27889,
"text": "JS++ | Variables and Data Types"
},
{
"code": null,
"e": 27957,
"s": 27921,
"text": "JS++ | Abstract Classes and Methods"
},
{
"code": null,
"e": 27985,
"s": 27957,
"text": "JS++ | The 'final' Modifier"
},
{
"code": null,
"e": 28029,
"s": 27985,
"text": "JS++ | Classes, OOP, and User-defined Types"
},
{
"code": null,
"e": 28087,
"s": 28029,
"text": "JS++ | How to install JS++ on different Operating Systems"
},
{
"code": null,
"e": 28109,
"s": 28087,
"text": "JS++ | Event Handlers"
}
] |
Instance variables in Java | Instance variables are declared in a class, but outside a method, constructor or any block.
When space is allocated for an object in the heap, a slot for each instance variable value is created.
When space is allocated for an object in the heap, a slot for each instance variable value is created.
Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
Instance variables can be declared at the class level before or after use.
Instance variables can be declared at the class level before or after use.
Access modifiers can be given for instance variables.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors, and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers.
The instance variables are visible for all methods, constructors, and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers.
Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor.
Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.
Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.
Online Demo
import java.io.*;
public class Employee {
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName) {
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal) {
salary = empSal;
}
// This method prints the employee details.
public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]) {
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
This will produce the following result −
name : Ransika
salary :1000.0 | [
{
"code": null,
"e": 1154,
"s": 1062,
"text": "Instance variables are declared in a class, but outside a method, constructor or any block."
},
{
"code": null,
"e": 1257,
"s": 1154,
"text": "When space is allocated for an object in the heap, a slot for each instance variable value is created."
},
{
"code": null,
"e": 1360,
"s": 1257,
"text": "When space is allocated for an object in the heap, a slot for each instance variable value is created."
},
{
"code": null,
"e": 1495,
"s": 1360,
"text": "Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed."
},
{
"code": null,
"e": 1630,
"s": 1495,
"text": "Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed."
},
{
"code": null,
"e": 1815,
"s": 1630,
"text": "Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class."
},
{
"code": null,
"e": 2000,
"s": 1815,
"text": "Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class."
},
{
"code": null,
"e": 2075,
"s": 2000,
"text": "Instance variables can be declared at the class level before or after use."
},
{
"code": null,
"e": 2150,
"s": 2075,
"text": "Instance variables can be declared at the class level before or after use."
},
{
"code": null,
"e": 2204,
"s": 2150,
"text": "Access modifiers can be given for instance variables."
},
{
"code": null,
"e": 2258,
"s": 2204,
"text": "Access modifiers can be given for instance variables."
},
{
"code": null,
"e": 2526,
"s": 2258,
"text": "The instance variables are visible for all methods, constructors, and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers."
},
{
"code": null,
"e": 2794,
"s": 2526,
"text": "The instance variables are visible for all methods, constructors, and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers."
},
{
"code": null,
"e": 3008,
"s": 2794,
"text": "Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor."
},
{
"code": null,
"e": 3222,
"s": 3008,
"text": "Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor."
},
{
"code": null,
"e": 3479,
"s": 3222,
"text": "Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName."
},
{
"code": null,
"e": 3736,
"s": 3479,
"text": "Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName."
},
{
"code": null,
"e": 3748,
"s": 3736,
"text": "Online Demo"
},
{
"code": null,
"e": 4529,
"s": 3748,
"text": "import java.io.*;\npublic class Employee {\n\n // this instance variable is visible for any child class.\n public String name;\n\n // salary variable is visible in Employee class only.\n private double salary;\n\n // The name variable is assigned in the constructor.\n public Employee (String empName) {\n name = empName;\n }\n\n // The salary variable is assigned a value.\n public void setSalary(double empSal) {\n salary = empSal;\n }\n\n // This method prints the employee details.\n public void printEmp() {\n System.out.println(\"name : \" + name );\n System.out.println(\"salary :\" + salary);\n }\n\n public static void main(String args[]) {\n Employee empOne = new Employee(\"Ransika\");\n empOne.setSalary(1000);\n empOne.printEmp();\n }\n}"
},
{
"code": null,
"e": 4570,
"s": 4529,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 4601,
"s": 4570,
"text": "name : Ransika\nsalary :1000.0"
}
] |
Java program to store a Student Information in a File using AWT - GeeksforGeeks | 20 May, 2020
Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. Java swing components are lightweight, platform-independent, provide powerful components like tables, scroll panels, buttons, list, colour chooser, etc.
In this article, we will see how to write the students information in a Jframe and store it in a file.
Approach: To solve this problem, the following steps are followed:
First, we need to create a frame using JFrame.Next create JLabels, JTextFields, JComboBoxes, JButtons and set their bounds respectively.Name these components accordingly and set their bounds.Now, in order to save the data into the text file on button click, we need to add Event Handlers. In this case, we will add ActionListener to perform an action method known as actionPerformed in which first we need to get the values from the text fields which is default as a “string”.Finally, the Jbuttons, JLabels, JTextFields and JComboBoxes are added to the JFrame and the text is stored in a text file.
First, we need to create a frame using JFrame.
Next create JLabels, JTextFields, JComboBoxes, JButtons and set their bounds respectively.
Name these components accordingly and set their bounds.
Now, in order to save the data into the text file on button click, we need to add Event Handlers. In this case, we will add ActionListener to perform an action method known as actionPerformed in which first we need to get the values from the text fields which is default as a “string”.
Finally, the Jbuttons, JLabels, JTextFields and JComboBoxes are added to the JFrame and the text is stored in a text file.
Below is the implementation of the above approach:
// Java program to write a student// information in JFrame and// storing it in a file import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.io.*; public class GFG { // Function to write a student // information in JFrame and // storing it in a file public static void StudentInfo() { // Creating a new frame using JFrame JFrame f = new JFrame( "Student Details Form"); // Creating the labels JLabel l1, l2, l3, l4, l5; // Creating three text fields. // One for student name, one for // college mail ID and one // for Mobile No JTextField t1, t2, t3; // Creating two JComboboxes // one for Branch and one // for Section JComboBox j1, j2; // Creating two buttons JButton b1, b2; // Naming the labels and setting // the bounds for the labels l1 = new JLabel("Student Name:"); l1.setBounds(50, 50, 100, 30); l2 = new JLabel("College Email ID:"); l2.setBounds(50, 120, 120, 30); l3 = new JLabel("Branch:"); l3.setBounds(50, 190, 50, 30); l4 = new JLabel("Section:"); l4.setBounds(420, 50, 70, 30); l5 = new JLabel("Mobile No:"); l5.setBounds(420, 120, 70, 30); // Creating the textfields and // setting the bounds for textfields t1 = new JTextField(); t1.setBounds(150, 50, 130, 30); t2 = new JTextField(); t2.setBounds(160, 120, 130, 30); t3 = new JTextField(); t3.setBounds(490, 120, 130, 30); // Creating two string arrays one for // braches and other for sections String s1[] = { " ", "CSE", "ECE", "EEE", "CIVIL", "MEC", "Others" }; String s2[] = { " ", "Section-A", "Section-B", "Section-C", "Section-D", "Section-E" }; // Creating two JComboBoxes one for // selecting branch and other for // selecting the section // and setting the bounds j1 = new JComboBox(s1); j1.setBounds(120, 190, 100, 30); j2 = new JComboBox(s2); j2.setBounds(470, 50, 140, 30); // Creating one button for Saving // and other button to close // and setting the bounds b1 = new JButton("Save"); b1.setBounds(150, 300, 70, 30); b2 = new JButton("close"); b2.setBounds(420, 300, 70, 30); // Adding action listener b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Getting the text from text fields // and JComboboxes // and copying it to a strings String s1 = t1.getText(); String s2 = t2.getText(); String s3 = j1.getSelectedItem() + ""; String s4 = j2.getSelectedItem() + ""; String s5 = t3.getText(); if (e.getSource() == b1) { try { // Creating a file and // writing the data // into a Textfile. FileWriter w = new FileWriter( "GFG.txt", true); w.write(s1 + "\n"); w.write(s2 + "\n"); w.write(s3 + "\n"); w.write(s4 + "\n"); w.write(s5 + "\n"); w.close(); } catch (Exception ae) { System.out.println(ae); } } // Shows a Pop up Message when // save button is clicked JOptionPane .showMessageDialog( f, "Successfully Saved" + " The Details"); } }); // Action listener to close the form b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); // Default method for closing the frame f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // Adding the created objects // to the frame f.add(l1); f.add(t1); f.add(l2); f.add(t2); f.add(l3); f.add(j1); f.add(l4); f.add(j2); f.add(l5); f.add(t3); f.add(b1); f.add(b2); f.setLayout(null); f.setSize(700, 600); f.setVisible(true); } // Driver code public static void main(String args[]) { StudentInfo(); }}
Output:
The window displayed on running the program:Entering the data:The dialog box showed after clicking on the save button:The text file in which the data is stored:
The window displayed on running the program:
Entering the data:
The dialog box showed after clicking on the save button:
The text file in which the data is stored:
java-advanced
Java-AWT
java-swing
Java
Project
Write From Home
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
SDE SHEET - A Complete Guide for SDE Preparation
XML parsing in Python
Python | Simple GUI calculator using Tkinter
Implementing Web Scraping in Python with BeautifulSoup
Working with zip files in Python | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n20 May, 2020"
},
{
"code": null,
"e": 24010,
"s": 23557,
"text": "Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications. Java swing components are lightweight, platform-independent, provide powerful components like tables, scroll panels, buttons, list, colour chooser, etc."
},
{
"code": null,
"e": 24113,
"s": 24010,
"text": "In this article, we will see how to write the students information in a Jframe and store it in a file."
},
{
"code": null,
"e": 24180,
"s": 24113,
"text": "Approach: To solve this problem, the following steps are followed:"
},
{
"code": null,
"e": 24779,
"s": 24180,
"text": "First, we need to create a frame using JFrame.Next create JLabels, JTextFields, JComboBoxes, JButtons and set their bounds respectively.Name these components accordingly and set their bounds.Now, in order to save the data into the text file on button click, we need to add Event Handlers. In this case, we will add ActionListener to perform an action method known as actionPerformed in which first we need to get the values from the text fields which is default as a “string”.Finally, the Jbuttons, JLabels, JTextFields and JComboBoxes are added to the JFrame and the text is stored in a text file."
},
{
"code": null,
"e": 24826,
"s": 24779,
"text": "First, we need to create a frame using JFrame."
},
{
"code": null,
"e": 24917,
"s": 24826,
"text": "Next create JLabels, JTextFields, JComboBoxes, JButtons and set their bounds respectively."
},
{
"code": null,
"e": 24973,
"s": 24917,
"text": "Name these components accordingly and set their bounds."
},
{
"code": null,
"e": 25259,
"s": 24973,
"text": "Now, in order to save the data into the text file on button click, we need to add Event Handlers. In this case, we will add ActionListener to perform an action method known as actionPerformed in which first we need to get the values from the text fields which is default as a “string”."
},
{
"code": null,
"e": 25382,
"s": 25259,
"text": "Finally, the Jbuttons, JLabels, JTextFields and JComboBoxes are added to the JFrame and the text is stored in a text file."
},
{
"code": null,
"e": 25433,
"s": 25382,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to write a student// information in JFrame and// storing it in a file import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.io.*; public class GFG { // Function to write a student // information in JFrame and // storing it in a file public static void StudentInfo() { // Creating a new frame using JFrame JFrame f = new JFrame( \"Student Details Form\"); // Creating the labels JLabel l1, l2, l3, l4, l5; // Creating three text fields. // One for student name, one for // college mail ID and one // for Mobile No JTextField t1, t2, t3; // Creating two JComboboxes // one for Branch and one // for Section JComboBox j1, j2; // Creating two buttons JButton b1, b2; // Naming the labels and setting // the bounds for the labels l1 = new JLabel(\"Student Name:\"); l1.setBounds(50, 50, 100, 30); l2 = new JLabel(\"College Email ID:\"); l2.setBounds(50, 120, 120, 30); l3 = new JLabel(\"Branch:\"); l3.setBounds(50, 190, 50, 30); l4 = new JLabel(\"Section:\"); l4.setBounds(420, 50, 70, 30); l5 = new JLabel(\"Mobile No:\"); l5.setBounds(420, 120, 70, 30); // Creating the textfields and // setting the bounds for textfields t1 = new JTextField(); t1.setBounds(150, 50, 130, 30); t2 = new JTextField(); t2.setBounds(160, 120, 130, 30); t3 = new JTextField(); t3.setBounds(490, 120, 130, 30); // Creating two string arrays one for // braches and other for sections String s1[] = { \" \", \"CSE\", \"ECE\", \"EEE\", \"CIVIL\", \"MEC\", \"Others\" }; String s2[] = { \" \", \"Section-A\", \"Section-B\", \"Section-C\", \"Section-D\", \"Section-E\" }; // Creating two JComboBoxes one for // selecting branch and other for // selecting the section // and setting the bounds j1 = new JComboBox(s1); j1.setBounds(120, 190, 100, 30); j2 = new JComboBox(s2); j2.setBounds(470, 50, 140, 30); // Creating one button for Saving // and other button to close // and setting the bounds b1 = new JButton(\"Save\"); b1.setBounds(150, 300, 70, 30); b2 = new JButton(\"close\"); b2.setBounds(420, 300, 70, 30); // Adding action listener b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Getting the text from text fields // and JComboboxes // and copying it to a strings String s1 = t1.getText(); String s2 = t2.getText(); String s3 = j1.getSelectedItem() + \"\"; String s4 = j2.getSelectedItem() + \"\"; String s5 = t3.getText(); if (e.getSource() == b1) { try { // Creating a file and // writing the data // into a Textfile. FileWriter w = new FileWriter( \"GFG.txt\", true); w.write(s1 + \"\\n\"); w.write(s2 + \"\\n\"); w.write(s3 + \"\\n\"); w.write(s4 + \"\\n\"); w.write(s5 + \"\\n\"); w.close(); } catch (Exception ae) { System.out.println(ae); } } // Shows a Pop up Message when // save button is clicked JOptionPane .showMessageDialog( f, \"Successfully Saved\" + \" The Details\"); } }); // Action listener to close the form b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); // Default method for closing the frame f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // Adding the created objects // to the frame f.add(l1); f.add(t1); f.add(l2); f.add(t2); f.add(l3); f.add(j1); f.add(l4); f.add(j2); f.add(l5); f.add(t3); f.add(b1); f.add(b2); f.setLayout(null); f.setSize(700, 600); f.setVisible(true); } // Driver code public static void main(String args[]) { StudentInfo(); }}",
"e": 30366,
"s": 25433,
"text": null
},
{
"code": null,
"e": 30374,
"s": 30366,
"text": "Output:"
},
{
"code": null,
"e": 30535,
"s": 30374,
"text": "The window displayed on running the program:Entering the data:The dialog box showed after clicking on the save button:The text file in which the data is stored:"
},
{
"code": null,
"e": 30580,
"s": 30535,
"text": "The window displayed on running the program:"
},
{
"code": null,
"e": 30599,
"s": 30580,
"text": "Entering the data:"
},
{
"code": null,
"e": 30656,
"s": 30599,
"text": "The dialog box showed after clicking on the save button:"
},
{
"code": null,
"e": 30699,
"s": 30656,
"text": "The text file in which the data is stored:"
},
{
"code": null,
"e": 30713,
"s": 30699,
"text": "java-advanced"
},
{
"code": null,
"e": 30722,
"s": 30713,
"text": "Java-AWT"
},
{
"code": null,
"e": 30733,
"s": 30722,
"text": "java-swing"
},
{
"code": null,
"e": 30738,
"s": 30733,
"text": "Java"
},
{
"code": null,
"e": 30746,
"s": 30738,
"text": "Project"
},
{
"code": null,
"e": 30762,
"s": 30746,
"text": "Write From Home"
},
{
"code": null,
"e": 30767,
"s": 30762,
"text": "Java"
},
{
"code": null,
"e": 30865,
"s": 30767,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30874,
"s": 30865,
"text": "Comments"
},
{
"code": null,
"e": 30887,
"s": 30874,
"text": "Old Comments"
},
{
"code": null,
"e": 30917,
"s": 30887,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30932,
"s": 30917,
"text": "Stream In Java"
},
{
"code": null,
"e": 30953,
"s": 30932,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30999,
"s": 30953,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31018,
"s": 30999,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31067,
"s": 31018,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 31089,
"s": 31067,
"text": "XML parsing in Python"
},
{
"code": null,
"e": 31134,
"s": 31089,
"text": "Python | Simple GUI calculator using Tkinter"
},
{
"code": null,
"e": 31189,
"s": 31134,
"text": "Implementing Web Scraping in Python with BeautifulSoup"
}
] |
Angular PrimeNG FloatLabel Component - GeeksforGeeks | 30 Jul, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the FloatLabel component in angular PrimeNG.
FloatLabel component is the floating label that can be used on the input component.
Creating Angular Application And Installing Module:
Step 1: Create an Angular application using the following command.ng new appname
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname
cd appname
Step 3: Install PrimeNG in your given directory.npm install primeng --save
npm install primeicons --save
npm install primeng --save
npm install primeicons --save
Project Structure: It will look like the following.
Example 1: This is the basic example that shows how to use FloatLabel component
app.component.html
<h2>GeeksforGeeks</h2> <p>PrimeNG FloatLabel component</p> <div class="p-field p-col-12 p-md-4"> <span class="p-float-label"> <input type="text" pInputText /> <label>InputText</label> </span></div>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations";import { HttpClientModule } from "@angular/common/http"; import { AppComponent } from "./app.component"; import { AutoCompleteModule } from "primeng/autocomplete";import { InputTextModule } from "primeng/inputtext"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, AutoCompleteModule, FormsModule, HttpClientModule, InputTextModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
Output:
Example 2: In this example, we will know how to use disabled property in the FloatLabel component.
app.component.html
<h2>GeeksforGeeks</h2> <p>PrimeNG FloatLabel component</p> <div class="p-field p-col-12 p-md-4"> <span class="p-float-label"> <input disabled="true" type="text" pInputText /> <label>InputText</label> </span></div>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations";import { HttpClientModule } from "@angular/common/http"; import { AppComponent } from "./app.component"; import { AutoCompleteModule } from "primeng/autocomplete";import { InputTextModule } from "primeng/inputtext"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, AutoCompleteModule, FormsModule, HttpClientModule, InputTextModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
Output:
Reference: https://primefaces.org/primeng/showcase/#/floatlabel
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
Angular 10 (focus) Event
Express.js express.Router() Function
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24718,
"s": 24690,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 25004,
"s": 24718,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the FloatLabel component in angular PrimeNG."
},
{
"code": null,
"e": 25088,
"s": 25004,
"text": "FloatLabel component is the floating label that can be used on the input component."
},
{
"code": null,
"e": 25140,
"s": 25088,
"text": "Creating Angular Application And Installing Module:"
},
{
"code": null,
"e": 25221,
"s": 25140,
"text": "Step 1: Create an Angular application using the following command.ng new appname"
},
{
"code": null,
"e": 25236,
"s": 25221,
"text": "ng new appname"
},
{
"code": null,
"e": 25343,
"s": 25236,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname"
},
{
"code": null,
"e": 25354,
"s": 25343,
"text": "cd appname"
},
{
"code": null,
"e": 25459,
"s": 25354,
"text": "Step 3: Install PrimeNG in your given directory.npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 25516,
"s": 25459,
"text": "npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 25568,
"s": 25516,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 25649,
"s": 25568,
"text": "Example 1: This is the basic example that shows how to use FloatLabel component "
},
{
"code": null,
"e": 25668,
"s": 25649,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2> <p>PrimeNG FloatLabel component</p> <div class=\"p-field p-col-12 p-md-4\"> <span class=\"p-float-label\"> <input type=\"text\" pInputText /> <label>InputText</label> </span></div>",
"e": 25876,
"s": 25668,
"text": null
},
{
"code": null,
"e": 25890,
"s": 25876,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\";import { HttpClientModule } from \"@angular/common/http\"; import { AppComponent } from \"./app.component\"; import { AutoCompleteModule } from \"primeng/autocomplete\";import { InputTextModule } from \"primeng/inputtext\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, AutoCompleteModule, FormsModule, HttpClientModule, InputTextModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 26575,
"s": 25890,
"text": null
},
{
"code": null,
"e": 26583,
"s": 26575,
"text": "Output:"
},
{
"code": null,
"e": 26683,
"s": 26583,
"text": "Example 2: In this example, we will know how to use disabled property in the FloatLabel component. "
},
{
"code": null,
"e": 26702,
"s": 26683,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2> <p>PrimeNG FloatLabel component</p> <div class=\"p-field p-col-12 p-md-4\"> <span class=\"p-float-label\"> <input disabled=\"true\" type=\"text\" pInputText /> <label>InputText</label> </span></div>",
"e": 26926,
"s": 26702,
"text": null
},
{
"code": null,
"e": 26940,
"s": 26926,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\";import { HttpClientModule } from \"@angular/common/http\"; import { AppComponent } from \"./app.component\"; import { AutoCompleteModule } from \"primeng/autocomplete\";import { InputTextModule } from \"primeng/inputtext\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, AutoCompleteModule, FormsModule, HttpClientModule, InputTextModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 27626,
"s": 26940,
"text": null
},
{
"code": null,
"e": 27634,
"s": 27626,
"text": "Output:"
},
{
"code": null,
"e": 27698,
"s": 27634,
"text": "Reference: https://primefaces.org/primeng/showcase/#/floatlabel"
},
{
"code": null,
"e": 27714,
"s": 27698,
"text": "Angular-PrimeNG"
},
{
"code": null,
"e": 27724,
"s": 27714,
"text": "AngularJS"
},
{
"code": null,
"e": 27741,
"s": 27724,
"text": "Web Technologies"
},
{
"code": null,
"e": 27839,
"s": 27741,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27848,
"s": 27839,
"text": "Comments"
},
{
"code": null,
"e": 27861,
"s": 27848,
"text": "Old Comments"
},
{
"code": null,
"e": 27905,
"s": 27861,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 27969,
"s": 27905,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 28004,
"s": 27969,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28028,
"s": 28004,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 28053,
"s": 28028,
"text": "Angular 10 (focus) Event"
},
{
"code": null,
"e": 28090,
"s": 28053,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 28123,
"s": 28090,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28185,
"s": 28123,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28228,
"s": 28185,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Codenation Interview Experience | On campus for Internship - GeeksforGeeks | 10 Aug, 2020
I applied for two month long summer(2021) internship at codenation. It was an On-campus internship recruitment (Tier – 2 college).
There were 4 rounds including the online coding round.
Coding round: The test was conducted on hacker rank. It consisted of 3 questions based on DSA. 2 were relatively easier while 1 was a bit tricky. Some students were facing issues compiling
Delete k characters from the string consisting of lowercase English alphabets. Among all such possible strings, return the string which is lexicographic ally the largest.Similar problem: https://leetcode.com/problems/remove-k-digits/Given two integer arrays, return the minimum number of moves required such that the second array is a sub sequence of the first array. You can insert an element at any index in the first array in one move. Elements in the second array are distinct. Both the arrays can have at most 10^5 elements.I solved it by first storing the index of every element of second array in a hashmap. For every element in the first array, if it is also present in the second array, append it’s index in second array(using the hashmap) to another list. The LIS of this list will be the length of maximum elements we can match without performing any operation. The length of 2nd array – LIS was the answer.Given an array of integers and x queries of the form l, r, s, t. The answer to each query is the number of subarrays int he range[l, r], of size s whose bitwise and (&) is greater than t. The array can have at most 10^5 elements and the number of queries were 500.Maintaining a prefix sum of the count of all bits from 2^0 to 2^30 and then answering every query using a sliding window approach worked for passing all the test cases.
Delete k characters from the string consisting of lowercase English alphabets. Among all such possible strings, return the string which is lexicographic ally the largest.Similar problem: https://leetcode.com/problems/remove-k-digits/
Similar problem: https://leetcode.com/problems/remove-k-digits/
Given two integer arrays, return the minimum number of moves required such that the second array is a sub sequence of the first array. You can insert an element at any index in the first array in one move. Elements in the second array are distinct. Both the arrays can have at most 10^5 elements.I solved it by first storing the index of every element of second array in a hashmap. For every element in the first array, if it is also present in the second array, append it’s index in second array(using the hashmap) to another list. The LIS of this list will be the length of maximum elements we can match without performing any operation. The length of 2nd array – LIS was the answer.
I solved it by first storing the index of every element of second array in a hashmap. For every element in the first array, if it is also present in the second array, append it’s index in second array(using the hashmap) to another list. The LIS of this list will be the length of maximum elements we can match without performing any operation. The length of 2nd array – LIS was the answer.
Given an array of integers and x queries of the form l, r, s, t. The answer to each query is the number of subarrays int he range[l, r], of size s whose bitwise and (&) is greater than t. The array can have at most 10^5 elements and the number of queries were 500.Maintaining a prefix sum of the count of all bits from 2^0 to 2^30 and then answering every query using a sliding window approach worked for passing all the test cases.
Maintaining a prefix sum of the count of all bits from 2^0 to 2^30 and then answering every query using a sliding window approach worked for passing all the test cases.
All those who solved at least 2.5 problems were shortlisted for the next round. 5 of the candidates moved to the next round.
Round 0: It was a project discussion round where you will be asked about your projects and in depth working. If you are well versed with your projects, this is the easiest round to get through. 2 students were rejected in this round. This round took place over call.
Round 1: It was the DSA round where I was asked 2 problems. The interviewer was really dull and non-interactive. He didn’t even read the question and simply just pasted the problem in the shared google doc. This round took place over google meet and I was asked to write code on the shared google doc. (Platform depends on interviewer too as one of my friend’s interview took place over a zoom call.)
First problem was, given the following function f, I had to define another function which, given a number n, returns its prime factors along with their powers.
C++
long long f(long long n) { if(n == 1 || n is a prime) { return n; } else { return any of the proper divisors of n; }}
Second problem was: https://leetcode.com/problems/backspace-string-compare/description/I was supposed to solve it in linear time and constant space.
I was supposed to solve it in linear time and constant space.
I was able to solve 1st problem completely and the second problem with the help of some hints. I was rejected in this round.
Round 2: Some of my friends who were selected for this round were asked about there projects and then given an open ended problem. This round is for checking the creative thinking skills of the candidate and is usually taken by a senior employee.
Overall, it was a good learning experience interviewing with codenation. Only one of the students were given the final offer for internship. After the online round shortlisting, the entire process took 2-3 days.
Codenation
Marketing
On-Campus
Internship
Interview Experiences
Codenation
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Interview Experience for Internship (Via Engage)
Zoho Interview Experience (Off-Campus ) 2022
Thoughtspot Interview Experience for SDE Intern
TurboHire Internship Interview Experience
Persistent Systems Interview Experience (Martian Program)
Amazon Interview Questions
Microsoft Interview Experience for Internship (Via Engage)
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience for SDE-1 (On-Campus)
Infosys Interview Experience for DSE - System Engineer | On-Campus 2022 | [
{
"code": null,
"e": 25155,
"s": 25127,
"text": "\n10 Aug, 2020"
},
{
"code": null,
"e": 25286,
"s": 25155,
"text": "I applied for two month long summer(2021) internship at codenation. It was an On-campus internship recruitment (Tier – 2 college)."
},
{
"code": null,
"e": 25341,
"s": 25286,
"text": "There were 4 rounds including the online coding round."
},
{
"code": null,
"e": 25531,
"s": 25341,
"text": "Coding round: The test was conducted on hacker rank. It consisted of 3 questions based on DSA. 2 were relatively easier while 1 was a bit tricky. Some students were facing issues compiling "
},
{
"code": null,
"e": 26882,
"s": 25531,
"text": "Delete k characters from the string consisting of lowercase English alphabets. Among all such possible strings, return the string which is lexicographic ally the largest.Similar problem: https://leetcode.com/problems/remove-k-digits/Given two integer arrays, return the minimum number of moves required such that the second array is a sub sequence of the first array. You can insert an element at any index in the first array in one move. Elements in the second array are distinct. Both the arrays can have at most 10^5 elements.I solved it by first storing the index of every element of second array in a hashmap. For every element in the first array, if it is also present in the second array, append it’s index in second array(using the hashmap) to another list. The LIS of this list will be the length of maximum elements we can match without performing any operation. The length of 2nd array – LIS was the answer.Given an array of integers and x queries of the form l, r, s, t. The answer to each query is the number of subarrays int he range[l, r], of size s whose bitwise and (&) is greater than t. The array can have at most 10^5 elements and the number of queries were 500.Maintaining a prefix sum of the count of all bits from 2^0 to 2^30 and then answering every query using a sliding window approach worked for passing all the test cases."
},
{
"code": null,
"e": 27116,
"s": 26882,
"text": "Delete k characters from the string consisting of lowercase English alphabets. Among all such possible strings, return the string which is lexicographic ally the largest.Similar problem: https://leetcode.com/problems/remove-k-digits/"
},
{
"code": null,
"e": 27180,
"s": 27116,
"text": "Similar problem: https://leetcode.com/problems/remove-k-digits/"
},
{
"code": null,
"e": 27866,
"s": 27180,
"text": "Given two integer arrays, return the minimum number of moves required such that the second array is a sub sequence of the first array. You can insert an element at any index in the first array in one move. Elements in the second array are distinct. Both the arrays can have at most 10^5 elements.I solved it by first storing the index of every element of second array in a hashmap. For every element in the first array, if it is also present in the second array, append it’s index in second array(using the hashmap) to another list. The LIS of this list will be the length of maximum elements we can match without performing any operation. The length of 2nd array – LIS was the answer."
},
{
"code": null,
"e": 28256,
"s": 27866,
"text": "I solved it by first storing the index of every element of second array in a hashmap. For every element in the first array, if it is also present in the second array, append it’s index in second array(using the hashmap) to another list. The LIS of this list will be the length of maximum elements we can match without performing any operation. The length of 2nd array – LIS was the answer."
},
{
"code": null,
"e": 28689,
"s": 28256,
"text": "Given an array of integers and x queries of the form l, r, s, t. The answer to each query is the number of subarrays int he range[l, r], of size s whose bitwise and (&) is greater than t. The array can have at most 10^5 elements and the number of queries were 500.Maintaining a prefix sum of the count of all bits from 2^0 to 2^30 and then answering every query using a sliding window approach worked for passing all the test cases."
},
{
"code": null,
"e": 28858,
"s": 28689,
"text": "Maintaining a prefix sum of the count of all bits from 2^0 to 2^30 and then answering every query using a sliding window approach worked for passing all the test cases."
},
{
"code": null,
"e": 28983,
"s": 28858,
"text": "All those who solved at least 2.5 problems were shortlisted for the next round. 5 of the candidates moved to the next round."
},
{
"code": null,
"e": 29251,
"s": 28983,
"text": "Round 0: It was a project discussion round where you will be asked about your projects and in depth working. If you are well versed with your projects, this is the easiest round to get through. 2 students were rejected in this round. This round took place over call. "
},
{
"code": null,
"e": 29653,
"s": 29251,
"text": "Round 1: It was the DSA round where I was asked 2 problems. The interviewer was really dull and non-interactive. He didn’t even read the question and simply just pasted the problem in the shared google doc. This round took place over google meet and I was asked to write code on the shared google doc. (Platform depends on interviewer too as one of my friend’s interview took place over a zoom call.)"
},
{
"code": null,
"e": 29813,
"s": 29653,
"text": "First problem was, given the following function f, I had to define another function which, given a number n, returns its prime factors along with their powers."
},
{
"code": null,
"e": 29817,
"s": 29813,
"text": "C++"
},
{
"code": "long long f(long long n) { if(n == 1 || n is a prime) { return n; } else { return any of the proper divisors of n; }}",
"e": 29969,
"s": 29817,
"text": null
},
{
"code": null,
"e": 30118,
"s": 29969,
"text": "Second problem was: https://leetcode.com/problems/backspace-string-compare/description/I was supposed to solve it in linear time and constant space."
},
{
"code": null,
"e": 30180,
"s": 30118,
"text": "I was supposed to solve it in linear time and constant space."
},
{
"code": null,
"e": 30306,
"s": 30180,
"text": "I was able to solve 1st problem completely and the second problem with the help of some hints. I was rejected in this round. "
},
{
"code": null,
"e": 30554,
"s": 30306,
"text": "Round 2: Some of my friends who were selected for this round were asked about there projects and then given an open ended problem. This round is for checking the creative thinking skills of the candidate and is usually taken by a senior employee. "
},
{
"code": null,
"e": 30767,
"s": 30554,
"text": "Overall, it was a good learning experience interviewing with codenation. Only one of the students were given the final offer for internship. After the online round shortlisting, the entire process took 2-3 days. "
},
{
"code": null,
"e": 30778,
"s": 30767,
"text": "Codenation"
},
{
"code": null,
"e": 30788,
"s": 30778,
"text": "Marketing"
},
{
"code": null,
"e": 30798,
"s": 30788,
"text": "On-Campus"
},
{
"code": null,
"e": 30809,
"s": 30798,
"text": "Internship"
},
{
"code": null,
"e": 30831,
"s": 30809,
"text": "Interview Experiences"
},
{
"code": null,
"e": 30842,
"s": 30831,
"text": "Codenation"
},
{
"code": null,
"e": 30940,
"s": 30842,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30949,
"s": 30940,
"text": "Comments"
},
{
"code": null,
"e": 30962,
"s": 30949,
"text": "Old Comments"
},
{
"code": null,
"e": 31021,
"s": 30962,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 31066,
"s": 31021,
"text": "Zoho Interview Experience (Off-Campus ) 2022"
},
{
"code": null,
"e": 31114,
"s": 31066,
"text": "Thoughtspot Interview Experience for SDE Intern"
},
{
"code": null,
"e": 31156,
"s": 31114,
"text": "TurboHire Internship Interview Experience"
},
{
"code": null,
"e": 31214,
"s": 31156,
"text": "Persistent Systems Interview Experience (Martian Program)"
},
{
"code": null,
"e": 31241,
"s": 31214,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 31300,
"s": 31241,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 31360,
"s": 31300,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 31410,
"s": 31360,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
}
] |
GATE | GATE-CS-2004 | Question 53 - GeeksforGeeks | 28 Jun, 2021
The employee information in a company is stored in the relation
Employee (name, sex, salary, deptName)
Consider the following SQL query
select deptName
from Employee
where sex = 'M'
group by deptName
having avg (salary) > (select avg (salary) from Employee)
It returns the names of the department in which(A) the average salary is more than the average salary in the company(B) the average salary of male employees is more than the average salary of all male employees in the company(C) the average salary of male employees is more than the average salary of employees in the same department
(D) the average salary of male employees is more than the average salary in the companyAnswer: (D)Explanation: In this SQL query, we have
select deptName --------------- Select the department name
from Employee ---------------- From the database of employees
where sex = 'M' --------------- Where sex is male (M)
group by deptName ------------- Group by the name of the department
having avg (salary) >
(select avg (salary) from Employee) ----- Having the average salary
greater than the average salary
of all employees in the organization.
So, this query would return the name of all departments in which the average salary of male employees is greater than the average salary of all employees in the company.
Hence, D is the correct choice.
Please comment below if you find anything wrong in the above post.Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25623,
"s": 25595,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25687,
"s": 25623,
"text": "The employee information in a company is stored in the relation"
},
{
"code": null,
"e": 25726,
"s": 25687,
"text": "Employee (name, sex, salary, deptName)"
},
{
"code": null,
"e": 25759,
"s": 25726,
"text": "Consider the following SQL query"
},
{
"code": null,
"e": 25910,
"s": 25759,
"text": "select deptName\n from Employee\n where sex = 'M'\n group by deptName\n having avg (salary) > (select avg (salary) from Employee)\n"
},
{
"code": null,
"e": 26244,
"s": 25910,
"text": "It returns the names of the department in which(A) the average salary is more than the average salary in the company(B) the average salary of male employees is more than the average salary of all male employees in the company(C) the average salary of male employees is more than the average salary of employees in the same department"
},
{
"code": null,
"e": 26382,
"s": 26244,
"text": "(D) the average salary of male employees is more than the average salary in the companyAnswer: (D)Explanation: In this SQL query, we have"
},
{
"code": null,
"e": 26886,
"s": 26382,
"text": "select deptName --------------- Select the department name\nfrom Employee ---------------- From the database of employees\nwhere sex = 'M' --------------- Where sex is male (M)\ngroup by deptName ------------- Group by the name of the department\nhaving avg (salary) > \n(select avg (salary) from Employee) ----- Having the average salary \n greater than the average salary \n of all employees in the organization.\n"
},
{
"code": null,
"e": 27056,
"s": 26886,
"text": "So, this query would return the name of all departments in which the average salary of male employees is greater than the average salary of all employees in the company."
},
{
"code": null,
"e": 27088,
"s": 27056,
"text": "Hence, D is the correct choice."
},
{
"code": null,
"e": 27178,
"s": 27090,
"text": "Please comment below if you find anything wrong in the above post.Quiz of this Question"
},
{
"code": null,
"e": 27191,
"s": 27178,
"text": "GATE-CS-2004"
},
{
"code": null,
"e": 27209,
"s": 27191,
"text": "GATE-GATE-CS-2004"
},
{
"code": null,
"e": 27214,
"s": 27209,
"text": "GATE"
},
{
"code": null,
"e": 27312,
"s": 27214,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27346,
"s": 27312,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 27380,
"s": 27346,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27414,
"s": 27380,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27447,
"s": 27414,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27483,
"s": 27447,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27517,
"s": 27483,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27553,
"s": 27517,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27587,
"s": 27553,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27621,
"s": 27587,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Python | Convert Bytearray to Hexadecimal String - GeeksforGeeks | 27 Jun, 2019
Sometimes, we might be in a problem in which we need to handle the unusual datatype conversions. One such conversion can be converting the list of bytes(bytearray) to the Hexadecimal string format. Let’s discuss certain ways in which this can be done.
Method #1 : Using format() + join()The combination of above functions can be used to perform this particular task. The format function converts the bytes in hexadecimal format. “02” in format is used to pad required leading zeroes. The join function allows to join the hexadecimal result into a string.
# Python3 code to demonstrate working of# Converting bytearray to hexadecimal string# Using join() + format() # initializing list test_list = [124, 67, 45, 11] # printing original list print("The original string is : " + str(test_list)) # using join() + format()# Converting bytearray to hexadecimal stringres = ''.join(format(x, '02x') for x in test_list) # printing result print("The string after conversion : " + str(res))
The original string is : [124, 67, 45, 11]
The string after conversion : 7c432d0b
Method #2 : Using binascii.hexlify()The inbuilt function of hexlify can be used to perform this particular task. This function is recommended for this particular conversion as it is tailormade to solve this specific problem.
# Python3 code to demonstrate working of# Converting bytearray to hexadecimal string# Using binascii.hexlify()import binascii # initializing list test_list = [124, 67, 45, 11] # printing original list print("The original string is : " + str(test_list)) # using binascii.hexlify()# Converting bytearray to hexadecimal stringres = binascii.hexlify(bytearray(test_list)) # printing result print("The string after conversion : " + str(res))
The original string is : [124, 67, 45, 11]
The string after conversion : 7c432d0b
Python string-programs
Python
Python Programs
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 dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n27 Jun, 2019"
},
{
"code": null,
"e": 25789,
"s": 25537,
"text": "Sometimes, we might be in a problem in which we need to handle the unusual datatype conversions. One such conversion can be converting the list of bytes(bytearray) to the Hexadecimal string format. Let’s discuss certain ways in which this can be done."
},
{
"code": null,
"e": 26092,
"s": 25789,
"text": "Method #1 : Using format() + join()The combination of above functions can be used to perform this particular task. The format function converts the bytes in hexadecimal format. “02” in format is used to pad required leading zeroes. The join function allows to join the hexadecimal result into a string."
},
{
"code": "# Python3 code to demonstrate working of# Converting bytearray to hexadecimal string# Using join() + format() # initializing list test_list = [124, 67, 45, 11] # printing original list print(\"The original string is : \" + str(test_list)) # using join() + format()# Converting bytearray to hexadecimal stringres = ''.join(format(x, '02x') for x in test_list) # printing result print(\"The string after conversion : \" + str(res))",
"e": 26522,
"s": 26092,
"text": null
},
{
"code": null,
"e": 26605,
"s": 26522,
"text": "The original string is : [124, 67, 45, 11]\nThe string after conversion : 7c432d0b\n"
},
{
"code": null,
"e": 26832,
"s": 26607,
"text": "Method #2 : Using binascii.hexlify()The inbuilt function of hexlify can be used to perform this particular task. This function is recommended for this particular conversion as it is tailormade to solve this specific problem."
},
{
"code": "# Python3 code to demonstrate working of# Converting bytearray to hexadecimal string# Using binascii.hexlify()import binascii # initializing list test_list = [124, 67, 45, 11] # printing original list print(\"The original string is : \" + str(test_list)) # using binascii.hexlify()# Converting bytearray to hexadecimal stringres = binascii.hexlify(bytearray(test_list)) # printing result print(\"The string after conversion : \" + str(res))",
"e": 27273,
"s": 26832,
"text": null
},
{
"code": null,
"e": 27356,
"s": 27273,
"text": "The original string is : [124, 67, 45, 11]\nThe string after conversion : 7c432d0b\n"
},
{
"code": null,
"e": 27379,
"s": 27356,
"text": "Python string-programs"
},
{
"code": null,
"e": 27386,
"s": 27379,
"text": "Python"
},
{
"code": null,
"e": 27402,
"s": 27386,
"text": "Python Programs"
},
{
"code": null,
"e": 27500,
"s": 27402,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27532,
"s": 27500,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27574,
"s": 27532,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27616,
"s": 27574,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27643,
"s": 27616,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27699,
"s": 27643,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27721,
"s": 27699,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27760,
"s": 27721,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27806,
"s": 27760,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27844,
"s": 27806,
"text": "Python | Convert a list to dictionary"
}
] |
Program to check the validity of password without using regex. - GeeksforGeeks | 04 Apr, 2022
Password checker program basically checks if a password is valid or not based on the password policies mention below:
Password should not contain any space.
Password should contain at least one digit(0-9).
Password length should be between 8 to 15 characters.
Password should contain at least one lowercase letter(a-z).
Password should contain at least one uppercase letter(A-Z).
Password should contain at least one special character ( @, #, %, &, !, $, etc...).
Example:
Input: GeeksForGeeks
Output: Invalid Password!
This input contains lowercase
as well as uppercase letters
but does not contain digits
and special characters.
Input: Geek$ForGeeks7
Output: Valid Password
This input satisfies all password
policies mentioned above.
Approach:In this program,
we are using String contains () method to check the passwords. This method accepts a CharSequence as an argument and returns true if the argument is present in a string otherwise returns false.
Firstly the length of the password has to be checked then whether it contains uppercase, lowercase, digits and special characters.
If all of them are present then the method isValid(String password) returns true.
Below is the implementation of the above approach:
Java
C++
Python3
C#
// Java code to validate a password public class PasswordValidator { // A utility function to check // whether a password is valid or not public static boolean isValid(String password) { // for checking if password length // is between 8 and 15 if (!((password.length() >= 8) && (password.length() <= 15))) { return false; } // to check space if (password.contains(" ")) { return false; } if (true) { int count = 0; // check digits from 0 to 9 for (int i = 0; i <= 9; i++) { // to convert int to string String str1 = Integer.toString(i); if (password.contains(str1)) { count = 1; } } if (count == 0) { return false; } } // for special characters if (!(password.contains("@") || password.contains("#") || password.contains("!") || password.contains("~") || password.contains("$") || password.contains("%") || password.contains("^") || password.contains("&") || password.contains("*") || password.contains("(") || password.contains(")") || password.contains("-") || password.contains("+") || password.contains("/") || password.contains(":") || password.contains(".") || password.contains(", ") || password.contains("<") || password.contains(">") || password.contains("?") || password.contains("|"))) { return false; } if (true) { int count = 0; // checking capital letters for (int i = 65; i <= 90; i++) { // type casting char c = (char)i; String str1 = Character.toString(c); if (password.contains(str1)) { count = 1; } } if (count == 0) { return false; } } if (true) { int count = 0; // checking small letters for (int i = 97; i <= 122; i++) { // type casting char c = (char)i; String str1 = Character.toString(c); if (password.contains(str1)) { count = 1; } } if (count == 0) { return false; } } // if all conditions fails return true; } // Driver code public static void main(String[] args) { String password1 = "GeeksForGeeks"; if (isValid(password1)) { System.out.println(password1 + " - Valid Password"); } else { System.out.println(password1 + " - Invalid Password!"); } String password2 = "Geek$ForGeeks7"; if (isValid(password2)) { System.out.println(password2 + " - Valid Password"); } else { System.out.println(password2 + " - Invalid Password!"); } }}
// C++ code to validate a password#include<bits/stdc++.h>using namespace std; // A utility function to check// whether a password is valid or notbool isValid(string password){ // For checking if password length // is between 8 and 15 if (!((password.length() >= 8) && (password.length() <= 15))) return false; // To check space if (password.find(" ") != std::string::npos) return false; if (true) { int count = 0; // Check digits from 0 to 9 for(int i = 0; i <= 9; i++) { // To convert int to string string str1 = to_string(i); if (password.find(str1) != std::string::npos) count = 1; } if (count == 0) return false; } // For special characters if (!((password.find("@") != std::string::npos) || (password.find("#") != std::string::npos) || (password.find("!") != std::string::npos) || (password.find("~") != std::string::npos) || (password.find("$") != std::string::npos) || (password.find("%") != std::string::npos) || (password.find("^") != std::string::npos) || (password.find("&") != std::string::npos) || (password.find("*") != std::string::npos) || (password.find("(") != std::string::npos) || (password.find(")") != std::string::npos) || (password.find("-") != std::string::npos) || (password.find("+") != std::string::npos) || (password.find("/") != std::string::npos) || (password.find(":") != std::string::npos) || (password.find(".") != std::string::npos) || (password.find(",") != std::string::npos) || (password.find("<") != std::string::npos) || (password.find(">") != std::string::npos) || (password.find("?") != std::string::npos) || (password.find("|") != std::string::npos))) return false; if (true) { int count = 0; // Checking capital letters for(int i = 65; i <= 90; i++) { // Type casting char c = (char)i; string str1(1, c); if (password.find(str1) != std::string::npos) count = 1; } if (count == 0) return false; } if (true) { int count = 0; // Checking small letters for(int i = 97; i <= 122; i++) { // Type casting char c = (char)i; string str1(1, c); if (password.find(str1) != std::string::npos) count = 1; } if (count == 0) return false; } // If all conditions fails return true;} // Driver codeint main(){ string password1 = "GeeksForGeeks"; if (isValid(password1)) cout << "Valid Password" << endl; else cout << "Invalid Password" << endl; string password2 = "Geek$ForGeeks7"; if (isValid(password2)) cout << "Valid Password" << endl; else cout << "Invalid Password" << endl;} // This code is contributed by Yash_R
# Python3 code to validate a password # A utility function to check# whether a password is valid or notdef isValid(password): # for checking if password length # is between 8 and 15 if (len(password) < 8 or len(password) > 15): return False # to check space if (" " in password): return False if (True): count = 0 # check digits from 0 to 9 arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] for i in password: if i in arr: count = 1 break if count == 0: return False # for special characters if True: count = 0 arr = ['@', '#','!','~','$','%','^', '&','*','(',',','-','+','/', ':','.',',','<','>','?','|'] for i in password: if i in arr: count = 1 break if count == 0: return False if True: count = 0 # checking capital letters for i in range(65, 91): if chr(i) in password: count = 1 if (count == 0): return False if (True): count = 0 # checking small letters for i in range(97, 123): if chr(i) in password: count = 1 if (count == 0): return False # if all conditions fails return True # Driver codepassword1 = "GeeksForGeeks" if (isValid([i for i in password1])): print("Valid Password")else: print("Invalid Password!!!") password2 = "Geek$ForGeeks7"if (isValid([i for i in password2])): print("Valid Password")else: print("Invalid Password!!!") # This code is contributed by mohit kumar 29
// C# code to validate a passwordusing System; class PasswordValidator{ // A utility function to check // whether a password is valid or not public static bool isValid(String password) { // for checking if password length // is between 8 and 15 if (!((password.Length >= 8) && (password.Length <= 15))) { return false; } // to check space if (password.Contains(" ")) { return false; } if (true) { int count = 0; // check digits from 0 to 9 for (int i = 0; i <= 9; i++) { // to convert int to string String str1 = i.ToString(); if (password.Contains(str1)) { count = 1; } } if (count == 0) { return false; } } // for special characters if (!(password.Contains("@") || password.Contains("#") || password.Contains("!") || password.Contains("~") || password.Contains("$") || password.Contains("%") || password.Contains("^") || password.Contains("&") || password.Contains("*") || password.Contains("(") || password.Contains(")") || password.Contains("-") || password.Contains("+") || password.Contains("/") || password.Contains(":") || password.Contains(".") || password.Contains(", ") || password.Contains("<") || password.Contains(">") || password.Contains("?") || password.Contains("|"))) { return false; } if (true) { int count = 0; // checking capital letters for (int i = 65; i <= 90; i++) { // type casting char c = (char)i; String str1 = c.ToString(); if (password.Contains(str1)) { count = 1; } } if (count == 0) { return false; } } if (true) { int count = 0; // checking small letters for (int i = 97; i <= 122; i++) { // type casting char c = (char)i; String str1 = c.ToString(); if (password.Contains(str1)) { count = 1; } } if (count == 0) { return false; } } // if all conditions fails return true; } // Driver code public static void Main(String[] args) { String password1 = "GeeksForGeeks"; if (isValid(password1)) { Console.WriteLine("Valid Password"); } else { Console.WriteLine("Invalid Password!!!"); } String password2 = "Geek$ForGeeks7"; if (isValid(password2)) { Console.WriteLine("Valid Password"); } else { Console.WriteLine("Invalid Password!!!"); } }} // This code is contributed by Rajput-Ji
GeeksForGeeks - Invalid Password!
Geek$ForGeeks7 - Valid Password
mohit kumar 29
Rajput-Ji
Yash_R
Anoop_Varghese
shivanshjona
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews | [
{
"code": null,
"e": 26477,
"s": 26449,
"text": "\n04 Apr, 2022"
},
{
"code": null,
"e": 26597,
"s": 26477,
"text": "Password checker program basically checks if a password is valid or not based on the password policies mention below: "
},
{
"code": null,
"e": 26638,
"s": 26597,
"text": "Password should not contain any space. "
},
{
"code": null,
"e": 26689,
"s": 26638,
"text": "Password should contain at least one digit(0-9). "
},
{
"code": null,
"e": 26745,
"s": 26689,
"text": "Password length should be between 8 to 15 characters. "
},
{
"code": null,
"e": 26807,
"s": 26745,
"text": "Password should contain at least one lowercase letter(a-z). "
},
{
"code": null,
"e": 26869,
"s": 26807,
"text": "Password should contain at least one uppercase letter(A-Z). "
},
{
"code": null,
"e": 26953,
"s": 26869,
"text": "Password should contain at least one special character ( @, #, %, &, !, $, etc...)."
},
{
"code": null,
"e": 26964,
"s": 26953,
"text": "Example: "
},
{
"code": null,
"e": 27232,
"s": 26964,
"text": "Input: GeeksForGeeks \nOutput: Invalid Password!\nThis input contains lowercase \nas well as uppercase letters \nbut does not contain digits \nand special characters.\n\nInput: Geek$ForGeeks7\nOutput: Valid Password\nThis input satisfies all password\npolicies mentioned above."
},
{
"code": null,
"e": 27262,
"s": 27234,
"text": "Approach:In this program, "
},
{
"code": null,
"e": 27458,
"s": 27262,
"text": "we are using String contains () method to check the passwords. This method accepts a CharSequence as an argument and returns true if the argument is present in a string otherwise returns false. "
},
{
"code": null,
"e": 27591,
"s": 27458,
"text": "Firstly the length of the password has to be checked then whether it contains uppercase, lowercase, digits and special characters. "
},
{
"code": null,
"e": 27673,
"s": 27591,
"text": "If all of them are present then the method isValid(String password) returns true."
},
{
"code": null,
"e": 27726,
"s": 27673,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27731,
"s": 27726,
"text": "Java"
},
{
"code": null,
"e": 27735,
"s": 27731,
"text": "C++"
},
{
"code": null,
"e": 27743,
"s": 27735,
"text": "Python3"
},
{
"code": null,
"e": 27746,
"s": 27743,
"text": "C#"
},
{
"code": "// Java code to validate a password public class PasswordValidator { // A utility function to check // whether a password is valid or not public static boolean isValid(String password) { // for checking if password length // is between 8 and 15 if (!((password.length() >= 8) && (password.length() <= 15))) { return false; } // to check space if (password.contains(\" \")) { return false; } if (true) { int count = 0; // check digits from 0 to 9 for (int i = 0; i <= 9; i++) { // to convert int to string String str1 = Integer.toString(i); if (password.contains(str1)) { count = 1; } } if (count == 0) { return false; } } // for special characters if (!(password.contains(\"@\") || password.contains(\"#\") || password.contains(\"!\") || password.contains(\"~\") || password.contains(\"$\") || password.contains(\"%\") || password.contains(\"^\") || password.contains(\"&\") || password.contains(\"*\") || password.contains(\"(\") || password.contains(\")\") || password.contains(\"-\") || password.contains(\"+\") || password.contains(\"/\") || password.contains(\":\") || password.contains(\".\") || password.contains(\", \") || password.contains(\"<\") || password.contains(\">\") || password.contains(\"?\") || password.contains(\"|\"))) { return false; } if (true) { int count = 0; // checking capital letters for (int i = 65; i <= 90; i++) { // type casting char c = (char)i; String str1 = Character.toString(c); if (password.contains(str1)) { count = 1; } } if (count == 0) { return false; } } if (true) { int count = 0; // checking small letters for (int i = 97; i <= 122; i++) { // type casting char c = (char)i; String str1 = Character.toString(c); if (password.contains(str1)) { count = 1; } } if (count == 0) { return false; } } // if all conditions fails return true; } // Driver code public static void main(String[] args) { String password1 = \"GeeksForGeeks\"; if (isValid(password1)) { System.out.println(password1 + \" - Valid Password\"); } else { System.out.println(password1 + \" - Invalid Password!\"); } String password2 = \"Geek$ForGeeks7\"; if (isValid(password2)) { System.out.println(password2 + \" - Valid Password\"); } else { System.out.println(password2 + \" - Invalid Password!\"); } }}",
"e": 30882,
"s": 27746,
"text": null
},
{
"code": "// C++ code to validate a password#include<bits/stdc++.h>using namespace std; // A utility function to check// whether a password is valid or notbool isValid(string password){ // For checking if password length // is between 8 and 15 if (!((password.length() >= 8) && (password.length() <= 15))) return false; // To check space if (password.find(\" \") != std::string::npos) return false; if (true) { int count = 0; // Check digits from 0 to 9 for(int i = 0; i <= 9; i++) { // To convert int to string string str1 = to_string(i); if (password.find(str1) != std::string::npos) count = 1; } if (count == 0) return false; } // For special characters if (!((password.find(\"@\") != std::string::npos) || (password.find(\"#\") != std::string::npos) || (password.find(\"!\") != std::string::npos) || (password.find(\"~\") != std::string::npos) || (password.find(\"$\") != std::string::npos) || (password.find(\"%\") != std::string::npos) || (password.find(\"^\") != std::string::npos) || (password.find(\"&\") != std::string::npos) || (password.find(\"*\") != std::string::npos) || (password.find(\"(\") != std::string::npos) || (password.find(\")\") != std::string::npos) || (password.find(\"-\") != std::string::npos) || (password.find(\"+\") != std::string::npos) || (password.find(\"/\") != std::string::npos) || (password.find(\":\") != std::string::npos) || (password.find(\".\") != std::string::npos) || (password.find(\",\") != std::string::npos) || (password.find(\"<\") != std::string::npos) || (password.find(\">\") != std::string::npos) || (password.find(\"?\") != std::string::npos) || (password.find(\"|\") != std::string::npos))) return false; if (true) { int count = 0; // Checking capital letters for(int i = 65; i <= 90; i++) { // Type casting char c = (char)i; string str1(1, c); if (password.find(str1) != std::string::npos) count = 1; } if (count == 0) return false; } if (true) { int count = 0; // Checking small letters for(int i = 97; i <= 122; i++) { // Type casting char c = (char)i; string str1(1, c); if (password.find(str1) != std::string::npos) count = 1; } if (count == 0) return false; } // If all conditions fails return true;} // Driver codeint main(){ string password1 = \"GeeksForGeeks\"; if (isValid(password1)) cout << \"Valid Password\" << endl; else cout << \"Invalid Password\" << endl; string password2 = \"Geek$ForGeeks7\"; if (isValid(password2)) cout << \"Valid Password\" << endl; else cout << \"Invalid Password\" << endl;} // This code is contributed by Yash_R",
"e": 34097,
"s": 30882,
"text": null
},
{
"code": "# Python3 code to validate a password # A utility function to check# whether a password is valid or notdef isValid(password): # for checking if password length # is between 8 and 15 if (len(password) < 8 or len(password) > 15): return False # to check space if (\" \" in password): return False if (True): count = 0 # check digits from 0 to 9 arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] for i in password: if i in arr: count = 1 break if count == 0: return False # for special characters if True: count = 0 arr = ['@', '#','!','~','$','%','^', '&','*','(',',','-','+','/', ':','.',',','<','>','?','|'] for i in password: if i in arr: count = 1 break if count == 0: return False if True: count = 0 # checking capital letters for i in range(65, 91): if chr(i) in password: count = 1 if (count == 0): return False if (True): count = 0 # checking small letters for i in range(97, 123): if chr(i) in password: count = 1 if (count == 0): return False # if all conditions fails return True # Driver codepassword1 = \"GeeksForGeeks\" if (isValid([i for i in password1])): print(\"Valid Password\")else: print(\"Invalid Password!!!\") password2 = \"Geek$ForGeeks7\"if (isValid([i for i in password2])): print(\"Valid Password\")else: print(\"Invalid Password!!!\") # This code is contributed by mohit kumar 29",
"e": 35811,
"s": 34097,
"text": null
},
{
"code": "// C# code to validate a passwordusing System; class PasswordValidator{ // A utility function to check // whether a password is valid or not public static bool isValid(String password) { // for checking if password length // is between 8 and 15 if (!((password.Length >= 8) && (password.Length <= 15))) { return false; } // to check space if (password.Contains(\" \")) { return false; } if (true) { int count = 0; // check digits from 0 to 9 for (int i = 0; i <= 9; i++) { // to convert int to string String str1 = i.ToString(); if (password.Contains(str1)) { count = 1; } } if (count == 0) { return false; } } // for special characters if (!(password.Contains(\"@\") || password.Contains(\"#\") || password.Contains(\"!\") || password.Contains(\"~\") || password.Contains(\"$\") || password.Contains(\"%\") || password.Contains(\"^\") || password.Contains(\"&\") || password.Contains(\"*\") || password.Contains(\"(\") || password.Contains(\")\") || password.Contains(\"-\") || password.Contains(\"+\") || password.Contains(\"/\") || password.Contains(\":\") || password.Contains(\".\") || password.Contains(\", \") || password.Contains(\"<\") || password.Contains(\">\") || password.Contains(\"?\") || password.Contains(\"|\"))) { return false; } if (true) { int count = 0; // checking capital letters for (int i = 65; i <= 90; i++) { // type casting char c = (char)i; String str1 = c.ToString(); if (password.Contains(str1)) { count = 1; } } if (count == 0) { return false; } } if (true) { int count = 0; // checking small letters for (int i = 97; i <= 122; i++) { // type casting char c = (char)i; String str1 = c.ToString(); if (password.Contains(str1)) { count = 1; } } if (count == 0) { return false; } } // if all conditions fails return true; } // Driver code public static void Main(String[] args) { String password1 = \"GeeksForGeeks\"; if (isValid(password1)) { Console.WriteLine(\"Valid Password\"); } else { Console.WriteLine(\"Invalid Password!!!\"); } String password2 = \"Geek$ForGeeks7\"; if (isValid(password2)) { Console.WriteLine(\"Valid Password\"); } else { Console.WriteLine(\"Invalid Password!!!\"); } }} // This code is contributed by Rajput-Ji",
"e": 39058,
"s": 35811,
"text": null
},
{
"code": null,
"e": 39124,
"s": 39058,
"text": "GeeksForGeeks - Invalid Password!\nGeek$ForGeeks7 - Valid Password"
},
{
"code": null,
"e": 39139,
"s": 39124,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 39149,
"s": 39139,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 39156,
"s": 39149,
"text": "Yash_R"
},
{
"code": null,
"e": 39171,
"s": 39156,
"text": "Anoop_Varghese"
},
{
"code": null,
"e": 39184,
"s": 39171,
"text": "shivanshjona"
},
{
"code": null,
"e": 39192,
"s": 39184,
"text": "Strings"
},
{
"code": null,
"e": 39200,
"s": 39192,
"text": "Strings"
},
{
"code": null,
"e": 39298,
"s": 39200,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39373,
"s": 39298,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 39430,
"s": 39373,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 39466,
"s": 39430,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 39513,
"s": 39466,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 39566,
"s": 39513,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 39602,
"s": 39566,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 39640,
"s": 39602,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 39670,
"s": 39640,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 39722,
"s": 39670,
"text": "Check whether two strings are anagram of each other"
}
] |
Python | os.truncate() method - GeeksforGeeks | 11 Oct, 2021
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.truncate() method in Python is used to truncate the file indicated by the specified path to at most specified length.
Syntax: os.truncate(path, length)
Parameters:path: A path-like object representing a file system path. This will indicate the file to be truncated.A path-like object is either a string or bytes object representing a path.length: An integer value denoting length (in bytes) to which the file is to be truncated.
Return Type: This method does not return any value.
Consider the below text as the content of the file named Python_intro.txt.
Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently.
# Python program to explain os.truncate() method # importing os module import os # File pathpath = "/home / ihritik / Desktop / Python_intro.txt" # Print the original size of the file (in bytes)print("File size (in bytes):", os.path.getsize(path)) # Length (in Bytes) to which # the file will be truncatedlength = 72 # Truncate the file # to at most given length# using os.truncate() methodos.truncate(path, length) # Print the content of fileprint("Content of file Python_intro.txt:")with open(path, 'r') as f: print(f.read()) # Print the new size of the file (in bytes)print("File size (in bytes):", os.path.getsize(path))
File size (in bytes): 409
Content of file Python_intro.txt:
Python is a widely used general-purpose, high level programming language
File size (in bytes): 72
Consider the below text as the new content of the file named Python_intro.txt.
Python is a widely used general-purpose, high level programming language
# Python program to explain os.truncate() method # importing os module import os # File pathpath = "/home / ihritik / Desktop / Python_intro.txt" # Print the original size of the file (in bytes)print("File size (in bytes):", os.path.getsize(path)) # Length (in Bytes) to which # the file will be truncatedlength = 72 # Truncate the file # to at most given length# using os.truncate() methodos.truncate(path, length) # Print the content of fileprint("Content of file Python_intro.txt:")with open(path, 'r') as f: print(f.read()) # Print the new size of the file (in bytes)print("File size (in bytes):", os.path.getsize(path))
File size (in bytes): 72
Content of file Python_intro.txt:
Python is a widely used general-purpose, high level programming language
File size (in bytes): 100
Actual file content after truncating file sized 72 bytes to 100 bytes:The file content up to its original size did not changed but to increase the file size to the specified size it got filled with some invalid characters.
# Python program to explain os.truncate() method # importing os module import os # File pathpath = "/home / ihritik / Desktop / Python_intro.txt" # Print the original size of the file (in bytes)print("File size (in bytes):", os.path.getsize(path)) # specify the length as 0# to delete the file contentlength = 0 # Truncate the file # to length 0os.truncate(path, length) # Print the content of fileprint("Content of file Python_intro.txt:")with open(path, 'r') as f: print(f.read()) # Print the new size of the file (in bytes)print("File size (in bytes):", os.path.getsize(path)) # Consider the same Python_intro.txt file# used in above example for this example
File size (in bytes): 100
Content of file Python_intro.txt:
File size (in bytes): 0
adnanirshad158
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 ?
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": "\n11 Oct, 2021"
},
{
"code": null,
"e": 25756,
"s": 25537,
"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."
},
{
"code": null,
"e": 25877,
"s": 25756,
"text": "os.truncate() method in Python is used to truncate the file indicated by the specified path to at most specified length."
},
{
"code": null,
"e": 25911,
"s": 25877,
"text": "Syntax: os.truncate(path, length)"
},
{
"code": null,
"e": 26188,
"s": 25911,
"text": "Parameters:path: A path-like object representing a file system path. This will indicate the file to be truncated.A path-like object is either a string or bytes object representing a path.length: An integer value denoting length (in bytes) to which the file is to be truncated."
},
{
"code": null,
"e": 26240,
"s": 26188,
"text": "Return Type: This method does not return any value."
},
{
"code": null,
"e": 26315,
"s": 26240,
"text": "Consider the below text as the content of the file named Python_intro.txt."
},
{
"code": null,
"e": 26724,
"s": 26315,
"text": "Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently."
},
{
"code": "# Python program to explain os.truncate() method # importing os module import os # File pathpath = \"/home / ihritik / Desktop / Python_intro.txt\" # Print the original size of the file (in bytes)print(\"File size (in bytes):\", os.path.getsize(path)) # Length (in Bytes) to which # the file will be truncatedlength = 72 # Truncate the file # to at most given length# using os.truncate() methodos.truncate(path, length) # Print the content of fileprint(\"Content of file Python_intro.txt:\")with open(path, 'r') as f: print(f.read()) # Print the new size of the file (in bytes)print(\"File size (in bytes):\", os.path.getsize(path))",
"e": 27363,
"s": 26724,
"text": null
},
{
"code": null,
"e": 27522,
"s": 27363,
"text": "File size (in bytes): 409\nContent of file Python_intro.txt:\nPython is a widely used general-purpose, high level programming language\nFile size (in bytes): 72\n"
},
{
"code": null,
"e": 27601,
"s": 27522,
"text": "Consider the below text as the new content of the file named Python_intro.txt."
},
{
"code": null,
"e": 27674,
"s": 27601,
"text": "Python is a widely used general-purpose, high level programming language"
},
{
"code": "# Python program to explain os.truncate() method # importing os module import os # File pathpath = \"/home / ihritik / Desktop / Python_intro.txt\" # Print the original size of the file (in bytes)print(\"File size (in bytes):\", os.path.getsize(path)) # Length (in Bytes) to which # the file will be truncatedlength = 72 # Truncate the file # to at most given length# using os.truncate() methodos.truncate(path, length) # Print the content of fileprint(\"Content of file Python_intro.txt:\")with open(path, 'r') as f: print(f.read()) # Print the new size of the file (in bytes)print(\"File size (in bytes):\", os.path.getsize(path))",
"e": 28313,
"s": 27674,
"text": null
},
{
"code": null,
"e": 28473,
"s": 28313,
"text": "File size (in bytes): 72\nContent of file Python_intro.txt:\nPython is a widely used general-purpose, high level programming language\n\nFile size (in bytes): 100\n"
},
{
"code": null,
"e": 28696,
"s": 28473,
"text": "Actual file content after truncating file sized 72 bytes to 100 bytes:The file content up to its original size did not changed but to increase the file size to the specified size it got filled with some invalid characters."
},
{
"code": "# Python program to explain os.truncate() method # importing os module import os # File pathpath = \"/home / ihritik / Desktop / Python_intro.txt\" # Print the original size of the file (in bytes)print(\"File size (in bytes):\", os.path.getsize(path)) # specify the length as 0# to delete the file contentlength = 0 # Truncate the file # to length 0os.truncate(path, length) # Print the content of fileprint(\"Content of file Python_intro.txt:\")with open(path, 'r') as f: print(f.read()) # Print the new size of the file (in bytes)print(\"File size (in bytes):\", os.path.getsize(path)) # Consider the same Python_intro.txt file# used in above example for this example",
"e": 29373,
"s": 28696,
"text": null
},
{
"code": null,
"e": 29459,
"s": 29373,
"text": "File size (in bytes): 100\nContent of file Python_intro.txt:\n\nFile size (in bytes): 0\n"
},
{
"code": null,
"e": 29474,
"s": 29459,
"text": "adnanirshad158"
},
{
"code": null,
"e": 29491,
"s": 29474,
"text": "python-os-module"
},
{
"code": null,
"e": 29498,
"s": 29491,
"text": "Python"
},
{
"code": null,
"e": 29596,
"s": 29498,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29628,
"s": 29596,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29670,
"s": 29628,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29712,
"s": 29670,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29739,
"s": 29712,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29795,
"s": 29739,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29817,
"s": 29795,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29856,
"s": 29817,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29887,
"s": 29856,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29916,
"s": 29887,
"text": "Create a directory in Python"
}
] |
Get the day from a date in Pandas - GeeksforGeeks | 09 Dec, 2021
Given a particular date, it is possible to obtain the day of the week on which the date falls. This is achieved with the help of Pandas library and the to_datetime() method present in pandas. In most of the datasets the Date column appears to be of the data type String, which definitely isn’t comfortable to perform any calculations with that column, such as the difference in months between 2 dates, the difference in time or finding the day of the week. Hence Pandas provides a method called to_datetime() to convert strings into Timestamp objects.Examples :
We'll use the date format 'dd/mm/yyyy'
Input : '24/07/2020'
Output : 'Friday'
Input : '01/01/2001'
Output : 'Monday'
Once we convert a date in string format into a date time object, it is easy to get the day of the week using the method day_name() on the Timestamp object created.Example 1 : In this example, we pass a random date with the type ‘str’ and format ‘dd/mm/yyyy’ to the to_datetime() method . As a result we get a Timestamp pandas object. Then we retrieve the day of the week by the Timestamp class’s day_name() method.
Python3
# importing the moduleimport pandas as pd # the date in "dd/mm/yyyy" formatdate = "19/02/2022"print("Initially the type is : ", type(date)) # converting string to DateTimedate = pd.to_datetime(date, format = "%d/%m/%Y")print("After conversion, the type is : ", type(date)) # fetching the dayprint("The day is : " + date.day_name())
Output :
Example 2 : In the below example, dates of different formats have been converted to a Timestamp object and then their respective days of the week are retrieved using day_name() method .
Python3
# importing the moduleimport pandas as pd # 'dd-mm-yyyy'date_1 = '22-07-2011' date_1 = pd.to_datetime(date_1, format ="%d-%m-%Y") print("The day on the date " + str(date_1) + " is : " + date_1.day_name()) # 'mm.dd.yyyy'date_2 = '12.03.2000' date_2 = pd.to_datetime(date_2, format ="%m.%d.%Y")print("The day on the date " + str(date_2) + " is : " + date_2.day_name()) # 'yyyy / dd / mm'date_3 = '2004/9/4' date_3 = pd.to_datetime(date_3, format ="%Y/%d/%m")print("The day on the date " + str(date_2) + " is : " + date_3.day_name())
Output :
surindertarika1234
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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": "\n09 Dec, 2021"
},
{
"code": null,
"e": 26101,
"s": 25537,
"text": "Given a particular date, it is possible to obtain the day of the week on which the date falls. This is achieved with the help of Pandas library and the to_datetime() method present in pandas. In most of the datasets the Date column appears to be of the data type String, which definitely isn’t comfortable to perform any calculations with that column, such as the difference in months between 2 dates, the difference in time or finding the day of the week. Hence Pandas provides a method called to_datetime() to convert strings into Timestamp objects.Examples : "
},
{
"code": null,
"e": 26224,
"s": 26101,
"text": "We'll use the date format 'dd/mm/yyyy'\n\nInput : '24/07/2020' \nOutput : 'Friday' \n\nInput : '01/01/2001'\nOutput : 'Monday' "
},
{
"code": null,
"e": 26640,
"s": 26224,
"text": "Once we convert a date in string format into a date time object, it is easy to get the day of the week using the method day_name() on the Timestamp object created.Example 1 : In this example, we pass a random date with the type ‘str’ and format ‘dd/mm/yyyy’ to the to_datetime() method . As a result we get a Timestamp pandas object. Then we retrieve the day of the week by the Timestamp class’s day_name() method. "
},
{
"code": null,
"e": 26648,
"s": 26640,
"text": "Python3"
},
{
"code": "# importing the moduleimport pandas as pd # the date in \"dd/mm/yyyy\" formatdate = \"19/02/2022\"print(\"Initially the type is : \", type(date)) # converting string to DateTimedate = pd.to_datetime(date, format = \"%d/%m/%Y\")print(\"After conversion, the type is : \", type(date)) # fetching the dayprint(\"The day is : \" + date.day_name())",
"e": 26980,
"s": 26648,
"text": null
},
{
"code": null,
"e": 26991,
"s": 26980,
"text": "Output : "
},
{
"code": null,
"e": 27179,
"s": 26991,
"text": "Example 2 : In the below example, dates of different formats have been converted to a Timestamp object and then their respective days of the week are retrieved using day_name() method . "
},
{
"code": null,
"e": 27187,
"s": 27179,
"text": "Python3"
},
{
"code": "# importing the moduleimport pandas as pd # 'dd-mm-yyyy'date_1 = '22-07-2011' date_1 = pd.to_datetime(date_1, format =\"%d-%m-%Y\") print(\"The day on the date \" + str(date_1) + \" is : \" + date_1.day_name()) # 'mm.dd.yyyy'date_2 = '12.03.2000' date_2 = pd.to_datetime(date_2, format =\"%m.%d.%Y\")print(\"The day on the date \" + str(date_2) + \" is : \" + date_2.day_name()) # 'yyyy / dd / mm'date_3 = '2004/9/4' date_3 = pd.to_datetime(date_3, format =\"%Y/%d/%m\")print(\"The day on the date \" + str(date_2) + \" is : \" + date_3.day_name())",
"e": 27735,
"s": 27187,
"text": null
},
{
"code": null,
"e": 27746,
"s": 27735,
"text": "Output : "
},
{
"code": null,
"e": 27767,
"s": 27748,
"text": "surindertarika1234"
},
{
"code": null,
"e": 27791,
"s": 27767,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27814,
"s": 27791,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 27828,
"s": 27814,
"text": "Python-pandas"
},
{
"code": null,
"e": 27835,
"s": 27828,
"text": "Python"
},
{
"code": null,
"e": 27933,
"s": 27835,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27965,
"s": 27933,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28007,
"s": 27965,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28049,
"s": 28007,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28076,
"s": 28049,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28132,
"s": 28076,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28154,
"s": 28132,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28193,
"s": 28154,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28224,
"s": 28193,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28253,
"s": 28224,
"text": "Create a directory in Python"
}
] |
Python program for arranging the students according to their marks in descending order - GeeksforGeeks | 20 Aug, 2020
Consider a class of 20 students whose names and marks are given to you. The task is to arrange the students according to their marks in decreasing order. Write a python program to perform the task.
Examples:
Input:
Arun: 78%
Geeta: 86%
Shilpi: 65%
Output:
Geeta: 86%
Arun: 78%
Shilpi: 65%
Approach: Since problem states that we need to collect student name and their marks first so for this we will take inputs one by one in the list data structure then sort them in reverse order using sorted() built-in function based on the student’s percentage and in the last we will print the value accordingly.
Below is the implementation:
Python3
print("-----Program for printing student name with marks using list-----") # create an empty dictionaryD = {} n = int(input('How many student record you want to store?? ')) # create an empty list# Add student information to the listls = [] for i in range(0, n): # Take combined input name and # percentage and split values # using split function. x,y = input("Enter the student name and it's percentage: ").split() # Add name and marks stored in x, y # respectively using tuple to the list ls.append((y,x)) # sort the elements of list# based on marksls = sorted(ls, reverse = True) print('Sorted list of students according to their marks in descending order') for i in ls: # print name and marks stored in # second and first position # respectively in list of tuples. print(i[1], i[0])
Output:
-----Program for printing student name with marks using list-----
How many student record you want to store?? 3
Enter the student name and percentage: Arun: 78%
Enter the student name and percentage: Geeta: 86%
Enter the student name and percentage: Shilpi: 65%
Sorted list of students according to their marks in descending order
Geeta: 86%
Arun: 78%
Shilpi: 65%
school-programming
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary | [
{
"code": null,
"e": 26078,
"s": 26050,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 26276,
"s": 26078,
"text": "Consider a class of 20 students whose names and marks are given to you. The task is to arrange the students according to their marks in decreasing order. Write a python program to perform the task."
},
{
"code": null,
"e": 26286,
"s": 26276,
"text": "Examples:"
},
{
"code": null,
"e": 26372,
"s": 26286,
"text": "Input:\nArun: 78%\nGeeta: 86%\nShilpi: 65%\n\nOutput: \nGeeta: 86%\nArun: 78%\nShilpi: 65%\n\n\n"
},
{
"code": null,
"e": 26684,
"s": 26372,
"text": "Approach: Since problem states that we need to collect student name and their marks first so for this we will take inputs one by one in the list data structure then sort them in reverse order using sorted() built-in function based on the student’s percentage and in the last we will print the value accordingly."
},
{
"code": null,
"e": 26713,
"s": 26684,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 26721,
"s": 26713,
"text": "Python3"
},
{
"code": "print(\"-----Program for printing student name with marks using list-----\") # create an empty dictionaryD = {} n = int(input('How many student record you want to store?? ')) # create an empty list# Add student information to the listls = [] for i in range(0, n): # Take combined input name and # percentage and split values # using split function. x,y = input(\"Enter the student name and it's percentage: \").split() # Add name and marks stored in x, y # respectively using tuple to the list ls.append((y,x)) # sort the elements of list# based on marksls = sorted(ls, reverse = True) print('Sorted list of students according to their marks in descending order') for i in ls: # print name and marks stored in # second and first position # respectively in list of tuples. print(i[1], i[0])",
"e": 27571,
"s": 26721,
"text": null
},
{
"code": null,
"e": 27579,
"s": 27571,
"text": "Output:"
},
{
"code": null,
"e": 27946,
"s": 27579,
"text": "-----Program for printing student name with marks using list-----\nHow many student record you want to store?? 3\nEnter the student name and percentage: Arun: 78%\nEnter the student name and percentage: Geeta: 86%\nEnter the student name and percentage: Shilpi: 65%\nSorted list of students according to their marks in descending order\nGeeta: 86%\nArun: 78%\nShilpi: 65%\n\n\n"
},
{
"code": null,
"e": 27965,
"s": 27946,
"text": "school-programming"
},
{
"code": null,
"e": 27972,
"s": 27965,
"text": "Python"
},
{
"code": null,
"e": 27988,
"s": 27972,
"text": "Python Programs"
},
{
"code": null,
"e": 28086,
"s": 27988,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28104,
"s": 28086,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28139,
"s": 28104,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28171,
"s": 28139,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28193,
"s": 28171,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28235,
"s": 28193,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28278,
"s": 28235,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28300,
"s": 28278,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28339,
"s": 28300,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28385,
"s": 28339,
"text": "Python | Split string into list of characters"
}
] |
Convert given Binary Array to String in C++ with Examples - GeeksforGeeks | 08 Dec, 2021
Given a binary array arr[] containing N integer elements, the task is to create a string s which contains all N elements at the same indices as they were in array arr[].
Example:
Input: arr[] = {0, 1, 0, 1}Output: string = “0101“
Input: arr[] = { 1, 1, 0, 0, 1, 1}Output: string = “110011”
Different methods to convert a binary array to a string in C++ are:
Using to_string() function.Using string stream.Adding char ‘0’ to each integer.Using type casting.Using push_back function.Using transform() function.
Using to_string() function.
Using string stream.
Adding char ‘0’ to each integer.
Using type casting.
Using push_back function.
Using transform() function.
Let’s start discussing each of these functions in detail.
Using to_string() function
The to_string() function accepts a single integer and converts the integer value into a string.
Syntax:
string to_string (int val);
Parameters:val – Numerical value.
Return Value:A string object containing the representation of val as a sequence of characters.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement// the above approach#include <iostream>#include <string>using namespace std; // Driver codeint main(){ int arr[5] = {1, 0, 1, 0, 1}; int size = sizeof(arr) / sizeof(arr[0]); // Creating an empty string string s = ""; for(int i = 0; i < size; i++) { s += to_string(arr[i]); } cout << s; return 0;}
Output:
10101
Using string stream
stringstream class is extremely useful in parsing input. A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream class the sstream header file needs to be included in the code.
Basic methods are:
clear(): to clear the stream
str(): to get and set string object whose content is present in stream.
operator << add a string to the stringstream object.
operator >> read something from the stringstream object,
The stringstream class can be used to convert the integer value into a string value in the following manner:
Insert data into the stream using ‘<<‘ operator.Extract data from stream using ‘>>’ operator or by using str() function.Concatenate the extracted data with the string ‘s’.
Insert data into the stream using ‘<<‘ operator.
Extract data from stream using ‘>>’ operator or by using str() function.
Concatenate the extracted data with the string ‘s’.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement// the above approach#include <iostream>#include <sstream>#include <string>using namespace std; // Driver codeint main(){ int arr[5] = {1, 0, 1, 0, 1}; int size = sizeof(arr) / sizeof(arr[0]); // Creating an empty string string s = ""; for(int i = 0; i < size; i++) { // Creating an empty stringstream stringstream temp; // Inserting data into the stream temp << arr[i]; // Extracting data from stream using // .str() function s += temp.str(); } // Printing the string cout << s;}
Output:
10101
Adding char ‘0’ to each Integer
The approach for adding char ‘0’ to each integer is quite simple.
First step is to declare an empty string s.Iterate over each element of array and concatenate each integer by adding ASCII Value of char ‘0’ with the string s.
First step is to declare an empty string s.
Iterate over each element of array and concatenate each integer by adding ASCII Value of char ‘0’ with the string s.
Logic:The result of adding ASCII value of char ‘0’ with integer 0 and 1 is computed by compiler as follows:
Decimal value of char ‘0’ is 48.
string += 0 + ‘0’ // += 0 + 48 // += 48Char value of decimal 48 is ‘0’.
string += 1 + ‘0’ // += 1 + 48 // += 49Char value of decimal 49 is ‘1’.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement // the above approach#include <iostream>#include <string>using namespace std; // Driver codeint main() { int arr[5] = {1, 1, 1, 0, 1}; int size = sizeof(arr) / sizeof(arr[0]); string s = ""; // Creating an empty string for(int i = 0; i < size; i++) { // arr[i] + 48 // adding ASCII of value of 0 // i.e., 48 s += arr[i] + '0'; } // Printing the string cout << s;}
Output:
11101
Using type casting
Before type casting and concatenating there is a need to add 48 to the integer otherwise it will lead to some weird symbols at the output. This happens because in the ASCII table numbers from 0 to 9 have a char value that starts from 48 to 57. In the case of a binary array, the integer will either be 0 or 1.
If it is 0, after adding it will be 48 then after type casting char ‘0’ is concatenated with string.If it is 1, after adding it will be 49 then after type casting char ‘1’ is concatenated with string.
If it is 0, after adding it will be 48 then after type casting char ‘0’ is concatenated with string.
If it is 1, after adding it will be 49 then after type casting char ‘1’ is concatenated with string.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement// the above approach#include <iostream>#include <string>using namespace std; // Driver codeint main(){ int arr[5] = {1, 1, 1, 0, 1}; int size = sizeof(arr) / sizeof(arr[0]); // Creating an empty string string s = ""; for(int i = 0; i < size; i++) { arr[i] += 48; s += (char) arr[i]; } // Printing the string cout << s;}
Output:
11101
Using push_back() function
The push_back() member function is provided to append characters. Appends character c to the end of the string, increasing its length by one.
Syntax:
void string:: push_back (char c)
Parameters: Character which to be appended.
Return value: None
Error: throws length_error if the resulting size exceeds the maximum number of characters(max_size).
Note:Logic behind adding char ‘0’ has been discussed in Method “Adding ‘0’ to integer”.
Below is the C++ program to implement the above approach:
C++
// C++ program to implement // the above approach#include <iostream>#include <vector>using namespace std; // Driver codeint main() { int arr[5] = {1, 0, 1, 0, 1}; int size = sizeof(arr) / sizeof(arr[0]); vector<char> s; for(int i = 0; i < size; i++) { s.push_back(arr[i] + '0'); } for(auto it : s) { cout << it; }}
Output:
10101
Using transform() function
The transform() function sequentially applies an operation to the elements of an array and store the result in another output array. To use the transform() function include the algorithm header file.
Below is the C++ program to implement the above method:
C++
// C++ program to implement// the above method#include <iostream>#include <algorithm>using namespace std; // define int to char functionchar intToChar(int i) { // logic behind adding 48 to integer // is discussed in Method "using type // casting". return i + 48;} // Driver codeint main() { int arr[5] = {1, 0, 1, 0, 1}; int size = sizeof(arr) / sizeof(arr[0]); char str[size + 1]; transform(arr, arr + 5, str, intToChar); // Printing the string cout << str;}
Output:
10101
Arrays
strings
C++
Strings
Arrays
Strings
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++
std::string class in C++
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 25537,
"s": 25367,
"text": "Given a binary array arr[] containing N integer elements, the task is to create a string s which contains all N elements at the same indices as they were in array arr[]."
},
{
"code": null,
"e": 25546,
"s": 25537,
"text": "Example:"
},
{
"code": null,
"e": 25597,
"s": 25546,
"text": "Input: arr[] = {0, 1, 0, 1}Output: string = “0101“"
},
{
"code": null,
"e": 25657,
"s": 25597,
"text": "Input: arr[] = { 1, 1, 0, 0, 1, 1}Output: string = “110011”"
},
{
"code": null,
"e": 25725,
"s": 25657,
"text": "Different methods to convert a binary array to a string in C++ are:"
},
{
"code": null,
"e": 25876,
"s": 25725,
"text": "Using to_string() function.Using string stream.Adding char ‘0’ to each integer.Using type casting.Using push_back function.Using transform() function."
},
{
"code": null,
"e": 25904,
"s": 25876,
"text": "Using to_string() function."
},
{
"code": null,
"e": 25925,
"s": 25904,
"text": "Using string stream."
},
{
"code": null,
"e": 25958,
"s": 25925,
"text": "Adding char ‘0’ to each integer."
},
{
"code": null,
"e": 25978,
"s": 25958,
"text": "Using type casting."
},
{
"code": null,
"e": 26004,
"s": 25978,
"text": "Using push_back function."
},
{
"code": null,
"e": 26032,
"s": 26004,
"text": "Using transform() function."
},
{
"code": null,
"e": 26090,
"s": 26032,
"text": "Let’s start discussing each of these functions in detail."
},
{
"code": null,
"e": 26117,
"s": 26090,
"text": "Using to_string() function"
},
{
"code": null,
"e": 26213,
"s": 26117,
"text": "The to_string() function accepts a single integer and converts the integer value into a string."
},
{
"code": null,
"e": 26221,
"s": 26213,
"text": "Syntax:"
},
{
"code": null,
"e": 26249,
"s": 26221,
"text": "string to_string (int val);"
},
{
"code": null,
"e": 26283,
"s": 26249,
"text": "Parameters:val – Numerical value."
},
{
"code": null,
"e": 26378,
"s": 26283,
"text": "Return Value:A string object containing the representation of val as a sequence of characters."
},
{
"code": null,
"e": 26436,
"s": 26378,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 26440,
"s": 26436,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>#include <string>using namespace std; // Driver codeint main(){ int arr[5] = {1, 0, 1, 0, 1}; int size = sizeof(arr) / sizeof(arr[0]); // Creating an empty string string s = \"\"; for(int i = 0; i < size; i++) { s += to_string(arr[i]); } cout << s; return 0;}",
"e": 26787,
"s": 26440,
"text": null
},
{
"code": null,
"e": 26795,
"s": 26787,
"text": "Output:"
},
{
"code": null,
"e": 26801,
"s": 26795,
"text": "10101"
},
{
"code": null,
"e": 26821,
"s": 26801,
"text": "Using string stream"
},
{
"code": null,
"e": 27090,
"s": 26821,
"text": "stringstream class is extremely useful in parsing input. A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream class the sstream header file needs to be included in the code."
},
{
"code": null,
"e": 27110,
"s": 27090,
"text": "Basic methods are:"
},
{
"code": null,
"e": 27139,
"s": 27110,
"text": "clear(): to clear the stream"
},
{
"code": null,
"e": 27211,
"s": 27139,
"text": "str(): to get and set string object whose content is present in stream."
},
{
"code": null,
"e": 27264,
"s": 27211,
"text": "operator << add a string to the stringstream object."
},
{
"code": null,
"e": 27321,
"s": 27264,
"text": "operator >> read something from the stringstream object,"
},
{
"code": null,
"e": 27430,
"s": 27321,
"text": "The stringstream class can be used to convert the integer value into a string value in the following manner:"
},
{
"code": null,
"e": 27602,
"s": 27430,
"text": "Insert data into the stream using ‘<<‘ operator.Extract data from stream using ‘>>’ operator or by using str() function.Concatenate the extracted data with the string ‘s’."
},
{
"code": null,
"e": 27651,
"s": 27602,
"text": "Insert data into the stream using ‘<<‘ operator."
},
{
"code": null,
"e": 27724,
"s": 27651,
"text": "Extract data from stream using ‘>>’ operator or by using str() function."
},
{
"code": null,
"e": 27776,
"s": 27724,
"text": "Concatenate the extracted data with the string ‘s’."
},
{
"code": null,
"e": 27834,
"s": 27776,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 27838,
"s": 27834,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>#include <sstream>#include <string>using namespace std; // Driver codeint main(){ int arr[5] = {1, 0, 1, 0, 1}; int size = sizeof(arr) / sizeof(arr[0]); // Creating an empty string string s = \"\"; for(int i = 0; i < size; i++) { // Creating an empty stringstream stringstream temp; // Inserting data into the stream temp << arr[i]; // Extracting data from stream using // .str() function s += temp.str(); } // Printing the string cout << s;}",
"e": 28400,
"s": 27838,
"text": null
},
{
"code": null,
"e": 28408,
"s": 28400,
"text": "Output:"
},
{
"code": null,
"e": 28414,
"s": 28408,
"text": "10101"
},
{
"code": null,
"e": 28446,
"s": 28414,
"text": "Adding char ‘0’ to each Integer"
},
{
"code": null,
"e": 28512,
"s": 28446,
"text": "The approach for adding char ‘0’ to each integer is quite simple."
},
{
"code": null,
"e": 28672,
"s": 28512,
"text": "First step is to declare an empty string s.Iterate over each element of array and concatenate each integer by adding ASCII Value of char ‘0’ with the string s."
},
{
"code": null,
"e": 28716,
"s": 28672,
"text": "First step is to declare an empty string s."
},
{
"code": null,
"e": 28833,
"s": 28716,
"text": "Iterate over each element of array and concatenate each integer by adding ASCII Value of char ‘0’ with the string s."
},
{
"code": null,
"e": 28941,
"s": 28833,
"text": "Logic:The result of adding ASCII value of char ‘0’ with integer 0 and 1 is computed by compiler as follows:"
},
{
"code": null,
"e": 28974,
"s": 28941,
"text": "Decimal value of char ‘0’ is 48."
},
{
"code": null,
"e": 29057,
"s": 28974,
"text": "string += 0 + ‘0’ // += 0 + 48 // += 48Char value of decimal 48 is ‘0’."
},
{
"code": null,
"e": 29139,
"s": 29057,
"text": "string += 1 + ‘0’ // += 1 + 48 // += 49Char value of decimal 49 is ‘1’."
},
{
"code": null,
"e": 29197,
"s": 29139,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 29201,
"s": 29197,
"text": "C++"
},
{
"code": "// C++ program to implement // the above approach#include <iostream>#include <string>using namespace std; // Driver codeint main() { int arr[5] = {1, 1, 1, 0, 1}; int size = sizeof(arr) / sizeof(arr[0]); string s = \"\"; // Creating an empty string for(int i = 0; i < size; i++) { // arr[i] + 48 // adding ASCII of value of 0 // i.e., 48 s += arr[i] + '0'; } // Printing the string cout << s;}",
"e": 29627,
"s": 29201,
"text": null
},
{
"code": null,
"e": 29635,
"s": 29627,
"text": "Output:"
},
{
"code": null,
"e": 29641,
"s": 29635,
"text": "11101"
},
{
"code": null,
"e": 29660,
"s": 29641,
"text": "Using type casting"
},
{
"code": null,
"e": 29970,
"s": 29660,
"text": "Before type casting and concatenating there is a need to add 48 to the integer otherwise it will lead to some weird symbols at the output. This happens because in the ASCII table numbers from 0 to 9 have a char value that starts from 48 to 57. In the case of a binary array, the integer will either be 0 or 1."
},
{
"code": null,
"e": 30171,
"s": 29970,
"text": "If it is 0, after adding it will be 48 then after type casting char ‘0’ is concatenated with string.If it is 1, after adding it will be 49 then after type casting char ‘1’ is concatenated with string."
},
{
"code": null,
"e": 30272,
"s": 30171,
"text": "If it is 0, after adding it will be 48 then after type casting char ‘0’ is concatenated with string."
},
{
"code": null,
"e": 30373,
"s": 30272,
"text": "If it is 1, after adding it will be 49 then after type casting char ‘1’ is concatenated with string."
},
{
"code": null,
"e": 30431,
"s": 30373,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 30435,
"s": 30431,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach#include <iostream>#include <string>using namespace std; // Driver codeint main(){ int arr[5] = {1, 1, 1, 0, 1}; int size = sizeof(arr) / sizeof(arr[0]); // Creating an empty string string s = \"\"; for(int i = 0; i < size; i++) { arr[i] += 48; s += (char) arr[i]; } // Printing the string cout << s;}",
"e": 30808,
"s": 30435,
"text": null
},
{
"code": null,
"e": 30816,
"s": 30808,
"text": "Output:"
},
{
"code": null,
"e": 30822,
"s": 30816,
"text": "11101"
},
{
"code": null,
"e": 30849,
"s": 30822,
"text": "Using push_back() function"
},
{
"code": null,
"e": 30991,
"s": 30849,
"text": "The push_back() member function is provided to append characters. Appends character c to the end of the string, increasing its length by one."
},
{
"code": null,
"e": 30999,
"s": 30991,
"text": "Syntax:"
},
{
"code": null,
"e": 31032,
"s": 30999,
"text": "void string:: push_back (char c)"
},
{
"code": null,
"e": 31079,
"s": 31032,
"text": "Parameters: Character which to be appended. "
},
{
"code": null,
"e": 31098,
"s": 31079,
"text": "Return value: None"
},
{
"code": null,
"e": 31199,
"s": 31098,
"text": "Error: throws length_error if the resulting size exceeds the maximum number of characters(max_size)."
},
{
"code": null,
"e": 31287,
"s": 31199,
"text": "Note:Logic behind adding char ‘0’ has been discussed in Method “Adding ‘0’ to integer”."
},
{
"code": null,
"e": 31345,
"s": 31287,
"text": "Below is the C++ program to implement the above approach:"
},
{
"code": null,
"e": 31349,
"s": 31345,
"text": "C++"
},
{
"code": "// C++ program to implement // the above approach#include <iostream>#include <vector>using namespace std; // Driver codeint main() { int arr[5] = {1, 0, 1, 0, 1}; int size = sizeof(arr) / sizeof(arr[0]); vector<char> s; for(int i = 0; i < size; i++) { s.push_back(arr[i] + '0'); } for(auto it : s) { cout << it; }}",
"e": 31682,
"s": 31349,
"text": null
},
{
"code": null,
"e": 31690,
"s": 31682,
"text": "Output:"
},
{
"code": null,
"e": 31696,
"s": 31690,
"text": "10101"
},
{
"code": null,
"e": 31723,
"s": 31696,
"text": "Using transform() function"
},
{
"code": null,
"e": 31924,
"s": 31723,
"text": "The transform() function sequentially applies an operation to the elements of an array and store the result in another output array. To use the transform() function include the algorithm header file. "
},
{
"code": null,
"e": 31980,
"s": 31924,
"text": "Below is the C++ program to implement the above method:"
},
{
"code": null,
"e": 31984,
"s": 31980,
"text": "C++"
},
{
"code": "// C++ program to implement// the above method#include <iostream>#include <algorithm>using namespace std; // define int to char functionchar intToChar(int i) { // logic behind adding 48 to integer // is discussed in Method \"using type // casting\". return i + 48;} // Driver codeint main() { int arr[5] = {1, 0, 1, 0, 1}; int size = sizeof(arr) / sizeof(arr[0]); char str[size + 1]; transform(arr, arr + 5, str, intToChar); // Printing the string cout << str;}",
"e": 32462,
"s": 31984,
"text": null
},
{
"code": null,
"e": 32470,
"s": 32462,
"text": "Output:"
},
{
"code": null,
"e": 32476,
"s": 32470,
"text": "10101"
},
{
"code": null,
"e": 32483,
"s": 32476,
"text": "Arrays"
},
{
"code": null,
"e": 32491,
"s": 32483,
"text": "strings"
},
{
"code": null,
"e": 32495,
"s": 32491,
"text": "C++"
},
{
"code": null,
"e": 32503,
"s": 32495,
"text": "Strings"
},
{
"code": null,
"e": 32510,
"s": 32503,
"text": "Arrays"
},
{
"code": null,
"e": 32518,
"s": 32510,
"text": "Strings"
},
{
"code": null,
"e": 32522,
"s": 32518,
"text": "CPP"
},
{
"code": null,
"e": 32620,
"s": 32522,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32648,
"s": 32620,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 32668,
"s": 32648,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 32692,
"s": 32668,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 32725,
"s": 32692,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 32750,
"s": 32725,
"text": "std::string class in C++"
},
{
"code": null,
"e": 32796,
"s": 32750,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 32821,
"s": 32796,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32881,
"s": 32821,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32915,
"s": 32881,
"text": "Longest Common Subsequence | DP-4"
}
] |
Java Program to Get the Attributes of a File - GeeksforGeeks | 04 Jan, 2021
In Java, there are several packages and API’s to perform a lot of different functions. One such package is java.nio.file. This package contains various methods which provide support for files. A package is java.nio.file.attribute, which can be used to access the attributes of the files specified in the path object.
So basically we are using the above mentioned two packages to access the attributes of files.
java.nio.file: This package is used to access FileSystem class and uses the inbuilt method “getpath()” helpful to get the path object.
java.nio.file.attribute: This package contains a lot of classes with predefined methods to read and access the attributes of a file. Firstly getFileAttributeView() method is used to get the files attributes and then readAttributes() method is used to get the attributes of the file. Then finally several methods of the class “BasicFileAttributes” are used to display various attributes of the file.
Below shows the basic implementation of these methods to display all the attributes of the file.
Java
// Java program to get the attributes of a fileimport java.nio.file.*;import java.nio.file.attribute.*;public class GFG { public static void main(String[] args) throws Exception { // reading the file path from the system. Scanner sc = new Scanner(System.in); System.out.println("Enter the file path"); String s = sc.next(); // setting the path Path path = FileSystems.getDefault().getPath(s); // setting all the file data to the attributes // in class file of BasicFileAttributeView. BasicFileAttributeView view = Files.getFileAttributeView( path, BasicFileAttributeView.class); // method to read the file attributes. BasicFileAttributes attribute = view.readAttributes(); // method to check the creation time of the file. System.out.print("Creation Time of the file: "); System.out.println(attribute.creationTime()); System.out.print( "Last Accessed Time of the file: "); System.out.println(attribute.lastAccessTime()); // method to check the last // modified time for the file System.out.print( "Last Modified Time for the file: "); System.out.println(attribute.lastModifiedTime()); // method to access the check whether // the file is a directory or not. System.out.println("Directory or not: " + attribute.isDirectory()); // method to access the size of the file in KB. System.out.println("Size of the file: " + attribute.size()); }}
Output:
Some other attributes are accessed as shown below:
Java
// Java program to get the attributes of a fileimport java.util.Scanner;import java.nio.file.attribute.*;import java.nio.file.*; publicclass GFG {public static void main(String[] args) throws Exception { // reading the file path from the system. Scanner sc = new Scanner(System.in); System.out.println("Enter the file path"); String s = sc.next(); // setting the path Path path = FileSystems.getDefault().getPath(s); // setting all the file data to the attributes in // class file of BasicFileAttributeView. BasicFileAttributeView view = Files.getFileAttributeView( path, BasicFileAttributeView.class); // method to read the file attributes. BasicFileAttributes attribute = view.readAttributes(); // check for regularity System.out.print("Regular File or not: "); System.out.println(attribute.isRegularFile()); // check whether it is a symbolic file or not System.out.print("Symbolic File or not: "); System.out.println(attribute.isSymbolicLink()); // type of file System.out.print("Other Type of File or not: "); System.out.println(attribute.isOther()); }}
Output:
Java-File Class
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": "\n04 Jan, 2021"
},
{
"code": null,
"e": 25542,
"s": 25225,
"text": "In Java, there are several packages and API’s to perform a lot of different functions. One such package is java.nio.file. This package contains various methods which provide support for files. A package is java.nio.file.attribute, which can be used to access the attributes of the files specified in the path object."
},
{
"code": null,
"e": 25636,
"s": 25542,
"text": "So basically we are using the above mentioned two packages to access the attributes of files."
},
{
"code": null,
"e": 25771,
"s": 25636,
"text": "java.nio.file: This package is used to access FileSystem class and uses the inbuilt method “getpath()” helpful to get the path object."
},
{
"code": null,
"e": 26170,
"s": 25771,
"text": "java.nio.file.attribute: This package contains a lot of classes with predefined methods to read and access the attributes of a file. Firstly getFileAttributeView() method is used to get the files attributes and then readAttributes() method is used to get the attributes of the file. Then finally several methods of the class “BasicFileAttributes” are used to display various attributes of the file."
},
{
"code": null,
"e": 26267,
"s": 26170,
"text": "Below shows the basic implementation of these methods to display all the attributes of the file."
},
{
"code": null,
"e": 26272,
"s": 26267,
"text": "Java"
},
{
"code": "// Java program to get the attributes of a fileimport java.nio.file.*;import java.nio.file.attribute.*;public class GFG { public static void main(String[] args) throws Exception { // reading the file path from the system. Scanner sc = new Scanner(System.in); System.out.println(\"Enter the file path\"); String s = sc.next(); // setting the path Path path = FileSystems.getDefault().getPath(s); // setting all the file data to the attributes // in class file of BasicFileAttributeView. BasicFileAttributeView view = Files.getFileAttributeView( path, BasicFileAttributeView.class); // method to read the file attributes. BasicFileAttributes attribute = view.readAttributes(); // method to check the creation time of the file. System.out.print(\"Creation Time of the file: \"); System.out.println(attribute.creationTime()); System.out.print( \"Last Accessed Time of the file: \"); System.out.println(attribute.lastAccessTime()); // method to check the last // modified time for the file System.out.print( \"Last Modified Time for the file: \"); System.out.println(attribute.lastModifiedTime()); // method to access the check whether // the file is a directory or not. System.out.println(\"Directory or not: \" + attribute.isDirectory()); // method to access the size of the file in KB. System.out.println(\"Size of the file: \" + attribute.size()); }}",
"e": 27921,
"s": 26272,
"text": null
},
{
"code": null,
"e": 27929,
"s": 27921,
"text": "Output:"
},
{
"code": null,
"e": 27980,
"s": 27929,
"text": "Some other attributes are accessed as shown below:"
},
{
"code": null,
"e": 27985,
"s": 27980,
"text": "Java"
},
{
"code": "// Java program to get the attributes of a fileimport java.util.Scanner;import java.nio.file.attribute.*;import java.nio.file.*; publicclass GFG {public static void main(String[] args) throws Exception { // reading the file path from the system. Scanner sc = new Scanner(System.in); System.out.println(\"Enter the file path\"); String s = sc.next(); // setting the path Path path = FileSystems.getDefault().getPath(s); // setting all the file data to the attributes in // class file of BasicFileAttributeView. BasicFileAttributeView view = Files.getFileAttributeView( path, BasicFileAttributeView.class); // method to read the file attributes. BasicFileAttributes attribute = view.readAttributes(); // check for regularity System.out.print(\"Regular File or not: \"); System.out.println(attribute.isRegularFile()); // check whether it is a symbolic file or not System.out.print(\"Symbolic File or not: \"); System.out.println(attribute.isSymbolicLink()); // type of file System.out.print(\"Other Type of File or not: \"); System.out.println(attribute.isOther()); }}",
"e": 29248,
"s": 27985,
"text": null
},
{
"code": null,
"e": 29256,
"s": 29248,
"text": "Output:"
},
{
"code": null,
"e": 29272,
"s": 29256,
"text": "Java-File Class"
},
{
"code": null,
"e": 29279,
"s": 29272,
"text": "Picked"
},
{
"code": null,
"e": 29284,
"s": 29279,
"text": "Java"
},
{
"code": null,
"e": 29298,
"s": 29284,
"text": "Java Programs"
},
{
"code": null,
"e": 29303,
"s": 29298,
"text": "Java"
},
{
"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": 29416,
"s": 29401,
"text": "Stream In Java"
},
{
"code": null,
"e": 29437,
"s": 29416,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29456,
"s": 29437,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29486,
"s": 29456,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29532,
"s": 29486,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29558,
"s": 29532,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29592,
"s": 29558,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29639,
"s": 29592,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 29671,
"s": 29639,
"text": "How to Iterate HashMap in Java?"
}
] |
Program to define various types of constants in C# - GeeksforGeeks | 22 Jun, 2020
As in other programming languages, various types of constants are defined the same as defined in C#, we can also define various types of constants and print their values. They are fixed in values in the program. There can be any types of constants like integer, character constants, float, double, string, octal, hexadecimal, etc.
Define constant: By using const keyword a constant can be defined. Its value can never be changed once it is defined.
Syntax:
const data_type constant_name = value;
Example:
Input: const int a = 15;
Output: a: 15
Example 1:
// C# program to define different types of constants using System;using System.Text; namespace Geeks{ class GFG { // Main Method static void Main(string[] args) { // integer constant const int A = 15; // float constant const float B = 50.83f; // to print above values Console.WriteLine("A: {0}", A); Console.WriteLine("B: {0}", B); } }}
Output:
A: 15
B: 50.83
Example 2:
// C# program to define different types of constants using System;using System.Text; namespace Geeks{ class GFG { // Main Method static void Main(string[] args) { // character constant const char C = 'S'; // double constant const double D = 70.23; // string constant const string E = "Geeks"; // to print above values Console.WriteLine("C: {0}", C); Console.WriteLine("D: {0}", D); Console.WriteLine("E: {0}", E); } }}
Output:
C: S
D: 70.23
E: Geeks
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Convert String to Character Array in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7 | [
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 25878,
"s": 25547,
"text": "As in other programming languages, various types of constants are defined the same as defined in C#, we can also define various types of constants and print their values. They are fixed in values in the program. There can be any types of constants like integer, character constants, float, double, string, octal, hexadecimal, etc."
},
{
"code": null,
"e": 25996,
"s": 25878,
"text": "Define constant: By using const keyword a constant can be defined. Its value can never be changed once it is defined."
},
{
"code": null,
"e": 26004,
"s": 25996,
"text": "Syntax:"
},
{
"code": null,
"e": 26044,
"s": 26004,
"text": "const data_type constant_name = value;\n"
},
{
"code": null,
"e": 26053,
"s": 26044,
"text": "Example:"
},
{
"code": null,
"e": 26095,
"s": 26053,
"text": "Input: const int a = 15; \nOutput: a: 15\n"
},
{
"code": null,
"e": 26106,
"s": 26095,
"text": "Example 1:"
},
{
"code": "// C# program to define different types of constants using System;using System.Text; namespace Geeks{ class GFG { // Main Method static void Main(string[] args) { // integer constant const int A = 15; // float constant const float B = 50.83f; // to print above values Console.WriteLine(\"A: {0}\", A); Console.WriteLine(\"B: {0}\", B); } }}",
"e": 26603,
"s": 26106,
"text": null
},
{
"code": null,
"e": 26611,
"s": 26603,
"text": "Output:"
},
{
"code": null,
"e": 26627,
"s": 26611,
"text": "A: 15\nB: 50.83\n"
},
{
"code": null,
"e": 26638,
"s": 26627,
"text": "Example 2:"
},
{
"code": "// C# program to define different types of constants using System;using System.Text; namespace Geeks{ class GFG { // Main Method static void Main(string[] args) { // character constant const char C = 'S'; // double constant const double D = 70.23; // string constant const string E = \"Geeks\"; // to print above values Console.WriteLine(\"C: {0}\", C); Console.WriteLine(\"D: {0}\", D); Console.WriteLine(\"E: {0}\", E); } }}",
"e": 27245,
"s": 26638,
"text": null
},
{
"code": null,
"e": 27253,
"s": 27245,
"text": "Output:"
},
{
"code": null,
"e": 27277,
"s": 27253,
"text": "C: S\nD: 70.23\nE: Geeks\n"
},
{
"code": null,
"e": 27280,
"s": 27277,
"text": "C#"
},
{
"code": null,
"e": 27292,
"s": 27280,
"text": "C# Programs"
},
{
"code": null,
"e": 27390,
"s": 27292,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27413,
"s": 27390,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27441,
"s": 27413,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27458,
"s": 27441,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27480,
"s": 27458,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27509,
"s": 27480,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 27549,
"s": 27509,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 27583,
"s": 27549,
"text": "Program to Print a New Line in C#"
},
{
"code": null,
"e": 27629,
"s": 27583,
"text": "Getting a Month Name Using Month Number in C#"
},
{
"code": null,
"e": 27654,
"s": 27629,
"text": "Socket Programming in C#"
}
] |
How to prevent XSS with HTML/PHP ? - GeeksforGeeks | 17 Dec, 2021
Cross-Site Scripting or XSS is a type of security vulnerability where an attacker gains access to a website and executes a potentially malicious script at the client’s side. This is one of the code injections attacks which can be caused by incorrectly validating user data, which usually gets inserted into the page through a web form or using a hyperlink that has been tampered. This code can be inserted via any client-side coding languages such as JavaScript, HTML, PHP, VBScript.
Why do they occur?Cross-Site Scripting or XSS attacks occur mostly due to non-delivery of secure codes from the server-side developers. Thus, it is the responsibility of every programmer to provide a security code that can make it hard for attackers to exploit possible security vulnerabilities.
What can an attacker accomplish with XSS?XSS vulnerability can be used by an attacker to accomplish a set of potential nefarious goals, like –
Steal ‘session identifier’ – By stealing one’s session id, the attacker can impersonate us and access the application. This can lead to the unauthorized person accessing the potential data.
URL redirection – URL redirection is the act of redirecting a user to another malicious phishing page to gather sensitive information.
Run unwanted software – An attacker can also install malware on our computers and other devices. This malware can cause harm to the data which is residing on the device.
Preventing XSS in HTML and PHPFollowing are the methods by which we can prevent XSS in our web applications –
Using htmlspecialchars() function – The htmlspecialchars() function converts special characters to HTML entities. For a majority of web-apps, we can use this method and this is one of the most popular methods to prevent XSS. This process is also known as HTML Escaping.‘&’ (ampersand) becomes ‘&’‘”‘ (double quote) becomes ‘"’” (greater than) becomes ‘>’
‘&’ (ampersand) becomes ‘&’
‘”‘ (double quote) becomes ‘"’
” (greater than) becomes ‘>’
htmlentities() – htmlentities() also performs the same task as htmlspecialchars() but this function covers more character entities. Using this function may also lead to excessive encoding and may cause some content to display incorrectly.
strip_tags() – This function removes content between HTML tags. This function also does not filter or encode non-paired closing angular braces.
addslashes() – The addslashes() function adds a slash character in an attempt to prevent the attacker from terminating the variable assignment and adding the executable code at the end.
Content Security Policy (CSP) – CSP is the last option that we choose to defend against XSS attack. The use of CSP puts restrictions on the attacker’s actions. Our browser executes all the JavsScript it receives from the server, whether they be internally sourced or externally sourced. When it comes to an HTML document, the browser fails to determine whether the resource is malicious or not. CSP is an HTTP header that whitelists a set of trusted resource sources that a browser can use to determine trust in the incoming resource.X-Content-Security-Policy: script-src 'self'The above line implies the browser to only trust the source URL which refers to the current domain. All the inputs for resources will be grabbed by the browser from this source only and all the others will be ignored.There are many resource directives that we can add. Some of them are given below –connect-src: Limits the sources to which you can connect using XMLHttpRequest, WebSocket, etc.font-src: Limits the sources for web fonts. frame-src: Limits the source URLs that can be embedded on a page as frames.img-src: Limits the sources for images. media-src: Limits the sources for video and audio.object-src: Limits the sources for Flash and other plugins. script-src: Limits the sources for script files.style-src: Limits the sources for CSS files.
X-Content-Security-Policy: script-src 'self'
The above line implies the browser to only trust the source URL which refers to the current domain. All the inputs for resources will be grabbed by the browser from this source only and all the others will be ignored.There are many resource directives that we can add. Some of them are given below –
connect-src: Limits the sources to which you can connect using XMLHttpRequest, WebSocket, etc.
font-src: Limits the sources for web fonts. frame-src: Limits the source URLs that can be embedded on a page as frames.
img-src: Limits the sources for images. media-src: Limits the sources for video and audio.
object-src: Limits the sources for Flash and other plugins. script-src: Limits the sources for script files.
style-src: Limits the sources for CSS files.
Third Party PHP Libraries – There are also some third party PHP libraries that help in prevention of XSS. Some of these are listed below –htmLawedPHP Anti-XSSHTML PurifierAmong all of these, HTMLPurifier is frequently maintained and updated. It is quite simple to use, once the developer has attained a basic level of HTML scripting knowledge.
htmLawedPHP Anti-XSSHTML Purifier
htmLawed
PHP Anti-XSS
HTML Purifier
Among all of these, HTMLPurifier is frequently maintained and updated. It is quite simple to use, once the developer has attained a basic level of HTML scripting knowledge.
Conclusion: As a guiding principle, we should try not to insert user-controlled data unless it’s explicitly needed for the application to function. Comments can be its best example where a user can enter malicious XSS causing scripts. This can more often be seen as serving no functional purpose to the application but also introducing some serious security vulnerabilities.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
kalrap615
HTML-Misc
PHP-Misc
Picked
HTML
PHP
Web Technologies
Web technologies Questions
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
How to position a div at the bottom of its container using CSS?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ? | [
{
"code": null,
"e": 25901,
"s": 25873,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 26385,
"s": 25901,
"text": "Cross-Site Scripting or XSS is a type of security vulnerability where an attacker gains access to a website and executes a potentially malicious script at the client’s side. This is one of the code injections attacks which can be caused by incorrectly validating user data, which usually gets inserted into the page through a web form or using a hyperlink that has been tampered. This code can be inserted via any client-side coding languages such as JavaScript, HTML, PHP, VBScript."
},
{
"code": null,
"e": 26681,
"s": 26385,
"text": "Why do they occur?Cross-Site Scripting or XSS attacks occur mostly due to non-delivery of secure codes from the server-side developers. Thus, it is the responsibility of every programmer to provide a security code that can make it hard for attackers to exploit possible security vulnerabilities."
},
{
"code": null,
"e": 26824,
"s": 26681,
"text": "What can an attacker accomplish with XSS?XSS vulnerability can be used by an attacker to accomplish a set of potential nefarious goals, like –"
},
{
"code": null,
"e": 27014,
"s": 26824,
"text": "Steal ‘session identifier’ – By stealing one’s session id, the attacker can impersonate us and access the application. This can lead to the unauthorized person accessing the potential data."
},
{
"code": null,
"e": 27149,
"s": 27014,
"text": "URL redirection – URL redirection is the act of redirecting a user to another malicious phishing page to gather sensitive information."
},
{
"code": null,
"e": 27319,
"s": 27149,
"text": "Run unwanted software – An attacker can also install malware on our computers and other devices. This malware can cause harm to the data which is residing on the device."
},
{
"code": null,
"e": 27429,
"s": 27319,
"text": "Preventing XSS in HTML and PHPFollowing are the methods by which we can prevent XSS in our web applications –"
},
{
"code": null,
"e": 27784,
"s": 27429,
"text": "Using htmlspecialchars() function – The htmlspecialchars() function converts special characters to HTML entities. For a majority of web-apps, we can use this method and this is one of the most popular methods to prevent XSS. This process is also known as HTML Escaping.‘&’ (ampersand) becomes ‘&’‘”‘ (double quote) becomes ‘\"’” (greater than) becomes ‘>’"
},
{
"code": null,
"e": 27812,
"s": 27784,
"text": "‘&’ (ampersand) becomes ‘&’"
},
{
"code": null,
"e": 27843,
"s": 27812,
"text": "‘”‘ (double quote) becomes ‘\"’"
},
{
"code": null,
"e": 27872,
"s": 27843,
"text": "” (greater than) becomes ‘>’"
},
{
"code": null,
"e": 28111,
"s": 27872,
"text": "htmlentities() – htmlentities() also performs the same task as htmlspecialchars() but this function covers more character entities. Using this function may also lead to excessive encoding and may cause some content to display incorrectly."
},
{
"code": null,
"e": 28255,
"s": 28111,
"text": "strip_tags() – This function removes content between HTML tags. This function also does not filter or encode non-paired closing angular braces."
},
{
"code": null,
"e": 28441,
"s": 28255,
"text": "addslashes() – The addslashes() function adds a slash character in an attempt to prevent the attacker from terminating the variable assignment and adding the executable code at the end."
},
{
"code": null,
"e": 29774,
"s": 28441,
"text": "Content Security Policy (CSP) – CSP is the last option that we choose to defend against XSS attack. The use of CSP puts restrictions on the attacker’s actions. Our browser executes all the JavsScript it receives from the server, whether they be internally sourced or externally sourced. When it comes to an HTML document, the browser fails to determine whether the resource is malicious or not. CSP is an HTTP header that whitelists a set of trusted resource sources that a browser can use to determine trust in the incoming resource.X-Content-Security-Policy: script-src 'self'The above line implies the browser to only trust the source URL which refers to the current domain. All the inputs for resources will be grabbed by the browser from this source only and all the others will be ignored.There are many resource directives that we can add. Some of them are given below –connect-src: Limits the sources to which you can connect using XMLHttpRequest, WebSocket, etc.font-src: Limits the sources for web fonts. frame-src: Limits the source URLs that can be embedded on a page as frames.img-src: Limits the sources for images. media-src: Limits the sources for video and audio.object-src: Limits the sources for Flash and other plugins. script-src: Limits the sources for script files.style-src: Limits the sources for CSS files."
},
{
"code": null,
"e": 29819,
"s": 29774,
"text": "X-Content-Security-Policy: script-src 'self'"
},
{
"code": null,
"e": 30119,
"s": 29819,
"text": "The above line implies the browser to only trust the source URL which refers to the current domain. All the inputs for resources will be grabbed by the browser from this source only and all the others will be ignored.There are many resource directives that we can add. Some of them are given below –"
},
{
"code": null,
"e": 30214,
"s": 30119,
"text": "connect-src: Limits the sources to which you can connect using XMLHttpRequest, WebSocket, etc."
},
{
"code": null,
"e": 30334,
"s": 30214,
"text": "font-src: Limits the sources for web fonts. frame-src: Limits the source URLs that can be embedded on a page as frames."
},
{
"code": null,
"e": 30425,
"s": 30334,
"text": "img-src: Limits the sources for images. media-src: Limits the sources for video and audio."
},
{
"code": null,
"e": 30534,
"s": 30425,
"text": "object-src: Limits the sources for Flash and other plugins. script-src: Limits the sources for script files."
},
{
"code": null,
"e": 30579,
"s": 30534,
"text": "style-src: Limits the sources for CSS files."
},
{
"code": null,
"e": 30923,
"s": 30579,
"text": "Third Party PHP Libraries – There are also some third party PHP libraries that help in prevention of XSS. Some of these are listed below –htmLawedPHP Anti-XSSHTML PurifierAmong all of these, HTMLPurifier is frequently maintained and updated. It is quite simple to use, once the developer has attained a basic level of HTML scripting knowledge."
},
{
"code": null,
"e": 30957,
"s": 30923,
"text": "htmLawedPHP Anti-XSSHTML Purifier"
},
{
"code": null,
"e": 30966,
"s": 30957,
"text": "htmLawed"
},
{
"code": null,
"e": 30979,
"s": 30966,
"text": "PHP Anti-XSS"
},
{
"code": null,
"e": 30993,
"s": 30979,
"text": "HTML Purifier"
},
{
"code": null,
"e": 31166,
"s": 30993,
"text": "Among all of these, HTMLPurifier is frequently maintained and updated. It is quite simple to use, once the developer has attained a basic level of HTML scripting knowledge."
},
{
"code": null,
"e": 31541,
"s": 31166,
"text": "Conclusion: As a guiding principle, we should try not to insert user-controlled data unless it’s explicitly needed for the application to function. Comments can be its best example where a user can enter malicious XSS causing scripts. This can more often be seen as serving no functional purpose to the application but also introducing some serious security vulnerabilities."
},
{
"code": null,
"e": 31678,
"s": 31541,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 31688,
"s": 31678,
"text": "kalrap615"
},
{
"code": null,
"e": 31698,
"s": 31688,
"text": "HTML-Misc"
},
{
"code": null,
"e": 31707,
"s": 31698,
"text": "PHP-Misc"
},
{
"code": null,
"e": 31714,
"s": 31707,
"text": "Picked"
},
{
"code": null,
"e": 31719,
"s": 31714,
"text": "HTML"
},
{
"code": null,
"e": 31723,
"s": 31719,
"text": "PHP"
},
{
"code": null,
"e": 31740,
"s": 31723,
"text": "Web Technologies"
},
{
"code": null,
"e": 31767,
"s": 31740,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 31772,
"s": 31767,
"text": "HTML"
},
{
"code": null,
"e": 31776,
"s": 31772,
"text": "PHP"
},
{
"code": null,
"e": 31874,
"s": 31776,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31922,
"s": 31874,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31946,
"s": 31922,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 31996,
"s": 31946,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 32046,
"s": 31996,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 32110,
"s": 32046,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 32155,
"s": 32110,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 32205,
"s": 32155,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 32245,
"s": 32205,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 32269,
"s": 32245,
"text": "PHP in_array() Function"
}
] |
Difference between HLookup and VLookup - GeeksforGeeks | 09 Mar, 2021
HLookup :Horizontal Lookup function is called as HLookup function. This function used to find values horizontally across a set of rows in a table. It looks for a value horizontally across the lookup table. It returns an approximate or exact value based on the row number given in Excel. VLookup function provides the same lookup value as HLookup function provides.
Syntax of HLookup :
HLOOKUP(lookup_value, table_array, row_index_num, [range_lookup]).
VLookup :Vertical Lookup function is called as VLookup function. This function is used to find values vertically across a set of rows in a table. It looks for a value vertically across the lookup table. It returns an exact or approximate value based on the column number given in Excel.
Syntax of VLookup :
VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup]).
Difference between HLookup and VLookup :
S.NO.
HLOOKUP
VLOOKUP
Difference Between
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Types of Software Testing
Software Engineering | COCOMO Model
Functional vs Non Functional Requirements
Software Engineering | Coupling and Cohesion
Software Engineering | Spiral Model | [
{
"code": null,
"e": 26103,
"s": 26075,
"text": "\n09 Mar, 2021"
},
{
"code": null,
"e": 26468,
"s": 26103,
"text": "HLookup :Horizontal Lookup function is called as HLookup function. This function used to find values horizontally across a set of rows in a table. It looks for a value horizontally across the lookup table. It returns an approximate or exact value based on the row number given in Excel. VLookup function provides the same lookup value as HLookup function provides."
},
{
"code": null,
"e": 26489,
"s": 26468,
"text": "Syntax of HLookup : "
},
{
"code": null,
"e": 26556,
"s": 26489,
"text": "HLOOKUP(lookup_value, table_array, row_index_num, [range_lookup])."
},
{
"code": null,
"e": 26845,
"s": 26556,
"text": "VLookup :Vertical Lookup function is called as VLookup function. This function is used to find values vertically across a set of rows in a table. It looks for a value vertically across the lookup table. It returns an exact or approximate value based on the column number given in Excel. "
},
{
"code": null,
"e": 26866,
"s": 26845,
"text": "Syntax of VLookup : "
},
{
"code": null,
"e": 26933,
"s": 26866,
"text": "VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup])."
},
{
"code": null,
"e": 26974,
"s": 26933,
"text": "Difference between HLookup and VLookup :"
},
{
"code": null,
"e": 26980,
"s": 26974,
"text": "S.NO."
},
{
"code": null,
"e": 26988,
"s": 26980,
"text": "HLOOKUP"
},
{
"code": null,
"e": 26996,
"s": 26988,
"text": "VLOOKUP"
},
{
"code": null,
"e": 27015,
"s": 26996,
"text": "Difference Between"
},
{
"code": null,
"e": 27036,
"s": 27015,
"text": "Software Engineering"
},
{
"code": null,
"e": 27134,
"s": 27036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27195,
"s": 27134,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27263,
"s": 27195,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 27321,
"s": 27263,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 27376,
"s": 27321,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 27442,
"s": 27376,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 27468,
"s": 27442,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 27504,
"s": 27468,
"text": "Software Engineering | COCOMO Model"
},
{
"code": null,
"e": 27546,
"s": 27504,
"text": "Functional vs Non Functional Requirements"
},
{
"code": null,
"e": 27591,
"s": 27546,
"text": "Software Engineering | Coupling and Cohesion"
}
] |
How to open a link in new tab using Selenium WebDriver? | We can open a link in the new tab with Selenium. . The methods Keys.chord and sendKeys can be used for this. The Keys.chord method allows you to pass multiple keys simultaneously.
We shall send Keys.CONTROL and Keys.ENTER as arguments to the Keys.chord method. Then the complete string is then passed as an argument to the sendKeys method. Finally, the sendKeys method has to be applied on the link which is identified by driver.findElement method.
String clicklnk = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath("//*[text()='Privacy Policy']")). sendKeys(clicklnk);
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class OpenInNwTab{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// wait of 4 seconds
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
// Keys.Chord string
String clicklnk = Keys.chord(Keys.CONTROL,Keys.ENTER);
// open the link in new tab, Keys.Chord string passed to sendKeys
driver.findElement(
By.xpath("//*[text()='Privacy Policy']")).sendKeys(clicklnk);
}
} | [
{
"code": null,
"e": 1242,
"s": 1062,
"text": "We can open a link in the new tab with Selenium. . The methods Keys.chord and sendKeys can be used for this. The Keys.chord method allows you to pass multiple keys simultaneously."
},
{
"code": null,
"e": 1511,
"s": 1242,
"text": "We shall send Keys.CONTROL and Keys.ENTER as arguments to the Keys.chord method. Then the complete string is then passed as an argument to the sendKeys method. Finally, the sendKeys method has to be applied on the link which is identified by driver.findElement method."
},
{
"code": null,
"e": 1648,
"s": 1511,
"text": "String clicklnk = Keys.chord(Keys.CONTROL,Keys.ENTER);\ndriver.findElement(By.xpath(\"//*[text()='Privacy Policy']\")). sendKeys(clicklnk);"
},
{
"code": null,
"e": 2505,
"s": 1648,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class OpenInNwTab{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // wait of 4 seconds\n driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);\n // Keys.Chord string\n String clicklnk = Keys.chord(Keys.CONTROL,Keys.ENTER);\n // open the link in new tab, Keys.Chord string passed to sendKeys\n driver.findElement(\n By.xpath(\"//*[text()='Privacy Policy']\")).sendKeys(clicklnk);\n }\n}"
}
] |
How to convert NaN to NA in an R data frame? | To convert NaN to NA in an R data frame, we can set the NaN values to NA values by using single square brackets. Firstly, we would need to access the column that contains NaN values then NaN values will be accessed using is.nan then we can set those values to NA as shown in the below examples.
Consider the below data frame −
Live Demo
x1<-sample(c(1,2,5,NaN),20,replace=TRUE)
x2<-rpois(20,2)
df1<-data.frame(x1,x2)
df1
x1 x2
1 5 1
2 1 2
3 5 3
4 NaN 2
5 5 1
6 5 2
7 NaN 1
8 5 4
9 5 2
10 2 0
11 NaN 0
12 1 0
13 NaN 4
14 1 2
15 5 1
16 1 2
17 2 2
18 5 0
19 2 1
20 5 1
Replacing NaN with NA in column x1 of df1 −
df1$x1[is.nan(df1$x1)]<-NA
df1
x1 x2
1 5 1
2 1 2
3 5 3
4 NA 2
5 5 1
6 5 2
7 NA 1
8 5 4
9 5 2
10 2 0
11 NA 0
12 1 0
13 NA 4
14 1 2
15 5 1
16 1 2
17 2 2
18 5 0
19 2 1
20 5 1
Live Demo
y1<-sample(c(rnorm(2),NaN),20,replace=TRUE)
y2<-rnorm(20)
y3<-rnorm(20)
df2<-data.frame(y1,y2,y3)
df2
y1 y2 y3
1 -0.0867355 -1.28729227 -0.20581922
2 NaN 1.11408057 0.56750161
3 NaN 0.47302790 -0.72410253
4 NaN -0.34217866 0.33855658
5 NaN -2.52516598 0.78809964
6 -0.0867355 -0.65268724 -0.04150251
7 -0.0867355 0.42845639 -0.12955272
8 -0.0867355 0.71995182 0.24011099
9 -0.0867355 0.07829339 3.10334568
10 -0.9135175 0.07250105 -0.41307585
11 -0.0867355 1.58477752 0.96751855
12 NaN -1.84389126 -0.42843257
13 -0.0867355 -0.10860452 -0.32978319
14 -0.9135175 -1.25311587 -1.07537515
15 -0.0867355 0.58514141 2.05516953
16 NaN 2.02405825 0.18098639
17 -0.9135175 0.90327161 -0.22561346
18 -0.9135175 0.81260538 -1.98065156
19 NaN -1.60608848 -1.39970818
20 NaN -0.82239927 -1.45993348
Replacing NaN with NA in column y1 of df2 −
df2$y1[is.nan(df2$y1)]<-NA
df2
y1 y2 y3
1 -0.0867355 -1.28729227 -0.20581922
2 NA 1.11408057 0.56750161
3 NA 0.47302790 -0.72410253
4 NA -0.34217866 0.33855658
5 NA -2.52516598 0.78809964
6 -0.0867355 -0.65268724 -0.04150251
7 -0.0867355 0.42845639 -0.12955272
8 -0.0867355 0.71995182 0.24011099
9 -0.0867355 0.07829339 3.10334568
10 -0.9135175 0.07250105 -0.41307585
11 -0.0867355 1.58477752 0.96751855
12 NA -1.84389126 -0.42843257
13 -0.0867355 -0.10860452 -0.32978319
14 -0.9135175 -1.25311587 -1.07537515
15 -0.0867355 0.58514141 2.05516953
16 NA 2.02405825 0.18098639
17 -0.9135175 0.90327161 -0.22561346
18 -0.9135175 0.81260538 -1.98065156
19 NA -1.60608848 -1.39970818
20 NA -0.82239927 -1.45993348 | [
{
"code": null,
"e": 1357,
"s": 1062,
"text": "To convert NaN to NA in an R data frame, we can set the NaN values to NA values by using single square brackets. Firstly, we would need to access the column that contains NaN values then NaN values will be accessed using is.nan then we can set those values to NA as shown in the below examples."
},
{
"code": null,
"e": 1389,
"s": 1357,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1400,
"s": 1389,
"text": " Live Demo"
},
{
"code": null,
"e": 1484,
"s": 1400,
"text": "x1<-sample(c(1,2,5,NaN),20,replace=TRUE)\nx2<-rpois(20,2)\ndf1<-data.frame(x1,x2)\ndf1"
},
{
"code": null,
"e": 1674,
"s": 1484,
"text": " x1 x2\n1 5 1\n2 1 2\n3 5 3\n4 NaN 2\n5 5 1\n6 5 2\n7 NaN 1\n8 5 4\n9 5 2\n10 2 0\n11 NaN 0\n12 1 0\n13 NaN 4\n14 1 2\n15 5 1\n16 1 2\n17 2 2\n18 5 0\n19 2 1\n20 5 1"
},
{
"code": null,
"e": 1718,
"s": 1674,
"text": "Replacing NaN with NA in column x1 of df1 −"
},
{
"code": null,
"e": 1749,
"s": 1718,
"text": "df1$x1[is.nan(df1$x1)]<-NA\ndf1"
},
{
"code": null,
"e": 1938,
"s": 1749,
"text": " x1 x2\n1 5 1\n2 1 2\n3 5 3\n4 NA 2\n5 5 1\n6 5 2\n7 NA 1\n8 5 4\n9 5 2\n10 2 0\n11 NA 0\n12 1 0\n13 NA 4\n14 1 2\n15 5 1\n16 1 2\n17 2 2\n18 5 0\n19 2 1\n20 5 1"
},
{
"code": null,
"e": 1949,
"s": 1938,
"text": " Live Demo"
},
{
"code": null,
"e": 2051,
"s": 1949,
"text": "y1<-sample(c(rnorm(2),NaN),20,replace=TRUE)\ny2<-rnorm(20)\ny3<-rnorm(20)\ndf2<-data.frame(y1,y2,y3)\ndf2"
},
{
"code": null,
"e": 2904,
"s": 2051,
"text": " y1 y2 y3\n1 -0.0867355 -1.28729227 -0.20581922\n2 NaN 1.11408057 0.56750161\n3 NaN 0.47302790 -0.72410253\n4 NaN -0.34217866 0.33855658\n5 NaN -2.52516598 0.78809964\n6 -0.0867355 -0.65268724 -0.04150251\n7 -0.0867355 0.42845639 -0.12955272\n8 -0.0867355 0.71995182 0.24011099\n9 -0.0867355 0.07829339 3.10334568\n10 -0.9135175 0.07250105 -0.41307585\n11 -0.0867355 1.58477752 0.96751855\n12 NaN -1.84389126 -0.42843257\n13 -0.0867355 -0.10860452 -0.32978319\n14 -0.9135175 -1.25311587 -1.07537515\n15 -0.0867355 0.58514141 2.05516953\n16 NaN 2.02405825 0.18098639\n17 -0.9135175 0.90327161 -0.22561346\n18 -0.9135175 0.81260538 -1.98065156\n19 NaN -1.60608848 -1.39970818\n20 NaN -0.82239927 -1.45993348"
},
{
"code": null,
"e": 2948,
"s": 2904,
"text": "Replacing NaN with NA in column y1 of df2 −"
},
{
"code": null,
"e": 2979,
"s": 2948,
"text": "df2$y1[is.nan(df2$y1)]<-NA\ndf2"
},
{
"code": null,
"e": 3855,
"s": 2979,
"text": " y1 y2 y3\n1 -0.0867355 -1.28729227 -0.20581922\n2 NA 1.11408057 0.56750161\n3 NA 0.47302790 -0.72410253\n4 NA -0.34217866 0.33855658\n5 NA -2.52516598 0.78809964\n6 -0.0867355 -0.65268724 -0.04150251\n7 -0.0867355 0.42845639 -0.12955272\n8 -0.0867355 0.71995182 0.24011099\n9 -0.0867355 0.07829339 3.10334568\n10 -0.9135175 0.07250105 -0.41307585\n11 -0.0867355 1.58477752 0.96751855\n12 NA -1.84389126 -0.42843257\n13 -0.0867355 -0.10860452 -0.32978319\n14 -0.9135175 -1.25311587 -1.07537515\n15 -0.0867355 0.58514141 2.05516953\n16 NA 2.02405825 0.18098639\n17 -0.9135175 0.90327161 -0.22561346\n18 -0.9135175 0.81260538 -1.98065156\n19 NA -1.60608848 -1.39970818\n20 NA -0.82239927 -1.45993348"
}
] |
How to Build a Machine Learning App in Python | by Chanin Nantasenamat | Towards Data Science | Have you ever wished for a web app that would allow you to build a machine learning model automatically by simply uploading a CSV file? In this article, you will learn how to build your very own machine learning web app in Python in a little over 100 lines of code.
The contents of this article is based on a YouTube video by the same name that I published a few months ago on my YouTube channel (Data Professor), which serves as a supplementary to this article.
Before diving further let’s take a step back to look at the big picture. Data collection, data cleaning, exploratory data analysis, model construction, and model deployment are all part of the data science life cycle. The following is a summary infographic of the life cycle:
It is critical for us as Data Scientists or Machine Learning Engineers to be able to deploy our data science projects in order to complete the data science life cycle. The deployment of machine learning models using established frameworks such as Django or Flask may be a daunting and/or time-consuming task.
At a high-level, the web app that we will be building today will essentially take in a CSV file as input data and the app will use it for the construction of a regression model using the random forest algorithm.
Now, let take a granular look at the details of what is happening at the front-end and back-end of the web app.
Users are able to upload their own dataset as CSV file and they are also able to adjust the learning parameters (in the left panel) and upon adjustment of these parameters, a new machine learning model will be built and its model performance will then be displayed (in the right panel).
Upload CSV data as inputThe CSV file should have a header as the first line (containing the column names) followed by the dataset in subsequent lines (line 2 and beyond). We can see that below the upload box in the left panel there is a link to the example CSV file (Example CSV input file). Let’s have a look at this example CSV file shown below:
Adjust learning parametersAfter uploading the CSV file, you should be able to see that a machine learning model has been built and its results are displayed in the right panel. It should be noted that the model is built using default parameters. The user can adjust learning parameters via the slider input and with each adjustment a new model will be built.
In the right panel, we can see that the first data being shown is the input dataframe in the 1. Dataset section and their results will be displayed in the 2. Model Performance section. Finally, learning parameters used in the model building is provided in the 3. Model Parameters section.
As for the model performance, performance metrics are shown for the training set and test set. As this is a regression model, the coefficient of determination (R^2)and error (either the mean squared error or mean absolute error).
Now, let’s take a high-level look under the hood of the inner workings of the app.
Upon uploading the input CSV file, the contents of the file will be converted into a Pandas dataframe and assigned to the df variable. The dataframe will then be separated into the X and y variables in order to prepare it as input for Scikit-learn. Next, these 2 variables are used for data splitting using the user specified value in the left panel (by default it is using the 80/20 split ratio). Details on the data split dimension and the column names are printed out in the right panel of the app’s front-end. A random forest model is then built using the major subset (80% subset) and the constructed model is applied to make predictions on the major (80%) and minor (20%) subsets. Model performance for this regression model is then reported into the right panel under the 2. Model Performance section.
This will be carried out using just 3 Python libraries including Streamlit, Pandas and Scikit-learn.
Streamlit is a simple to use web framework that allows you to quickly implement a data-driven app in no time.
Pandas is a data structure tool that makes it possible to handle, manipulate and transform tabular datasets.
Scikit-learn is a powerful tool that provides users the ability to build machine learning models (i.e. that can perform various learning tasks including classification, regression and clustering) as well as coming equipped with example datasets and feature engineering capabilities.
The full code of this app is shown below. The code spans 131 lines and white spaces are added along with commented lines in order to make the code readable.
Import the prerequisite libraries consisting of streamlit, pandas and the various functions from the scikit-learn library.
Lines 8–10: Comments explaining about what Lines 11–12 are doing.
Lines 11–12: The page title and its layout is set using the st.set_page_config() function. Here we can see that we are setting the page_title to 'The Machine Learning App’ while the layout is set to 'wide’ which will allow the contents of the app to fit the full width of the browser (i.e. otherwise by default the contents will be confined to a fixed width).
Lines 14–15: Comments explaining what Lines 16–65 are doing.
Line 16: Here we are defining a custom function called build_model() and the statements below from Lines 17 onwards will dictate what this function will do
Lines 17–18: The contents of the input dataframe stored in the df variable will be separated into 2 variables (X and Y). On line 17, all columns except for the last column will be assigned to the X variable while the last column will be assigned to the Y variable.
Lines 20–21: Line 20 is a comment saying what Line 21 is doing, which is to use the train_test_split() function for performing data splitting of the input data (stored in X and Y variables). By default the data will split using a ratio of 80/20 whereby the 80% subset will be assigned to X_train and Y_train while the 20% subset will be assigned to X_test and Y_test.
Lines 23–27: Line 23 prints 1.2. Data splits as a bold text using Markdown syntax (i.e. here we can see that we are using the ** symbols before and after the phrase that we want to make the text to be bold as in **1.2. Data splits**. Next, we are going to print the data dimensions of the X and Y variables where Lines 24 and 26 will print out Training set and Testing set using the st.write() function while Lines 25 and 27 will print out the data dimensions using the st.info() function by appending .shape after X_train and X_test variables as in X_train.shape and X_test.shape, respectively. Note that the st.info() function will create a colored box around the variable output.
Lines 29–33: In a similar fashion to the code block on Lines 23–27, this block will print out the X and Y variable names that are stored in X.columns and Y.name, respectively.
Lines 35–43: The RandomForestRegressor() function will be used for build a regression model. The various input arguments for building the random forest model will use the user specified value from the left-hand panel of the app’s front-end (in the back-end this corresponds to Lines 82–97).
Line 44: The model will now be trained by using therf.fit() function and as input argument we will be using X_train and Y_train.
Line 46: The heading for section 2. Model performance will be printed out using the st.subheader() function.
Lines 48–54: Line 48 prints the heading for 2.1. Training set using the st.markdown() function. Line 49 applies the trained model to make a prediction on the training set using the rd.predict() function using X_test as the input argument. Line 50 prints the text of the performance metric to be printed for the Coefficient of determination (R2). Line 51 uses the st.info() function to print the R2 score via the r2_score() function by using Y_train and Y_pred_train (representing the actual Y values and predicted Y values for the training set) as input arguments. Line 53 uses the st.write() function to print the text of the next performance metric, which is the Error. Next, Line 54 uses the st.info() function to print the mean squared error value via the mean_squared_error() function by using Y_train and Y_pred_train as input arguments.
Lines 56–59: This block of code performs exactly the same procedures but instead of the Training set it will perform it on the Test set. So instead of using the Training set data (Y_train and Y_pred_train) you would use the Test set data (Y_test and Y_pred_test).
Lines 64–65: Line 64 prints the header 3. Model Parameters by using the st.subheader() function.
The web app’s title will be printed here. Lines 68 and 75 initiates and ends the use of the st.write() function to write the page’s header in Mardown syntax. Line 69 uses the # symbol to make the text to be a Heading 1 size (according to the Markdown syntax). Lines 71 and 73 will then print a description about the web app.
Several code blocks for the left sidebar panel is described here. Line 78 comments what the next several code blocks is about which is the Left sidebar panel for collecting user specified input.
Lines 79–83 defines the CSV upload box. Line 79 prints 1. Upload your CSV data as the header via the st.sidebar.header() function. Note here that we added .sidebar in between st and header in order to specify that this header should go to the sidebar. Otherwise if it was written as st.header() then it would go to the right panel. Line 80 assigns the st.sidebar.file_uploader() function to the uploaded_file variable (i.e. this variable will now represent the user uploaded CSV file content). Lines 81–83 will print the link to the example CSV file that users can use to test out the app (here you can feel free to replace this with your own custom dataset in CSV file format).
Lines 85–87 starts by commenting that the following code blocks will pertain to parameter settings for the random forest model. Line 86 then uses the st.sidebar.header() function to print 2. Set Parameters as the header text. Finally, Line 87 creates a slider bar using the st.sidebar.slider() function where its input arguments specify Data split ratio (% for Training Set) as the text label for the slider while the 4 sets of numerical values (10, 90, 80, 5) represents the minimum value, maximum value, default value and the increment step size value. The minimum and maximum values are used to set the boundaries for the slider bar and we can see that the minimum value is 10 (shown at the far left of the slider bar) and the maximum value is 90 (shown at the far right of the slider bar). The default value of 80 will be used if the user does not adjust the slider bar. The increment step size will allow user to incrementally increase or decrease the slider value by a step size of 5 (e.g. 75, 80, 85, etc.)
Lines 89–93 defines the various slider bars for the learning parameters in 2.1. Learning Parameters in a similar fashion to what was described for Line 87. These parameters include n_estimators, max_features, min_samples_split and min_samples_leaf.
Lines 95–100 defines the various slider bars for the general parameters in 2.2. General Parameters in a similar fashion to what was described for Line 87. These parameters include random_state, criterion, bootstrap, oob_score and n_jobs.
Comments that the forthcoming blocks of code will print the model output into the main or right panel.
Applies the if-else statement to detect whether the CSV file is uploaded or not. Upon loading the web app for the first time it will default to the else statement since no CSV file is yet uploaded. Upon loading a CSV file the if statement is activated.
If the else statement (Lines 113–134) is activated, we will see a message saying Awaiting for CSV file to be uploaded along with a clickable button saying Press to use Example Dataset (which we will explain in a short moment what this button does).
If the if statement (Lines 108–112) is activated, the uploaded CSV file (whose contents are contained within the uploaded_file variable) will be assigned to the df variable (Line 109). Next, the heading 1.1. Glimpse of dataset is printed using the st.markdown() function (Line 110) followed by printing the dataframe content of the df variable (Line 111). Then, the dataframe contents in the df variable will be used as input argument to the build_model() custom function (i.e. described earlier in Lines 14–65) where the random forest model will be built and its model results will be displayed to the front-end.
Okay, so now that the web app has been coded. Let’s proceed to running the web app.
Let’s assume that you are starting from scratch, you will have to create a new conda environment (a good idea to ensure reproducibility of your code).
Firstly, create a new conda environment called ml as follows in a terminal command line:
conda create -n ml python=3.7.9
Secondly, we will login to the ml environment
conda activate ml
Firstly, download the requirements.txt file
wget https://raw.githubusercontent.com/dataprofessor/ml-auto-app/main/requirements.txt
Secondly, install the libraries as shown below
pip install -r requirements.txt
Now, download the web app files hosted on the GitHub repo of the Data Professor or use the 134 lines of code found above.
wget https://github.com/dataprofessor/ml-app/archive/main.zip
Then unzip the contents
unzip main.zip
Change into the main directory
cd main
Now that you’re in the main directory you should be able to see the ml-app.py file.
To launch the app, type the following into a terminal command line (i.e. also make sure that the ml-app.py file is in the current working directory):
streamlit run ml-app.py
In a few moments you will see the following message in the terminal prompt.
> streamlit run ml-app.pyYou can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://10.0.0.11:8501
Finally, a browser pops up and you will see the app.
Congratulations, you have now created the machine learning web app!
To make your web app public and available to the world, you can deploy it to the internet. I’ve created a YouTube video showing how you can do that on Heroku and Streamlit Sharing.
How to Deploy Data Science Web App to Heroku
How to Deploy Data Science Web App to Streamlit Sharing
I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page).
www.youtube.com
✅ YouTube: http://youtube.com/dataprofessor/✅ Website: http://dataprofessor.org/ (Under construction)✅ LinkedIn: https://www.linkedin.com/company/dataprofessor/✅ Twitter: https://twitter.com/thedataprof✅ FaceBook: http://facebook.com/dataprofessor/✅ GitHub: https://github.com/dataprofessor/✅ Instagram: https://www.instagram.com/data.professor/ | [
{
"code": null,
"e": 438,
"s": 172,
"text": "Have you ever wished for a web app that would allow you to build a machine learning model automatically by simply uploading a CSV file? In this article, you will learn how to build your very own machine learning web app in Python in a little over 100 lines of code."
},
{
"code": null,
"e": 635,
"s": 438,
"text": "The contents of this article is based on a YouTube video by the same name that I published a few months ago on my YouTube channel (Data Professor), which serves as a supplementary to this article."
},
{
"code": null,
"e": 911,
"s": 635,
"text": "Before diving further let’s take a step back to look at the big picture. Data collection, data cleaning, exploratory data analysis, model construction, and model deployment are all part of the data science life cycle. The following is a summary infographic of the life cycle:"
},
{
"code": null,
"e": 1220,
"s": 911,
"text": "It is critical for us as Data Scientists or Machine Learning Engineers to be able to deploy our data science projects in order to complete the data science life cycle. The deployment of machine learning models using established frameworks such as Django or Flask may be a daunting and/or time-consuming task."
},
{
"code": null,
"e": 1432,
"s": 1220,
"text": "At a high-level, the web app that we will be building today will essentially take in a CSV file as input data and the app will use it for the construction of a regression model using the random forest algorithm."
},
{
"code": null,
"e": 1544,
"s": 1432,
"text": "Now, let take a granular look at the details of what is happening at the front-end and back-end of the web app."
},
{
"code": null,
"e": 1831,
"s": 1544,
"text": "Users are able to upload their own dataset as CSV file and they are also able to adjust the learning parameters (in the left panel) and upon adjustment of these parameters, a new machine learning model will be built and its model performance will then be displayed (in the right panel)."
},
{
"code": null,
"e": 2179,
"s": 1831,
"text": "Upload CSV data as inputThe CSV file should have a header as the first line (containing the column names) followed by the dataset in subsequent lines (line 2 and beyond). We can see that below the upload box in the left panel there is a link to the example CSV file (Example CSV input file). Let’s have a look at this example CSV file shown below:"
},
{
"code": null,
"e": 2538,
"s": 2179,
"text": "Adjust learning parametersAfter uploading the CSV file, you should be able to see that a machine learning model has been built and its results are displayed in the right panel. It should be noted that the model is built using default parameters. The user can adjust learning parameters via the slider input and with each adjustment a new model will be built."
},
{
"code": null,
"e": 2827,
"s": 2538,
"text": "In the right panel, we can see that the first data being shown is the input dataframe in the 1. Dataset section and their results will be displayed in the 2. Model Performance section. Finally, learning parameters used in the model building is provided in the 3. Model Parameters section."
},
{
"code": null,
"e": 3057,
"s": 2827,
"text": "As for the model performance, performance metrics are shown for the training set and test set. As this is a regression model, the coefficient of determination (R^2)and error (either the mean squared error or mean absolute error)."
},
{
"code": null,
"e": 3140,
"s": 3057,
"text": "Now, let’s take a high-level look under the hood of the inner workings of the app."
},
{
"code": null,
"e": 3949,
"s": 3140,
"text": "Upon uploading the input CSV file, the contents of the file will be converted into a Pandas dataframe and assigned to the df variable. The dataframe will then be separated into the X and y variables in order to prepare it as input for Scikit-learn. Next, these 2 variables are used for data splitting using the user specified value in the left panel (by default it is using the 80/20 split ratio). Details on the data split dimension and the column names are printed out in the right panel of the app’s front-end. A random forest model is then built using the major subset (80% subset) and the constructed model is applied to make predictions on the major (80%) and minor (20%) subsets. Model performance for this regression model is then reported into the right panel under the 2. Model Performance section."
},
{
"code": null,
"e": 4050,
"s": 3949,
"text": "This will be carried out using just 3 Python libraries including Streamlit, Pandas and Scikit-learn."
},
{
"code": null,
"e": 4160,
"s": 4050,
"text": "Streamlit is a simple to use web framework that allows you to quickly implement a data-driven app in no time."
},
{
"code": null,
"e": 4269,
"s": 4160,
"text": "Pandas is a data structure tool that makes it possible to handle, manipulate and transform tabular datasets."
},
{
"code": null,
"e": 4552,
"s": 4269,
"text": "Scikit-learn is a powerful tool that provides users the ability to build machine learning models (i.e. that can perform various learning tasks including classification, regression and clustering) as well as coming equipped with example datasets and feature engineering capabilities."
},
{
"code": null,
"e": 4709,
"s": 4552,
"text": "The full code of this app is shown below. The code spans 131 lines and white spaces are added along with commented lines in order to make the code readable."
},
{
"code": null,
"e": 4832,
"s": 4709,
"text": "Import the prerequisite libraries consisting of streamlit, pandas and the various functions from the scikit-learn library."
},
{
"code": null,
"e": 4898,
"s": 4832,
"text": "Lines 8–10: Comments explaining about what Lines 11–12 are doing."
},
{
"code": null,
"e": 5258,
"s": 4898,
"text": "Lines 11–12: The page title and its layout is set using the st.set_page_config() function. Here we can see that we are setting the page_title to 'The Machine Learning App’ while the layout is set to 'wide’ which will allow the contents of the app to fit the full width of the browser (i.e. otherwise by default the contents will be confined to a fixed width)."
},
{
"code": null,
"e": 5319,
"s": 5258,
"text": "Lines 14–15: Comments explaining what Lines 16–65 are doing."
},
{
"code": null,
"e": 5475,
"s": 5319,
"text": "Line 16: Here we are defining a custom function called build_model() and the statements below from Lines 17 onwards will dictate what this function will do"
},
{
"code": null,
"e": 5740,
"s": 5475,
"text": "Lines 17–18: The contents of the input dataframe stored in the df variable will be separated into 2 variables (X and Y). On line 17, all columns except for the last column will be assigned to the X variable while the last column will be assigned to the Y variable."
},
{
"code": null,
"e": 6108,
"s": 5740,
"text": "Lines 20–21: Line 20 is a comment saying what Line 21 is doing, which is to use the train_test_split() function for performing data splitting of the input data (stored in X and Y variables). By default the data will split using a ratio of 80/20 whereby the 80% subset will be assigned to X_train and Y_train while the 20% subset will be assigned to X_test and Y_test."
},
{
"code": null,
"e": 6791,
"s": 6108,
"text": "Lines 23–27: Line 23 prints 1.2. Data splits as a bold text using Markdown syntax (i.e. here we can see that we are using the ** symbols before and after the phrase that we want to make the text to be bold as in **1.2. Data splits**. Next, we are going to print the data dimensions of the X and Y variables where Lines 24 and 26 will print out Training set and Testing set using the st.write() function while Lines 25 and 27 will print out the data dimensions using the st.info() function by appending .shape after X_train and X_test variables as in X_train.shape and X_test.shape, respectively. Note that the st.info() function will create a colored box around the variable output."
},
{
"code": null,
"e": 6967,
"s": 6791,
"text": "Lines 29–33: In a similar fashion to the code block on Lines 23–27, this block will print out the X and Y variable names that are stored in X.columns and Y.name, respectively."
},
{
"code": null,
"e": 7258,
"s": 6967,
"text": "Lines 35–43: The RandomForestRegressor() function will be used for build a regression model. The various input arguments for building the random forest model will use the user specified value from the left-hand panel of the app’s front-end (in the back-end this corresponds to Lines 82–97)."
},
{
"code": null,
"e": 7387,
"s": 7258,
"text": "Line 44: The model will now be trained by using therf.fit() function and as input argument we will be using X_train and Y_train."
},
{
"code": null,
"e": 7496,
"s": 7387,
"text": "Line 46: The heading for section 2. Model performance will be printed out using the st.subheader() function."
},
{
"code": null,
"e": 8340,
"s": 7496,
"text": "Lines 48–54: Line 48 prints the heading for 2.1. Training set using the st.markdown() function. Line 49 applies the trained model to make a prediction on the training set using the rd.predict() function using X_test as the input argument. Line 50 prints the text of the performance metric to be printed for the Coefficient of determination (R2). Line 51 uses the st.info() function to print the R2 score via the r2_score() function by using Y_train and Y_pred_train (representing the actual Y values and predicted Y values for the training set) as input arguments. Line 53 uses the st.write() function to print the text of the next performance metric, which is the Error. Next, Line 54 uses the st.info() function to print the mean squared error value via the mean_squared_error() function by using Y_train and Y_pred_train as input arguments."
},
{
"code": null,
"e": 8604,
"s": 8340,
"text": "Lines 56–59: This block of code performs exactly the same procedures but instead of the Training set it will perform it on the Test set. So instead of using the Training set data (Y_train and Y_pred_train) you would use the Test set data (Y_test and Y_pred_test)."
},
{
"code": null,
"e": 8701,
"s": 8604,
"text": "Lines 64–65: Line 64 prints the header 3. Model Parameters by using the st.subheader() function."
},
{
"code": null,
"e": 9026,
"s": 8701,
"text": "The web app’s title will be printed here. Lines 68 and 75 initiates and ends the use of the st.write() function to write the page’s header in Mardown syntax. Line 69 uses the # symbol to make the text to be a Heading 1 size (according to the Markdown syntax). Lines 71 and 73 will then print a description about the web app."
},
{
"code": null,
"e": 9221,
"s": 9026,
"text": "Several code blocks for the left sidebar panel is described here. Line 78 comments what the next several code blocks is about which is the Left sidebar panel for collecting user specified input."
},
{
"code": null,
"e": 9900,
"s": 9221,
"text": "Lines 79–83 defines the CSV upload box. Line 79 prints 1. Upload your CSV data as the header via the st.sidebar.header() function. Note here that we added .sidebar in between st and header in order to specify that this header should go to the sidebar. Otherwise if it was written as st.header() then it would go to the right panel. Line 80 assigns the st.sidebar.file_uploader() function to the uploaded_file variable (i.e. this variable will now represent the user uploaded CSV file content). Lines 81–83 will print the link to the example CSV file that users can use to test out the app (here you can feel free to replace this with your own custom dataset in CSV file format)."
},
{
"code": null,
"e": 10914,
"s": 9900,
"text": "Lines 85–87 starts by commenting that the following code blocks will pertain to parameter settings for the random forest model. Line 86 then uses the st.sidebar.header() function to print 2. Set Parameters as the header text. Finally, Line 87 creates a slider bar using the st.sidebar.slider() function where its input arguments specify Data split ratio (% for Training Set) as the text label for the slider while the 4 sets of numerical values (10, 90, 80, 5) represents the minimum value, maximum value, default value and the increment step size value. The minimum and maximum values are used to set the boundaries for the slider bar and we can see that the minimum value is 10 (shown at the far left of the slider bar) and the maximum value is 90 (shown at the far right of the slider bar). The default value of 80 will be used if the user does not adjust the slider bar. The increment step size will allow user to incrementally increase or decrease the slider value by a step size of 5 (e.g. 75, 80, 85, etc.)"
},
{
"code": null,
"e": 11163,
"s": 10914,
"text": "Lines 89–93 defines the various slider bars for the learning parameters in 2.1. Learning Parameters in a similar fashion to what was described for Line 87. These parameters include n_estimators, max_features, min_samples_split and min_samples_leaf."
},
{
"code": null,
"e": 11401,
"s": 11163,
"text": "Lines 95–100 defines the various slider bars for the general parameters in 2.2. General Parameters in a similar fashion to what was described for Line 87. These parameters include random_state, criterion, bootstrap, oob_score and n_jobs."
},
{
"code": null,
"e": 11504,
"s": 11401,
"text": "Comments that the forthcoming blocks of code will print the model output into the main or right panel."
},
{
"code": null,
"e": 11757,
"s": 11504,
"text": "Applies the if-else statement to detect whether the CSV file is uploaded or not. Upon loading the web app for the first time it will default to the else statement since no CSV file is yet uploaded. Upon loading a CSV file the if statement is activated."
},
{
"code": null,
"e": 12006,
"s": 11757,
"text": "If the else statement (Lines 113–134) is activated, we will see a message saying Awaiting for CSV file to be uploaded along with a clickable button saying Press to use Example Dataset (which we will explain in a short moment what this button does)."
},
{
"code": null,
"e": 12620,
"s": 12006,
"text": "If the if statement (Lines 108–112) is activated, the uploaded CSV file (whose contents are contained within the uploaded_file variable) will be assigned to the df variable (Line 109). Next, the heading 1.1. Glimpse of dataset is printed using the st.markdown() function (Line 110) followed by printing the dataframe content of the df variable (Line 111). Then, the dataframe contents in the df variable will be used as input argument to the build_model() custom function (i.e. described earlier in Lines 14–65) where the random forest model will be built and its model results will be displayed to the front-end."
},
{
"code": null,
"e": 12704,
"s": 12620,
"text": "Okay, so now that the web app has been coded. Let’s proceed to running the web app."
},
{
"code": null,
"e": 12855,
"s": 12704,
"text": "Let’s assume that you are starting from scratch, you will have to create a new conda environment (a good idea to ensure reproducibility of your code)."
},
{
"code": null,
"e": 12944,
"s": 12855,
"text": "Firstly, create a new conda environment called ml as follows in a terminal command line:"
},
{
"code": null,
"e": 12976,
"s": 12944,
"text": "conda create -n ml python=3.7.9"
},
{
"code": null,
"e": 13022,
"s": 12976,
"text": "Secondly, we will login to the ml environment"
},
{
"code": null,
"e": 13040,
"s": 13022,
"text": "conda activate ml"
},
{
"code": null,
"e": 13084,
"s": 13040,
"text": "Firstly, download the requirements.txt file"
},
{
"code": null,
"e": 13171,
"s": 13084,
"text": "wget https://raw.githubusercontent.com/dataprofessor/ml-auto-app/main/requirements.txt"
},
{
"code": null,
"e": 13218,
"s": 13171,
"text": "Secondly, install the libraries as shown below"
},
{
"code": null,
"e": 13250,
"s": 13218,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 13372,
"s": 13250,
"text": "Now, download the web app files hosted on the GitHub repo of the Data Professor or use the 134 lines of code found above."
},
{
"code": null,
"e": 13434,
"s": 13372,
"text": "wget https://github.com/dataprofessor/ml-app/archive/main.zip"
},
{
"code": null,
"e": 13458,
"s": 13434,
"text": "Then unzip the contents"
},
{
"code": null,
"e": 13473,
"s": 13458,
"text": "unzip main.zip"
},
{
"code": null,
"e": 13504,
"s": 13473,
"text": "Change into the main directory"
},
{
"code": null,
"e": 13512,
"s": 13504,
"text": "cd main"
},
{
"code": null,
"e": 13596,
"s": 13512,
"text": "Now that you’re in the main directory you should be able to see the ml-app.py file."
},
{
"code": null,
"e": 13746,
"s": 13596,
"text": "To launch the app, type the following into a terminal command line (i.e. also make sure that the ml-app.py file is in the current working directory):"
},
{
"code": null,
"e": 13770,
"s": 13746,
"text": "streamlit run ml-app.py"
},
{
"code": null,
"e": 13846,
"s": 13770,
"text": "In a few moments you will see the following message in the terminal prompt."
},
{
"code": null,
"e": 13990,
"s": 13846,
"text": "> streamlit run ml-app.pyYou can now view your Streamlit app in your browser.Local URL: http://localhost:8501Network URL: http://10.0.0.11:8501"
},
{
"code": null,
"e": 14043,
"s": 13990,
"text": "Finally, a browser pops up and you will see the app."
},
{
"code": null,
"e": 14111,
"s": 14043,
"text": "Congratulations, you have now created the machine learning web app!"
},
{
"code": null,
"e": 14292,
"s": 14111,
"text": "To make your web app public and available to the world, you can deploy it to the internet. I’ve created a YouTube video showing how you can do that on Heroku and Streamlit Sharing."
},
{
"code": null,
"e": 14337,
"s": 14292,
"text": "How to Deploy Data Science Web App to Heroku"
},
{
"code": null,
"e": 14393,
"s": 14337,
"text": "How to Deploy Data Science Web App to Streamlit Sharing"
},
{
"code": null,
"e": 14755,
"s": 14393,
"text": "I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page)."
},
{
"code": null,
"e": 14771,
"s": 14755,
"text": "www.youtube.com"
}
] |
Adding a Character as Thousands Separator to Given Number in Java - GeeksforGeeks | 04 Nov, 2020
Given an integer n and character ch, return a String using the character as thousands separator on the given number.
Examples:
Input: n=1234 , ch =’.’
Output: 1.234
In the above-given input, “.” character is used as the thousands separator and is placed between hundreds and thousands of places starting from the right. The obtained output is returned as String Format.
Input: n=123456789 , ch =’.’
Output: 123.456.789
Approach:
Convert number into a string.Start string traversal from the right side.Add the separator character after every three digits
Convert number into a string.
Start string traversal from the right side.
Add the separator character after every three digits
Below is the code using the same approach using Java.
Java
// Java Program for Adding a character as thousands separator// to the given number and returning in string format class GFG { static String thousandSeparator(int n, String ch) { // Counting number of digits int l = (int)Math.floor(Math.log10(n)) + 1; StringBuffer str = new StringBuffer(""); int count = 0; int r = 0; // Checking if number of digits is greater than 3 if (l > 3) { for (int i = l - 1; i >= 0; i--) { r = n % 10; n = n / 10; count++; if (((count % 3) == 0) && (i != 0)) { // Parsing String value of Integer str.append(String.valueOf(r)); // Appending the separator str.append(ch); } else str.append(String.valueOf(r)); } str.reverse(); } // If digits less than equal to 3, directly print n else str.append(String.valueOf(n)); return str.toString(); } // Driver code public static void main(String[] args) { int n = 123456789; String ch = "."; System.out.println(thousandSeparator(n, ch)); }}
123.456.789
Time Complexity: O(n)
Java-String-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Generics in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23974,
"s": 23946,
"text": "\n04 Nov, 2020"
},
{
"code": null,
"e": 24091,
"s": 23974,
"text": "Given an integer n and character ch, return a String using the character as thousands separator on the given number."
},
{
"code": null,
"e": 24101,
"s": 24091,
"text": "Examples:"
},
{
"code": null,
"e": 24125,
"s": 24101,
"text": "Input: n=1234 , ch =’.’"
},
{
"code": null,
"e": 24140,
"s": 24125,
"text": "Output: 1.234 "
},
{
"code": null,
"e": 24345,
"s": 24140,
"text": "In the above-given input, “.” character is used as the thousands separator and is placed between hundreds and thousands of places starting from the right. The obtained output is returned as String Format."
},
{
"code": null,
"e": 24374,
"s": 24345,
"text": "Input: n=123456789 , ch =’.’"
},
{
"code": null,
"e": 24394,
"s": 24374,
"text": "Output: 123.456.789"
},
{
"code": null,
"e": 24405,
"s": 24394,
"text": "Approach: "
},
{
"code": null,
"e": 24530,
"s": 24405,
"text": "Convert number into a string.Start string traversal from the right side.Add the separator character after every three digits"
},
{
"code": null,
"e": 24560,
"s": 24530,
"text": "Convert number into a string."
},
{
"code": null,
"e": 24604,
"s": 24560,
"text": "Start string traversal from the right side."
},
{
"code": null,
"e": 24657,
"s": 24604,
"text": "Add the separator character after every three digits"
},
{
"code": null,
"e": 24712,
"s": 24657,
"text": "Below is the code using the same approach using Java. "
},
{
"code": null,
"e": 24717,
"s": 24712,
"text": "Java"
},
{
"code": "// Java Program for Adding a character as thousands separator// to the given number and returning in string format class GFG { static String thousandSeparator(int n, String ch) { // Counting number of digits int l = (int)Math.floor(Math.log10(n)) + 1; StringBuffer str = new StringBuffer(\"\"); int count = 0; int r = 0; // Checking if number of digits is greater than 3 if (l > 3) { for (int i = l - 1; i >= 0; i--) { r = n % 10; n = n / 10; count++; if (((count % 3) == 0) && (i != 0)) { // Parsing String value of Integer str.append(String.valueOf(r)); // Appending the separator str.append(ch); } else str.append(String.valueOf(r)); } str.reverse(); } // If digits less than equal to 3, directly print n else str.append(String.valueOf(n)); return str.toString(); } // Driver code public static void main(String[] args) { int n = 123456789; String ch = \".\"; System.out.println(thousandSeparator(n, ch)); }}",
"e": 25996,
"s": 24717,
"text": null
},
{
"code": null,
"e": 26010,
"s": 25996,
"text": "123.456.789\n\n"
},
{
"code": null,
"e": 26032,
"s": 26010,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 26053,
"s": 26032,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 26058,
"s": 26053,
"text": "Java"
},
{
"code": null,
"e": 26072,
"s": 26058,
"text": "Java Programs"
},
{
"code": null,
"e": 26077,
"s": 26072,
"text": "Java"
},
{
"code": null,
"e": 26175,
"s": 26077,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26190,
"s": 26175,
"text": "Stream In Java"
},
{
"code": null,
"e": 26236,
"s": 26190,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 26257,
"s": 26236,
"text": "Constructors in Java"
},
{
"code": null,
"e": 26276,
"s": 26257,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 26293,
"s": 26276,
"text": "Generics in Java"
},
{
"code": null,
"e": 26337,
"s": 26293,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 26363,
"s": 26337,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 26397,
"s": 26363,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 26444,
"s": 26397,
"text": "Implementing a Linked List in Java using Class"
}
] |
How B+Tree Indexes Are Built In A Database? | by Christopher Tao | Towards Data Science | If you are not a DBA or a Database Developer, you may not know the mechanisms of the database index. But as long as you can write some SQL queries, you must have been heard of database indexes and know that indexes can improve the performance of the SQL queries.
In one of my previous articles, I have introduced the B+Tree index which is still used by most of the database management systems (DBMS). It can improve the SQL query performance on most types of conditions.
towardsdatascience.com
There is a diagram that I used as an example, which is shown as follows.
Are you curious why the B+Tree looks like this? Specifically, why the top-level has its only node with the number 5? Why the leaf-node 7 is alone? In this article, I’ll introduce how the B+Tree index is built from scratch.
Let’s start from an empty table, and ignore what other columns it has, just focusing on the key column having the B+Tree index created on.
Now, suppose we started to use this table. So, a series of entries will be inserted into the table. Because there is a B+Tree index on the key column, the index will need to be built as the data rows are inserted one by one.
Although usually the key field might be inserted in order, of course, that’s not always the case. To demonstrate the mechanism in a general case, let’s assume the keys are inserted randomly. For example, the order is as follows:
5, 7, 8, 1, 4, 6, 2, 3, 9
It needs to be emphasised that, there is not only one way to build a B+Tree index. Therefore, we need to have some assumptions in our example. Don’t worry, the mechanism of all B+Tree indexes is the same.
Assumption 1: Each block of the hard disk drive can be stored with two keys
Of course, in practice, this number is impossibly small. But it will make our example much easier to be understood.
OK. Now, we can insert the first two numbers into the index.
Because of Assumption 1, we don’t need to worry about anything when we insert two values. The values have to be sorted, so 5 is on the left whereas 7 is on the right. Please note that the node is a leaf node because we don’t need any non-leaf node at the moment as there are only two values that can be stored in one leaf node.
When we insert a new number “8”, we firstly assume that we need to insert it into the existing leaf node. However, it will end up with a node with three values “5, 7, 8”. Based on Assumption 1, we need to split the node because the block can only store two values.
Assumption 2: When a node is split, the right value of the left node goes to the higher level
We need to make Assumption 2 to define which value goes to the higher level whenever a node is split. Please note that it is also possible to have the assumption such as the left value of the right node goes up, and we just need to define that and follow.
Therefore, the last value “8” which cannot be stored in this block is split and become a new leaf node. After that, the left node is “5” and “7”, and the rightmost value is “7”, so it will go to the higher level.
Now, we have a non-leaf node. This new node needs to be created with two pointers on both of its left and right. The left pointer points to the node having values smaller, whereas the right pointer points to the larger.
Next, when we insert the number “1”, the leaf node “5, 7” becomes “1, 5, 7” which cause another split. The last value “7” will be separated and become a new leaf node. Please note that the number “7” will not be merged into the other node with the number “8”, this is because B+Tree doesn’t have this feature, as well as this will cause extra overhead to build the index. It is not necessary.
After that, based on Assumption 2, the rightmost value of the left node is the number “5”. It made its way to a higher level. There is already a node with the number “7”, so the number five will be simply inserted on the left of “7”. Don’t forget to make the pointer points to the node less or equal to “5”.
The next value is “4”. It caused a split again, so the number 4 went to the next level based on Assumption 2. However, the first-level non-leaf node “5, 7” has already got two values. Based on Assumption 1, it needs to be split.
It does no doubt that the number “5” should go up to the second-level non-leaf node based on Assumption 1. However, it is very important to know that the number 5 will not exist in the first-level non-leaf node anymore. This is one of the mechanisms of B+Tree, there should not be any duplicated values in non-leaf nodes.
Inserting the number “6” is relatively easy. Because the leaf node “5” still has a space, the number “6” will be inserted in this node without any other effects.
When the number “2” is inserted, the leaf node “1, 2, 4” needs to be split. Based on Assumption 2, the number “2” needs to be lifted. As the non-leaf node “4” still has space, so the number “2” end up there without further effects.
The last two numbers “3” and “9” can find their spots on the leaf nodes. Therefore, no more split is required.
So, all the 9 numbers are inserted into the B+Tree index with this random order.
In this article, I have used graphs to illustrate how a B+Tree is built from scratch. It turns out the assumptions can be different between the implementations of B+Tree indexes. However, the mechanisms are the same.
As the most classic type of index, B+Tree has been utilised for dozens of years and are still using by most of the DBMS. Although it might not be the most advanced index anymore, I believe it is still iconic and a DBA, Data Analyst and Software Developer should know.
medium.com
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above) | [
{
"code": null,
"e": 435,
"s": 172,
"text": "If you are not a DBA or a Database Developer, you may not know the mechanisms of the database index. But as long as you can write some SQL queries, you must have been heard of database indexes and know that indexes can improve the performance of the SQL queries."
},
{
"code": null,
"e": 643,
"s": 435,
"text": "In one of my previous articles, I have introduced the B+Tree index which is still used by most of the database management systems (DBMS). It can improve the SQL query performance on most types of conditions."
},
{
"code": null,
"e": 666,
"s": 643,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 739,
"s": 666,
"text": "There is a diagram that I used as an example, which is shown as follows."
},
{
"code": null,
"e": 962,
"s": 739,
"text": "Are you curious why the B+Tree looks like this? Specifically, why the top-level has its only node with the number 5? Why the leaf-node 7 is alone? In this article, I’ll introduce how the B+Tree index is built from scratch."
},
{
"code": null,
"e": 1101,
"s": 962,
"text": "Let’s start from an empty table, and ignore what other columns it has, just focusing on the key column having the B+Tree index created on."
},
{
"code": null,
"e": 1326,
"s": 1101,
"text": "Now, suppose we started to use this table. So, a series of entries will be inserted into the table. Because there is a B+Tree index on the key column, the index will need to be built as the data rows are inserted one by one."
},
{
"code": null,
"e": 1555,
"s": 1326,
"text": "Although usually the key field might be inserted in order, of course, that’s not always the case. To demonstrate the mechanism in a general case, let’s assume the keys are inserted randomly. For example, the order is as follows:"
},
{
"code": null,
"e": 1581,
"s": 1555,
"text": "5, 7, 8, 1, 4, 6, 2, 3, 9"
},
{
"code": null,
"e": 1786,
"s": 1581,
"text": "It needs to be emphasised that, there is not only one way to build a B+Tree index. Therefore, we need to have some assumptions in our example. Don’t worry, the mechanism of all B+Tree indexes is the same."
},
{
"code": null,
"e": 1862,
"s": 1786,
"text": "Assumption 1: Each block of the hard disk drive can be stored with two keys"
},
{
"code": null,
"e": 1978,
"s": 1862,
"text": "Of course, in practice, this number is impossibly small. But it will make our example much easier to be understood."
},
{
"code": null,
"e": 2039,
"s": 1978,
"text": "OK. Now, we can insert the first two numbers into the index."
},
{
"code": null,
"e": 2367,
"s": 2039,
"text": "Because of Assumption 1, we don’t need to worry about anything when we insert two values. The values have to be sorted, so 5 is on the left whereas 7 is on the right. Please note that the node is a leaf node because we don’t need any non-leaf node at the moment as there are only two values that can be stored in one leaf node."
},
{
"code": null,
"e": 2632,
"s": 2367,
"text": "When we insert a new number “8”, we firstly assume that we need to insert it into the existing leaf node. However, it will end up with a node with three values “5, 7, 8”. Based on Assumption 1, we need to split the node because the block can only store two values."
},
{
"code": null,
"e": 2726,
"s": 2632,
"text": "Assumption 2: When a node is split, the right value of the left node goes to the higher level"
},
{
"code": null,
"e": 2982,
"s": 2726,
"text": "We need to make Assumption 2 to define which value goes to the higher level whenever a node is split. Please note that it is also possible to have the assumption such as the left value of the right node goes up, and we just need to define that and follow."
},
{
"code": null,
"e": 3195,
"s": 2982,
"text": "Therefore, the last value “8” which cannot be stored in this block is split and become a new leaf node. After that, the left node is “5” and “7”, and the rightmost value is “7”, so it will go to the higher level."
},
{
"code": null,
"e": 3415,
"s": 3195,
"text": "Now, we have a non-leaf node. This new node needs to be created with two pointers on both of its left and right. The left pointer points to the node having values smaller, whereas the right pointer points to the larger."
},
{
"code": null,
"e": 3808,
"s": 3415,
"text": "Next, when we insert the number “1”, the leaf node “5, 7” becomes “1, 5, 7” which cause another split. The last value “7” will be separated and become a new leaf node. Please note that the number “7” will not be merged into the other node with the number “8”, this is because B+Tree doesn’t have this feature, as well as this will cause extra overhead to build the index. It is not necessary."
},
{
"code": null,
"e": 4116,
"s": 3808,
"text": "After that, based on Assumption 2, the rightmost value of the left node is the number “5”. It made its way to a higher level. There is already a node with the number “7”, so the number five will be simply inserted on the left of “7”. Don’t forget to make the pointer points to the node less or equal to “5”."
},
{
"code": null,
"e": 4345,
"s": 4116,
"text": "The next value is “4”. It caused a split again, so the number 4 went to the next level based on Assumption 2. However, the first-level non-leaf node “5, 7” has already got two values. Based on Assumption 1, it needs to be split."
},
{
"code": null,
"e": 4667,
"s": 4345,
"text": "It does no doubt that the number “5” should go up to the second-level non-leaf node based on Assumption 1. However, it is very important to know that the number 5 will not exist in the first-level non-leaf node anymore. This is one of the mechanisms of B+Tree, there should not be any duplicated values in non-leaf nodes."
},
{
"code": null,
"e": 4829,
"s": 4667,
"text": "Inserting the number “6” is relatively easy. Because the leaf node “5” still has a space, the number “6” will be inserted in this node without any other effects."
},
{
"code": null,
"e": 5061,
"s": 4829,
"text": "When the number “2” is inserted, the leaf node “1, 2, 4” needs to be split. Based on Assumption 2, the number “2” needs to be lifted. As the non-leaf node “4” still has space, so the number “2” end up there without further effects."
},
{
"code": null,
"e": 5172,
"s": 5061,
"text": "The last two numbers “3” and “9” can find their spots on the leaf nodes. Therefore, no more split is required."
},
{
"code": null,
"e": 5253,
"s": 5172,
"text": "So, all the 9 numbers are inserted into the B+Tree index with this random order."
},
{
"code": null,
"e": 5470,
"s": 5253,
"text": "In this article, I have used graphs to illustrate how a B+Tree is built from scratch. It turns out the assumptions can be different between the implementations of B+Tree indexes. However, the mechanisms are the same."
},
{
"code": null,
"e": 5738,
"s": 5470,
"text": "As the most classic type of index, B+Tree has been utilised for dozens of years and are still using by most of the DBMS. Although it might not be the most advanced index anymore, I believe it is still iconic and a DBA, Data Analyst and Software Developer should know."
},
{
"code": null,
"e": 5749,
"s": 5738,
"text": "medium.com"
}
] |
Kruskal's algorithm in Javascript | Kruskal's algorithm is a greedy algorithm that works as follows −
1. It Creates a set of all edges in the graph.
2. While the above set is not empty and not all vertices are covered,
It removes the minimum weight edge from this set
It checks if this edge is forming a cycle or just connecting 2 trees. If it forms a cycle, we discard this edge, else we add it to our tree.
3. When the above processing is complete, we have a minimum spanning tree.
In order to implement this algorithm, we need 2 more data structures.
First, we need a priority queue that we can use to keep the edges in a sorted order and get our required edge on each iteration.
Next, we need a disjoint set data structure. A disjoint-set data structure (also called a union-find data structure or merge–find set) is a data structure that tracks a set of elements partitioned into a number of disjoint (non-overlapping) subsets. Whenever we add a new node to a tree, we will check if they are already connected. If yes, then we have a cycle. If no, we will make a union of both vertices of the edge. This will add them to the same subset.
Let us look at the implementation of UnionFind or DisjointSet data structure &minsu;
class UnionFind {
constructor(elements) {
// Number of disconnected components
this.count = elements.length;
// Keep Track of connected components
this.parent = {};
// Initialize the data structure such that all
// elements have themselves as parents
elements.forEach(e => (this.parent[e] = e));
}
union(a, b) {
let rootA = this.find(a);
let rootB = this.find(b);
// Roots are same so these are already connected.
if (rootA === rootB) return;
// Always make the element with smaller root the parent.
if (rootA < rootB) {
if (this.parent[b] != b) this.union(this.parent[b], a);
this.parent[b] = this.parent[a];
} else {
if (this.parent[a] != a) this.union(this.parent[a], b);
this.parent[a] = this.parent[b];
}
}
// Returns final parent of a node
find(a) {
while (this.parent[a] !== a) {
a = this.parent[a];
}
return a;
}
// Checks connectivity of the 2 nodes
connected(a, b) {
return this.find(a) === this.find(b);
}
}
You can test this using −
let uf = new UnionFind(["A", "B", "C", "D", "E"]);
uf.union("A", "B"); uf.union("A", "C");
uf.union("C", "D");
console.log(uf.connected("B", "E"));
console.log(uf.connected("B", "D"));
This will give the output −
false
true
Now let us look at the implementation of Kruskal's algorithm using this data structure −
kruskalsMST() {
// Initialize graph that'll contain the MST
const MST = new Graph();
this.nodes.forEach(node => MST.addNode(node));
if (this.nodes.length === 0) {
return MST;
}
// Create a Priority Queue
edgeQueue = new PriorityQueue(this.nodes.length * this.nodes.length);
// Add all edges to the Queue:
for (let node in this.edges) {
this.edges[node].forEach(edge => {
edgeQueue.enqueue([node, edge.node], edge.weight);
});
}
let uf = new UnionFind(this.nodes);
// Loop until either we explore all nodes or queue is empty
while (!edgeQueue.isEmpty()) {
// Get the edge data using destructuring
let nextEdge = edgeQueue.dequeue();
let nodes = nextEdge.data;
let weight = nextEdge.priority;
if (!uf.connected(nodes[0], nodes[1])) {
MST.addEdge(nodes[0], nodes[1], weight);
uf.union(nodes[0], nodes[1]);
}
}
return MST;
}
You can test this using −
let g = new Graph();
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addNode("E");
g.addNode("F");
g.addNode("G");
g.addEdge("A", "C", 100);
g.addEdge("A", "B", 3);
g.addEdge("A", "D", 4);
g.addEdge("C", "D", 3);
g.addEdge("D", "E", 8);
g.addEdge("E", "F", 10);
g.addEdge("B", "G", 9);
g.addEdge("E", "G", 50);
g.kruskalsMST().display();
This will give the output −
A->B, D
B->A, G
C->D
D->C, A, E
E->D, F
F->E
G->B | [
{
"code": null,
"e": 1128,
"s": 1062,
"text": "Kruskal's algorithm is a greedy algorithm that works as follows −"
},
{
"code": null,
"e": 1175,
"s": 1128,
"text": "1. It Creates a set of all edges in the graph."
},
{
"code": null,
"e": 1245,
"s": 1175,
"text": "2. While the above set is not empty and not all vertices are covered,"
},
{
"code": null,
"e": 1294,
"s": 1245,
"text": "It removes the minimum weight edge from this set"
},
{
"code": null,
"e": 1435,
"s": 1294,
"text": "It checks if this edge is forming a cycle or just connecting 2 trees. If it forms a cycle, we discard this edge, else we add it to our tree."
},
{
"code": null,
"e": 1510,
"s": 1435,
"text": "3. When the above processing is complete, we have a minimum spanning tree."
},
{
"code": null,
"e": 1580,
"s": 1510,
"text": "In order to implement this algorithm, we need 2 more data structures."
},
{
"code": null,
"e": 1709,
"s": 1580,
"text": "First, we need a priority queue that we can use to keep the edges in a sorted order and get our required edge on each iteration."
},
{
"code": null,
"e": 2169,
"s": 1709,
"text": "Next, we need a disjoint set data structure. A disjoint-set data structure (also called a union-find data structure or merge–find set) is a data structure that tracks a set of elements partitioned into a number of disjoint (non-overlapping) subsets. Whenever we add a new node to a tree, we will check if they are already connected. If yes, then we have a cycle. If no, we will make a union of both vertices of the edge. This will add them to the same subset."
},
{
"code": null,
"e": 2254,
"s": 2169,
"text": "Let us look at the implementation of UnionFind or DisjointSet data structure &minsu;"
},
{
"code": null,
"e": 3369,
"s": 2254,
"text": "class UnionFind {\n constructor(elements) {\n // Number of disconnected components\n this.count = elements.length;\n\n // Keep Track of connected components\n this.parent = {};\n\n // Initialize the data structure such that all\n // elements have themselves as parents\n elements.forEach(e => (this.parent[e] = e));\n }\n\n union(a, b) {\n let rootA = this.find(a);\n let rootB = this.find(b);\n\n // Roots are same so these are already connected.\n if (rootA === rootB) return;\n\n // Always make the element with smaller root the parent.\n if (rootA < rootB) {\n if (this.parent[b] != b) this.union(this.parent[b], a);\n this.parent[b] = this.parent[a];\n } else {\n if (this.parent[a] != a) this.union(this.parent[a], b);\n this.parent[a] = this.parent[b];\n }\n }\n\n // Returns final parent of a node\n find(a) {\n while (this.parent[a] !== a) {\n a = this.parent[a];\n }\n return a;\n }\n\n // Checks connectivity of the 2 nodes\n connected(a, b) {\n return this.find(a) === this.find(b);\n }\n}"
},
{
"code": null,
"e": 3395,
"s": 3369,
"text": "You can test this using −"
},
{
"code": null,
"e": 3581,
"s": 3395,
"text": "let uf = new UnionFind([\"A\", \"B\", \"C\", \"D\", \"E\"]);\nuf.union(\"A\", \"B\"); uf.union(\"A\", \"C\");\nuf.union(\"C\", \"D\");\n\nconsole.log(uf.connected(\"B\", \"E\"));\nconsole.log(uf.connected(\"B\", \"D\"));"
},
{
"code": null,
"e": 3609,
"s": 3581,
"text": "This will give the output −"
},
{
"code": null,
"e": 3620,
"s": 3609,
"text": "false\ntrue"
},
{
"code": null,
"e": 3709,
"s": 3620,
"text": "Now let us look at the implementation of Kruskal's algorithm using this data structure −"
},
{
"code": null,
"e": 4661,
"s": 3709,
"text": "kruskalsMST() {\n // Initialize graph that'll contain the MST\n const MST = new Graph();\n this.nodes.forEach(node => MST.addNode(node));\n if (this.nodes.length === 0) {\n return MST;\n }\n\n // Create a Priority Queue\n edgeQueue = new PriorityQueue(this.nodes.length * this.nodes.length);\n\n // Add all edges to the Queue:\n for (let node in this.edges) {\n this.edges[node].forEach(edge => {\n edgeQueue.enqueue([node, edge.node], edge.weight);\n });\n }\n\n let uf = new UnionFind(this.nodes);\n\n // Loop until either we explore all nodes or queue is empty\n while (!edgeQueue.isEmpty()) {\n // Get the edge data using destructuring\n let nextEdge = edgeQueue.dequeue();\n let nodes = nextEdge.data;\n let weight = nextEdge.priority;\n\n if (!uf.connected(nodes[0], nodes[1])) {\n MST.addEdge(nodes[0], nodes[1], weight);\n uf.union(nodes[0], nodes[1]);\n }\n }\n return MST;\n}"
},
{
"code": null,
"e": 4687,
"s": 4661,
"text": "You can test this using −"
},
{
"code": null,
"e": 5045,
"s": 4687,
"text": "let g = new Graph();\ng.addNode(\"A\");\ng.addNode(\"B\");\ng.addNode(\"C\");\ng.addNode(\"D\");\ng.addNode(\"E\");\ng.addNode(\"F\");\ng.addNode(\"G\");\n\ng.addEdge(\"A\", \"C\", 100);\ng.addEdge(\"A\", \"B\", 3);\ng.addEdge(\"A\", \"D\", 4);\ng.addEdge(\"C\", \"D\", 3);\ng.addEdge(\"D\", \"E\", 8);\ng.addEdge(\"E\", \"F\", 10);\ng.addEdge(\"B\", \"G\", 9);\ng.addEdge(\"E\", \"G\", 50);\n\ng.kruskalsMST().display();"
},
{
"code": null,
"e": 5073,
"s": 5045,
"text": "This will give the output −"
},
{
"code": null,
"e": 5123,
"s": 5073,
"text": "A->B, D\nB->A, G\nC->D\nD->C, A, E\nE->D, F\nF->E\nG->B"
}
] |
LinkedList in Arduino | The LinkedList library by Ivan Seidel helps implement this data structure in Arduino. A linked list contains a set of nodes wherein each node contains some data, and a link (reference) to the next node in the list.
To install this library, go to Library Manager, and search for LinkedList.
Once installed, go to: File→ Examples→LinkedList and open the SimpleIntegerList example.
Much of the code is self-explanatory. We include the library and create the object, specifying integer as the data type.
#include <LinkedList.h>
LinkedList<int> myList = LinkedList<int>();
Within setup, we populate the list with some integers, using the .add() function.
void setup()
{
Serial.begin(9600);
Serial.println("Hello!");
// Add some stuff to the list
int k = -240,
l = 123,
m = -2,
n = 222;
myList.add(n);
myList.add(0);
myList.add(l);
myList.add(17);
myList.add(k);
myList.add(m);
}
In the loop, we print the size of the list, using the .size() function, and get each successive element using the .get() function. If the value of that element is less than 0, we print it.
void loop() {
int listSize = myList.size();
Serial.print("There are ");
Serial.print(listSize);
Serial.print(" integers in the list. The negative ones are: ");
// Print Negative numbers
for (int h = 0; h < listSize; h++) {
// Get value from list
int val = myList.get(h);
// If the value is negative, print it
if (val < 0) {
Serial.print(" ");
Serial.print(val);
}
}
while (true); // nothing else to do, loop forever
}
When run on the Serial Monitor, the output is −
As you can see, this one is quite straightforward. You are encouraged to go through the other examples that come in with this library as well. | [
{
"code": null,
"e": 1277,
"s": 1062,
"text": "The LinkedList library by Ivan Seidel helps implement this data structure in Arduino. A linked list contains a set of nodes wherein each node contains some data, and a link (reference) to the next node in the list."
},
{
"code": null,
"e": 1352,
"s": 1277,
"text": "To install this library, go to Library Manager, and search for LinkedList."
},
{
"code": null,
"e": 1441,
"s": 1352,
"text": "Once installed, go to: File→ Examples→LinkedList and open the SimpleIntegerList example."
},
{
"code": null,
"e": 1562,
"s": 1441,
"text": "Much of the code is self-explanatory. We include the library and create the object, specifying integer as the data type."
},
{
"code": null,
"e": 1630,
"s": 1562,
"text": "#include <LinkedList.h>\nLinkedList<int> myList = LinkedList<int>();"
},
{
"code": null,
"e": 1712,
"s": 1630,
"text": "Within setup, we populate the list with some integers, using the .add() function."
},
{
"code": null,
"e": 1985,
"s": 1712,
"text": "void setup()\n{\n Serial.begin(9600);\n Serial.println(\"Hello!\");\n\n // Add some stuff to the list\n int k = -240,\n l = 123,\n m = -2,\n n = 222;\n myList.add(n);\n myList.add(0);\n myList.add(l);\n myList.add(17);\n myList.add(k);\n myList.add(m);\n}"
},
{
"code": null,
"e": 2174,
"s": 1985,
"text": "In the loop, we print the size of the list, using the .size() function, and get each successive element using the .get() function. If the value of that element is less than 0, we print it."
},
{
"code": null,
"e": 2669,
"s": 2174,
"text": "void loop() {\n int listSize = myList.size();\n\n Serial.print(\"There are \");\n Serial.print(listSize);\n Serial.print(\" integers in the list. The negative ones are: \");\n\n // Print Negative numbers\n for (int h = 0; h < listSize; h++) {\n\n // Get value from list\n int val = myList.get(h);\n\n // If the value is negative, print it\n if (val < 0) {\n Serial.print(\" \");\n Serial.print(val);\n }\n }\n\n while (true); // nothing else to do, loop forever\n}"
},
{
"code": null,
"e": 2717,
"s": 2669,
"text": "When run on the Serial Monitor, the output is −"
},
{
"code": null,
"e": 2860,
"s": 2717,
"text": "As you can see, this one is quite straightforward. You are encouraged to go through the other examples that come in with this library as well."
}
] |
List vs tuple vs dictionary in Python | List and Tuple objects are sequences. A dictionary is a hash table of key-value pairs. List and tuple is an ordered collection of items. Dictionary is unordered collection.
List and dictionary objects are mutable i.e. it is possible to add new item or delete and item from it. Tuple is an immutable object. Addition or deletion operations are not possible on tuple object.
Each of them is a collection of comma-separated items. List items are enclosed in square brackets [], tuple items in round brackets or parentheses (), and dictionary items in curly brackets {}
>>> L1=[12, "Ravi", "B.Com FY", 78.50] #list
>>> T1=(12, "Ravi", "B.Com FY", 78.50)#tuple
>>> D1={"Rollno":12, "class":"B.com FY", "precentage":78.50}#dictionary
List and tuple items are indexed. Slice operator allows item of certain index to be accessed
>>> print (L1[2])
B.Com FY
>>> print (T1[2])
B.Com FY
Items in dictionary are not indexed. Value associated with a certain key is obtained by putting in square bracket. The get() method of dictionary also returns associated value.
>>> print (D1['class'])
B.com FY
>>> print (D1.get('class'))
B.com FY | [
{
"code": null,
"e": 1235,
"s": 1062,
"text": "List and Tuple objects are sequences. A dictionary is a hash table of key-value pairs. List and tuple is an ordered collection of items. Dictionary is unordered collection."
},
{
"code": null,
"e": 1435,
"s": 1235,
"text": "List and dictionary objects are mutable i.e. it is possible to add new item or delete and item from it. Tuple is an immutable object. Addition or deletion operations are not possible on tuple object."
},
{
"code": null,
"e": 1628,
"s": 1435,
"text": "Each of them is a collection of comma-separated items. List items are enclosed in square brackets [], tuple items in round brackets or parentheses (), and dictionary items in curly brackets {}"
},
{
"code": null,
"e": 1790,
"s": 1628,
"text": ">>> L1=[12, \"Ravi\", \"B.Com FY\", 78.50] #list\n>>> T1=(12, \"Ravi\", \"B.Com FY\", 78.50)#tuple\n>>> D1={\"Rollno\":12, \"class\":\"B.com FY\", \"precentage\":78.50}#dictionary"
},
{
"code": null,
"e": 1883,
"s": 1790,
"text": "List and tuple items are indexed. Slice operator allows item of certain index to be accessed"
},
{
"code": null,
"e": 1937,
"s": 1883,
"text": ">>> print (L1[2])\nB.Com FY\n>>> print (T1[2])\nB.Com FY"
},
{
"code": null,
"e": 2114,
"s": 1937,
"text": "Items in dictionary are not indexed. Value associated with a certain key is obtained by putting in square bracket. The get() method of dictionary also returns associated value."
},
{
"code": null,
"e": 2184,
"s": 2114,
"text": ">>> print (D1['class'])\nB.com FY\n>>> print (D1.get('class'))\nB.com FY"
}
] |
Random Walks with Restart Explained | by Vatsal | Towards Data Science | The scope of this article is to explain and focus around the conceptual understanding behind the random walk with restart algorithm. A strong mathematical understanding will not be provided here, but I have left links to resources where for those interested can investigate further into the mathematics behind this algorithm. I will also provide a documented Python script at the end of the article associated to the implementation of this algorithm.
Introduction
What is a Random Walk?
Random Walk with Restart
Advantages
Disadvantages
Python Implementation
Resources
This algorithm is highly applicable in research as well as the industry. If you’re working with time series data, or able to structure your data as a network then a random walk / random walk with reset can be implemented on it. In finance, it is often argued that the changes in stock prices follow a random walk. This algorithm works well with other stochastic processes like Markov Chains and Monte Carlo Simulations. This simple to understand algorithm was first formally introduced by Karl Pearson, a mathematician who dedicated majority of his life to building a strong foundation around mathematical statistics.
In our examples below we will be running a random walk on either of the following things. 1) A connected graph G with vertices V and edges E connecting multiple nodes to each otherOR2) A NxN matrix Note : A matrix can be converted into a graph and vice versa
Common problems where this algorithm is applied are :
Recommendation Systems
Community Detection
Clustering
Image Segmentation
A random walk is a type of stochastic process. The simplest explanation of a random walk would be through walking. Imagine, that each step you take is determined probabilistically. This implies that at each index of time, you have moved in a certain direction based on a probabilistic outcome. This algorithm explores the relationship to each step that you would take and its distance from the initial starting point.
If you started at the origin (large black circle in the image above) with an equal probability of moving in any direction at each time step. The image above outlines 3 possible walks after 4 time steps, each with a different ending point from the origin. If this process was simulated a large number of times with a large enough time step, then you can create a probability distribution associated to the outcome of each random walk ending at a specific location.
In this 2-dimensional example, after many iterations of a random walk, the distribution will look like a 3D bell curve (as shown in figure 2). This can be replicated in N dimensions.
Given this probability distribution, it can be represented as the closeness between a pair of positions.
Random walk with restart is exactly as a random walk but with one extra component to it. This component can be denoted as the restart probability. Essentially indicating that for every step taken in any direction there is a probability associated to going back to the initial starting position, the origin. In our example above of randomly moving in any direction, imagine now that there is a chance that you would instantly teleport back to the origin after every step based on this restart probability.
This article has an excellent explanation of the mathematics behind the random walk with restart algorithm.
Provides a strong representation of similarity between two nodes in a weighted & unweighted graph
Has a variety of applications and can be used be used in joint with other stochastic models like Markov Chains
Using the same restart probability for every node
There is no systematic way of choosing the restart probability for each application
Here I’ve implemented the random walk with restart algorithm on a given network G. Note, that there are many variations of this algorithm and can be substantially improved depending on the problem you’re trying to solve. The resulting output of this script can be used on other ML algorithms and models like kNN and k means.
A very simple, 1 line implementation of this algorithm can be through a library called networkX. They have a built in function called PageRank which is essentially random walk with restart. Below I’ve included a simple example from the networkX documentation for PageRank.
import networkx as nxG = nx.DiGraph(nx.path_graph(4)) # create the networkpr = nx.pagerank(G, alpha=0.9) # apply PageRank
http://www.cs.cmu.edu/~christos/PUBLICATIONS/icdm06-rwr.pdf
https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0213857#:~:text=However%2C%20RWR%20suffers%20from%20two,each%20application%20without%20theoretical%20justification.
https://medium.com/@chaitanya_bhatia/random-walk-with-restart-and-its-applications-f53d7c98cb9
https://www.youtube.com/watch?v=6wUD_gp5WeE&t=85s
https://en.wikipedia.org/wiki/Random_walk
https://networkx.org/documentation/networkx-1.10/reference/generated/networkx.algorithms.link_analysis.pagerank_alg.pagerank.html
https://github.com/jinhongjung/pyrwr
If you liked this article, then you might also like my other articles where I’ve explained things like the Monte Carlo method and Markov Chains. | [
{
"code": null,
"e": 622,
"s": 171,
"text": "The scope of this article is to explain and focus around the conceptual understanding behind the random walk with restart algorithm. A strong mathematical understanding will not be provided here, but I have left links to resources where for those interested can investigate further into the mathematics behind this algorithm. I will also provide a documented Python script at the end of the article associated to the implementation of this algorithm."
},
{
"code": null,
"e": 635,
"s": 622,
"text": "Introduction"
},
{
"code": null,
"e": 658,
"s": 635,
"text": "What is a Random Walk?"
},
{
"code": null,
"e": 683,
"s": 658,
"text": "Random Walk with Restart"
},
{
"code": null,
"e": 694,
"s": 683,
"text": "Advantages"
},
{
"code": null,
"e": 708,
"s": 694,
"text": "Disadvantages"
},
{
"code": null,
"e": 730,
"s": 708,
"text": "Python Implementation"
},
{
"code": null,
"e": 740,
"s": 730,
"text": "Resources"
},
{
"code": null,
"e": 1358,
"s": 740,
"text": "This algorithm is highly applicable in research as well as the industry. If you’re working with time series data, or able to structure your data as a network then a random walk / random walk with reset can be implemented on it. In finance, it is often argued that the changes in stock prices follow a random walk. This algorithm works well with other stochastic processes like Markov Chains and Monte Carlo Simulations. This simple to understand algorithm was first formally introduced by Karl Pearson, a mathematician who dedicated majority of his life to building a strong foundation around mathematical statistics."
},
{
"code": null,
"e": 1617,
"s": 1358,
"text": "In our examples below we will be running a random walk on either of the following things. 1) A connected graph G with vertices V and edges E connecting multiple nodes to each otherOR2) A NxN matrix Note : A matrix can be converted into a graph and vice versa"
},
{
"code": null,
"e": 1671,
"s": 1617,
"text": "Common problems where this algorithm is applied are :"
},
{
"code": null,
"e": 1694,
"s": 1671,
"text": "Recommendation Systems"
},
{
"code": null,
"e": 1714,
"s": 1694,
"text": "Community Detection"
},
{
"code": null,
"e": 1725,
"s": 1714,
"text": "Clustering"
},
{
"code": null,
"e": 1744,
"s": 1725,
"text": "Image Segmentation"
},
{
"code": null,
"e": 2162,
"s": 1744,
"text": "A random walk is a type of stochastic process. The simplest explanation of a random walk would be through walking. Imagine, that each step you take is determined probabilistically. This implies that at each index of time, you have moved in a certain direction based on a probabilistic outcome. This algorithm explores the relationship to each step that you would take and its distance from the initial starting point."
},
{
"code": null,
"e": 2626,
"s": 2162,
"text": "If you started at the origin (large black circle in the image above) with an equal probability of moving in any direction at each time step. The image above outlines 3 possible walks after 4 time steps, each with a different ending point from the origin. If this process was simulated a large number of times with a large enough time step, then you can create a probability distribution associated to the outcome of each random walk ending at a specific location."
},
{
"code": null,
"e": 2809,
"s": 2626,
"text": "In this 2-dimensional example, after many iterations of a random walk, the distribution will look like a 3D bell curve (as shown in figure 2). This can be replicated in N dimensions."
},
{
"code": null,
"e": 2914,
"s": 2809,
"text": "Given this probability distribution, it can be represented as the closeness between a pair of positions."
},
{
"code": null,
"e": 3419,
"s": 2914,
"text": "Random walk with restart is exactly as a random walk but with one extra component to it. This component can be denoted as the restart probability. Essentially indicating that for every step taken in any direction there is a probability associated to going back to the initial starting position, the origin. In our example above of randomly moving in any direction, imagine now that there is a chance that you would instantly teleport back to the origin after every step based on this restart probability."
},
{
"code": null,
"e": 3527,
"s": 3419,
"text": "This article has an excellent explanation of the mathematics behind the random walk with restart algorithm."
},
{
"code": null,
"e": 3625,
"s": 3527,
"text": "Provides a strong representation of similarity between two nodes in a weighted & unweighted graph"
},
{
"code": null,
"e": 3736,
"s": 3625,
"text": "Has a variety of applications and can be used be used in joint with other stochastic models like Markov Chains"
},
{
"code": null,
"e": 3786,
"s": 3736,
"text": "Using the same restart probability for every node"
},
{
"code": null,
"e": 3870,
"s": 3786,
"text": "There is no systematic way of choosing the restart probability for each application"
},
{
"code": null,
"e": 4195,
"s": 3870,
"text": "Here I’ve implemented the random walk with restart algorithm on a given network G. Note, that there are many variations of this algorithm and can be substantially improved depending on the problem you’re trying to solve. The resulting output of this script can be used on other ML algorithms and models like kNN and k means."
},
{
"code": null,
"e": 4468,
"s": 4195,
"text": "A very simple, 1 line implementation of this algorithm can be through a library called networkX. They have a built in function called PageRank which is essentially random walk with restart. Below I’ve included a simple example from the networkX documentation for PageRank."
},
{
"code": null,
"e": 4595,
"s": 4468,
"text": "import networkx as nxG = nx.DiGraph(nx.path_graph(4)) # create the networkpr = nx.pagerank(G, alpha=0.9) # apply PageRank "
},
{
"code": null,
"e": 4655,
"s": 4595,
"text": "http://www.cs.cmu.edu/~christos/PUBLICATIONS/icdm06-rwr.pdf"
},
{
"code": null,
"e": 4837,
"s": 4655,
"text": "https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0213857#:~:text=However%2C%20RWR%20suffers%20from%20two,each%20application%20without%20theoretical%20justification."
},
{
"code": null,
"e": 4932,
"s": 4837,
"text": "https://medium.com/@chaitanya_bhatia/random-walk-with-restart-and-its-applications-f53d7c98cb9"
},
{
"code": null,
"e": 4982,
"s": 4932,
"text": "https://www.youtube.com/watch?v=6wUD_gp5WeE&t=85s"
},
{
"code": null,
"e": 5024,
"s": 4982,
"text": "https://en.wikipedia.org/wiki/Random_walk"
},
{
"code": null,
"e": 5154,
"s": 5024,
"text": "https://networkx.org/documentation/networkx-1.10/reference/generated/networkx.algorithms.link_analysis.pagerank_alg.pagerank.html"
},
{
"code": null,
"e": 5191,
"s": 5154,
"text": "https://github.com/jinhongjung/pyrwr"
}
] |
Sum of absolute differences of indices of occurrences of each array element - GeeksforGeeks | 20 May, 2021
Given an array arr[] consisting of N integers, the task for each array element arr[i] is to print the sum of |i – j| for all possible indices j such that arr[i] = arr[j].
Examples:
Input: arr[] = {1, 3, 1, 1, 2}Output: 5 0 3 4 0Explanation: For arr[0], sum = |0 – 0| + |0 – 2| + |0 – 3| = 5. For arr[1], sum = |1 – 1| = 0. For arr[2], sum = |2 – 0| + |2 – 2| + |2 – 3| = 3. For arr[3], sum = |3 – 0| + |3 – 2| + |3 – 3| = 4. For arr[4], sum = |4 – 4| = 0. Therefore, the required output is 5 0 3 4 0.
Input: arr[] = {1, 1, 1}Output: 3 2 3
Naive approach: The simplest approach is to traverse the given array and for each element arr[i] ( 0 ≤ i ≤ N ), traverse the array and check if arr[i] is same as arr[j] ( 0 ≤ j ≤ N ). If found to be true, add abs(i – j) to the sum print the sum obtained for each array element.
Time Complexity: O(N2) where N is the size of the given array.Auxiliary Space: O(N)
Efficient Approach: The idea is to use Map data structure to optimize the above approach. Follow the steps below to solve the problem:
Initialize a Map to store the vector of indices for repetitions of each unique element present in the array.Traverse the given array from i = 0 to N – 1 and for each array element arr[i], initialize the sum with 0 and traverse the vector map[arr[i]] which stores the indices of the occurrences of the element arr[i].For each value j present in the vector, increment the sum by abs(i – j).After traversing the vector, store the sum for the element at index i and print the sum.
Initialize a Map to store the vector of indices for repetitions of each unique element present in the array.
Traverse the given array from i = 0 to N – 1 and for each array element arr[i], initialize the sum with 0 and traverse the vector map[arr[i]] which stores the indices of the occurrences of the element arr[i].
For each value j present in the vector, increment the sum by abs(i – j).
After traversing the vector, store the sum for the element at index i and print the sum.
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 sum of differences// of indices of occurrences of each// unique array elementvoid sum(int arr[], int n){ // Stores indices of each // array element map<int, vector<int> > mp; // Store the indices for (int i = 0; i < n; i++) { mp[arr[i]].push_back(i); } // Stores the sums int ans[n]; // Traverse the array for (int i = 0; i < n; i++) { // Find sum for each element int sum = 0; // Iterate over the Map for (auto it : mp[arr[i]]) { // Calculate sum of // occurrences of arr[i] sum += abs(it - i); } // Store sum for // current element ans[i] = sum; } // Print answer for each element for (int i = 0; i < n; i++) { cout << ans[i] << " "; } return;} // Driver Codeint main(){ // Given array int arr[] = { 1, 3, 1, 1, 2 }; // Given size int n = sizeof(arr) / sizeof(arr[0]); // Function call sum(arr, n); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find sum of differences// of indices of occurrences of each// unique array elementstatic void sum(int arr[], int n){ // Stores indices of each // array element HashMap<Integer, Vector<Integer>> mp = new HashMap<>(); // Store the indices for(int i = 0; i < n; i++) { Vector<Integer> v = new Vector<>(); v.add(i); if (mp.containsKey(arr[i])) v.addAll(mp.get(arr[i])); mp.put(arr[i], v); } // Stores the sums int []ans = new int[n]; // Traverse the array for(int i = 0; i < n; i++) { // Find sum for each element int sum = 0; // Iterate over the Map for(int it : mp.get(arr[i])) { // Calculate sum of // occurrences of arr[i] sum += Math.abs(it - i); } // Store sum for // current element ans[i] = sum; } // Print answer for each element for(int i = 0; i < n; i++) { System.out.print(ans[i] + " "); } return;} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = { 1, 3, 1, 1, 2 }; // Given size int n = arr.length; // Function call sum(arr, n);}} // This code is contributed by Princi Singh
# Python3 program for the above approachfrom collections import defaultdict # Function to find sum of differences# of indices of occurrences of each# unique array elementdef sum_i(arr, n): # Stores indices of each # array element mp = defaultdict(lambda : []) # Store the indices for i in range(n): mp[arr[i]].append(i) # Stores the sums ans = [0] * n # Traverse the array for i in range(n): # Find sum for each element sum = 0 # Iterate over the Map for it in mp[arr[i]]: # Calculate sum of # occurrences of arr[i] sum += abs(it - i) # Store sum for # current element ans[i] = sum # Print answer for each element for i in range(n): print(ans[i], end = " ") # Driver codeif __name__ == '__main__': # Given array arr = [ 1, 3, 1, 1, 2 ] # Given size n = len(arr) # Function Call sum_i(arr, n) # This code is contributed by Shivam Singh
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find sum of differences// of indices of occurrences of each// unique array elementstatic void sum(int []arr, int n){ // Stores indices of each // array element Dictionary<int, List<int>> mp = new Dictionary<int, List<int>>(); // Store the indices for(int i = 0; i < n; i++) { List<int> v = new List<int>(); v.Add(i); if (mp.ContainsKey(arr[i])) v.AddRange(mp[arr[i]]); mp[arr[i]]= v; } // Stores the sums int []ans = new int[n]; // Traverse the array for(int i = 0; i < n; i++) { // Find sum for each element int sum = 0; // Iterate over the Map foreach(int it in mp[arr[i]]) { // Calculate sum of // occurrences of arr[i] sum += Math.Abs(it - i); } // Store sum for // current element ans[i] = sum; } // Print answer for each element for(int i = 0; i < n; i++) { Console.Write(ans[i] + " "); } return;} // Driver Codepublic static void Main(String[] args){ // Given array int []arr = { 1, 3, 1, 1, 2 }; // Given size int n = arr.Length; // Function call sum(arr, n);}} // This code is contributed by shikhasingrajput
<script> // JavaScript program for the above approach // Function to find sum of differences// of indices of occurrences of each// unique array elementfunction sum(arr, n){ // Stores indices of each // array element var mp = new Map(); // Store the indices for (var i = 0; i < n; i++) { if(mp.has(arr[i])) { var tmp = mp.get(arr[i]); tmp.push(i); mp.set(arr[i], tmp); } else { mp.set(arr[i], [i]); } } // Stores the sums var ans = Array(n); // Traverse the array for (var i = 0; i < n; i++) { // Find sum for each element var sum = 0; // Iterate over the Map mp.get(arr[i]).forEach(it => { // Calculate sum of // occurrences of arr[i] sum += Math.abs(it - i); }); // Store sum for // current element ans[i] = sum; } // Print answer for each element for (var i = 0; i < n; i++) { document.write( ans[i] + " "); } return;} // Driver Code // Given arrayvar arr = [1, 3, 1, 1, 2]; // Given sizevar n = arr.length; // Function callsum(arr, n); </script>
5 0 3 4 0
Time Complexity: O(N * L) where N is the size of the given array and L is the maximum frequency of any array element.Auxiliary Space: O(N)
SHIVAMSINGH67
khushboogoyal499
princi singh
shikhasingrajput
rrrtnx
cpp-map
frequency-counting
Arrays
Hash
Mathematical
Searching
Arrays
Searching
Hash
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum | [
{
"code": null,
"e": 25408,
"s": 25380,
"text": "\n20 May, 2021"
},
{
"code": null,
"e": 25579,
"s": 25408,
"text": "Given an array arr[] consisting of N integers, the task for each array element arr[i] is to print the sum of |i – j| for all possible indices j such that arr[i] = arr[j]."
},
{
"code": null,
"e": 25589,
"s": 25579,
"text": "Examples:"
},
{
"code": null,
"e": 25909,
"s": 25589,
"text": "Input: arr[] = {1, 3, 1, 1, 2}Output: 5 0 3 4 0Explanation: For arr[0], sum = |0 – 0| + |0 – 2| + |0 – 3| = 5. For arr[1], sum = |1 – 1| = 0. For arr[2], sum = |2 – 0| + |2 – 2| + |2 – 3| = 3. For arr[3], sum = |3 – 0| + |3 – 2| + |3 – 3| = 4. For arr[4], sum = |4 – 4| = 0. Therefore, the required output is 5 0 3 4 0."
},
{
"code": null,
"e": 25947,
"s": 25909,
"text": "Input: arr[] = {1, 1, 1}Output: 3 2 3"
},
{
"code": null,
"e": 26225,
"s": 25947,
"text": "Naive approach: The simplest approach is to traverse the given array and for each element arr[i] ( 0 ≤ i ≤ N ), traverse the array and check if arr[i] is same as arr[j] ( 0 ≤ j ≤ N ). If found to be true, add abs(i – j) to the sum print the sum obtained for each array element."
},
{
"code": null,
"e": 26309,
"s": 26225,
"text": "Time Complexity: O(N2) where N is the size of the given array.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 26444,
"s": 26309,
"text": "Efficient Approach: The idea is to use Map data structure to optimize the above approach. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26921,
"s": 26444,
"text": "Initialize a Map to store the vector of indices for repetitions of each unique element present in the array.Traverse the given array from i = 0 to N – 1 and for each array element arr[i], initialize the sum with 0 and traverse the vector map[arr[i]] which stores the indices of the occurrences of the element arr[i].For each value j present in the vector, increment the sum by abs(i – j).After traversing the vector, store the sum for the element at index i and print the sum."
},
{
"code": null,
"e": 27030,
"s": 26921,
"text": "Initialize a Map to store the vector of indices for repetitions of each unique element present in the array."
},
{
"code": null,
"e": 27239,
"s": 27030,
"text": "Traverse the given array from i = 0 to N – 1 and for each array element arr[i], initialize the sum with 0 and traverse the vector map[arr[i]] which stores the indices of the occurrences of the element arr[i]."
},
{
"code": null,
"e": 27312,
"s": 27239,
"text": "For each value j present in the vector, increment the sum by abs(i – j)."
},
{
"code": null,
"e": 27401,
"s": 27312,
"text": "After traversing the vector, store the sum for the element at index i and print the sum."
},
{
"code": null,
"e": 27452,
"s": 27401,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27456,
"s": 27452,
"text": "C++"
},
{
"code": null,
"e": 27461,
"s": 27456,
"text": "Java"
},
{
"code": null,
"e": 27469,
"s": 27461,
"text": "Python3"
},
{
"code": null,
"e": 27472,
"s": 27469,
"text": "C#"
},
{
"code": null,
"e": 27483,
"s": 27472,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find sum of differences// of indices of occurrences of each// unique array elementvoid sum(int arr[], int n){ // Stores indices of each // array element map<int, vector<int> > mp; // Store the indices for (int i = 0; i < n; i++) { mp[arr[i]].push_back(i); } // Stores the sums int ans[n]; // Traverse the array for (int i = 0; i < n; i++) { // Find sum for each element int sum = 0; // Iterate over the Map for (auto it : mp[arr[i]]) { // Calculate sum of // occurrences of arr[i] sum += abs(it - i); } // Store sum for // current element ans[i] = sum; } // Print answer for each element for (int i = 0; i < n; i++) { cout << ans[i] << \" \"; } return;} // Driver Codeint main(){ // Given array int arr[] = { 1, 3, 1, 1, 2 }; // Given size int n = sizeof(arr) / sizeof(arr[0]); // Function call sum(arr, n); return 0;}",
"e": 28598,
"s": 27483,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find sum of differences// of indices of occurrences of each// unique array elementstatic void sum(int arr[], int n){ // Stores indices of each // array element HashMap<Integer, Vector<Integer>> mp = new HashMap<>(); // Store the indices for(int i = 0; i < n; i++) { Vector<Integer> v = new Vector<>(); v.add(i); if (mp.containsKey(arr[i])) v.addAll(mp.get(arr[i])); mp.put(arr[i], v); } // Stores the sums int []ans = new int[n]; // Traverse the array for(int i = 0; i < n; i++) { // Find sum for each element int sum = 0; // Iterate over the Map for(int it : mp.get(arr[i])) { // Calculate sum of // occurrences of arr[i] sum += Math.abs(it - i); } // Store sum for // current element ans[i] = sum; } // Print answer for each element for(int i = 0; i < n; i++) { System.out.print(ans[i] + \" \"); } return;} // Driver Codepublic static void main(String[] args){ // Given array int arr[] = { 1, 3, 1, 1, 2 }; // Given size int n = arr.length; // Function call sum(arr, n);}} // This code is contributed by Princi Singh",
"e": 29979,
"s": 28598,
"text": null
},
{
"code": "# Python3 program for the above approachfrom collections import defaultdict # Function to find sum of differences# of indices of occurrences of each# unique array elementdef sum_i(arr, n): # Stores indices of each # array element mp = defaultdict(lambda : []) # Store the indices for i in range(n): mp[arr[i]].append(i) # Stores the sums ans = [0] * n # Traverse the array for i in range(n): # Find sum for each element sum = 0 # Iterate over the Map for it in mp[arr[i]]: # Calculate sum of # occurrences of arr[i] sum += abs(it - i) # Store sum for # current element ans[i] = sum # Print answer for each element for i in range(n): print(ans[i], end = \" \") # Driver codeif __name__ == '__main__': # Given array arr = [ 1, 3, 1, 1, 2 ] # Given size n = len(arr) # Function Call sum_i(arr, n) # This code is contributed by Shivam Singh",
"e": 30989,
"s": 29979,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find sum of differences// of indices of occurrences of each// unique array elementstatic void sum(int []arr, int n){ // Stores indices of each // array element Dictionary<int, List<int>> mp = new Dictionary<int, List<int>>(); // Store the indices for(int i = 0; i < n; i++) { List<int> v = new List<int>(); v.Add(i); if (mp.ContainsKey(arr[i])) v.AddRange(mp[arr[i]]); mp[arr[i]]= v; } // Stores the sums int []ans = new int[n]; // Traverse the array for(int i = 0; i < n; i++) { // Find sum for each element int sum = 0; // Iterate over the Map foreach(int it in mp[arr[i]]) { // Calculate sum of // occurrences of arr[i] sum += Math.Abs(it - i); } // Store sum for // current element ans[i] = sum; } // Print answer for each element for(int i = 0; i < n; i++) { Console.Write(ans[i] + \" \"); } return;} // Driver Codepublic static void Main(String[] args){ // Given array int []arr = { 1, 3, 1, 1, 2 }; // Given size int n = arr.Length; // Function call sum(arr, n);}} // This code is contributed by shikhasingrajput",
"e": 32440,
"s": 30989,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find sum of differences// of indices of occurrences of each// unique array elementfunction sum(arr, n){ // Stores indices of each // array element var mp = new Map(); // Store the indices for (var i = 0; i < n; i++) { if(mp.has(arr[i])) { var tmp = mp.get(arr[i]); tmp.push(i); mp.set(arr[i], tmp); } else { mp.set(arr[i], [i]); } } // Stores the sums var ans = Array(n); // Traverse the array for (var i = 0; i < n; i++) { // Find sum for each element var sum = 0; // Iterate over the Map mp.get(arr[i]).forEach(it => { // Calculate sum of // occurrences of arr[i] sum += Math.abs(it - i); }); // Store sum for // current element ans[i] = sum; } // Print answer for each element for (var i = 0; i < n; i++) { document.write( ans[i] + \" \"); } return;} // Driver Code // Given arrayvar arr = [1, 3, 1, 1, 2]; // Given sizevar n = arr.length; // Function callsum(arr, n); </script>",
"e": 33634,
"s": 32440,
"text": null
},
{
"code": null,
"e": 33644,
"s": 33634,
"text": "5 0 3 4 0"
},
{
"code": null,
"e": 33785,
"s": 33646,
"text": "Time Complexity: O(N * L) where N is the size of the given array and L is the maximum frequency of any array element.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 33801,
"s": 33787,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 33818,
"s": 33801,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 33831,
"s": 33818,
"text": "princi singh"
},
{
"code": null,
"e": 33848,
"s": 33831,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 33855,
"s": 33848,
"text": "rrrtnx"
},
{
"code": null,
"e": 33863,
"s": 33855,
"text": "cpp-map"
},
{
"code": null,
"e": 33882,
"s": 33863,
"text": "frequency-counting"
},
{
"code": null,
"e": 33889,
"s": 33882,
"text": "Arrays"
},
{
"code": null,
"e": 33894,
"s": 33889,
"text": "Hash"
},
{
"code": null,
"e": 33907,
"s": 33894,
"text": "Mathematical"
},
{
"code": null,
"e": 33917,
"s": 33907,
"text": "Searching"
},
{
"code": null,
"e": 33924,
"s": 33917,
"text": "Arrays"
},
{
"code": null,
"e": 33934,
"s": 33924,
"text": "Searching"
},
{
"code": null,
"e": 33939,
"s": 33934,
"text": "Hash"
},
{
"code": null,
"e": 33952,
"s": 33939,
"text": "Mathematical"
},
{
"code": null,
"e": 34050,
"s": 33952,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34059,
"s": 34050,
"text": "Comments"
},
{
"code": null,
"e": 34072,
"s": 34059,
"text": "Old Comments"
},
{
"code": null,
"e": 34120,
"s": 34072,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34164,
"s": 34120,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 34187,
"s": 34164,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34201,
"s": 34187,
"text": "Linear Search"
},
{
"code": null,
"e": 34269,
"s": 34201,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34354,
"s": 34269,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 34390,
"s": 34354,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 34421,
"s": 34390,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 34455,
"s": 34421,
"text": "Hashing | Set 3 (Open Addressing)"
}
] |
LISP - Tree | You can build tree data structures from cons cells, as lists of lists.
To implement tree structures, you will have to design functionalities that would traverse through the cons cells, in specific order, for example, pre-order, in-order, and post-order for binary trees.
Let us consider a tree structure made up of cons cell that form the following list of lists −
((1 2) (3 4) (5 6)).
Diagrammatically, it could be expressed as −
Although mostly you will need to write your own tree-functionalities according to your specific need, LISP provides some tree functions that you can use.
Apart from all the list functions, the following functions work especially on tree structures −
copy-tree x & optional vecp
It returns a copy of the tree of cons cells x. It recursively copies both the car and the cdr directions. If x is not a cons cell, the function simply returns x unchanged. If the optional vecp argument is true, this function copies vectors (recursively) as well as cons cells.
tree-equal x y & key :test :test-not :key
It compares two trees of cons cells. If x and y are both cons cells, their cars and cdrs are compared recursively. If neither x nor y is a cons cell, they are compared by eql, or according to the specified test. The :key function, if specified, is applied to the elements of both trees.
subst new old tree & key :test :test-not :key
It substitutes occurrences of given old item with new item, in tree, which is a tree of cons cells.
nsubst new old tree & key :test :test-not :key
It works same as subst, but it destroys the original tree.
sublis alist tree & key :test :test-not :key
It works like subst, except that it takes an association list alist of old-new pairs. Each element of the tree (after applying the :key function, if any), is compared with the cars of alist; if it matches, it is replaced by the corresponding cdr.
nsublis alist tree & key :test :test-not :key
It works same as sublis, but a destructive version.
Create a new source code file named main.lisp and type the following code in it.
(setq lst (list '(1 2) '(3 4) '(5 6)))
(setq mylst (copy-list lst))
(setq tr (copy-tree lst))
(write lst)
(terpri)
(write mylst)
(terpri)
(write tr)
When you execute the code, it returns the following result −
((1 2) (3 4) (5 6))
((1 2) (3 4) (5 6))
((1 2) (3 4) (5 6))
Create a new source code file named main.lisp and type the following code in it.
(setq tr '((1 2 (3 4 5) ((7 8) (7 8 9)))))
(write tr)
(setq trs (subst 7 1 tr))
(terpri)
(write trs)
When you execute the code, it returns the following result −
((1 2 (3 4 5) ((7 8) (7 8 9))))
((7 2 (3 4 5) ((7 8) (7 8 9))))
Let us try to build our own tree, using the list functions available in LISP.
(defun make-tree (item)
"it creates a new node with item."
(cons (cons item nil) nil)
)
Next let us add a child node into the tree - it will take two tree nodes and add the second tree as the child of the first.
(defun add-child (tree child)
(setf (car tree) (append (car tree) child))
tree)
This function will return the first child a given tree - it will take a tree node and return the first child of that node, or nil, if this node does not have any child node.
(defun first-child (tree)
(if (null tree)
nil
(cdr (car tree))
)
)
This function will return the next sibling of a given node - it takes a tree node as argument, and returns a reference to the next sibling node, or nil, if the node does not have any.
(defun next-sibling (tree)
(cdr tree)
)
Lastly we need a function to return the information in a node −
(defun data (tree)
(car (car tree))
)
This example uses the above functionalities −
Create a new source code file named main.lisp and type the following code in it.
(defun make-tree (item)
"it creates a new node with item."
(cons (cons item nil) nil)
)
(defun first-child (tree)
(if (null tree)
nil
(cdr (car tree))
)
)
(defun next-sibling (tree)
(cdr tree)
)
(defun data (tree)
(car (car tree))
)
(defun add-child (tree child)
(setf (car tree) (append (car tree) child))
tree
)
(setq tr '((1 2 (3 4 5) ((7 8) (7 8 9)))))
(setq mytree (make-tree 10))
(write (data mytree))
(terpri)
(write (first-child tr))
(terpri)
(setq newtree (add-child tr mytree))
(terpri)
(write newtree)
When you execute the code, it returns the following result −
10
(2 (3 4 5) ((7 8) (7 8 9)))
((1 2 (3 4 5) ((7 8) (7 8 9)) (10)))
79 Lectures
7 hours
Arnold Higuit
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2131,
"s": 2060,
"text": "You can build tree data structures from cons cells, as lists of lists."
},
{
"code": null,
"e": 2331,
"s": 2131,
"text": "To implement tree structures, you will have to design functionalities that would traverse through the cons cells, in specific order, for example, pre-order, in-order, and post-order for binary trees."
},
{
"code": null,
"e": 2425,
"s": 2331,
"text": "Let us consider a tree structure made up of cons cell that form the following list of lists −"
},
{
"code": null,
"e": 2446,
"s": 2425,
"text": "((1 2) (3 4) (5 6))."
},
{
"code": null,
"e": 2491,
"s": 2446,
"text": "Diagrammatically, it could be expressed as −"
},
{
"code": null,
"e": 2645,
"s": 2491,
"text": "Although mostly you will need to write your own tree-functionalities according to your specific need, LISP provides some tree functions that you can use."
},
{
"code": null,
"e": 2741,
"s": 2645,
"text": "Apart from all the list functions, the following functions work especially on tree structures −"
},
{
"code": null,
"e": 2769,
"s": 2741,
"text": "copy-tree x & optional vecp"
},
{
"code": null,
"e": 3046,
"s": 2769,
"text": "It returns a copy of the tree of cons cells x. It recursively copies both the car and the cdr directions. If x is not a cons cell, the function simply returns x unchanged. If the optional vecp argument is true, this function copies vectors (recursively) as well as cons cells."
},
{
"code": null,
"e": 3088,
"s": 3046,
"text": "tree-equal x y & key :test :test-not :key"
},
{
"code": null,
"e": 3375,
"s": 3088,
"text": "It compares two trees of cons cells. If x and y are both cons cells, their cars and cdrs are compared recursively. If neither x nor y is a cons cell, they are compared by eql, or according to the specified test. The :key function, if specified, is applied to the elements of both trees."
},
{
"code": null,
"e": 3421,
"s": 3375,
"text": "subst new old tree & key :test :test-not :key"
},
{
"code": null,
"e": 3521,
"s": 3421,
"text": "It substitutes occurrences of given old item with new item, in tree, which is a tree of cons cells."
},
{
"code": null,
"e": 3568,
"s": 3521,
"text": "nsubst new old tree & key :test :test-not :key"
},
{
"code": null,
"e": 3627,
"s": 3568,
"text": "It works same as subst, but it destroys the original tree."
},
{
"code": null,
"e": 3672,
"s": 3627,
"text": "sublis alist tree & key :test :test-not :key"
},
{
"code": null,
"e": 3920,
"s": 3672,
"text": "It works like subst, except that it takes an association list alist of old-new pairs. Each element of the tree (after applying the :key function, if any), is compared with the cars of alist; if it matches, it is replaced by the corresponding cdr."
},
{
"code": null,
"e": 3966,
"s": 3920,
"text": "nsublis alist tree & key :test :test-not :key"
},
{
"code": null,
"e": 4018,
"s": 3966,
"text": "It works same as sublis, but a destructive version."
},
{
"code": null,
"e": 4099,
"s": 4018,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 4249,
"s": 4099,
"text": "(setq lst (list '(1 2) '(3 4) '(5 6)))\n(setq mylst (copy-list lst))\n(setq tr (copy-tree lst))\n\n(write lst)\n(terpri)\n(write mylst)\n(terpri)\n(write tr)"
},
{
"code": null,
"e": 4310,
"s": 4249,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 4371,
"s": 4310,
"text": "((1 2) (3 4) (5 6))\n((1 2) (3 4) (5 6))\n((1 2) (3 4) (5 6))\n"
},
{
"code": null,
"e": 4452,
"s": 4371,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 4553,
"s": 4452,
"text": "(setq tr '((1 2 (3 4 5) ((7 8) (7 8 9)))))\n(write tr)\n(setq trs (subst 7 1 tr))\n(terpri)\n(write trs)"
},
{
"code": null,
"e": 4614,
"s": 4553,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 4679,
"s": 4614,
"text": "((1 2 (3 4 5) ((7 8) (7 8 9))))\n((7 2 (3 4 5) ((7 8) (7 8 9))))\n"
},
{
"code": null,
"e": 4757,
"s": 4679,
"text": "Let us try to build our own tree, using the list functions available in LISP."
},
{
"code": null,
"e": 4851,
"s": 4757,
"text": "(defun make-tree (item)\n \"it creates a new node with item.\"\n (cons (cons item nil) nil)\n)"
},
{
"code": null,
"e": 4975,
"s": 4851,
"text": "Next let us add a child node into the tree - it will take two tree nodes and add the second tree as the child of the first."
},
{
"code": null,
"e": 5061,
"s": 4975,
"text": "(defun add-child (tree child)\n (setf (car tree) (append (car tree) child))\n tree)"
},
{
"code": null,
"e": 5235,
"s": 5061,
"text": "This function will return the first child a given tree - it will take a tree node and return the first child of that node, or nil, if this node does not have any child node."
},
{
"code": null,
"e": 5320,
"s": 5235,
"text": "(defun first-child (tree)\n (if (null tree)\n nil\n (cdr (car tree))\n )\n)"
},
{
"code": null,
"e": 5504,
"s": 5320,
"text": "This function will return the next sibling of a given node - it takes a tree node as argument, and returns a reference to the next sibling node, or nil, if the node does not have any."
},
{
"code": null,
"e": 5547,
"s": 5504,
"text": "(defun next-sibling (tree)\n (cdr tree)\n)"
},
{
"code": null,
"e": 5611,
"s": 5547,
"text": "Lastly we need a function to return the information in a node −"
},
{
"code": null,
"e": 5652,
"s": 5611,
"text": "(defun data (tree)\n (car (car tree))\n)"
},
{
"code": null,
"e": 5698,
"s": 5652,
"text": "This example uses the above functionalities −"
},
{
"code": null,
"e": 5779,
"s": 5698,
"text": "Create a new source code file named main.lisp and type the following code in it."
},
{
"code": null,
"e": 6331,
"s": 5779,
"text": "(defun make-tree (item)\n \"it creates a new node with item.\"\n (cons (cons item nil) nil)\n)\n(defun first-child (tree)\n (if (null tree)\n nil\n (cdr (car tree))\n )\n)\n\n(defun next-sibling (tree)\n (cdr tree)\n)\n(defun data (tree)\n (car (car tree))\n)\n(defun add-child (tree child)\n (setf (car tree) (append (car tree) child))\n tree\n)\n\n(setq tr '((1 2 (3 4 5) ((7 8) (7 8 9)))))\n(setq mytree (make-tree 10))\n\n(write (data mytree))\n(terpri)\n(write (first-child tr))\n(terpri)\n(setq newtree (add-child tr mytree))\n(terpri)\n(write newtree)"
},
{
"code": null,
"e": 6392,
"s": 6331,
"text": "When you execute the code, it returns the following result −"
},
{
"code": null,
"e": 6462,
"s": 6392,
"text": "10\n(2 (3 4 5) ((7 8) (7 8 9)))\n\n((1 2 (3 4 5) ((7 8) (7 8 9)) (10)))\n"
},
{
"code": null,
"e": 6495,
"s": 6462,
"text": "\n 79 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6510,
"s": 6495,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 6517,
"s": 6510,
"text": " Print"
},
{
"code": null,
"e": 6528,
"s": 6517,
"text": " Add Notes"
}
] |
Improve Your Data Wrangling With Object Oriented Programming | by Callum Ballard | Towards Data Science | One of the dirty secrets of data science goes as follows:
“Far from spending hours discovering glorious new algorithms and developing cutting edge neural networks, you will in fact spend most of your time cleaning, munging, and manipulating data”
This is the result of a simple, inescapable truth — data in the real world doesn’t normally come nicely wrapped up in a Pandas dataframe with a pretty little bow on top. And since better quality data begets better quality models, it’s a part of the process that we can’t just ignore.
Some time ago, I wrote a blog about techniques for wrangling data that, despite containing mistakes, was at least structured in a dataframe. But what if you don’t even have that? Recall my last blog from On Target — we were using Splinter to scrape data from match pages on the English Premier League website.
towardsdatascience.com
This has given us all the data that we notionally need for the analysis/model building that we want to do. But it’s not in the friendliest format — the scraping code that I wrote put everything into nested dictionaries, whose schemas look like a bit like this:
MATCH_DICTIONARY-> MatchID (str)-> GameWeek (str)-> Events (long list of strings)-> Stats -> HomeStats (dictionary of team stats) -> AwayStats (dictionary of team stats)-> Players -> HomeTeam -> TeamName (str) -> StartingPlayers (list of strings) -> Subs (list of strings) -> AwayTeam -> TeamName (str) -> StartingPlayers (list of strings) -> Subs (list of strings)
It’s worth noting that collecting this data as dictionaries in the first instance was not irrational — the number of ‘Events’ in each match is different from game to game, so we can’t store them nicely in a relational table. Moreover, the dictionary method means that the match data stays associated with the MatchID, which is the unique identifier for each game and will be important later on in the modelling process.
At any rate, we’re going to need to get at this data somehow, and put it into a model-friendly format. However, the code for manipulating nested dictionaries gets messy pretty quickly, and perhaps more dangerously, dictionaries are mutable data structures — i.e. their contents can be edited. Thus, keeping the data in its present dictionary form could be risky.
Happily, there is another way — Object Oriented Programming (OOP).
Before diving into our specific example, let’s take a step back and think about ‘objects’ at a more conceptual level — particularly in the context of Python. You may be familiar with Python being an ‘Object Oriented Language’, but what does this actually mean?
An ‘object’, very roughly speaking, is a thing in Python that we can store to our computer’s memory. So this could be a string, or a list, or a dictionary. It could also be something more abstract, such as a pandas dataframe, a matplotlib figure, or a scikit learn model.
One key characteristic of most objects is that we can perform ‘methods’ upon them. Methods are in-built functions that are specific to a particular type of object. For example, we can ‘call’ the .lower( ) method on a string to make all the characters lower case:
IN: 'MyString'.lower()OUT: 'mystring'
However, if we tried calling the .lower( ) method on a different type of object (for example, an integer) then we’d get an error — this method doesn’t make sense in the context of an object that isn’t a string.
This brings us onto the concept of ‘Classes’. In Python, a Class is a combination of two things:
A type of object.
A series of ‘built in’ methods that we can call on that type of object.
‘String’ is an example of a Class in Python. We can create individual objects of type ‘String’ (e.g. “Hello World”, “MyString”, or “I Love Towards Data Science”), and we have a selection of methods that we can call on them. Importantly, these methods are ‘built into’ the object.
It’s also worth noting that objects often have attributes (which we can look up). For example, a pandas dataframe has a ‘shape’ attribute, which tells us how many rows and columns it has. Similarly, the names of its columns and its index are also attributes. Of course, the attributes of two objects of the same class can be different (a different dataframe may have more or fewer columns and rows) but it would still be an object that we could call the same methods on.
If analogies help, you could think about my pet, Sushi, as an object. In particular, she is an ‘object’ of class ‘Cat’. She therefore shares some intrinsic characteristics with other objects of the same class (i.e. other cats), however she has attributes, such as ‘fur length’ or ‘eye color’, that could be different to other cats.
Importantly, she also comes with some ‘built in’ methods that we can perform on her, e.g. .stroke( ) .feed( ) or .playfight( ), which we’d also be able to perform on other cats. Of course, if we tried to call these methods on objects of other classes, such as Lamps, Bicycles, or Biscuits, then we’d get an error.
Or at least referred to a psychological clinician.
This is all well and good, though you may be wondering what on earth this has to do with data wrangling.
Well, here’s where things get interesting — Python lets you create your own Classes. This means that if you have data representations of things that are intrinsically similar, but with slight differences (such as our nested dictionaries containing all the match data), then it may be best to turn these into bespoke Python objects.
Suppose I want to create a new class ‘Match’. What might objects of this class look like? As mentioned above, each match object would have a set of attributes:
The players that played in the match for each team
The stats for that match (e.g. ball possession, number of tackles, etc.)
The commentary for that match
We could also define methods (remember, these are just ‘functions’, specific to the class). For example, we could have a method that outputted a dataframe showing the number of minutes each player played.
First things first, we have to define all of this in a way that Python will understand. Let’s build this definition up bit by bit.
A class definition will always start in more or less the same way:
class Match(object):
The first line tells Python that you are defining a class, in the same way that ‘def’ would tell Python that you’re defining a standalone function. The desired name of the class is given (standard formatting guidelines suggests you do this using Pascal Case), and then the phrase ‘object’ is put in parentheses.
The first thing to add to this class is something known as the ‘constructor’. Remember — the whole point of this is to turn a nested dictionary (of type ‘dictionary’) into a new object (of type ‘Match’). The constructor is the function built into the Match class that will create that new object.
class Match(object): def __init__(self, match):
The constructor’s syntax is the same, regardless of the class we’re defining. It is defined using the phrase __init__ (there are two underscores either side) and has two variables:
‘self’ (you can think of this as a dummy variable, which refers to the object we’re going to create).
‘match’ (this is simply a placeholder for the thing that will be used to create the new object, in our case the nested dictionary of match information).
The class’ constructor assigns attributes to a newly created object. Let’s start building these out for our ‘Match’ objects. Two basic attributes of each match are the unique match ID, and the week of the season that the match took place in. Both of these datapoints can be found in the first layer of our nested dictionaries:
class Match(object): def __init__(self, match): self.match_id = match['MatchID'] self.game_week = match['GameWeek']
So the above code simply tells our constructor that our new object’s match_id attribute should be equal to the value found under the input dictionary’s ‘MatchID’ key. The constructor can be quite flexible with attribute assignment:
class Match(object): def __init__(self, match): self.match_id = match['MatchID'] self.game_week = match['GameWeek'] self.home_team = match['Players']['HomeTeam'] self.away_team = match['Players']['AwayTeam'] self.teams = [self.home_team, self.away_team]
Notice how we created the ‘teams’ attribute by combining two attributes that we’d defined in the lines above? We can get more exotic with these attribution defintions — having defined an ‘events’ attribute (which extracts the list of commentary strings from the nested dictionary) we can then define a ‘goals’ attribute by filtering that list for commentary strings containing the phrase ‘Goal!’
class Match(object): def __init__(self, match): self.match_id = match['MatchID'] self.game_week = match['GameWeek'] self.home_team = match['Players']['HomeTeam'] self.away_team = match['Players']['AwayTeam'] self.teams = [self.home_team, self.away_team] self.events = match['Events'] self.goals = list(filter(lambda x: 'Goal!' in x, self.events))
We can continue adding all the different attributes we need in the same way.
Once we’re done, we can start creating (or ‘instantiating’, in the technical parlance) our actual Match objects. This is very easy— we simply take the match dictionary and do the following:
my_match_object = Match(my_match_dict)
Having done this, we can see that our object has all the attributes and methods built in as we would expect.
So now, instead of having to pass a bunch of annoying dictionary lookups (and worse) to get the data we need out of each match dictionary, we just call a simple method/attribute lookup on the match object.
At this point, it’s worth thinking about how we store these objects. Bearing in mind that a Premier League season has 760 games, storing each Match object with its own variable (as I did with the example above) is deeply impractical.
Exactly what object management strategy to pursue is up to the individual. Personally, it was enough to store the Match objects in a single list — I was able to create this using a simple list comprehension, since the match dictionaries were themselves already in a list.
match_object_list = [Match(i) for i in match_dict_list]
You could also store them in a dictionary, using the match ID as the key (using a dictionary comprehension).
{Match(i).match_id : Match(i) for i in match_dict_list}
You can also store objects as elements in a pandas dataframe if you’re feeling especially fancy.
Having created our Match class, there’s another class we could think about creating — Events. Remember, the strings in our match events are scraped from the match commentary on the Premier League website.
These event strings are similar, insomuch as they describe something that happened at a particular point during the match, and describe which players/teams did those things. But again, as strings, they’re not especially helpful for data analysis.
Wouldn’t it be nice if there was some way to take an event string, and automatically see which player it concerned, or what time the event took place, or what the outcome of the event was? Well, OOP can do just that! In this case, we can use another trick — subclasses.
Subclasses are a way of acknowledging that different classes can share some characteristics, but not others. As an example, let’s think about the different events in a football match — we could have shots, fouls, corner kicks, substitutions, and so forth. These events all share some characteristics, for example, they will all have a timestamp telling us when in the match they took place. So we could have an ‘Event’ class that has ‘time’ as an attribute.
However, there could be some characteristics that are specific to shots (e.g. where on the pitch the player shot from, or if the shot was a kick or a header). Evidently these attributes don’t make sense for ‘Substitution’ events. We may, therefore, want a ‘Shot’ class to capture this additional information.
Similarly, there are different types of shot — goals, saves, misses, and so forth, which may have specific attributes. Thus, we might want ‘Goal’, ‘Save’, and ‘Miss’ classes. You notice that we end up with a sort of tree of inter-connected classes:
-> Events -> Shots -> Goals -> Misses -> Saves -> Corners -> Fouls
Note — within this tree, although each additional ‘branch’ adds new attributes, it KEEPS the attributes of the layer above. So ‘Shots’ will keep the attributes that we define in the ‘Events’ class, and ‘Goals’ will keep the extra attributes that we define in the ‘Shots’ class.
This makes sense; every Goal is a type of Shot, and every Shot is a type of Event, so it's logical that Goals would have at least the same attributes as Events. This logic is the essence of ‘Class Inheritance’, and is one of the key motivators for us to use Subclasses. Whatsmore, we can implement this quite easily. Consider the following event string that describes a goal:
“64. Goal!Goal! Liverpool 4, Norwich City 1. Teemu Pukki (Norwich City) right footed shot from the centre of the box to the bottom left corner. Assisted by Emiliano Buendia with a through ball.”
We can declare our Event class in the same way as before, creating attributes to return the original event text (i.e. the above string), and the time during the match that it took place:
class Event(object): def __init__(self, event_string): self.event_text = str(event_string) self.time = event_string.split('.')[0]
We can then create a subclass, ‘Shot’, which is a particular type of event. Note, this time, instead of using the phrase ‘object’, we pass the name of the ‘superclass’ that we want our new subclass to inherit from (i.e. ‘Event’).
class Shot(Event): def __init__(self, event_string): super().__init__(event_string)
The super().__init__ phrase simply tells Python to look at all the attributes of the superclass whenever we instantiate a new ‘Shot’ object, as well as the ones we define especially in the new subclass (which we would define within the same __init__ constructor).
Of course, if we want to create a ‘Goal’ subclass, we can do the same again, substituting ‘Event’ for ‘Shot’ (since ‘Goal’ will be a subclass of ‘Shot’).
class Goal(Shot): def __init__(self, event_string): super().__init__(event_string)
n.b. I’ve not included the full Event class definition here— the cell runs to nearly 200 lines of code with more regex than is generally considered healthy in a single blog...
Recall from an earlier gif that the Match class has an attribute ‘goals’. This returns a list of strings, with each string being the commentary for an individual goal in that match.
Suppose we use one of the goals from the Match object to instantiate a Goal object, using our freshly coded ‘Goal’ class — remember we do this as follows:
my_goal = Goal(my_event_string)
Then we see that we can start pulling information about that goal directly from the Goal object:
Again, this is a considerably neater way of processing the data than trying to attack it with ad hoc functions, especially given the number of goals that we will have to analyse in this project!
This is just the tip of the iceberg of the sort of data management made possible with OOP. Just to give you a flavour, here’s a method I made for the Match class. Simply call .shots_table() on a Match object, and it produces a detailed pandas dataframe of all the shots taken during that match.
Given that I already have a list of match objects, you can see how, having put in the initial legwork with OOP, I could create a dataframe documenting every single shot taken in the Premier League this season with just a couple of lines of code:
df = pd.DataFrame()for match in match_object_list: df = pd.concat([df, match.shots_table()])
We’ve certainly come a long way from that list of nested dictionaries!
This is the latest post in my blog column ‘On Target’, in which I’ll be attempting to build out a model for ‘Moneyballing’ Fantasy Premier League. I’d love to hear any comments about the blog, or any of the concepts that the piece touches on. Feel free to leave a message below, or reach out to me through LinkedIn. | [
{
"code": null,
"e": 230,
"s": 172,
"text": "One of the dirty secrets of data science goes as follows:"
},
{
"code": null,
"e": 419,
"s": 230,
"text": "“Far from spending hours discovering glorious new algorithms and developing cutting edge neural networks, you will in fact spend most of your time cleaning, munging, and manipulating data”"
},
{
"code": null,
"e": 703,
"s": 419,
"text": "This is the result of a simple, inescapable truth — data in the real world doesn’t normally come nicely wrapped up in a Pandas dataframe with a pretty little bow on top. And since better quality data begets better quality models, it’s a part of the process that we can’t just ignore."
},
{
"code": null,
"e": 1013,
"s": 703,
"text": "Some time ago, I wrote a blog about techniques for wrangling data that, despite containing mistakes, was at least structured in a dataframe. But what if you don’t even have that? Recall my last blog from On Target — we were using Splinter to scrape data from match pages on the English Premier League website."
},
{
"code": null,
"e": 1036,
"s": 1013,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1297,
"s": 1036,
"text": "This has given us all the data that we notionally need for the analysis/model building that we want to do. But it’s not in the friendliest format — the scraping code that I wrote put everything into nested dictionaries, whose schemas look like a bit like this:"
},
{
"code": null,
"e": 1701,
"s": 1297,
"text": "MATCH_DICTIONARY-> MatchID (str)-> GameWeek (str)-> Events (long list of strings)-> Stats -> HomeStats (dictionary of team stats) -> AwayStats (dictionary of team stats)-> Players -> HomeTeam -> TeamName (str) -> StartingPlayers (list of strings) -> Subs (list of strings) -> AwayTeam -> TeamName (str) -> StartingPlayers (list of strings) -> Subs (list of strings)"
},
{
"code": null,
"e": 2121,
"s": 1701,
"text": "It’s worth noting that collecting this data as dictionaries in the first instance was not irrational — the number of ‘Events’ in each match is different from game to game, so we can’t store them nicely in a relational table. Moreover, the dictionary method means that the match data stays associated with the MatchID, which is the unique identifier for each game and will be important later on in the modelling process."
},
{
"code": null,
"e": 2484,
"s": 2121,
"text": "At any rate, we’re going to need to get at this data somehow, and put it into a model-friendly format. However, the code for manipulating nested dictionaries gets messy pretty quickly, and perhaps more dangerously, dictionaries are mutable data structures — i.e. their contents can be edited. Thus, keeping the data in its present dictionary form could be risky."
},
{
"code": null,
"e": 2551,
"s": 2484,
"text": "Happily, there is another way — Object Oriented Programming (OOP)."
},
{
"code": null,
"e": 2812,
"s": 2551,
"text": "Before diving into our specific example, let’s take a step back and think about ‘objects’ at a more conceptual level — particularly in the context of Python. You may be familiar with Python being an ‘Object Oriented Language’, but what does this actually mean?"
},
{
"code": null,
"e": 3084,
"s": 2812,
"text": "An ‘object’, very roughly speaking, is a thing in Python that we can store to our computer’s memory. So this could be a string, or a list, or a dictionary. It could also be something more abstract, such as a pandas dataframe, a matplotlib figure, or a scikit learn model."
},
{
"code": null,
"e": 3347,
"s": 3084,
"text": "One key characteristic of most objects is that we can perform ‘methods’ upon them. Methods are in-built functions that are specific to a particular type of object. For example, we can ‘call’ the .lower( ) method on a string to make all the characters lower case:"
},
{
"code": null,
"e": 3385,
"s": 3347,
"text": "IN: 'MyString'.lower()OUT: 'mystring'"
},
{
"code": null,
"e": 3596,
"s": 3385,
"text": "However, if we tried calling the .lower( ) method on a different type of object (for example, an integer) then we’d get an error — this method doesn’t make sense in the context of an object that isn’t a string."
},
{
"code": null,
"e": 3693,
"s": 3596,
"text": "This brings us onto the concept of ‘Classes’. In Python, a Class is a combination of two things:"
},
{
"code": null,
"e": 3711,
"s": 3693,
"text": "A type of object."
},
{
"code": null,
"e": 3783,
"s": 3711,
"text": "A series of ‘built in’ methods that we can call on that type of object."
},
{
"code": null,
"e": 4063,
"s": 3783,
"text": "‘String’ is an example of a Class in Python. We can create individual objects of type ‘String’ (e.g. “Hello World”, “MyString”, or “I Love Towards Data Science”), and we have a selection of methods that we can call on them. Importantly, these methods are ‘built into’ the object."
},
{
"code": null,
"e": 4534,
"s": 4063,
"text": "It’s also worth noting that objects often have attributes (which we can look up). For example, a pandas dataframe has a ‘shape’ attribute, which tells us how many rows and columns it has. Similarly, the names of its columns and its index are also attributes. Of course, the attributes of two objects of the same class can be different (a different dataframe may have more or fewer columns and rows) but it would still be an object that we could call the same methods on."
},
{
"code": null,
"e": 4866,
"s": 4534,
"text": "If analogies help, you could think about my pet, Sushi, as an object. In particular, she is an ‘object’ of class ‘Cat’. She therefore shares some intrinsic characteristics with other objects of the same class (i.e. other cats), however she has attributes, such as ‘fur length’ or ‘eye color’, that could be different to other cats."
},
{
"code": null,
"e": 5180,
"s": 4866,
"text": "Importantly, she also comes with some ‘built in’ methods that we can perform on her, e.g. .stroke( ) .feed( ) or .playfight( ), which we’d also be able to perform on other cats. Of course, if we tried to call these methods on objects of other classes, such as Lamps, Bicycles, or Biscuits, then we’d get an error."
},
{
"code": null,
"e": 5231,
"s": 5180,
"text": "Or at least referred to a psychological clinician."
},
{
"code": null,
"e": 5336,
"s": 5231,
"text": "This is all well and good, though you may be wondering what on earth this has to do with data wrangling."
},
{
"code": null,
"e": 5668,
"s": 5336,
"text": "Well, here’s where things get interesting — Python lets you create your own Classes. This means that if you have data representations of things that are intrinsically similar, but with slight differences (such as our nested dictionaries containing all the match data), then it may be best to turn these into bespoke Python objects."
},
{
"code": null,
"e": 5828,
"s": 5668,
"text": "Suppose I want to create a new class ‘Match’. What might objects of this class look like? As mentioned above, each match object would have a set of attributes:"
},
{
"code": null,
"e": 5879,
"s": 5828,
"text": "The players that played in the match for each team"
},
{
"code": null,
"e": 5952,
"s": 5879,
"text": "The stats for that match (e.g. ball possession, number of tackles, etc.)"
},
{
"code": null,
"e": 5982,
"s": 5952,
"text": "The commentary for that match"
},
{
"code": null,
"e": 6187,
"s": 5982,
"text": "We could also define methods (remember, these are just ‘functions’, specific to the class). For example, we could have a method that outputted a dataframe showing the number of minutes each player played."
},
{
"code": null,
"e": 6318,
"s": 6187,
"text": "First things first, we have to define all of this in a way that Python will understand. Let’s build this definition up bit by bit."
},
{
"code": null,
"e": 6385,
"s": 6318,
"text": "A class definition will always start in more or less the same way:"
},
{
"code": null,
"e": 6406,
"s": 6385,
"text": "class Match(object):"
},
{
"code": null,
"e": 6718,
"s": 6406,
"text": "The first line tells Python that you are defining a class, in the same way that ‘def’ would tell Python that you’re defining a standalone function. The desired name of the class is given (standard formatting guidelines suggests you do this using Pascal Case), and then the phrase ‘object’ is put in parentheses."
},
{
"code": null,
"e": 7015,
"s": 6718,
"text": "The first thing to add to this class is something known as the ‘constructor’. Remember — the whole point of this is to turn a nested dictionary (of type ‘dictionary’) into a new object (of type ‘Match’). The constructor is the function built into the Match class that will create that new object."
},
{
"code": null,
"e": 7070,
"s": 7015,
"text": "class Match(object): def __init__(self, match):"
},
{
"code": null,
"e": 7251,
"s": 7070,
"text": "The constructor’s syntax is the same, regardless of the class we’re defining. It is defined using the phrase __init__ (there are two underscores either side) and has two variables:"
},
{
"code": null,
"e": 7353,
"s": 7251,
"text": "‘self’ (you can think of this as a dummy variable, which refers to the object we’re going to create)."
},
{
"code": null,
"e": 7506,
"s": 7353,
"text": "‘match’ (this is simply a placeholder for the thing that will be used to create the new object, in our case the nested dictionary of match information)."
},
{
"code": null,
"e": 7833,
"s": 7506,
"text": "The class’ constructor assigns attributes to a newly created object. Let’s start building these out for our ‘Match’ objects. Two basic attributes of each match are the unique match ID, and the week of the season that the match took place in. Both of these datapoints can be found in the first layer of our nested dictionaries:"
},
{
"code": null,
"e": 7970,
"s": 7833,
"text": "class Match(object): def __init__(self, match): self.match_id = match['MatchID'] self.game_week = match['GameWeek']"
},
{
"code": null,
"e": 8202,
"s": 7970,
"text": "So the above code simply tells our constructor that our new object’s match_id attribute should be equal to the value found under the input dictionary’s ‘MatchID’ key. The constructor can be quite flexible with attribute assignment:"
},
{
"code": null,
"e": 8498,
"s": 8202,
"text": "class Match(object): def __init__(self, match): self.match_id = match['MatchID'] self.game_week = match['GameWeek'] self.home_team = match['Players']['HomeTeam'] self.away_team = match['Players']['AwayTeam'] self.teams = [self.home_team, self.away_team]"
},
{
"code": null,
"e": 8894,
"s": 8498,
"text": "Notice how we created the ‘teams’ attribute by combining two attributes that we’d defined in the lines above? We can get more exotic with these attribution defintions — having defined an ‘events’ attribute (which extracts the list of commentary strings from the nested dictionary) we can then define a ‘goals’ attribute by filtering that list for commentary strings containing the phrase ‘Goal!’"
},
{
"code": null,
"e": 9297,
"s": 8894,
"text": "class Match(object): def __init__(self, match): self.match_id = match['MatchID'] self.game_week = match['GameWeek'] self.home_team = match['Players']['HomeTeam'] self.away_team = match['Players']['AwayTeam'] self.teams = [self.home_team, self.away_team] self.events = match['Events'] self.goals = list(filter(lambda x: 'Goal!' in x, self.events))"
},
{
"code": null,
"e": 9374,
"s": 9297,
"text": "We can continue adding all the different attributes we need in the same way."
},
{
"code": null,
"e": 9564,
"s": 9374,
"text": "Once we’re done, we can start creating (or ‘instantiating’, in the technical parlance) our actual Match objects. This is very easy— we simply take the match dictionary and do the following:"
},
{
"code": null,
"e": 9603,
"s": 9564,
"text": "my_match_object = Match(my_match_dict)"
},
{
"code": null,
"e": 9712,
"s": 9603,
"text": "Having done this, we can see that our object has all the attributes and methods built in as we would expect."
},
{
"code": null,
"e": 9918,
"s": 9712,
"text": "So now, instead of having to pass a bunch of annoying dictionary lookups (and worse) to get the data we need out of each match dictionary, we just call a simple method/attribute lookup on the match object."
},
{
"code": null,
"e": 10152,
"s": 9918,
"text": "At this point, it’s worth thinking about how we store these objects. Bearing in mind that a Premier League season has 760 games, storing each Match object with its own variable (as I did with the example above) is deeply impractical."
},
{
"code": null,
"e": 10424,
"s": 10152,
"text": "Exactly what object management strategy to pursue is up to the individual. Personally, it was enough to store the Match objects in a single list — I was able to create this using a simple list comprehension, since the match dictionaries were themselves already in a list."
},
{
"code": null,
"e": 10480,
"s": 10424,
"text": "match_object_list = [Match(i) for i in match_dict_list]"
},
{
"code": null,
"e": 10589,
"s": 10480,
"text": "You could also store them in a dictionary, using the match ID as the key (using a dictionary comprehension)."
},
{
"code": null,
"e": 10645,
"s": 10589,
"text": "{Match(i).match_id : Match(i) for i in match_dict_list}"
},
{
"code": null,
"e": 10742,
"s": 10645,
"text": "You can also store objects as elements in a pandas dataframe if you’re feeling especially fancy."
},
{
"code": null,
"e": 10947,
"s": 10742,
"text": "Having created our Match class, there’s another class we could think about creating — Events. Remember, the strings in our match events are scraped from the match commentary on the Premier League website."
},
{
"code": null,
"e": 11194,
"s": 10947,
"text": "These event strings are similar, insomuch as they describe something that happened at a particular point during the match, and describe which players/teams did those things. But again, as strings, they’re not especially helpful for data analysis."
},
{
"code": null,
"e": 11464,
"s": 11194,
"text": "Wouldn’t it be nice if there was some way to take an event string, and automatically see which player it concerned, or what time the event took place, or what the outcome of the event was? Well, OOP can do just that! In this case, we can use another trick — subclasses."
},
{
"code": null,
"e": 11922,
"s": 11464,
"text": "Subclasses are a way of acknowledging that different classes can share some characteristics, but not others. As an example, let’s think about the different events in a football match — we could have shots, fouls, corner kicks, substitutions, and so forth. These events all share some characteristics, for example, they will all have a timestamp telling us when in the match they took place. So we could have an ‘Event’ class that has ‘time’ as an attribute."
},
{
"code": null,
"e": 12231,
"s": 11922,
"text": "However, there could be some characteristics that are specific to shots (e.g. where on the pitch the player shot from, or if the shot was a kick or a header). Evidently these attributes don’t make sense for ‘Substitution’ events. We may, therefore, want a ‘Shot’ class to capture this additional information."
},
{
"code": null,
"e": 12480,
"s": 12231,
"text": "Similarly, there are different types of shot — goals, saves, misses, and so forth, which may have specific attributes. Thus, we might want ‘Goal’, ‘Save’, and ‘Miss’ classes. You notice that we end up with a sort of tree of inter-connected classes:"
},
{
"code": null,
"e": 12574,
"s": 12480,
"text": "-> Events -> Shots -> Goals -> Misses -> Saves -> Corners -> Fouls"
},
{
"code": null,
"e": 12852,
"s": 12574,
"text": "Note — within this tree, although each additional ‘branch’ adds new attributes, it KEEPS the attributes of the layer above. So ‘Shots’ will keep the attributes that we define in the ‘Events’ class, and ‘Goals’ will keep the extra attributes that we define in the ‘Shots’ class."
},
{
"code": null,
"e": 13228,
"s": 12852,
"text": "This makes sense; every Goal is a type of Shot, and every Shot is a type of Event, so it's logical that Goals would have at least the same attributes as Events. This logic is the essence of ‘Class Inheritance’, and is one of the key motivators for us to use Subclasses. Whatsmore, we can implement this quite easily. Consider the following event string that describes a goal:"
},
{
"code": null,
"e": 13423,
"s": 13228,
"text": "“64. Goal!Goal! Liverpool 4, Norwich City 1. Teemu Pukki (Norwich City) right footed shot from the centre of the box to the bottom left corner. Assisted by Emiliano Buendia with a through ball.”"
},
{
"code": null,
"e": 13610,
"s": 13423,
"text": "We can declare our Event class in the same way as before, creating attributes to return the original event text (i.e. the above string), and the time during the match that it took place:"
},
{
"code": null,
"e": 13761,
"s": 13610,
"text": "class Event(object): def __init__(self, event_string): self.event_text = str(event_string) self.time = event_string.split('.')[0]"
},
{
"code": null,
"e": 13991,
"s": 13761,
"text": "We can then create a subclass, ‘Shot’, which is a particular type of event. Note, this time, instead of using the phrase ‘object’, we pass the name of the ‘superclass’ that we want our new subclass to inherit from (i.e. ‘Event’)."
},
{
"code": null,
"e": 14089,
"s": 13991,
"text": "class Shot(Event): def __init__(self, event_string): super().__init__(event_string)"
},
{
"code": null,
"e": 14353,
"s": 14089,
"text": "The super().__init__ phrase simply tells Python to look at all the attributes of the superclass whenever we instantiate a new ‘Shot’ object, as well as the ones we define especially in the new subclass (which we would define within the same __init__ constructor)."
},
{
"code": null,
"e": 14507,
"s": 14353,
"text": "Of course, if we want to create a ‘Goal’ subclass, we can do the same again, substituting ‘Event’ for ‘Shot’ (since ‘Goal’ will be a subclass of ‘Shot’)."
},
{
"code": null,
"e": 14600,
"s": 14507,
"text": "class Goal(Shot): def __init__(self, event_string): super().__init__(event_string)"
},
{
"code": null,
"e": 14776,
"s": 14600,
"text": "n.b. I’ve not included the full Event class definition here— the cell runs to nearly 200 lines of code with more regex than is generally considered healthy in a single blog..."
},
{
"code": null,
"e": 14958,
"s": 14776,
"text": "Recall from an earlier gif that the Match class has an attribute ‘goals’. This returns a list of strings, with each string being the commentary for an individual goal in that match."
},
{
"code": null,
"e": 15113,
"s": 14958,
"text": "Suppose we use one of the goals from the Match object to instantiate a Goal object, using our freshly coded ‘Goal’ class — remember we do this as follows:"
},
{
"code": null,
"e": 15145,
"s": 15113,
"text": "my_goal = Goal(my_event_string)"
},
{
"code": null,
"e": 15242,
"s": 15145,
"text": "Then we see that we can start pulling information about that goal directly from the Goal object:"
},
{
"code": null,
"e": 15437,
"s": 15242,
"text": "Again, this is a considerably neater way of processing the data than trying to attack it with ad hoc functions, especially given the number of goals that we will have to analyse in this project!"
},
{
"code": null,
"e": 15732,
"s": 15437,
"text": "This is just the tip of the iceberg of the sort of data management made possible with OOP. Just to give you a flavour, here’s a method I made for the Match class. Simply call .shots_table() on a Match object, and it produces a detailed pandas dataframe of all the shots taken during that match."
},
{
"code": null,
"e": 15978,
"s": 15732,
"text": "Given that I already have a list of match objects, you can see how, having put in the initial legwork with OOP, I could create a dataframe documenting every single shot taken in the Premier League this season with just a couple of lines of code:"
},
{
"code": null,
"e": 16074,
"s": 15978,
"text": "df = pd.DataFrame()for match in match_object_list: df = pd.concat([df, match.shots_table()])"
},
{
"code": null,
"e": 16145,
"s": 16074,
"text": "We’ve certainly come a long way from that list of nested dictionaries!"
}
] |
Collect.js | transform() Function - GeeksforGeeks | 04 Jun, 2020
The transform() function iterates over a collection and callback each item in the collection, the items inside the collection are replaced by the new callback values. It is similar to the JavaScript map() function but the values got replaced in transform() function.In JavaScript, the array is first converted to a collection and then the function is applied to the collection.
Syntax:
data.transform(item, key)
Parameters: This function accepts two parameter as mentioned above and described below:
item: This parameter holds the collection item.
key: This parameter holds new operational value.
Return Value: Returns an modified array which is created by this function.
Below examples illustrate the transform() function in collect.js
Example 1: Here in this example, we take a collection and then using the transform() function modified the values using the key transformation parameter and return the new value.
// It is used to import collect.js libraryconst collect = require('collect.js'); const data= collect([1, 2, 3, 4, 5]); data.transform((item, key) => item * 5); console.log(data.all());
Output:
[5 , 10 , 15 , 20 , 25 ]
Example 2: Same thing we have done here as above example.
// It is used to import collect.js libraryconst collect = require('collect.js'); const x= collect([10, 20, 30, 40, 50]); x.transform((item, key) => item / 10); console.log(x.all());
Output:
[1 , 2 , 3 , 4 , 5 ]
Reference: https://collect.js.org/api/transform.html
akhilsharma870
Collect.js
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 get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n04 Jun, 2020"
},
{
"code": null,
"e": 25287,
"s": 24909,
"text": "The transform() function iterates over a collection and callback each item in the collection, the items inside the collection are replaced by the new callback values. It is similar to the JavaScript map() function but the values got replaced in transform() function.In JavaScript, the array is first converted to a collection and then the function is applied to the collection."
},
{
"code": null,
"e": 25295,
"s": 25287,
"text": "Syntax:"
},
{
"code": null,
"e": 25321,
"s": 25295,
"text": "data.transform(item, key)"
},
{
"code": null,
"e": 25409,
"s": 25321,
"text": "Parameters: This function accepts two parameter as mentioned above and described below:"
},
{
"code": null,
"e": 25457,
"s": 25409,
"text": "item: This parameter holds the collection item."
},
{
"code": null,
"e": 25506,
"s": 25457,
"text": "key: This parameter holds new operational value."
},
{
"code": null,
"e": 25581,
"s": 25506,
"text": "Return Value: Returns an modified array which is created by this function."
},
{
"code": null,
"e": 25646,
"s": 25581,
"text": "Below examples illustrate the transform() function in collect.js"
},
{
"code": null,
"e": 25825,
"s": 25646,
"text": "Example 1: Here in this example, we take a collection and then using the transform() function modified the values using the key transformation parameter and return the new value."
},
{
"code": "// It is used to import collect.js libraryconst collect = require('collect.js'); const data= collect([1, 2, 3, 4, 5]); data.transform((item, key) => item * 5); console.log(data.all());",
"e": 26013,
"s": 25825,
"text": null
},
{
"code": null,
"e": 26021,
"s": 26013,
"text": "Output:"
},
{
"code": null,
"e": 26046,
"s": 26021,
"text": "[5 , 10 , 15 , 20 , 25 ]"
},
{
"code": null,
"e": 26104,
"s": 26046,
"text": "Example 2: Same thing we have done here as above example."
},
{
"code": "// It is used to import collect.js libraryconst collect = require('collect.js'); const x= collect([10, 20, 30, 40, 50]); x.transform((item, key) => item / 10); console.log(x.all());",
"e": 26289,
"s": 26104,
"text": null
},
{
"code": null,
"e": 26297,
"s": 26289,
"text": "Output:"
},
{
"code": null,
"e": 26318,
"s": 26297,
"text": "[1 , 2 , 3 , 4 , 5 ]"
},
{
"code": null,
"e": 26371,
"s": 26318,
"text": "Reference: https://collect.js.org/api/transform.html"
},
{
"code": null,
"e": 26386,
"s": 26371,
"text": "akhilsharma870"
},
{
"code": null,
"e": 26397,
"s": 26386,
"text": "Collect.js"
},
{
"code": null,
"e": 26408,
"s": 26397,
"text": "JavaScript"
},
{
"code": null,
"e": 26425,
"s": 26408,
"text": "Web Technologies"
},
{
"code": null,
"e": 26523,
"s": 26425,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26532,
"s": 26523,
"text": "Comments"
},
{
"code": null,
"e": 26545,
"s": 26532,
"text": "Old Comments"
},
{
"code": null,
"e": 26606,
"s": 26545,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26647,
"s": 26606,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 26701,
"s": 26647,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 26741,
"s": 26701,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26803,
"s": 26741,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 26859,
"s": 26803,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26892,
"s": 26859,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26954,
"s": 26892,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26997,
"s": 26954,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Replace repeating elements with greater that greatest values - GeeksforGeeks | 25 May, 2021
Given an integer array, if an integer is repeating then replace it with a number greater than that number that has not been inserted yet in the array.Examples:
Input : arr = {1, 3, 4, 5, 3}
Output : 1 3 4 5 6
Here 3 is repeating so it is replaced with 6
Input : arr = {1, 3, 4, 4, 5, 3}
Output : 1 3 4 6 5 7
We need to replace repeating numbers with a number that does not appear in the array and is one greater than the largest present in the array.Source: Paytm Interview Experience (Backend Developer).Calculate the maximum element in the array and replace the repeated elements with the maxx+1 and update the maxx element as visited. In the implementation, basic concept of hashing is used.
C++
Java
Python3
C#
Javascript
// CPP program to replace repeating elements// with greater than the greatest.#include <bits/stdc++.h>using namespace std; void replaceElements(int arr[], int n){ // Maximum element in an array int maxx = *max_element(arr, arr+n); unordered_set<int> s; for (int i = 0; i < n; i++) { // check whether the element is // repeated or not if (s.find(arr[i]) == s.end()) s.insert(arr[i]); else { // update the repeated element with the // maxx element arr[i] = maxx + 1; maxx++; // update the max // mark the maximum element as visited s.insert(maxx); } }} // Driver codeint main(){ int arr[] = { 1, 3, 4, 5, 3 }; int n = sizeof(arr)/sizeof(arr[0]); replaceElements(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;}
// Java program to replace repeating elements// with greater than the greatest.import java.util.*;class Solution{ //returns the maximum element static int max_element(int arr[]) { int max=arr[0]; for(int i=1;i<arr.length;i++) { if(max<arr[i]) max=arr[i]; } return max; } static void replaceElements(int arr[], int n){ // Maximum element in an array int maxx = max_element(arr); Vector<Integer> s=new Vector<Integer>(); for (int i = 0; i < n; i++) { // check whether the element is // repeated or not if (!s.contains(arr[i])) s.add(arr[i]); else { // update the repeated element with the // maxx element arr[i] = maxx + 1; maxx++; // update the max // mark the maximum element as visited s.add(maxx); } }} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 3, 4, 5, 3 }; int n = arr.length; replaceElements(arr, n); for (int i = 0; i < n; i++) System.out.print( arr[i] + " "); }}//contributed by Arnab Kundu
# Python 3 program to replace repeating# elements with greater than the greatest. def replaceElements( arr, n): # Maximum element in an array maxx = max(arr) s = [] for i in range (n) : # check whether the element is # repeated or not if arr[i] not in s: s.append(arr[i]) else: # update the repeated element # with the maxx element arr[i] = maxx + 1 maxx += 1 # update the max # mark the maximum element # as visited s.append(maxx) # Driver codeif __name__ =="__main__": arr = [ 1, 3, 4, 5, 3 ] n = len(arr) replaceElements(arr, n) for i in range( n): print (arr[i], end = " ") # This code is contributed by ita_c
// C# program to replace repeating elements// with greater than the greatest.using System;using System.Collections.Generic; class GFG{ //returns the maximum element static int max_element(int []arr) { int max = arr[0]; for(int i = 1; i < arr.Length; i++) { if(max < arr[i]) max = arr[i]; } return max; } static void replaceElements(int []arr, int n){ // Maximum element in an array int maxx = max_element(arr); List<int> s = new List<int>(); for (int i = 0; i < n; i++) { // check whether the element is // repeated or not if (!s.Contains(arr[i])) s.Add(arr[i]); else { // update the repeated element with the // maxx element arr[i] = maxx + 1; maxx++; // update the max // mark the maximum element as visited s.Add(maxx); } }} // Driver codepublic static void Main(){ int []arr = { 1, 3, 4, 5, 3 }; int n = arr.Length; replaceElements(arr, n); for (int i = 0; i < n; i++) Console.Write( arr[i] + " ");}} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to replace repeating elements// with greater than the greatest. //returns the maximum element function max_element(arr) { let max=arr[0]; for(let i=1;i<arr.length;i++) { if(max<arr[i]) max=arr[i]; } return max; } function replaceElements(arr,n) { // Maximum element in an array let maxx = max_element(arr); let s=[]; for (let i = 0; i < n; i++) { // check whether the element is // repeated or not if (!s.includes(arr[i])) s.push(arr[i]); else { // update the repeated element with the // maxx element arr[i] = maxx + 1; maxx++; // update the max // mark the maximum element as visited s.push(maxx); } } } // Driver code let arr=[1, 3, 4, 5, 3]; let n = arr.length; replaceElements(arr, n); for (let i = 0; i < n; i++) document.write( arr[i] + " "); // This code is contributed by rag2127 </script>
1 3 4 5 6
andrew1234
ukasp
princiraj1992
rag2127
cpp-unordered_set
Paytm
Technical Scripter 2018
Arrays
Hash
Paytm
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Python | Using 2D arrays/lists the right way
Given an array of size n and a number k, find all elements that appear more than n/k times
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining) | [
{
"code": null,
"e": 24719,
"s": 24691,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 24881,
"s": 24719,
"text": "Given an integer array, if an integer is repeating then replace it with a number greater than that number that has not been inserted yet in the array.Examples: "
},
{
"code": null,
"e": 25030,
"s": 24881,
"text": "Input : arr = {1, 3, 4, 5, 3}\nOutput : 1 3 4 5 6\nHere 3 is repeating so it is replaced with 6\n\nInput : arr = {1, 3, 4, 4, 5, 3}\nOutput : 1 3 4 6 5 7"
},
{
"code": null,
"e": 25419,
"s": 25030,
"text": "We need to replace repeating numbers with a number that does not appear in the array and is one greater than the largest present in the array.Source: Paytm Interview Experience (Backend Developer).Calculate the maximum element in the array and replace the repeated elements with the maxx+1 and update the maxx element as visited. In the implementation, basic concept of hashing is used. "
},
{
"code": null,
"e": 25423,
"s": 25419,
"text": "C++"
},
{
"code": null,
"e": 25428,
"s": 25423,
"text": "Java"
},
{
"code": null,
"e": 25436,
"s": 25428,
"text": "Python3"
},
{
"code": null,
"e": 25439,
"s": 25436,
"text": "C#"
},
{
"code": null,
"e": 25450,
"s": 25439,
"text": "Javascript"
},
{
"code": "// CPP program to replace repeating elements// with greater than the greatest.#include <bits/stdc++.h>using namespace std; void replaceElements(int arr[], int n){ // Maximum element in an array int maxx = *max_element(arr, arr+n); unordered_set<int> s; for (int i = 0; i < n; i++) { // check whether the element is // repeated or not if (s.find(arr[i]) == s.end()) s.insert(arr[i]); else { // update the repeated element with the // maxx element arr[i] = maxx + 1; maxx++; // update the max // mark the maximum element as visited s.insert(maxx); } }} // Driver codeint main(){ int arr[] = { 1, 3, 4, 5, 3 }; int n = sizeof(arr)/sizeof(arr[0]); replaceElements(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}",
"e": 26346,
"s": 25450,
"text": null
},
{
"code": "// Java program to replace repeating elements// with greater than the greatest.import java.util.*;class Solution{ //returns the maximum element static int max_element(int arr[]) { int max=arr[0]; for(int i=1;i<arr.length;i++) { if(max<arr[i]) max=arr[i]; } return max; } static void replaceElements(int arr[], int n){ // Maximum element in an array int maxx = max_element(arr); Vector<Integer> s=new Vector<Integer>(); for (int i = 0; i < n; i++) { // check whether the element is // repeated or not if (!s.contains(arr[i])) s.add(arr[i]); else { // update the repeated element with the // maxx element arr[i] = maxx + 1; maxx++; // update the max // mark the maximum element as visited s.add(maxx); } }} // Driver codepublic static void main(String args[]){ int arr[] = { 1, 3, 4, 5, 3 }; int n = arr.length; replaceElements(arr, n); for (int i = 0; i < n; i++) System.out.print( arr[i] + \" \"); }}//contributed by Arnab Kundu",
"e": 27520,
"s": 26346,
"text": null
},
{
"code": "# Python 3 program to replace repeating# elements with greater than the greatest. def replaceElements( arr, n): # Maximum element in an array maxx = max(arr) s = [] for i in range (n) : # check whether the element is # repeated or not if arr[i] not in s: s.append(arr[i]) else: # update the repeated element # with the maxx element arr[i] = maxx + 1 maxx += 1 # update the max # mark the maximum element # as visited s.append(maxx) # Driver codeif __name__ ==\"__main__\": arr = [ 1, 3, 4, 5, 3 ] n = len(arr) replaceElements(arr, n) for i in range( n): print (arr[i], end = \" \") # This code is contributed by ita_c",
"e": 28298,
"s": 27520,
"text": null
},
{
"code": "// C# program to replace repeating elements// with greater than the greatest.using System;using System.Collections.Generic; class GFG{ //returns the maximum element static int max_element(int []arr) { int max = arr[0]; for(int i = 1; i < arr.Length; i++) { if(max < arr[i]) max = arr[i]; } return max; } static void replaceElements(int []arr, int n){ // Maximum element in an array int maxx = max_element(arr); List<int> s = new List<int>(); for (int i = 0; i < n; i++) { // check whether the element is // repeated or not if (!s.Contains(arr[i])) s.Add(arr[i]); else { // update the repeated element with the // maxx element arr[i] = maxx + 1; maxx++; // update the max // mark the maximum element as visited s.Add(maxx); } }} // Driver codepublic static void Main(){ int []arr = { 1, 3, 4, 5, 3 }; int n = arr.Length; replaceElements(arr, n); for (int i = 0; i < n; i++) Console.Write( arr[i] + \" \");}} // This code is contributed by PrinciRaj1992",
"e": 29496,
"s": 28298,
"text": null
},
{
"code": "<script> // JavaScript program to replace repeating elements// with greater than the greatest. //returns the maximum element function max_element(arr) { let max=arr[0]; for(let i=1;i<arr.length;i++) { if(max<arr[i]) max=arr[i]; } return max; } function replaceElements(arr,n) { // Maximum element in an array let maxx = max_element(arr); let s=[]; for (let i = 0; i < n; i++) { // check whether the element is // repeated or not if (!s.includes(arr[i])) s.push(arr[i]); else { // update the repeated element with the // maxx element arr[i] = maxx + 1; maxx++; // update the max // mark the maximum element as visited s.push(maxx); } } } // Driver code let arr=[1, 3, 4, 5, 3]; let n = arr.length; replaceElements(arr, n); for (let i = 0; i < n; i++) document.write( arr[i] + \" \"); // This code is contributed by rag2127 </script>",
"e": 30619,
"s": 29496,
"text": null
},
{
"code": null,
"e": 30629,
"s": 30619,
"text": "1 3 4 5 6"
},
{
"code": null,
"e": 30642,
"s": 30631,
"text": "andrew1234"
},
{
"code": null,
"e": 30648,
"s": 30642,
"text": "ukasp"
},
{
"code": null,
"e": 30662,
"s": 30648,
"text": "princiraj1992"
},
{
"code": null,
"e": 30670,
"s": 30662,
"text": "rag2127"
},
{
"code": null,
"e": 30688,
"s": 30670,
"text": "cpp-unordered_set"
},
{
"code": null,
"e": 30694,
"s": 30688,
"text": "Paytm"
},
{
"code": null,
"e": 30718,
"s": 30694,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 30725,
"s": 30718,
"text": "Arrays"
},
{
"code": null,
"e": 30730,
"s": 30725,
"text": "Hash"
},
{
"code": null,
"e": 30736,
"s": 30730,
"text": "Paytm"
},
{
"code": null,
"e": 30743,
"s": 30736,
"text": "Arrays"
},
{
"code": null,
"e": 30748,
"s": 30743,
"text": "Hash"
},
{
"code": null,
"e": 30846,
"s": 30748,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30855,
"s": 30846,
"text": "Comments"
},
{
"code": null,
"e": 30868,
"s": 30855,
"text": "Old Comments"
},
{
"code": null,
"e": 30891,
"s": 30868,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 30923,
"s": 30891,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30944,
"s": 30923,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 30989,
"s": 30944,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 31080,
"s": 30989,
"text": "Given an array of size n and a number k, find all elements that appear more than n/k times"
},
{
"code": null,
"e": 31116,
"s": 31080,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 31147,
"s": 31116,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 31174,
"s": 31147,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 31208,
"s": 31174,
"text": "Hashing | Set 3 (Open Addressing)"
}
] |
Create a legend with Pandas and Matplotlib.pyplot | To create a legend with Pandas and matplotib.pyplot(), we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Make a two-dimensional, size-mutable, potentially heterogeneous tabular data.
Plot the dataframe instance with bar class by name and legend is True.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
df = pd.DataFrame({'Numbers': [3, 4, 1, 7, 8, 5], 'Frequency': [2, 4, 1, 4, 3, 2]})
df.plot(ax=ax, kind='bar', legend=True)
plt.show() | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "To create a legend with Pandas and matplotib.pyplot(), we can take the following steps −"
},
{
"code": null,
"e": 1227,
"s": 1151,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1305,
"s": 1227,
"text": "Make a two-dimensional, size-mutable, potentially heterogeneous tabular data."
},
{
"code": null,
"e": 1376,
"s": 1305,
"text": "Plot the dataframe instance with bar class by name and legend is True."
},
{
"code": null,
"e": 1418,
"s": 1376,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1726,
"s": 1418,
"text": "import pandas as pd\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig, ax = plt.subplots()\n\ndf = pd.DataFrame({'Numbers': [3, 4, 1, 7, 8, 5], 'Frequency': [2, 4, 1, 4, 3, 2]})\ndf.plot(ax=ax, kind='bar', legend=True)\n\nplt.show()"
}
] |
Explain the concept of Uninitialized array accessing in C language | In C language, is the program executed, if we use an uninitialized array?
If we use any uninitialized array, compiler will not generate any compilation and an execution error.
If we use any uninitialized array, compiler will not generate any compilation and an execution error.
If an array is uninitialized, you may get unpredictable result.
If an array is uninitialized, you may get unpredictable result.
So, it’s better we should always initialize the array elements with default values.
So, it’s better we should always initialize the array elements with default values.
Following is the C program of accessing an uninitialized array −
Live Demo
#include <stdio.h>
int main(void){
int a[4];
int b[4] = {1};
int c[4] = {1,2,3,4};
int i; //for loop counter
//printing all alements of all arrays
printf("\nArray a:\n");
for( i=0; i<4; i++ )
printf("arr[%d]: %d\n",i,a[i]);
printf("\nArray b:\n");
for( i=0; i<4; i++)
printf("arr[%d]: %d\n",i,b[i]);
printf("\nArray c:\n");
for( i=0; i<4; i++ )
printf("arr[%d]: %d\n",i, c[i]);
return 0;
}
When the above program is executed, it produces the following result −
Array a:
arr[0]: 4195872
arr[1]: 0
arr[2]: 4195408
arr[3]: 0
Array b:
arr[0]: 1
arr[1]: 0
arr[2]: 0
arr[3]: 0
Array c:
arr[0]: 1
arr[1]: 2
arr[2]: 3
arr[3]: 4
If we didn’t initialize an array, by default, it prints garbage values and never show an error.
Consider another C program for accessing an uninitialized array −
Live Demo
#include <stdio.h>
int main(void){
int A[4];
int B[4] ;
int C[4] = {1,2};
int i; //for loop counter
//printing all alements of all arrays
printf("\nArray a:\n");
for( i=0; i<4; i++ )
printf("arr[%d]: %d\n",i,A[i]);
printf("\nArray b:\n");
for( i=0; i<4; i++)
printf("arr[%d]: %d\n",i,B[i]);
printf("\nArray c:\n");
for( i=0; i<4; i++ )
printf("arr[%d]: %d\n",i, C[i]);
return 0;
}
When the above program is executed, it produces the following result −
Array a:
arr[0]: 4195856
arr[1]: 0
arr[2]: 4195408
arr[3]: 0
Array b:
arr[0]: -915120393
arr[1]: 32767
arr[2]: 0
arr[3]: 0
Array c:
arr[0]: 1
arr[1]: 2
arr[2]: 0
arr[3]: 0 | [
{
"code": null,
"e": 1136,
"s": 1062,
"text": "In C language, is the program executed, if we use an uninitialized array?"
},
{
"code": null,
"e": 1238,
"s": 1136,
"text": "If we use any uninitialized array, compiler will not generate any compilation and an execution error."
},
{
"code": null,
"e": 1340,
"s": 1238,
"text": "If we use any uninitialized array, compiler will not generate any compilation and an execution error."
},
{
"code": null,
"e": 1404,
"s": 1340,
"text": "If an array is uninitialized, you may get unpredictable result."
},
{
"code": null,
"e": 1468,
"s": 1404,
"text": "If an array is uninitialized, you may get unpredictable result."
},
{
"code": null,
"e": 1552,
"s": 1468,
"text": "So, it’s better we should always initialize the array elements with default values."
},
{
"code": null,
"e": 1636,
"s": 1552,
"text": "So, it’s better we should always initialize the array elements with default values."
},
{
"code": null,
"e": 1701,
"s": 1636,
"text": "Following is the C program of accessing an uninitialized array −"
},
{
"code": null,
"e": 1712,
"s": 1701,
"text": " Live Demo"
},
{
"code": null,
"e": 2156,
"s": 1712,
"text": "#include <stdio.h>\nint main(void){\n int a[4];\n int b[4] = {1};\n int c[4] = {1,2,3,4};\n int i; //for loop counter\n //printing all alements of all arrays\n printf(\"\\nArray a:\\n\");\n for( i=0; i<4; i++ )\n printf(\"arr[%d]: %d\\n\",i,a[i]);\n printf(\"\\nArray b:\\n\");\n for( i=0; i<4; i++)\n printf(\"arr[%d]: %d\\n\",i,b[i]);\n printf(\"\\nArray c:\\n\");\n for( i=0; i<4; i++ )\n printf(\"arr[%d]: %d\\n\",i, c[i]);\n return 0;\n}"
},
{
"code": null,
"e": 2227,
"s": 2156,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2388,
"s": 2227,
"text": "Array a:\narr[0]: 4195872\narr[1]: 0\narr[2]: 4195408\narr[3]: 0\n\nArray b:\narr[0]: 1\narr[1]: 0\narr[2]: 0\narr[3]: 0\n\nArray c:\narr[0]: 1\narr[1]: 2\narr[2]: 3\narr[3]: 4"
},
{
"code": null,
"e": 2484,
"s": 2388,
"text": "If we didn’t initialize an array, by default, it prints garbage values and never show an error."
},
{
"code": null,
"e": 2550,
"s": 2484,
"text": "Consider another C program for accessing an uninitialized array −"
},
{
"code": null,
"e": 2561,
"s": 2550,
"text": " Live Demo"
},
{
"code": null,
"e": 2996,
"s": 2561,
"text": "#include <stdio.h>\nint main(void){\n int A[4];\n int B[4] ;\n int C[4] = {1,2};\n int i; //for loop counter\n //printing all alements of all arrays\n printf(\"\\nArray a:\\n\");\n for( i=0; i<4; i++ )\n printf(\"arr[%d]: %d\\n\",i,A[i]);\n printf(\"\\nArray b:\\n\");\n for( i=0; i<4; i++)\n printf(\"arr[%d]: %d\\n\",i,B[i]);\n printf(\"\\nArray c:\\n\");\n for( i=0; i<4; i++ )\n printf(\"arr[%d]: %d\\n\",i, C[i]);\n return 0;\n}"
},
{
"code": null,
"e": 3067,
"s": 2996,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 3241,
"s": 3067,
"text": "Array a:\narr[0]: 4195856\narr[1]: 0\narr[2]: 4195408\narr[3]: 0\n\nArray b:\narr[0]: -915120393\narr[1]: 32767\narr[2]: 0\narr[3]: 0\n\nArray c:\narr[0]: 1\narr[1]: 2\narr[2]: 0\narr[3]: 0"
}
] |
Program to find last digit of n’th Fibonnaci Number in C++ | In this problem, we are given a number N. Our task is to create a Program to find last digit of Nth Fibonacci number in C++.
We need to find the last digit (i.e. LSB ) of the Nth Fibonacci number.
Let’s take an example to understand the problem,
Input: N = 120 Output: 1
A simple solution will be using the direct Fibonacci formula to find the Nth term. But this method will not be feasible when N is a large number. So to overcome this thing, we will use the property of the Fibonacci Series that the last digit repeats itself after 60 terms. I.e. The last digit of the 75th term is the same as that of the 135th term.
This means that working till 60 will give us all possible combinations and to find which term to use we will find the number’s mod with 60.
Live Demo
#include
using namespace std;
long int fibo(int N){
long int a=0,b=1,c;
for(int i=2; i< N;i++) {
c=a+b;
a=b;
b=c;
}
return c;
}
int findLastDigitNterm(int N) {
N = N % 60;
return ( fibo(N)%10);
}
int main() {
int N = 683;
cout<<"The last digit of "<<N<<"th Fibonacci term is "<<findLastDigitNterm(N);
return 0;
}
The last digit of 683th Fibonacci term is 1 | [
{
"code": null,
"e": 1187,
"s": 1062,
"text": "In this problem, we are given a number N. Our task is to create a Program to find last digit of Nth Fibonacci number in C++."
},
{
"code": null,
"e": 1259,
"s": 1187,
"text": "We need to find the last digit (i.e. LSB ) of the Nth Fibonacci number."
},
{
"code": null,
"e": 1308,
"s": 1259,
"text": "Let’s take an example to understand the problem,"
},
{
"code": null,
"e": 1333,
"s": 1308,
"text": "Input: N = 120 Output: 1"
},
{
"code": null,
"e": 1682,
"s": 1333,
"text": "A simple solution will be using the direct Fibonacci formula to find the Nth term. But this method will not be feasible when N is a large number. So to overcome this thing, we will use the property of the Fibonacci Series that the last digit repeats itself after 60 terms. I.e. The last digit of the 75th term is the same as that of the 135th term."
},
{
"code": null,
"e": 1822,
"s": 1682,
"text": "This means that working till 60 will give us all possible combinations and to find which term to use we will find the number’s mod with 60."
},
{
"code": null,
"e": 1833,
"s": 1822,
"text": " Live Demo"
},
{
"code": null,
"e": 2191,
"s": 1833,
"text": "#include\nusing namespace std;\nlong int fibo(int N){\n long int a=0,b=1,c;\n for(int i=2; i< N;i++) {\n c=a+b;\n a=b;\n b=c;\n }\n return c;\n}\nint findLastDigitNterm(int N) {\n N = N % 60;\n return ( fibo(N)%10);\n}\nint main() {\n int N = 683;\n cout<<\"The last digit of \"<<N<<\"th Fibonacci term is \"<<findLastDigitNterm(N);\n return 0;\n}"
},
{
"code": null,
"e": 2235,
"s": 2191,
"text": "The last digit of 683th Fibonacci term is 1"
}
] |
TestNG - Parameterized Test | Another interesting feature available in TestNG is parametric testing. In most cases, you'll come across a scenario where the business logic requires a hugely varying number of tests. Parameterized tests allow developers to run the same test over and over again using different values.
TestNG lets you pass parameters directly to your test methods in two different ways −
With testng.xml
With Data Providers
With this technique, you define the simple parameters in the testng.xml file and then reference those parameters in the source files. Let us have an example to demonstrate how to use this technique to pass parameters.
Create a java test class, say, ParameterizedTest1.java.
Create a java test class, say, ParameterizedTest1.java.
Add test method parameterTest() to your test class. This method takes a string as input parameter.
Add test method parameterTest() to your test class. This method takes a string as input parameter.
Add the annotation @Parameters("myName") to this method. The parameter would be passed a value from testng.xml, which we will see in the next step.
Add the annotation @Parameters("myName") to this method. The parameter would be passed a value from testng.xml, which we will see in the next step.
Create a java class file named ParameterizedTest1.java in /work/testng/src.
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class ParameterizedTest1 {
@Test
@Parameters("myName")
public void parameterTest(String myName) {
System.out.println("Parameterized value is : " + myName);
}
}
Create testng.xml in /work/testng/src to execute test case(s).
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1">
<test name = "test1">
<parameter name = "myName" value="manisha"/>
<classes>
<class name = "ParameterizedTest1" />
</classes>
</test>
</suite>
We can also define the parameters at the <suite> level. Suppose we have defined myName at both <suite> and <test> levels. In such cases, regular scoping rules apply. It means that any class inside <test> tag will see the value of parameter defined in <test>, while the classes in the rest of the testng.xml file will see the value defined in <suite>.
Compile the test case class using javac.
/work/testng/src$ javac ParameterizedTest1.java
Now, run testng.xml, which will run the parameterTest method. TestNG will try to find a parameter named myName first in the <test> tag, and then, if it can’t find it, it searches in the <suit> tag that encloses it.
/work/testng/src$ java org.testng.TestNG testng.xml
Verify the output.
Parameterized value is : manisha
===============================================
Suite1
Total tests run: 1, Failures: 0, Skips: 0
===============================================
TestNG will automatically try to convert the value specified in testng.xml to the type of your parameter. Here are the types supported −
String
int/Integer
boolean/Boolean
byte/Byte
char/Character
double/Double
float/Float
long/Long
short/Short
When you need to pass complex parameters or parameters that need to be created from Java (complex objects, objects read from a property file or a database, etc.), parameters can be passed using Dataproviders.
A Data Provider is a method annotated with @DataProvider. This annotation has only one string attribute: its name. If the name is not supplied, the data provider’s name automatically defaults to the method’s name. A data provider returns an array of objects.
The following examples demonstrate how to use data providers. The first example is about @DataProvider using Vector, String, or Integer as parameter, and the second example is about @DataProvider using object as parameter.
Here, the @DataProvider passes Integer and Boolean as parameter.
Create Java class
Create a java class called PrimeNumberChecker.java. This class checks if the number is prime. Create this class in /work/testng/src.
public class PrimeNumberChecker {
public Boolean validate(final Integer primeNumber) {
for (int i = 2; i < (primeNumber / 2); i++) {
if (primeNumber % i == 0) {
return false;
}
}
return true;
}
}
Create Test Case Class
Create a java test class, say, ParamTestWithDataProvider1.java in /work/testng/src.
Create a java test class, say, ParamTestWithDataProvider1.java in /work/testng/src.
Define the method primeNumbers(), which is defined as a Data provider using the annotation. This method returns an array of objects.
Define the method primeNumbers(), which is defined as a Data provider using the annotation. This method returns an array of objects.
Add the test method testPrimeNumberChecker() to your test class. This method takes an Integer and Boolean as input parameters. This method validates if the parameter passed is a prime number.
Add the test method testPrimeNumberChecker() to your test class. This method takes an Integer and Boolean as input parameters. This method validates if the parameter passed is a prime number.
Add the annotation @Test(dataProvider = "test1") to this method. The attribute dataProvider is mapped to "test1".
Add the annotation @Test(dataProvider = "test1") to this method. The attribute dataProvider is mapped to "test1".
Following are the contents of ParamTestWithDataProvider1.java.
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ParamTestWithDataProvider1 {
private PrimeNumberChecker primeNumberChecker;
@BeforeMethod
public void initialize() {
primeNumberChecker = new PrimeNumberChecker();
}
@DataProvider(name = "test1")
public static Object[][] primeNumbers() {
return new Object[][] {{2, true}, {6, false}, {19, true}, {22, false}, {23, true}};
}
// This test will run 4 times since we have 5 parameters defined
@Test(dataProvider = "test1")
public void testPrimeNumberChecker(Integer inputNumber, Boolean expectedResult) {
System.out.println(inputNumber + " " + expectedResult);
Assert.assertEquals(expectedResult, primeNumberChecker.validate(inputNumber));
}
}
Create testng.xml
Create a testng.xml /work/testng/src to execute Test case(s).
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1">
<test name = "test1">
<classes>
<class name = "ParamTestWithDataProvider1" />
</classes>
</test>
</suite>
Compile the Test case class using javac.
/work/testng/src$ javac ParamTestWithDataProvider1.java PrimeNumberChecker.java
Now, run testng.xml.
/work/testng/src$ java org.testng.TestNG testng.xml
Verify the output.
2 true
6 false
19 true
22 false
23 true
===============================================
Suite1
Total tests run: 5, Failures: 0, Skips: 0
===============================================
Here, the @DataProvider passes Object as parameter.
Create Java class
Create a java class Bean.java, which is a simple object with get/set methods, in /work/testng/src.
public class Bean {
private String val;
private int i;
public Bean(String val, int i) {
this.val = val;
this.i = i;
}
public String getVal() {
return val;
}
public void setVal(String val) {
this.val = val;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
Create Test Case Class
Create a java test class, say, ParamTestWithDataProvider2.java.
Create a java test class, say, ParamTestWithDataProvider2.java.
Define the method primeNumbers(), which is defined as a data provider using annotation. This method returns an array of object.
Define the method primeNumbers(), which is defined as a data provider using annotation. This method returns an array of object.
Add the test method testMethod() to your test class. This method takes an object bean as parameter.
Add the test method testMethod() to your test class. This method takes an object bean as parameter.
Add the annotation @Test(dataProvider = "test1") to this method. The attribute dataProvider is mapped to "test1".
Add the annotation @Test(dataProvider = "test1") to this method. The attribute dataProvider is mapped to "test1".
Create a java class file named ParamTestWithDataProvider2.java in /work/testng/src.
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ParamTestWithDataProvider2 {
@DataProvider(name = "test1")
public static Object[][] primeNumbers() {
return new Object[][] { { new Bean("hi I am the bean", 111) } };
}
@Test(dataProvider = "test1")
public void testMethod(Bean myBean) {
System.out.println(myBean.getVal() + " " + myBean.getI());
}
}
Create testng.xml
Create testng.xml in /work/testng/src to execute test case(s).
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1">
<test name = "test1">
<classes>
<class name = "ParamTestWithDataProvider2" />
</classes>
</test>
</suite>
Compile the test case class using javac.
/work/testng/src$ javac ParamTestWithDataProvider2.java Bean.java
Now, run testng.xml.
/work/testng/src$ java org.testng.TestNG testng.xml
Verify the output.
hi I am the bean 111
===============================================
Suite1
Total tests run: 1, Failures: 0, Skips: 0
===============================================
38 Lectures
4.5 hours
Lets Kode It
15 Lectures
1.5 hours
Quaatso Learning
28 Lectures
3 hours
Dezlearn Education
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2346,
"s": 2060,
"text": "Another interesting feature available in TestNG is parametric testing. In most cases, you'll come across a scenario where the business logic requires a hugely varying number of tests. Parameterized tests allow developers to run the same test over and over again using different values."
},
{
"code": null,
"e": 2432,
"s": 2346,
"text": "TestNG lets you pass parameters directly to your test methods in two different ways −"
},
{
"code": null,
"e": 2448,
"s": 2432,
"text": "With testng.xml"
},
{
"code": null,
"e": 2468,
"s": 2448,
"text": "With Data Providers"
},
{
"code": null,
"e": 2686,
"s": 2468,
"text": "With this technique, you define the simple parameters in the testng.xml file and then reference those parameters in the source files. Let us have an example to demonstrate how to use this technique to pass parameters."
},
{
"code": null,
"e": 2742,
"s": 2686,
"text": "Create a java test class, say, ParameterizedTest1.java."
},
{
"code": null,
"e": 2798,
"s": 2742,
"text": "Create a java test class, say, ParameterizedTest1.java."
},
{
"code": null,
"e": 2897,
"s": 2798,
"text": "Add test method parameterTest() to your test class. This method takes a string as input parameter."
},
{
"code": null,
"e": 2996,
"s": 2897,
"text": "Add test method parameterTest() to your test class. This method takes a string as input parameter."
},
{
"code": null,
"e": 3144,
"s": 2996,
"text": "Add the annotation @Parameters(\"myName\") to this method. The parameter would be passed a value from testng.xml, which we will see in the next step."
},
{
"code": null,
"e": 3292,
"s": 3144,
"text": "Add the annotation @Parameters(\"myName\") to this method. The parameter would be passed a value from testng.xml, which we will see in the next step."
},
{
"code": null,
"e": 3368,
"s": 3292,
"text": "Create a java class file named ParameterizedTest1.java in /work/testng/src."
},
{
"code": null,
"e": 3632,
"s": 3368,
"text": "import org.testng.annotations.Parameters;\nimport org.testng.annotations.Test;\n\npublic class ParameterizedTest1 {\n @Test\n @Parameters(\"myName\")\n public void parameterTest(String myName) {\n System.out.println(\"Parameterized value is : \" + myName);\n }\n}"
},
{
"code": null,
"e": 3695,
"s": 3632,
"text": "Create testng.xml in /work/testng/src to execute test case(s)."
},
{
"code": null,
"e": 4002,
"s": 3695,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n\n<suite name = \"Suite1\">\n <test name = \"test1\">\n\n <parameter name = \"myName\" value=\"manisha\"/>\n\n <classes>\n <class name = \"ParameterizedTest1\" />\n </classes>\n\n </test>\n</suite>"
},
{
"code": null,
"e": 4353,
"s": 4002,
"text": "We can also define the parameters at the <suite> level. Suppose we have defined myName at both <suite> and <test> levels. In such cases, regular scoping rules apply. It means that any class inside <test> tag will see the value of parameter defined in <test>, while the classes in the rest of the testng.xml file will see the value defined in <suite>."
},
{
"code": null,
"e": 4394,
"s": 4353,
"text": "Compile the test case class using javac."
},
{
"code": null,
"e": 4443,
"s": 4394,
"text": "/work/testng/src$ javac ParameterizedTest1.java\n"
},
{
"code": null,
"e": 4658,
"s": 4443,
"text": "Now, run testng.xml, which will run the parameterTest method. TestNG will try to find a parameter named myName first in the <test> tag, and then, if it can’t find it, it searches in the <suit> tag that encloses it."
},
{
"code": null,
"e": 4711,
"s": 4658,
"text": "/work/testng/src$ java org.testng.TestNG testng.xml\n"
},
{
"code": null,
"e": 4730,
"s": 4711,
"text": "Verify the output."
},
{
"code": null,
"e": 4910,
"s": 4730,
"text": "Parameterized value is : manisha\n\n===============================================\nSuite1\nTotal tests run: 1, Failures: 0, Skips: 0\n===============================================\n"
},
{
"code": null,
"e": 5047,
"s": 4910,
"text": "TestNG will automatically try to convert the value specified in testng.xml to the type of your parameter. Here are the types supported −"
},
{
"code": null,
"e": 5054,
"s": 5047,
"text": "String"
},
{
"code": null,
"e": 5066,
"s": 5054,
"text": "int/Integer"
},
{
"code": null,
"e": 5082,
"s": 5066,
"text": "boolean/Boolean"
},
{
"code": null,
"e": 5092,
"s": 5082,
"text": "byte/Byte"
},
{
"code": null,
"e": 5107,
"s": 5092,
"text": "char/Character"
},
{
"code": null,
"e": 5121,
"s": 5107,
"text": "double/Double"
},
{
"code": null,
"e": 5133,
"s": 5121,
"text": "float/Float"
},
{
"code": null,
"e": 5143,
"s": 5133,
"text": "long/Long"
},
{
"code": null,
"e": 5155,
"s": 5143,
"text": "short/Short"
},
{
"code": null,
"e": 5364,
"s": 5155,
"text": "When you need to pass complex parameters or parameters that need to be created from Java (complex objects, objects read from a property file or a database, etc.), parameters can be passed using Dataproviders."
},
{
"code": null,
"e": 5623,
"s": 5364,
"text": "A Data Provider is a method annotated with @DataProvider. This annotation has only one string attribute: its name. If the name is not supplied, the data provider’s name automatically defaults to the method’s name. A data provider returns an array of objects."
},
{
"code": null,
"e": 5846,
"s": 5623,
"text": "The following examples demonstrate how to use data providers. The first example is about @DataProvider using Vector, String, or Integer as parameter, and the second example is about @DataProvider using object as parameter."
},
{
"code": null,
"e": 5911,
"s": 5846,
"text": "Here, the @DataProvider passes Integer and Boolean as parameter."
},
{
"code": null,
"e": 5929,
"s": 5911,
"text": "Create Java class"
},
{
"code": null,
"e": 6062,
"s": 5929,
"text": "Create a java class called PrimeNumberChecker.java. This class checks if the number is prime. Create this class in /work/testng/src."
},
{
"code": null,
"e": 6313,
"s": 6062,
"text": "public class PrimeNumberChecker {\n public Boolean validate(final Integer primeNumber) {\n\n for (int i = 2; i < (primeNumber / 2); i++) {\n if (primeNumber % i == 0) {\n return false;\n }\n }\n return true;\n }\n}"
},
{
"code": null,
"e": 6336,
"s": 6313,
"text": "Create Test Case Class"
},
{
"code": null,
"e": 6420,
"s": 6336,
"text": "Create a java test class, say, ParamTestWithDataProvider1.java in /work/testng/src."
},
{
"code": null,
"e": 6504,
"s": 6420,
"text": "Create a java test class, say, ParamTestWithDataProvider1.java in /work/testng/src."
},
{
"code": null,
"e": 6637,
"s": 6504,
"text": "Define the method primeNumbers(), which is defined as a Data provider using the annotation. This method returns an array of objects."
},
{
"code": null,
"e": 6770,
"s": 6637,
"text": "Define the method primeNumbers(), which is defined as a Data provider using the annotation. This method returns an array of objects."
},
{
"code": null,
"e": 6962,
"s": 6770,
"text": "Add the test method testPrimeNumberChecker() to your test class. This method takes an Integer and Boolean as input parameters. This method validates if the parameter passed is a prime number."
},
{
"code": null,
"e": 7154,
"s": 6962,
"text": "Add the test method testPrimeNumberChecker() to your test class. This method takes an Integer and Boolean as input parameters. This method validates if the parameter passed is a prime number."
},
{
"code": null,
"e": 7268,
"s": 7154,
"text": "Add the annotation @Test(dataProvider = \"test1\") to this method. The attribute dataProvider is mapped to \"test1\"."
},
{
"code": null,
"e": 7382,
"s": 7268,
"text": "Add the annotation @Test(dataProvider = \"test1\") to this method. The attribute dataProvider is mapped to \"test1\"."
},
{
"code": null,
"e": 7445,
"s": 7382,
"text": "Following are the contents of ParamTestWithDataProvider1.java."
},
{
"code": null,
"e": 8309,
"s": 7445,
"text": "import org.testng.Assert;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\npublic class ParamTestWithDataProvider1 {\n private PrimeNumberChecker primeNumberChecker;\n\n @BeforeMethod\n public void initialize() {\n primeNumberChecker = new PrimeNumberChecker();\n }\n\n @DataProvider(name = \"test1\")\n public static Object[][] primeNumbers() {\n return new Object[][] {{2, true}, {6, false}, {19, true}, {22, false}, {23, true}};\n }\n\n // This test will run 4 times since we have 5 parameters defined\n @Test(dataProvider = \"test1\")\n public void testPrimeNumberChecker(Integer inputNumber, Boolean expectedResult) {\n System.out.println(inputNumber + \" \" + expectedResult);\n Assert.assertEquals(expectedResult, primeNumberChecker.validate(inputNumber));\n }\n}"
},
{
"code": null,
"e": 8327,
"s": 8309,
"text": "Create testng.xml"
},
{
"code": null,
"e": 8389,
"s": 8327,
"text": "Create a testng.xml /work/testng/src to execute Test case(s)."
},
{
"code": null,
"e": 8650,
"s": 8389,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n\n<suite name = \"Suite1\">\n <test name = \"test1\">\n <classes>\n <class name = \"ParamTestWithDataProvider1\" />\n </classes>\n </test>\n</suite>"
},
{
"code": null,
"e": 8691,
"s": 8650,
"text": "Compile the Test case class using javac."
},
{
"code": null,
"e": 8772,
"s": 8691,
"text": "/work/testng/src$ javac ParamTestWithDataProvider1.java PrimeNumberChecker.java\n"
},
{
"code": null,
"e": 8793,
"s": 8772,
"text": "Now, run testng.xml."
},
{
"code": null,
"e": 8846,
"s": 8793,
"text": "/work/testng/src$ java org.testng.TestNG testng.xml\n"
},
{
"code": null,
"e": 8865,
"s": 8846,
"text": "Verify the output."
},
{
"code": null,
"e": 9073,
"s": 8865,
"text": " 2 true\n 6 false\n 19 true\n 22 false\n 23 true\n\n===============================================\n Suite1\n Total tests run: 5, Failures: 0, Skips: 0\n===============================================\n"
},
{
"code": null,
"e": 9125,
"s": 9073,
"text": "Here, the @DataProvider passes Object as parameter."
},
{
"code": null,
"e": 9143,
"s": 9125,
"text": "Create Java class"
},
{
"code": null,
"e": 9242,
"s": 9143,
"text": "Create a java class Bean.java, which is a simple object with get/set methods, in /work/testng/src."
},
{
"code": null,
"e": 9601,
"s": 9242,
"text": "public class Bean {\n private String val;\n private int i;\n\n public Bean(String val, int i) {\n this.val = val;\n this.i = i;\n }\n\n public String getVal() {\n return val;\n }\n\n public void setVal(String val) {\n this.val = val;\n }\n\n public int getI() {\n return i;\n }\n\n public void setI(int i) {\n this.i = i;\n }\n}"
},
{
"code": null,
"e": 9624,
"s": 9601,
"text": "Create Test Case Class"
},
{
"code": null,
"e": 9688,
"s": 9624,
"text": "Create a java test class, say, ParamTestWithDataProvider2.java."
},
{
"code": null,
"e": 9752,
"s": 9688,
"text": "Create a java test class, say, ParamTestWithDataProvider2.java."
},
{
"code": null,
"e": 9880,
"s": 9752,
"text": "Define the method primeNumbers(), which is defined as a data provider using annotation. This method returns an array of object."
},
{
"code": null,
"e": 10008,
"s": 9880,
"text": "Define the method primeNumbers(), which is defined as a data provider using annotation. This method returns an array of object."
},
{
"code": null,
"e": 10108,
"s": 10008,
"text": "Add the test method testMethod() to your test class. This method takes an object bean as parameter."
},
{
"code": null,
"e": 10208,
"s": 10108,
"text": "Add the test method testMethod() to your test class. This method takes an object bean as parameter."
},
{
"code": null,
"e": 10322,
"s": 10208,
"text": "Add the annotation @Test(dataProvider = \"test1\") to this method. The attribute dataProvider is mapped to \"test1\"."
},
{
"code": null,
"e": 10436,
"s": 10322,
"text": "Add the annotation @Test(dataProvider = \"test1\") to this method. The attribute dataProvider is mapped to \"test1\"."
},
{
"code": null,
"e": 10520,
"s": 10436,
"text": "Create a java class file named ParamTestWithDataProvider2.java in /work/testng/src."
},
{
"code": null,
"e": 10944,
"s": 10520,
"text": "import org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\npublic class ParamTestWithDataProvider2 {\n @DataProvider(name = \"test1\")\n public static Object[][] primeNumbers() {\n return new Object[][] { { new Bean(\"hi I am the bean\", 111) } };\n }\n\n @Test(dataProvider = \"test1\")\n public void testMethod(Bean myBean) {\n System.out.println(myBean.getVal() + \" \" + myBean.getI());\n }\n}"
},
{
"code": null,
"e": 10962,
"s": 10944,
"text": "Create testng.xml"
},
{
"code": null,
"e": 11025,
"s": 10962,
"text": "Create testng.xml in /work/testng/src to execute test case(s)."
},
{
"code": null,
"e": 11286,
"s": 11025,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n\n<suite name = \"Suite1\">\n <test name = \"test1\">\n <classes>\n <class name = \"ParamTestWithDataProvider2\" />\n </classes>\n </test>\n</suite>"
},
{
"code": null,
"e": 11327,
"s": 11286,
"text": "Compile the test case class using javac."
},
{
"code": null,
"e": 11394,
"s": 11327,
"text": "/work/testng/src$ javac ParamTestWithDataProvider2.java Bean.java\n"
},
{
"code": null,
"e": 11415,
"s": 11394,
"text": "Now, run testng.xml."
},
{
"code": null,
"e": 11468,
"s": 11415,
"text": "/work/testng/src$ java org.testng.TestNG testng.xml\n"
},
{
"code": null,
"e": 11487,
"s": 11468,
"text": "Verify the output."
},
{
"code": null,
"e": 11664,
"s": 11487,
"text": " hi I am the bean 111\n\n===============================================\n Suite1\n Total tests run: 1, Failures: 0, Skips: 0\n===============================================\n"
},
{
"code": null,
"e": 11699,
"s": 11664,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11713,
"s": 11699,
"text": " Lets Kode It"
},
{
"code": null,
"e": 11748,
"s": 11713,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11766,
"s": 11748,
"text": " Quaatso Learning"
},
{
"code": null,
"e": 11799,
"s": 11766,
"text": "\n 28 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 11819,
"s": 11799,
"text": " Dezlearn Education"
},
{
"code": null,
"e": 11826,
"s": 11819,
"text": " Print"
},
{
"code": null,
"e": 11837,
"s": 11826,
"text": " Add Notes"
}
] |
How to select from table where conditions are set for id and name in MySQL? | Let us first create a table −
mysql> create table DemoTable819(
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName varchar(100)
);
Query OK, 0 rows affected (0.88 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable819(StudentName) values('Chris');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable819(StudentName) values('Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable819(StudentName) values('Adam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable819(StudentName) values('Mike');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable819(StudentName) values('Sam');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable819;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1 | Chris |
| 2 | Robert |
| 3 | Adam |
| 4 | Mike |
| 5 | Sam |
+-----------+-------------+
5 rows in set (0.00 sec)
Following is the query to select from the table where conditions are set for name and id −
mysql> select *from DemoTable819 where StudentName='Robert' and StudentId > 1;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 2 | Robert |
+-----------+-------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1248,
"s": 1092,
"text": "mysql> create table DemoTable819(\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentName varchar(100)\n);\nQuery OK, 0 rows affected (0.88 sec)"
},
{
"code": null,
"e": 1304,
"s": 1248,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1791,
"s": 1304,
"text": "mysql> insert into DemoTable819(StudentName) values('Chris');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable819(StudentName) values('Robert');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable819(StudentName) values('Adam');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable819(StudentName) values('Mike');\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable819(StudentName) values('Sam');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1851,
"s": 1791,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1885,
"s": 1851,
"text": "mysql> select *from DemoTable819;"
},
{
"code": null,
"e": 1926,
"s": 1885,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2203,
"s": 1926,
"text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 1 | Chris |\n| 2 | Robert |\n| 3 | Adam |\n| 4 | Mike |\n| 5 | Sam |\n+-----------+-------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2294,
"s": 2203,
"text": "Following is the query to select from the table where conditions are set for name and id −"
},
{
"code": null,
"e": 2373,
"s": 2294,
"text": "mysql> select *from DemoTable819 where StudentName='Robert' and StudentId > 1;"
},
{
"code": null,
"e": 2414,
"s": 2373,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2578,
"s": 2414,
"text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 2 | Robert |\n+-----------+-------------+\n1 row in set (0.00 sec)"
}
] |
Cordova - Vibration | This plugin is used for connecting to device's vibration functionality.
We can install this plugin in command prompt window by running the following code −
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-vibration
Once the plugin is installed we can add buttons in index.html that will be used later to trigger the vibration.
<button id = "vibration">VIBRATION</button>
<button id = "vibrationPattern">PATTERN</button>
Now we are going to add event listeners inside onDeviceReady in index.js.
document.getElementById("vibration").addEventListener("click", vibration);
document.getElementById("vibrationPattern").addEventListener("click", vibrationPattern);
This plugin is very easy to use. We will create two functions.
function vibration() {
var time = 3000;
navigator.vibrate(time);
}
function vibrationPattern() {
var pattern = [1000, 1000, 1000, 1000];
navigator.vibrate(pattern);
}
The first function is taking time parameter. This parameter is used for setting the duration of the vibration. Device will vibrate for three seconds once we press VIBRATION button.
The second function is using pattern parameter. This array will ask device to vibrate for one second, then wait for one second, then repeat the process again.
45 Lectures
2 hours
Skillbakerystudios
16 Lectures
1 hours
Nilay Mehta
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2252,
"s": 2180,
"text": "This plugin is used for connecting to device's vibration functionality."
},
{
"code": null,
"e": 2336,
"s": 2252,
"text": "We can install this plugin in command prompt window by running the following code −"
},
{
"code": null,
"e": 2422,
"s": 2336,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-vibration\n"
},
{
"code": null,
"e": 2534,
"s": 2422,
"text": "Once the plugin is installed we can add buttons in index.html that will be used later to trigger the vibration."
},
{
"code": null,
"e": 2627,
"s": 2534,
"text": "<button id = \"vibration\">VIBRATION</button>\n<button id = \"vibrationPattern\">PATTERN</button>"
},
{
"code": null,
"e": 2701,
"s": 2627,
"text": "Now we are going to add event listeners inside onDeviceReady in index.js."
},
{
"code": null,
"e": 2865,
"s": 2701,
"text": "document.getElementById(\"vibration\").addEventListener(\"click\", vibration);\ndocument.getElementById(\"vibrationPattern\").addEventListener(\"click\", vibrationPattern);"
},
{
"code": null,
"e": 2928,
"s": 2865,
"text": "This plugin is very easy to use. We will create two functions."
},
{
"code": null,
"e": 3108,
"s": 2928,
"text": "function vibration() {\n var time = 3000;\n navigator.vibrate(time);\n}\n\nfunction vibrationPattern() {\n var pattern = [1000, 1000, 1000, 1000];\n navigator.vibrate(pattern);\n}"
},
{
"code": null,
"e": 3289,
"s": 3108,
"text": "The first function is taking time parameter. This parameter is used for setting the duration of the vibration. Device will vibrate for three seconds once we press VIBRATION button."
},
{
"code": null,
"e": 3448,
"s": 3289,
"text": "The second function is using pattern parameter. This array will ask device to vibrate for one second, then wait for one second, then repeat the process again."
},
{
"code": null,
"e": 3481,
"s": 3448,
"text": "\n 45 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3501,
"s": 3481,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3534,
"s": 3501,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3547,
"s": 3534,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 3554,
"s": 3547,
"text": " Print"
},
{
"code": null,
"e": 3565,
"s": 3554,
"text": " Add Notes"
}
] |
How to use Singleton with Global Context in android? | Before getting into example, we should know what singleton design patter is. A singleton is a design pattern that restricts the instantiation of a class to only one instance. Notable uses include controlling concurrency, and creating a central point of access for an application to access its data store.
This example demonstrates How to use Singleton with Global Context in android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version>"1.0" encoding>"utf-8"?>
<LinearLayout 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"
android:orientation>"vertical">
<Button
android:id>"@+id/show"
android:text>"start dialog in singleTone"
android:layout_width>"wrap_content"
android:layout_height>"wrap_content" />
</LinearLayout>
In the above code, we have taken a button. When user click on show button, it will show toast using global context
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button show;
singleTonExample singletonexample;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = findViewById(R.id.show);
singletonexample = singleTonExample.getInstance();
singletonexample.init(getApplicationContext());
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(singleTonExample.get(),"Showing with global content",Toast.LENGTH_LONG).show();
}
});
}
}
In the above code, we have used singleTonExample as singleton class so create a call as singleTonExample.java and add the following code-
package com.example.andy.myapplication;
import android.app.Dialog;
import android.content.Context;
import android.view.Window;
public class singleTonExample {
private Context appContext;
private Dialog dialog;
private static final singleTonExample ourInstance > new singleTonExample();
public void init(Context context) {
if(appContext >> null) {
this.appContext > context;
}
}
private Context getContext() {
return appContext;
}
public static Context get() {
return getInstance().getContext();
}
public static synchronized singleTonExample getInstance() {
return ourInstance;
}
private singleTonExample() { }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Now click on above button, it will show toast using global context as shown below –
Click here to download the project code | [
{
"code": null,
"e": 1367,
"s": 1062,
"text": "Before getting into example, we should know what singleton design patter is. A singleton is a design pattern that restricts the instantiation of a class to only one instance. Notable uses include controlling concurrency, and creating a central point of access for an application to access its data store."
},
{
"code": null,
"e": 1445,
"s": 1367,
"text": "This example demonstrates How to use Singleton with Global Context in android"
},
{
"code": null,
"e": 1574,
"s": 1445,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1639,
"s": 1574,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2140,
"s": 1639,
"text": "<?xml version>\"1.0\" encoding>\"utf-8\"?>\n<LinearLayout xmlns:android>\"http://schemas.android.com/apk/res/android\"\n xmlns:tools>\"http://schemas.android.com/tools\"\n android:layout_width>\"match_parent\"\n android:layout_height>\"match_parent\"\n tools:context>\".MainActivity\"\n android:orientation>\"vertical\">\n <Button\n android:id>\"@+id/show\"\n android:text>\"start dialog in singleTone\"\n android:layout_width>\"wrap_content\"\n android:layout_height>\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2255,
"s": 2140,
"text": "In the above code, we have taken a button. When user click on show button, it will show toast using global context"
},
{
"code": null,
"e": 2312,
"s": 2255,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3178,
"s": 2312,
"text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n Button show;\n singleTonExample singletonexample;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n show = findViewById(R.id.show);\n singletonexample = singleTonExample.getInstance();\n singletonexample.init(getApplicationContext());\n show.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(singleTonExample.get(),\"Showing with global content\",Toast.LENGTH_LONG).show();\n }\n });\n }\n}"
},
{
"code": null,
"e": 3316,
"s": 3178,
"text": "In the above code, we have used singleTonExample as singleton class so create a call as singleTonExample.java and add the following code-"
},
{
"code": null,
"e": 4003,
"s": 3316,
"text": "package com.example.andy.myapplication;\nimport android.app.Dialog;\nimport android.content.Context;\nimport android.view.Window;\npublic class singleTonExample {\n private Context appContext;\n private Dialog dialog;\n private static final singleTonExample ourInstance > new singleTonExample();\n public void init(Context context) {\n if(appContext >> null) {\n this.appContext > context;\n }\n }\n private Context getContext() {\n return appContext;\n }\n public static Context get() {\n return getInstance().getContext();\n }\n public static synchronized singleTonExample getInstance() {\n return ourInstance;\n }\n private singleTonExample() { }\n}"
},
{
"code": null,
"e": 4350,
"s": 4003,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 4434,
"s": 4350,
"text": "Now click on above button, it will show toast using global context as shown below –"
},
{
"code": null,
"e": 4474,
"s": 4434,
"text": "Click here to download the project code"
}
] |
JavaScript - Array filter() Method | Javascript array filter() method creates a new array with all elements that pass the test implemented by the provided function.
Its syntax is as follows −
array.filter(callback[, thisObject]);
callback − Function to test each element of the array.
callback − Function to test each element of the array.
thisObject − Object to use as this when executing callback.
thisObject − Object to use as this when executing callback.
Returns created array.
This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script.
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisp*/) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
Try the following example.
<html>
<head>
<title>JavaScript Array filter Method</title>
</head>
<body>
<script type = "text/javascript">
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisp*/) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
function isBigEnough(element, index, array) {
return (element >= 10);
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
document.write("Filtered Value : " + filtered );
</script>
</body>
</html>
Filtered Value : 12,130,44
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2594,
"s": 2466,
"text": "Javascript array filter() method creates a new array with all elements that pass the test implemented by the provided function."
},
{
"code": null,
"e": 2621,
"s": 2594,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2660,
"s": 2621,
"text": "array.filter(callback[, thisObject]);\n"
},
{
"code": null,
"e": 2715,
"s": 2660,
"text": "callback − Function to test each element of the array."
},
{
"code": null,
"e": 2770,
"s": 2715,
"text": "callback − Function to test each element of the array."
},
{
"code": null,
"e": 2830,
"s": 2770,
"text": "thisObject − Object to use as this when executing callback."
},
{
"code": null,
"e": 2890,
"s": 2830,
"text": "thisObject − Object to use as this when executing callback."
},
{
"code": null,
"e": 2913,
"s": 2890,
"text": "Returns created array."
},
{
"code": null,
"e": 3128,
"s": 2913,
"text": "This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script."
},
{
"code": null,
"e": 3621,
"s": 3128,
"text": "if (!Array.prototype.filter) {\n Array.prototype.filter = function(fun /*, thisp*/) {\n var len = this.length;\n if (typeof fun != \"function\")\n throw new TypeError();\n \n var res = new Array();\n var thisp = arguments[1];\n for (var i = 0; i < len; i++) {\n if (i in this) {\n var val = this[i]; // in case fun mutates this\n if (fun.call(thisp, val, i, this))\n res.push(val);\n }\n }\n return res;\n };\n}"
},
{
"code": null,
"e": 3648,
"s": 3621,
"text": "Try the following example."
},
{
"code": null,
"e": 4731,
"s": 3648,
"text": "<html>\n <head>\n <title>JavaScript Array filter Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n if (!Array.prototype.filter) {\n Array.prototype.filter = function(fun /*, thisp*/) {\n var len = this.length;\n \n if (typeof fun != \"function\")\n throw new TypeError();\n \n var res = new Array();\n var thisp = arguments[1];\n \n for (var i = 0; i < len; i++) {\n if (i in this) {\n var val = this[i]; // in case fun mutates this\n if (fun.call(thisp, val, i, this))\n res.push(val);\n }\n }\n return res;\n };\n }\n function isBigEnough(element, index, array) {\n return (element >= 10);\n }\n var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);\n document.write(\"Filtered Value : \" + filtered ); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 4760,
"s": 4731,
"text": "Filtered Value : 12,130,44 \n"
},
{
"code": null,
"e": 4795,
"s": 4760,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4809,
"s": 4795,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4843,
"s": 4809,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4857,
"s": 4843,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4892,
"s": 4857,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4909,
"s": 4892,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4944,
"s": 4909,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4961,
"s": 4944,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4994,
"s": 4961,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5022,
"s": 4994,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5056,
"s": 5022,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 5084,
"s": 5056,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5091,
"s": 5084,
"text": " Print"
},
{
"code": null,
"e": 5102,
"s": 5091,
"text": " Add Notes"
}
] |
Perl - Loops | There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −
Perl programming language provides the following types of loop to handle the looping requirements.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Repeats a statement or group of statements until a given condition becomes true. It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn.
Like a while statement, except that it tests the condition at the end of the loop body
You can use one or more loop inside any another while, for or do..while loop.
Loop control statements change the execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Perl supports the following control statements. Click the following links to check their detail.
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Terminates the loop statement and transfers execution to the statement immediately following the loop.
A continue BLOCK, it is always executed just before the conditional is about to be evaluated again.
The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed.
Perl supports a goto command with three forms: goto label, goto expr, and goto &name.
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.
#!/usr/local/bin/perl
for( ; ; ) {
printf "This loop will run forever.\n";
}
You can terminate the above infinite loop by pressing the Ctrl + C keys.
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but as a programmer more commonly use the for (;;) construct to signify an infinite loop.
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2449,
"s": 2220,
"text": "There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on."
},
{
"code": null,
"e": 2555,
"s": 2449,
"text": "Programming languages provide various control structures that allow for more complicated execution paths."
},
{
"code": null,
"e": 2736,
"s": 2555,
"text": "A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −"
},
{
"code": null,
"e": 2835,
"s": 2736,
"text": "Perl programming language provides the following types of loop to handle the looping requirements."
},
{
"code": null,
"e": 2966,
"s": 2835,
"text": "Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body."
},
{
"code": null,
"e": 3102,
"s": 2966,
"text": "Repeats a statement or group of statements until a given condition becomes true. It tests the condition before executing the loop body."
},
{
"code": null,
"e": 3208,
"s": 3102,
"text": "Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable."
},
{
"code": null,
"e": 3325,
"s": 3208,
"text": "The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn."
},
{
"code": null,
"e": 3412,
"s": 3325,
"text": "Like a while statement, except that it tests the condition at the end of the loop body"
},
{
"code": null,
"e": 3490,
"s": 3412,
"text": "You can use one or more loop inside any another while, for or do..while loop."
},
{
"code": null,
"e": 3661,
"s": 3490,
"text": "Loop control statements change the execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed."
},
{
"code": null,
"e": 3758,
"s": 3661,
"text": "Perl supports the following control statements. Click the following links to check their detail."
},
{
"code": null,
"e": 3867,
"s": 3758,
"text": "Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating."
},
{
"code": null,
"e": 3970,
"s": 3867,
"text": "Terminates the loop statement and transfers execution to the statement immediately following the loop."
},
{
"code": null,
"e": 4070,
"s": 3970,
"text": "A continue BLOCK, it is always executed just before the conditional is about to be evaluated again."
},
{
"code": null,
"e": 4198,
"s": 4070,
"text": "The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed."
},
{
"code": null,
"e": 4284,
"s": 4198,
"text": "Perl supports a goto command with three forms: goto label, goto expr, and goto &name."
},
{
"code": null,
"e": 4549,
"s": 4284,
"text": "A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty."
},
{
"code": null,
"e": 4631,
"s": 4549,
"text": "#!/usr/local/bin/perl\n \nfor( ; ; ) {\n printf \"This loop will run forever.\\n\";\n}"
},
{
"code": null,
"e": 4704,
"s": 4631,
"text": "You can terminate the above infinite loop by pressing the Ctrl + C keys."
},
{
"code": null,
"e": 4920,
"s": 4704,
"text": "When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but as a programmer more commonly use the for (;;) construct to signify an infinite loop."
},
{
"code": null,
"e": 4955,
"s": 4920,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4969,
"s": 4955,
"text": " Devi Killada"
},
{
"code": null,
"e": 5004,
"s": 4969,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5024,
"s": 5004,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 5057,
"s": 5024,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5073,
"s": 5057,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5106,
"s": 5073,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5123,
"s": 5106,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 5156,
"s": 5123,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5179,
"s": 5156,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5214,
"s": 5179,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5237,
"s": 5214,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 5244,
"s": 5237,
"text": " Print"
},
{
"code": null,
"e": 5255,
"s": 5244,
"text": " Add Notes"
}
] |
numpy.random.dirichlet() in Python - GeeksforGeeks | 15 Jul, 2020
With the help of dirichlet() method, we can get the random samples from dirichlet distribution and return the numpy array of some random samples by using this method.
Syntax : numpy.random.dirichlet(alpha, size=None)
Parameters :
1) alpha – number of samples.
2) size – output shape of a numpy array.
Return : Return the random samples array.
Example #1 :
In this example we can see that by using random.dirichlet() method, we are able to get the random samples of dirichlet distribution and return the numpy array having size defined in the parameters.
Python3
# import dirichletimport numpy as npimport matplotlib.pyplot as plt # Using dirichlet() methodgfg = np.random.dirichlet((3, 4, 5, 19), size = 1000) count, bins, ignored = plt.hist(gfg, 30, density = True)plt.show()
Output :
Example #2 :
Python3
# import dirichletimport numpy as npimport matplotlib.pyplot as plt # Using dirichlet() methodgfg = np.random.dirichlet((6, 5, 4, 3, 2, 1), 1000) count, bins, ignored = plt.hist(gfg, 30, density = True)plt.show()
Output :
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24483,
"s": 24455,
"text": "\n15 Jul, 2020"
},
{
"code": null,
"e": 24650,
"s": 24483,
"text": "With the help of dirichlet() method, we can get the random samples from dirichlet distribution and return the numpy array of some random samples by using this method."
},
{
"code": null,
"e": 24700,
"s": 24650,
"text": "Syntax : numpy.random.dirichlet(alpha, size=None)"
},
{
"code": null,
"e": 24713,
"s": 24700,
"text": "Parameters :"
},
{
"code": null,
"e": 24743,
"s": 24713,
"text": "1) alpha – number of samples."
},
{
"code": null,
"e": 24784,
"s": 24743,
"text": "2) size – output shape of a numpy array."
},
{
"code": null,
"e": 24826,
"s": 24784,
"text": "Return : Return the random samples array."
},
{
"code": null,
"e": 24839,
"s": 24826,
"text": "Example #1 :"
},
{
"code": null,
"e": 25037,
"s": 24839,
"text": "In this example we can see that by using random.dirichlet() method, we are able to get the random samples of dirichlet distribution and return the numpy array having size defined in the parameters."
},
{
"code": null,
"e": 25045,
"s": 25037,
"text": "Python3"
},
{
"code": "# import dirichletimport numpy as npimport matplotlib.pyplot as plt # Using dirichlet() methodgfg = np.random.dirichlet((3, 4, 5, 19), size = 1000) count, bins, ignored = plt.hist(gfg, 30, density = True)plt.show()",
"e": 25262,
"s": 25045,
"text": null
},
{
"code": null,
"e": 25271,
"s": 25262,
"text": "Output :"
},
{
"code": null,
"e": 25284,
"s": 25271,
"text": "Example #2 :"
},
{
"code": null,
"e": 25292,
"s": 25284,
"text": "Python3"
},
{
"code": "# import dirichletimport numpy as npimport matplotlib.pyplot as plt # Using dirichlet() methodgfg = np.random.dirichlet((6, 5, 4, 3, 2, 1), 1000) count, bins, ignored = plt.hist(gfg, 30, density = True)plt.show()",
"e": 25507,
"s": 25292,
"text": null
},
{
"code": null,
"e": 25516,
"s": 25507,
"text": "Output :"
},
{
"code": null,
"e": 25536,
"s": 25516,
"text": "Python numpy-Random"
},
{
"code": null,
"e": 25549,
"s": 25536,
"text": "Python-numpy"
},
{
"code": null,
"e": 25556,
"s": 25549,
"text": "Python"
},
{
"code": null,
"e": 25654,
"s": 25556,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25663,
"s": 25654,
"text": "Comments"
},
{
"code": null,
"e": 25676,
"s": 25663,
"text": "Old Comments"
},
{
"code": null,
"e": 25694,
"s": 25676,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25729,
"s": 25694,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 25751,
"s": 25729,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25783,
"s": 25751,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25813,
"s": 25783,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 25855,
"s": 25813,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25881,
"s": 25855,
"text": "Python String | replace()"
},
{
"code": null,
"e": 25924,
"s": 25881,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 25968,
"s": 25924,
"text": "Reading and Writing to text files in Python"
}
] |
Federated Learning: A Simple Implementation of FedAvg (Federated Averaging) with PyTorch | by Ece Işık Polat | Towards Data Science | Mobile devices such as phones, tablets, and smartwatches are now primary computing devices and have become integral for many people. These devices host huge amounts of valuable and private data thanks to the combination of rich user interactions and powerful sensors. Models trained on such data could significantly improve the usability and power of intelligent applications. However, the sensitive nature of this data means there are also some risks and responsibilities [1]. At this point, the Federated Learning (FL) concept comes into play.
In FL, each client trains its model decentrally. In other words, the model training process is carried out separately for each client. Only learned model parameters are sent to a trusted center to combine and feed the aggregated main model. Then the trusted center sent back the aggregated main model back to these clients, and this process is circulated [2].
In this context, I prepared a simple implementation with IID (independent and identically distributed) data to show how the parameters of hundreds of different models that are running on different nodes can be combined with the FedAvg method and whether this model will give a reasonable result. This implementation was carried out on the MNIST Data set. The MNIST data set contains 28 * 28 pixel grayscale images of numbers from 0 to 9 [3].
The MNIST data set does not contain each label equally. Therefore, to fulfill the IID requirement, the dataset was grouped, shuffled, and then distributed so that each node contains an equal number of each label.
A simple 2-layer model was created for the classification process.
Functions to be used for FedAvg are defined.
Here, an iteration is completed as follows.
Since the parameters of the main model and parameters of all local models in the nodes are randomly initialized, all these parameters will be different from each other. For this reason, the main model sends its parameters to the nodes before the training of local models in the nodes begins.Nodes start to train their local models over their own data by using these parameters.Each node updates its parameters while training its own model. After the training process is completed, each node sends its parameters to the main model.The main model takes the average of these parameters and sets them as its new weight parameters and passes them back to the nodes for the next iteration.
Since the parameters of the main model and parameters of all local models in the nodes are randomly initialized, all these parameters will be different from each other. For this reason, the main model sends its parameters to the nodes before the training of local models in the nodes begins.
Nodes start to train their local models over their own data by using these parameters.
Each node updates its parameters while training its own model. After the training process is completed, each node sends its parameters to the main model.
The main model takes the average of these parameters and sets them as its new weight parameters and passes them back to the nodes for the next iteration.
The above flow is for one iteration. This iteration can be repeated over and over to improve the performance of the main model.
Note: The purpose here is not to increase the performance of the classification algorithm, but to compare the performance of the model obtained with federated learning with a centralized model. If you wish, you can use more complicated models or adjust hyperparameters to improve performance.
And if you are ready, here we go!
Functions for data distribution
split_and_shuffle_labels(y_data, seed, amount): The data set does not contain an equal number of each label. In order to distribute the data to the nodes as IID, an equal number of them must be taken. This function groups them as much as the amount given from each label and shuffles the order within itself. Please be aware that, what shuffled here is the indexes of the data, we will use them when retrieving the data in the future. But these indexes need to be reset to avoid key errors. Therefore, a new column has been defined and shuffled indexes are kept there.
get_iid_subsamples_indices(label_dict, number_of_samples, amount): This function divides the indexes in each node with an equal number of each label. (Here the indexes are still distributed, not data)
create_iid_subsamples(sample_dict, x_data, y_data, x_name, y_name): This function distributes x and y data to nodes in dictionary.
Functions for FedAvg
create_model_optimizer_criterion_dict(number_of_samples): This function creates a model, optimizer and loss function for each node.
get_averaged_weights(model_dict, number_of_samples): This function takes the average of the weights in individual nodes.
set_averaged_weights_as_main_model_weights_and_update_main_model(main_model,model_dict, number_of_samples): This function sends the averaged weights of individual nodes to the main model and sets them as the new weights of the main model. ( calls def get_averaged_weights(model_dict, number_of_samples))
compare_local_and_merged_model_performance(number_of_samples: This function compares the accuracy of the main model and the local model running on each node.
send_main_model_to_nodes_and_update_model_dict(main_model, model_dict, number_of_samples): This function sends the parameters of the main model to the nodes.
start_train_end_node_process_without_print(): This function trains individual local models in nodes.
First, let’s examine what would the performance of the centralized model be if the data were not distributed to nodes at all?
— — — Centralized Model — — — epoch: 1 | train accuracy: 0.8743 | test accuracy: 0.9437epoch: 2 | train accuracy: 0.9567 | test accuracy: 0.9654epoch: 3 | train accuracy: 0.9712 | test accuracy: 0.9701epoch: 4 | train accuracy: 0.9785 | test accuracy: 0.9738epoch: 5 | train accuracy: 0.9834 | test accuracy: 0.9713epoch: 6 | train accuracy: 0.9864 | test accuracy: 0.9768epoch: 7 | train accuracy: 0.9898 | test accuracy: 0.9763epoch: 8 | train accuracy: 0.9923 | test accuracy: 0.9804epoch: 9 | train accuracy: 0.9941 | test accuracy: 0.9784epoch: 10 | train accuracy: 0.9959 | test accuracy: 0.9792 — — — Training finished — — -
The model used in this example is very simple, different improvements can be performed to increase model performance, such as using more complex models, increasing epoch or hyperparameter tuning. However, the purpose here is to compare the performance of the main model that is formed by combining the parameters of the local models trained on their own data with a centralized model that trained on all training data. In this way, we can gain insight into the capacity of federated learning.
Then, start our first iteration
Data is distributed to nodes
The main model is created
Models, optimizers, and loss functions in nodes are defined
Keys of dicts are being made iterable
Parameters of the main model are sent to nodesSince the parameters of the main model and parameters of all local models in the nodes are randomly initialized, all these parameters will be different from each other. For this reason, the main model sends its parameters to the nodes before the training of local models in the nodes begins. You can check the weights below.
Models in the nodes are trained
Federated main model vs centralized model before 1st iteration (on all test data)Since the main model is randomly initialized and no action taken on it yet, before first iteration its performance is very poor. After first iteration, the accuracy of main model increased to %85.
Before 1st iteration main model accuracy on all test data: 0.1180After 1st iteration main model accuracy on all test data: 0.8529Centralized model accuracy on all test data: 0.9790
This is a single iteration, we can send the parameters of the main model back to the nodes and repeat the above steps. Now let’s check how the performance of the main model improves when we repeat the iteration 10 more times.
Iteration 2 : main_model accuracy on all test data: 0.8928Iteration 3 : main_model accuracy on all test data: 0.9073Iteration 4 : main_model accuracy on all test data: 0.9150Iteration 5 : main_model accuracy on all test data: 0.9209Iteration 6 : main_model accuracy on all test data: 0.9273Iteration 7 : main_model accuracy on all test data: 0.9321Iteration 8 : main_model accuracy on all test data: 0.9358Iteration 9 : main_model accuracy on all test data: 0.9382Iteration 10 : main_model accuracy on all test data: 0.9411Iteration 11 : main_model accuracy on all test data: 0.9431
The accuracy of the centralized model was calculated as approximately 98%. The accuracy of the main model obtained by FedAvg method started from 85% and improved to 94%. In this case, we can say that although the main model obtained by FedAvg method was trained without seeing the data, its performance cannot be underestimated.
You can visit the https://github.com/eceisik/fl_public/blob/master/fedavg_mnist_iid.ipynb to see the full implementation.
*You can visit the github page.
[1] J. Konečný, H. B. McMahan, D. Ramage, and P. Richtárik, “Federated Optimization: Distributed Machine Learning for On-Device Intelligence,” pp. 1–38, 2016.
[2] H. B. Mcmahan and D. Ramage, “Communication-Efficient Learning of Deep Networks from Decentralized Data,” vol. 54, 2017.
[3] Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner. “Gradient-based learning applied to document recognition.” Proceedings of the IEEE, 86(11):2278–2324, November 1998. | [
{
"code": null,
"e": 718,
"s": 172,
"text": "Mobile devices such as phones, tablets, and smartwatches are now primary computing devices and have become integral for many people. These devices host huge amounts of valuable and private data thanks to the combination of rich user interactions and powerful sensors. Models trained on such data could significantly improve the usability and power of intelligent applications. However, the sensitive nature of this data means there are also some risks and responsibilities [1]. At this point, the Federated Learning (FL) concept comes into play."
},
{
"code": null,
"e": 1078,
"s": 718,
"text": "In FL, each client trains its model decentrally. In other words, the model training process is carried out separately for each client. Only learned model parameters are sent to a trusted center to combine and feed the aggregated main model. Then the trusted center sent back the aggregated main model back to these clients, and this process is circulated [2]."
},
{
"code": null,
"e": 1520,
"s": 1078,
"text": "In this context, I prepared a simple implementation with IID (independent and identically distributed) data to show how the parameters of hundreds of different models that are running on different nodes can be combined with the FedAvg method and whether this model will give a reasonable result. This implementation was carried out on the MNIST Data set. The MNIST data set contains 28 * 28 pixel grayscale images of numbers from 0 to 9 [3]."
},
{
"code": null,
"e": 1733,
"s": 1520,
"text": "The MNIST data set does not contain each label equally. Therefore, to fulfill the IID requirement, the dataset was grouped, shuffled, and then distributed so that each node contains an equal number of each label."
},
{
"code": null,
"e": 1800,
"s": 1733,
"text": "A simple 2-layer model was created for the classification process."
},
{
"code": null,
"e": 1845,
"s": 1800,
"text": "Functions to be used for FedAvg are defined."
},
{
"code": null,
"e": 1889,
"s": 1845,
"text": "Here, an iteration is completed as follows."
},
{
"code": null,
"e": 2573,
"s": 1889,
"text": "Since the parameters of the main model and parameters of all local models in the nodes are randomly initialized, all these parameters will be different from each other. For this reason, the main model sends its parameters to the nodes before the training of local models in the nodes begins.Nodes start to train their local models over their own data by using these parameters.Each node updates its parameters while training its own model. After the training process is completed, each node sends its parameters to the main model.The main model takes the average of these parameters and sets them as its new weight parameters and passes them back to the nodes for the next iteration."
},
{
"code": null,
"e": 2865,
"s": 2573,
"text": "Since the parameters of the main model and parameters of all local models in the nodes are randomly initialized, all these parameters will be different from each other. For this reason, the main model sends its parameters to the nodes before the training of local models in the nodes begins."
},
{
"code": null,
"e": 2952,
"s": 2865,
"text": "Nodes start to train their local models over their own data by using these parameters."
},
{
"code": null,
"e": 3106,
"s": 2952,
"text": "Each node updates its parameters while training its own model. After the training process is completed, each node sends its parameters to the main model."
},
{
"code": null,
"e": 3260,
"s": 3106,
"text": "The main model takes the average of these parameters and sets them as its new weight parameters and passes them back to the nodes for the next iteration."
},
{
"code": null,
"e": 3388,
"s": 3260,
"text": "The above flow is for one iteration. This iteration can be repeated over and over to improve the performance of the main model."
},
{
"code": null,
"e": 3681,
"s": 3388,
"text": "Note: The purpose here is not to increase the performance of the classification algorithm, but to compare the performance of the model obtained with federated learning with a centralized model. If you wish, you can use more complicated models or adjust hyperparameters to improve performance."
},
{
"code": null,
"e": 3715,
"s": 3681,
"text": "And if you are ready, here we go!"
},
{
"code": null,
"e": 3747,
"s": 3715,
"text": "Functions for data distribution"
},
{
"code": null,
"e": 4316,
"s": 3747,
"text": "split_and_shuffle_labels(y_data, seed, amount): The data set does not contain an equal number of each label. In order to distribute the data to the nodes as IID, an equal number of them must be taken. This function groups them as much as the amount given from each label and shuffles the order within itself. Please be aware that, what shuffled here is the indexes of the data, we will use them when retrieving the data in the future. But these indexes need to be reset to avoid key errors. Therefore, a new column has been defined and shuffled indexes are kept there."
},
{
"code": null,
"e": 4517,
"s": 4316,
"text": "get_iid_subsamples_indices(label_dict, number_of_samples, amount): This function divides the indexes in each node with an equal number of each label. (Here the indexes are still distributed, not data)"
},
{
"code": null,
"e": 4648,
"s": 4517,
"text": "create_iid_subsamples(sample_dict, x_data, y_data, x_name, y_name): This function distributes x and y data to nodes in dictionary."
},
{
"code": null,
"e": 4669,
"s": 4648,
"text": "Functions for FedAvg"
},
{
"code": null,
"e": 4801,
"s": 4669,
"text": "create_model_optimizer_criterion_dict(number_of_samples): This function creates a model, optimizer and loss function for each node."
},
{
"code": null,
"e": 4922,
"s": 4801,
"text": "get_averaged_weights(model_dict, number_of_samples): This function takes the average of the weights in individual nodes."
},
{
"code": null,
"e": 5226,
"s": 4922,
"text": "set_averaged_weights_as_main_model_weights_and_update_main_model(main_model,model_dict, number_of_samples): This function sends the averaged weights of individual nodes to the main model and sets them as the new weights of the main model. ( calls def get_averaged_weights(model_dict, number_of_samples))"
},
{
"code": null,
"e": 5384,
"s": 5226,
"text": "compare_local_and_merged_model_performance(number_of_samples: This function compares the accuracy of the main model and the local model running on each node."
},
{
"code": null,
"e": 5542,
"s": 5384,
"text": "send_main_model_to_nodes_and_update_model_dict(main_model, model_dict, number_of_samples): This function sends the parameters of the main model to the nodes."
},
{
"code": null,
"e": 5643,
"s": 5542,
"text": "start_train_end_node_process_without_print(): This function trains individual local models in nodes."
},
{
"code": null,
"e": 5769,
"s": 5643,
"text": "First, let’s examine what would the performance of the centralized model be if the data were not distributed to nodes at all?"
},
{
"code": null,
"e": 6402,
"s": 5769,
"text": " — — — Centralized Model — — — epoch: 1 | train accuracy: 0.8743 | test accuracy: 0.9437epoch: 2 | train accuracy: 0.9567 | test accuracy: 0.9654epoch: 3 | train accuracy: 0.9712 | test accuracy: 0.9701epoch: 4 | train accuracy: 0.9785 | test accuracy: 0.9738epoch: 5 | train accuracy: 0.9834 | test accuracy: 0.9713epoch: 6 | train accuracy: 0.9864 | test accuracy: 0.9768epoch: 7 | train accuracy: 0.9898 | test accuracy: 0.9763epoch: 8 | train accuracy: 0.9923 | test accuracy: 0.9804epoch: 9 | train accuracy: 0.9941 | test accuracy: 0.9784epoch: 10 | train accuracy: 0.9959 | test accuracy: 0.9792 — — — Training finished — — -"
},
{
"code": null,
"e": 6895,
"s": 6402,
"text": "The model used in this example is very simple, different improvements can be performed to increase model performance, such as using more complex models, increasing epoch or hyperparameter tuning. However, the purpose here is to compare the performance of the main model that is formed by combining the parameters of the local models trained on their own data with a centralized model that trained on all training data. In this way, we can gain insight into the capacity of federated learning."
},
{
"code": null,
"e": 6927,
"s": 6895,
"text": "Then, start our first iteration"
},
{
"code": null,
"e": 6956,
"s": 6927,
"text": "Data is distributed to nodes"
},
{
"code": null,
"e": 6982,
"s": 6956,
"text": "The main model is created"
},
{
"code": null,
"e": 7042,
"s": 6982,
"text": "Models, optimizers, and loss functions in nodes are defined"
},
{
"code": null,
"e": 7080,
"s": 7042,
"text": "Keys of dicts are being made iterable"
},
{
"code": null,
"e": 7451,
"s": 7080,
"text": "Parameters of the main model are sent to nodesSince the parameters of the main model and parameters of all local models in the nodes are randomly initialized, all these parameters will be different from each other. For this reason, the main model sends its parameters to the nodes before the training of local models in the nodes begins. You can check the weights below."
},
{
"code": null,
"e": 7483,
"s": 7451,
"text": "Models in the nodes are trained"
},
{
"code": null,
"e": 7761,
"s": 7483,
"text": "Federated main model vs centralized model before 1st iteration (on all test data)Since the main model is randomly initialized and no action taken on it yet, before first iteration its performance is very poor. After first iteration, the accuracy of main model increased to %85."
},
{
"code": null,
"e": 7942,
"s": 7761,
"text": "Before 1st iteration main model accuracy on all test data: 0.1180After 1st iteration main model accuracy on all test data: 0.8529Centralized model accuracy on all test data: 0.9790"
},
{
"code": null,
"e": 8168,
"s": 7942,
"text": "This is a single iteration, we can send the parameters of the main model back to the nodes and repeat the above steps. Now let’s check how the performance of the main model improves when we repeat the iteration 10 more times."
},
{
"code": null,
"e": 8761,
"s": 8168,
"text": "Iteration 2 : main_model accuracy on all test data: 0.8928Iteration 3 : main_model accuracy on all test data: 0.9073Iteration 4 : main_model accuracy on all test data: 0.9150Iteration 5 : main_model accuracy on all test data: 0.9209Iteration 6 : main_model accuracy on all test data: 0.9273Iteration 7 : main_model accuracy on all test data: 0.9321Iteration 8 : main_model accuracy on all test data: 0.9358Iteration 9 : main_model accuracy on all test data: 0.9382Iteration 10 : main_model accuracy on all test data: 0.9411Iteration 11 : main_model accuracy on all test data: 0.9431"
},
{
"code": null,
"e": 9090,
"s": 8761,
"text": "The accuracy of the centralized model was calculated as approximately 98%. The accuracy of the main model obtained by FedAvg method started from 85% and improved to 94%. In this case, we can say that although the main model obtained by FedAvg method was trained without seeing the data, its performance cannot be underestimated."
},
{
"code": null,
"e": 9212,
"s": 9090,
"text": "You can visit the https://github.com/eceisik/fl_public/blob/master/fedavg_mnist_iid.ipynb to see the full implementation."
},
{
"code": null,
"e": 9244,
"s": 9212,
"text": "*You can visit the github page."
},
{
"code": null,
"e": 9406,
"s": 9244,
"text": "[1] J. Konečný, H. B. McMahan, D. Ramage, and P. Richtárik, “Federated Optimization: Distributed Machine Learning for On-Device Intelligence,” pp. 1–38, 2016."
},
{
"code": null,
"e": 9531,
"s": 9406,
"text": "[2] H. B. Mcmahan and D. Ramage, “Communication-Efficient Learning of Deep Networks from Decentralized Data,” vol. 54, 2017."
}
] |
MS SQL Server - Quick Guide | This chapter introduces SQL Server, discusses its usage, advantages, versions, and components.
It is a software, developed by Microsoft, which is implemented from the specification of RDBMS.
It is a software, developed by Microsoft, which is implemented from the specification of RDBMS.
It is also an ORDBMS.
It is also an ORDBMS.
It is platform dependent.
It is platform dependent.
It is both GUI and command based software.
It is both GUI and command based software.
It supports SQL (SEQUEL) language which is an IBM product, non-procedural, common database and case insensitive language.
It supports SQL (SEQUEL) language which is an IBM product, non-procedural, common database and case insensitive language.
To create databases.
To maintain databases.
To analyze the data through SQL Server Analysis Services (SSAS).
To generate reports through SQL Server Reporting Services (SSRS).
To carry out ETL operations through SQL Server Integration Services (SSIS).
SQL Server works in client-server architecture, hence it supports two types of components − (a) Workstation and (b) Server.
Workstation components are installed in every device/SQL Server operator’s machine. These are just interfaces to interact with Server components. Example: SSMS, SSCM, Profiler, BIDS, SQLEM etc.
Workstation components are installed in every device/SQL Server operator’s machine. These are just interfaces to interact with Server components. Example: SSMS, SSCM, Profiler, BIDS, SQLEM etc.
Server components are installed in centralized server. These are services. Example: SQL Server, SQL Server Agent, SSIS, SSAS, SSRS, SQL browser, SQL Server full text search etc.
Server components are installed in centralized server. These are services. Example: SQL Server, SQL Server Agent, SSIS, SSAS, SSRS, SQL browser, SQL Server full text search etc.
An instance is an installation of SQL Server.
An instance is an exact copy of the same software.
If we install 'n' times, then 'n' instances will be created.
There are two types of instances in SQL Server a) Default b) Named.
Only one default instance will be supported in one Server.
Multiple named instances will be supported in one Server.
Default instance will take the server name as Instance name.
Default instance service name is MSSQLSERVER.
16 instances will be supported in 2000 version.
50 instances will supported in 2005 and later versions.
To install different versions in one machine.
To reduce cost.
To maintain production, development, and test environments separately.
To reduce temporary database problems.
To separate security privileges.
To maintain standby server.
SQL Server is available in various editions. This chapter lists the multiple editions with its features.
Enterprise − This is the top-end edition with a full feature set.
Enterprise − This is the top-end edition with a full feature set.
Standard − This has less features than Enterprise, when there is no requirement of advanced features.
Standard − This has less features than Enterprise, when there is no requirement of advanced features.
Workgroup − This is suitable for remote offices of a larger company.
Workgroup − This is suitable for remote offices of a larger company.
Web − This is designed for web applications.
Web − This is designed for web applications.
Developer − This is similar to Enterprise, but licensed to only one user for development, testing and demo. It can be easily upgraded to Enterprise without reinstallation.
Developer − This is similar to Enterprise, but licensed to only one user for development, testing and demo. It can be easily upgraded to Enterprise without reinstallation.
Express − This is free entry level database. It can utilize only 1 CPU and 1 GB memory, the maximum size of the database is 10 GB.
Express − This is free entry level database. It can utilize only 1 CPU and 1 GB memory, the maximum size of the database is 10 GB.
Compact − This is free embedded database for mobile application development. The maximum size of the database is 4 GB.
Compact − This is free embedded database for mobile application development. The maximum size of the database is 4 GB.
Datacenter − The major change in new SQL Server 2008 R2 is Datacenter Edition. The Datacenter edition has no memory limitation and offers support for more than 25 instances.
Datacenter − The major change in new SQL Server 2008 R2 is Datacenter Edition. The Datacenter edition has no memory limitation and offers support for more than 25 instances.
Business Intelligence − Business Intelligence Edition is a new introduction in SQL Server 2012. This edition includes all the features in the Standard edition and support for advanced BI features such as Power View and PowerPivot, but it lacks support for advanced availability features like AlwaysOn Availability Groups and other online operations.
Business Intelligence − Business Intelligence Edition is a new introduction in SQL Server 2012. This edition includes all the features in the Standard edition and support for advanced BI features such as Power View and PowerPivot, but it lacks support for advanced availability features like AlwaysOn Availability Groups and other online operations.
Enterprise Evaluation − The SQL Server Evaluation Edition is a great way to get a fully functional and free instance of SQL Server for learning and developing solutions. This edition has a built-in expiry of 6 months from the time that you install it.
Enterprise Evaluation − The SQL Server Evaluation Edition is a great way to get a fully functional and free instance of SQL Server for learning and developing solutions. This edition has a built-in expiry of 6 months from the time that you install it.
SQL Server supports two types of installation −
Standalone
Cluster based
Check RDP access for the server.
Check OS bit, IP, domain of server.
Check if your account is in admin group to run setup.exe file.
Software location.
Which version, edition, SP and hotfix if any.
Service accounts for database engine, agent, SSAS, SSIS, SSRS, if any.
Named instance name if any.
Location for binaries, system, user databases.
Authentication mode.
Collation setting.
List of features.
Setup support files.
.net framework 2.0.
SQL Server native client.
Setup support files.
.net framework 3.5 SP1.
SQL Server native client.
Windows installer 4.5/later version.
Setup support files.
.net framework 4.0.
SQL Server native client.
Windows installer 4.5/later version.
Windows PowerShell 2.0.
Step 1 − Download the Evaluation Edition from http://www.microsoft.com/download/en/details.aspx?id=29066
Once the software is downloaded, the following files will be available based on your download (32 or 64 bit) option.
ENU\x86\SQLFULL_x86_ENU_Core.box
ENU\x86\SQLFULL_x86_ENU_Install.exe
ENU\x86\SQLFULL_x86_ENU_Lang.box
OR
ENU\x86\SQLFULL_x64_ENU_Core.box
ENU\x86\SQLFULL_x64_ENU_Install.exe
ENU\x86\SQLFULL_x64_ENU_Lang.box
Note − X86 (32 bit) and X64 (64 bit)
Step 2 − Double-click the “SQLFULL_x86_ENU_Install.exe” or “SQLFULL_x64_ENU_Install.exe”, it will extract the required files for installation in the“SQLFULL_x86_ENU” or “SQLFULL_x86_ENU” folder respectively.
Step 3 − Click the “SQLFULL_x86_ENU” or “SQLFULL_x64_ENU_Install.exe” folder and double-click “SETUP” application.
For understanding, here we have used SQLFULL_x64_ENU_Install.exe software.
Step 4 − Once we click on 'setup' application, the following screen will open.
Step 5 − Click Installation which is on the left side of the above screen.
Step 6 − Click the first option of the right side seen on the above screen. The following screen will open.
Step 7 − Click OK and the following screen pops up.
Step 8 − Click Next to get the following screen.
Step 9 − Make sure to check the product key selection and click Next.
Step 10 − Select the checkbox to accept the license option and click Next.
Step 11 − Select SQL Server feature installation option and click Next.
Step 12 − Select Database engine services checkbox and click Next.
Step 13 − Enter the named instance (here I used TestInstance) and click Next.
Step 14 − Click Next on the above screen and the following screen appears.
Step 15 − Select service account names and start-up types for the above listed services and click Collation.
Step 16 − Make sure the correct collation selection is checked and click Next.
Step 17 − Make sure authentication mode selection and administrators are checked and click Data Directories.
Step 18 − Make sure to select the above directory locations and click Next. The following screen appears.
Step 19 − Click Next on the above screen.
Step 20 − Click Next on the above screen to the get the following screen.
Step 21 − Make sure to check the above selection correctly and click Install.
Installation is successful as shown in the above screen. Click Close to finish.
We have classified the architecture of SQL Server into the following parts for easy understanding −
General architecture
Memory architecture
Data file architecture
Log file architecture
Client − Where the request initiated.
Query − SQL query which is high level language.
Logical Units − Keywords, expressions and operators, etc.
N/W Packets − Network related code.
Protocols − In SQL Server we have 4 protocols.
Shared memory (for local connections and troubleshooting purpose).
Shared memory (for local connections and troubleshooting purpose).
Named pipes (for connections which are in LAN connectivity).
Named pipes (for connections which are in LAN connectivity).
TCP/IP (for connections which are in WAN connectivity).
TCP/IP (for connections which are in WAN connectivity).
VIA-Virtual Interface Adapter (requires special hardware to set up by vendor and also deprecated from SQL 2012 version).
VIA-Virtual Interface Adapter (requires special hardware to set up by vendor and also deprecated from SQL 2012 version).
Server − Where SQL Services got installed and databases reside.
Relational Engine − This is where real execution will be done. It contains Query parser, Query optimizer and Query executor.
Query Parser (Command Parser) and Compiler (Translator) − This will check syntax of the query and it will convert the query to machine language.
Query Optimizer − It will prepare the execution plan as output by taking query, statistics and Algebrizer tree as input.
Execution Plan − It is like a roadmap, which contains the order of all the steps to be performed as part of the query execution.
Query Executor − This is where the query will be executed step by step with the help of execution plan and also the storage engine will be contacted.
Storage Engine − It is responsible for storage and retrieval of data on the storage system (disk, SAN, etc.,), data manipulation, locking and managing transactions.
SQL OS − This lies between the host machine (Windows OS) and SQL Server. All the activities performed on database engine are taken care of by SQL OS. SQL OS provides various operating system services, such as memory management deals with buffer pool, log buffer and deadlock detection using the blocking and locking structure.
Checkpoint Process − Checkpoint is an internal process that writes all dirty pages (modified pages) from Buffer Cache to Physical disk. Apart from this, it also writes the log records from log buffer to physical file. Writing of Dirty pages from buffer cache to data file is also known as Hardening of dirty pages.
It is a dedicated process and runs automatically by SQL Server at specific intervals. SQL Server runs checkpoint process for each database individually. Checkpoint helps to reduce the recovery time for SQL Server in the event of unexpected shutdown or system crash\Failure.
In SQL Server 2012 there are four types of checkpoints −
Automatic − This is the most common checkpoint which runs as a process in the background to make sure SQL Server Database can be recovered in the time limit defined by the Recovery Interval − Server Configuration Option.
Automatic − This is the most common checkpoint which runs as a process in the background to make sure SQL Server Database can be recovered in the time limit defined by the Recovery Interval − Server Configuration Option.
Indirect − This is new in SQL Server 2012. This also runs in the background but to meet a user-specified target recovery time for the specific database where the option has been configured. Once the Target_Recovery_Time for a given database has been selected, this will override the Recovery Interval specified for the server and avoid automatic checkpoint on such DB.
Indirect − This is new in SQL Server 2012. This also runs in the background but to meet a user-specified target recovery time for the specific database where the option has been configured. Once the Target_Recovery_Time for a given database has been selected, this will override the Recovery Interval specified for the server and avoid automatic checkpoint on such DB.
Manual − This one runs just like any other T-SQL statement, once you issue checkpoint command it will run to its completion. Manual checkpoint runs for your current database only. You can also specify the Checkpoint_Duration which is optional - this duration specifies the time in which you want your checkpoint to complete.
Manual − This one runs just like any other T-SQL statement, once you issue checkpoint command it will run to its completion. Manual checkpoint runs for your current database only. You can also specify the Checkpoint_Duration which is optional - this duration specifies the time in which you want your checkpoint to complete.
Internal − As a user you can’t control internal checkpoint. Issued on specific operations such as
Shutdown initiates a checkpoint operation on all databases except when shutdown is not clean (shutdown with nowait).
If the recovery model gets changed from Full\Bulk-logged to Simple.
While taking backup of the database.
If your DB is in simple recovery model, checkpoint process executes automatically either when the log becomes 70% full, or based on Server option-Recovery Interval.
Alter database command to add or remove a data\log file also initiates a checkpoint.
Checkpoint also takes place when the recovery model of the DB is bulk-logged and a minimally logged operation is performed.
DB Snapshot creation.
Internal − As a user you can’t control internal checkpoint. Issued on specific operations such as
Shutdown initiates a checkpoint operation on all databases except when shutdown is not clean (shutdown with nowait).
Shutdown initiates a checkpoint operation on all databases except when shutdown is not clean (shutdown with nowait).
If the recovery model gets changed from Full\Bulk-logged to Simple.
If the recovery model gets changed from Full\Bulk-logged to Simple.
While taking backup of the database.
While taking backup of the database.
If your DB is in simple recovery model, checkpoint process executes automatically either when the log becomes 70% full, or based on Server option-Recovery Interval.
If your DB is in simple recovery model, checkpoint process executes automatically either when the log becomes 70% full, or based on Server option-Recovery Interval.
Alter database command to add or remove a data\log file also initiates a checkpoint.
Alter database command to add or remove a data\log file also initiates a checkpoint.
Checkpoint also takes place when the recovery model of the DB is bulk-logged and a minimally logged operation is performed.
Checkpoint also takes place when the recovery model of the DB is bulk-logged and a minimally logged operation is performed.
DB Snapshot creation.
DB Snapshot creation.
Lazy Writer Process − Lazy writer will push dirty pages to disk for an entirely different reason, because it needs to free up memory in the buffer pool. This happens when SQL server comes under memory pressure. As far as I am aware, this is controlled by an internal process and there is no setting for it.
Lazy Writer Process − Lazy writer will push dirty pages to disk for an entirely different reason, because it needs to free up memory in the buffer pool. This happens when SQL server comes under memory pressure. As far as I am aware, this is controlled by an internal process and there is no setting for it.
SQL server constantly monitors memory usage to assess resource contention (or availability); its job is to make sure that there is a certain amount of free space available at all times. As part of this process, when it notices any such resource contention, it triggers Lazy Writer to free up some pages in memory by writing out dirty pages to disk. It employs Least Recently Used (LRU) algorithm to decide which pages are to be flushed to the disk.
If Lazy Writer is always active, it could indicate memory bottleneck.
Following are some of the salient features of memory architecture.
One of the primary design goals of all database software is to minimize disk I/O because disk reads and writes are among the most resource-intensive operations.
One of the primary design goals of all database software is to minimize disk I/O because disk reads and writes are among the most resource-intensive operations.
Memory in windows can be called with Virtual Address Space, shared by Kernel mode (OS mode) and User mode (Application like SQL Server).
Memory in windows can be called with Virtual Address Space, shared by Kernel mode (OS mode) and User mode (Application like SQL Server).
SQL Server "User address space" is broken into two regions: MemToLeave and Buffer Pool.
SQL Server "User address space" is broken into two regions: MemToLeave and Buffer Pool.
Size of MemToLeave (MTL) and Buffer Pool (BPool) is determined by SQL Server during startup.
Size of MemToLeave (MTL) and Buffer Pool (BPool) is determined by SQL Server during startup.
Buffer management is a key component in achieving I/O highly efficiency. The buffer management component consists of two mechanisms: the buffer manager to access and update database pages, and the buffer pool to reduce database file I/O.
Buffer management is a key component in achieving I/O highly efficiency. The buffer management component consists of two mechanisms: the buffer manager to access and update database pages, and the buffer pool to reduce database file I/O.
The buffer pool is further divided into multiple sections. The most important ones being the buffer cache (also referred to as data cache) and procedure cache. Buffer cache holds the data pages in memory so that frequently accessed data can be retrieved from cache. The alternative would be reading data pages from the disk. Reading data pages from cache optimizes performance by minimizing the number of required I/O operations which are inherently slower than retrieving data from the memory.
The buffer pool is further divided into multiple sections. The most important ones being the buffer cache (also referred to as data cache) and procedure cache. Buffer cache holds the data pages in memory so that frequently accessed data can be retrieved from cache. The alternative would be reading data pages from the disk. Reading data pages from cache optimizes performance by minimizing the number of required I/O operations which are inherently slower than retrieving data from the memory.
Procedure cache keeps the stored procedure and query execution plans to minimize the number of times that query plans have to be generated. You can find out information about the size and activity within the procedure cache using DBCC PROCCACHE statement.
Procedure cache keeps the stored procedure and query execution plans to minimize the number of times that query plans have to be generated. You can find out information about the size and activity within the procedure cache using DBCC PROCCACHE statement.
Other portions of buffer pool include −
System level data structures − Holds SQL Server instance level data about databases and locks.
System level data structures − Holds SQL Server instance level data about databases and locks.
Log cache − Reserved for reading and writing transaction log pages.
Log cache − Reserved for reading and writing transaction log pages.
Connection context − Each connection to the instance has a small area of memory to record the current state of the connection. This information includes stored procedure and user-defined function parameters, cursor positions and more.
Connection context − Each connection to the instance has a small area of memory to record the current state of the connection. This information includes stored procedure and user-defined function parameters, cursor positions and more.
Stack space − Windows allocates stack space for each thread started by SQL Server.
Stack space − Windows allocates stack space for each thread started by SQL Server.
Data File architecture has the following components −
Database files can be grouped together in file groups for allocation and administration purposes. No file can be a member of more than one file group. Log files are never part of a file group. Log space is managed separately from data space.
There are two types of file groups in SQL Server, Primary and User-defined. Primary file group contains the primary data file and any other files not specifically assigned to another file group. All pages for the system tables are allocated in the primary file group. User-defined file groups are any file groups specified using the file group keyword in create database or alter database statement.
One file group in each database operates as the default file group. When SQL Server allocates a page to a table or index for which no file group was specified when they were created, the pages are allocated from default file group. To switch the default file group from one file group to another file group, it should have db_owner fixed db role.
By default, primary file group is the default file group. User should have db_owner fixed database role in order to take backup of files and file groups individually.
Databases have three types of files - Primary data file, Secondary data file, and Log file. Primary data file is the starting point of the database and points to the other files in the database.
Every database has one primary data file. We can give any extension for the primary data file but the recommended extension is .mdf. Secondary data file is a file other than the primary data file in that database. Some databases may have multiple secondary data files. Some databases may not have a single secondary data file. Recommended extension for secondary data file is .ndf.
Log files hold all of the log information used to recover the database. Database must have at least one log file. We can have multiple log files for one database. The recommended extension for log file is .ldf.
The location of all the files in a database are recorded in both master database and the primary file for the database. Most of the time, the database engine uses the file location from the master database.
Files have two names − Logical and Physical. Logical name is used to refer to the file in all T-SQL statements. Physical name is the OS_file_name, it must follow the rules of OS. Data and Log files can be placed on either FAT or NTFS file systems, but cannot be placed on compressed file systems. There can be up to 32,767 files in one database.
Extents are basic unit in which space is allocated to tables and indexes. An extent is 8 contiguous pages or 64KB. SQL Server has two types of extents - Uniform and Mixed. Uniform extents are made up of only single object. Mixed extents are shared by up to eight objects.
It is the fundamental unit of data storage in MS SQL Server. The size of the page is 8KB. The start of each page is 96 byte header used to store system information such as type of page, amount of free space on the page and object id of the object owning the page. There are 9 types of data pages in SQL Server.
Data − Data rows with all data except text, ntext and image data.
Data − Data rows with all data except text, ntext and image data.
Index − Index entries.
Index − Index entries.
Text\Image − Text, image and ntext data.
Text\Image − Text, image and ntext data.
GAM − Information about allocated extents.
GAM − Information about allocated extents.
SGAM − Information about allocated extents at system level.
SGAM − Information about allocated extents at system level.
Page Free Space (PFS) − Information about free space available on pages.
Page Free Space (PFS) − Information about free space available on pages.
Index Allocation Map (IAM) − Information about extents used by a table or index.
Index Allocation Map (IAM) − Information about extents used by a table or index.
Bulk Changed Map (BCM) − Information about extents modified by bulk operations since the last backup log statement.
Bulk Changed Map (BCM) − Information about extents modified by bulk operations since the last backup log statement.
Differential Changed Map (DCM) − Information about extents that have changed since the last backup database statement.
Differential Changed Map (DCM) − Information about extents that have changed since the last backup database statement.
The SQL Server transaction log operates logically as if the transaction log is a string of log records. Each log record is identified by Log Sequence Number (LSN). Each log record contains the ID of the transaction that it belongs to.
Log records for data modifications record either the logical operation performed or they record the before and after images of the modified data. The before image is a copy of the data before the operation is performed; the after image is a copy of the data after the operation has been performed.
The steps to recover an operation depend on the type of log record −
Logical operation logged.
To roll the logical operation forward, the operation is performed again.
To roll the logical operation back, the reverse logical operation is performed.
To roll the logical operation forward, the operation is performed again.
To roll the logical operation back, the reverse logical operation is performed.
Before and after image logged.
To roll the operation forward, the after image is applied.
To roll the operation back, the before image is applied.
To roll the operation forward, the after image is applied.
To roll the operation back, the before image is applied.
Different types of operations are recorded in the transaction log. These operations include −
The start and end of each transaction.
The start and end of each transaction.
Every data modification (insert, update, or delete). This includes changes by system stored procedures or data definition language (DDL) statements to any table, including system tables.
Every data modification (insert, update, or delete). This includes changes by system stored procedures or data definition language (DDL) statements to any table, including system tables.
Every extent and page allocation or de allocation.
Every extent and page allocation or de allocation.
Creating or dropping a table or index.
Creating or dropping a table or index.
Rollback operations are also logged. Each transaction reserves space on the transaction log to make sure that enough log space exists to support a rollback that is caused by either an explicit rollback statement or if an error is encountered. This reserved space is freed when the transaction is completed.
The section of the log file from the first log record that must be present for a successful database-wide rollback to the last-written log record is called the active part of the log, or the active log. This is the section of the log required to a full recovery of the database. No part of the active log can ever be truncated. LSN of this first log record is known as the minimum recovery LSN (Min LSN).
The SQL Server Database Engine divides each physical log file internally into a number of virtual log files. Virtual log files have no fixed size, and there is no fixed number of virtual log files for a physical log file.
The Database Engine chooses the size of the virtual log files dynamically while it is creating or extending log files. The Database Engine tries to maintain a small number of virtual files. The size or number of virtual log files cannot be configured or set by administrators. The only time virtual log files affect system performance is if the physical log files are defined by small size and growth_increment values.
The size value is the initial size for the log file and the growth_increment value is the amount of space added to the file every time new space is required. If the log files grow to a large size because of many small increments, they will have many virtual log files. This can slow down database startup and also log backup and restore operations.
We recommend that you assign log files a size value close to the final size required, and also have a relatively large growth_increment value. SQL Server uses a write-ahead log (WAL), which guarantees that no data modifications are written to disk before the associated log record is written to disk. This maintains the ACID properties for a transaction.
SQL Server Management Studio is a workstation component\client tool that will be installed if we select workstation component in installation steps. This allows you to connect to and manage your SQL Server from a graphical interface instead of having to use the command line.
In order to connect to a remote instance of an SQL Server, you will need this or similar software. It is used by Administrators, Developers, Testers, etc.
The following methods are used to open SQL Server Management Studio.
Start → All Programs → MS SQL Server 2012 → SQL Server Management Studio
Go to Run and type SQLWB (For 2005 Version) SSMS (For 2008 and Later Versions). Then click Enter.
SQL Server Management Studio will be open up as shown in the following snapshot in either of the above method.
A login is a simple credential for accessing SQL Server. For example, you provide your username and password when logging on to Windows or even your e-mail account. This username and password builds up the credentials. Therefore, credentials are simply a username and a password.
SQL Server allows four types of logins −
A login based on Windows credentials.
A login specific to SQL Server.
A login mapped to a certificate.
A login mapped to asymmetric key.
In this tutorial, we are interested in logins based on Windows Credentials and logins specific to SQL Server.
Logins based on Windows credentials allow you to log in to SQL Server using a Windows username and password. If you need to create your own credentials (username and password,) you can create a login specific to SQL Server.
To create, alter, or remove a SQL Server login, you can take one of two approaches −
Using SQL Server Management Studio.
Using T-SQL statements.
Following methods are used to create Login −
Step 1 − After connecting to SQL Server Instance, expand logins folder as shown in the following snapshot.
Step 2 − Right-click on Logins, then click Newlogin and the following screen will open.
Step 3 − Fill the Login name, Password and Confirm password columns as shown in the above screen and then click OK.
Login will be created as shown in the following image.
Create login yourloginname with password='yourpassword'
To create login name with TestLogin and password ‘P@ssword’ run below the following query.
Create login TestLogin with password='P@ssword'
Database is a collection of objects such as table, view, stored procedure, function, trigger, etc.
In MS SQL Server, two types of databases are available.
System databases
User Databases
System databases are created automatically when we install MS SQL Server. Following is a list of system databases −
Master
Model
MSDB
Tempdb
Resource (Introduced in 2005 version)
Distribution (It’s for Replication feature only)
User databases are created by users (Administrators, developers, and testers who have access to create databases).
Following methods are used to create user database.
Following is the basic syntax for creating database in MS SQL Server.
Create database <yourdatabasename>
OR
Restore Database <Your database name> from disk = '<Backup file location + file name>
To create database called ‘Testdb’, run the following query.
Create database Testdb
OR
Restore database Testdb from disk = 'D:\Backup\Testdb_full_backup.bak'
Note − D:\backup is location of backup file and Testdb_full_backup.bak is the backup file name
Connect to SQL Server instance and right-click on the databases folder. Click on new database and the following screen will appear.
Enter the database name field with your database name (example: to create database with the name ‘Testdb’) and click OK. Testdb database will be created as shown in the following snapshot.
Select your database based on your action before going ahead with any of the following methods.
To run a query to select backup history on database called ‘msdb’, select the msdb database as shown in the following snapshot.
Use <your database name>
To run your query to select backup history on database called ‘msdb’, select the msdb database by executing the following query.
Exec use msdb
The query will open msdb database. You can execute the following query to select backup history.
Select * from backupset
To remove your database from MS SQL Server, use drop database command. Following two methods can be used for this purpose.
Following is the basic syntax for removing database from MS SQL Server.
Drop database <your database name>
To remove database name ‘Testdb’, run the following query.
Drop database Testdb
Connect to SQL Server and right-click the database you want to remove. Click delete command and the following screen will appear.
Click OK to remove the database (in this example, the name is Testdb as shown in the above screen) from MS SQL Server.
Backup is a copy of data/database, etc. Backing up MS SQL Server database is essential for protecting data. MS SQL Server backups are mainly three types − Full or Database, Differential or Incremental, and Transactional Log or Log.
Backup database can be done using either of the following two methods.
Backup database <Your database name> to disk = '<Backup file location + file name>'
Backup database <Your database name> to
disk = '<Backup file location + file name>' with differential
Backup log <Your database name> to disk = '<Backup file location + file name>'
The following command is used for full backup database called 'TestDB' to the location 'D:\' with backup file name 'TestDB_Full.bak'
Backup database TestDB to disk = 'D:\TestDB_Full.bak'
The following command is used for differential backup database called 'TestDB' to the location 'D:\' with backup file name 'TestDB_diff.bak'
Backup database TestDB to disk = 'D:\TestDB_diff.bak' with differential
The following command is used for Log backup database called 'TestDB' to the location 'D:\' with backup file name 'TestDB_log.trn'
Backup log TestDB to disk = 'D:\TestDB_log.trn'
Step 1 − Connect to database instance named 'TESTINSTANCE' and expand databases folder as shown in the following snapshot.
Step 2 − Right-click on 'TestDB' database and select tasks. Click Backup and the following screen will appear.
Step 3 − Select backup type (Full\diff\log) and make sure to check destination path which is where the backup file will be created. Select options at the top left corner to see the following screen.
Step 4 − Click OK to create 'TestDB' database full backup as shown in the following snapshot.
Restoring is the process of copying data from a backup and applying logged transactions to the data. Restore is what you do with backups. Take the backup file and turn it back into a database.
The Restore database option can be done using either of the following two methods.
Restore database <Your database name> from disk = '<Backup file location + file name>'
The following command is used to restore database called 'TestDB' with backup file name 'TestDB_Full.bak' which is available in 'D:\' location if you are overwriting the existed database.
Restore database TestDB from disk = ' D:\TestDB_Full.bak' with replace
If you are creating a new database with this restore command and there is no similar path of data, log files in target server, then use move option like the following command.
Make sure the D:\Data path exists as used in the following command for data and log files.
RESTORE DATABASE TestDB FROM DISK = 'D:\ TestDB_Full.bak' WITH MOVE 'TestDB' TO
'D:\Data\TestDB.mdf', MOVE 'TestDB_Log' TO 'D:\Data\TestDB_Log.ldf'
Step 1 − Connect to database instance named 'TESTINSTANCE' and right-click on databases folder. Click Restore database as shown in the following snapshot.
Step 2 − Select device radio button and click on ellipse to select the backup file as shown in the following snapshot.
Step 3 − Click OK and the following screen pops up.
Step 4 − Select Files option which is on the top left corner as shown in the following snapshot.
Step 5 − Select Options which is on the top left corner and click OK to restore 'TestDB' database as shown in the following snapshot.
User refers to an account in MS SQL Server database which is used to access database.
Users can be created using either of the following two methods.
Create user <username> for login <loginname>
To create user name 'TestUser' with mapping to Login name 'TestLogin' in TestDB database, run the following query.
create user TestUser for login TestLogin
Where 'TestLogin' is the login name which was created as part of the Login creation
Note − First we have to create Login with any name before creating a user account.
Let’s use Login name called 'TestLogin'.
Step 1 − Connect SQL Server and expand databases folder. Then expand database called 'TestDB' where we are going to create the user account and expand the security folder. Right-click on users and click on the new user to see the following screen.
Step 2 − Enter 'TestUser' in the user name field and click on ellipse to select the Login name called 'TestLogin' as shown in the following snapshot.
Step 3 − Click OK to display login name. Again click OK to create 'TestUser' user as shown in the following snapshot.
Permissions refer to the rules governing the levels of access that principals have to securables. You can grant, revoke and deny permissions in MS SQL Server.
To assign permissions either of the following two methods can be used.
Use <database name>
Grant <permission name> on <object name> to <username\principle>
To assign select permission to a user called 'TestUser' on object called 'TestTable' in 'TestDB' database, run the following query.
USE TestDB
GO
Grant select on TestTable to TestUser
Step 1 − Connect to instance and expand folders as shown in the following snapshot.
Step 2 − Right-click on TestUser and click Properties. The following screen appears.
Step 3 Click Search and select specific options. Click Object types, select tables and click browse. Select 'TestTable' and click OK. The following screen appears.
Step 4 Select checkbox for Grant column under Select permission and click OK as shown in the above snapshot.
Step 5 Select permission on 'TestTable' of TestDB database granted to 'TestUser'. Click OK.
Monitoring refers to checking database status, settings which can be the owner’s name, file names, file sizes, backup schedules, etc.
SQL Server databases can be monitored mainly through SQL Server Management Studio or T-SQL, and also can be monitored through various methods like creating agent jobs and configuring database mail, third party tools, etc.
Database status can be checked whether it is online or in any other state as shown in the following snapshot.
As per the above screen, all databases are in 'Online' status. If any database is in any other state, then that state will be shown as shown in the following snapshot.
MS SQL Server provides the following two services which is mandatory for databases creation and maintenance. Other add-on services available for different purposes are also listed.
SQL Server
SQL Server Agent
SQL Server Browser
SQL Server Full Text Search
SQL Server Integration Services
SQL Server Reporting Services
SQL Server Analysis Services
The above services can be availed using the following method.
To start any of the services, either of the following two methods can be used.
Step 1 − Go to Run, type services.msc and click OK. The following screen appears.
Step 2 − To start service, right-click on service, click Start button. Services will start as shown in the following snapshot.
Step 1 − Open configuration manager using the following process.
Start → All Programs → MS SQL Server 2012 → Configuration Tools → SQL Server configuration manager.
Step 2 − Select the service name, right-click and click on start option. Services will start as shown in the following snapshot.
To stop any of the services, either of the following three methods can be used.
Step 1 − Go to Run, type services.msc and click OK. The following screen appears.
Step 2 − To stop services, right-click on service and click Stop. The selected service will be stopped as shown in the following snapshot.
Step 1 − Open configuration manager using the following process.
Start → All Programs → MS SQL Server 2012 → Configuration Tools → SQL Server configuration manager.
Step 2 − Select the service name, right-click and click Stop option. The selected service will be stopped as shown in the following snapshot.
Step 1 − Connect to the instance as shown in the following snapshot.
Step 2 − Right-click on instance name and click Stop option. The following screen appears.
Step 3 − Click Yes button and the following screen will open.
Step 4 − Click Yes option on the above screen to stop SQL Server agent service. The services will be stopped as shown in the following screenshot.
We cannot use the SQL Server Management Studio method to start the Services as unable to connect due to services already stopped state.
We cannot use the SQL Server Management Studio method to start the Services as unable to connect due to services already stopped state.
We cannot exclude stopping SQL Service agent service while stopping SQL Server service as SQL Server Agent Service is a dependent service.
We cannot exclude stopping SQL Service agent service while stopping SQL Server service as SQL Server Agent Service is a dependent service.
High Availability (HA) is the solution\process\technology to make the application\database available 24x7 under either planned or un-planned outages.
Mainly, there are five options in MS SQL Server to achieve\setup high availability solution for the databases.
The source data will be copied to destination through replication agents (jobs). Object level technology.
Publisher is source server.
Distributor is optional and stores replicated data for the subscriber.
Subscriber is the destination server.
The source data will be copied to destination through Transaction Log backup jobs. Database level technology.
Primary server is source server.
Secondary server is destination server.
Monitor server is optional and will be monitored by log shipping status.
The primary data will be copied to secondary through network transaction basis with the help of mirroring endpoint and port number. Database level technology.
Principal server is source server.
Mirror server is destination server.
Witness server is optional and used to make automatic failover.
The data will be stored in shared location which is used by both primary and secondary servers based on availability of the server. Instance level technology. Windows Clustering setup is required with shared storage.
Active node is where SQL Services are running.
Passive node is where SQL Services are not running.
The primary data will be copied to secondary through network transaction basis. Group of database level technology. Windows Clustering setup is required without shared storage.
Primary replica is source server.
Secondary replica is destination server.
Following are the steps to configure HA technology (Mirroring and Log shipping) except Clustering, AlwaysON Availability groups and Replication.
Step 1 − Take one full and one T-log backup of source database.
To configure mirroring\log shipping for the database 'TestDB' in 'TESTINSTANCE' as primary and 'DEVINSTANCE' as secondary SQL Servers, write the following query to take full and T-log backups on Source (TESTINSTANCE) server.
Connect to 'TESTINSTANCE' SQL Server and open new query and write the following code and execute as shown in the following screenshot.
Backup database TestDB to disk = 'D:\testdb_full.bak'
GO
Backup log TestDB to disk = 'D:\testdb_log.trn'
Step 2 − Copy the backup files to destination server.
In this case, we have only one physical server and two SQL Servers Instances installed, hence there is no need to copy, but if two SQL Server instances are in different physical server, we need to copy the following two files to any location of the secondary server where 'DEVINSTANCE' instance is installed.
Step 3 − Restore the database with backup files in destination server with 'norecovery' option.
Connect to 'DEVINSTANCE' SQL Server and open New Query. Write the following code to restore the database with the name 'TestDB' which is the same name of primary database ('TestDB') for database mirroring. However, we can provide different name for log shipping configuration. In this case, let’s use 'TestDB' database name. Use 'norecovery' option for two (full and t-log backup files) restores.
Restore database TestDB from disk = 'D:\TestDB_full.bak'
with move 'TestDB' to 'D:\DATA\TestDB_DR.mdf',
move 'TestDB_log' to 'D:\DATA\TestDB_log_DR.ldf',
norecovery
GO
Restore database TestDB from disk = 'D:\TestDB_log.trn' with norecovery
Refresh the databases folder in 'DEVINSTANCE' server to see restored database 'TestDB' with restoring status as shown in the following snapshot.
Step 4 − Configure the HA (Log shipping, Mirroring) as per your requirement as shown in the following snapshot.
Right-click on 'TestDB' database of 'TESTINSTANCE' SQL Server which is primary and click Properties. The following screen will appear.
Step 5 − Select the option called either 'Mirroring' or 'Transaction Log Shipping' which are in red color box as shown in the above screen as per your requirement and follow the wizard steps guided by system itself to complete configuration.
Report is a displayable component.
Report is basically used for two purposes - Company Internal Operations and Company External Operations.
This is a service which is used to create and publish various kinds of reports.
Following are the three requirements necessary to develop any report.
Business process
Layout
Query\Procedure\View
The BIDS (Business Intelligence Studio till 2008 R2) and SSDT (SQL Server Data Tools from 2012) are environment to develop reports.
Following are the steps to open BIDS\SSDT environment to develop reports.
Step 1 − Open either BIDS\SSDT based on the version from the Microsoft SQL Server programs group. The following screen will appear. In this case, SSDT has opened.
Step 2 − Go to file at the top left corner in the above screenshot. Click New and select project. The following screen will open.
Step 3 − In the above screen, select reporting services under business intelligence at the top left corner as shown in the following screenshot.
Step 4 − In the above screen, select either report server project wizard (it will guide you step by step through wizards) or report server project (it will be used to select customized settings) based on your requirement to develop the report.
Execution plan will be generated by Query optimizer with the help of statistics and Algebrizer\processor tree. It is the result of Query optimizer and tells how to do\perform your work\requirement.
There are two different execution plans - Estimated and Actual.
Estimated execution plan indicates optimizer view.
Actual execution plan indicates what executed the query and how was it done.
Execution plans are stored in memory called plan cache, hence can be reused. Each plan is stored once unless optimizer decides parallelism for the execution of the query.
There are three different formats of execution plans available in SQL Server - Graphical plans, Text plans, and XML plans.
SHOWPLAN is the permission which is required for the user who wants to see the execution plan.
Following is the procedure to view the estimated execution plan.
Step 1 − Connect to SQL Server instance. In this case, 'TESTINSTANCE' is the instance name as shown in the following snapshot.
Step 2 − Click on New Query option on the above screen and write the following query. Before writing the query, select the database name. In this case, 'TestDB' is database name.
Select * from StudentTable
Step 3 − Click the symbol which is highlighted in red color box on the above screen to display the estimated execution plan as shown in the following screenshot.
Step 4 − Place the mouse on table scan which is the second symbol above the red color box in the above screen to display the estimated execution plan in detail. The following screenshot appears.
Following is the procedure to view the actual execution plan.
Step 1 Connect to SQL Server instance. In this case, 'TESTINSTANCE' is the instance name.
Step 2 − Click New Query option seen on the above screen and write the following query. Before writing the query, select the database name. In this case, 'TestDB' is database name.
Select * from StudentTable
Step 3 − Click the symbol which is highlighted in red color box on the above screen and then execute the query to display the actual execution plan along with the query result as shown in the following screenshot.
Step 4 − Place the mouse on the table scan which is the second symbol above the red color box on the screen to display the actual execution plan in detail. The following screenshot appears.
Step 5 − Click Results which is on the left top corner on the above screen to get the following screen.
This service is used to carry out ETL (Extraction, Transform and Load data) and admin operations. The BIDS (Business Intelligence Studio till 2008 R2) and SSDT (SQL Server Data Tools from 2012) are the environments to develop packages.
Solution (Collection of projects) ---> Project (Collection of packages) ---> Package (Collection of tasks for ETL and admin operations)
Under Package, the following components are available −
Control Flow (Containers and Tasks)
Data Flow (Source, Transformations, Destinations)
Event Handler (Sending of messages, Emails)
Package Explorer (A single view for all in package)
Parameters (User interaction)
Following are the steps to open BIDS\SSDT.
Step 1 − Open either BIDS\SSDT based on the version from the Microsoft SQL Server programs group. The following screen appears.
Step 2 − The above screen shows SSDT has opened. Go to file at the top left corner in the above image and click New. Select project and the following screen opens.
Step 3 − Select Integration Services under Business Intelligence on the top left corner in the above screen to get the following screen.
Step 4 − In the above screen, select either Integration Services Project or Integration Services Import Project Wizard based on your requirement to develop\create the package.
This service is used to analyze huge amounts of data and apply to business decisions. It is also used to create two or multidimensional business models.
In SQL Server 2000 version, it is called MSAS (Microsoft Analysis Services).
From SQL Server 2005, it is called SSAS (SQL Server Analysis Services).
There are two modes − Native Mode (SQL Server Mode) and Share Point Mode.
There are two models − Tabular Model (For Team and Personal Analysis) and Multi Dimensions Model (For Corporate Analysis).
The BIDS (Business Intelligence Studio till 2008 R2) and SSDT (SQL Server Data Tools from 2012) are environments to work with SSAS.
Step 1 − Open either BIDS\SSDT based on the version from the Microsoft SQL Server programs group. The following screen will appear.
Step 2 − The above screen shows SSDT has opened. Go to file on the top left corner in the above image and click New. Select project and the following screen opens.
Step 3 − Select Analysis Services in the above screen under Business Intelligence as seen on the top left corner. The following screen pops up.
Step 4 − In the above screen, select any one option from the listed five options based on your requirement to work with Analysis services.
32 Lectures
2.5 hours
Pavan Lalwani
18 Lectures
1.5 hours
Dr. Saatya Prasad
102 Lectures
10 hours
Pavan Lalwani
52 Lectures
4 hours
Pavan Lalwani
239 Lectures
33 hours
Gowthami Swarna
53 Lectures
5 hours
Akshay Magre
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2330,
"s": 2235,
"text": "This chapter introduces SQL Server, discusses its usage, advantages, versions, and components."
},
{
"code": null,
"e": 2426,
"s": 2330,
"text": "It is a software, developed by Microsoft, which is implemented from the specification of RDBMS."
},
{
"code": null,
"e": 2522,
"s": 2426,
"text": "It is a software, developed by Microsoft, which is implemented from the specification of RDBMS."
},
{
"code": null,
"e": 2544,
"s": 2522,
"text": "It is also an ORDBMS."
},
{
"code": null,
"e": 2566,
"s": 2544,
"text": "It is also an ORDBMS."
},
{
"code": null,
"e": 2592,
"s": 2566,
"text": "It is platform dependent."
},
{
"code": null,
"e": 2618,
"s": 2592,
"text": "It is platform dependent."
},
{
"code": null,
"e": 2661,
"s": 2618,
"text": "It is both GUI and command based software."
},
{
"code": null,
"e": 2704,
"s": 2661,
"text": "It is both GUI and command based software."
},
{
"code": null,
"e": 2826,
"s": 2704,
"text": "It supports SQL (SEQUEL) language which is an IBM product, non-procedural, common database and case insensitive language."
},
{
"code": null,
"e": 2948,
"s": 2826,
"text": "It supports SQL (SEQUEL) language which is an IBM product, non-procedural, common database and case insensitive language."
},
{
"code": null,
"e": 2969,
"s": 2948,
"text": "To create databases."
},
{
"code": null,
"e": 2992,
"s": 2969,
"text": "To maintain databases."
},
{
"code": null,
"e": 3057,
"s": 2992,
"text": "To analyze the data through SQL Server Analysis Services (SSAS)."
},
{
"code": null,
"e": 3123,
"s": 3057,
"text": "To generate reports through SQL Server Reporting Services (SSRS)."
},
{
"code": null,
"e": 3199,
"s": 3123,
"text": "To carry out ETL operations through SQL Server Integration Services (SSIS)."
},
{
"code": null,
"e": 3323,
"s": 3199,
"text": "SQL Server works in client-server architecture, hence it supports two types of components − (a) Workstation and (b) Server."
},
{
"code": null,
"e": 3517,
"s": 3323,
"text": "Workstation components are installed in every device/SQL Server operator’s machine. These are just interfaces to interact with Server components. Example: SSMS, SSCM, Profiler, BIDS, SQLEM etc."
},
{
"code": null,
"e": 3711,
"s": 3517,
"text": "Workstation components are installed in every device/SQL Server operator’s machine. These are just interfaces to interact with Server components. Example: SSMS, SSCM, Profiler, BIDS, SQLEM etc."
},
{
"code": null,
"e": 3889,
"s": 3711,
"text": "Server components are installed in centralized server. These are services. Example: SQL Server, SQL Server Agent, SSIS, SSAS, SSRS, SQL browser, SQL Server full text search etc."
},
{
"code": null,
"e": 4067,
"s": 3889,
"text": "Server components are installed in centralized server. These are services. Example: SQL Server, SQL Server Agent, SSIS, SSAS, SSRS, SQL browser, SQL Server full text search etc."
},
{
"code": null,
"e": 4113,
"s": 4067,
"text": "An instance is an installation of SQL Server."
},
{
"code": null,
"e": 4164,
"s": 4113,
"text": "An instance is an exact copy of the same software."
},
{
"code": null,
"e": 4225,
"s": 4164,
"text": "If we install 'n' times, then 'n' instances will be created."
},
{
"code": null,
"e": 4293,
"s": 4225,
"text": "There are two types of instances in SQL Server a) Default b) Named."
},
{
"code": null,
"e": 4352,
"s": 4293,
"text": "Only one default instance will be supported in one Server."
},
{
"code": null,
"e": 4410,
"s": 4352,
"text": "Multiple named instances will be supported in one Server."
},
{
"code": null,
"e": 4471,
"s": 4410,
"text": "Default instance will take the server name as Instance name."
},
{
"code": null,
"e": 4517,
"s": 4471,
"text": "Default instance service name is MSSQLSERVER."
},
{
"code": null,
"e": 4565,
"s": 4517,
"text": "16 instances will be supported in 2000 version."
},
{
"code": null,
"e": 4621,
"s": 4565,
"text": "50 instances will supported in 2005 and later versions."
},
{
"code": null,
"e": 4667,
"s": 4621,
"text": "To install different versions in one machine."
},
{
"code": null,
"e": 4683,
"s": 4667,
"text": "To reduce cost."
},
{
"code": null,
"e": 4754,
"s": 4683,
"text": "To maintain production, development, and test environments separately."
},
{
"code": null,
"e": 4793,
"s": 4754,
"text": "To reduce temporary database problems."
},
{
"code": null,
"e": 4826,
"s": 4793,
"text": "To separate security privileges."
},
{
"code": null,
"e": 4854,
"s": 4826,
"text": "To maintain standby server."
},
{
"code": null,
"e": 4959,
"s": 4854,
"text": "SQL Server is available in various editions. This chapter lists the multiple editions with its features."
},
{
"code": null,
"e": 5025,
"s": 4959,
"text": "Enterprise − This is the top-end edition with a full feature set."
},
{
"code": null,
"e": 5091,
"s": 5025,
"text": "Enterprise − This is the top-end edition with a full feature set."
},
{
"code": null,
"e": 5193,
"s": 5091,
"text": "Standard − This has less features than Enterprise, when there is no requirement of advanced features."
},
{
"code": null,
"e": 5295,
"s": 5193,
"text": "Standard − This has less features than Enterprise, when there is no requirement of advanced features."
},
{
"code": null,
"e": 5364,
"s": 5295,
"text": "Workgroup − This is suitable for remote offices of a larger company."
},
{
"code": null,
"e": 5433,
"s": 5364,
"text": "Workgroup − This is suitable for remote offices of a larger company."
},
{
"code": null,
"e": 5478,
"s": 5433,
"text": "Web − This is designed for web applications."
},
{
"code": null,
"e": 5523,
"s": 5478,
"text": "Web − This is designed for web applications."
},
{
"code": null,
"e": 5695,
"s": 5523,
"text": "Developer − This is similar to Enterprise, but licensed to only one user for development, testing and demo. It can be easily upgraded to Enterprise without reinstallation."
},
{
"code": null,
"e": 5867,
"s": 5695,
"text": "Developer − This is similar to Enterprise, but licensed to only one user for development, testing and demo. It can be easily upgraded to Enterprise without reinstallation."
},
{
"code": null,
"e": 5998,
"s": 5867,
"text": "Express − This is free entry level database. It can utilize only 1 CPU and 1 GB memory, the maximum size of the database is 10 GB."
},
{
"code": null,
"e": 6129,
"s": 5998,
"text": "Express − This is free entry level database. It can utilize only 1 CPU and 1 GB memory, the maximum size of the database is 10 GB."
},
{
"code": null,
"e": 6248,
"s": 6129,
"text": "Compact − This is free embedded database for mobile application development. The maximum size of the database is 4 GB."
},
{
"code": null,
"e": 6367,
"s": 6248,
"text": "Compact − This is free embedded database for mobile application development. The maximum size of the database is 4 GB."
},
{
"code": null,
"e": 6541,
"s": 6367,
"text": "Datacenter − The major change in new SQL Server 2008 R2 is Datacenter Edition. The Datacenter edition has no memory limitation and offers support for more than 25 instances."
},
{
"code": null,
"e": 6715,
"s": 6541,
"text": "Datacenter − The major change in new SQL Server 2008 R2 is Datacenter Edition. The Datacenter edition has no memory limitation and offers support for more than 25 instances."
},
{
"code": null,
"e": 7065,
"s": 6715,
"text": "Business Intelligence − Business Intelligence Edition is a new introduction in SQL Server 2012. This edition includes all the features in the Standard edition and support for advanced BI features such as Power View and PowerPivot, but it lacks support for advanced availability features like AlwaysOn Availability Groups and other online operations."
},
{
"code": null,
"e": 7415,
"s": 7065,
"text": "Business Intelligence − Business Intelligence Edition is a new introduction in SQL Server 2012. This edition includes all the features in the Standard edition and support for advanced BI features such as Power View and PowerPivot, but it lacks support for advanced availability features like AlwaysOn Availability Groups and other online operations."
},
{
"code": null,
"e": 7667,
"s": 7415,
"text": "Enterprise Evaluation − The SQL Server Evaluation Edition is a great way to get a fully functional and free instance of SQL Server for learning and developing solutions. This edition has a built-in expiry of 6 months from the time that you install it."
},
{
"code": null,
"e": 7919,
"s": 7667,
"text": "Enterprise Evaluation − The SQL Server Evaluation Edition is a great way to get a fully functional and free instance of SQL Server for learning and developing solutions. This edition has a built-in expiry of 6 months from the time that you install it."
},
{
"code": null,
"e": 7967,
"s": 7919,
"text": "SQL Server supports two types of installation −"
},
{
"code": null,
"e": 7978,
"s": 7967,
"text": "Standalone"
},
{
"code": null,
"e": 7992,
"s": 7978,
"text": "Cluster based"
},
{
"code": null,
"e": 8025,
"s": 7992,
"text": "Check RDP access for the server."
},
{
"code": null,
"e": 8061,
"s": 8025,
"text": "Check OS bit, IP, domain of server."
},
{
"code": null,
"e": 8124,
"s": 8061,
"text": "Check if your account is in admin group to run setup.exe file."
},
{
"code": null,
"e": 8143,
"s": 8124,
"text": "Software location."
},
{
"code": null,
"e": 8189,
"s": 8143,
"text": "Which version, edition, SP and hotfix if any."
},
{
"code": null,
"e": 8260,
"s": 8189,
"text": "Service accounts for database engine, agent, SSAS, SSIS, SSRS, if any."
},
{
"code": null,
"e": 8288,
"s": 8260,
"text": "Named instance name if any."
},
{
"code": null,
"e": 8335,
"s": 8288,
"text": "Location for binaries, system, user databases."
},
{
"code": null,
"e": 8356,
"s": 8335,
"text": "Authentication mode."
},
{
"code": null,
"e": 8375,
"s": 8356,
"text": "Collation setting."
},
{
"code": null,
"e": 8393,
"s": 8375,
"text": "List of features."
},
{
"code": null,
"e": 8414,
"s": 8393,
"text": "Setup support files."
},
{
"code": null,
"e": 8434,
"s": 8414,
"text": ".net framework 2.0."
},
{
"code": null,
"e": 8460,
"s": 8434,
"text": "SQL Server native client."
},
{
"code": null,
"e": 8481,
"s": 8460,
"text": "Setup support files."
},
{
"code": null,
"e": 8505,
"s": 8481,
"text": ".net framework 3.5 SP1."
},
{
"code": null,
"e": 8531,
"s": 8505,
"text": "SQL Server native client."
},
{
"code": null,
"e": 8568,
"s": 8531,
"text": "Windows installer 4.5/later version."
},
{
"code": null,
"e": 8589,
"s": 8568,
"text": "Setup support files."
},
{
"code": null,
"e": 8609,
"s": 8589,
"text": ".net framework 4.0."
},
{
"code": null,
"e": 8635,
"s": 8609,
"text": "SQL Server native client."
},
{
"code": null,
"e": 8672,
"s": 8635,
"text": "Windows installer 4.5/later version."
},
{
"code": null,
"e": 8696,
"s": 8672,
"text": "Windows PowerShell 2.0."
},
{
"code": null,
"e": 8801,
"s": 8696,
"text": "Step 1 − Download the Evaluation Edition from http://www.microsoft.com/download/en/details.aspx?id=29066"
},
{
"code": null,
"e": 8918,
"s": 8801,
"text": "Once the software is downloaded, the following files will be available based on your download (32 or 64 bit) option."
},
{
"code": null,
"e": 8951,
"s": 8918,
"text": "ENU\\x86\\SQLFULL_x86_ENU_Core.box"
},
{
"code": null,
"e": 8987,
"s": 8951,
"text": "ENU\\x86\\SQLFULL_x86_ENU_Install.exe"
},
{
"code": null,
"e": 9020,
"s": 8987,
"text": "ENU\\x86\\SQLFULL_x86_ENU_Lang.box"
},
{
"code": null,
"e": 9023,
"s": 9020,
"text": "OR"
},
{
"code": null,
"e": 9056,
"s": 9023,
"text": "ENU\\x86\\SQLFULL_x64_ENU_Core.box"
},
{
"code": null,
"e": 9092,
"s": 9056,
"text": "ENU\\x86\\SQLFULL_x64_ENU_Install.exe"
},
{
"code": null,
"e": 9125,
"s": 9092,
"text": "ENU\\x86\\SQLFULL_x64_ENU_Lang.box"
},
{
"code": null,
"e": 9162,
"s": 9125,
"text": "Note − X86 (32 bit) and X64 (64 bit)"
},
{
"code": null,
"e": 9370,
"s": 9162,
"text": "Step 2 − Double-click the “SQLFULL_x86_ENU_Install.exe” or “SQLFULL_x64_ENU_Install.exe”, it will extract the required files for installation in the“SQLFULL_x86_ENU” or “SQLFULL_x86_ENU” folder respectively."
},
{
"code": null,
"e": 9485,
"s": 9370,
"text": "Step 3 − Click the “SQLFULL_x86_ENU” or “SQLFULL_x64_ENU_Install.exe” folder and double-click “SETUP” application."
},
{
"code": null,
"e": 9560,
"s": 9485,
"text": "For understanding, here we have used SQLFULL_x64_ENU_Install.exe software."
},
{
"code": null,
"e": 9639,
"s": 9560,
"text": "Step 4 − Once we click on 'setup' application, the following screen will open."
},
{
"code": null,
"e": 9714,
"s": 9639,
"text": "Step 5 − Click Installation which is on the left side of the above screen."
},
{
"code": null,
"e": 9822,
"s": 9714,
"text": "Step 6 − Click the first option of the right side seen on the above screen. The following screen will open."
},
{
"code": null,
"e": 9874,
"s": 9822,
"text": "Step 7 − Click OK and the following screen pops up."
},
{
"code": null,
"e": 9923,
"s": 9874,
"text": "Step 8 − Click Next to get the following screen."
},
{
"code": null,
"e": 9994,
"s": 9923,
"text": "Step 9 − Make sure to check the product key selection and click Next."
},
{
"code": null,
"e": 10069,
"s": 9994,
"text": "Step 10 − Select the checkbox to accept the license option and click Next."
},
{
"code": null,
"e": 10141,
"s": 10069,
"text": "Step 11 − Select SQL Server feature installation option and click Next."
},
{
"code": null,
"e": 10208,
"s": 10141,
"text": "Step 12 − Select Database engine services checkbox and click Next."
},
{
"code": null,
"e": 10286,
"s": 10208,
"text": "Step 13 − Enter the named instance (here I used TestInstance) and click Next."
},
{
"code": null,
"e": 10361,
"s": 10286,
"text": "Step 14 − Click Next on the above screen and the following screen appears."
},
{
"code": null,
"e": 10470,
"s": 10361,
"text": "Step 15 − Select service account names and start-up types for the above listed services and click Collation."
},
{
"code": null,
"e": 10549,
"s": 10470,
"text": "Step 16 − Make sure the correct collation selection is checked and click Next."
},
{
"code": null,
"e": 10658,
"s": 10549,
"text": "Step 17 − Make sure authentication mode selection and administrators are checked and click Data Directories."
},
{
"code": null,
"e": 10764,
"s": 10658,
"text": "Step 18 − Make sure to select the above directory locations and click Next. The following screen appears."
},
{
"code": null,
"e": 10806,
"s": 10764,
"text": "Step 19 − Click Next on the above screen."
},
{
"code": null,
"e": 10880,
"s": 10806,
"text": "Step 20 − Click Next on the above screen to the get the following screen."
},
{
"code": null,
"e": 10958,
"s": 10880,
"text": "Step 21 − Make sure to check the above selection correctly and click Install."
},
{
"code": null,
"e": 11038,
"s": 10958,
"text": "Installation is successful as shown in the above screen. Click Close to finish."
},
{
"code": null,
"e": 11138,
"s": 11038,
"text": "We have classified the architecture of SQL Server into the following parts for easy understanding −"
},
{
"code": null,
"e": 11159,
"s": 11138,
"text": "General architecture"
},
{
"code": null,
"e": 11179,
"s": 11159,
"text": "Memory architecture"
},
{
"code": null,
"e": 11202,
"s": 11179,
"text": "Data file architecture"
},
{
"code": null,
"e": 11224,
"s": 11202,
"text": "Log file architecture"
},
{
"code": null,
"e": 11262,
"s": 11224,
"text": "Client − Where the request initiated."
},
{
"code": null,
"e": 11310,
"s": 11262,
"text": "Query − SQL query which is high level language."
},
{
"code": null,
"e": 11368,
"s": 11310,
"text": "Logical Units − Keywords, expressions and operators, etc."
},
{
"code": null,
"e": 11404,
"s": 11368,
"text": "N/W Packets − Network related code."
},
{
"code": null,
"e": 11451,
"s": 11404,
"text": "Protocols − In SQL Server we have 4 protocols."
},
{
"code": null,
"e": 11518,
"s": 11451,
"text": "Shared memory (for local connections and troubleshooting purpose)."
},
{
"code": null,
"e": 11585,
"s": 11518,
"text": "Shared memory (for local connections and troubleshooting purpose)."
},
{
"code": null,
"e": 11646,
"s": 11585,
"text": "Named pipes (for connections which are in LAN connectivity)."
},
{
"code": null,
"e": 11707,
"s": 11646,
"text": "Named pipes (for connections which are in LAN connectivity)."
},
{
"code": null,
"e": 11763,
"s": 11707,
"text": "TCP/IP (for connections which are in WAN connectivity)."
},
{
"code": null,
"e": 11819,
"s": 11763,
"text": "TCP/IP (for connections which are in WAN connectivity)."
},
{
"code": null,
"e": 11940,
"s": 11819,
"text": "VIA-Virtual Interface Adapter (requires special hardware to set up by vendor and also deprecated from SQL 2012 version)."
},
{
"code": null,
"e": 12061,
"s": 11940,
"text": "VIA-Virtual Interface Adapter (requires special hardware to set up by vendor and also deprecated from SQL 2012 version)."
},
{
"code": null,
"e": 12125,
"s": 12061,
"text": "Server − Where SQL Services got installed and databases reside."
},
{
"code": null,
"e": 12250,
"s": 12125,
"text": "Relational Engine − This is where real execution will be done. It contains Query parser, Query optimizer and Query executor."
},
{
"code": null,
"e": 12395,
"s": 12250,
"text": "Query Parser (Command Parser) and Compiler (Translator) − This will check syntax of the query and it will convert the query to machine language."
},
{
"code": null,
"e": 12516,
"s": 12395,
"text": "Query Optimizer − It will prepare the execution plan as output by taking query, statistics and Algebrizer tree as input."
},
{
"code": null,
"e": 12645,
"s": 12516,
"text": "Execution Plan − It is like a roadmap, which contains the order of all the steps to be performed as part of the query execution."
},
{
"code": null,
"e": 12795,
"s": 12645,
"text": "Query Executor − This is where the query will be executed step by step with the help of execution plan and also the storage engine will be contacted."
},
{
"code": null,
"e": 12960,
"s": 12795,
"text": "Storage Engine − It is responsible for storage and retrieval of data on the storage system (disk, SAN, etc.,), data manipulation, locking and managing transactions."
},
{
"code": null,
"e": 13287,
"s": 12960,
"text": "SQL OS − This lies between the host machine (Windows OS) and SQL Server. All the activities performed on database engine are taken care of by SQL OS. SQL OS provides various operating system services, such as memory management deals with buffer pool, log buffer and deadlock detection using the blocking and locking structure."
},
{
"code": null,
"e": 13602,
"s": 13287,
"text": "Checkpoint Process − Checkpoint is an internal process that writes all dirty pages (modified pages) from Buffer Cache to Physical disk. Apart from this, it also writes the log records from log buffer to physical file. Writing of Dirty pages from buffer cache to data file is also known as Hardening of dirty pages."
},
{
"code": null,
"e": 13876,
"s": 13602,
"text": "It is a dedicated process and runs automatically by SQL Server at specific intervals. SQL Server runs checkpoint process for each database individually. Checkpoint helps to reduce the recovery time for SQL Server in the event of unexpected shutdown or system crash\\Failure."
},
{
"code": null,
"e": 13933,
"s": 13876,
"text": "In SQL Server 2012 there are four types of checkpoints −"
},
{
"code": null,
"e": 14154,
"s": 13933,
"text": "Automatic − This is the most common checkpoint which runs as a process in the background to make sure SQL Server Database can be recovered in the time limit defined by the Recovery Interval − Server Configuration Option."
},
{
"code": null,
"e": 14375,
"s": 14154,
"text": "Automatic − This is the most common checkpoint which runs as a process in the background to make sure SQL Server Database can be recovered in the time limit defined by the Recovery Interval − Server Configuration Option."
},
{
"code": null,
"e": 14744,
"s": 14375,
"text": "Indirect − This is new in SQL Server 2012. This also runs in the background but to meet a user-specified target recovery time for the specific database where the option has been configured. Once the Target_Recovery_Time for a given database has been selected, this will override the Recovery Interval specified for the server and avoid automatic checkpoint on such DB."
},
{
"code": null,
"e": 15113,
"s": 14744,
"text": "Indirect − This is new in SQL Server 2012. This also runs in the background but to meet a user-specified target recovery time for the specific database where the option has been configured. Once the Target_Recovery_Time for a given database has been selected, this will override the Recovery Interval specified for the server and avoid automatic checkpoint on such DB."
},
{
"code": null,
"e": 15438,
"s": 15113,
"text": "Manual − This one runs just like any other T-SQL statement, once you issue checkpoint command it will run to its completion. Manual checkpoint runs for your current database only. You can also specify the Checkpoint_Duration which is optional - this duration specifies the time in which you want your checkpoint to complete."
},
{
"code": null,
"e": 15763,
"s": 15438,
"text": "Manual − This one runs just like any other T-SQL statement, once you issue checkpoint command it will run to its completion. Manual checkpoint runs for your current database only. You can also specify the Checkpoint_Duration which is optional - this duration specifies the time in which you want your checkpoint to complete."
},
{
"code": null,
"e": 16482,
"s": 15763,
"text": "Internal − As a user you can’t control internal checkpoint. Issued on specific operations such as\n\nShutdown initiates a checkpoint operation on all databases except when shutdown is not clean (shutdown with nowait).\nIf the recovery model gets changed from Full\\Bulk-logged to Simple.\nWhile taking backup of the database.\nIf your DB is in simple recovery model, checkpoint process executes automatically either when the log becomes 70% full, or based on Server option-Recovery Interval.\nAlter database command to add or remove a data\\log file also initiates a checkpoint.\nCheckpoint also takes place when the recovery model of the DB is bulk-logged and a minimally logged operation is performed.\nDB Snapshot creation.\n\n"
},
{
"code": null,
"e": 16580,
"s": 16482,
"text": "Internal − As a user you can’t control internal checkpoint. Issued on specific operations such as"
},
{
"code": null,
"e": 16697,
"s": 16580,
"text": "Shutdown initiates a checkpoint operation on all databases except when shutdown is not clean (shutdown with nowait)."
},
{
"code": null,
"e": 16814,
"s": 16697,
"text": "Shutdown initiates a checkpoint operation on all databases except when shutdown is not clean (shutdown with nowait)."
},
{
"code": null,
"e": 16882,
"s": 16814,
"text": "If the recovery model gets changed from Full\\Bulk-logged to Simple."
},
{
"code": null,
"e": 16950,
"s": 16882,
"text": "If the recovery model gets changed from Full\\Bulk-logged to Simple."
},
{
"code": null,
"e": 16987,
"s": 16950,
"text": "While taking backup of the database."
},
{
"code": null,
"e": 17024,
"s": 16987,
"text": "While taking backup of the database."
},
{
"code": null,
"e": 17189,
"s": 17024,
"text": "If your DB is in simple recovery model, checkpoint process executes automatically either when the log becomes 70% full, or based on Server option-Recovery Interval."
},
{
"code": null,
"e": 17354,
"s": 17189,
"text": "If your DB is in simple recovery model, checkpoint process executes automatically either when the log becomes 70% full, or based on Server option-Recovery Interval."
},
{
"code": null,
"e": 17439,
"s": 17354,
"text": "Alter database command to add or remove a data\\log file also initiates a checkpoint."
},
{
"code": null,
"e": 17524,
"s": 17439,
"text": "Alter database command to add or remove a data\\log file also initiates a checkpoint."
},
{
"code": null,
"e": 17648,
"s": 17524,
"text": "Checkpoint also takes place when the recovery model of the DB is bulk-logged and a minimally logged operation is performed."
},
{
"code": null,
"e": 17772,
"s": 17648,
"text": "Checkpoint also takes place when the recovery model of the DB is bulk-logged and a minimally logged operation is performed."
},
{
"code": null,
"e": 17794,
"s": 17772,
"text": "DB Snapshot creation."
},
{
"code": null,
"e": 17816,
"s": 17794,
"text": "DB Snapshot creation."
},
{
"code": null,
"e": 18123,
"s": 17816,
"text": "Lazy Writer Process − Lazy writer will push dirty pages to disk for an entirely different reason, because it needs to free up memory in the buffer pool. This happens when SQL server comes under memory pressure. As far as I am aware, this is controlled by an internal process and there is no setting for it."
},
{
"code": null,
"e": 18430,
"s": 18123,
"text": "Lazy Writer Process − Lazy writer will push dirty pages to disk for an entirely different reason, because it needs to free up memory in the buffer pool. This happens when SQL server comes under memory pressure. As far as I am aware, this is controlled by an internal process and there is no setting for it."
},
{
"code": null,
"e": 18879,
"s": 18430,
"text": "SQL server constantly monitors memory usage to assess resource contention (or availability); its job is to make sure that there is a certain amount of free space available at all times. As part of this process, when it notices any such resource contention, it triggers Lazy Writer to free up some pages in memory by writing out dirty pages to disk. It employs Least Recently Used (LRU) algorithm to decide which pages are to be flushed to the disk."
},
{
"code": null,
"e": 18949,
"s": 18879,
"text": "If Lazy Writer is always active, it could indicate memory bottleneck."
},
{
"code": null,
"e": 19016,
"s": 18949,
"text": "Following are some of the salient features of memory architecture."
},
{
"code": null,
"e": 19177,
"s": 19016,
"text": "One of the primary design goals of all database software is to minimize disk I/O because disk reads and writes are among the most resource-intensive operations."
},
{
"code": null,
"e": 19338,
"s": 19177,
"text": "One of the primary design goals of all database software is to minimize disk I/O because disk reads and writes are among the most resource-intensive operations."
},
{
"code": null,
"e": 19475,
"s": 19338,
"text": "Memory in windows can be called with Virtual Address Space, shared by Kernel mode (OS mode) and User mode (Application like SQL Server)."
},
{
"code": null,
"e": 19612,
"s": 19475,
"text": "Memory in windows can be called with Virtual Address Space, shared by Kernel mode (OS mode) and User mode (Application like SQL Server)."
},
{
"code": null,
"e": 19700,
"s": 19612,
"text": "SQL Server \"User address space\" is broken into two regions: MemToLeave and Buffer Pool."
},
{
"code": null,
"e": 19788,
"s": 19700,
"text": "SQL Server \"User address space\" is broken into two regions: MemToLeave and Buffer Pool."
},
{
"code": null,
"e": 19881,
"s": 19788,
"text": "Size of MemToLeave (MTL) and Buffer Pool (BPool) is determined by SQL Server during startup."
},
{
"code": null,
"e": 19974,
"s": 19881,
"text": "Size of MemToLeave (MTL) and Buffer Pool (BPool) is determined by SQL Server during startup."
},
{
"code": null,
"e": 20212,
"s": 19974,
"text": "Buffer management is a key component in achieving I/O highly efficiency. The buffer management component consists of two mechanisms: the buffer manager to access and update database pages, and the buffer pool to reduce database file I/O."
},
{
"code": null,
"e": 20450,
"s": 20212,
"text": "Buffer management is a key component in achieving I/O highly efficiency. The buffer management component consists of two mechanisms: the buffer manager to access and update database pages, and the buffer pool to reduce database file I/O."
},
{
"code": null,
"e": 20945,
"s": 20450,
"text": "The buffer pool is further divided into multiple sections. The most important ones being the buffer cache (also referred to as data cache) and procedure cache. Buffer cache holds the data pages in memory so that frequently accessed data can be retrieved from cache. The alternative would be reading data pages from the disk. Reading data pages from cache optimizes performance by minimizing the number of required I/O operations which are inherently slower than retrieving data from the memory."
},
{
"code": null,
"e": 21440,
"s": 20945,
"text": "The buffer pool is further divided into multiple sections. The most important ones being the buffer cache (also referred to as data cache) and procedure cache. Buffer cache holds the data pages in memory so that frequently accessed data can be retrieved from cache. The alternative would be reading data pages from the disk. Reading data pages from cache optimizes performance by minimizing the number of required I/O operations which are inherently slower than retrieving data from the memory."
},
{
"code": null,
"e": 21696,
"s": 21440,
"text": "Procedure cache keeps the stored procedure and query execution plans to minimize the number of times that query plans have to be generated. You can find out information about the size and activity within the procedure cache using DBCC PROCCACHE statement."
},
{
"code": null,
"e": 21952,
"s": 21696,
"text": "Procedure cache keeps the stored procedure and query execution plans to minimize the number of times that query plans have to be generated. You can find out information about the size and activity within the procedure cache using DBCC PROCCACHE statement."
},
{
"code": null,
"e": 21992,
"s": 21952,
"text": "Other portions of buffer pool include −"
},
{
"code": null,
"e": 22087,
"s": 21992,
"text": "System level data structures − Holds SQL Server instance level data about databases and locks."
},
{
"code": null,
"e": 22182,
"s": 22087,
"text": "System level data structures − Holds SQL Server instance level data about databases and locks."
},
{
"code": null,
"e": 22250,
"s": 22182,
"text": "Log cache − Reserved for reading and writing transaction log pages."
},
{
"code": null,
"e": 22318,
"s": 22250,
"text": "Log cache − Reserved for reading and writing transaction log pages."
},
{
"code": null,
"e": 22553,
"s": 22318,
"text": "Connection context − Each connection to the instance has a small area of memory to record the current state of the connection. This information includes stored procedure and user-defined function parameters, cursor positions and more."
},
{
"code": null,
"e": 22788,
"s": 22553,
"text": "Connection context − Each connection to the instance has a small area of memory to record the current state of the connection. This information includes stored procedure and user-defined function parameters, cursor positions and more."
},
{
"code": null,
"e": 22871,
"s": 22788,
"text": "Stack space − Windows allocates stack space for each thread started by SQL Server."
},
{
"code": null,
"e": 22954,
"s": 22871,
"text": "Stack space − Windows allocates stack space for each thread started by SQL Server."
},
{
"code": null,
"e": 23008,
"s": 22954,
"text": "Data File architecture has the following components −"
},
{
"code": null,
"e": 23250,
"s": 23008,
"text": "Database files can be grouped together in file groups for allocation and administration purposes. No file can be a member of more than one file group. Log files are never part of a file group. Log space is managed separately from data space."
},
{
"code": null,
"e": 23650,
"s": 23250,
"text": "There are two types of file groups in SQL Server, Primary and User-defined. Primary file group contains the primary data file and any other files not specifically assigned to another file group. All pages for the system tables are allocated in the primary file group. User-defined file groups are any file groups specified using the file group keyword in create database or alter database statement."
},
{
"code": null,
"e": 23997,
"s": 23650,
"text": "One file group in each database operates as the default file group. When SQL Server allocates a page to a table or index for which no file group was specified when they were created, the pages are allocated from default file group. To switch the default file group from one file group to another file group, it should have db_owner fixed db role."
},
{
"code": null,
"e": 24164,
"s": 23997,
"text": "By default, primary file group is the default file group. User should have db_owner fixed database role in order to take backup of files and file groups individually."
},
{
"code": null,
"e": 24359,
"s": 24164,
"text": "Databases have three types of files - Primary data file, Secondary data file, and Log file. Primary data file is the starting point of the database and points to the other files in the database."
},
{
"code": null,
"e": 24741,
"s": 24359,
"text": "Every database has one primary data file. We can give any extension for the primary data file but the recommended extension is .mdf. Secondary data file is a file other than the primary data file in that database. Some databases may have multiple secondary data files. Some databases may not have a single secondary data file. Recommended extension for secondary data file is .ndf."
},
{
"code": null,
"e": 24952,
"s": 24741,
"text": "Log files hold all of the log information used to recover the database. Database must have at least one log file. We can have multiple log files for one database. The recommended extension for log file is .ldf."
},
{
"code": null,
"e": 25159,
"s": 24952,
"text": "The location of all the files in a database are recorded in both master database and the primary file for the database. Most of the time, the database engine uses the file location from the master database."
},
{
"code": null,
"e": 25505,
"s": 25159,
"text": "Files have two names − Logical and Physical. Logical name is used to refer to the file in all T-SQL statements. Physical name is the OS_file_name, it must follow the rules of OS. Data and Log files can be placed on either FAT or NTFS file systems, but cannot be placed on compressed file systems. There can be up to 32,767 files in one database."
},
{
"code": null,
"e": 25777,
"s": 25505,
"text": "Extents are basic unit in which space is allocated to tables and indexes. An extent is 8 contiguous pages or 64KB. SQL Server has two types of extents - Uniform and Mixed. Uniform extents are made up of only single object. Mixed extents are shared by up to eight objects."
},
{
"code": null,
"e": 26088,
"s": 25777,
"text": "It is the fundamental unit of data storage in MS SQL Server. The size of the page is 8KB. The start of each page is 96 byte header used to store system information such as type of page, amount of free space on the page and object id of the object owning the page. There are 9 types of data pages in SQL Server."
},
{
"code": null,
"e": 26154,
"s": 26088,
"text": "Data − Data rows with all data except text, ntext and image data."
},
{
"code": null,
"e": 26220,
"s": 26154,
"text": "Data − Data rows with all data except text, ntext and image data."
},
{
"code": null,
"e": 26243,
"s": 26220,
"text": "Index − Index entries."
},
{
"code": null,
"e": 26266,
"s": 26243,
"text": "Index − Index entries."
},
{
"code": null,
"e": 26307,
"s": 26266,
"text": "Text\\Image − Text, image and ntext data."
},
{
"code": null,
"e": 26348,
"s": 26307,
"text": "Text\\Image − Text, image and ntext data."
},
{
"code": null,
"e": 26391,
"s": 26348,
"text": "GAM − Information about allocated extents."
},
{
"code": null,
"e": 26434,
"s": 26391,
"text": "GAM − Information about allocated extents."
},
{
"code": null,
"e": 26494,
"s": 26434,
"text": "SGAM − Information about allocated extents at system level."
},
{
"code": null,
"e": 26554,
"s": 26494,
"text": "SGAM − Information about allocated extents at system level."
},
{
"code": null,
"e": 26627,
"s": 26554,
"text": "Page Free Space (PFS) − Information about free space available on pages."
},
{
"code": null,
"e": 26700,
"s": 26627,
"text": "Page Free Space (PFS) − Information about free space available on pages."
},
{
"code": null,
"e": 26781,
"s": 26700,
"text": "Index Allocation Map (IAM) − Information about extents used by a table or index."
},
{
"code": null,
"e": 26862,
"s": 26781,
"text": "Index Allocation Map (IAM) − Information about extents used by a table or index."
},
{
"code": null,
"e": 26978,
"s": 26862,
"text": "Bulk Changed Map (BCM) − Information about extents modified by bulk operations since the last backup log statement."
},
{
"code": null,
"e": 27094,
"s": 26978,
"text": "Bulk Changed Map (BCM) − Information about extents modified by bulk operations since the last backup log statement."
},
{
"code": null,
"e": 27213,
"s": 27094,
"text": "Differential Changed Map (DCM) − Information about extents that have changed since the last backup database statement."
},
{
"code": null,
"e": 27332,
"s": 27213,
"text": "Differential Changed Map (DCM) − Information about extents that have changed since the last backup database statement."
},
{
"code": null,
"e": 27567,
"s": 27332,
"text": "The SQL Server transaction log operates logically as if the transaction log is a string of log records. Each log record is identified by Log Sequence Number (LSN). Each log record contains the ID of the transaction that it belongs to."
},
{
"code": null,
"e": 27865,
"s": 27567,
"text": "Log records for data modifications record either the logical operation performed or they record the before and after images of the modified data. The before image is a copy of the data before the operation is performed; the after image is a copy of the data after the operation has been performed."
},
{
"code": null,
"e": 27934,
"s": 27865,
"text": "The steps to recover an operation depend on the type of log record −"
},
{
"code": null,
"e": 28116,
"s": 27934,
"text": "Logical operation logged.\n\nTo roll the logical operation forward, the operation is performed again.\nTo roll the logical operation back, the reverse logical operation is performed.\n\n"
},
{
"code": null,
"e": 28189,
"s": 28116,
"text": "To roll the logical operation forward, the operation is performed again."
},
{
"code": null,
"e": 28269,
"s": 28189,
"text": "To roll the logical operation back, the reverse logical operation is performed."
},
{
"code": null,
"e": 28419,
"s": 28269,
"text": "Before and after image logged.\n\nTo roll the operation forward, the after image is applied.\nTo roll the operation back, the before image is applied.\n\n"
},
{
"code": null,
"e": 28478,
"s": 28419,
"text": "To roll the operation forward, the after image is applied."
},
{
"code": null,
"e": 28535,
"s": 28478,
"text": "To roll the operation back, the before image is applied."
},
{
"code": null,
"e": 28629,
"s": 28535,
"text": "Different types of operations are recorded in the transaction log. These operations include −"
},
{
"code": null,
"e": 28668,
"s": 28629,
"text": "The start and end of each transaction."
},
{
"code": null,
"e": 28707,
"s": 28668,
"text": "The start and end of each transaction."
},
{
"code": null,
"e": 28894,
"s": 28707,
"text": "Every data modification (insert, update, or delete). This includes changes by system stored procedures or data definition language (DDL) statements to any table, including system tables."
},
{
"code": null,
"e": 29081,
"s": 28894,
"text": "Every data modification (insert, update, or delete). This includes changes by system stored procedures or data definition language (DDL) statements to any table, including system tables."
},
{
"code": null,
"e": 29132,
"s": 29081,
"text": "Every extent and page allocation or de allocation."
},
{
"code": null,
"e": 29183,
"s": 29132,
"text": "Every extent and page allocation or de allocation."
},
{
"code": null,
"e": 29222,
"s": 29183,
"text": "Creating or dropping a table or index."
},
{
"code": null,
"e": 29261,
"s": 29222,
"text": "Creating or dropping a table or index."
},
{
"code": null,
"e": 29568,
"s": 29261,
"text": "Rollback operations are also logged. Each transaction reserves space on the transaction log to make sure that enough log space exists to support a rollback that is caused by either an explicit rollback statement or if an error is encountered. This reserved space is freed when the transaction is completed."
},
{
"code": null,
"e": 29973,
"s": 29568,
"text": "The section of the log file from the first log record that must be present for a successful database-wide rollback to the last-written log record is called the active part of the log, or the active log. This is the section of the log required to a full recovery of the database. No part of the active log can ever be truncated. LSN of this first log record is known as the minimum recovery LSN (Min LSN)."
},
{
"code": null,
"e": 30195,
"s": 29973,
"text": "The SQL Server Database Engine divides each physical log file internally into a number of virtual log files. Virtual log files have no fixed size, and there is no fixed number of virtual log files for a physical log file."
},
{
"code": null,
"e": 30614,
"s": 30195,
"text": "The Database Engine chooses the size of the virtual log files dynamically while it is creating or extending log files. The Database Engine tries to maintain a small number of virtual files. The size or number of virtual log files cannot be configured or set by administrators. The only time virtual log files affect system performance is if the physical log files are defined by small size and growth_increment values."
},
{
"code": null,
"e": 30963,
"s": 30614,
"text": "The size value is the initial size for the log file and the growth_increment value is the amount of space added to the file every time new space is required. If the log files grow to a large size because of many small increments, they will have many virtual log files. This can slow down database startup and also log backup and restore operations."
},
{
"code": null,
"e": 31318,
"s": 30963,
"text": "We recommend that you assign log files a size value close to the final size required, and also have a relatively large growth_increment value. SQL Server uses a write-ahead log (WAL), which guarantees that no data modifications are written to disk before the associated log record is written to disk. This maintains the ACID properties for a transaction."
},
{
"code": null,
"e": 31594,
"s": 31318,
"text": "SQL Server Management Studio is a workstation component\\client tool that will be installed if we select workstation component in installation steps. This allows you to connect to and manage your SQL Server from a graphical interface instead of having to use the command line."
},
{
"code": null,
"e": 31749,
"s": 31594,
"text": "In order to connect to a remote instance of an SQL Server, you will need this or similar software. It is used by Administrators, Developers, Testers, etc."
},
{
"code": null,
"e": 31818,
"s": 31749,
"text": "The following methods are used to open SQL Server Management Studio."
},
{
"code": null,
"e": 31891,
"s": 31818,
"text": "Start → All Programs → MS SQL Server 2012 → SQL Server Management Studio"
},
{
"code": null,
"e": 31989,
"s": 31891,
"text": "Go to Run and type SQLWB (For 2005 Version) SSMS (For 2008 and Later Versions). Then click Enter."
},
{
"code": null,
"e": 32100,
"s": 31989,
"text": "SQL Server Management Studio will be open up as shown in the following snapshot in either of the above method."
},
{
"code": null,
"e": 32380,
"s": 32100,
"text": "A login is a simple credential for accessing SQL Server. For example, you provide your username and password when logging on to Windows or even your e-mail account. This username and password builds up the credentials. Therefore, credentials are simply a username and a password."
},
{
"code": null,
"e": 32421,
"s": 32380,
"text": "SQL Server allows four types of logins −"
},
{
"code": null,
"e": 32459,
"s": 32421,
"text": "A login based on Windows credentials."
},
{
"code": null,
"e": 32491,
"s": 32459,
"text": "A login specific to SQL Server."
},
{
"code": null,
"e": 32524,
"s": 32491,
"text": "A login mapped to a certificate."
},
{
"code": null,
"e": 32558,
"s": 32524,
"text": "A login mapped to asymmetric key."
},
{
"code": null,
"e": 32668,
"s": 32558,
"text": "In this tutorial, we are interested in logins based on Windows Credentials and logins specific to SQL Server."
},
{
"code": null,
"e": 32892,
"s": 32668,
"text": "Logins based on Windows credentials allow you to log in to SQL Server using a Windows username and password. If you need to create your own credentials (username and password,) you can create a login specific to SQL Server."
},
{
"code": null,
"e": 32977,
"s": 32892,
"text": "To create, alter, or remove a SQL Server login, you can take one of two approaches −"
},
{
"code": null,
"e": 33013,
"s": 32977,
"text": "Using SQL Server Management Studio."
},
{
"code": null,
"e": 33037,
"s": 33013,
"text": "Using T-SQL statements."
},
{
"code": null,
"e": 33082,
"s": 33037,
"text": "Following methods are used to create Login −"
},
{
"code": null,
"e": 33189,
"s": 33082,
"text": "Step 1 − After connecting to SQL Server Instance, expand logins folder as shown in the following snapshot."
},
{
"code": null,
"e": 33277,
"s": 33189,
"text": "Step 2 − Right-click on Logins, then click Newlogin and the following screen will open."
},
{
"code": null,
"e": 33393,
"s": 33277,
"text": "Step 3 − Fill the Login name, Password and Confirm password columns as shown in the above screen and then click OK."
},
{
"code": null,
"e": 33448,
"s": 33393,
"text": "Login will be created as shown in the following image."
},
{
"code": null,
"e": 33505,
"s": 33448,
"text": "Create login yourloginname with password='yourpassword'\n"
},
{
"code": null,
"e": 33596,
"s": 33505,
"text": "To create login name with TestLogin and password ‘P@ssword’ run below the following query."
},
{
"code": null,
"e": 33645,
"s": 33596,
"text": "Create login TestLogin with password='P@ssword'\n"
},
{
"code": null,
"e": 33744,
"s": 33645,
"text": "Database is a collection of objects such as table, view, stored procedure, function, trigger, etc."
},
{
"code": null,
"e": 33800,
"s": 33744,
"text": "In MS SQL Server, two types of databases are available."
},
{
"code": null,
"e": 33817,
"s": 33800,
"text": "System databases"
},
{
"code": null,
"e": 33832,
"s": 33817,
"text": "User Databases"
},
{
"code": null,
"e": 33948,
"s": 33832,
"text": "System databases are created automatically when we install MS SQL Server. Following is a list of system databases −"
},
{
"code": null,
"e": 33955,
"s": 33948,
"text": "Master"
},
{
"code": null,
"e": 33961,
"s": 33955,
"text": "Model"
},
{
"code": null,
"e": 33966,
"s": 33961,
"text": "MSDB"
},
{
"code": null,
"e": 33973,
"s": 33966,
"text": "Tempdb"
},
{
"code": null,
"e": 34011,
"s": 33973,
"text": "Resource (Introduced in 2005 version)"
},
{
"code": null,
"e": 34060,
"s": 34011,
"text": "Distribution (It’s for Replication feature only)"
},
{
"code": null,
"e": 34175,
"s": 34060,
"text": "User databases are created by users (Administrators, developers, and testers who have access to create databases)."
},
{
"code": null,
"e": 34227,
"s": 34175,
"text": "Following methods are used to create user database."
},
{
"code": null,
"e": 34297,
"s": 34227,
"text": "Following is the basic syntax for creating database in MS SQL Server."
},
{
"code": null,
"e": 34333,
"s": 34297,
"text": "Create database <yourdatabasename>\n"
},
{
"code": null,
"e": 34336,
"s": 34333,
"text": "OR"
},
{
"code": null,
"e": 34423,
"s": 34336,
"text": "Restore Database <Your database name> from disk = '<Backup file location + file name>\n"
},
{
"code": null,
"e": 34484,
"s": 34423,
"text": "To create database called ‘Testdb’, run the following query."
},
{
"code": null,
"e": 34508,
"s": 34484,
"text": "Create database Testdb\n"
},
{
"code": null,
"e": 34511,
"s": 34508,
"text": "OR"
},
{
"code": null,
"e": 34583,
"s": 34511,
"text": "Restore database Testdb from disk = 'D:\\Backup\\Testdb_full_backup.bak'\n"
},
{
"code": null,
"e": 34678,
"s": 34583,
"text": "Note − D:\\backup is location of backup file and Testdb_full_backup.bak is the backup file name"
},
{
"code": null,
"e": 34810,
"s": 34678,
"text": "Connect to SQL Server instance and right-click on the databases folder. Click on new database and the following screen will appear."
},
{
"code": null,
"e": 34999,
"s": 34810,
"text": "Enter the database name field with your database name (example: to create database with the name ‘Testdb’) and click OK. Testdb database will be created as shown in the following snapshot."
},
{
"code": null,
"e": 35095,
"s": 34999,
"text": "Select your database based on your action before going ahead with any of the following methods."
},
{
"code": null,
"e": 35223,
"s": 35095,
"text": "To run a query to select backup history on database called ‘msdb’, select the msdb database as shown in the following snapshot."
},
{
"code": null,
"e": 35249,
"s": 35223,
"text": "Use <your database name>\n"
},
{
"code": null,
"e": 35378,
"s": 35249,
"text": "To run your query to select backup history on database called ‘msdb’, select the msdb database by executing the following query."
},
{
"code": null,
"e": 35393,
"s": 35378,
"text": "Exec use msdb\n"
},
{
"code": null,
"e": 35490,
"s": 35393,
"text": "The query will open msdb database. You can execute the following query to select backup history."
},
{
"code": null,
"e": 35515,
"s": 35490,
"text": "Select * from backupset\n"
},
{
"code": null,
"e": 35638,
"s": 35515,
"text": "To remove your database from MS SQL Server, use drop database command. Following two methods can be used for this purpose."
},
{
"code": null,
"e": 35710,
"s": 35638,
"text": "Following is the basic syntax for removing database from MS SQL Server."
},
{
"code": null,
"e": 35746,
"s": 35710,
"text": "Drop database <your database name>\n"
},
{
"code": null,
"e": 35805,
"s": 35746,
"text": "To remove database name ‘Testdb’, run the following query."
},
{
"code": null,
"e": 35827,
"s": 35805,
"text": "Drop database Testdb\n"
},
{
"code": null,
"e": 35957,
"s": 35827,
"text": "Connect to SQL Server and right-click the database you want to remove. Click delete command and the following screen will appear."
},
{
"code": null,
"e": 36076,
"s": 35957,
"text": "Click OK to remove the database (in this example, the name is Testdb as shown in the above screen) from MS SQL Server."
},
{
"code": null,
"e": 36308,
"s": 36076,
"text": "Backup is a copy of data/database, etc. Backing up MS SQL Server database is essential for protecting data. MS SQL Server backups are mainly three types − Full or Database, Differential or Incremental, and Transactional Log or Log."
},
{
"code": null,
"e": 36379,
"s": 36308,
"text": "Backup database can be done using either of the following two methods."
},
{
"code": null,
"e": 36464,
"s": 36379,
"text": "Backup database <Your database name> to disk = '<Backup file location + file name>'\n"
},
{
"code": null,
"e": 36571,
"s": 36464,
"text": "Backup database <Your database name> to \n disk = '<Backup file location + file name>' with differential\n"
},
{
"code": null,
"e": 36651,
"s": 36571,
"text": "Backup log <Your database name> to disk = '<Backup file location + file name>'\n"
},
{
"code": null,
"e": 36784,
"s": 36651,
"text": "The following command is used for full backup database called 'TestDB' to the location 'D:\\' with backup file name 'TestDB_Full.bak'"
},
{
"code": null,
"e": 36839,
"s": 36784,
"text": "Backup database TestDB to disk = 'D:\\TestDB_Full.bak'\n"
},
{
"code": null,
"e": 36980,
"s": 36839,
"text": "The following command is used for differential backup database called 'TestDB' to the location 'D:\\' with backup file name 'TestDB_diff.bak'"
},
{
"code": null,
"e": 37053,
"s": 36980,
"text": "Backup database TestDB to disk = 'D:\\TestDB_diff.bak' with differential\n"
},
{
"code": null,
"e": 37184,
"s": 37053,
"text": "The following command is used for Log backup database called 'TestDB' to the location 'D:\\' with backup file name 'TestDB_log.trn'"
},
{
"code": null,
"e": 37233,
"s": 37184,
"text": "Backup log TestDB to disk = 'D:\\TestDB_log.trn'\n"
},
{
"code": null,
"e": 37356,
"s": 37233,
"text": "Step 1 − Connect to database instance named 'TESTINSTANCE' and expand databases folder as shown in the following snapshot."
},
{
"code": null,
"e": 37467,
"s": 37356,
"text": "Step 2 − Right-click on 'TestDB' database and select tasks. Click Backup and the following screen will appear."
},
{
"code": null,
"e": 37666,
"s": 37467,
"text": "Step 3 − Select backup type (Full\\diff\\log) and make sure to check destination path which is where the backup file will be created. Select options at the top left corner to see the following screen."
},
{
"code": null,
"e": 37760,
"s": 37666,
"text": "Step 4 − Click OK to create 'TestDB' database full backup as shown in the following snapshot."
},
{
"code": null,
"e": 37953,
"s": 37760,
"text": "Restoring is the process of copying data from a backup and applying logged transactions to the data. Restore is what you do with backups. Take the backup file and turn it back into a database."
},
{
"code": null,
"e": 38036,
"s": 37953,
"text": "The Restore database option can be done using either of the following two methods."
},
{
"code": null,
"e": 38124,
"s": 38036,
"text": "Restore database <Your database name> from disk = '<Backup file location + file name>'\n"
},
{
"code": null,
"e": 38312,
"s": 38124,
"text": "The following command is used to restore database called 'TestDB' with backup file name 'TestDB_Full.bak' which is available in 'D:\\' location if you are overwriting the existed database."
},
{
"code": null,
"e": 38384,
"s": 38312,
"text": "Restore database TestDB from disk = ' D:\\TestDB_Full.bak' with replace\n"
},
{
"code": null,
"e": 38560,
"s": 38384,
"text": "If you are creating a new database with this restore command and there is no similar path of data, log files in target server, then use move option like the following command."
},
{
"code": null,
"e": 38651,
"s": 38560,
"text": "Make sure the D:\\Data path exists as used in the following command for data and log files."
},
{
"code": null,
"e": 38804,
"s": 38651,
"text": "RESTORE DATABASE TestDB FROM DISK = 'D:\\ TestDB_Full.bak' WITH MOVE 'TestDB' TO \n 'D:\\Data\\TestDB.mdf', MOVE 'TestDB_Log' TO 'D:\\Data\\TestDB_Log.ldf'\n"
},
{
"code": null,
"e": 38959,
"s": 38804,
"text": "Step 1 − Connect to database instance named 'TESTINSTANCE' and right-click on databases folder. Click Restore database as shown in the following snapshot."
},
{
"code": null,
"e": 39078,
"s": 38959,
"text": "Step 2 − Select device radio button and click on ellipse to select the backup file as shown in the following snapshot."
},
{
"code": null,
"e": 39130,
"s": 39078,
"text": "Step 3 − Click OK and the following screen pops up."
},
{
"code": null,
"e": 39227,
"s": 39130,
"text": "Step 4 − Select Files option which is on the top left corner as shown in the following snapshot."
},
{
"code": null,
"e": 39361,
"s": 39227,
"text": "Step 5 − Select Options which is on the top left corner and click OK to restore 'TestDB' database as shown in the following snapshot."
},
{
"code": null,
"e": 39447,
"s": 39361,
"text": "User refers to an account in MS SQL Server database which is used to access database."
},
{
"code": null,
"e": 39511,
"s": 39447,
"text": "Users can be created using either of the following two methods."
},
{
"code": null,
"e": 39557,
"s": 39511,
"text": "Create user <username> for login <loginname>\n"
},
{
"code": null,
"e": 39672,
"s": 39557,
"text": "To create user name 'TestUser' with mapping to Login name 'TestLogin' in TestDB database, run the following query."
},
{
"code": null,
"e": 39714,
"s": 39672,
"text": "create user TestUser for login TestLogin\n"
},
{
"code": null,
"e": 39798,
"s": 39714,
"text": "Where 'TestLogin' is the login name which was created as part of the Login creation"
},
{
"code": null,
"e": 39881,
"s": 39798,
"text": "Note − First we have to create Login with any name before creating a user account."
},
{
"code": null,
"e": 39922,
"s": 39881,
"text": "Let’s use Login name called 'TestLogin'."
},
{
"code": null,
"e": 40170,
"s": 39922,
"text": "Step 1 − Connect SQL Server and expand databases folder. Then expand database called 'TestDB' where we are going to create the user account and expand the security folder. Right-click on users and click on the new user to see the following screen."
},
{
"code": null,
"e": 40320,
"s": 40170,
"text": "Step 2 − Enter 'TestUser' in the user name field and click on ellipse to select the Login name called 'TestLogin' as shown in the following snapshot."
},
{
"code": null,
"e": 40438,
"s": 40320,
"text": "Step 3 − Click OK to display login name. Again click OK to create 'TestUser' user as shown in the following snapshot."
},
{
"code": null,
"e": 40597,
"s": 40438,
"text": "Permissions refer to the rules governing the levels of access that principals have to securables. You can grant, revoke and deny permissions in MS SQL Server."
},
{
"code": null,
"e": 40668,
"s": 40597,
"text": "To assign permissions either of the following two methods can be used."
},
{
"code": null,
"e": 40754,
"s": 40668,
"text": "Use <database name>\nGrant <permission name> on <object name> to <username\\principle>\n"
},
{
"code": null,
"e": 40886,
"s": 40754,
"text": "To assign select permission to a user called 'TestUser' on object called 'TestTable' in 'TestDB' database, run the following query."
},
{
"code": null,
"e": 40939,
"s": 40886,
"text": "USE TestDB\nGO\nGrant select on TestTable to TestUser\n"
},
{
"code": null,
"e": 41023,
"s": 40939,
"text": "Step 1 − Connect to instance and expand folders as shown in the following snapshot."
},
{
"code": null,
"e": 41108,
"s": 41023,
"text": "Step 2 − Right-click on TestUser and click Properties. The following screen appears."
},
{
"code": null,
"e": 41272,
"s": 41108,
"text": "Step 3 Click Search and select specific options. Click Object types, select tables and click browse. Select 'TestTable' and click OK. The following screen appears."
},
{
"code": null,
"e": 41381,
"s": 41272,
"text": "Step 4 Select checkbox for Grant column under Select permission and click OK as shown in the above snapshot."
},
{
"code": null,
"e": 41473,
"s": 41381,
"text": "Step 5 Select permission on 'TestTable' of TestDB database granted to 'TestUser'. Click OK."
},
{
"code": null,
"e": 41607,
"s": 41473,
"text": "Monitoring refers to checking database status, settings which can be the owner’s name, file names, file sizes, backup schedules, etc."
},
{
"code": null,
"e": 41829,
"s": 41607,
"text": "SQL Server databases can be monitored mainly through SQL Server Management Studio or T-SQL, and also can be monitored through various methods like creating agent jobs and configuring database mail, third party tools, etc."
},
{
"code": null,
"e": 41939,
"s": 41829,
"text": "Database status can be checked whether it is online or in any other state as shown in the following snapshot."
},
{
"code": null,
"e": 42107,
"s": 41939,
"text": "As per the above screen, all databases are in 'Online' status. If any database is in any other state, then that state will be shown as shown in the following snapshot."
},
{
"code": null,
"e": 42288,
"s": 42107,
"text": "MS SQL Server provides the following two services which is mandatory for databases creation and maintenance. Other add-on services available for different purposes are also listed."
},
{
"code": null,
"e": 42299,
"s": 42288,
"text": "SQL Server"
},
{
"code": null,
"e": 42316,
"s": 42299,
"text": "SQL Server Agent"
},
{
"code": null,
"e": 42335,
"s": 42316,
"text": "SQL Server Browser"
},
{
"code": null,
"e": 42363,
"s": 42335,
"text": "SQL Server Full Text Search"
},
{
"code": null,
"e": 42395,
"s": 42363,
"text": "SQL Server Integration Services"
},
{
"code": null,
"e": 42425,
"s": 42395,
"text": "SQL Server Reporting Services"
},
{
"code": null,
"e": 42454,
"s": 42425,
"text": "SQL Server Analysis Services"
},
{
"code": null,
"e": 42516,
"s": 42454,
"text": "The above services can be availed using the following method."
},
{
"code": null,
"e": 42595,
"s": 42516,
"text": "To start any of the services, either of the following two methods can be used."
},
{
"code": null,
"e": 42677,
"s": 42595,
"text": "Step 1 − Go to Run, type services.msc and click OK. The following screen appears."
},
{
"code": null,
"e": 42804,
"s": 42677,
"text": "Step 2 − To start service, right-click on service, click Start button. Services will start as shown in the following snapshot."
},
{
"code": null,
"e": 42869,
"s": 42804,
"text": "Step 1 − Open configuration manager using the following process."
},
{
"code": null,
"e": 42969,
"s": 42869,
"text": "Start → All Programs → MS SQL Server 2012 → Configuration Tools → SQL Server configuration manager."
},
{
"code": null,
"e": 43098,
"s": 42969,
"text": "Step 2 − Select the service name, right-click and click on start option. Services will start as shown in the following snapshot."
},
{
"code": null,
"e": 43178,
"s": 43098,
"text": "To stop any of the services, either of the following three methods can be used."
},
{
"code": null,
"e": 43260,
"s": 43178,
"text": "Step 1 − Go to Run, type services.msc and click OK. The following screen appears."
},
{
"code": null,
"e": 43399,
"s": 43260,
"text": "Step 2 − To stop services, right-click on service and click Stop. The selected service will be stopped as shown in the following snapshot."
},
{
"code": null,
"e": 43464,
"s": 43399,
"text": "Step 1 − Open configuration manager using the following process."
},
{
"code": null,
"e": 43564,
"s": 43464,
"text": "Start → All Programs → MS SQL Server 2012 → Configuration Tools → SQL Server configuration manager."
},
{
"code": null,
"e": 43706,
"s": 43564,
"text": "Step 2 − Select the service name, right-click and click Stop option. The selected service will be stopped as shown in the following snapshot."
},
{
"code": null,
"e": 43775,
"s": 43706,
"text": "Step 1 − Connect to the instance as shown in the following snapshot."
},
{
"code": null,
"e": 43866,
"s": 43775,
"text": "Step 2 − Right-click on instance name and click Stop option. The following screen appears."
},
{
"code": null,
"e": 43929,
"s": 43866,
"text": "Step 3 − Click Yes button and the following screen will open."
},
{
"code": null,
"e": 44076,
"s": 43929,
"text": "Step 4 − Click Yes option on the above screen to stop SQL Server agent service. The services will be stopped as shown in the following screenshot."
},
{
"code": null,
"e": 44212,
"s": 44076,
"text": "We cannot use the SQL Server Management Studio method to start the Services as unable to connect due to services already stopped state."
},
{
"code": null,
"e": 44348,
"s": 44212,
"text": "We cannot use the SQL Server Management Studio method to start the Services as unable to connect due to services already stopped state."
},
{
"code": null,
"e": 44487,
"s": 44348,
"text": "We cannot exclude stopping SQL Service agent service while stopping SQL Server service as SQL Server Agent Service is a dependent service."
},
{
"code": null,
"e": 44626,
"s": 44487,
"text": "We cannot exclude stopping SQL Service agent service while stopping SQL Server service as SQL Server Agent Service is a dependent service."
},
{
"code": null,
"e": 44776,
"s": 44626,
"text": "High Availability (HA) is the solution\\process\\technology to make the application\\database available 24x7 under either planned or un-planned outages."
},
{
"code": null,
"e": 44887,
"s": 44776,
"text": "Mainly, there are five options in MS SQL Server to achieve\\setup high availability solution for the databases."
},
{
"code": null,
"e": 44993,
"s": 44887,
"text": "The source data will be copied to destination through replication agents (jobs). Object level technology."
},
{
"code": null,
"e": 45021,
"s": 44993,
"text": "Publisher is source server."
},
{
"code": null,
"e": 45092,
"s": 45021,
"text": "Distributor is optional and stores replicated data for the subscriber."
},
{
"code": null,
"e": 45130,
"s": 45092,
"text": "Subscriber is the destination server."
},
{
"code": null,
"e": 45240,
"s": 45130,
"text": "The source data will be copied to destination through Transaction Log backup jobs. Database level technology."
},
{
"code": null,
"e": 45273,
"s": 45240,
"text": "Primary server is source server."
},
{
"code": null,
"e": 45313,
"s": 45273,
"text": "Secondary server is destination server."
},
{
"code": null,
"e": 45386,
"s": 45313,
"text": "Monitor server is optional and will be monitored by log shipping status."
},
{
"code": null,
"e": 45545,
"s": 45386,
"text": "The primary data will be copied to secondary through network transaction basis with the help of mirroring endpoint and port number. Database level technology."
},
{
"code": null,
"e": 45580,
"s": 45545,
"text": "Principal server is source server."
},
{
"code": null,
"e": 45617,
"s": 45580,
"text": "Mirror server is destination server."
},
{
"code": null,
"e": 45681,
"s": 45617,
"text": "Witness server is optional and used to make automatic failover."
},
{
"code": null,
"e": 45898,
"s": 45681,
"text": "The data will be stored in shared location which is used by both primary and secondary servers based on availability of the server. Instance level technology. Windows Clustering setup is required with shared storage."
},
{
"code": null,
"e": 45945,
"s": 45898,
"text": "Active node is where SQL Services are running."
},
{
"code": null,
"e": 45997,
"s": 45945,
"text": "Passive node is where SQL Services are not running."
},
{
"code": null,
"e": 46174,
"s": 45997,
"text": "The primary data will be copied to secondary through network transaction basis. Group of database level technology. Windows Clustering setup is required without shared storage."
},
{
"code": null,
"e": 46208,
"s": 46174,
"text": "Primary replica is source server."
},
{
"code": null,
"e": 46249,
"s": 46208,
"text": "Secondary replica is destination server."
},
{
"code": null,
"e": 46394,
"s": 46249,
"text": "Following are the steps to configure HA technology (Mirroring and Log shipping) except Clustering, AlwaysON Availability groups and Replication."
},
{
"code": null,
"e": 46458,
"s": 46394,
"text": "Step 1 − Take one full and one T-log backup of source database."
},
{
"code": null,
"e": 46683,
"s": 46458,
"text": "To configure mirroring\\log shipping for the database 'TestDB' in 'TESTINSTANCE' as primary and 'DEVINSTANCE' as secondary SQL Servers, write the following query to take full and T-log backups on Source (TESTINSTANCE) server."
},
{
"code": null,
"e": 46818,
"s": 46683,
"text": "Connect to 'TESTINSTANCE' SQL Server and open new query and write the following code and execute as shown in the following screenshot."
},
{
"code": null,
"e": 46924,
"s": 46818,
"text": "Backup database TestDB to disk = 'D:\\testdb_full.bak'\nGO\nBackup log TestDB to disk = 'D:\\testdb_log.trn'\n"
},
{
"code": null,
"e": 46978,
"s": 46924,
"text": "Step 2 − Copy the backup files to destination server."
},
{
"code": null,
"e": 47287,
"s": 46978,
"text": "In this case, we have only one physical server and two SQL Servers Instances installed, hence there is no need to copy, but if two SQL Server instances are in different physical server, we need to copy the following two files to any location of the secondary server where 'DEVINSTANCE' instance is installed."
},
{
"code": null,
"e": 47383,
"s": 47287,
"text": "Step 3 − Restore the database with backup files in destination server with 'norecovery' option."
},
{
"code": null,
"e": 47780,
"s": 47383,
"text": "Connect to 'DEVINSTANCE' SQL Server and open New Query. Write the following code to restore the database with the name 'TestDB' which is the same name of primary database ('TestDB') for database mirroring. However, we can provide different name for log shipping configuration. In this case, let’s use 'TestDB' database name. Use 'norecovery' option for two (full and t-log backup files) restores."
},
{
"code": null,
"e": 48021,
"s": 47780,
"text": "Restore database TestDB from disk = 'D:\\TestDB_full.bak'\nwith move 'TestDB' to 'D:\\DATA\\TestDB_DR.mdf',\nmove 'TestDB_log' to 'D:\\DATA\\TestDB_log_DR.ldf',\nnorecovery\nGO\nRestore database TestDB from disk = 'D:\\TestDB_log.trn' with norecovery\n"
},
{
"code": null,
"e": 48166,
"s": 48021,
"text": "Refresh the databases folder in 'DEVINSTANCE' server to see restored database 'TestDB' with restoring status as shown in the following snapshot."
},
{
"code": null,
"e": 48278,
"s": 48166,
"text": "Step 4 − Configure the HA (Log shipping, Mirroring) as per your requirement as shown in the following snapshot."
},
{
"code": null,
"e": 48413,
"s": 48278,
"text": "Right-click on 'TestDB' database of 'TESTINSTANCE' SQL Server which is primary and click Properties. The following screen will appear."
},
{
"code": null,
"e": 48655,
"s": 48413,
"text": "Step 5 − Select the option called either 'Mirroring' or 'Transaction Log Shipping' which are in red color box as shown in the above screen as per your requirement and follow the wizard steps guided by system itself to complete configuration."
},
{
"code": null,
"e": 48690,
"s": 48655,
"text": "Report is a displayable component."
},
{
"code": null,
"e": 48795,
"s": 48690,
"text": "Report is basically used for two purposes - Company Internal Operations and Company External Operations."
},
{
"code": null,
"e": 48875,
"s": 48795,
"text": "This is a service which is used to create and publish various kinds of reports."
},
{
"code": null,
"e": 48945,
"s": 48875,
"text": "Following are the three requirements necessary to develop any report."
},
{
"code": null,
"e": 48962,
"s": 48945,
"text": "Business process"
},
{
"code": null,
"e": 48969,
"s": 48962,
"text": "Layout"
},
{
"code": null,
"e": 48990,
"s": 48969,
"text": "Query\\Procedure\\View"
},
{
"code": null,
"e": 49122,
"s": 48990,
"text": "The BIDS (Business Intelligence Studio till 2008 R2) and SSDT (SQL Server Data Tools from 2012) are environment to develop reports."
},
{
"code": null,
"e": 49196,
"s": 49122,
"text": "Following are the steps to open BIDS\\SSDT environment to develop reports."
},
{
"code": null,
"e": 49359,
"s": 49196,
"text": "Step 1 − Open either BIDS\\SSDT based on the version from the Microsoft SQL Server programs group. The following screen will appear. In this case, SSDT has opened."
},
{
"code": null,
"e": 49489,
"s": 49359,
"text": "Step 2 − Go to file at the top left corner in the above screenshot. Click New and select project. The following screen will open."
},
{
"code": null,
"e": 49634,
"s": 49489,
"text": "Step 3 − In the above screen, select reporting services under business intelligence at the top left corner as shown in the following screenshot."
},
{
"code": null,
"e": 49878,
"s": 49634,
"text": "Step 4 − In the above screen, select either report server project wizard (it will guide you step by step through wizards) or report server project (it will be used to select customized settings) based on your requirement to develop the report."
},
{
"code": null,
"e": 50076,
"s": 49878,
"text": "Execution plan will be generated by Query optimizer with the help of statistics and Algebrizer\\processor tree. It is the result of Query optimizer and tells how to do\\perform your work\\requirement."
},
{
"code": null,
"e": 50140,
"s": 50076,
"text": "There are two different execution plans - Estimated and Actual."
},
{
"code": null,
"e": 50191,
"s": 50140,
"text": "Estimated execution plan indicates optimizer view."
},
{
"code": null,
"e": 50268,
"s": 50191,
"text": "Actual execution plan indicates what executed the query and how was it done."
},
{
"code": null,
"e": 50439,
"s": 50268,
"text": "Execution plans are stored in memory called plan cache, hence can be reused. Each plan is stored once unless optimizer decides parallelism for the execution of the query."
},
{
"code": null,
"e": 50562,
"s": 50439,
"text": "There are three different formats of execution plans available in SQL Server - Graphical plans, Text plans, and XML plans."
},
{
"code": null,
"e": 50657,
"s": 50562,
"text": "SHOWPLAN is the permission which is required for the user who wants to see the execution plan."
},
{
"code": null,
"e": 50722,
"s": 50657,
"text": "Following is the procedure to view the estimated execution plan."
},
{
"code": null,
"e": 50849,
"s": 50722,
"text": "Step 1 − Connect to SQL Server instance. In this case, 'TESTINSTANCE' is the instance name as shown in the following snapshot."
},
{
"code": null,
"e": 51028,
"s": 50849,
"text": "Step 2 − Click on New Query option on the above screen and write the following query. Before writing the query, select the database name. In this case, 'TestDB' is database name."
},
{
"code": null,
"e": 51056,
"s": 51028,
"text": "Select * from StudentTable\n"
},
{
"code": null,
"e": 51218,
"s": 51056,
"text": "Step 3 − Click the symbol which is highlighted in red color box on the above screen to display the estimated execution plan as shown in the following screenshot."
},
{
"code": null,
"e": 51413,
"s": 51218,
"text": "Step 4 − Place the mouse on table scan which is the second symbol above the red color box in the above screen to display the estimated execution plan in detail. The following screenshot appears."
},
{
"code": null,
"e": 51475,
"s": 51413,
"text": "Following is the procedure to view the actual execution plan."
},
{
"code": null,
"e": 51565,
"s": 51475,
"text": "Step 1 Connect to SQL Server instance. In this case, 'TESTINSTANCE' is the instance name."
},
{
"code": null,
"e": 51746,
"s": 51565,
"text": "Step 2 − Click New Query option seen on the above screen and write the following query. Before writing the query, select the database name. In this case, 'TestDB' is database name."
},
{
"code": null,
"e": 51774,
"s": 51746,
"text": "Select * from StudentTable\n"
},
{
"code": null,
"e": 51988,
"s": 51774,
"text": "Step 3 − Click the symbol which is highlighted in red color box on the above screen and then execute the query to display the actual execution plan along with the query result as shown in the following screenshot."
},
{
"code": null,
"e": 52178,
"s": 51988,
"text": "Step 4 − Place the mouse on the table scan which is the second symbol above the red color box on the screen to display the actual execution plan in detail. The following screenshot appears."
},
{
"code": null,
"e": 52282,
"s": 52178,
"text": "Step 5 − Click Results which is on the left top corner on the above screen to get the following screen."
},
{
"code": null,
"e": 52518,
"s": 52282,
"text": "This service is used to carry out ETL (Extraction, Transform and Load data) and admin operations. The BIDS (Business Intelligence Studio till 2008 R2) and SSDT (SQL Server Data Tools from 2012) are the environments to develop packages."
},
{
"code": null,
"e": 52654,
"s": 52518,
"text": "Solution (Collection of projects) ---> Project (Collection of packages) ---> Package (Collection of tasks for ETL and admin operations)"
},
{
"code": null,
"e": 52710,
"s": 52654,
"text": "Under Package, the following components are available −"
},
{
"code": null,
"e": 52746,
"s": 52710,
"text": "Control Flow (Containers and Tasks)"
},
{
"code": null,
"e": 52796,
"s": 52746,
"text": "Data Flow (Source, Transformations, Destinations)"
},
{
"code": null,
"e": 52840,
"s": 52796,
"text": "Event Handler (Sending of messages, Emails)"
},
{
"code": null,
"e": 52892,
"s": 52840,
"text": "Package Explorer (A single view for all in package)"
},
{
"code": null,
"e": 52922,
"s": 52892,
"text": "Parameters (User interaction)"
},
{
"code": null,
"e": 52965,
"s": 52922,
"text": "Following are the steps to open BIDS\\SSDT."
},
{
"code": null,
"e": 53093,
"s": 52965,
"text": "Step 1 − Open either BIDS\\SSDT based on the version from the Microsoft SQL Server programs group. The following screen appears."
},
{
"code": null,
"e": 53257,
"s": 53093,
"text": "Step 2 − The above screen shows SSDT has opened. Go to file at the top left corner in the above image and click New. Select project and the following screen opens."
},
{
"code": null,
"e": 53394,
"s": 53257,
"text": "Step 3 − Select Integration Services under Business Intelligence on the top left corner in the above screen to get the following screen."
},
{
"code": null,
"e": 53570,
"s": 53394,
"text": "Step 4 − In the above screen, select either Integration Services Project or Integration Services Import Project Wizard based on your requirement to develop\\create the package."
},
{
"code": null,
"e": 53723,
"s": 53570,
"text": "This service is used to analyze huge amounts of data and apply to business decisions. It is also used to create two or multidimensional business models."
},
{
"code": null,
"e": 53800,
"s": 53723,
"text": "In SQL Server 2000 version, it is called MSAS (Microsoft Analysis Services)."
},
{
"code": null,
"e": 53872,
"s": 53800,
"text": "From SQL Server 2005, it is called SSAS (SQL Server Analysis Services)."
},
{
"code": null,
"e": 53946,
"s": 53872,
"text": "There are two modes − Native Mode (SQL Server Mode) and Share Point Mode."
},
{
"code": null,
"e": 54069,
"s": 53946,
"text": "There are two models − Tabular Model (For Team and Personal Analysis) and Multi Dimensions Model (For Corporate Analysis)."
},
{
"code": null,
"e": 54201,
"s": 54069,
"text": "The BIDS (Business Intelligence Studio till 2008 R2) and SSDT (SQL Server Data Tools from 2012) are environments to work with SSAS."
},
{
"code": null,
"e": 54333,
"s": 54201,
"text": "Step 1 − Open either BIDS\\SSDT based on the version from the Microsoft SQL Server programs group. The following screen will appear."
},
{
"code": null,
"e": 54497,
"s": 54333,
"text": "Step 2 − The above screen shows SSDT has opened. Go to file on the top left corner in the above image and click New. Select project and the following screen opens."
},
{
"code": null,
"e": 54641,
"s": 54497,
"text": "Step 3 − Select Analysis Services in the above screen under Business Intelligence as seen on the top left corner. The following screen pops up."
},
{
"code": null,
"e": 54780,
"s": 54641,
"text": "Step 4 − In the above screen, select any one option from the listed five options based on your requirement to work with Analysis services."
},
{
"code": null,
"e": 54815,
"s": 54780,
"text": "\n 32 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 54830,
"s": 54815,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 54865,
"s": 54830,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 54884,
"s": 54865,
"text": " Dr. Saatya Prasad"
},
{
"code": null,
"e": 54919,
"s": 54884,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 54934,
"s": 54919,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 54967,
"s": 54934,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 54982,
"s": 54967,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 55017,
"s": 54982,
"text": "\n 239 Lectures \n 33 hours \n"
},
{
"code": null,
"e": 55034,
"s": 55017,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 55067,
"s": 55034,
"text": "\n 53 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 55081,
"s": 55067,
"text": " Akshay Magre"
},
{
"code": null,
"e": 55088,
"s": 55081,
"text": " Print"
},
{
"code": null,
"e": 55099,
"s": 55088,
"text": " Add Notes"
}
] |
Using Recurrent Neural Networks for Track Detection In Noise | by Jüri Sildam | Towards Data Science | By observing sonar or radar screens, humans can easily detect tracks, formed by objects that typically are far away and are observed only as points. The respective point patterns can be visually detected even in noisy images. Moreover, in cases when tracks keep appearing and disappearing in noise, trained operators can quickly decide whether unconnected tracks themselves form patterns of tracks that are likely related to the same object.
The above-mentioned observations are needed to make a decision about presence or absence of an object. For example, if the object is very bright as compared to noise then such a decision can be made by observing (or detecting) just a single bright point. However, if the points related to noise exhibit brightnesses comparable to the object of interest, we end up with a number of false detections. As the next step in object detection, we assume that noise is homogeneous and therefore the points related to noise do not form tracks. However, if noise distribution is not homogeneous, the points related to noise too can form short tracks. Thus, we end up with false track detections. Such a situation occurs when due to noise, the tracks of the object of interest are short so that they appear and disappear exhibiting noise-track intermittency. In this is a case, a human observer would look for the pattern of tracks that can be related to a single object. Once such a pattern of tracks is found, the presence of an object of interest can be declared.
On another hand, with the increasing noise level and with the increasing number of objects to track, the existing tracking algorithms based on modeling of object motion, have to deal with the exponentially increasing computational complexity. It should also be noted that carrying out respective calculations increase data processing power consumption along with a need for powerful processors and an increased memory.
Recent significant progress in various applications of machine learning (e.g. deep learning, DL) have demonstrated the results matching or even exceeding human’s abilities (e.g. in playing chess or go). A success in implementation of trained DLs on small single-board computers such as Raspberry Pi indicate the possible new directions of DL application to the problems of object detection, tracking, and localization using inexpensive autonomous, low power consuming robots.
In this work, I will look into a toy problem of track detection in binary (i.e. black and white) images. The respective Python code, written as the Jupyter notebook, uses Keras framework and is available here. Below, I show the main blocks of this code and the output of the calculations.
The problem shown below is not a trivial one, and its success warrants further research in this area. Below I implemented a type of Recurrent Neural Network (RNN), called the long-short-time-memory (LSTM) network. The idea is to apply an algorithm that can use spatial and time information concurrently, such that is able to capture patterns of an object exhibiting intermittent appearance and disappearance in noise.
Prior getting to concrete examples, I import all Python modules, required for this work.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib.font_manager import FontProperties
%matplotlib inline
from keras.models import model_from_json
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.layers.recurrent import LSTM
from keras import optimizers
import utils
Now I load the pre-generated artificial data required for the LSTM training and testing. Note that I have used 3000 and 300 images for training and testing respectively. These images were stacked into 3D matrices, each image having a size of 10 by 30 pixels. Each image was labeled as either noisy (y[i] = 0) or including track (y[i]=1).
DATA_PATH = ''
test_fname_start = 'test_linear'
train_fname_start = 'train_linear'
no_files = 1
train_X, train_y_true = utils.load_data(DATA_PATH, train_fname_start, no_files)
test_X, test_y_true = utils.load_data(DATA_PATH, test_fname_start, no_files)
print(train_X.shape, test_X.shape, train_y_true.shape, test_y_true.shape)
(3000, 10, 30) (300, 10, 30) (3000, 1) (300, 1)
Next, to show the structure of the data, we look into a few example images.
font0 = FontProperties();
font1 = font0.copy();
font1.set_size('xx-large');
font1.set_weight('bold');
fig = plt.figure(figsize=(30,20));
cmap = colors.ListedColormap(['white', 'black']);
#rect = l,b,w,h
rect1 = 0.2, 0.1, 0.1, 0.2
rect2 = 0.4, 0.1, 0.3, 0.2
start = 2*3
ax1= fig.add_axes(rect1);
ax2 = fig.add_axes(rect2);
im = test_X[start,:,:].copy()
ax1.imshow(im.transpose(),origin='lower', cmap=cmap, interpolation = 'none',aspect='auto');
ax1.set_title('Example of noise image',fontproperties=font1);
ax1.set_xlabel('non-dim time',fontproperties=font1);
ax1.set_ylabel('non-dim range',fontproperties=font1);
ims = test_X[start:start+3,:,:].copy()
im = np.reshape(ims, (ims.shape[0]*ims.shape[1],ims.shape[2]));
ax2.imshow(im.transpose(),origin='lower', cmap=cmap, interpolation = 'none',aspect='auto');
ax2.set_title('Example of three stacked images: noise, noise+track, noise+track',fontproperties=font1);
ax2.set_xlabel('non-dim time',fontproperties=font1);
ax2.set_ylabel('non-dim range',fontproperties=font1);
ax2.set_xlim(0,30);
ax2.set_ylim(0.30);
for i in range(0,30,10):
ax2.plot([i, i],[0, 30],'r-');
Above, the left image shows a typical distribution of noise marked by black rectangles. On the right, the three images have been concatenated. From the left to the right, the first image corresponds to noise shown on the left, and the next two images show a linear track, looking as a staircase consisting of small black rectangular boxes going down through the middle and the rightmost images.
For purposes of LSTM processing, in this work, the images are processed in the sequences of ten. Below, I show only the first three to stress the 3D arrangement of data.
fig = plt.figure(figsize=(30,20));
cmap = colors.ListedColormap(['white', 'black']);
#rect = l,b,w,h
rect1 = 0.2, 0.1, 0.1, 0.2
rect2 = 0.22, 0.11, 0.1, 0.2
rect3 = 0.25, 0.12, 0.1, 0.2
ax1= fig.add_axes(rect3);
im = test_X[start+2,:,:].copy()
ax1.imshow(im.transpose(),origin='lower', cmap=cmap, interpolation = 'none',aspect='auto');
ax2= fig.add_axes(rect2);
im = test_X[start+1,:,:].copy()
ax2.imshow(im.transpose(),origin='lower', cmap=cmap, interpolation = 'none',aspect='auto');
ax3= fig.add_axes(rect1);
im = test_X[start,:,:].copy()
ax3.imshow(im.transpose(),origin='lower', cmap=cmap, interpolation = 'none',aspect='auto');
ax3.set_xlabel('non-dim time',fontproperties=font1);
ax3.set_ylabel('non-dim range',fontproperties=font1);
I use LSTM model architecture in Keras framework with the Tensorflow backend. Below, if ‘keras_model_load’ is set to True, the pre-trained model will be used. If ‘keras_model_load’ is set to False, the model is trained from scratch.
keras_model_load = True # False, True
batch_size = 3
if keras_model_load:
model_name = 'keras_3k_dat_linmodel'
model_lin = utils.load_keras_model(model_name)
else:
np.random.seed(17)
input_shape = (train_X.shape[1],train_X.shape[2])
hidden_size = 16
model_lin = Sequential()
model_lin.add(LSTM(input_shape=input_shape, output_dim=hidden_size, return_sequences=True))
model_lin.add(Dense(hidden_size))
model_lin.add(Activation('relu'))
model_lin.add(Dense(output_dim=1, activation="relu"))
optimizer = optimizers.Adam(clipnorm=2)
model_lin.compile(optimizer=optimizer, loss='binary_crossentropy')
model_lin.summary()
if not keras_model_load:
y3D = utils.track_y_3D(train_y_true, n = dxn)
model_lin.fit(train_X, y3D, epochs = 100, batch_size = batch_size, verbose = 1, shuffle=True)
Now we use the trained model to predict labels of the input images used for training as well as for testing.
Y_estim_train = model_lin.predict(train_X, batch_size = batch_size)
Y_estim_test = model_lin.predict(test_X, batch_size = batch_size)
print(Y_estim_train.shape, Y_estim_test.shape)
(3000, 10, 1) (300, 10, 1)
To estimate one label per image, we need to average over 10 labels that were generated for 10 time steps of each image.
Y_estim_train=Y_estim_train.sum(axis=1)/Y_estim_train.shape[1]
Y_estim_test=Y_estim_test.sum(axis=1)/Y_estim_test.shape[1]
Since the predicted output is real valued, using the threshold value of 0.5, I categorized the output into two categories: the ones corresponding to the track presence (y=1), and the ones corresponding to the track absence (y=0). Below y corresponds either to the Y_estim_test or to the Y_estim_train.
Y_estim_test[Y_estim_test < 0.5]=0
Y_estim_test[Y_estim_test >= 0.5]=1
Y_estim_train[Y_estim_train < 0.5]=0
Y_estim_train[Y_estim_train >= 0.5]=1
Below is shown a subset of training and test results. On top of each concatenated image, the distribution of averaged labels is plotted. The blue and the red colors show respectively the true and the estimated labels. Note that both label types match perfectly for the training subset shown below.
Finally, I estimated the probability of detection (Pd) and the probability of false alarms (Pfa), applied to the test, and to the training data. This metrics is often used for receiver operating characterisitc estimation.
Looking at the output shown above, one can see that the trained model tends to overfit (compare Pd=0.988 for training, and Pd=0.629 for test data). My experience with the numerous test runs (not shown here), indicates that for this dataset, over-fitting tended to decrease with the increase of training data size, which was to be expected.
Improvement of the accuracy as a result of finding a better RNN architecture and the fine-tuning of hyper-parameters is one of the potential future research topics.
In spite of simplicity of the presented data generation algorithm, the data generating model output closely resembles a real scenario of active sonars.
The scenario analyzed in this work, at any given time was limited to the detection of a single track. Track detections were carried out without the help of object motion modeling algorithms. The latter do not require any training (besides some fine-tuning) but operationally need more expensive computations.
This study is a first step, based on an LSTM neural network, towards the improvement of confidence of object detection via discovery and detection of patterns of tracks (or track stitching) belonging to the same objects, which due to noise appear and disappear on sonar or radar screens. | [
{
"code": null,
"e": 613,
"s": 171,
"text": "By observing sonar or radar screens, humans can easily detect tracks, formed by objects that typically are far away and are observed only as points. The respective point patterns can be visually detected even in noisy images. Moreover, in cases when tracks keep appearing and disappearing in noise, trained operators can quickly decide whether unconnected tracks themselves form patterns of tracks that are likely related to the same object."
},
{
"code": null,
"e": 1669,
"s": 613,
"text": "The above-mentioned observations are needed to make a decision about presence or absence of an object. For example, if the object is very bright as compared to noise then such a decision can be made by observing (or detecting) just a single bright point. However, if the points related to noise exhibit brightnesses comparable to the object of interest, we end up with a number of false detections. As the next step in object detection, we assume that noise is homogeneous and therefore the points related to noise do not form tracks. However, if noise distribution is not homogeneous, the points related to noise too can form short tracks. Thus, we end up with false track detections. Such a situation occurs when due to noise, the tracks of the object of interest are short so that they appear and disappear exhibiting noise-track intermittency. In this is a case, a human observer would look for the pattern of tracks that can be related to a single object. Once such a pattern of tracks is found, the presence of an object of interest can be declared."
},
{
"code": null,
"e": 2088,
"s": 1669,
"text": "On another hand, with the increasing noise level and with the increasing number of objects to track, the existing tracking algorithms based on modeling of object motion, have to deal with the exponentially increasing computational complexity. It should also be noted that carrying out respective calculations increase data processing power consumption along with a need for powerful processors and an increased memory."
},
{
"code": null,
"e": 2564,
"s": 2088,
"text": "Recent significant progress in various applications of machine learning (e.g. deep learning, DL) have demonstrated the results matching or even exceeding human’s abilities (e.g. in playing chess or go). A success in implementation of trained DLs on small single-board computers such as Raspberry Pi indicate the possible new directions of DL application to the problems of object detection, tracking, and localization using inexpensive autonomous, low power consuming robots."
},
{
"code": null,
"e": 2853,
"s": 2564,
"text": "In this work, I will look into a toy problem of track detection in binary (i.e. black and white) images. The respective Python code, written as the Jupyter notebook, uses Keras framework and is available here. Below, I show the main blocks of this code and the output of the calculations."
},
{
"code": null,
"e": 3271,
"s": 2853,
"text": "The problem shown below is not a trivial one, and its success warrants further research in this area. Below I implemented a type of Recurrent Neural Network (RNN), called the long-short-time-memory (LSTM) network. The idea is to apply an algorithm that can use spatial and time information concurrently, such that is able to capture patterns of an object exhibiting intermittent appearance and disappearance in noise."
},
{
"code": null,
"e": 3360,
"s": 3271,
"text": "Prior getting to concrete examples, I import all Python modules, required for this work."
},
{
"code": null,
"e": 3719,
"s": 3360,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\nfrom matplotlib.font_manager import FontProperties\n%matplotlib inline\n\nfrom keras.models import model_from_json\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\nfrom keras.layers.recurrent import LSTM\nfrom keras import optimizers\nimport utils"
},
{
"code": null,
"e": 4057,
"s": 3719,
"text": "Now I load the pre-generated artificial data required for the LSTM training and testing. Note that I have used 3000 and 300 images for training and testing respectively. These images were stacked into 3D matrices, each image having a size of 10 by 30 pixels. Each image was labeled as either noisy (y[i] = 0) or including track (y[i]=1)."
},
{
"code": null,
"e": 4384,
"s": 4057,
"text": "DATA_PATH = ''\ntest_fname_start = 'test_linear'\ntrain_fname_start = 'train_linear'\nno_files = 1\ntrain_X, train_y_true = utils.load_data(DATA_PATH, train_fname_start, no_files)\ntest_X, test_y_true = utils.load_data(DATA_PATH, test_fname_start, no_files)\nprint(train_X.shape, test_X.shape, train_y_true.shape, test_y_true.shape)"
},
{
"code": null,
"e": 4432,
"s": 4384,
"text": "(3000, 10, 30) (300, 10, 30) (3000, 1) (300, 1)"
},
{
"code": null,
"e": 4508,
"s": 4432,
"text": "Next, to show the structure of the data, we look into a few example images."
},
{
"code": null,
"e": 5629,
"s": 4508,
"text": "font0 = FontProperties();\nfont1 = font0.copy();\nfont1.set_size('xx-large');\nfont1.set_weight('bold');\n\nfig = plt.figure(figsize=(30,20));\ncmap = colors.ListedColormap(['white', 'black']);\n#rect = l,b,w,h\nrect1 = 0.2, 0.1, 0.1, 0.2\nrect2 = 0.4, 0.1, 0.3, 0.2\nstart = 2*3 \nax1= fig.add_axes(rect1);\nax2 = fig.add_axes(rect2);\nim = test_X[start,:,:].copy()\nax1.imshow(im.transpose(),origin='lower', cmap=cmap, interpolation = 'none',aspect='auto');\nax1.set_title('Example of noise image',fontproperties=font1);\nax1.set_xlabel('non-dim time',fontproperties=font1);\nax1.set_ylabel('non-dim range',fontproperties=font1);\nims = test_X[start:start+3,:,:].copy()\nim = np.reshape(ims, (ims.shape[0]*ims.shape[1],ims.shape[2]));\nax2.imshow(im.transpose(),origin='lower', cmap=cmap, interpolation = 'none',aspect='auto');\nax2.set_title('Example of three stacked images: noise, noise+track, noise+track',fontproperties=font1);\nax2.set_xlabel('non-dim time',fontproperties=font1);\nax2.set_ylabel('non-dim range',fontproperties=font1);\nax2.set_xlim(0,30);\nax2.set_ylim(0.30);\nfor i in range(0,30,10):\n ax2.plot([i, i],[0, 30],'r-');"
},
{
"code": null,
"e": 6024,
"s": 5629,
"text": "Above, the left image shows a typical distribution of noise marked by black rectangles. On the right, the three images have been concatenated. From the left to the right, the first image corresponds to noise shown on the left, and the next two images show a linear track, looking as a staircase consisting of small black rectangular boxes going down through the middle and the rightmost images."
},
{
"code": null,
"e": 6194,
"s": 6024,
"text": "For purposes of LSTM processing, in this work, the images are processed in the sequences of ten. Below, I show only the first three to stress the 3D arrangement of data."
},
{
"code": null,
"e": 6936,
"s": 6194,
"text": "fig = plt.figure(figsize=(30,20));\ncmap = colors.ListedColormap(['white', 'black']);\n#rect = l,b,w,h\nrect1 = 0.2, 0.1, 0.1, 0.2\nrect2 = 0.22, 0.11, 0.1, 0.2\nrect3 = 0.25, 0.12, 0.1, 0.2\n\nax1= fig.add_axes(rect3);\nim = test_X[start+2,:,:].copy()\nax1.imshow(im.transpose(),origin='lower', cmap=cmap, interpolation = 'none',aspect='auto');\nax2= fig.add_axes(rect2);\nim = test_X[start+1,:,:].copy()\nax2.imshow(im.transpose(),origin='lower', cmap=cmap, interpolation = 'none',aspect='auto');\nax3= fig.add_axes(rect1);\nim = test_X[start,:,:].copy()\nax3.imshow(im.transpose(),origin='lower', cmap=cmap, interpolation = 'none',aspect='auto');\nax3.set_xlabel('non-dim time',fontproperties=font1);\nax3.set_ylabel('non-dim range',fontproperties=font1);"
},
{
"code": null,
"e": 7169,
"s": 6936,
"text": "I use LSTM model architecture in Keras framework with the Tensorflow backend. Below, if ‘keras_model_load’ is set to True, the pre-trained model will be used. If ‘keras_model_load’ is set to False, the model is trained from scratch."
},
{
"code": null,
"e": 7838,
"s": 7169,
"text": "keras_model_load = True # False, True\nbatch_size = 3\n\nif keras_model_load:\n model_name = 'keras_3k_dat_linmodel'\n model_lin = utils.load_keras_model(model_name)\nelse:\n np.random.seed(17)\n input_shape = (train_X.shape[1],train_X.shape[2])\n hidden_size = 16\n model_lin = Sequential()\n model_lin.add(LSTM(input_shape=input_shape, output_dim=hidden_size, return_sequences=True))\n model_lin.add(Dense(hidden_size))\n model_lin.add(Activation('relu'))\n model_lin.add(Dense(output_dim=1, activation=\"relu\"))\n optimizer = optimizers.Adam(clipnorm=2)\n model_lin.compile(optimizer=optimizer, loss='binary_crossentropy')\n model_lin.summary()"
},
{
"code": null,
"e": 8011,
"s": 7838,
"text": "if not keras_model_load:\n y3D = utils.track_y_3D(train_y_true, n = dxn)\n model_lin.fit(train_X, y3D, epochs = 100, batch_size = batch_size, verbose = 1, shuffle=True)"
},
{
"code": null,
"e": 8120,
"s": 8011,
"text": "Now we use the trained model to predict labels of the input images used for training as well as for testing."
},
{
"code": null,
"e": 8301,
"s": 8120,
"text": "Y_estim_train = model_lin.predict(train_X, batch_size = batch_size)\nY_estim_test = model_lin.predict(test_X, batch_size = batch_size)\nprint(Y_estim_train.shape, Y_estim_test.shape)"
},
{
"code": null,
"e": 8328,
"s": 8301,
"text": "(3000, 10, 1) (300, 10, 1)"
},
{
"code": null,
"e": 8448,
"s": 8328,
"text": "To estimate one label per image, we need to average over 10 labels that were generated for 10 time steps of each image."
},
{
"code": null,
"e": 8571,
"s": 8448,
"text": "Y_estim_train=Y_estim_train.sum(axis=1)/Y_estim_train.shape[1]\nY_estim_test=Y_estim_test.sum(axis=1)/Y_estim_test.shape[1]"
},
{
"code": null,
"e": 8873,
"s": 8571,
"text": "Since the predicted output is real valued, using the threshold value of 0.5, I categorized the output into two categories: the ones corresponding to the track presence (y=1), and the ones corresponding to the track absence (y=0). Below y corresponds either to the Y_estim_test or to the Y_estim_train."
},
{
"code": null,
"e": 9019,
"s": 8873,
"text": "Y_estim_test[Y_estim_test < 0.5]=0\nY_estim_test[Y_estim_test >= 0.5]=1\nY_estim_train[Y_estim_train < 0.5]=0\nY_estim_train[Y_estim_train >= 0.5]=1"
},
{
"code": null,
"e": 9317,
"s": 9019,
"text": "Below is shown a subset of training and test results. On top of each concatenated image, the distribution of averaged labels is plotted. The blue and the red colors show respectively the true and the estimated labels. Note that both label types match perfectly for the training subset shown below."
},
{
"code": null,
"e": 9539,
"s": 9317,
"text": "Finally, I estimated the probability of detection (Pd) and the probability of false alarms (Pfa), applied to the test, and to the training data. This metrics is often used for receiver operating characterisitc estimation."
},
{
"code": null,
"e": 9879,
"s": 9539,
"text": "Looking at the output shown above, one can see that the trained model tends to overfit (compare Pd=0.988 for training, and Pd=0.629 for test data). My experience with the numerous test runs (not shown here), indicates that for this dataset, over-fitting tended to decrease with the increase of training data size, which was to be expected."
},
{
"code": null,
"e": 10044,
"s": 9879,
"text": "Improvement of the accuracy as a result of finding a better RNN architecture and the fine-tuning of hyper-parameters is one of the potential future research topics."
},
{
"code": null,
"e": 10196,
"s": 10044,
"text": "In spite of simplicity of the presented data generation algorithm, the data generating model output closely resembles a real scenario of active sonars."
},
{
"code": null,
"e": 10505,
"s": 10196,
"text": "The scenario analyzed in this work, at any given time was limited to the detection of a single track. Track detections were carried out without the help of object motion modeling algorithms. The latter do not require any training (besides some fine-tuning) but operationally need more expensive computations."
}
] |
A Complete Guide to Plotting Categorical Variables with Seaborn | by Will Norris | Towards Data Science | · The Data· Categorical Distribution Plots ∘ Box Plots ∘ Violin Plots ∘ Boxen Plot· Categorical Estimate Plots ∘ Bar Plot ∘ Point Plot ∘ Count Plot· Categorical Scatter Plots ∘ Strip Plot ∘ Swarm Plot· Combining Plots· Faceting Data with Catplot· Documentation and Links
In this post we will use one of Seaborn’s conveniently available datasets about the Titanic, which I’m sure many readers have seen before. Seaborn has quite a few datasets ready to be loaded into Python to practice with; they are great for practicing data processing, exploration, and basic machine learning techniques.
titanic = sns.load_dataset('titanic')titanic.head()
titanic.info()titanic['species'].unique()
This data set is great because it has a decent number of entries — almost 900 — while also having an interesting story to dig into. There are lots of questions to ask and relationships between variables to explore making it a great example data set. Most critical for this article is that there is also a good mix of numerical and categorical variables to explore.
We have two different kinds of categorical distribution plots, box plots and violin plots. These kinds of plots allow us to choose a numerical variable, like age, and plot the distribution of age for each category in a selected categorical variable.
Many of us have probably made quite a few box plots over the years. They are an easy and effective way to visualize groups of numerical data through their quartiles. Seaborn makes creating attractive box plots simple and allows us to easily compare an extra dimension with the hue argument that appears in many Seaborn functions.
Basic Boxplot
Lets take a look at distribution of age by passenger class.
plt.figure(figsize=(8,5))sns.boxplot(x='class',y='age',data=titanic, palette='rainbow')plt.title("Age by Passenger Class, Titanic")
We can see that age tends to decrease as you go down in passenger class. That makes sense, young people tend to travel on a budget. Notice how little code this required to create a pretty aesthetically pleasing plot? Seaborn’s basic plots are very polished.
Also pay attention to how we can wrap Matplotlib formatting syntax around our Seaborn plots. This only works when we are using Axis-level functions, which you can read about in another one of my posts about figure-level and axis-level functions in Seaborn.
Adding Hue
Like many other plots available in Seaborn, box plots can take an added hue argument to add another variable for comparison.
Adding the hue shows us that regardless of class the age of passengers that survived was generally lower than those who passed away.
Having the hue for additional comparison allows this box plot to be quite information dense. The more complex the plot gets the longer it will take for viewers to comprehend it, but it is nice to have the option when interesting insights are more easily shown with an added dimension.
Violin plots are not very frequently used but I have found them to be useful on occasion, and they are an interesting change from more popular options. They plot a vertical kernel density plot for each category and a small box plot to summarize important statistics.
plt.figure(figsize=(10,6))sns.violinplot(x='class',y="age",data=titanic, hue='sex', palette='rainbow')plt.title("Violin Plot of Age by Class, Separated by Sex")
While I like this plot, I think it is easier to compare the genders with slightly different formatting:
plt.figure(figsize=(10,6))sns.violinplot(x='class',y="age",data=titanic, hue='sex', split='True', palette='rainbow')plt.title("Violin Plot of Age by Class, Separated by Sex")
When we split the violin on the hue it is a lot easier to see the differences in each KDE. However, the IQR stats aren’t split by the sex anymore; instead they apply to the entire class. So there are trade-offs to styling your plot in certain ways.
The boxen plot, otherwise known as a Letter-value plot, is a box plot meant for large data sets (n > 10,000). It is similar to a traditional box plot, however it essentially just plots more quantiles. With more quantiles, we can see more info about the distribution shape beyond the central 50% of the data; this extra detail is especially present in the tails, where box plots tend to give limited information.
plt.figure(figsize=(8,5))sns.boxenplot(x='class', y='age', data=titanic, palette='rainbow')plt.title("Distribution of Age by Passenger Class")
Just in case there still isn’t enough going on here for you, we can also add a hue to a boxen plot!
plt.figure(figsize=(8,5))sns.boxenplot(x='class', y='age', data=titanic, palette='rainbow', hue='survived')plt.title("Distribution of Age by Passenger Class, Separated by Survival")
We can see that the boxen plot gives us much more information beyond the central 50% of the data. However, keep in mind that boxen plots are meant for larger data sets with entries between 10,000 and 100,000. This data set of under 1,000 entries is definitely not ideal. Here is a link to the paper where boxen plots were created that explains them very well.
Bar plots are classic. You get an estimate of central tendency for a numerical variable for each class on the x axis. Say we were interested in knowing the average fare price of passengers that embarked from different towns:
plt.figure(figsize=(8,5))sns.barplot(x='embark_town',y='fare',data=titanic, palette='rainbow')plt.title("Fare of Passenger by Embarked Town")
Seaborn will take the mean as default, but you can use other measures of central tendency as well. There is a noticeable difference between Cherbourg and the other two, let’s separate the bars by class to see who was boarding in each town.
plt.figure(figsize=(8,5))sns.barplot(x='embark_town',y='fare',data=titanic, palette='rainbow', hue='class')plt.title("Fare of Passenger by Embarked Town, Divided by Class")
Now we can see that the average fare price in Cherbourg was so high due to some very expensive first class tickets. The large error bar on the fare price in first class from Cherbourg is also interesting; that could mean there is a lot of separation between some very high price outlier tickets and the rest. We’ll explore this further in the combined plots section below!
Point plots convey the same information as a bar plot with a different style. They can be good for overlaying with different plots since they have a smaller footprint in the space.
plt.figure(figsize=(8,5))sns.pointplot(x='embark_town',y='fare',data=titanic)plt.title("Average Fare Price by Embarked Town")
plt.figure(figsize=(8,5))sns.pointplot(x='embark_town',y='fare',data=titanic, hue='class')plt.title("Average Fare Price by Embarked Town, Separated by Sex")
Count Plots are essentially histograms across a categorical variable. They take all the same arguments as bar plots in Seaborn, which helps keep things simple.
plt.figure(figsize=(8,5))sns.countplot(x='embark_town',data=titanic, palette='rainbow')plt.title("Count of Passengers that Embarked in Each City")
plt.figure(figsize=(8,5))sns.countplot(x='embark_town',data=titanic, palette='rainbow',hue='sex')plt.title("Count of Passengers that Embarked in Each City, Separated by Sex")
Both strip plots and swarm plots are essentially scatter plots where one variable is categorical. I like to use them as additions to other kinds of plots, which we’ll discuss below as they are useful for quickly visualizing the number of data points in a group.
plt.figure(figsize=(12,8))sns.stripplot(x='class', y='age', data=titanic, jitter=True, hue='alive', dodge=True, palette='viridis')
I don’t love the way strip plots look when you have a lot of data points. But swarm plots might make this a little more useful. Strip plots can look great with less data points and they can convey really interesting attributes of your data since they don’t hide details behind aggregation.
Swarm plots are fantastic because they offer an easy way to show the individual data points in a distribution. Instead of a big blob like the strip plot, the swarm plot simply adjusts the points along the x-axis. Although they also don’t scale well with tons of values, they offer more organized insight.
plt.figure(figsize=(10,7))sns.swarmplot(x='class', y='age', data=titanic, hue='alive', dodge=True, palette='viridis')plt.title("Age by Passenger Class, Separated by Survival")
Here we can more easily see where the dense age groups are rather than the difficult to interpret strip plot above.
One of my favorite uses for a swarm plot is to enhance another kind of plot since they convey relative volume very well. As we will see in the violin plot below even though at one point the KDE values may look similarly “large”, the volume of data points in each of the classes may be quite different. We can add a swarm plot on top of our violin plot to show the individual data points that help to give us a more complete picture.
plt.figure(figsize=(12,8))sns.violinplot(x='class',y="age", data=titanic, hue='survived', split='True', palette='rainbow')sns.swarmplot(x='class',y="age", data=titanic, hue='survived', dodge='True', color='grey', alpha=.8, s=4)plt.title("Age by Passenger Class, Separated by Survival")
By adding the swarm plot we can see where the actual majority of data points are contained. I have seen Violin plots misinterpreted many times where a viewer may assume a relatively similar number of ~25 year old third class passengers lived and survived in third class, and the swarm plot does a great job clearing that up.
plt.figure(figsize=(12,8))sns.boxplot(x='class',y='age',hue='survived',data=titanic, palette='rainbow')sns.swarmplot(x='class',y='age',hue='survived', dodge=True,data=titanic, alpha=.8,color='grey',s=4)plt.title("Age by Passenger Class, Separated by Survival")
The story is very similar with box plots as with violin plots. Summary statistics of each group are very useful, however adding the swarm plot helps to show a more complete story.
Remember when were looking at the average ticket prices by the town embarked from and separated by passenger class earlier?
We saw that the price of Cherbourg tickets was high, which turned out was due to the mean price of first class tickets being so high in Cherbourg. We also had this large error bar on the mean price of first class tickets in Cherbourg. Using a strip plot, we can try to get a better understanding of what’s happening there.
plt.figure(figsize=(12,7))sns.barplot(x='embark_town',y='fare',data=titanic, palette='rainbow', hue='class')sns.stripplot(x='embark_town',y="fare",data=titanic, hue='class', dodge='True', color='grey', alpha=.8, s=2)plt.title("Fare of Passenger by Embarked Town, Divided by Class")
Now we can see that there were two very expensive tickets sold in Cherbourg that skewed the mean, which is why our first class bar plot had a large error bar. While two people paid close to double the next most expensive first class tickets, there were also people in first class that paid a lower fare than some of those who boarded in second class! We get all kinds of new insights when we combine plots.
Catplot() is the figure-level function that can create all of the above plots we have discussed. Figure-level functions plot a Seaborn object and interface with the Matplotlib API instead of creating a Matplotlib object like Seaborn’s axis-level functions.
While working with figure-level functions is generally more complex and has less clear documentation, there are some strengths that make them worth using in certain cases. They are particularly good at faceting data into subplots as we can see below.
g = sns.catplot(x='class',y='survived', col = 'who', data=titanic, kind='bar', aspect=.6, palette='Set2')(g.set_axis_labels("Class", "Survival Rate") .set_titles("{col_name}") .set(ylim=(0,1)))plt.tight_layout()plt.savefig('seaborn_catplot.png', dpi=1000)
Faceting data allows us to see data at different granularities. Faceting is really a fancy word for separating data into classes along a specific dimension(s). So here we are separating the data along the “who” variable, which allows us to plot each type of person separately.
Being able to say col='<column_name>' to automatically facet is a powerful option that most figure-level functions have access to. Accomplishing the same thing in Matplotlib requires significantly more time subsetting data and creating multiple subplots manually. I discuss the power of figure-level plotting more in this article.
Don’t forget that we could still add a hue argument to add even more information to this plot! Faceting data with Seaborn’s figure-level functionality can be an excellent way to make more complex plots.
You will notice that Seaborn figures require different functions for formatting, however saving the plot can still be done via plt.savefig() since the final Seaborn figure interfaces with the Matplotlib API. I won’t get into detail on figure-level plotting since there is a lot to discuss, but do read my other article about the topic if you are curious.
We’ve gone through a lot of different plots in this post. I hope that you have seen how easy Seaborn can make an aesthetically pleasing plot that conveys a lot of useful information to the viewer. Once I got used to using it, Seaborn has saved me a massive amount of time writing fewer lines of code to produce pleasing visualizations.
Box Plot
Violin Plot
Boxen Plot
Strip Plot
Swarm Plot
Point Plot
Bar Plot
Count Plot
Catplot
Note: If you are enjoying reading my and others’ content here on Medium, consider subscribing using the link below to support the creation of content like this and unlock unlimited stories! | [
{
"code": null,
"e": 445,
"s": 172,
"text": "· The Data· Categorical Distribution Plots ∘ Box Plots ∘ Violin Plots ∘ Boxen Plot· Categorical Estimate Plots ∘ Bar Plot ∘ Point Plot ∘ Count Plot· Categorical Scatter Plots ∘ Strip Plot ∘ Swarm Plot· Combining Plots· Faceting Data with Catplot· Documentation and Links"
},
{
"code": null,
"e": 765,
"s": 445,
"text": "In this post we will use one of Seaborn’s conveniently available datasets about the Titanic, which I’m sure many readers have seen before. Seaborn has quite a few datasets ready to be loaded into Python to practice with; they are great for practicing data processing, exploration, and basic machine learning techniques."
},
{
"code": null,
"e": 817,
"s": 765,
"text": "titanic = sns.load_dataset('titanic')titanic.head()"
},
{
"code": null,
"e": 859,
"s": 817,
"text": "titanic.info()titanic['species'].unique()"
},
{
"code": null,
"e": 1224,
"s": 859,
"text": "This data set is great because it has a decent number of entries — almost 900 — while also having an interesting story to dig into. There are lots of questions to ask and relationships between variables to explore making it a great example data set. Most critical for this article is that there is also a good mix of numerical and categorical variables to explore."
},
{
"code": null,
"e": 1474,
"s": 1224,
"text": "We have two different kinds of categorical distribution plots, box plots and violin plots. These kinds of plots allow us to choose a numerical variable, like age, and plot the distribution of age for each category in a selected categorical variable."
},
{
"code": null,
"e": 1804,
"s": 1474,
"text": "Many of us have probably made quite a few box plots over the years. They are an easy and effective way to visualize groups of numerical data through their quartiles. Seaborn makes creating attractive box plots simple and allows us to easily compare an extra dimension with the hue argument that appears in many Seaborn functions."
},
{
"code": null,
"e": 1818,
"s": 1804,
"text": "Basic Boxplot"
},
{
"code": null,
"e": 1878,
"s": 1818,
"text": "Lets take a look at distribution of age by passenger class."
},
{
"code": null,
"e": 2010,
"s": 1878,
"text": "plt.figure(figsize=(8,5))sns.boxplot(x='class',y='age',data=titanic, palette='rainbow')plt.title(\"Age by Passenger Class, Titanic\")"
},
{
"code": null,
"e": 2268,
"s": 2010,
"text": "We can see that age tends to decrease as you go down in passenger class. That makes sense, young people tend to travel on a budget. Notice how little code this required to create a pretty aesthetically pleasing plot? Seaborn’s basic plots are very polished."
},
{
"code": null,
"e": 2525,
"s": 2268,
"text": "Also pay attention to how we can wrap Matplotlib formatting syntax around our Seaborn plots. This only works when we are using Axis-level functions, which you can read about in another one of my posts about figure-level and axis-level functions in Seaborn."
},
{
"code": null,
"e": 2536,
"s": 2525,
"text": "Adding Hue"
},
{
"code": null,
"e": 2661,
"s": 2536,
"text": "Like many other plots available in Seaborn, box plots can take an added hue argument to add another variable for comparison."
},
{
"code": null,
"e": 2794,
"s": 2661,
"text": "Adding the hue shows us that regardless of class the age of passengers that survived was generally lower than those who passed away."
},
{
"code": null,
"e": 3079,
"s": 2794,
"text": "Having the hue for additional comparison allows this box plot to be quite information dense. The more complex the plot gets the longer it will take for viewers to comprehend it, but it is nice to have the option when interesting insights are more easily shown with an added dimension."
},
{
"code": null,
"e": 3346,
"s": 3079,
"text": "Violin plots are not very frequently used but I have found them to be useful on occasion, and they are an interesting change from more popular options. They plot a vertical kernel density plot for each category and a small box plot to summarize important statistics."
},
{
"code": null,
"e": 3507,
"s": 3346,
"text": "plt.figure(figsize=(10,6))sns.violinplot(x='class',y=\"age\",data=titanic, hue='sex', palette='rainbow')plt.title(\"Violin Plot of Age by Class, Separated by Sex\")"
},
{
"code": null,
"e": 3611,
"s": 3507,
"text": "While I like this plot, I think it is easier to compare the genders with slightly different formatting:"
},
{
"code": null,
"e": 3786,
"s": 3611,
"text": "plt.figure(figsize=(10,6))sns.violinplot(x='class',y=\"age\",data=titanic, hue='sex', split='True', palette='rainbow')plt.title(\"Violin Plot of Age by Class, Separated by Sex\")"
},
{
"code": null,
"e": 4035,
"s": 3786,
"text": "When we split the violin on the hue it is a lot easier to see the differences in each KDE. However, the IQR stats aren’t split by the sex anymore; instead they apply to the entire class. So there are trade-offs to styling your plot in certain ways."
},
{
"code": null,
"e": 4447,
"s": 4035,
"text": "The boxen plot, otherwise known as a Letter-value plot, is a box plot meant for large data sets (n > 10,000). It is similar to a traditional box plot, however it essentially just plots more quantiles. With more quantiles, we can see more info about the distribution shape beyond the central 50% of the data; this extra detail is especially present in the tails, where box plots tend to give limited information."
},
{
"code": null,
"e": 4590,
"s": 4447,
"text": "plt.figure(figsize=(8,5))sns.boxenplot(x='class', y='age', data=titanic, palette='rainbow')plt.title(\"Distribution of Age by Passenger Class\")"
},
{
"code": null,
"e": 4690,
"s": 4590,
"text": "Just in case there still isn’t enough going on here for you, we can also add a hue to a boxen plot!"
},
{
"code": null,
"e": 4872,
"s": 4690,
"text": "plt.figure(figsize=(8,5))sns.boxenplot(x='class', y='age', data=titanic, palette='rainbow', hue='survived')plt.title(\"Distribution of Age by Passenger Class, Separated by Survival\")"
},
{
"code": null,
"e": 5232,
"s": 4872,
"text": "We can see that the boxen plot gives us much more information beyond the central 50% of the data. However, keep in mind that boxen plots are meant for larger data sets with entries between 10,000 and 100,000. This data set of under 1,000 entries is definitely not ideal. Here is a link to the paper where boxen plots were created that explains them very well."
},
{
"code": null,
"e": 5457,
"s": 5232,
"text": "Bar plots are classic. You get an estimate of central tendency for a numerical variable for each class on the x axis. Say we were interested in knowing the average fare price of passengers that embarked from different towns:"
},
{
"code": null,
"e": 5599,
"s": 5457,
"text": "plt.figure(figsize=(8,5))sns.barplot(x='embark_town',y='fare',data=titanic, palette='rainbow')plt.title(\"Fare of Passenger by Embarked Town\")"
},
{
"code": null,
"e": 5839,
"s": 5599,
"text": "Seaborn will take the mean as default, but you can use other measures of central tendency as well. There is a noticeable difference between Cherbourg and the other two, let’s separate the bars by class to see who was boarding in each town."
},
{
"code": null,
"e": 6012,
"s": 5839,
"text": "plt.figure(figsize=(8,5))sns.barplot(x='embark_town',y='fare',data=titanic, palette='rainbow', hue='class')plt.title(\"Fare of Passenger by Embarked Town, Divided by Class\")"
},
{
"code": null,
"e": 6385,
"s": 6012,
"text": "Now we can see that the average fare price in Cherbourg was so high due to some very expensive first class tickets. The large error bar on the fare price in first class from Cherbourg is also interesting; that could mean there is a lot of separation between some very high price outlier tickets and the rest. We’ll explore this further in the combined plots section below!"
},
{
"code": null,
"e": 6566,
"s": 6385,
"text": "Point plots convey the same information as a bar plot with a different style. They can be good for overlaying with different plots since they have a smaller footprint in the space."
},
{
"code": null,
"e": 6692,
"s": 6566,
"text": "plt.figure(figsize=(8,5))sns.pointplot(x='embark_town',y='fare',data=titanic)plt.title(\"Average Fare Price by Embarked Town\")"
},
{
"code": null,
"e": 6849,
"s": 6692,
"text": "plt.figure(figsize=(8,5))sns.pointplot(x='embark_town',y='fare',data=titanic, hue='class')plt.title(\"Average Fare Price by Embarked Town, Separated by Sex\")"
},
{
"code": null,
"e": 7009,
"s": 6849,
"text": "Count Plots are essentially histograms across a categorical variable. They take all the same arguments as bar plots in Seaborn, which helps keep things simple."
},
{
"code": null,
"e": 7156,
"s": 7009,
"text": "plt.figure(figsize=(8,5))sns.countplot(x='embark_town',data=titanic, palette='rainbow')plt.title(\"Count of Passengers that Embarked in Each City\")"
},
{
"code": null,
"e": 7331,
"s": 7156,
"text": "plt.figure(figsize=(8,5))sns.countplot(x='embark_town',data=titanic, palette='rainbow',hue='sex')plt.title(\"Count of Passengers that Embarked in Each City, Separated by Sex\")"
},
{
"code": null,
"e": 7593,
"s": 7331,
"text": "Both strip plots and swarm plots are essentially scatter plots where one variable is categorical. I like to use them as additions to other kinds of plots, which we’ll discuss below as they are useful for quickly visualizing the number of data points in a group."
},
{
"code": null,
"e": 7724,
"s": 7593,
"text": "plt.figure(figsize=(12,8))sns.stripplot(x='class', y='age', data=titanic, jitter=True, hue='alive', dodge=True, palette='viridis')"
},
{
"code": null,
"e": 8014,
"s": 7724,
"text": "I don’t love the way strip plots look when you have a lot of data points. But swarm plots might make this a little more useful. Strip plots can look great with less data points and they can convey really interesting attributes of your data since they don’t hide details behind aggregation."
},
{
"code": null,
"e": 8319,
"s": 8014,
"text": "Swarm plots are fantastic because they offer an easy way to show the individual data points in a distribution. Instead of a big blob like the strip plot, the swarm plot simply adjusts the points along the x-axis. Although they also don’t scale well with tons of values, they offer more organized insight."
},
{
"code": null,
"e": 8495,
"s": 8319,
"text": "plt.figure(figsize=(10,7))sns.swarmplot(x='class', y='age', data=titanic, hue='alive', dodge=True, palette='viridis')plt.title(\"Age by Passenger Class, Separated by Survival\")"
},
{
"code": null,
"e": 8611,
"s": 8495,
"text": "Here we can more easily see where the dense age groups are rather than the difficult to interpret strip plot above."
},
{
"code": null,
"e": 9044,
"s": 8611,
"text": "One of my favorite uses for a swarm plot is to enhance another kind of plot since they convey relative volume very well. As we will see in the violin plot below even though at one point the KDE values may look similarly “large”, the volume of data points in each of the classes may be quite different. We can add a swarm plot on top of our violin plot to show the individual data points that help to give us a more complete picture."
},
{
"code": null,
"e": 9330,
"s": 9044,
"text": "plt.figure(figsize=(12,8))sns.violinplot(x='class',y=\"age\", data=titanic, hue='survived', split='True', palette='rainbow')sns.swarmplot(x='class',y=\"age\", data=titanic, hue='survived', dodge='True', color='grey', alpha=.8, s=4)plt.title(\"Age by Passenger Class, Separated by Survival\")"
},
{
"code": null,
"e": 9655,
"s": 9330,
"text": "By adding the swarm plot we can see where the actual majority of data points are contained. I have seen Violin plots misinterpreted many times where a viewer may assume a relatively similar number of ~25 year old third class passengers lived and survived in third class, and the swarm plot does a great job clearing that up."
},
{
"code": null,
"e": 9916,
"s": 9655,
"text": "plt.figure(figsize=(12,8))sns.boxplot(x='class',y='age',hue='survived',data=titanic, palette='rainbow')sns.swarmplot(x='class',y='age',hue='survived', dodge=True,data=titanic, alpha=.8,color='grey',s=4)plt.title(\"Age by Passenger Class, Separated by Survival\")"
},
{
"code": null,
"e": 10096,
"s": 9916,
"text": "The story is very similar with box plots as with violin plots. Summary statistics of each group are very useful, however adding the swarm plot helps to show a more complete story."
},
{
"code": null,
"e": 10220,
"s": 10096,
"text": "Remember when were looking at the average ticket prices by the town embarked from and separated by passenger class earlier?"
},
{
"code": null,
"e": 10543,
"s": 10220,
"text": "We saw that the price of Cherbourg tickets was high, which turned out was due to the mean price of first class tickets being so high in Cherbourg. We also had this large error bar on the mean price of first class tickets in Cherbourg. Using a strip plot, we can try to get a better understanding of what’s happening there."
},
{
"code": null,
"e": 10825,
"s": 10543,
"text": "plt.figure(figsize=(12,7))sns.barplot(x='embark_town',y='fare',data=titanic, palette='rainbow', hue='class')sns.stripplot(x='embark_town',y=\"fare\",data=titanic, hue='class', dodge='True', color='grey', alpha=.8, s=2)plt.title(\"Fare of Passenger by Embarked Town, Divided by Class\")"
},
{
"code": null,
"e": 11232,
"s": 10825,
"text": "Now we can see that there were two very expensive tickets sold in Cherbourg that skewed the mean, which is why our first class bar plot had a large error bar. While two people paid close to double the next most expensive first class tickets, there were also people in first class that paid a lower fare than some of those who boarded in second class! We get all kinds of new insights when we combine plots."
},
{
"code": null,
"e": 11489,
"s": 11232,
"text": "Catplot() is the figure-level function that can create all of the above plots we have discussed. Figure-level functions plot a Seaborn object and interface with the Matplotlib API instead of creating a Matplotlib object like Seaborn’s axis-level functions."
},
{
"code": null,
"e": 11740,
"s": 11489,
"text": "While working with figure-level functions is generally more complex and has less clear documentation, there are some strengths that make them worth using in certain cases. They are particularly good at faceting data into subplots as we can see below."
},
{
"code": null,
"e": 12013,
"s": 11740,
"text": "g = sns.catplot(x='class',y='survived', col = 'who', data=titanic, kind='bar', aspect=.6, palette='Set2')(g.set_axis_labels(\"Class\", \"Survival Rate\") .set_titles(\"{col_name}\") .set(ylim=(0,1)))plt.tight_layout()plt.savefig('seaborn_catplot.png', dpi=1000)"
},
{
"code": null,
"e": 12290,
"s": 12013,
"text": "Faceting data allows us to see data at different granularities. Faceting is really a fancy word for separating data into classes along a specific dimension(s). So here we are separating the data along the “who” variable, which allows us to plot each type of person separately."
},
{
"code": null,
"e": 12621,
"s": 12290,
"text": "Being able to say col='<column_name>' to automatically facet is a powerful option that most figure-level functions have access to. Accomplishing the same thing in Matplotlib requires significantly more time subsetting data and creating multiple subplots manually. I discuss the power of figure-level plotting more in this article."
},
{
"code": null,
"e": 12824,
"s": 12621,
"text": "Don’t forget that we could still add a hue argument to add even more information to this plot! Faceting data with Seaborn’s figure-level functionality can be an excellent way to make more complex plots."
},
{
"code": null,
"e": 13179,
"s": 12824,
"text": "You will notice that Seaborn figures require different functions for formatting, however saving the plot can still be done via plt.savefig() since the final Seaborn figure interfaces with the Matplotlib API. I won’t get into detail on figure-level plotting since there is a lot to discuss, but do read my other article about the topic if you are curious."
},
{
"code": null,
"e": 13515,
"s": 13179,
"text": "We’ve gone through a lot of different plots in this post. I hope that you have seen how easy Seaborn can make an aesthetically pleasing plot that conveys a lot of useful information to the viewer. Once I got used to using it, Seaborn has saved me a massive amount of time writing fewer lines of code to produce pleasing visualizations."
},
{
"code": null,
"e": 13524,
"s": 13515,
"text": "Box Plot"
},
{
"code": null,
"e": 13536,
"s": 13524,
"text": "Violin Plot"
},
{
"code": null,
"e": 13547,
"s": 13536,
"text": "Boxen Plot"
},
{
"code": null,
"e": 13558,
"s": 13547,
"text": "Strip Plot"
},
{
"code": null,
"e": 13569,
"s": 13558,
"text": "Swarm Plot"
},
{
"code": null,
"e": 13580,
"s": 13569,
"text": "Point Plot"
},
{
"code": null,
"e": 13589,
"s": 13580,
"text": "Bar Plot"
},
{
"code": null,
"e": 13600,
"s": 13589,
"text": "Count Plot"
},
{
"code": null,
"e": 13608,
"s": 13600,
"text": "Catplot"
}
] |
MongoDB | Create Database using MongoShell - GeeksforGeeks | 19 Sep, 2019
A MongoDB Database is the container for all the collections, where Collection is a bunch of MongoDB documents similar to tables in RDBMS and Document is made up of the fields similar to a tuple in RDBMS, but it has a dynamic schema here.
Example of a Document:
{
"Name" : "Aman",
Age : 24,
Gender : "Male"
}
Above document contains the information of a person in JSON format.If we have a bunch of documents then it creates a collection. So we can say a User collection contains documents containing User Information.
Example of a Collection:
[
{
"Name" : "Aman",
Age : 24,
Gender : "Male"
},
{
"Name" : "Suraj",
Age : 32,
Gender : "Male"
},
{
"Name" : "Joyita",
"Age" : 21,
"Gender" : "Female"
},
{
"Name" : "Mahfuj",
"Age" : 24,
"Gender" : "Male"
},
]
MongoShell:The mongo shell is an interactive JavaScript interface to query and update data as well as perform administrative operations in MongoDB.
Databases: In MongoDB, databases basically holds the collections of documents. A database contains collection which contains the document. On a single MongoDB server, we can run multiple databases. Default created database of MongoDB is ‘db’ present within the data folder. When you install MongoDB some databases are automatically generated to use.so we can say that it is not required to create a database before you start working with it.
Create a New Database : You can create a new Database in MongoDB by using “use Database_Name” command. The command creates a new database if it doesn’t exist, otherwise, it will return the existing database.you can run this command in mongo shell to create a new database. Your newly created database is not present in the list of Database. To display database, you need to insert at least one document into it.
Syntax:
use Database_Name
Example: CREATING A NEW DATABASE
In MongoDB default database is test. If you did not create any Database and started inserting collection then all collections are stored in the Default Database.
Show list of Databases : You can check currently selected database, using the command “show dbs“. Your newly created database is not present in the list of Database. To display any database, you need to insert at least one or more document into it.
Example: LIST OF DATABASES
Check current Database : You can check list of databases, using the command “db”
Example: CHECKING CURRENTLY SELECTED DATABASE
Switch to other Database : You can switch to other database using the command “use Database_Name“. If Database does not exists then it will create a new Database.
Example: SWITCHING TO ANOTHER DATABASEIn the above Example, First we check current Database name using db command which was UserDB then we use “use test” command to switch to database test.
References:https://docs.mongodb.com/manual/core/databases-and-collections/#databases
nidhi_biet
MongoDB
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method
File uploading in React.js
How to apply style to parent if it has child with CSS?
How to Open URL in New Tab using JavaScript ? | [
{
"code": null,
"e": 25638,
"s": 25610,
"text": "\n19 Sep, 2019"
},
{
"code": null,
"e": 25876,
"s": 25638,
"text": "A MongoDB Database is the container for all the collections, where Collection is a bunch of MongoDB documents similar to tables in RDBMS and Document is made up of the fields similar to a tuple in RDBMS, but it has a dynamic schema here."
},
{
"code": null,
"e": 25899,
"s": 25876,
"text": "Example of a Document:"
},
{
"code": null,
"e": 25975,
"s": 25899,
"text": "{\n \"Name\" : \"Aman\",\n Age : 24,\n Gender : \"Male\" \n}\n"
},
{
"code": null,
"e": 26184,
"s": 25975,
"text": "Above document contains the information of a person in JSON format.If we have a bunch of documents then it creates a collection. So we can say a User collection contains documents containing User Information."
},
{
"code": null,
"e": 26209,
"s": 26184,
"text": "Example of a Collection:"
},
{
"code": null,
"e": 26561,
"s": 26209,
"text": "[ \n {\n \"Name\" : \"Aman\",\n Age : 24,\n Gender : \"Male\" \n },\n {\n \"Name\" : \"Suraj\",\n Age : 32,\n Gender : \"Male\" \n },\n {\n \"Name\" : \"Joyita\",\n \"Age\" : 21,\n \"Gender\" : \"Female\"\n },\n {\n \"Name\" : \"Mahfuj\",\n \"Age\" : 24,\n \"Gender\" : \"Male\"\n },\n]\n"
},
{
"code": null,
"e": 26709,
"s": 26561,
"text": "MongoShell:The mongo shell is an interactive JavaScript interface to query and update data as well as perform administrative operations in MongoDB."
},
{
"code": null,
"e": 27151,
"s": 26709,
"text": "Databases: In MongoDB, databases basically holds the collections of documents. A database contains collection which contains the document. On a single MongoDB server, we can run multiple databases. Default created database of MongoDB is ‘db’ present within the data folder. When you install MongoDB some databases are automatically generated to use.so we can say that it is not required to create a database before you start working with it."
},
{
"code": null,
"e": 27563,
"s": 27151,
"text": "Create a New Database : You can create a new Database in MongoDB by using “use Database_Name” command. The command creates a new database if it doesn’t exist, otherwise, it will return the existing database.you can run this command in mongo shell to create a new database. Your newly created database is not present in the list of Database. To display database, you need to insert at least one document into it."
},
{
"code": null,
"e": 27571,
"s": 27563,
"text": "Syntax:"
},
{
"code": null,
"e": 27590,
"s": 27571,
"text": " use Database_Name"
},
{
"code": null,
"e": 27623,
"s": 27590,
"text": "Example: CREATING A NEW DATABASE"
},
{
"code": null,
"e": 27785,
"s": 27623,
"text": "In MongoDB default database is test. If you did not create any Database and started inserting collection then all collections are stored in the Default Database."
},
{
"code": null,
"e": 28034,
"s": 27785,
"text": "Show list of Databases : You can check currently selected database, using the command “show dbs“. Your newly created database is not present in the list of Database. To display any database, you need to insert at least one or more document into it."
},
{
"code": null,
"e": 28061,
"s": 28034,
"text": "Example: LIST OF DATABASES"
},
{
"code": null,
"e": 28142,
"s": 28061,
"text": "Check current Database : You can check list of databases, using the command “db”"
},
{
"code": null,
"e": 28188,
"s": 28142,
"text": "Example: CHECKING CURRENTLY SELECTED DATABASE"
},
{
"code": null,
"e": 28351,
"s": 28188,
"text": "Switch to other Database : You can switch to other database using the command “use Database_Name“. If Database does not exists then it will create a new Database."
},
{
"code": null,
"e": 28541,
"s": 28351,
"text": "Example: SWITCHING TO ANOTHER DATABASEIn the above Example, First we check current Database name using db command which was UserDB then we use “use test” command to switch to database test."
},
{
"code": null,
"e": 28626,
"s": 28541,
"text": "References:https://docs.mongodb.com/manual/core/databases-and-collections/#databases"
},
{
"code": null,
"e": 28637,
"s": 28626,
"text": "nidhi_biet"
},
{
"code": null,
"e": 28645,
"s": 28637,
"text": "MongoDB"
},
{
"code": null,
"e": 28662,
"s": 28645,
"text": "Web Technologies"
},
{
"code": null,
"e": 28760,
"s": 28662,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28800,
"s": 28760,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28845,
"s": 28800,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28888,
"s": 28845,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28949,
"s": 28888,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29007,
"s": 28949,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 29079,
"s": 29007,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29112,
"s": 29079,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 29139,
"s": 29112,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 29194,
"s": 29139,
"text": "How to apply style to parent if it has child with CSS?"
}
] |
Find K Closest Points to the Origin - GeeksforGeeks | 25 Nov, 2021
Given a list of points on the 2-D plane and an integer K. The task is to find K closest points to the origin and print them.Note: The distance between two points on a plane is the Euclidean distance.
Examples:
Input : point = [[3, 3], [5, -1], [-2, 4]], K = 2
Output : [[3, 3], [-2, 4]]
Square of Distance of origin from this point is
(3, 3) = 18
(5, -1) = 26
(-2, 4) = 20
So the closest two points are [3, 3], [-2, 4].
Input : point = [[1, 3], [-2, 2]], K = 1
Output : [[-2, 2]]
Square of Distance of origin from this point is
(1, 3) = 10
(-2, 2) = 8
So the closest point to origin is (-2, 2)
Approach: The idea is to calculate the Euclidean distance from the origin for every given point and sort the array according to the Euclidean distance found. Print the first k closest points from the list.
Algorithm : Consider two points with coordinates as (x1, y1) and (x2, y2) respectively. The Euclidean distance between these two points will be:
√{(x2-x1)2 + (y2-y1)2}
Sort the points by distance using the Euclidean distance formula.Select first K points form the listPrint the points obtained in any order.
Sort the points by distance using the Euclidean distance formula.
Select first K points form the list
Print the points obtained in any order.
Note:
In multimap we can directly store the value of {(x2-x1)2 + (y2-y1)2} instead of its square root because of the following property : If sqrt(x) < sqrt(y) the x < y
Because of this, we have reduced the time complexity (Time complexity of the square root of an integer is O(√ n) )
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for implementation of // above approach#include<bits/stdc++.h>using namespace std; // Function to print required answervoid pClosest(vector<vector<int>> pts, int k){ // In multimap values gets // automatically sorted based on // their keys which is distance here multimap<int, int> mp; for(int i = 0; i < pts.size(); i++) { int x = pts[i][0], y = pts[i][1]; mp.insert({(x * x) + (y * y) , i}); } for(auto it = mp.begin(); it != mp.end() && k > 0; it++, k--) cout << "[" << pts[it->second][0] << ", " << pts[it->second][1] << "]" << "\n";} // Driver codeint main(){ vector<vector<int>> points = { { 3, 3 }, { 5, -1 }, { -2, 4 } }; int K = 2; pClosest(points, K); return 0;} // This code is contributed by sarthak_eddy.
// Java program for implementation of // above approachimport java.util.*; class GFG{ // Function to print required answerstatic void pClosest(int [][]pts, int k){ int n = pts.length; int[] distance = new int[n]; for(int i = 0; i < n; i++) { int x = pts[i][0], y = pts[i][1]; distance[i] = (x * x) + (y * y); } Arrays.sort(distance); // Find the k-th distance int distk = distance[k - 1]; // Print all distances which are // smaller than k-th distance for(int i = 0; i < n; i++) { int x = pts[i][0], y = pts[i][1]; int dist = (x * x) + (y * y); if (dist <= distk) System.out.println("[" + x + ", " + y + "]"); }} // Driver codepublic static void main (String[] args){ int points[][] = { { 3, 3 }, { 5, -1 }, { -2, 4 } }; int K = 2; pClosest(points, K);}} // This code is contributed by sarthak_eddy.
# Python3 program for implementation of# above approach # Function to return required answerdef pClosest(points, K): points.sort(key = lambda K: K[0]**2 + K[1]**2) return points[:K] # Driver programpoints = [[3, 3], [5, -1], [-2, 4]] K = 2 print(pClosest(points, K))
// C# program for implementation// of above approachusing System;class GFG{ // Function to print// required answerstatic void pClosest(int [,]pts, int k){ int n = pts.GetLength(0); int[] distance = new int[n]; for(int i = 0; i < n; i++) { int x = pts[i, 0], y = pts[i, 1]; distance[i] = (x * x) + (y * y); } Array.Sort(distance); // Find the k-th distance int distk = distance[k - 1]; // Print all distances which are // smaller than k-th distance for(int i = 0; i < n; i++) { int x = pts[i, 0], y = pts[i, 1]; int dist = (x * x) + (y * y); if (dist <= distk) Console.WriteLine("[" + x + ", " + y + "]"); }} // Driver codepublic static void Main (string[] args){ int [,]points = {{3, 3}, {5, -1}, {-2, 4}}; int K = 2; pClosest(points, K);}} // This code is contributed by Chitranayal
<script>// Javascript program for implementation of// above approach // Function to print required answerfunction pClosest(pts,k){ let n = pts.length; let distance = new Array(n); for(let i = 0; i < n; i++) { let x = pts[i][0], y = pts[i][1]; distance[i] = (x * x) + (y * y); } distance.sort(function(a,b){return a-b;}); // Find the k-th distance let distk = distance[k - 1]; // Print all distances which are // smaller than k-th distance for(let i = 0; i < n; i++) { let x = pts[i][0], y = pts[i][1]; let dist = (x * x) + (y * y); if (dist <= distk) document.write("[" + x + ", " + y + "]<br>"); }} // Driver codelet points = [[3, 3], [5, -1], [-2, 4]];let K = 2;pClosest(points, K); // This code is contributed by rag2127</script>
[[3, 3], [-2, 4]]
Complexity Analysis:
Time Complexity: O(n log n). Time complexity to find the distance from the origin for every point is O(n) and to sort the array is O(n log n)
Space Complexity: O(n). As we are making an array to store distance from the origin for each point.
andrew1234
sarthak_eddy
ukasp
rag2127
NimishGupta95
marco11
prasanna1995
Geometric
Mathematical
Python Programs
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
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Convex Hull | Set 2 (Graham Scan)
Optimum location of point to minimize total distance
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": 26615,
"s": 26587,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 26815,
"s": 26615,
"text": "Given a list of points on the 2-D plane and an integer K. The task is to find K closest points to the origin and print them.Note: The distance between two points on a plane is the Euclidean distance."
},
{
"code": null,
"e": 26826,
"s": 26815,
"text": "Examples: "
},
{
"code": null,
"e": 27214,
"s": 26826,
"text": "Input : point = [[3, 3], [5, -1], [-2, 4]], K = 2\nOutput : [[3, 3], [-2, 4]]\nSquare of Distance of origin from this point is \n(3, 3) = 18\n(5, -1) = 26\n(-2, 4) = 20\nSo the closest two points are [3, 3], [-2, 4].\n\nInput : point = [[1, 3], [-2, 2]], K = 1\nOutput : [[-2, 2]]\nSquare of Distance of origin from this point is\n(1, 3) = 10\n(-2, 2) = 8 \nSo the closest point to origin is (-2, 2)"
},
{
"code": null,
"e": 27420,
"s": 27214,
"text": "Approach: The idea is to calculate the Euclidean distance from the origin for every given point and sort the array according to the Euclidean distance found. Print the first k closest points from the list."
},
{
"code": null,
"e": 27566,
"s": 27420,
"text": "Algorithm : Consider two points with coordinates as (x1, y1) and (x2, y2) respectively. The Euclidean distance between these two points will be: "
},
{
"code": null,
"e": 27589,
"s": 27566,
"text": "√{(x2-x1)2 + (y2-y1)2}"
},
{
"code": null,
"e": 27729,
"s": 27589,
"text": "Sort the points by distance using the Euclidean distance formula.Select first K points form the listPrint the points obtained in any order."
},
{
"code": null,
"e": 27795,
"s": 27729,
"text": "Sort the points by distance using the Euclidean distance formula."
},
{
"code": null,
"e": 27831,
"s": 27795,
"text": "Select first K points form the list"
},
{
"code": null,
"e": 27871,
"s": 27831,
"text": "Print the points obtained in any order."
},
{
"code": null,
"e": 27878,
"s": 27871,
"text": "Note: "
},
{
"code": null,
"e": 28041,
"s": 27878,
"text": "In multimap we can directly store the value of {(x2-x1)2 + (y2-y1)2} instead of its square root because of the following property : If sqrt(x) < sqrt(y) the x < y"
},
{
"code": null,
"e": 28157,
"s": 28041,
"text": "Because of this, we have reduced the time complexity (Time complexity of the square root of an integer is O(√ n) ) "
},
{
"code": null,
"e": 28209,
"s": 28157,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28213,
"s": 28209,
"text": "C++"
},
{
"code": null,
"e": 28218,
"s": 28213,
"text": "Java"
},
{
"code": null,
"e": 28226,
"s": 28218,
"text": "Python3"
},
{
"code": null,
"e": 28229,
"s": 28226,
"text": "C#"
},
{
"code": null,
"e": 28240,
"s": 28229,
"text": "Javascript"
},
{
"code": "// C++ program for implementation of // above approach#include<bits/stdc++.h>using namespace std; // Function to print required answervoid pClosest(vector<vector<int>> pts, int k){ // In multimap values gets // automatically sorted based on // their keys which is distance here multimap<int, int> mp; for(int i = 0; i < pts.size(); i++) { int x = pts[i][0], y = pts[i][1]; mp.insert({(x * x) + (y * y) , i}); } for(auto it = mp.begin(); it != mp.end() && k > 0; it++, k--) cout << \"[\" << pts[it->second][0] << \", \" << pts[it->second][1] << \"]\" << \"\\n\";} // Driver codeint main(){ vector<vector<int>> points = { { 3, 3 }, { 5, -1 }, { -2, 4 } }; int K = 2; pClosest(points, K); return 0;} // This code is contributed by sarthak_eddy.",
"e": 29154,
"s": 28240,
"text": null
},
{
"code": "// Java program for implementation of // above approachimport java.util.*; class GFG{ // Function to print required answerstatic void pClosest(int [][]pts, int k){ int n = pts.length; int[] distance = new int[n]; for(int i = 0; i < n; i++) { int x = pts[i][0], y = pts[i][1]; distance[i] = (x * x) + (y * y); } Arrays.sort(distance); // Find the k-th distance int distk = distance[k - 1]; // Print all distances which are // smaller than k-th distance for(int i = 0; i < n; i++) { int x = pts[i][0], y = pts[i][1]; int dist = (x * x) + (y * y); if (dist <= distk) System.out.println(\"[\" + x + \", \" + y + \"]\"); }} // Driver codepublic static void main (String[] args){ int points[][] = { { 3, 3 }, { 5, -1 }, { -2, 4 } }; int K = 2; pClosest(points, K);}} // This code is contributed by sarthak_eddy.",
"e": 30118,
"s": 29154,
"text": null
},
{
"code": "# Python3 program for implementation of# above approach # Function to return required answerdef pClosest(points, K): points.sort(key = lambda K: K[0]**2 + K[1]**2) return points[:K] # Driver programpoints = [[3, 3], [5, -1], [-2, 4]] K = 2 print(pClosest(points, K))",
"e": 30393,
"s": 30118,
"text": null
},
{
"code": "// C# program for implementation// of above approachusing System;class GFG{ // Function to print// required answerstatic void pClosest(int [,]pts, int k){ int n = pts.GetLength(0); int[] distance = new int[n]; for(int i = 0; i < n; i++) { int x = pts[i, 0], y = pts[i, 1]; distance[i] = (x * x) + (y * y); } Array.Sort(distance); // Find the k-th distance int distk = distance[k - 1]; // Print all distances which are // smaller than k-th distance for(int i = 0; i < n; i++) { int x = pts[i, 0], y = pts[i, 1]; int dist = (x * x) + (y * y); if (dist <= distk) Console.WriteLine(\"[\" + x + \", \" + y + \"]\"); }} // Driver codepublic static void Main (string[] args){ int [,]points = {{3, 3}, {5, -1}, {-2, 4}}; int K = 2; pClosest(points, K);}} // This code is contributed by Chitranayal",
"e": 31349,
"s": 30393,
"text": null
},
{
"code": "<script>// Javascript program for implementation of// above approach // Function to print required answerfunction pClosest(pts,k){ let n = pts.length; let distance = new Array(n); for(let i = 0; i < n; i++) { let x = pts[i][0], y = pts[i][1]; distance[i] = (x * x) + (y * y); } distance.sort(function(a,b){return a-b;}); // Find the k-th distance let distk = distance[k - 1]; // Print all distances which are // smaller than k-th distance for(let i = 0; i < n; i++) { let x = pts[i][0], y = pts[i][1]; let dist = (x * x) + (y * y); if (dist <= distk) document.write(\"[\" + x + \", \" + y + \"]<br>\"); }} // Driver codelet points = [[3, 3], [5, -1], [-2, 4]];let K = 2;pClosest(points, K); // This code is contributed by rag2127</script>",
"e": 32192,
"s": 31349,
"text": null
},
{
"code": null,
"e": 32210,
"s": 32192,
"text": "[[3, 3], [-2, 4]]"
},
{
"code": null,
"e": 32234,
"s": 32212,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 32376,
"s": 32234,
"text": "Time Complexity: O(n log n). Time complexity to find the distance from the origin for every point is O(n) and to sort the array is O(n log n)"
},
{
"code": null,
"e": 32476,
"s": 32376,
"text": "Space Complexity: O(n). As we are making an array to store distance from the origin for each point."
},
{
"code": null,
"e": 32487,
"s": 32476,
"text": "andrew1234"
},
{
"code": null,
"e": 32500,
"s": 32487,
"text": "sarthak_eddy"
},
{
"code": null,
"e": 32506,
"s": 32500,
"text": "ukasp"
},
{
"code": null,
"e": 32514,
"s": 32506,
"text": "rag2127"
},
{
"code": null,
"e": 32528,
"s": 32514,
"text": "NimishGupta95"
},
{
"code": null,
"e": 32536,
"s": 32528,
"text": "marco11"
},
{
"code": null,
"e": 32549,
"s": 32536,
"text": "prasanna1995"
},
{
"code": null,
"e": 32559,
"s": 32549,
"text": "Geometric"
},
{
"code": null,
"e": 32572,
"s": 32559,
"text": "Mathematical"
},
{
"code": null,
"e": 32588,
"s": 32572,
"text": "Python Programs"
},
{
"code": null,
"e": 32601,
"s": 32588,
"text": "Mathematical"
},
{
"code": null,
"e": 32611,
"s": 32601,
"text": "Geometric"
},
{
"code": null,
"e": 32709,
"s": 32611,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32758,
"s": 32709,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 32811,
"s": 32758,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 32862,
"s": 32811,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 32896,
"s": 32862,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 32949,
"s": 32896,
"text": "Optimum location of point to minimize total distance"
},
{
"code": null,
"e": 32979,
"s": 32949,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 33039,
"s": 32979,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33054,
"s": 33039,
"text": "C++ Data Types"
},
{
"code": null,
"e": 33097,
"s": 33054,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
LocalDate getDayOfYear() method in Java with Examples - GeeksforGeeks | 28 Nov, 2018
The getDayOfYear() method of LocalDate class in Java gets the day-of-year field.
Syntax:
public int getDayOfYear()
Parameter: This method does not accepts any parameter.
Return Value: The function returns the day of the year which is in range [1, 365/366] depending on leap year or not.
Below programs illustrate the getDayOfYear() method of LocalDate in Java:
Program 1:
// Program to illustrate the getDayOfYear() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse("2018-11-27"); // Prints the day number System.out.println(dt.getDayOfYear()); }}
331
Program 2:
// Program to illustrate the getDayOfYear() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse("2018-01-02"); // Prints the day number System.out.println(dt.getDayOfYear()); }}
2
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getDayOfYear()
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Multithreading in Java
Collections in Java | [
{
"code": null,
"e": 25499,
"s": 25471,
"text": "\n28 Nov, 2018"
},
{
"code": null,
"e": 25580,
"s": 25499,
"text": "The getDayOfYear() method of LocalDate class in Java gets the day-of-year field."
},
{
"code": null,
"e": 25588,
"s": 25580,
"text": "Syntax:"
},
{
"code": null,
"e": 25615,
"s": 25588,
"text": "public int getDayOfYear()\n"
},
{
"code": null,
"e": 25670,
"s": 25615,
"text": "Parameter: This method does not accepts any parameter."
},
{
"code": null,
"e": 25787,
"s": 25670,
"text": "Return Value: The function returns the day of the year which is in range [1, 365/366] depending on leap year or not."
},
{
"code": null,
"e": 25861,
"s": 25787,
"text": "Below programs illustrate the getDayOfYear() method of LocalDate in Java:"
},
{
"code": null,
"e": 25872,
"s": 25861,
"text": "Program 1:"
},
{
"code": "// Program to illustrate the getDayOfYear() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse(\"2018-11-27\"); // Prints the day number System.out.println(dt.getDayOfYear()); }}",
"e": 26195,
"s": 25872,
"text": null
},
{
"code": null,
"e": 26200,
"s": 26195,
"text": "331\n"
},
{
"code": null,
"e": 26211,
"s": 26200,
"text": "Program 2:"
},
{
"code": "// Program to illustrate the getDayOfYear() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse(\"2018-01-02\"); // Prints the day number System.out.println(dt.getDayOfYear()); }}",
"e": 26534,
"s": 26211,
"text": null
},
{
"code": null,
"e": 26537,
"s": 26534,
"text": "2\n"
},
{
"code": null,
"e": 26631,
"s": 26537,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getDayOfYear()"
},
{
"code": null,
"e": 26646,
"s": 26631,
"text": "Java-Functions"
},
{
"code": null,
"e": 26661,
"s": 26646,
"text": "Java-LocalDate"
},
{
"code": null,
"e": 26679,
"s": 26661,
"text": "Java-time package"
},
{
"code": null,
"e": 26684,
"s": 26679,
"text": "Java"
},
{
"code": null,
"e": 26689,
"s": 26684,
"text": "Java"
},
{
"code": null,
"e": 26787,
"s": 26689,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26802,
"s": 26787,
"text": "Stream In Java"
},
{
"code": null,
"e": 26821,
"s": 26802,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26839,
"s": 26821,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26871,
"s": 26839,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26891,
"s": 26871,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26923,
"s": 26891,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26947,
"s": 26923,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 26959,
"s": 26947,
"text": "Set in Java"
},
{
"code": null,
"e": 26982,
"s": 26959,
"text": "Multithreading in Java"
}
] |
Scala Float round() method with example - GeeksforGeeks | 29 Oct, 2019
The round() method is utilized to return the rounded value of the specified float value. If the float value is 5.5 or greater than 5.5 till 5.9, then it will returns 6 otherwise 5 if the float value is 5.0 or till 5.4
Method Definition: (Float_Value).round
Return Type: It returns the rounded value of the specified float value.
Example #1:
// Scala program of Float round()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying round method val result = (5.4).round // Displays output println(result) }}
5
Example #2:
// Scala program of Float round()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying round method val result = (5.9).round // Displays output println(result) }}
6
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Scala Map
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Scala List contains() method with example
Scala | Arrays
Scala String substring() method with example
Lambda Expression in Scala
How to get the first element of List in Scala
Scala | Traits | [
{
"code": null,
"e": 25195,
"s": 25167,
"text": "\n29 Oct, 2019"
},
{
"code": null,
"e": 25413,
"s": 25195,
"text": "The round() method is utilized to return the rounded value of the specified float value. If the float value is 5.5 or greater than 5.5 till 5.9, then it will returns 6 otherwise 5 if the float value is 5.0 or till 5.4"
},
{
"code": null,
"e": 25452,
"s": 25413,
"text": "Method Definition: (Float_Value).round"
},
{
"code": null,
"e": 25524,
"s": 25452,
"text": "Return Type: It returns the rounded value of the specified float value."
},
{
"code": null,
"e": 25536,
"s": 25524,
"text": "Example #1:"
},
{
"code": "// Scala program of Float round()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying round method val result = (5.4).round // Displays output println(result) }} ",
"e": 25810,
"s": 25536,
"text": null
},
{
"code": null,
"e": 25813,
"s": 25810,
"text": "5\n"
},
{
"code": null,
"e": 25825,
"s": 25813,
"text": "Example #2:"
},
{
"code": "// Scala program of Float round()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Applying round method val result = (5.9).round // Displays output println(result) }} ",
"e": 26099,
"s": 25825,
"text": null
},
{
"code": null,
"e": 26102,
"s": 26099,
"text": "6\n"
},
{
"code": null,
"e": 26108,
"s": 26102,
"text": "Scala"
},
{
"code": null,
"e": 26121,
"s": 26108,
"text": "Scala-Method"
},
{
"code": null,
"e": 26127,
"s": 26121,
"text": "Scala"
},
{
"code": null,
"e": 26225,
"s": 26127,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26247,
"s": 26225,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 26257,
"s": 26247,
"text": "Scala Map"
},
{
"code": null,
"e": 26269,
"s": 26257,
"text": "Scala Lists"
},
{
"code": null,
"e": 26322,
"s": 26269,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 26364,
"s": 26322,
"text": "Scala List contains() method with example"
},
{
"code": null,
"e": 26379,
"s": 26364,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 26424,
"s": 26379,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 26451,
"s": 26424,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 26497,
"s": 26451,
"text": "How to get the first element of List in Scala"
}
] |
HTTP headers | Access-Control-Allow-Credentials - GeeksforGeeks | 07 Jan, 2022
The HTTP Access-Control-Allow-Credentials is a Response header. The Access-Control-Allow-Credentials header is used to tell the browsers to expose the response to front-end JavaScript code when the request’s credentials mode Request.credentials is “include”. Remember one thing when the Request.credentials is “include” mode browsers will expose the response to front-end JavaScript code if the Access-Control-Allow-Credentials is set true.
The Access-Control-Allow-Credentials header performs with the XMLHttpRequest.withCredentials property or with the credentials option in the Request() constructor of the Fetch API.
Note: Credentials are actually cookies, authorization headers or TLS(Transport Layer Security) client certificates.
Syntax:
Access-Control-Allow-Credentials: true
Directives: This header accept a single directive mentioned above and described below:
true: This the only meaningful or you can say valid value for Access-Control-Allow-Credentials header. If this credentials is not required, then remove the header. Don’t put there Access-Control-Allow-Credentials: false. This directive is case sensitive true
Example:
This is allowing the Access-Control-Allow-Credentials.Access-Control-Allow-Credentials: true
Access-Control-Allow-Credentials: true
This is using the xhr with credentials.var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.geeksforgeeks.org/', true);
xhr.withCredentials = true;
xhr.send(null);
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.geeksforgeeks.org/', true);
xhr.withCredentials = true;
xhr.send(null);
This is using Fetch with credentials.fetch(url, {
credentials: 'include'
})
fetch(url, {
credentials: 'include'
})
To check this Access-Control-Allow-Credentials in action go to Inspect Element -> Network check the response header for Access-Control-Allow-Credentials like below, Access-Control-Allow-Credentials is highlighted you can see.
Supported Browsers: The browsers compatible with HTTP Access-Control-Allow-Credentials header are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
rajeev0719singh
HTTP-headers
Picked
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method | [
{
"code": null,
"e": 25717,
"s": 25689,
"text": "\n07 Jan, 2022"
},
{
"code": null,
"e": 26158,
"s": 25717,
"text": "The HTTP Access-Control-Allow-Credentials is a Response header. The Access-Control-Allow-Credentials header is used to tell the browsers to expose the response to front-end JavaScript code when the request’s credentials mode Request.credentials is “include”. Remember one thing when the Request.credentials is “include” mode browsers will expose the response to front-end JavaScript code if the Access-Control-Allow-Credentials is set true."
},
{
"code": null,
"e": 26338,
"s": 26158,
"text": "The Access-Control-Allow-Credentials header performs with the XMLHttpRequest.withCredentials property or with the credentials option in the Request() constructor of the Fetch API."
},
{
"code": null,
"e": 26454,
"s": 26338,
"text": "Note: Credentials are actually cookies, authorization headers or TLS(Transport Layer Security) client certificates."
},
{
"code": null,
"e": 26462,
"s": 26454,
"text": "Syntax:"
},
{
"code": null,
"e": 26501,
"s": 26462,
"text": "Access-Control-Allow-Credentials: true"
},
{
"code": null,
"e": 26588,
"s": 26501,
"text": "Directives: This header accept a single directive mentioned above and described below:"
},
{
"code": null,
"e": 26847,
"s": 26588,
"text": "true: This the only meaningful or you can say valid value for Access-Control-Allow-Credentials header. If this credentials is not required, then remove the header. Don’t put there Access-Control-Allow-Credentials: false. This directive is case sensitive true"
},
{
"code": null,
"e": 26856,
"s": 26847,
"text": "Example:"
},
{
"code": null,
"e": 26949,
"s": 26856,
"text": "This is allowing the Access-Control-Allow-Credentials.Access-Control-Allow-Credentials: true"
},
{
"code": null,
"e": 26988,
"s": 26949,
"text": "Access-Control-Allow-Credentials: true"
},
{
"code": null,
"e": 27162,
"s": 26988,
"text": "This is using the xhr with credentials.var xhr = new XMLHttpRequest();\nxhr.open('GET', 'https://www.geeksforgeeks.org/', true); \nxhr.withCredentials = true; \nxhr.send(null);"
},
{
"code": null,
"e": 27297,
"s": 27162,
"text": "var xhr = new XMLHttpRequest();\nxhr.open('GET', 'https://www.geeksforgeeks.org/', true); \nxhr.withCredentials = true; \nxhr.send(null);"
},
{
"code": null,
"e": 27377,
"s": 27297,
"text": "This is using Fetch with credentials.fetch(url, {\n credentials: 'include' \n})"
},
{
"code": null,
"e": 27420,
"s": 27377,
"text": "fetch(url, {\n credentials: 'include' \n})"
},
{
"code": null,
"e": 27646,
"s": 27420,
"text": "To check this Access-Control-Allow-Credentials in action go to Inspect Element -> Network check the response header for Access-Control-Allow-Credentials like below, Access-Control-Allow-Credentials is highlighted you can see."
},
{
"code": null,
"e": 27758,
"s": 27646,
"text": "Supported Browsers: The browsers compatible with HTTP Access-Control-Allow-Credentials header are listed below:"
},
{
"code": null,
"e": 27772,
"s": 27758,
"text": "Google Chrome"
},
{
"code": null,
"e": 27790,
"s": 27772,
"text": "Internet Explorer"
},
{
"code": null,
"e": 27798,
"s": 27790,
"text": "Firefox"
},
{
"code": null,
"e": 27805,
"s": 27798,
"text": "Safari"
},
{
"code": null,
"e": 27811,
"s": 27805,
"text": "Opera"
},
{
"code": null,
"e": 27827,
"s": 27811,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 27840,
"s": 27827,
"text": "HTTP-headers"
},
{
"code": null,
"e": 27847,
"s": 27840,
"text": "Picked"
},
{
"code": null,
"e": 27866,
"s": 27847,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27883,
"s": 27866,
"text": "Web Technologies"
},
{
"code": null,
"e": 27981,
"s": 27883,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28021,
"s": 27981,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28054,
"s": 28021,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28099,
"s": 28054,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28142,
"s": 28099,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28192,
"s": 28142,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28253,
"s": 28192,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28315,
"s": 28253,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28373,
"s": 28315,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 28445,
"s": 28373,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Python | Decimal logical_xor() method - GeeksforGeeks | 05 Sep, 2019
Decimal#logical_xor() : logical_xor() is a Decimal class method which returns the digit-wise exclusive or of the two Decimal values.
Syntax: Decimal.logical_xor()
Parameter: Decimal values
Return: the digit-wise and of the two (logical) Decimal values.
Code #1 : Example for logical_xor() method
# Python Program explaining # logical_xor() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('0') b = Decimal('1') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.logical_xor() methodprint ("\n\nDecimal a with logical_xor() method : ", a.logical_xor(b)) print ("Decimal b with logical_xor() method : ", b.logical_xor(b))
Output :
Decimal value a : 0
Decimal value b : 1
Decimal a with logical_xor() method : 1
Decimal b with logical_xor() method : 0
Code #2 : Example for logical_xor() method
# Python Program explaining # logical_xor() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('1') b = Decimal('0') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.logical_xor() methodprint ("\n\nDecimal a with logical_xor() method : ", a.logical_xor(a)) print ("Decimal b with logical_xor() method : ", a.logical_xor(b))
Output :
Decimal value a : 1
Decimal value b : 0
Decimal a with logical_xor() method : 0
Decimal b with logical_xor() method : 1
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": "\n05 Sep, 2019"
},
{
"code": null,
"e": 25670,
"s": 25537,
"text": "Decimal#logical_xor() : logical_xor() is a Decimal class method which returns the digit-wise exclusive or of the two Decimal values."
},
{
"code": null,
"e": 25700,
"s": 25670,
"text": "Syntax: Decimal.logical_xor()"
},
{
"code": null,
"e": 25726,
"s": 25700,
"text": "Parameter: Decimal values"
},
{
"code": null,
"e": 25790,
"s": 25726,
"text": "Return: the digit-wise and of the two (logical) Decimal values."
},
{
"code": null,
"e": 25833,
"s": 25790,
"text": "Code #1 : Example for logical_xor() method"
},
{
"code": "# Python Program explaining # logical_xor() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('0') b = Decimal('1') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.logical_xor() methodprint (\"\\n\\nDecimal a with logical_xor() method : \", a.logical_xor(b)) print (\"Decimal b with logical_xor() method : \", b.logical_xor(b))",
"e": 26267,
"s": 25833,
"text": null
},
{
"code": null,
"e": 26276,
"s": 26267,
"text": "Output :"
},
{
"code": null,
"e": 26404,
"s": 26276,
"text": "Decimal value a : 0\nDecimal value b : 1\n\n\nDecimal a with logical_xor() method : 1\nDecimal b with logical_xor() method : 0\n\n"
},
{
"code": null,
"e": 26447,
"s": 26404,
"text": "Code #2 : Example for logical_xor() method"
},
{
"code": "# Python Program explaining # logical_xor() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('1') b = Decimal('0') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.logical_xor() methodprint (\"\\n\\nDecimal a with logical_xor() method : \", a.logical_xor(a)) print (\"Decimal b with logical_xor() method : \", a.logical_xor(b))",
"e": 26881,
"s": 26447,
"text": null
},
{
"code": null,
"e": 26890,
"s": 26881,
"text": "Output :"
},
{
"code": null,
"e": 27017,
"s": 26890,
"text": "Decimal value a : 1\nDecimal value b : 0\n\n\nDecimal a with logical_xor() method : 0\nDecimal b with logical_xor() method : 1\n"
},
{
"code": null,
"e": 27024,
"s": 27017,
"text": "Python"
},
{
"code": null,
"e": 27122,
"s": 27024,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27154,
"s": 27122,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27196,
"s": 27154,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27238,
"s": 27196,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27265,
"s": 27238,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27321,
"s": 27265,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27343,
"s": 27321,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27382,
"s": 27343,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27413,
"s": 27382,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27442,
"s": 27413,
"text": "Create a directory in Python"
}
] |
Axios in React: A Guide for Beginners - GeeksforGeeks | 29 Apr, 2022
In the tech industry, many frontend frameworks are popular, and React is one of them. With any backend language using this framework is not easy. To communicate with the database developers have to follow a specific rule, and they have to write a certain line of code.
In React communicating with the backend server is done via HTTP protocol. If you’re a developer, then you might have been familiar with the XML Http Request interface and Fetch API. It allows you to fetch data and make HTTP requests.
This one is the common method to communicate with the database in React. In React there is another method to communicate with the backend server and that requires the installation of a popular library Axios.
In this article, we are going to discuss this library, its key features, and how Axios work in different cases while communicating with the database.
Introduction to Axios: Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST endpoints. This library is very useful to perform CRUD operations.
This popular library is used to communicate with the backend. Axios supports the Promise API, native to JS ES6.Using Axios we make API requests in our application. Once the request is made we get the data in Return, and then we use this data in our project. This library is very popular among developers. You can check on GitHub and you will find 78k stars on it.
This popular library is used to communicate with the backend. Axios supports the Promise API, native to JS ES6.
Using Axios we make API requests in our application. Once the request is made we get the data in Return, and then we use this data in our project.
This library is very popular among developers. You can check on GitHub and you will find 78k stars on it.
Before you install Axios your React project app should be ready to install this library. Create a React application following the steps given below...
Step 1: Below is the command to create React app in your project...npx create-react-app new_files
Step 1: Below is the command to create React app in your project...
npx create-react-app new_files
Step 2: Enter in the directory created in the first step.cd new_files
Step 2: Enter in the directory created in the first step.
cd new_files
Step 3: Install Axios library using the command given below...npm install axios
Step 3: Install Axios library using the command given below...
npm install axios
Step 4: Once this has been done, you can start the server using the command given below..npm start
Step 4: Once this has been done, you can start the server using the command given below..
npm start
After Axios installation, you can import this library into your file and use it to make an HTTP request. Below is the code snippet of a file where the library is imported at the top...
Javascript
import React from "react";import axios from "axios"; class App extends React.Component { state = { newfiles: null, }; handleFile(e) { // Getting the files from the input let newfiles = e.target.newfiles; this.setState({ newfiles }); } handleUpload(e) { let newfiles = this.state.newfiles; let formData = new FormData(); // Adding files to the formdata formData.append("image", newfiles); formData.append("name", "Name"); axios({ // Endpoint to send files url: "http://localhost:8080/files", method: "POST", headers: { // Add any auth token here authorization: "your token comes here", }, // Attaching the form data data: formData, }) // Handle the response from backend here .then((res) => { }) // Catch errors if any .catch((err) => { }); } render() { return ( <div> <h1>Select your files</h1> <input type="file" // To select multiple files multiple="multiple" onChange={(e) => this.handleFile(e)} /> <button onClick={(e) => this.handleUpload(e)}> Send Files </button> </div> ); }} export default App;
The above example is just a small code description to showcase how to use Axios in your project. We will discuss multiple methods such as GET, POST, PUT in Axios in the upcoming section.
Need of Axios in React: As we have discussed that Axios allows you to communicate with the APIs in your React project. The same tasks can also be performed by using AJAX, but Axios provide you more functionality and features and that helps you in building your application quickly.
Axios is a promise-based library, so you need to implement some promise-based asynchronous HTTP requests. jQuery and AJAX also perform the same job but in React project React handles each and everything in its own virtual DOM, so there is no need to use jQuery at all.
Below is an example to fetch the customer’s data using Axios...
Javascript
const getCustomersData = () => { axios .get("https://jsonplaceholder.typicode.com/customers") .then(data => console.log(data.data)) .catch(error => console.log(error)); }; getCustomersData();
Now let’s come to the next point and understand how different operations can be performed such as fetching the data or consuming the data using Axios (GET-POST-DELETE).
GET Request with Axios: Create a component MyBlog and hook it into the component DidMount lifecycle. Import the Axios at the top and fetch the data with Get request.
Javascript
import React from 'react'; import axios from 'axios'; export default class MyList extends React.Component { state = { blogs: [] } componentDidMount() { axios.get(`https://jsonplaceholder.typicode.com/posts`) .then(response => { const posts = response.data; this.setState ({posts}); }) } render() { return ( < ul > {this.state.posts.map (post => {post.title} )} < /ul > )} }
Here we are using axios.get (URL) to get a promise that returns a response object. Returned response is assigned to the post’s object. We can also retrieve other information such as status code etc.
POST Request with Axios: Create a new component AddPost for Post requests. This request will add a post to the post list.
Javascript
import React from 'react';import axios from 'axios';export default class AddPost extends React.Component { state = { postTitle: '', } handleChange = event => { this.setState({ postTitle: event.target.value }); } handleSubmit = event => { event.preventDefault(); const post = { postName: this.state.postName }; axios.post(`https://jsonplaceholder.typicode.com/posts`, { post }) .then(res => { console.log(res); console.log(res.data); }) [Text Wrapping Break] } render() { return ( <div> <form onSubmit="{this.handleSubmit}"> <label> Post Name: <input type="text" name="name" onChange="{this.handleChange}" /> </label> <button type="submit">Add</button> </form> </div> )}}
In the above code, we have made an HTTP Post request and added a new post to the database. The onChange event triggers the method handleChange() and updates the request when the API request returns the data successfully.
Delete Request With Axios: To send the delete request to the server axios.delete is used. You need to specify two parameters while making this request URL and optional config.
axios.delete(url, {
data: { foo: "bar" },
headers: { "Authorization": "******" }
});
While sending the delete request you will have to set the request body and headers. Use config.data for this purpose. In the above POST request, modify the code as given below...
Javascript
handleSubmit = event => { event.preventDefault(); axios.delete(`https://jsonplaceholder.typicode.com/posts/${this.state.postName}`) .then(res => { console.log(res); console.log(res.data); })}
Response Objects in Axios: When you send a request to the server, you receive a response object from the server with the properties given below...
data: You receive data from the server in payload form. This data is returned in JSON form and parse back into a JavaScript object to you.
status: You get the HTTP code returned from the server.
statusText: HTTP status message returned by the server.
headers: All the headers are sent back by the server.
config: original request configuration.
request: actual XMLHttpRequest object.
Error Object: You will get an error object if there will be a problem with the request. Promise will be rejected with an error object with the properties given
message: Error message text.
response: Response object (if received).
request: Actual XMLHttpRequest object (when running in a browser).
config: Original request configuration.
Features of Axios Library
JSON data is transformed automatically.
It transforms the request and response data.
Useful in making HTTP requests from Node.js
It makes XMLHttpRequests from the browser.
Provide client-side support for protecting against XSRF.
Supports promise API.
Ability to cancel the request.
Shorthand Methods in Axios: Below are some shorthand methods of Axios...
axios.request(config)
axios.head(url[, config])
axios.get(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.delete(url[, config])
axios.options(url[, config])
axios.patch(url[, data[, config]])
This article explained everything about Axios library. We have discussed some useful operations such as fetching the data, posting the data, updating the data, or deleting the data in Axios. Once you will start working on React, you will have to use this library to communicate with the database server. So it is important to make a practice of it and understand how things work in Axios.
React-Questions
GBlog
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Introduction to Recurrent Neural Network
12 pip Commands For Python Developers
A Freshers Guide To Programming
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components | [
{
"code": null,
"e": 26287,
"s": 26259,
"text": "\n29 Apr, 2022"
},
{
"code": null,
"e": 26557,
"s": 26287,
"text": "In the tech industry, many frontend frameworks are popular, and React is one of them. With any backend language using this framework is not easy. To communicate with the database developers have to follow a specific rule, and they have to write a certain line of code. "
},
{
"code": null,
"e": 26793,
"s": 26557,
"text": "In React communicating with the backend server is done via HTTP protocol. If you’re a developer, then you might have been familiar with the XML Http Request interface and Fetch API. It allows you to fetch data and make HTTP requests. "
},
{
"code": null,
"e": 27002,
"s": 26793,
"text": "This one is the common method to communicate with the database in React. In React there is another method to communicate with the backend server and that requires the installation of a popular library Axios. "
},
{
"code": null,
"e": 27153,
"s": 27002,
"text": "In this article, we are going to discuss this library, its key features, and how Axios work in different cases while communicating with the database. "
},
{
"code": null,
"e": 27335,
"s": 27153,
"text": "Introduction to Axios: Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST endpoints. This library is very useful to perform CRUD operations."
},
{
"code": null,
"e": 27700,
"s": 27335,
"text": "This popular library is used to communicate with the backend. Axios supports the Promise API, native to JS ES6.Using Axios we make API requests in our application. Once the request is made we get the data in Return, and then we use this data in our project. This library is very popular among developers. You can check on GitHub and you will find 78k stars on it. "
},
{
"code": null,
"e": 27812,
"s": 27700,
"text": "This popular library is used to communicate with the backend. Axios supports the Promise API, native to JS ES6."
},
{
"code": null,
"e": 27960,
"s": 27812,
"text": "Using Axios we make API requests in our application. Once the request is made we get the data in Return, and then we use this data in our project. "
},
{
"code": null,
"e": 28067,
"s": 27960,
"text": "This library is very popular among developers. You can check on GitHub and you will find 78k stars on it. "
},
{
"code": null,
"e": 28218,
"s": 28067,
"text": "Before you install Axios your React project app should be ready to install this library. Create a React application following the steps given below..."
},
{
"code": null,
"e": 28316,
"s": 28218,
"text": "Step 1: Below is the command to create React app in your project...npx create-react-app new_files"
},
{
"code": null,
"e": 28384,
"s": 28316,
"text": "Step 1: Below is the command to create React app in your project..."
},
{
"code": null,
"e": 28415,
"s": 28384,
"text": "npx create-react-app new_files"
},
{
"code": null,
"e": 28485,
"s": 28415,
"text": "Step 2: Enter in the directory created in the first step.cd new_files"
},
{
"code": null,
"e": 28543,
"s": 28485,
"text": "Step 2: Enter in the directory created in the first step."
},
{
"code": null,
"e": 28556,
"s": 28543,
"text": "cd new_files"
},
{
"code": null,
"e": 28636,
"s": 28556,
"text": "Step 3: Install Axios library using the command given below...npm install axios"
},
{
"code": null,
"e": 28699,
"s": 28636,
"text": "Step 3: Install Axios library using the command given below..."
},
{
"code": null,
"e": 28717,
"s": 28699,
"text": "npm install axios"
},
{
"code": null,
"e": 28816,
"s": 28717,
"text": "Step 4: Once this has been done, you can start the server using the command given below..npm start"
},
{
"code": null,
"e": 28906,
"s": 28816,
"text": "Step 4: Once this has been done, you can start the server using the command given below.."
},
{
"code": null,
"e": 28916,
"s": 28906,
"text": "npm start"
},
{
"code": null,
"e": 29101,
"s": 28916,
"text": "After Axios installation, you can import this library into your file and use it to make an HTTP request. Below is the code snippet of a file where the library is imported at the top..."
},
{
"code": null,
"e": 29114,
"s": 29103,
"text": "Javascript"
},
{
"code": "import React from \"react\";import axios from \"axios\"; class App extends React.Component { state = { newfiles: null, }; handleFile(e) { // Getting the files from the input let newfiles = e.target.newfiles; this.setState({ newfiles }); } handleUpload(e) { let newfiles = this.state.newfiles; let formData = new FormData(); // Adding files to the formdata formData.append(\"image\", newfiles); formData.append(\"name\", \"Name\"); axios({ // Endpoint to send files url: \"http://localhost:8080/files\", method: \"POST\", headers: { // Add any auth token here authorization: \"your token comes here\", }, // Attaching the form data data: formData, }) // Handle the response from backend here .then((res) => { }) // Catch errors if any .catch((err) => { }); } render() { return ( <div> <h1>Select your files</h1> <input type=\"file\" // To select multiple files multiple=\"multiple\" onChange={(e) => this.handleFile(e)} /> <button onClick={(e) => this.handleUpload(e)}> Send Files </button> </div> ); }} export default App;",
"e": 30367,
"s": 29114,
"text": null
},
{
"code": null,
"e": 30554,
"s": 30367,
"text": "The above example is just a small code description to showcase how to use Axios in your project. We will discuss multiple methods such as GET, POST, PUT in Axios in the upcoming section."
},
{
"code": null,
"e": 30837,
"s": 30554,
"text": "Need of Axios in React: As we have discussed that Axios allows you to communicate with the APIs in your React project. The same tasks can also be performed by using AJAX, but Axios provide you more functionality and features and that helps you in building your application quickly. "
},
{
"code": null,
"e": 31111,
"s": 30837,
"text": "Axios is a promise-based library, so you need to implement some promise-based asynchronous HTTP requests. jQuery and AJAX also perform the same job but in React project React handles each and everything in its own virtual DOM, so there is no need to use jQuery at all. "
},
{
"code": null,
"e": 31175,
"s": 31111,
"text": "Below is an example to fetch the customer’s data using Axios..."
},
{
"code": null,
"e": 31186,
"s": 31175,
"text": "Javascript"
},
{
"code": "const getCustomersData = () => { axios .get(\"https://jsonplaceholder.typicode.com/customers\") .then(data => console.log(data.data)) .catch(error => console.log(error)); }; getCustomersData();",
"e": 31383,
"s": 31186,
"text": null
},
{
"code": null,
"e": 31552,
"s": 31383,
"text": "Now let’s come to the next point and understand how different operations can be performed such as fetching the data or consuming the data using Axios (GET-POST-DELETE)."
},
{
"code": null,
"e": 31718,
"s": 31552,
"text": "GET Request with Axios: Create a component MyBlog and hook it into the component DidMount lifecycle. Import the Axios at the top and fetch the data with Get request."
},
{
"code": null,
"e": 31729,
"s": 31718,
"text": "Javascript"
},
{
"code": "import React from 'react'; import axios from 'axios'; export default class MyList extends React.Component { state = { blogs: [] } componentDidMount() { axios.get(`https://jsonplaceholder.typicode.com/posts`) .then(response => { const posts = response.data; this.setState ({posts}); }) } render() { return ( < ul > {this.state.posts.map (post => {post.title} )} < /ul > )} }",
"e": 32140,
"s": 31729,
"text": null
},
{
"code": null,
"e": 32339,
"s": 32140,
"text": "Here we are using axios.get (URL) to get a promise that returns a response object. Returned response is assigned to the post’s object. We can also retrieve other information such as status code etc."
},
{
"code": null,
"e": 32462,
"s": 32339,
"text": "POST Request with Axios: Create a new component AddPost for Post requests. This request will add a post to the post list. "
},
{
"code": null,
"e": 32473,
"s": 32462,
"text": "Javascript"
},
{
"code": "import React from 'react';import axios from 'axios';export default class AddPost extends React.Component { state = { postTitle: '', } handleChange = event => { this.setState({ postTitle: event.target.value }); } handleSubmit = event => { event.preventDefault(); const post = { postName: this.state.postName }; axios.post(`https://jsonplaceholder.typicode.com/posts`, { post }) .then(res => { console.log(res); console.log(res.data); }) [Text Wrapping Break] } render() { return ( <div> <form onSubmit=\"{this.handleSubmit}\"> <label> Post Name: <input type=\"text\" name=\"name\" onChange=\"{this.handleChange}\" /> </label> <button type=\"submit\">Add</button> </form> </div> )}}",
"e": 33355,
"s": 32473,
"text": null
},
{
"code": null,
"e": 33576,
"s": 33355,
"text": "In the above code, we have made an HTTP Post request and added a new post to the database. The onChange event triggers the method handleChange() and updates the request when the API request returns the data successfully."
},
{
"code": null,
"e": 33753,
"s": 33576,
"text": "Delete Request With Axios: To send the delete request to the server axios.delete is used. You need to specify two parameters while making this request URL and optional config. "
},
{
"code": null,
"e": 33846,
"s": 33753,
"text": "axios.delete(url, { \n data: { foo: \"bar\" }, \n headers: { \"Authorization\": \"******\" } \n}); "
},
{
"code": null,
"e": 34025,
"s": 33846,
"text": "While sending the delete request you will have to set the request body and headers. Use config.data for this purpose. In the above POST request, modify the code as given below..."
},
{
"code": null,
"e": 34036,
"s": 34025,
"text": "Javascript"
},
{
"code": "handleSubmit = event => { event.preventDefault(); axios.delete(`https://jsonplaceholder.typicode.com/posts/${this.state.postName}`) .then(res => { console.log(res); console.log(res.data); })}",
"e": 34234,
"s": 34036,
"text": null
},
{
"code": null,
"e": 34381,
"s": 34234,
"text": "Response Objects in Axios: When you send a request to the server, you receive a response object from the server with the properties given below..."
},
{
"code": null,
"e": 34520,
"s": 34381,
"text": "data: You receive data from the server in payload form. This data is returned in JSON form and parse back into a JavaScript object to you."
},
{
"code": null,
"e": 34576,
"s": 34520,
"text": "status: You get the HTTP code returned from the server."
},
{
"code": null,
"e": 34632,
"s": 34576,
"text": "statusText: HTTP status message returned by the server."
},
{
"code": null,
"e": 34686,
"s": 34632,
"text": "headers: All the headers are sent back by the server."
},
{
"code": null,
"e": 34726,
"s": 34686,
"text": "config: original request configuration."
},
{
"code": null,
"e": 34765,
"s": 34726,
"text": "request: actual XMLHttpRequest object."
},
{
"code": null,
"e": 34925,
"s": 34765,
"text": "Error Object: You will get an error object if there will be a problem with the request. Promise will be rejected with an error object with the properties given"
},
{
"code": null,
"e": 34955,
"s": 34925,
"text": "message: Error message text. "
},
{
"code": null,
"e": 34997,
"s": 34955,
"text": "response: Response object (if received). "
},
{
"code": null,
"e": 35065,
"s": 34997,
"text": "request: Actual XMLHttpRequest object (when running in a browser). "
},
{
"code": null,
"e": 35106,
"s": 35065,
"text": "config: Original request configuration. "
},
{
"code": null,
"e": 35132,
"s": 35106,
"text": "Features of Axios Library"
},
{
"code": null,
"e": 35172,
"s": 35132,
"text": "JSON data is transformed automatically."
},
{
"code": null,
"e": 35217,
"s": 35172,
"text": "It transforms the request and response data."
},
{
"code": null,
"e": 35261,
"s": 35217,
"text": "Useful in making HTTP requests from Node.js"
},
{
"code": null,
"e": 35304,
"s": 35261,
"text": "It makes XMLHttpRequests from the browser."
},
{
"code": null,
"e": 35361,
"s": 35304,
"text": "Provide client-side support for protecting against XSRF."
},
{
"code": null,
"e": 35383,
"s": 35361,
"text": "Supports promise API."
},
{
"code": null,
"e": 35414,
"s": 35383,
"text": "Ability to cancel the request."
},
{
"code": null,
"e": 35487,
"s": 35414,
"text": "Shorthand Methods in Axios: Below are some shorthand methods of Axios..."
},
{
"code": null,
"e": 35509,
"s": 35487,
"text": "axios.request(config)"
},
{
"code": null,
"e": 35535,
"s": 35509,
"text": "axios.head(url[, config])"
},
{
"code": null,
"e": 35560,
"s": 35535,
"text": "axios.get(url[, config])"
},
{
"code": null,
"e": 35594,
"s": 35560,
"text": "axios.post(url[, data[, config]])"
},
{
"code": null,
"e": 35627,
"s": 35594,
"text": "axios.put(url[, data[, config]])"
},
{
"code": null,
"e": 35655,
"s": 35627,
"text": "axios.delete(url[, config])"
},
{
"code": null,
"e": 35684,
"s": 35655,
"text": "axios.options(url[, config])"
},
{
"code": null,
"e": 35719,
"s": 35684,
"text": "axios.patch(url[, data[, config]])"
},
{
"code": null,
"e": 36108,
"s": 35719,
"text": "This article explained everything about Axios library. We have discussed some useful operations such as fetching the data, posting the data, updating the data, or deleting the data in Axios. Once you will start working on React, you will have to use this library to communicate with the database server. So it is important to make a practice of it and understand how things work in Axios."
},
{
"code": null,
"e": 36124,
"s": 36108,
"text": "React-Questions"
},
{
"code": null,
"e": 36130,
"s": 36124,
"text": "GBlog"
},
{
"code": null,
"e": 36138,
"s": 36130,
"text": "ReactJS"
},
{
"code": null,
"e": 36155,
"s": 36138,
"text": "Web Technologies"
},
{
"code": null,
"e": 36253,
"s": 36155,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36278,
"s": 36253,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36305,
"s": 36278,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 36346,
"s": 36305,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 36384,
"s": 36346,
"text": "12 pip Commands For Python Developers"
},
{
"code": null,
"e": 36416,
"s": 36384,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 36459,
"s": 36416,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 36504,
"s": 36459,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 36569,
"s": 36504,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 36637,
"s": 36569,
"text": "How to pass data from one component to other component in ReactJS ?"
}
] |
Engineering Mathematics - Well Formed Formulas (WFF) - GeeksforGeeks | 17 Dec, 2021
Well-Formed Formula(WFF) is an expression consisting of variables(capital letters), parentheses, and connective symbols. An expression is basically a combination of operands & operators and here operands and operators are the connective symbols.
Below are the possible Connective Symbols:
¬ (Negation)∧ (Conjunction)∨ (Disjunction)⇒ (Rightwards Arrow)⇔ (Left-Right Arrow)
¬ (Negation)
∧ (Conjunction)
∨ (Disjunction)
⇒ (Rightwards Arrow)
⇔ (Left-Right Arrow)
1. Statements that do not contain any connectives are called Atomic or Simple statements and these statements in themselves are WFFs.
For example,
P, Q, R, etc.
2. Statements that contain one or more primary statements are called Molecular or Composite statements.
For example,
If P and Q are two simple statements, then some of the Composite statements which follow WFF standards can be formed are:
-> ¬P
-> ¬Q
-> (P ∨ Q)
-> (P ∧ Q)
-> (¬P ∨ Q)
-> ((P ∨ Q) ∧ Q)
-> (P ⇒ Q)
-> (P ⇔ Q)
-> ¬(P ∨ Q)
-> ¬(¬P ∨ ¬Q)
A Statement variable standing alone is a Well-Formed Formula(WFF). For example– Statements like P, ∼P, Q, ∼Q are themselves Well Formed Formulas.If ‘P’ is a WFF then ∼P is a formula as well.If P & Q are WFFs, then (P∨Q), (P∧Q), (P⇒Q), (P⇔Q), etc. are also WFFs.
A Statement variable standing alone is a Well-Formed Formula(WFF). For example– Statements like P, ∼P, Q, ∼Q are themselves Well Formed Formulas.
If ‘P’ is a WFF then ∼P is a formula as well.
If P & Q are WFFs, then (P∨Q), (P∧Q), (P⇒Q), (P⇔Q), etc. are also WFFs.
WFF
Explanation
(P), ‘P’ itself alone is considered as a WFF by Rule 1 but placing that inside parenthesis is not considered as a WFF by any rule.¬P ∧ Q, this can be either (¬P∧Q) or ¬(P∧Q) so we have ambiguity in this statement and hence it will not be considered as a WFF. Parentheses are mandatory to be included in Composite Statements.((P ⇒ Q)), We can say (P⇒Q) is a WFF and let (P⇒Q) = A, now considering the outer parentheses, we will be left with (A), which is not a valid WFF. Parentheses play a really important role in these types of questions.(P ⇒⇒ Q), connective symbol right after a connective symbol is not considered to be valid for a WFF.((P ∧ Q) ∧)Q), conjunction operator after (P∧Q) is not valid.((P ∧ Q) ∧ PQ), invalid placement of variables(PQ).(P ∨ Q) ⇒ (∧ Q), with the Conjunction component, only one variable ‘Q’ is present. In order to form an operation inside a parentheses minimum of 2 variables are required.
(P), ‘P’ itself alone is considered as a WFF by Rule 1 but placing that inside parenthesis is not considered as a WFF by any rule.
¬P ∧ Q, this can be either (¬P∧Q) or ¬(P∧Q) so we have ambiguity in this statement and hence it will not be considered as a WFF. Parentheses are mandatory to be included in Composite Statements.
((P ⇒ Q)), We can say (P⇒Q) is a WFF and let (P⇒Q) = A, now considering the outer parentheses, we will be left with (A), which is not a valid WFF. Parentheses play a really important role in these types of questions.
(P ⇒⇒ Q), connective symbol right after a connective symbol is not considered to be valid for a WFF.
((P ∧ Q) ∧)Q), conjunction operator after (P∧Q) is not valid.
((P ∧ Q) ∧ PQ), invalid placement of variables(PQ).
(P ∨ Q) ⇒ (∧ Q), with the Conjunction component, only one variable ‘Q’ is present. In order to form an operation inside a parentheses minimum of 2 variables are required.
Picked
Computer Subject
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Transmission Control Protocol (TCP)?
Difference Between User Mode and Kernel Mode
OSI Security Architecture
Regular Expression to DFA
Token, Patterns, and Lexems
Inequalities in LaTeX
Relationship between number of nodes and height of binary tree
Activation Functions
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
Arrow Symbols in LaTeX | [
{
"code": null,
"e": 25911,
"s": 25883,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 26157,
"s": 25911,
"text": "Well-Formed Formula(WFF) is an expression consisting of variables(capital letters), parentheses, and connective symbols. An expression is basically a combination of operands & operators and here operands and operators are the connective symbols."
},
{
"code": null,
"e": 26200,
"s": 26157,
"text": "Below are the possible Connective Symbols:"
},
{
"code": null,
"e": 26283,
"s": 26200,
"text": "¬ (Negation)∧ (Conjunction)∨ (Disjunction)⇒ (Rightwards Arrow)⇔ (Left-Right Arrow)"
},
{
"code": null,
"e": 26296,
"s": 26283,
"text": "¬ (Negation)"
},
{
"code": null,
"e": 26312,
"s": 26296,
"text": "∧ (Conjunction)"
},
{
"code": null,
"e": 26328,
"s": 26312,
"text": "∨ (Disjunction)"
},
{
"code": null,
"e": 26349,
"s": 26328,
"text": "⇒ (Rightwards Arrow)"
},
{
"code": null,
"e": 26370,
"s": 26349,
"text": "⇔ (Left-Right Arrow)"
},
{
"code": null,
"e": 26505,
"s": 26370,
"text": "1. Statements that do not contain any connectives are called Atomic or Simple statements and these statements in themselves are WFFs. "
},
{
"code": null,
"e": 26518,
"s": 26505,
"text": "For example,"
},
{
"code": null,
"e": 26532,
"s": 26518,
"text": "P, Q, R, etc."
},
{
"code": null,
"e": 26637,
"s": 26532,
"text": "2. Statements that contain one or more primary statements are called Molecular or Composite statements. "
},
{
"code": null,
"e": 26651,
"s": 26637,
"text": "For example, "
},
{
"code": null,
"e": 26773,
"s": 26651,
"text": "If P and Q are two simple statements, then some of the Composite statements which follow WFF standards can be formed are:"
},
{
"code": null,
"e": 26783,
"s": 26773,
"text": "-> ¬P "
},
{
"code": null,
"e": 26793,
"s": 26783,
"text": "-> ¬Q "
},
{
"code": null,
"e": 26808,
"s": 26793,
"text": "-> (P ∨ Q) "
},
{
"code": null,
"e": 26822,
"s": 26808,
"text": "-> (P ∧ Q)"
},
{
"code": null,
"e": 26838,
"s": 26822,
"text": "-> (¬P ∨ Q) "
},
{
"code": null,
"e": 26858,
"s": 26838,
"text": "-> ((P ∨ Q) ∧ Q)"
},
{
"code": null,
"e": 26872,
"s": 26858,
"text": "-> (P ⇒ Q)"
},
{
"code": null,
"e": 26886,
"s": 26872,
"text": "-> (P ⇔ Q)"
},
{
"code": null,
"e": 26901,
"s": 26886,
"text": "-> ¬(P ∨ Q)"
},
{
"code": null,
"e": 26918,
"s": 26901,
"text": "-> ¬(¬P ∨ ¬Q)"
},
{
"code": null,
"e": 27180,
"s": 26918,
"text": "A Statement variable standing alone is a Well-Formed Formula(WFF). For example– Statements like P, ∼P, Q, ∼Q are themselves Well Formed Formulas.If ‘P’ is a WFF then ∼P is a formula as well.If P & Q are WFFs, then (P∨Q), (P∧Q), (P⇒Q), (P⇔Q), etc. are also WFFs."
},
{
"code": null,
"e": 27326,
"s": 27180,
"text": "A Statement variable standing alone is a Well-Formed Formula(WFF). For example– Statements like P, ∼P, Q, ∼Q are themselves Well Formed Formulas."
},
{
"code": null,
"e": 27372,
"s": 27326,
"text": "If ‘P’ is a WFF then ∼P is a formula as well."
},
{
"code": null,
"e": 27444,
"s": 27372,
"text": "If P & Q are WFFs, then (P∨Q), (P∧Q), (P⇒Q), (P⇔Q), etc. are also WFFs."
},
{
"code": null,
"e": 27448,
"s": 27444,
"text": "WFF"
},
{
"code": null,
"e": 27460,
"s": 27448,
"text": "Explanation"
},
{
"code": null,
"e": 28383,
"s": 27460,
"text": "(P), ‘P’ itself alone is considered as a WFF by Rule 1 but placing that inside parenthesis is not considered as a WFF by any rule.¬P ∧ Q, this can be either (¬P∧Q) or ¬(P∧Q) so we have ambiguity in this statement and hence it will not be considered as a WFF. Parentheses are mandatory to be included in Composite Statements.((P ⇒ Q)), We can say (P⇒Q) is a WFF and let (P⇒Q) = A, now considering the outer parentheses, we will be left with (A), which is not a valid WFF. Parentheses play a really important role in these types of questions.(P ⇒⇒ Q), connective symbol right after a connective symbol is not considered to be valid for a WFF.((P ∧ Q) ∧)Q), conjunction operator after (P∧Q) is not valid.((P ∧ Q) ∧ PQ), invalid placement of variables(PQ).(P ∨ Q) ⇒ (∧ Q), with the Conjunction component, only one variable ‘Q’ is present. In order to form an operation inside a parentheses minimum of 2 variables are required."
},
{
"code": null,
"e": 28514,
"s": 28383,
"text": "(P), ‘P’ itself alone is considered as a WFF by Rule 1 but placing that inside parenthesis is not considered as a WFF by any rule."
},
{
"code": null,
"e": 28709,
"s": 28514,
"text": "¬P ∧ Q, this can be either (¬P∧Q) or ¬(P∧Q) so we have ambiguity in this statement and hence it will not be considered as a WFF. Parentheses are mandatory to be included in Composite Statements."
},
{
"code": null,
"e": 28926,
"s": 28709,
"text": "((P ⇒ Q)), We can say (P⇒Q) is a WFF and let (P⇒Q) = A, now considering the outer parentheses, we will be left with (A), which is not a valid WFF. Parentheses play a really important role in these types of questions."
},
{
"code": null,
"e": 29027,
"s": 28926,
"text": "(P ⇒⇒ Q), connective symbol right after a connective symbol is not considered to be valid for a WFF."
},
{
"code": null,
"e": 29089,
"s": 29027,
"text": "((P ∧ Q) ∧)Q), conjunction operator after (P∧Q) is not valid."
},
{
"code": null,
"e": 29141,
"s": 29089,
"text": "((P ∧ Q) ∧ PQ), invalid placement of variables(PQ)."
},
{
"code": null,
"e": 29312,
"s": 29141,
"text": "(P ∨ Q) ⇒ (∧ Q), with the Conjunction component, only one variable ‘Q’ is present. In order to form an operation inside a parentheses minimum of 2 variables are required."
},
{
"code": null,
"e": 29319,
"s": 29312,
"text": "Picked"
},
{
"code": null,
"e": 29336,
"s": 29319,
"text": "Computer Subject"
},
{
"code": null,
"e": 29360,
"s": 29336,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 29458,
"s": 29360,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29503,
"s": 29458,
"text": "What is Transmission Control Protocol (TCP)?"
},
{
"code": null,
"e": 29548,
"s": 29503,
"text": "Difference Between User Mode and Kernel Mode"
},
{
"code": null,
"e": 29574,
"s": 29548,
"text": "OSI Security Architecture"
},
{
"code": null,
"e": 29600,
"s": 29574,
"text": "Regular Expression to DFA"
},
{
"code": null,
"e": 29628,
"s": 29600,
"text": "Token, Patterns, and Lexems"
},
{
"code": null,
"e": 29650,
"s": 29628,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 29713,
"s": 29650,
"text": "Relationship between number of nodes and height of binary tree"
},
{
"code": null,
"e": 29734,
"s": 29713,
"text": "Activation Functions"
},
{
"code": null,
"e": 29799,
"s": 29734,
"text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph"
}
] |
Static Single Assignment (with relevant examples) - GeeksforGeeks | 06 Oct, 2021
Static Single Assignment was presented in 1988 by Barry K. Rosen, Mark N, Wegman, and F. Kenneth Zadeck.
In compiler design, Static Single Assignment ( shortened SSA) is a means of structuring the IR (intermediate representation) such that every variable is allotted a value only once and every variable is defined before it’s use. The prime use of SSA is it simplifies and improves the results of compiler optimisation algorithms, simultaneously by simplifying the variable properties. Some Algorithms improved by application of SSA –
Constant Propagation – Translation of calculations from runtime to compile time. E.g. – the instruction v = 2*7+13 is treated like v = 27Value Range Propagation – Finding the possible range of values a calculation could result in.Dead Code Elimination –Removing the code which is not accessible and will have no effect on results whatsoever.Strength Reduction –Replacing computationally expensive calculations by inexpensive ones.Register Allocation –Optimising the use of registers for calculations.
Constant Propagation – Translation of calculations from runtime to compile time. E.g. – the instruction v = 2*7+13 is treated like v = 27
Value Range Propagation – Finding the possible range of values a calculation could result in.
Dead Code Elimination –Removing the code which is not accessible and will have no effect on results whatsoever.
Strength Reduction –Replacing computationally expensive calculations by inexpensive ones.
Register Allocation –Optimising the use of registers for calculations.
Any code can be converted to SSA form by simply replacing the target variable of each code segment with a new variable and substituting each use of a variable with the new edition of the variable reaching that point. Versions are created by splitting the original variables existing in IR and are represented by original name with a subscript such that every variable gets its own version.
Example #1:
Convert the following code segment to SSA form:
x = y - z
s = x + s
x = s + p
s = z * q
s = x * s
Solution:
x = y - z
s2 = x + s
x2 = s2 + p
s3 = z * q
s4 = x2 * s3
Here x,y,z,s,p,q are original variables and x2, s2, s3, s4 are versions of x and s.
Example #2:
Convert the following code segment to SSA form:
a = s - b
q = a * e
a = q + d
q = b - c
q = a * q
Solution:
a = s - b
q = a * e
a2 = q + d
q2 = b - c
q3 = a2 * q2
Here a,b,c,d,e,q,s are original variables and a2, q2, q3 are versions of a and q.
Picked
Compiler Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
S - attributed and L - attributed SDTs in Syntax directed translation
Issues in the design of a code generator
Error Handling in Compiler Design
Difference between Top down parsing and Bottom up parsing
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS | [
{
"code": null,
"e": 25665,
"s": 25637,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 25771,
"s": 25665,
"text": "Static Single Assignment was presented in 1988 by Barry K. Rosen, Mark N, Wegman, and F. Kenneth Zadeck. "
},
{
"code": null,
"e": 26203,
"s": 25771,
"text": "In compiler design, Static Single Assignment ( shortened SSA) is a means of structuring the IR (intermediate representation) such that every variable is allotted a value only once and every variable is defined before it’s use. The prime use of SSA is it simplifies and improves the results of compiler optimisation algorithms, simultaneously by simplifying the variable properties. Some Algorithms improved by application of SSA – "
},
{
"code": null,
"e": 26704,
"s": 26203,
"text": "Constant Propagation – Translation of calculations from runtime to compile time. E.g. – the instruction v = 2*7+13 is treated like v = 27Value Range Propagation – Finding the possible range of values a calculation could result in.Dead Code Elimination –Removing the code which is not accessible and will have no effect on results whatsoever.Strength Reduction –Replacing computationally expensive calculations by inexpensive ones.Register Allocation –Optimising the use of registers for calculations."
},
{
"code": null,
"e": 26842,
"s": 26704,
"text": "Constant Propagation – Translation of calculations from runtime to compile time. E.g. – the instruction v = 2*7+13 is treated like v = 27"
},
{
"code": null,
"e": 26936,
"s": 26842,
"text": "Value Range Propagation – Finding the possible range of values a calculation could result in."
},
{
"code": null,
"e": 27048,
"s": 26936,
"text": "Dead Code Elimination –Removing the code which is not accessible and will have no effect on results whatsoever."
},
{
"code": null,
"e": 27138,
"s": 27048,
"text": "Strength Reduction –Replacing computationally expensive calculations by inexpensive ones."
},
{
"code": null,
"e": 27209,
"s": 27138,
"text": "Register Allocation –Optimising the use of registers for calculations."
},
{
"code": null,
"e": 27599,
"s": 27209,
"text": "Any code can be converted to SSA form by simply replacing the target variable of each code segment with a new variable and substituting each use of a variable with the new edition of the variable reaching that point. Versions are created by splitting the original variables existing in IR and are represented by original name with a subscript such that every variable gets its own version."
},
{
"code": null,
"e": 27611,
"s": 27599,
"text": "Example #1:"
},
{
"code": null,
"e": 27659,
"s": 27611,
"text": "Convert the following code segment to SSA form:"
},
{
"code": null,
"e": 27709,
"s": 27659,
"text": "x = y - z\ns = x + s\nx = s + p\ns = z * q\ns = x * s"
},
{
"code": null,
"e": 27719,
"s": 27709,
"text": "Solution:"
},
{
"code": null,
"e": 27776,
"s": 27719,
"text": "x = y - z\ns2 = x + s\nx2 = s2 + p\ns3 = z * q\ns4 = x2 * s3"
},
{
"code": null,
"e": 27861,
"s": 27776,
"text": "Here x,y,z,s,p,q are original variables and x2, s2, s3, s4 are versions of x and s. "
},
{
"code": null,
"e": 27873,
"s": 27861,
"text": "Example #2:"
},
{
"code": null,
"e": 27921,
"s": 27873,
"text": "Convert the following code segment to SSA form:"
},
{
"code": null,
"e": 27971,
"s": 27921,
"text": "a = s - b\nq = a * e\na = q + d\nq = b - c\nq = a * q"
},
{
"code": null,
"e": 27981,
"s": 27971,
"text": "Solution:"
},
{
"code": null,
"e": 28036,
"s": 27981,
"text": "a = s - b\nq = a * e\na2 = q + d\nq2 = b - c\nq3 = a2 * q2"
},
{
"code": null,
"e": 28119,
"s": 28036,
"text": "Here a,b,c,d,e,q,s are original variables and a2, q2, q3 are versions of a and q. "
},
{
"code": null,
"e": 28126,
"s": 28119,
"text": "Picked"
},
{
"code": null,
"e": 28142,
"s": 28126,
"text": "Compiler Design"
},
{
"code": null,
"e": 28150,
"s": 28142,
"text": "GATE CS"
},
{
"code": null,
"e": 28248,
"s": 28150,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28306,
"s": 28248,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 28376,
"s": 28306,
"text": "S - attributed and L - attributed SDTs in Syntax directed translation"
},
{
"code": null,
"e": 28417,
"s": 28376,
"text": "Issues in the design of a code generator"
},
{
"code": null,
"e": 28451,
"s": 28417,
"text": "Error Handling in Compiler Design"
},
{
"code": null,
"e": 28509,
"s": 28451,
"text": "Difference between Top down parsing and Bottom up parsing"
},
{
"code": null,
"e": 28529,
"s": 28509,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 28553,
"s": 28529,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 28566,
"s": 28553,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 28593,
"s": 28566,
"text": "Types of Operating Systems"
}
] |
Check if a queue can be sorted into another queue using a stack - GeeksforGeeks | 13 Jan, 2022
Given a Queue consisting of first n natural numbers (in random order). The task is to check whether the given Queue elements can be arranged in increasing order in another Queue using a stack. The operation allowed are: 1. Push and pop elements from the stack 2. Pop (Or Dequeue) from the given Queue. 3. Push (Or Enqueue) in the another Queue.
Examples :
Input : Queue[] = { 5, 1, 2, 3, 4 } Output : Yes Pop the first element of the given Queue i.e 5. Push 5 into the stack. Now, pop all the elements of the given Queue and push them to second Queue. Now, pop element 5 in the stack and push it to the second Queue. Input : Queue[] = { 5, 1, 2, 6, 3, 4 } Output : No Push 5 to stack. Pop 1, 2 from given Queue and push it to another Queue. Pop 6 from given Queue and push to stack. Pop 3, 4 from given Queue and push to second Queue. Now, from using any of above operation, we cannot push 5 into the second Queue because it is below the 6 in the stack.
Observe, second Queue (which will contain the sorted element) takes inputs (or enqueue elements) either from given Queue or Stack. So, the next expected (which will initially be 1) element must be present as a front element of a given Queue or top element of the Stack. So, simply simulate the process for the second Queue by initializing the expected element as 1. And check if we can get the expected element from the front of the given Queue or from the top of the Stack. If we cannot take it from either of them then pop the front element of the given Queue and push it in the Stack. Also, observe, that the stack must also be sorted at each instance i.e the element at the top of the stack must be the smallest in the stack. For eg. let x > y, then x will always be expected before y. So, x cannot be pushed before y in the stack. Therefore, we cannot push an element with a higher value on the top of the element having a lesser value.
Algorithm: 1. Initialize the expected_element = 1 2. Check if either front element of given Queue or top element of the stack have expected_element ....a) If yes, increment expected_element by 1, repeat step 2. ....b) Else, pop front of Queue and push it to the stack. If the popped element is greater than top of the Stack, return “No”.
Below is the implementation of this approach:
C++
Java
Python3
C#
Javascript
// CPP Program to check if a queue of first// n natural number can be sorted using a stack#include <bits/stdc++.h>using namespace std; // Function to check if given queue element// can be sorted into another queue using a// stack.bool checkSorted(int n, queue<int>& q){ stack<int> st; int expected = 1; int fnt; // while given Queue is not empty. while (!q.empty()) { fnt = q.front(); q.pop(); // if front element is the expected element if (fnt == expected) expected++; else { // if stack is empty, push the element if (st.empty()) { st.push(fnt); } // if top element is less than element which // need to be pushed, then return false. else if (!st.empty() && st.top() < fnt) { return false; } // else push into the stack. else st.push(fnt); } // while expected element are coming from // stack, pop them out. while (!st.empty() && st.top() == expected) { st.pop(); expected++; } } // if the final expected element value is equal // to initial Queue size and the stack is empty. if (expected - 1 == n && st.empty()) return true; return false;} // Driven Programint main(){ queue<int> q; q.push(5); q.push(1); q.push(2); q.push(3); q.push(4); int n = q.size(); (checkSorted(n, q) ? (cout << "Yes") : (cout << "No")); return 0;}
// Java Program to check if a queue// of first n natural number can// be sorted using a stackimport java.io.*;import java.util.*; class GFG{ static Queue<Integer> q = new LinkedList<Integer>(); // Function to check if given // queue element can be sorted // into another queue using a stack. static boolean checkSorted(int n) { Stack<Integer> st = new Stack<Integer>(); int expected = 1; int fnt; // while given Queue // is not empty. while (q.size() != 0) { fnt = q.peek(); q.poll(); // if front element is // the expected element if (fnt == expected) expected++; else { // if stack is empty, // push the element if (st.size() == 0) { st.push(fnt); } // if top element is less than // element which need to be // pushed, then return false. else if (st.size() != 0 && st.peek() < fnt) { return false; } // else push into the stack. else st.push(fnt); } // while expected element are // coming from stack, pop them out. while (st.size() != 0 && st.peek() == expected) { st.pop(); expected++; } } // if the final expected element // value is equal to initial Queue // size and the stack is empty. if (expected - 1 == n && st.size() == 0) return true; return false; } // Driver Code public static void main(String args[]) { q.add(5); q.add(1); q.add(2); q.add(3); q.add(4); int n = q.size(); if (checkSorted(n)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by// Manish Shaw(manishshaw1)
# Python Program to check if a queue of first# n natural number can be sorted using a stackfrom queue import Queue # Function to check if given queue element# can be sorted into another queue using a# stack.def checkSorted(n, q): st = [] expected = 1 fnt = None # while given Queue is not empty. while (not q.empty()): fnt = q.queue[0] q.get() # if front element is the # expected element if (fnt == expected): expected += 1 else: # if stack is empty, put the element if (len(st) == 0): st.append(fnt) # if top element is less than element which # need to be puted, then return false. elif (len(st) != 0 and st[-1] < fnt): return False # else put into the stack. else: st.append(fnt) # while expected element are coming # from stack, pop them out. while (len(st) != 0 and st[-1] == expected): st.pop() expected += 1 # if the final expected element value is equal # to initial Queue size and the stack is empty. if (expected - 1 == n and len(st) == 0): return True return False # Driver Codeif __name__ == '__main__': q = Queue() q.put(5) q.put(1) q.put(2) q.put(3) q.put(4) n = q.qsize() if checkSorted(n, q): print("Yes") else: print("No") # This code is contributed by PranchalK
// C# Program to check if a queue// of first n natural number can// be sorted using a stackusing System;using System.Linq;using System.Collections.Generic; class GFG{ // Function to check if given // queue element can be sorted // into another queue using a stack. static bool checkSorted(int n, ref Queue<int> q) { Stack<int> st = new Stack<int>(); int expected = 1; int fnt; // while given Queue // is not empty. while (q.Count != 0) { fnt = q.Peek(); q.Dequeue(); // if front element is // the expected element if (fnt == expected) expected++; else { // if stack is empty, // push the element if (st.Count == 0) { st.Push(fnt); } // if top element is less than // element which need to be // pushed, then return false. else if (st.Count != 0 && st.Peek() < fnt) { return false; } // else push into the stack. else st.Push(fnt); } // while expected element are // coming from stack, pop them out. while (st.Count != 0 && st.Peek() == expected) { st.Pop(); expected++; } } // if the final expected element // value is equal to initial Queue // size and the stack is empty. if (expected - 1 == n && st.Count == 0) return true; return false; } // Driver Code static void Main() { Queue<int> q = new Queue<int>(); q.Enqueue(5); q.Enqueue(1); q.Enqueue(2); q.Enqueue(3); q.Enqueue(4); int n = q.Count; if (checkSorted(n, ref q)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by// Manish Shaw(manishshaw1)
<script> // Javascript Program to check if a queue // of first n natural number can // be sorted using a stack let q = []; // Function to check if given // queue element can be sorted // into another queue using a stack. function checkSorted(n) { let st = []; let expected = 1; let fnt; // while given Queue // is not empty. while (q.length != 0) { fnt = q[0]; q.shift(); // if front element is // the expected element if (fnt == expected) expected++; else { // if stack is empty, // push the element if (st.length == 0) { st.push(fnt); } // if top element is less than // element which need to be // pushed, then return false. else if (st.length != 0 && st[st.length - 1] < fnt) { return false; } // else push into the stack. else st.push(fnt); } // while expected element are // coming from stack, pop them out. while (st.length != 0 && st[st.length - 1] == expected) { st.pop(); expected++; } } // if the final expected element // value is equal to initial Queue // size and the stack is empty. if ((expected - 1) == n && st.length == 0) return true; return false; } q.push(5); q.push(1); q.push(2); q.push(3); q.push(4); let n = q.length; if (checkSorted(n)) document.write("Yes"); else document.write("No"); // This code is contributed by suresh07.</script>
Yes
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fckxsNKtDUo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Video Contributed by Parul Shandilya
manishshaw1
ParulShandilya
abdulmohsin
PranchalKatiyar
18ucs102
suresh07
simmytarika5
sundara mohan m
gsouvik04
notavacillator
Queue
Sorting
Stack
Stack
Sorting
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Queue | Set 1 (Introduction and Array Implementation)
Priority Queue | Set 1 (Introduction)
LRU Cache Implementation
Queue - Linked List Implementation
Circular Queue | Set 1 (Introduction and Array Implementation) | [
{
"code": null,
"e": 25933,
"s": 25905,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 26278,
"s": 25933,
"text": "Given a Queue consisting of first n natural numbers (in random order). The task is to check whether the given Queue elements can be arranged in increasing order in another Queue using a stack. The operation allowed are: 1. Push and pop elements from the stack 2. Pop (Or Dequeue) from the given Queue. 3. Push (Or Enqueue) in the another Queue."
},
{
"code": null,
"e": 26289,
"s": 26278,
"text": "Examples :"
},
{
"code": null,
"e": 26891,
"s": 26289,
"text": " Input : Queue[] = { 5, 1, 2, 3, 4 } Output : Yes Pop the first element of the given Queue i.e 5. Push 5 into the stack. Now, pop all the elements of the given Queue and push them to second Queue. Now, pop element 5 in the stack and push it to the second Queue. Input : Queue[] = { 5, 1, 2, 6, 3, 4 } Output : No Push 5 to stack. Pop 1, 2 from given Queue and push it to another Queue. Pop 6 from given Queue and push to stack. Pop 3, 4 from given Queue and push to second Queue. Now, from using any of above operation, we cannot push 5 into the second Queue because it is below the 6 in the stack. "
},
{
"code": null,
"e": 27833,
"s": 26891,
"text": "Observe, second Queue (which will contain the sorted element) takes inputs (or enqueue elements) either from given Queue or Stack. So, the next expected (which will initially be 1) element must be present as a front element of a given Queue or top element of the Stack. So, simply simulate the process for the second Queue by initializing the expected element as 1. And check if we can get the expected element from the front of the given Queue or from the top of the Stack. If we cannot take it from either of them then pop the front element of the given Queue and push it in the Stack. Also, observe, that the stack must also be sorted at each instance i.e the element at the top of the stack must be the smallest in the stack. For eg. let x > y, then x will always be expected before y. So, x cannot be pushed before y in the stack. Therefore, we cannot push an element with a higher value on the top of the element having a lesser value."
},
{
"code": null,
"e": 28171,
"s": 27833,
"text": "Algorithm: 1. Initialize the expected_element = 1 2. Check if either front element of given Queue or top element of the stack have expected_element ....a) If yes, increment expected_element by 1, repeat step 2. ....b) Else, pop front of Queue and push it to the stack. If the popped element is greater than top of the Stack, return “No”."
},
{
"code": null,
"e": 28218,
"s": 28171,
"text": "Below is the implementation of this approach: "
},
{
"code": null,
"e": 28222,
"s": 28218,
"text": "C++"
},
{
"code": null,
"e": 28227,
"s": 28222,
"text": "Java"
},
{
"code": null,
"e": 28235,
"s": 28227,
"text": "Python3"
},
{
"code": null,
"e": 28238,
"s": 28235,
"text": "C#"
},
{
"code": null,
"e": 28249,
"s": 28238,
"text": "Javascript"
},
{
"code": "// CPP Program to check if a queue of first// n natural number can be sorted using a stack#include <bits/stdc++.h>using namespace std; // Function to check if given queue element// can be sorted into another queue using a// stack.bool checkSorted(int n, queue<int>& q){ stack<int> st; int expected = 1; int fnt; // while given Queue is not empty. while (!q.empty()) { fnt = q.front(); q.pop(); // if front element is the expected element if (fnt == expected) expected++; else { // if stack is empty, push the element if (st.empty()) { st.push(fnt); } // if top element is less than element which // need to be pushed, then return false. else if (!st.empty() && st.top() < fnt) { return false; } // else push into the stack. else st.push(fnt); } // while expected element are coming from // stack, pop them out. while (!st.empty() && st.top() == expected) { st.pop(); expected++; } } // if the final expected element value is equal // to initial Queue size and the stack is empty. if (expected - 1 == n && st.empty()) return true; return false;} // Driven Programint main(){ queue<int> q; q.push(5); q.push(1); q.push(2); q.push(3); q.push(4); int n = q.size(); (checkSorted(n, q) ? (cout << \"Yes\") : (cout << \"No\")); return 0;}",
"e": 29823,
"s": 28249,
"text": null
},
{
"code": "// Java Program to check if a queue// of first n natural number can// be sorted using a stackimport java.io.*;import java.util.*; class GFG{ static Queue<Integer> q = new LinkedList<Integer>(); // Function to check if given // queue element can be sorted // into another queue using a stack. static boolean checkSorted(int n) { Stack<Integer> st = new Stack<Integer>(); int expected = 1; int fnt; // while given Queue // is not empty. while (q.size() != 0) { fnt = q.peek(); q.poll(); // if front element is // the expected element if (fnt == expected) expected++; else { // if stack is empty, // push the element if (st.size() == 0) { st.push(fnt); } // if top element is less than // element which need to be // pushed, then return false. else if (st.size() != 0 && st.peek() < fnt) { return false; } // else push into the stack. else st.push(fnt); } // while expected element are // coming from stack, pop them out. while (st.size() != 0 && st.peek() == expected) { st.pop(); expected++; } } // if the final expected element // value is equal to initial Queue // size and the stack is empty. if (expected - 1 == n && st.size() == 0) return true; return false; } // Driver Code public static void main(String args[]) { q.add(5); q.add(1); q.add(2); q.add(3); q.add(4); int n = q.size(); if (checkSorted(n)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 32055,
"s": 29823,
"text": null
},
{
"code": "# Python Program to check if a queue of first# n natural number can be sorted using a stackfrom queue import Queue # Function to check if given queue element# can be sorted into another queue using a# stack.def checkSorted(n, q): st = [] expected = 1 fnt = None # while given Queue is not empty. while (not q.empty()): fnt = q.queue[0] q.get() # if front element is the # expected element if (fnt == expected): expected += 1 else: # if stack is empty, put the element if (len(st) == 0): st.append(fnt) # if top element is less than element which # need to be puted, then return false. elif (len(st) != 0 and st[-1] < fnt): return False # else put into the stack. else: st.append(fnt) # while expected element are coming # from stack, pop them out. while (len(st) != 0 and st[-1] == expected): st.pop() expected += 1 # if the final expected element value is equal # to initial Queue size and the stack is empty. if (expected - 1 == n and len(st) == 0): return True return False # Driver Codeif __name__ == '__main__': q = Queue() q.put(5) q.put(1) q.put(2) q.put(3) q.put(4) n = q.qsize() if checkSorted(n, q): print(\"Yes\") else: print(\"No\") # This code is contributed by PranchalK",
"e": 33570,
"s": 32055,
"text": null
},
{
"code": "// C# Program to check if a queue// of first n natural number can// be sorted using a stackusing System;using System.Linq;using System.Collections.Generic; class GFG{ // Function to check if given // queue element can be sorted // into another queue using a stack. static bool checkSorted(int n, ref Queue<int> q) { Stack<int> st = new Stack<int>(); int expected = 1; int fnt; // while given Queue // is not empty. while (q.Count != 0) { fnt = q.Peek(); q.Dequeue(); // if front element is // the expected element if (fnt == expected) expected++; else { // if stack is empty, // push the element if (st.Count == 0) { st.Push(fnt); } // if top element is less than // element which need to be // pushed, then return false. else if (st.Count != 0 && st.Peek() < fnt) { return false; } // else push into the stack. else st.Push(fnt); } // while expected element are // coming from stack, pop them out. while (st.Count != 0 && st.Peek() == expected) { st.Pop(); expected++; } } // if the final expected element // value is equal to initial Queue // size and the stack is empty. if (expected - 1 == n && st.Count == 0) return true; return false; } // Driver Code static void Main() { Queue<int> q = new Queue<int>(); q.Enqueue(5); q.Enqueue(1); q.Enqueue(2); q.Enqueue(3); q.Enqueue(4); int n = q.Count; if (checkSorted(n, ref q)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 35792,
"s": 33570,
"text": null
},
{
"code": "<script> // Javascript Program to check if a queue // of first n natural number can // be sorted using a stack let q = []; // Function to check if given // queue element can be sorted // into another queue using a stack. function checkSorted(n) { let st = []; let expected = 1; let fnt; // while given Queue // is not empty. while (q.length != 0) { fnt = q[0]; q.shift(); // if front element is // the expected element if (fnt == expected) expected++; else { // if stack is empty, // push the element if (st.length == 0) { st.push(fnt); } // if top element is less than // element which need to be // pushed, then return false. else if (st.length != 0 && st[st.length - 1] < fnt) { return false; } // else push into the stack. else st.push(fnt); } // while expected element are // coming from stack, pop them out. while (st.length != 0 && st[st.length - 1] == expected) { st.pop(); expected++; } } // if the final expected element // value is equal to initial Queue // size and the stack is empty. if ((expected - 1) == n && st.length == 0) return true; return false; } q.push(5); q.push(1); q.push(2); q.push(3); q.push(4); let n = q.length; if (checkSorted(n)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by suresh07.</script>",
"e": 37779,
"s": 35792,
"text": null
},
{
"code": null,
"e": 37783,
"s": 37779,
"text": "Yes"
},
{
"code": null,
"e": 38077,
"s": 37785,
"text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fckxsNKtDUo\" 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": 38116,
"s": 38077,
"text": "Video Contributed by Parul Shandilya "
},
{
"code": null,
"e": 38128,
"s": 38116,
"text": "manishshaw1"
},
{
"code": null,
"e": 38143,
"s": 38128,
"text": "ParulShandilya"
},
{
"code": null,
"e": 38155,
"s": 38143,
"text": "abdulmohsin"
},
{
"code": null,
"e": 38171,
"s": 38155,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 38180,
"s": 38171,
"text": "18ucs102"
},
{
"code": null,
"e": 38189,
"s": 38180,
"text": "suresh07"
},
{
"code": null,
"e": 38202,
"s": 38189,
"text": "simmytarika5"
},
{
"code": null,
"e": 38218,
"s": 38202,
"text": "sundara mohan m"
},
{
"code": null,
"e": 38228,
"s": 38218,
"text": "gsouvik04"
},
{
"code": null,
"e": 38243,
"s": 38228,
"text": "notavacillator"
},
{
"code": null,
"e": 38249,
"s": 38243,
"text": "Queue"
},
{
"code": null,
"e": 38257,
"s": 38249,
"text": "Sorting"
},
{
"code": null,
"e": 38263,
"s": 38257,
"text": "Stack"
},
{
"code": null,
"e": 38269,
"s": 38263,
"text": "Stack"
},
{
"code": null,
"e": 38277,
"s": 38269,
"text": "Sorting"
},
{
"code": null,
"e": 38283,
"s": 38277,
"text": "Queue"
},
{
"code": null,
"e": 38381,
"s": 38283,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38435,
"s": 38381,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 38473,
"s": 38435,
"text": "Priority Queue | Set 1 (Introduction)"
},
{
"code": null,
"e": 38498,
"s": 38473,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 38533,
"s": 38498,
"text": "Queue - Linked List Implementation"
}
] |
Rotate digits of a given number by K - GeeksforGeeks | 29 Apr, 2021
Given two integers N and K, the task is to rotate the digits of N by K. If K is a positive integer, left rotate its digits. Otherwise, right rotate its digits.
Examples:
Input: N = 12345, K = 2Output: 34512 Explanation: Left rotating N(= 12345) by K(= 2) modifies N to 34512. Therefore, the required output is 34512
Input: N = 12345, K = -3Output: 34512 Explanation: Right rotating N(= 12345) by K( = -3) modifies N to 34512. Therefore, the required output is 34512
Approach: Follow the steps below to solve the problem:
Initialize a variable, say X, to store the count of digits in N.
Update K = (K + X) % X to reduce it to a case of left rotation.
Remove the first K digits of N and append all the removed digits to the right of the digits of N.
Finally, print the value of N.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the count of// digits in Nint numberOfDigit(int N){ // Stores count of // digits in N int digit = 0; // Calculate the count // of digits in N while (N > 0) { // Update digit digit++; // Update N N /= 10; } return digit;} // Function to rotate the digits of N by Kvoid rotateNumberByK(int N, int K){ // Stores count of digits in N int X = numberOfDigit(N); // Update K so that only need to // handle left rotation K = ((K % X) + X) % X; // Stores first K digits of N int left_no = N / (int)(pow(10, X - K)); // Remove first K digits of N N = N % (int)(pow(10, X - K)); // Stores count of digits in left_no int left_digit = numberOfDigit(left_no); // Append left_no to the right of // digits of N N = (N * (int)(pow(10, left_digit))) + left_no; cout << N;} // Driver codeint main(){ int N = 12345, K = 7; // Function Call rotateNumberByK(N, K); return 0;} // The code is contributed by Dharanendra L V
// Java program to implement// the above approach import java.io.*; class GFG { // Function to find the count of // digits in N static int numberOfDigit(int N) { // Stores count of // digits in N int digit = 0; // Calculate the count // of digits in N while (N > 0) { // Update digit digit++; // Update N N /= 10; } return digit; } // Function to rotate the digits of N by K static void rotateNumberByK(int N, int K) { // Stores count of digits in N int X = numberOfDigit(N); // Update K so that only need to // handle left rotation K = ((K % X) + X) % X; // Stores first K digits of N int left_no = N / (int)(Math.pow(10, X - K)); // Remove first K digits of N N = N % (int)(Math.pow(10, X - K)); // Stores count of digits in left_no int left_digit = numberOfDigit(left_no); // Append left_no to the right of // digits of N N = (N * (int)(Math.pow(10, left_digit))) + left_no; System.out.println(N); } // Driver Code public static void main(String args[]) { int N = 12345, K = 7; // Function Call rotateNumberByK(N, K); }}
# Python3 program to implement# the above approach # Function to find the count of# digits in Ndef numberOfDigit(N): # Stores count of # digits in N digit = 0 # Calculate the count # of digits in N while (N > 0): # Update digit digit += 1 # Update N N //= 10 return digit # Function to rotate the digits of N by Kdef rotateNumberByK(N, K): # Stores count of digits in N X = numberOfDigit(N) # Update K so that only need to # handle left rotation K = ((K % X) + X) % X # Stores first K digits of N left_no = N // pow(10, X - K) # Remove first K digits of N N = N % pow(10, X - K) # Stores count of digits in left_no left_digit = numberOfDigit(left_no) # Append left_no to the right of # digits of N N = N * pow(10, left_digit) + left_no print(N) # Driver Codeif __name__ == '__main__': N, K = 12345, 7 # Function Call rotateNumberByK(N, K) # This code is contributed by mohit kumar 29
// C# program to implement// the above approachusing System;class GFG{ // Function to find the count of // digits in N static int numberOfDigit(int N) { // Stores count of // digits in N int digit = 0; // Calculate the count // of digits in N while (N > 0) { // Update digit digit++; // Update N N /= 10; } return digit; } // Function to rotate the digits of N by K static void rotateNumberByK(int N, int K) { // Stores count of digits in N int X = numberOfDigit(N); // Update K so that only need to // handle left rotation K = ((K % X) + X) % X; // Stores first K digits of N int left_no = N / (int)(Math.Pow(10, X - K)); // Remove first K digits of N N = N % (int)(Math.Pow(10, X - K)); // Stores count of digits in left_no int left_digit = numberOfDigit(left_no); // Append left_no to the right of // digits of N N = (N * (int)(Math.Pow(10, left_digit))) + left_no; Console.WriteLine(N); } // Driver Code public static void Main(string []args) { int N = 12345, K = 7; // Function Call rotateNumberByK(N, K); }} // This code is contributed by AnkThon
<script>// Javascript program to implement// the above approach // Function to find the count of // digits in N function numberOfDigit(N) { // Stores count of // digits in N let digit = 0; // Calculate the count // of digits in N while (N > 0) { // Update digit digit++; // Update N N = Math.floor( N / 10); } return digit; } // Function to rotate the digits of N by K function rotateNumberByK(N, K) { // Stores count of digits in N let X = numberOfDigit(N); // Update K so that only need to // handle left rotation K = ((K % X) + X) % X; // Stores first K digits of N let left_no = Math.floor (N / Math.floor(Math.pow(10, X - K))); // Remove first K digits of N N = N % Math.floor(Math.pow(10, X - K)); // Stores count of digits in left_no let left_digit = numberOfDigit(left_no); // Append left_no to the right of // digits of N N = (N * Math.floor(Math.pow(10, left_digit))) + left_no; document.write(N); } // Driver Code let N = 12345, K = 7; // Function Call rotateNumberByK(N, K); // This code is contributed by souravghosh0416.</script>
34512
Time Complexity: O(log10N)Auxiliary Space: O(1)
mohit kumar 29
ankthon
dharanendralv23
souravghosh0416
number-digits
rotation
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 for factorial of a number
Print all possible combinations of r elements in a given array of size n
Program for Decimal to Binary Conversion
The Knight's tour problem | Backtracking-1
Operators in C / C++
Find minimum number of coins that make a given value
Program to find sum of elements in a given array | [
{
"code": null,
"e": 26671,
"s": 26643,
"text": "\n29 Apr, 2021"
},
{
"code": null,
"e": 26831,
"s": 26671,
"text": "Given two integers N and K, the task is to rotate the digits of N by K. If K is a positive integer, left rotate its digits. Otherwise, right rotate its digits."
},
{
"code": null,
"e": 26841,
"s": 26831,
"text": "Examples:"
},
{
"code": null,
"e": 26987,
"s": 26841,
"text": "Input: N = 12345, K = 2Output: 34512 Explanation: Left rotating N(= 12345) by K(= 2) modifies N to 34512. Therefore, the required output is 34512"
},
{
"code": null,
"e": 27137,
"s": 26987,
"text": "Input: N = 12345, K = -3Output: 34512 Explanation: Right rotating N(= 12345) by K( = -3) modifies N to 34512. Therefore, the required output is 34512"
},
{
"code": null,
"e": 27192,
"s": 27137,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27257,
"s": 27192,
"text": "Initialize a variable, say X, to store the count of digits in N."
},
{
"code": null,
"e": 27321,
"s": 27257,
"text": "Update K = (K + X) % X to reduce it to a case of left rotation."
},
{
"code": null,
"e": 27419,
"s": 27321,
"text": "Remove the first K digits of N and append all the removed digits to the right of the digits of N."
},
{
"code": null,
"e": 27450,
"s": 27419,
"text": "Finally, print the value of N."
},
{
"code": null,
"e": 27501,
"s": 27450,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27505,
"s": 27501,
"text": "C++"
},
{
"code": null,
"e": 27510,
"s": 27505,
"text": "Java"
},
{
"code": null,
"e": 27518,
"s": 27510,
"text": "Python3"
},
{
"code": null,
"e": 27521,
"s": 27518,
"text": "C#"
},
{
"code": null,
"e": 27532,
"s": 27521,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the count of// digits in Nint numberOfDigit(int N){ // Stores count of // digits in N int digit = 0; // Calculate the count // of digits in N while (N > 0) { // Update digit digit++; // Update N N /= 10; } return digit;} // Function to rotate the digits of N by Kvoid rotateNumberByK(int N, int K){ // Stores count of digits in N int X = numberOfDigit(N); // Update K so that only need to // handle left rotation K = ((K % X) + X) % X; // Stores first K digits of N int left_no = N / (int)(pow(10, X - K)); // Remove first K digits of N N = N % (int)(pow(10, X - K)); // Stores count of digits in left_no int left_digit = numberOfDigit(left_no); // Append left_no to the right of // digits of N N = (N * (int)(pow(10, left_digit))) + left_no; cout << N;} // Driver codeint main(){ int N = 12345, K = 7; // Function Call rotateNumberByK(N, K); return 0;} // The code is contributed by Dharanendra L V",
"e": 28666,
"s": 27532,
"text": null
},
{
"code": "// Java program to implement// the above approach import java.io.*; class GFG { // Function to find the count of // digits in N static int numberOfDigit(int N) { // Stores count of // digits in N int digit = 0; // Calculate the count // of digits in N while (N > 0) { // Update digit digit++; // Update N N /= 10; } return digit; } // Function to rotate the digits of N by K static void rotateNumberByK(int N, int K) { // Stores count of digits in N int X = numberOfDigit(N); // Update K so that only need to // handle left rotation K = ((K % X) + X) % X; // Stores first K digits of N int left_no = N / (int)(Math.pow(10, X - K)); // Remove first K digits of N N = N % (int)(Math.pow(10, X - K)); // Stores count of digits in left_no int left_digit = numberOfDigit(left_no); // Append left_no to the right of // digits of N N = (N * (int)(Math.pow(10, left_digit))) + left_no; System.out.println(N); } // Driver Code public static void main(String args[]) { int N = 12345, K = 7; // Function Call rotateNumberByK(N, K); }}",
"e": 30022,
"s": 28666,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to find the count of# digits in Ndef numberOfDigit(N): # Stores count of # digits in N digit = 0 # Calculate the count # of digits in N while (N > 0): # Update digit digit += 1 # Update N N //= 10 return digit # Function to rotate the digits of N by Kdef rotateNumberByK(N, K): # Stores count of digits in N X = numberOfDigit(N) # Update K so that only need to # handle left rotation K = ((K % X) + X) % X # Stores first K digits of N left_no = N // pow(10, X - K) # Remove first K digits of N N = N % pow(10, X - K) # Stores count of digits in left_no left_digit = numberOfDigit(left_no) # Append left_no to the right of # digits of N N = N * pow(10, left_digit) + left_no print(N) # Driver Codeif __name__ == '__main__': N, K = 12345, 7 # Function Call rotateNumberByK(N, K) # This code is contributed by mohit kumar 29",
"e": 31024,
"s": 30022,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ // Function to find the count of // digits in N static int numberOfDigit(int N) { // Stores count of // digits in N int digit = 0; // Calculate the count // of digits in N while (N > 0) { // Update digit digit++; // Update N N /= 10; } return digit; } // Function to rotate the digits of N by K static void rotateNumberByK(int N, int K) { // Stores count of digits in N int X = numberOfDigit(N); // Update K so that only need to // handle left rotation K = ((K % X) + X) % X; // Stores first K digits of N int left_no = N / (int)(Math.Pow(10, X - K)); // Remove first K digits of N N = N % (int)(Math.Pow(10, X - K)); // Stores count of digits in left_no int left_digit = numberOfDigit(left_no); // Append left_no to the right of // digits of N N = (N * (int)(Math.Pow(10, left_digit))) + left_no; Console.WriteLine(N); } // Driver Code public static void Main(string []args) { int N = 12345, K = 7; // Function Call rotateNumberByK(N, K); }} // This code is contributed by AnkThon",
"e": 32416,
"s": 31024,
"text": null
},
{
"code": "<script>// Javascript program to implement// the above approach // Function to find the count of // digits in N function numberOfDigit(N) { // Stores count of // digits in N let digit = 0; // Calculate the count // of digits in N while (N > 0) { // Update digit digit++; // Update N N = Math.floor( N / 10); } return digit; } // Function to rotate the digits of N by K function rotateNumberByK(N, K) { // Stores count of digits in N let X = numberOfDigit(N); // Update K so that only need to // handle left rotation K = ((K % X) + X) % X; // Stores first K digits of N let left_no = Math.floor (N / Math.floor(Math.pow(10, X - K))); // Remove first K digits of N N = N % Math.floor(Math.pow(10, X - K)); // Stores count of digits in left_no let left_digit = numberOfDigit(left_no); // Append left_no to the right of // digits of N N = (N * Math.floor(Math.pow(10, left_digit))) + left_no; document.write(N); } // Driver Code let N = 12345, K = 7; // Function Call rotateNumberByK(N, K); // This code is contributed by souravghosh0416.</script>",
"e": 33792,
"s": 32416,
"text": null
},
{
"code": null,
"e": 33798,
"s": 33792,
"text": "34512"
},
{
"code": null,
"e": 33848,
"s": 33800,
"text": "Time Complexity: O(log10N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33863,
"s": 33848,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33871,
"s": 33863,
"text": "ankthon"
},
{
"code": null,
"e": 33887,
"s": 33871,
"text": "dharanendralv23"
},
{
"code": null,
"e": 33903,
"s": 33887,
"text": "souravghosh0416"
},
{
"code": null,
"e": 33917,
"s": 33903,
"text": "number-digits"
},
{
"code": null,
"e": 33926,
"s": 33917,
"text": "rotation"
},
{
"code": null,
"e": 33939,
"s": 33926,
"text": "Mathematical"
},
{
"code": null,
"e": 33952,
"s": 33939,
"text": "Mathematical"
},
{
"code": null,
"e": 34050,
"s": 33952,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34074,
"s": 34050,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 34117,
"s": 34074,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 34131,
"s": 34117,
"text": "Prime Numbers"
},
{
"code": null,
"e": 34165,
"s": 34131,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 34238,
"s": 34165,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 34279,
"s": 34238,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 34322,
"s": 34279,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 34343,
"s": 34322,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 34396,
"s": 34343,
"text": "Find minimum number of coins that make a given value"
}
] |
Class getClassLoader() method in Java with Examples - GeeksforGeeks | 27 Jan, 2022
The getClassLoader() method of java.lang.Class class is used to get the classLoader of this entity. This entity can be a class, an array, an interface, etc. The method returns the classLoader of this entity.Syntax:
public ClassLoader getClassLoader()
Parameter: This method does not accept any parameter.Return Value: This method returns the ClassLoader of the entity.Below programs demonstrate the getClassLoader() method.Example 1:
Java
// Java program to demonstrate getClassLoader() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the classLoader of myClass // using getClassLoader() method System.out.println("ClassLoader of myClass: " + myClass.getClassLoader()); }}
Class represented by myClass: class Test
ClassLoader of myClass: sun.misc.Launcher$AppClassLoader@42a57993
Example 2:
Java
// Java program to demonstrate getClassLoader() method public class Test { class Arr { } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for Arr Class arrClass = Arr.class; // Get the classLoader of arrClass // using getClassLoader() method System.out.println("ClassLoader of arrClass: " + arrClass.getClassLoader()); }}
ClassLoader of arrClass: sun.misc.Launcher$AppClassLoader@42a57993
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getClassLoader–
adnanirshad158
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Internal Working of HashMap in Java
Comparator Interface in Java with Examples
Strings in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 25442,
"s": 25225,
"text": "The getClassLoader() method of java.lang.Class class is used to get the classLoader of this entity. This entity can be a class, an array, an interface, etc. The method returns the classLoader of this entity.Syntax: "
},
{
"code": null,
"e": 25478,
"s": 25442,
"text": "public ClassLoader getClassLoader()"
},
{
"code": null,
"e": 25662,
"s": 25478,
"text": "Parameter: This method does not accept any parameter.Return Value: This method returns the ClassLoader of the entity.Below programs demonstrate the getClassLoader() method.Example 1: "
},
{
"code": null,
"e": 25667,
"s": 25662,
"text": "Java"
},
{
"code": "// Java program to demonstrate getClassLoader() method public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the classLoader of myClass // using getClassLoader() method System.out.println(\"ClassLoader of myClass: \" + myClass.getClassLoader()); }}",
"e": 26228,
"s": 25667,
"text": null
},
{
"code": null,
"e": 26335,
"s": 26228,
"text": "Class represented by myClass: class Test\nClassLoader of myClass: sun.misc.Launcher$AppClassLoader@42a57993"
},
{
"code": null,
"e": 26349,
"s": 26337,
"text": "Example 2: "
},
{
"code": null,
"e": 26354,
"s": 26349,
"text": "Java"
},
{
"code": "// Java program to demonstrate getClassLoader() method public class Test { class Arr { } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for Arr Class arrClass = Arr.class; // Get the classLoader of arrClass // using getClassLoader() method System.out.println(\"ClassLoader of arrClass: \" + arrClass.getClassLoader()); }}",
"e": 26812,
"s": 26354,
"text": null
},
{
"code": null,
"e": 26879,
"s": 26812,
"text": "ClassLoader of arrClass: sun.misc.Launcher$AppClassLoader@42a57993"
},
{
"code": null,
"e": 26972,
"s": 26881,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getClassLoader– "
},
{
"code": null,
"e": 26987,
"s": 26972,
"text": "adnanirshad158"
},
{
"code": null,
"e": 27002,
"s": 26987,
"text": "Java-Functions"
},
{
"code": null,
"e": 27020,
"s": 27002,
"text": "Java-lang package"
},
{
"code": null,
"e": 27036,
"s": 27020,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 27041,
"s": 27036,
"text": "Java"
},
{
"code": null,
"e": 27046,
"s": 27041,
"text": "Java"
},
{
"code": null,
"e": 27144,
"s": 27046,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27159,
"s": 27144,
"text": "Stream In Java"
},
{
"code": null,
"e": 27180,
"s": 27159,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27199,
"s": 27180,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27229,
"s": 27199,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27275,
"s": 27229,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27292,
"s": 27275,
"text": "Generics in Java"
},
{
"code": null,
"e": 27313,
"s": 27292,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27349,
"s": 27313,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 27392,
"s": 27349,
"text": "Comparator Interface in Java with Examples"
}
] |
Convert numbers into binary representation and add them without carry - GeeksforGeeks | 29 Apr, 2021
Given two numbers N and M. The task to convert both the numbers in the binary form then add respective bits of both the binary converted numbers but with a given condition that there is not any carry system in this addition.
Input: N = 37, M = 12
Output: 41
Input: N = 456, M = 854
Output: 670
Approach:
If we don’t consider carry then the binary addition of two bits will be:
1 + 0 = 1
0 + 1 = 1
0 + 0 = 0
1 + 1 = 0 (No carry)
If you observe clearly you will notice that this is just bitwise XOR of two numbers.
Below is the implementation of the above approach
C++
Java
Python3
C#
Javascript
// C++ program to add two binary// number without carry#include<bits/stdc++.h>using namespace std; // Function returns sum of both// the binary number without// carryint NoCarrySum(int N, int M){ // XOR of N and M return N ^ M;} // Driver codeint main(){ int N = 37; int M = 12; cout << NoCarrySum(N, M); return 0;}
// Java program to add two binary// number without carryimport java.util.*; class GFG{ // Function returns sum of both// the binary number without// carrystatic int NoCarrySum(int N, int M){ // XOR of N and M return N ^ M;} // Driver codepublic static void main(String[] args){ int N = 37; int M = 12; System.out.print(NoCarrySum(N, M));}} // This code is contributed by amal kumar choubey
# Python3 program to add two binary# number without carry # Function returns sum of both# the binary number without# carrydef NoCarrySum(N, M): # XOR of N and M return N ^ M # Driver codeN = 37M = 12print(NoCarrySum(N, M)) # This code is contributed by sayesha
// C# program to add two binary// number without carryusing System; class GFG{ // Function returns sum of both// the binary number without// carrystatic int NoCarrySum(int N, int M){ // XOR of N and M return N ^ M;} // Driver codestatic public void Main(String[] args){ int N = 37; int M = 12; Console.Write(NoCarrySum(N, M));}} // This code is contributed by Rajput-Ji
<script> // Javascript program to add two binary// number without carry // Function returns sum of both// the binary number without// carryfunction NoCarrySum(N, M){ // XOR of N and M return N ^ M;} // Driver code let N = 37; let M = 12; document.write(NoCarrySum(N, M)); </script>
41
Amal Kumar Choubey
Rajput-Ji
subhammahato348
Bitwise-XOR
Articles
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Docker - COPY Instruction
Time complexities of different data structures
Difference between Class and Object
SQL | Date functions
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable? | [
{
"code": null,
"e": 25743,
"s": 25715,
"text": "\n29 Apr, 2021"
},
{
"code": null,
"e": 25970,
"s": 25743,
"text": "Given two numbers N and M. The task to convert both the numbers in the binary form then add respective bits of both the binary converted numbers but with a given condition that there is not any carry system in this addition. "
},
{
"code": null,
"e": 26040,
"s": 25970,
"text": "Input: N = 37, M = 12\nOutput: 41\n\nInput: N = 456, M = 854\nOutput: 670"
},
{
"code": null,
"e": 26054,
"s": 26042,
"text": "Approach: "
},
{
"code": null,
"e": 26129,
"s": 26054,
"text": "If we don’t consider carry then the binary addition of two bits will be: "
},
{
"code": null,
"e": 26196,
"s": 26129,
"text": " 1 + 0 = 1\n 0 + 1 = 1\n 0 + 0 = 0\n 1 + 1 = 0 (No carry)"
},
{
"code": null,
"e": 26283,
"s": 26196,
"text": "If you observe clearly you will notice that this is just bitwise XOR of two numbers. "
},
{
"code": null,
"e": 26335,
"s": 26283,
"text": "Below is the implementation of the above approach "
},
{
"code": null,
"e": 26339,
"s": 26335,
"text": "C++"
},
{
"code": null,
"e": 26344,
"s": 26339,
"text": "Java"
},
{
"code": null,
"e": 26352,
"s": 26344,
"text": "Python3"
},
{
"code": null,
"e": 26355,
"s": 26352,
"text": "C#"
},
{
"code": null,
"e": 26366,
"s": 26355,
"text": "Javascript"
},
{
"code": "// C++ program to add two binary// number without carry#include<bits/stdc++.h>using namespace std; // Function returns sum of both// the binary number without// carryint NoCarrySum(int N, int M){ // XOR of N and M return N ^ M;} // Driver codeint main(){ int N = 37; int M = 12; cout << NoCarrySum(N, M); return 0;}",
"e": 26709,
"s": 26366,
"text": null
},
{
"code": "// Java program to add two binary// number without carryimport java.util.*; class GFG{ // Function returns sum of both// the binary number without// carrystatic int NoCarrySum(int N, int M){ // XOR of N and M return N ^ M;} // Driver codepublic static void main(String[] args){ int N = 37; int M = 12; System.out.print(NoCarrySum(N, M));}} // This code is contributed by amal kumar choubey",
"e": 27118,
"s": 26709,
"text": null
},
{
"code": "# Python3 program to add two binary# number without carry # Function returns sum of both# the binary number without# carrydef NoCarrySum(N, M): # XOR of N and M return N ^ M # Driver codeN = 37M = 12print(NoCarrySum(N, M)) # This code is contributed by sayesha",
"e": 27386,
"s": 27118,
"text": null
},
{
"code": "// C# program to add two binary// number without carryusing System; class GFG{ // Function returns sum of both// the binary number without// carrystatic int NoCarrySum(int N, int M){ // XOR of N and M return N ^ M;} // Driver codestatic public void Main(String[] args){ int N = 37; int M = 12; Console.Write(NoCarrySum(N, M));}} // This code is contributed by Rajput-Ji",
"e": 27780,
"s": 27386,
"text": null
},
{
"code": "<script> // Javascript program to add two binary// number without carry // Function returns sum of both// the binary number without// carryfunction NoCarrySum(N, M){ // XOR of N and M return N ^ M;} // Driver code let N = 37; let M = 12; document.write(NoCarrySum(N, M)); </script>",
"e": 28086,
"s": 27780,
"text": null
},
{
"code": null,
"e": 28089,
"s": 28086,
"text": "41"
},
{
"code": null,
"e": 28110,
"s": 28091,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 28120,
"s": 28110,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 28136,
"s": 28120,
"text": "subhammahato348"
},
{
"code": null,
"e": 28148,
"s": 28136,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 28157,
"s": 28148,
"text": "Articles"
},
{
"code": null,
"e": 28167,
"s": 28157,
"text": "Bit Magic"
},
{
"code": null,
"e": 28177,
"s": 28167,
"text": "Bit Magic"
},
{
"code": null,
"e": 28275,
"s": 28177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28312,
"s": 28275,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 28338,
"s": 28312,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 28385,
"s": 28338,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 28421,
"s": 28385,
"text": "Difference between Class and Object"
},
{
"code": null,
"e": 28442,
"s": 28421,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 28469,
"s": 28442,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 28515,
"s": 28469,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 28583,
"s": 28515,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 28612,
"s": 28583,
"text": "Count set bits in an integer"
}
] |
How to get form input value using AngularJS ? - GeeksforGeeks | 01 Oct, 2020
Given a form element and the task is to get the form values input by the user with the help of AngularJS.
Approach:
We are storing the data in the JSON object after the user enters it in the input element with the help of the Angular.copy(object) method.
After that, data from the JSON object can be accessed easily.
Example 1: In this example, the data is stored in the JSON object and accessed from it.
HTML
<!DOCTYPE HTML><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.userData = ''; $scope.getData = function (user) { $scope.userData = angular.copy(user); }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to get form input value in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> <form action="javascript:void(0)"> firstName: <input type="text" ng-model="user.fName" /><br> lastName : <input type="text" ng-model="user.lName" /><br> <br> <button ng-click="getData(user)"> SAVE </button> </form> <p>FirstName = {{userData.fName}}</p> <p>lastName = {{userData.lName}}</p> </div> </div></body> </html>
Output:
Example 2: In this example, the data is stored in the JSON object and the JSON object’s data is printed.
HTML
<!DOCTYPE HTML><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.userData = ''; $scope.getData = function (user) { $scope.userData = angular.copy(user); }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to get form input value in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> <form action="javascript:void(0)"> firstName: <input type="text" ng-model="user.fName" /> <br> lastName : <input type="text" ng-model="user.lName" /> <br> Ph.No.: <input type="text" ng-model="user.Phone" /> <br> City: <input type="text" ng-model="user.city" /> <br> <button ng-click="getData(user)"> SAVE </button> </form> <p>User Data Json = {{userData | json}}</p> </div> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
AngularJS-Misc
HTML-Misc
AngularJS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Auth Guards in Angular 9/10/11
Angular PrimeNG Calendar Component
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 26254,
"s": 26226,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 26360,
"s": 26254,
"text": "Given a form element and the task is to get the form values input by the user with the help of AngularJS."
},
{
"code": null,
"e": 26371,
"s": 26360,
"text": "Approach: "
},
{
"code": null,
"e": 26511,
"s": 26371,
"text": "We are storing the data in the JSON object after the user enters it in the input element with the help of the Angular.copy(object) method. "
},
{
"code": null,
"e": 26573,
"s": 26511,
"text": "After that, data from the JSON object can be accessed easily."
},
{
"code": null,
"e": 26661,
"s": 26573,
"text": "Example 1: In this example, the data is stored in the JSON object and accessed from it."
},
{
"code": null,
"e": 26666,
"s": 26661,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.userData = ''; $scope.getData = function (user) { $scope.userData = angular.copy(user); }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to get form input value in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> <form action=\"javascript:void(0)\"> firstName: <input type=\"text\" ng-model=\"user.fName\" /><br> lastName : <input type=\"text\" ng-model=\"user.lName\" /><br> <br> <button ng-click=\"getData(user)\"> SAVE </button> </form> <p>FirstName = {{userData.fName}}</p> <p>lastName = {{userData.lName}}</p> </div> </div></body> </html>",
"e": 27833,
"s": 26666,
"text": null
},
{
"code": null,
"e": 27841,
"s": 27833,
"text": "Output:"
},
{
"code": null,
"e": 27947,
"s": 27841,
"text": "Example 2: In this example, the data is stored in the JSON object and the JSON object’s data is printed. "
},
{
"code": null,
"e": 27952,
"s": 27947,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.userData = ''; $scope.getData = function (user) { $scope.userData = angular.copy(user); }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to get form input value in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> <form action=\"javascript:void(0)\"> firstName: <input type=\"text\" ng-model=\"user.fName\" /> <br> lastName : <input type=\"text\" ng-model=\"user.lName\" /> <br> Ph.No.: <input type=\"text\" ng-model=\"user.Phone\" /> <br> City: <input type=\"text\" ng-model=\"user.city\" /> <br> <button ng-click=\"getData(user)\"> SAVE </button> </form> <p>User Data Json = {{userData | json}}</p> </div> </div></body> </html>",
"e": 29304,
"s": 27952,
"text": null
},
{
"code": null,
"e": 29312,
"s": 29304,
"text": "Output:"
},
{
"code": null,
"e": 29449,
"s": 29312,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 29464,
"s": 29449,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 29474,
"s": 29464,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29484,
"s": 29474,
"text": "AngularJS"
},
{
"code": null,
"e": 29489,
"s": 29484,
"text": "HTML"
},
{
"code": null,
"e": 29506,
"s": 29489,
"text": "Web Technologies"
},
{
"code": null,
"e": 29511,
"s": 29506,
"text": "HTML"
},
{
"code": null,
"e": 29609,
"s": 29511,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29644,
"s": 29609,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 29675,
"s": 29644,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 29710,
"s": 29675,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 29755,
"s": 29710,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 29797,
"s": 29755,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 29847,
"s": 29797,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29909,
"s": 29847,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29957,
"s": 29909,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 30017,
"s": 29957,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Python - Data visualization using Bokeh - GeeksforGeeks | 23 Jun, 2020
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots. Bokeh output can be obtained in various mediums like notebook, html and server. It is possible to embed bokeh plots in Django and flask apps.Bokeh provides two visualization interfaces to users:
bokeh.models : A low level interface that provides high flexibility to application developers.bokeh.plotting : A high level interface for creating visual glyphs.
To install bokeh package, run the following command in the terminal:
pip install bokeh
The dataset used for generating bokeh graphs is collected from Kaggle.
Code #1: Scatter MarkersTo create scatter circle markers, circle() method is used.
# import modulesfrom bokeh.plotting import figure, output_notebook, show # output to notebookoutput_notebook() # create figurep = figure(plot_width = 400, plot_height = 400) # add a circle renderer with# size, color and alphap.circle([1, 2, 3, 4, 5], [4, 7, 1, 6, 3], size = 10, color = "navy", alpha = 0.5) # show the resultsshow(p)
Output :
Code #2: Single lineTo create a single line, line() method is used.
# import modulesfrom bokeh.plotting import figure, output_notebook, show # output to notebookoutput_notebook() # create figurep = figure(plot_width = 400, plot_height = 400) # add a line rendererp.line([1, 2, 3, 4, 5], [3, 1, 2, 6, 5], line_width = 2, color = "green") # show the resultsshow(p)
Output :
Code #3: Bar ChartBar chart presents categorical data with rectangular bars. The length of the bar is proportional to the values that are represented.
# import necessary modulesimport pandas as pdfrom bokeh.charts import Bar, output_notebook, show # output to notebookoutput_notebook() # read data in dataframedf = pd.read_csv(r"D:/kaggle/mcdonald/menu.csv") # create barp = Bar(df, "Category", values = "Calories", title = "Total Calories by Category", legend = "top_right") # show the resultsshow(p)
Output :
Code #4: Box PlotBox plot is used to represent statistical data on a plot. It helps to summarize statistical properties of various data groups present in the data.
# import necessary modulesfrom bokeh.charts import BoxPlot, output_notebook, showimport pandas as pd # output to notebookoutput_notebook() # read data in dataframedf = pd.read_csv(r"D:/kaggle / mcdonald / menu.csv") # create barp = BoxPlot(df, values = "Protein", label = "Category", color = "yellow", title = "Protein Summary (grouped by category)", legend = "top_right") # show the resultsshow(p)
Output :
Code #5: HistogramHistogram is used to represent distribution of numerical data. The height of a rectangle in a histogram is proportional to the frequency of values in a class interval.
# import necessary modulesfrom bokeh.charts import Histogram, output_notebook, showimport pandas as pd # output to notebookoutput_notebook() # read data in dataframedf = pd.read_csv(r"D:/kaggle / mcdonald / menu.csv") # create histogramp = Histogram(df, values = "Total Fat", title = "Total Fat Distribution", color = "navy") # show the resultsshow(p)
Output :
Code #6: Scatter plotScatter plot is used to plot values of two variables in a dataset. It helps to find correlation among the two variables that are selected.
# import necessary modulesfrom bokeh.charts import Scatter, output_notebook, showimport pandas as pd # output to notebookoutput_notebook() # read data in dataframedf = pd.read_csv(r"D:/kaggle / mcdonald / menu.csv") # create scatter plotp = Scatter(df, x = "Carbohydrates", y = "Saturated Fat", title = "Saturated Fat vs Carbohydrates", xlabel = "Carbohydrates", ylabel = "Saturated Fat", color = "orange") # show the resultsshow(p)
Output :References: https://bokeh.pydata.org/en/latest/
python-modules
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": 26149,
"s": 26121,
"text": "\n23 Jun, 2020"
},
{
"code": null,
"e": 26453,
"s": 26149,
"text": "Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots. Bokeh output can be obtained in various mediums like notebook, html and server. It is possible to embed bokeh plots in Django and flask apps.Bokeh provides two visualization interfaces to users:"
},
{
"code": null,
"e": 26615,
"s": 26453,
"text": "bokeh.models : A low level interface that provides high flexibility to application developers.bokeh.plotting : A high level interface for creating visual glyphs."
},
{
"code": null,
"e": 26684,
"s": 26615,
"text": "To install bokeh package, run the following command in the terminal:"
},
{
"code": null,
"e": 26702,
"s": 26684,
"text": "pip install bokeh"
},
{
"code": null,
"e": 26773,
"s": 26702,
"text": "The dataset used for generating bokeh graphs is collected from Kaggle."
},
{
"code": null,
"e": 26856,
"s": 26773,
"text": "Code #1: Scatter MarkersTo create scatter circle markers, circle() method is used."
},
{
"code": "# import modulesfrom bokeh.plotting import figure, output_notebook, show # output to notebookoutput_notebook() # create figurep = figure(plot_width = 400, plot_height = 400) # add a circle renderer with# size, color and alphap.circle([1, 2, 3, 4, 5], [4, 7, 1, 6, 3], size = 10, color = \"navy\", alpha = 0.5) # show the resultsshow(p) ",
"e": 27204,
"s": 26856,
"text": null
},
{
"code": null,
"e": 27213,
"s": 27204,
"text": "Output :"
},
{
"code": null,
"e": 27281,
"s": 27213,
"text": "Code #2: Single lineTo create a single line, line() method is used."
},
{
"code": "# import modulesfrom bokeh.plotting import figure, output_notebook, show # output to notebookoutput_notebook() # create figurep = figure(plot_width = 400, plot_height = 400) # add a line rendererp.line([1, 2, 3, 4, 5], [3, 1, 2, 6, 5], line_width = 2, color = \"green\") # show the resultsshow(p)",
"e": 27589,
"s": 27281,
"text": null
},
{
"code": null,
"e": 27598,
"s": 27589,
"text": "Output :"
},
{
"code": null,
"e": 27749,
"s": 27598,
"text": "Code #3: Bar ChartBar chart presents categorical data with rectangular bars. The length of the bar is proportional to the values that are represented."
},
{
"code": "# import necessary modulesimport pandas as pdfrom bokeh.charts import Bar, output_notebook, show # output to notebookoutput_notebook() # read data in dataframedf = pd.read_csv(r\"D:/kaggle/mcdonald/menu.csv\") # create barp = Bar(df, \"Category\", values = \"Calories\", title = \"Total Calories by Category\", legend = \"top_right\") # show the resultsshow(p)",
"e": 28135,
"s": 27749,
"text": null
},
{
"code": null,
"e": 28144,
"s": 28135,
"text": "Output :"
},
{
"code": null,
"e": 28308,
"s": 28144,
"text": "Code #4: Box PlotBox plot is used to represent statistical data on a plot. It helps to summarize statistical properties of various data groups present in the data."
},
{
"code": "# import necessary modulesfrom bokeh.charts import BoxPlot, output_notebook, showimport pandas as pd # output to notebookoutput_notebook() # read data in dataframedf = pd.read_csv(r\"D:/kaggle / mcdonald / menu.csv\") # create barp = BoxPlot(df, values = \"Protein\", label = \"Category\", color = \"yellow\", title = \"Protein Summary (grouped by category)\", legend = \"top_right\") # show the resultsshow(p)",
"e": 28735,
"s": 28308,
"text": null
},
{
"code": null,
"e": 28744,
"s": 28735,
"text": "Output :"
},
{
"code": null,
"e": 28930,
"s": 28744,
"text": "Code #5: HistogramHistogram is used to represent distribution of numerical data. The height of a rectangle in a histogram is proportional to the frequency of values in a class interval."
},
{
"code": "# import necessary modulesfrom bokeh.charts import Histogram, output_notebook, showimport pandas as pd # output to notebookoutput_notebook() # read data in dataframedf = pd.read_csv(r\"D:/kaggle / mcdonald / menu.csv\") # create histogramp = Histogram(df, values = \"Total Fat\", title = \"Total Fat Distribution\", color = \"navy\") # show the resultsshow(p) ",
"e": 29316,
"s": 28930,
"text": null
},
{
"code": null,
"e": 29325,
"s": 29316,
"text": "Output :"
},
{
"code": null,
"e": 29485,
"s": 29325,
"text": "Code #6: Scatter plotScatter plot is used to plot values of two variables in a dataset. It helps to find correlation among the two variables that are selected."
},
{
"code": "# import necessary modulesfrom bokeh.charts import Scatter, output_notebook, showimport pandas as pd # output to notebookoutput_notebook() # read data in dataframedf = pd.read_csv(r\"D:/kaggle / mcdonald / menu.csv\") # create scatter plotp = Scatter(df, x = \"Carbohydrates\", y = \"Saturated Fat\", title = \"Saturated Fat vs Carbohydrates\", xlabel = \"Carbohydrates\", ylabel = \"Saturated Fat\", color = \"orange\") # show the resultsshow(p) ",
"e": 29957,
"s": 29485,
"text": null
},
{
"code": null,
"e": 30013,
"s": 29957,
"text": "Output :References: https://bokeh.pydata.org/en/latest/"
},
{
"code": null,
"e": 30028,
"s": 30013,
"text": "python-modules"
},
{
"code": null,
"e": 30035,
"s": 30028,
"text": "Python"
},
{
"code": null,
"e": 30133,
"s": 30035,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30151,
"s": 30133,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30186,
"s": 30151,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30218,
"s": 30186,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30240,
"s": 30218,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30282,
"s": 30240,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30312,
"s": 30282,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 30338,
"s": 30312,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30367,
"s": 30338,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30411,
"s": 30367,
"text": "Reading and Writing to text files in Python"
}
] |
Add two bit strings - GeeksforGeeks | 23 Feb, 2022
Given two bit sequences as strings, write a function to return the addition of the two sequences. Bit strings can be of different lengths also. For example, if string 1 is “1100011” and second string 2 is “10”, then the function should return “1100101”.
Since the sizes of two strings may be different, we first make the size of a smaller string equal to that of the bigger string by adding leading 0s. After making sizes the same, we one by one add bits from rightmost bit to leftmost bit. In every iteration, we need to sum 3 bits: 2 bits of 2 given strings and carry. The sum bit will be 1 if, either all of the 3 bits are set or one of them is set. So we can do XOR of all bits to find the sum bit. How to find carry – carry will be 1 if any of the two bits is set. So we can find carry by taking OR of all pairs. Following is step by step algorithm.1. Make them equal sized by adding 0s at the beginning of smaller string. 2. Perform bit addition .....Boolean expression for adding 3 bits a, b, c .....Sum = a XOR b XOR c .....Carry = (a AND b) OR ( b AND c ) OR ( c AND a )Following is implementation of the above algorithm.
C++
Java
Python3
C#
#include <iostream>using namespace std; //adds the two-bit strings and return the resultstring addBitStrings( string first, string second ); // Helper method: given two unequal sized bit strings, converts them to// same length by adding leading 0s in the smaller string. Returns the// new lengthint makeEqualLength(string &str1, string &str2){ int len1 = str1.size(); int len2 = str2.size(); if (len1 < len2) { for (int i = 0 ; i < len2 - len1 ; i++) str1 = '0' + str1; return len2; } else if (len1 > len2) { for (int i = 0 ; i < len1 - len2 ; i++) str2 = '0' + str2; } return len1; // If len1 >= len2} // The main function that adds two-bit sequences and returns the additionstring addBitStrings( string first, string second ){ string result; // To store the sum bits // make the lengths same before adding int length = makeEqualLength(first, second); int carry = 0; // Initialize carry // Add all bits one by one for (int i = length-1 ; i >= 0 ; i--) { int firstBit = first.at(i) - '0'; int secondBit = second.at(i) - '0'; // boolean expression for sum of 3 bits int sum = (firstBit ^ secondBit ^ carry)+'0'; result = (char)sum + result; // boolean expression for 3-bit addition carry = (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry); } // if overflow, then add a leading 1 if (carry) result = '1' + result; return result;} // Driver program to test above functionsint main(){ string str1 = "1100011"; string str2 = "10"; cout << "Sum is " << addBitStrings(str1, str2); return 0;}
// Java implementation of above algorithmclass GFG{ // Helper method: given two unequal sized bit strings, // converts them to same length by adding leading 0s // in the smaller string. Returns the new length // Using StringBuilder as Java only uses call by value static int makeEqualLength(StringBuilder str1, StringBuilder str2) { int len1 = str1.length(); int len2 = str2.length(); if (len1 < len2) { for (int i = 0; i < len2 - len1; i++) str1.insert(0, '0'); return len2; } else if (len1 > len2) { for (int i = 0; i < len1 - len2; i++) str2.insert(0, '0'); } return len1; // If len1 >= len2 } // The main function that adds two-bit sequences // and returns the addition static String addBitStrings(StringBuilder str1, StringBuilder str2) { String result = ""; // To store the sum bits // make the lengths same before adding int length = makeEqualLength(str1, str2); // Convert StringBuilder to Strings String first = str1.toString(); String second = str2.toString(); int carry = 0; // Initialize carry // Add all bits one by one for (int i = length - 1; i >= 0; i--) { int firstBit = first.charAt(i) - '0'; int secondBit = second.charAt(i) - '0'; // boolean expression for sum of 3 bits int sum = (firstBit ^ secondBit ^ carry) + '0'; result = String.valueOf((char) sum) + result; // boolean expression for 3-bit addition carry = (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry); } // if overflow, then add a leading 1 if (carry == 1) result = "1" + result; return result; } // Driver Code public static void main(String[] args) { String str1 = "1100011"; String str2 = "10"; System.out.println("Sum is " + addBitStrings(new StringBuilder(str1), new StringBuilder(str2))); }} // This code is contributed by Vivek Kumar Singh
# Python3 program for above approach # adds the two-bit strings and return the result # Helper method: given two unequal sized bit strings,# converts them to same length by adding leading 0s# in the smaller string. Returns the new lengthdef makeEqualLength(str1, str2): len1 = len(str1) # Length of string 1 len2 = len(str2) # length of string 2 if len1 < len2: str1 = (len2 - len1) * '0' + str1 len1 = len2 elif len2 < len1: str2 = (len1 - len2) * '0' + str2 len2 = len1 return len1, str1, str2 def addBitStrings( first, second ): result = '' # To store the sum bits # make the lengths same before adding length, first, second = makeEqualLength(first, second) carry = 0 # initialize carry as 0 # Add all bits one by one for i in range(length - 1, -1, -1): firstBit = int(first[i]) secondBit = int(second[i]) # boolean expression for sum of 3 bits sum = (firstBit ^ secondBit ^ carry) + 48 result = chr(sum) + result # boolean expression for 3 bits addition carry = (firstBit & secondBit) | \ (secondBit & carry) | \ (firstBit & carry) # if overflow, then add a leading 1 if carry == 1: result = '1' + result return result # Driver Codeif __name__ == '__main__': str1 = '1100011' str2 = '10' print('Sum is', addBitStrings(str1, str2)) # This code is contributed by# chaudhary_19 (Mayank Chaudhary)
// C# implementation of above algorithmusing System;using System.Text; class GFG{ // Helper method: given two unequal sized // bit strings, converts them to same length // by adding leading 0s in the smaller string. // Returns the new length Using StringBuilder // as Java only uses call by value static int makeEqualLength(StringBuilder str1, StringBuilder str2) { int len1 = str1.Length; int len2 = str2.Length; if (len1 < len2) { for (int i = 0; i < len2 - len1; i++) { str1.Insert(0, '0'); } return len2; } else if (len1 > len2) { for (int i = 0; i < len1 - len2; i++) { str2.Insert(0, '0'); } } return len1; // If len1 >= len2 } // The main function that adds two-bit sequences // and returns the addition static string addBitStrings(StringBuilder str1, StringBuilder str2) { string result = ""; // To store the sum bits // make the lengths same before adding int length = makeEqualLength(str1, str2); // Convert StringBuilder to Strings string first = str1.ToString(); string second = str2.ToString(); int carry = 0; // Initialize carry // Add all bits one by one for (int i = length - 1; i >= 0; i--) { int firstBit = first[i] - '0'; int secondBit = second[i] - '0'; // boolean expression for sum of 3 bits int sum = (firstBit ^ secondBit ^ carry) + '0'; result = ((char) sum).ToString() + result; // boolean expression for 3-bit addition carry = (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry); } // if overflow, then add a leading 1 if (carry == 1) { result = "1" + result; } return result; } // Driver Code public static void Main(string[] args) { string str1 = "1100011"; string str2 = "10"; Console.WriteLine("Sum is " + addBitStrings(new StringBuilder(str1), new StringBuilder(str2))); }} // This code is contributed by kumar65
Output:
Sum is 1100101
Time Complexity: O(|str1|)
Auxiliary Space: O(1)This article is compiled by Ravi Chandra Enaganti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
Vivekkumar Singh
chaudhary_19
kumar65
subham348
surinderdawra388
binary-representation
binary-string
Bitwise-XOR
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Bit Tricks for Competitive Programming
Write an Efficient Method to Check if a Number is Multiple of 3
Check for Integer Overflow
Convert decimal fraction to binary number
Reverse actual bits of the given number
Builtin functions of GCC compiler
Hamming code Implementation in C/C++
Check if a Number is Odd or Even using Bitwise Operators | [
{
"code": null,
"e": 24934,
"s": 24906,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 25190,
"s": 24934,
"text": "Given two bit sequences as strings, write a function to return the addition of the two sequences. Bit strings can be of different lengths also. For example, if string 1 is “1100011” and second string 2 is “10”, then the function should return “1100101”. "
},
{
"code": null,
"e": 26068,
"s": 25190,
"text": "Since the sizes of two strings may be different, we first make the size of a smaller string equal to that of the bigger string by adding leading 0s. After making sizes the same, we one by one add bits from rightmost bit to leftmost bit. In every iteration, we need to sum 3 bits: 2 bits of 2 given strings and carry. The sum bit will be 1 if, either all of the 3 bits are set or one of them is set. So we can do XOR of all bits to find the sum bit. How to find carry – carry will be 1 if any of the two bits is set. So we can find carry by taking OR of all pairs. Following is step by step algorithm.1. Make them equal sized by adding 0s at the beginning of smaller string. 2. Perform bit addition .....Boolean expression for adding 3 bits a, b, c .....Sum = a XOR b XOR c .....Carry = (a AND b) OR ( b AND c ) OR ( c AND a )Following is implementation of the above algorithm. "
},
{
"code": null,
"e": 26072,
"s": 26068,
"text": "C++"
},
{
"code": null,
"e": 26077,
"s": 26072,
"text": "Java"
},
{
"code": null,
"e": 26085,
"s": 26077,
"text": "Python3"
},
{
"code": null,
"e": 26088,
"s": 26085,
"text": "C#"
},
{
"code": "#include <iostream>using namespace std; //adds the two-bit strings and return the resultstring addBitStrings( string first, string second ); // Helper method: given two unequal sized bit strings, converts them to// same length by adding leading 0s in the smaller string. Returns the// new lengthint makeEqualLength(string &str1, string &str2){ int len1 = str1.size(); int len2 = str2.size(); if (len1 < len2) { for (int i = 0 ; i < len2 - len1 ; i++) str1 = '0' + str1; return len2; } else if (len1 > len2) { for (int i = 0 ; i < len1 - len2 ; i++) str2 = '0' + str2; } return len1; // If len1 >= len2} // The main function that adds two-bit sequences and returns the additionstring addBitStrings( string first, string second ){ string result; // To store the sum bits // make the lengths same before adding int length = makeEqualLength(first, second); int carry = 0; // Initialize carry // Add all bits one by one for (int i = length-1 ; i >= 0 ; i--) { int firstBit = first.at(i) - '0'; int secondBit = second.at(i) - '0'; // boolean expression for sum of 3 bits int sum = (firstBit ^ secondBit ^ carry)+'0'; result = (char)sum + result; // boolean expression for 3-bit addition carry = (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry); } // if overflow, then add a leading 1 if (carry) result = '1' + result; return result;} // Driver program to test above functionsint main(){ string str1 = \"1100011\"; string str2 = \"10\"; cout << \"Sum is \" << addBitStrings(str1, str2); return 0;}",
"e": 27773,
"s": 26088,
"text": null
},
{
"code": "// Java implementation of above algorithmclass GFG{ // Helper method: given two unequal sized bit strings, // converts them to same length by adding leading 0s // in the smaller string. Returns the new length // Using StringBuilder as Java only uses call by value static int makeEqualLength(StringBuilder str1, StringBuilder str2) { int len1 = str1.length(); int len2 = str2.length(); if (len1 < len2) { for (int i = 0; i < len2 - len1; i++) str1.insert(0, '0'); return len2; } else if (len1 > len2) { for (int i = 0; i < len1 - len2; i++) str2.insert(0, '0'); } return len1; // If len1 >= len2 } // The main function that adds two-bit sequences // and returns the addition static String addBitStrings(StringBuilder str1, StringBuilder str2) { String result = \"\"; // To store the sum bits // make the lengths same before adding int length = makeEqualLength(str1, str2); // Convert StringBuilder to Strings String first = str1.toString(); String second = str2.toString(); int carry = 0; // Initialize carry // Add all bits one by one for (int i = length - 1; i >= 0; i--) { int firstBit = first.charAt(i) - '0'; int secondBit = second.charAt(i) - '0'; // boolean expression for sum of 3 bits int sum = (firstBit ^ secondBit ^ carry) + '0'; result = String.valueOf((char) sum) + result; // boolean expression for 3-bit addition carry = (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry); } // if overflow, then add a leading 1 if (carry == 1) result = \"1\" + result; return result; } // Driver Code public static void main(String[] args) { String str1 = \"1100011\"; String str2 = \"10\"; System.out.println(\"Sum is \" + addBitStrings(new StringBuilder(str1), new StringBuilder(str2))); }} // This code is contributed by Vivek Kumar Singh",
"e": 30047,
"s": 27773,
"text": null
},
{
"code": "# Python3 program for above approach # adds the two-bit strings and return the result # Helper method: given two unequal sized bit strings,# converts them to same length by adding leading 0s# in the smaller string. Returns the new lengthdef makeEqualLength(str1, str2): len1 = len(str1) # Length of string 1 len2 = len(str2) # length of string 2 if len1 < len2: str1 = (len2 - len1) * '0' + str1 len1 = len2 elif len2 < len1: str2 = (len1 - len2) * '0' + str2 len2 = len1 return len1, str1, str2 def addBitStrings( first, second ): result = '' # To store the sum bits # make the lengths same before adding length, first, second = makeEqualLength(first, second) carry = 0 # initialize carry as 0 # Add all bits one by one for i in range(length - 1, -1, -1): firstBit = int(first[i]) secondBit = int(second[i]) # boolean expression for sum of 3 bits sum = (firstBit ^ secondBit ^ carry) + 48 result = chr(sum) + result # boolean expression for 3 bits addition carry = (firstBit & secondBit) | \\ (secondBit & carry) | \\ (firstBit & carry) # if overflow, then add a leading 1 if carry == 1: result = '1' + result return result # Driver Codeif __name__ == '__main__': str1 = '1100011' str2 = '10' print('Sum is', addBitStrings(str1, str2)) # This code is contributed by# chaudhary_19 (Mayank Chaudhary)",
"e": 31533,
"s": 30047,
"text": null
},
{
"code": "// C# implementation of above algorithmusing System;using System.Text; class GFG{ // Helper method: given two unequal sized // bit strings, converts them to same length // by adding leading 0s in the smaller string. // Returns the new length Using StringBuilder // as Java only uses call by value static int makeEqualLength(StringBuilder str1, StringBuilder str2) { int len1 = str1.Length; int len2 = str2.Length; if (len1 < len2) { for (int i = 0; i < len2 - len1; i++) { str1.Insert(0, '0'); } return len2; } else if (len1 > len2) { for (int i = 0; i < len1 - len2; i++) { str2.Insert(0, '0'); } } return len1; // If len1 >= len2 } // The main function that adds two-bit sequences // and returns the addition static string addBitStrings(StringBuilder str1, StringBuilder str2) { string result = \"\"; // To store the sum bits // make the lengths same before adding int length = makeEqualLength(str1, str2); // Convert StringBuilder to Strings string first = str1.ToString(); string second = str2.ToString(); int carry = 0; // Initialize carry // Add all bits one by one for (int i = length - 1; i >= 0; i--) { int firstBit = first[i] - '0'; int secondBit = second[i] - '0'; // boolean expression for sum of 3 bits int sum = (firstBit ^ secondBit ^ carry) + '0'; result = ((char) sum).ToString() + result; // boolean expression for 3-bit addition carry = (firstBit & secondBit) | (secondBit & carry) | (firstBit & carry); } // if overflow, then add a leading 1 if (carry == 1) { result = \"1\" + result; } return result; } // Driver Code public static void Main(string[] args) { string str1 = \"1100011\"; string str2 = \"10\"; Console.WriteLine(\"Sum is \" + addBitStrings(new StringBuilder(str1), new StringBuilder(str2))); }} // This code is contributed by kumar65",
"e": 33896,
"s": 31533,
"text": null
},
{
"code": null,
"e": 33904,
"s": 33896,
"text": "Output:"
},
{
"code": null,
"e": 33920,
"s": 33904,
"text": " Sum is 1100101"
},
{
"code": null,
"e": 33947,
"s": 33920,
"text": "Time Complexity: O(|str1|)"
},
{
"code": null,
"e": 34145,
"s": 33947,
"text": "Auxiliary Space: O(1)This article is compiled by Ravi Chandra Enaganti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 34158,
"s": 34145,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 34175,
"s": 34158,
"text": "Vivekkumar Singh"
},
{
"code": null,
"e": 34188,
"s": 34175,
"text": "chaudhary_19"
},
{
"code": null,
"e": 34196,
"s": 34188,
"text": "kumar65"
},
{
"code": null,
"e": 34206,
"s": 34196,
"text": "subham348"
},
{
"code": null,
"e": 34223,
"s": 34206,
"text": "surinderdawra388"
},
{
"code": null,
"e": 34245,
"s": 34223,
"text": "binary-representation"
},
{
"code": null,
"e": 34259,
"s": 34245,
"text": "binary-string"
},
{
"code": null,
"e": 34271,
"s": 34259,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 34281,
"s": 34271,
"text": "Bit Magic"
},
{
"code": null,
"e": 34291,
"s": 34281,
"text": "Bit Magic"
},
{
"code": null,
"e": 34389,
"s": 34291,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34398,
"s": 34389,
"text": "Comments"
},
{
"code": null,
"e": 34411,
"s": 34398,
"text": "Old Comments"
},
{
"code": null,
"e": 34462,
"s": 34411,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 34485,
"s": 34462,
"text": "Program to find parity"
},
{
"code": null,
"e": 34524,
"s": 34485,
"text": "Bit Tricks for Competitive Programming"
},
{
"code": null,
"e": 34588,
"s": 34524,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 34615,
"s": 34588,
"text": "Check for Integer Overflow"
},
{
"code": null,
"e": 34657,
"s": 34615,
"text": "Convert decimal fraction to binary number"
},
{
"code": null,
"e": 34697,
"s": 34657,
"text": "Reverse actual bits of the given number"
},
{
"code": null,
"e": 34731,
"s": 34697,
"text": "Builtin functions of GCC compiler"
},
{
"code": null,
"e": 34768,
"s": 34731,
"text": "Hamming code Implementation in C/C++"
}
] |
Add a Pandas series to another Pandas series - GeeksforGeeks | 30 Jul, 2020
Let us see how to add a Pandas series to another series in Python. This can be done using 2 ways :
append()
concat()
Method 1 : Using the append() function. It appends one series object at the end of another series object and returns an appended series.
# importing the moduleimport pandas as pd # create 2 series objectsseries_1 = pd.Series([2, 4, 6, 8])series_2 = pd.Series([10, 12, 14, 16]) # adding series_2 to series_1 using the append() functionseries_1 = series_1.append(series_2, ignore_index = True) # displaying series_1print(series_1)
Output :
Method 2 : Using the concat() function. It takes a list of series objects that are to be concatenated as an argument and returns a concatenated series.
# importing the moduleimport pandas as pd # create 2 series objectsseries_1 = pd.Series([2, 4, 6, 8])series_2 = pd.Series([10, 12, 14, 16]) # adding series_2 to series_1 using the concat() functionseries_1 = pd.concat([series_1, series_2]) # displaying series_1print(series_1)
Output :
data mining
data-science
Picked
Python pandas-series-methods
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
sum() function 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": 24495,
"s": 24467,
"text": "\n30 Jul, 2020"
},
{
"code": null,
"e": 24594,
"s": 24495,
"text": "Let us see how to add a Pandas series to another series in Python. This can be done using 2 ways :"
},
{
"code": null,
"e": 24603,
"s": 24594,
"text": "append()"
},
{
"code": null,
"e": 24612,
"s": 24603,
"text": "concat()"
},
{
"code": null,
"e": 24749,
"s": 24612,
"text": "Method 1 : Using the append() function. It appends one series object at the end of another series object and returns an appended series."
},
{
"code": "# importing the moduleimport pandas as pd # create 2 series objectsseries_1 = pd.Series([2, 4, 6, 8])series_2 = pd.Series([10, 12, 14, 16]) # adding series_2 to series_1 using the append() functionseries_1 = series_1.append(series_2, ignore_index = True) # displaying series_1print(series_1)",
"e": 25046,
"s": 24749,
"text": null
},
{
"code": null,
"e": 25055,
"s": 25046,
"text": "Output :"
},
{
"code": null,
"e": 25207,
"s": 25055,
"text": "Method 2 : Using the concat() function. It takes a list of series objects that are to be concatenated as an argument and returns a concatenated series."
},
{
"code": "# importing the moduleimport pandas as pd # create 2 series objectsseries_1 = pd.Series([2, 4, 6, 8])series_2 = pd.Series([10, 12, 14, 16]) # adding series_2 to series_1 using the concat() functionseries_1 = pd.concat([series_1, series_2]) # displaying series_1print(series_1)",
"e": 25489,
"s": 25207,
"text": null
},
{
"code": null,
"e": 25498,
"s": 25489,
"text": "Output :"
},
{
"code": null,
"e": 25510,
"s": 25498,
"text": "data mining"
},
{
"code": null,
"e": 25523,
"s": 25510,
"text": "data-science"
},
{
"code": null,
"e": 25530,
"s": 25523,
"text": "Picked"
},
{
"code": null,
"e": 25559,
"s": 25530,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 25566,
"s": 25559,
"text": "Python"
},
{
"code": null,
"e": 25582,
"s": 25566,
"text": "Write From Home"
},
{
"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": 25720,
"s": 25702,
"text": "Python Dictionary"
},
{
"code": null,
"e": 25742,
"s": 25720,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25774,
"s": 25742,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25816,
"s": 25774,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 25841,
"s": 25816,
"text": "sum() function in Python"
},
{
"code": null,
"e": 25877,
"s": 25841,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 25913,
"s": 25877,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 25929,
"s": 25913,
"text": "Python infinity"
},
{
"code": null,
"e": 25990,
"s": 25929,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
5 simples steps to build your time series forecasting model | by Mahbubul Alam | Towards Data Science | I am a strong believer in “learning by doing” philosophy.
Data science is an applied field, so you need to get your feet wet to learn something. One can read all the “how to” tutorials on swimming, but at some point, they do have to test the water.
Beginners in data science often get caught into the impression that they have to learn everything under the sun before they can do a project. Wrong! I believe people can learn faster not by reading stuff but by doing small bits and pieces of projects.
In this article I want you to learn how to fit a time series forecasting model ARIMA — which, for many, is an intimidating algorithm. In this article, you will learn it in just 5 easy steps and make real forecasts. You are not going to build a Ferrari, but I’m sure you will learn to build a car that you can take to the streets.
Let’s roll the sleeves.
For this demo, we are going to use a forecasting package calledfpp2 in R programming environment. Let’s load that package.
# Required packageslibrary(fpp2)
I’ve got some data that I extracted from an actual time series. The following are the values, let’s copy them in the R script as well.
# your datavalues = c(92.1, 92.6, 89.5, 80.9, 95.6, 72.5, 71.2, 78.8, 73.8, 83.5, 97.9, 93.4, 98.0, 90.2, 96.7, 100.0, 103.6, 74.6, 78.9, 92.0, 83.4, 98.1, 109.9, 102.2, 102.1, 96.2, 106.9, 95.1, 113.4, 84.0, 88.6, 94.9, 94.7, 105.7, 108.6, 101.9, 113.9, 100.9, 100.2, 91.9, 99.6, 87.2, 92.1, 104.9, 103.4, 103.3, 103.9, 108.5)
Like every other modeling software, this package has a specific data formatting requirement. The ts() function takes care of it by converting data into a time series object.
In this function we specify the starting year (2015) and 12-month frequency.
# your time seriestime_series = ts(values, start = 2015, frequency =12)
Decomposition basically means deconstructing and visualizing the series into its component parts.
# time series decompositionautoplot(decompose(time_series)) + theme(plot.title = element_text(size=8))
This figure below displays 4 pieces of information: your data (top one), overall trend and seasonality. The final piece is called the remainder or the random part.
The actual model building is a simple 2-lines code using auto.arima() function. auto.arima will take care of the optimum parameter values, you just need to specify a few boolean parameters.
model = auto.arima(time_series, seasonal = TRUE, stepwise = FALSE, approximation = FALSE)
Making an actual forecast is the simplest of all the steps above, just half of a line length code— can you believe? We are using forecast() function and passing the model above and specifying the number of time steps into the future you want to forecast (I specified 30 months ahead)
# making forecastforecast_arima = forecast(model, h=30)
You are practically done with forecasting. You can print the forecast values with the print(forecast_arima) function.
Or, you may want to visualize the forecast values, the input series and confidence intervals altogether.
# visualizing forecastautoplot(time_series, series = " Data") + autolayer(forecast_arima, series = "Forecast") + ggtitle(" Forecasting with ARIMA") + theme(plot.title = element_text(size=8))
This is an extra step for model evaluation and accuracy tests. First, let’s check out model description:
# model descriptionmodel['model']
I highlighted few things that you might be interested in: the description of the model (ARIMA(0,1,2(0,1,1)[12]) and AIC values. AIC is often used to compare the performance of two or more models.
In most machine learning models accuracy is determined based on RMSE or MAE values. Let’s print them as well.
# accuracyaccuracy(model)
That is all!
You have just built and implemented a forecasting model using 5 simple steps. Does that mean you became a master of forecasting? No, but you know the overall structure of the model from beginning to end and able to play with it with different datasets, different parameter values etc.
Just like I said in the beginning, you haven’t built a Ferrari but you’ve built a car that you can take to the grocery store!
I can be reached via Twitter or LinkedIn. | [
{
"code": null,
"e": 230,
"s": 172,
"text": "I am a strong believer in “learning by doing” philosophy."
},
{
"code": null,
"e": 421,
"s": 230,
"text": "Data science is an applied field, so you need to get your feet wet to learn something. One can read all the “how to” tutorials on swimming, but at some point, they do have to test the water."
},
{
"code": null,
"e": 673,
"s": 421,
"text": "Beginners in data science often get caught into the impression that they have to learn everything under the sun before they can do a project. Wrong! I believe people can learn faster not by reading stuff but by doing small bits and pieces of projects."
},
{
"code": null,
"e": 1003,
"s": 673,
"text": "In this article I want you to learn how to fit a time series forecasting model ARIMA — which, for many, is an intimidating algorithm. In this article, you will learn it in just 5 easy steps and make real forecasts. You are not going to build a Ferrari, but I’m sure you will learn to build a car that you can take to the streets."
},
{
"code": null,
"e": 1027,
"s": 1003,
"text": "Let’s roll the sleeves."
},
{
"code": null,
"e": 1150,
"s": 1027,
"text": "For this demo, we are going to use a forecasting package calledfpp2 in R programming environment. Let’s load that package."
},
{
"code": null,
"e": 1183,
"s": 1150,
"text": "# Required packageslibrary(fpp2)"
},
{
"code": null,
"e": 1318,
"s": 1183,
"text": "I’ve got some data that I extracted from an actual time series. The following are the values, let’s copy them in the R script as well."
},
{
"code": null,
"e": 1675,
"s": 1318,
"text": "# your datavalues = c(92.1, 92.6, 89.5, 80.9, 95.6, 72.5, 71.2, 78.8, 73.8, 83.5, 97.9, 93.4, 98.0, 90.2, 96.7, 100.0, 103.6, 74.6, 78.9, 92.0, 83.4, 98.1, 109.9, 102.2, 102.1, 96.2, 106.9, 95.1, 113.4, 84.0, 88.6, 94.9, 94.7, 105.7, 108.6, 101.9, 113.9, 100.9, 100.2, 91.9, 99.6, 87.2, 92.1, 104.9, 103.4, 103.3, 103.9, 108.5)"
},
{
"code": null,
"e": 1849,
"s": 1675,
"text": "Like every other modeling software, this package has a specific data formatting requirement. The ts() function takes care of it by converting data into a time series object."
},
{
"code": null,
"e": 1926,
"s": 1849,
"text": "In this function we specify the starting year (2015) and 12-month frequency."
},
{
"code": null,
"e": 1998,
"s": 1926,
"text": "# your time seriestime_series = ts(values, start = 2015, frequency =12)"
},
{
"code": null,
"e": 2096,
"s": 1998,
"text": "Decomposition basically means deconstructing and visualizing the series into its component parts."
},
{
"code": null,
"e": 2199,
"s": 2096,
"text": "# time series decompositionautoplot(decompose(time_series)) + theme(plot.title = element_text(size=8))"
},
{
"code": null,
"e": 2363,
"s": 2199,
"text": "This figure below displays 4 pieces of information: your data (top one), overall trend and seasonality. The final piece is called the remainder or the random part."
},
{
"code": null,
"e": 2553,
"s": 2363,
"text": "The actual model building is a simple 2-lines code using auto.arima() function. auto.arima will take care of the optimum parameter values, you just need to specify a few boolean parameters."
},
{
"code": null,
"e": 2643,
"s": 2553,
"text": "model = auto.arima(time_series, seasonal = TRUE, stepwise = FALSE, approximation = FALSE)"
},
{
"code": null,
"e": 2927,
"s": 2643,
"text": "Making an actual forecast is the simplest of all the steps above, just half of a line length code— can you believe? We are using forecast() function and passing the model above and specifying the number of time steps into the future you want to forecast (I specified 30 months ahead)"
},
{
"code": null,
"e": 2983,
"s": 2927,
"text": "# making forecastforecast_arima = forecast(model, h=30)"
},
{
"code": null,
"e": 3101,
"s": 2983,
"text": "You are practically done with forecasting. You can print the forecast values with the print(forecast_arima) function."
},
{
"code": null,
"e": 3206,
"s": 3101,
"text": "Or, you may want to visualize the forecast values, the input series and confidence intervals altogether."
},
{
"code": null,
"e": 3400,
"s": 3206,
"text": "# visualizing forecastautoplot(time_series, series = \" Data\") + autolayer(forecast_arima, series = \"Forecast\") + ggtitle(\" Forecasting with ARIMA\") + theme(plot.title = element_text(size=8))"
},
{
"code": null,
"e": 3505,
"s": 3400,
"text": "This is an extra step for model evaluation and accuracy tests. First, let’s check out model description:"
},
{
"code": null,
"e": 3539,
"s": 3505,
"text": "# model descriptionmodel['model']"
},
{
"code": null,
"e": 3735,
"s": 3539,
"text": "I highlighted few things that you might be interested in: the description of the model (ARIMA(0,1,2(0,1,1)[12]) and AIC values. AIC is often used to compare the performance of two or more models."
},
{
"code": null,
"e": 3845,
"s": 3735,
"text": "In most machine learning models accuracy is determined based on RMSE or MAE values. Let’s print them as well."
},
{
"code": null,
"e": 3871,
"s": 3845,
"text": "# accuracyaccuracy(model)"
},
{
"code": null,
"e": 3884,
"s": 3871,
"text": "That is all!"
},
{
"code": null,
"e": 4169,
"s": 3884,
"text": "You have just built and implemented a forecasting model using 5 simple steps. Does that mean you became a master of forecasting? No, but you know the overall structure of the model from beginning to end and able to play with it with different datasets, different parameter values etc."
},
{
"code": null,
"e": 4295,
"s": 4169,
"text": "Just like I said in the beginning, you haven’t built a Ferrari but you’ve built a car that you can take to the grocery store!"
}
] |
How to prepend a string in PHP ? | 31 May, 2020
We have given two strings and the task is to prepend a string str1 with another string str2 in PHP. There is no specific function to prepend a string in PHP. In order to do this task, we have the following operators in PHP:
Method 1: Using Concatenation Operator(“.”): The Concatenation operator is used to prepend a string str1 with another string str2 by concatenation of str1 and str2.
Syntax:
$x . $y
Example :
PHP
<?php// PHP program to prepend a string // Function to prepend a string function prepend_string ($str1, $str2){ // Using concatenation operator (.) $res = $str1 . $str2; // Returning the result return $res; } // Given string$str1 = "Geeksforgeeks"; $str2 = "Example"; // Function Call$str = prepend_string ($str1, $str2); // Printing the resultecho $str; ?>
GeeksforgeeksExample
Method 2: Using Concatenation assignment operator (“.=”): The Concatenation assignment operator is used to prepend a string str1 with another string str2 by appending the str2 to the str1.
Syntax:
$x .= $y
Example :
PHP
<?php// PHP program to prepend a string // Function to prepend a string function prepend_string ($str1, $str2) { // Using Concatenation assignment // operator (.=) $str1 .= $str2; // Returning the result return $str1;} // Given string$str1 = "Geeksforgeeks"; $str2 = "Example"; // Function call$str = prepend_string ($str1, $str2); // Printing the resultecho $str; ?>
GeeksforgeeksExample
PHP-string
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 execute PHP code using command line ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to execute PHP code using command line ?
How to delete an array element based on key in PHP?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 May, 2020"
},
{
"code": null,
"e": 252,
"s": 28,
"text": "We have given two strings and the task is to prepend a string str1 with another string str2 in PHP. There is no specific function to prepend a string in PHP. In order to do this task, we have the following operators in PHP:"
},
{
"code": null,
"e": 417,
"s": 252,
"text": "Method 1: Using Concatenation Operator(“.”): The Concatenation operator is used to prepend a string str1 with another string str2 by concatenation of str1 and str2."
},
{
"code": null,
"e": 425,
"s": 417,
"text": "Syntax:"
},
{
"code": null,
"e": 434,
"s": 425,
"text": "$x . $y\n"
},
{
"code": null,
"e": 444,
"s": 434,
"text": "Example :"
},
{
"code": null,
"e": 448,
"s": 444,
"text": "PHP"
},
{
"code": "<?php// PHP program to prepend a string // Function to prepend a string function prepend_string ($str1, $str2){ // Using concatenation operator (.) $res = $str1 . $str2; // Returning the result return $res; } // Given string$str1 = \"Geeksforgeeks\"; $str2 = \"Example\"; // Function Call$str = prepend_string ($str1, $str2); // Printing the resultecho $str; ?>",
"e": 843,
"s": 448,
"text": null
},
{
"code": null,
"e": 864,
"s": 843,
"text": "GeeksforgeeksExample"
},
{
"code": null,
"e": 1053,
"s": 864,
"text": "Method 2: Using Concatenation assignment operator (“.=”): The Concatenation assignment operator is used to prepend a string str1 with another string str2 by appending the str2 to the str1."
},
{
"code": null,
"e": 1061,
"s": 1053,
"text": "Syntax:"
},
{
"code": null,
"e": 1071,
"s": 1061,
"text": "$x .= $y\n"
},
{
"code": null,
"e": 1081,
"s": 1071,
"text": "Example :"
},
{
"code": null,
"e": 1085,
"s": 1081,
"text": "PHP"
},
{
"code": "<?php// PHP program to prepend a string // Function to prepend a string function prepend_string ($str1, $str2) { // Using Concatenation assignment // operator (.=) $str1 .= $str2; // Returning the result return $str1;} // Given string$str1 = \"Geeksforgeeks\"; $str2 = \"Example\"; // Function call$str = prepend_string ($str1, $str2); // Printing the resultecho $str; ?>",
"e": 1488,
"s": 1085,
"text": null
},
{
"code": null,
"e": 1509,
"s": 1488,
"text": "GeeksforgeeksExample"
},
{
"code": null,
"e": 1520,
"s": 1509,
"text": "PHP-string"
},
{
"code": null,
"e": 1524,
"s": 1520,
"text": "PHP"
},
{
"code": null,
"e": 1537,
"s": 1524,
"text": "PHP Programs"
},
{
"code": null,
"e": 1554,
"s": 1537,
"text": "Web Technologies"
},
{
"code": null,
"e": 1581,
"s": 1554,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1585,
"s": 1581,
"text": "PHP"
},
{
"code": null,
"e": 1683,
"s": 1585,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1728,
"s": 1683,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 1752,
"s": 1728,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 1804,
"s": 1752,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 1854,
"s": 1804,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1894,
"s": 1854,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 1939,
"s": 1894,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 1991,
"s": 1939,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 2041,
"s": 1991,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2081,
"s": 2041,
"text": "How to convert array to string in PHP ?"
}
] |
Sched module in Python | 06 Feb, 2020
Sched module is the standard library, can be used in the creation of bots and other monitoring and automation applications. The sched module implements a generic event scheduler for running tasks at specific times. It provides similar tools like task scheduler in windows or Linux, but the main advantage is with Python’s own sched module platform differences can be ignored.
Example:
# Python program for Creating # an event scheduler import schedimport time # Creating an instance of the# scheduler classscheduler = sched.scheduler(time.time, time.sleep)
scheduler.enter(): Events can be scheduled to run after a delay, or at a specific time. To schedule them with a delay, enter() method is used.Syntax: scheduler.enter(delay, priority, action, argument=(), kwargs={})Parameters:delay: A number representing the delay timepriority: Priority valueaction: Calling functionargument: A tuple of argumentsExample:import schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time # and name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # first event with delay of# 1 seconde1 = scheduler.enter(1, 1, print_event, ('1 st', )) # second event with delay of# 2 secondse1 = scheduler.enter(2, 1, print_event, (' 2nd', )) # executing the eventsscheduler.run()Output :START: 1580389814.152131
EVENT: 1580389815.1548214 1 st
EVENT: 1580389816.1533117 2nd
Syntax: scheduler.enter(delay, priority, action, argument=(), kwargs={})
Parameters:delay: A number representing the delay timepriority: Priority valueaction: Calling functionargument: A tuple of arguments
Example:
import schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time # and name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # first event with delay of# 1 seconde1 = scheduler.enter(1, 1, print_event, ('1 st', )) # second event with delay of# 2 secondse1 = scheduler.enter(2, 1, print_event, (' 2nd', )) # executing the eventsscheduler.run()
Output :
START: 1580389814.152131
EVENT: 1580389815.1548214 1 st
EVENT: 1580389816.1533117 2nd
scheduler.enterabs() The enterabs() time adds an event to the internal queue of the scheduler, as the run() method of a scheduler is called, the entries in the queue of a scheduler are executed one by one.Syntax: scheduler.enterabs(time, priority, action, argument=(), kwargs={})Parameters:time: Time at which the event/action has to be executedpriority: The priority of the eventaction: The function that constitutes an eventargument: Positional arguments to the event functionkwargs: A dictionary of keyword arguments to the event functionExample:# library importedimport schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time and# name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # event x with delay of 1 second# enters queue using enterabs methode_x = scheduler.enterabs(time.time()+1, 1, print_event, argument = ("Event X", )); # executing the eventsscheduler.run()Output :START: 1580389960.5845037
EVENT: 1580389961.5875661 Event X
Syntax: scheduler.enterabs(time, priority, action, argument=(), kwargs={})
Parameters:time: Time at which the event/action has to be executedpriority: The priority of the eventaction: The function that constitutes an eventargument: Positional arguments to the event functionkwargs: A dictionary of keyword arguments to the event function
Example:
# library importedimport schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time and# name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # event x with delay of 1 second# enters queue using enterabs methode_x = scheduler.enterabs(time.time()+1, 1, print_event, argument = ("Event X", )); # executing the eventsscheduler.run()
Output :
START: 1580389960.5845037
EVENT: 1580389961.5875661 Event X
scheduler.cancel() Remove the event from the queue. If the event is not an event currently in the queue, this method will raise a ValueError.Syntax: scheduler.cancel(event)Parameter:event: The event that should be removed.import schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time and# name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # first event with delay # of 1 seconde1 = scheduler.enter(1, 1, print_event, ('1 st', )) # second event with delay # of 2 secondse2 = scheduler.enter(2, 1, print_event, (' 2nd', )) # removing 1st event from # the event queuescheduler.cancel(e1) # executing the eventsscheduler.run()Output :START: 1580390119.54074
EVENT: 1580390121.5439944 2nd
Syntax: scheduler.cancel(event)
Parameter:event: The event that should be removed.
import schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time and# name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # first event with delay # of 1 seconde1 = scheduler.enter(1, 1, print_event, ('1 st', )) # second event with delay # of 2 secondse2 = scheduler.enter(2, 1, print_event, (' 2nd', )) # removing 1st event from # the event queuescheduler.cancel(e1) # executing the eventsscheduler.run()
Output :
START: 1580390119.54074
EVENT: 1580390121.5439944 2nd
scheduler.empty() It return True if the event queue is empty. It takes no argument.Example:import schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time # and name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # checking if event queue is# empty or notprint(scheduler.empty()) # event entering into queuee1 = scheduler.enter(2, 1, print_event, ('1 st', )) # checking if event queue is # empty or notprint(scheduler.empty()) # executing the eventsscheduler.run()Output :START: 1580390318.1343799
True
False
EVENT: 1580390320.136075 1 st
Example:
import schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time # and name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # checking if event queue is# empty or notprint(scheduler.empty()) # event entering into queuee1 = scheduler.enter(2, 1, print_event, ('1 st', )) # checking if event queue is # empty or notprint(scheduler.empty()) # executing the eventsscheduler.run()
Output :
START: 1580390318.1343799
True
False
EVENT: 1580390320.136075 1 st
scheduler.queue Read-only attribute returning a list of upcoming events in the order they will be run. Each event is shown as a named tuple with the following fields: time, priority, action, argument, kwargs.# library importedimport schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time # and name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # event entering into queuee1 = scheduler.enter(2, 1, print_event, ('1 st', )) # printing the details of# upcoming events in event queueprint(scheduler.queue) # executing the eventsscheduler.run()Output :START: 1580390446.8743565[Event(time=1580390448.8743565, priority=1, action=, argument=(‘1 st’, ), kwargs={})]EVENT: 1580390448.876916 1 st
# library importedimport schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time # and name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # event entering into queuee1 = scheduler.enter(2, 1, print_event, ('1 st', )) # printing the details of# upcoming events in event queueprint(scheduler.queue) # executing the eventsscheduler.run()
Output :
START: 1580390446.8743565[Event(time=1580390448.8743565, priority=1, action=, argument=(‘1 st’, ), kwargs={})]EVENT: 1580390448.876916 1 st
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Feb, 2020"
},
{
"code": null,
"e": 404,
"s": 28,
"text": "Sched module is the standard library, can be used in the creation of bots and other monitoring and automation applications. The sched module implements a generic event scheduler for running tasks at specific times. It provides similar tools like task scheduler in windows or Linux, but the main advantage is with Python’s own sched module platform differences can be ignored."
},
{
"code": null,
"e": 413,
"s": 404,
"text": "Example:"
},
{
"code": "# Python program for Creating # an event scheduler import schedimport time # Creating an instance of the# scheduler classscheduler = sched.scheduler(time.time, time.sleep)",
"e": 619,
"s": 413,
"text": null
},
{
"code": null,
"e": 1620,
"s": 619,
"text": "scheduler.enter(): Events can be scheduled to run after a delay, or at a specific time. To schedule them with a delay, enter() method is used.Syntax: scheduler.enter(delay, priority, action, argument=(), kwargs={})Parameters:delay: A number representing the delay timepriority: Priority valueaction: Calling functionargument: A tuple of argumentsExample:import schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time # and name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # first event with delay of# 1 seconde1 = scheduler.enter(1, 1, print_event, ('1 st', )) # second event with delay of# 2 secondse1 = scheduler.enter(2, 1, print_event, (' 2nd', )) # executing the eventsscheduler.run()Output :START: 1580389814.152131\nEVENT: 1580389815.1548214 1 st\nEVENT: 1580389816.1533117 2nd\n"
},
{
"code": null,
"e": 1693,
"s": 1620,
"text": "Syntax: scheduler.enter(delay, priority, action, argument=(), kwargs={})"
},
{
"code": null,
"e": 1826,
"s": 1693,
"text": "Parameters:delay: A number representing the delay timepriority: Priority valueaction: Calling functionargument: A tuple of arguments"
},
{
"code": null,
"e": 1835,
"s": 1826,
"text": "Example:"
},
{
"code": "import schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time # and name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # first event with delay of# 1 seconde1 = scheduler.enter(1, 1, print_event, ('1 st', )) # second event with delay of# 2 secondse1 = scheduler.enter(2, 1, print_event, (' 2nd', )) # executing the eventsscheduler.run()",
"e": 2387,
"s": 1835,
"text": null
},
{
"code": null,
"e": 2396,
"s": 2387,
"text": "Output :"
},
{
"code": null,
"e": 2484,
"s": 2396,
"text": "START: 1580389814.152131\nEVENT: 1580389815.1548214 1 st\nEVENT: 1580389816.1533117 2nd\n"
},
{
"code": null,
"e": 3647,
"s": 2484,
"text": "scheduler.enterabs() The enterabs() time adds an event to the internal queue of the scheduler, as the run() method of a scheduler is called, the entries in the queue of a scheduler are executed one by one.Syntax: scheduler.enterabs(time, priority, action, argument=(), kwargs={})Parameters:time: Time at which the event/action has to be executedpriority: The priority of the eventaction: The function that constitutes an eventargument: Positional arguments to the event functionkwargs: A dictionary of keyword arguments to the event functionExample:# library importedimport schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time and# name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # event x with delay of 1 second# enters queue using enterabs methode_x = scheduler.enterabs(time.time()+1, 1, print_event, argument = (\"Event X\", )); # executing the eventsscheduler.run()Output :START: 1580389960.5845037\nEVENT: 1580389961.5875661 Event X\n"
},
{
"code": null,
"e": 3722,
"s": 3647,
"text": "Syntax: scheduler.enterabs(time, priority, action, argument=(), kwargs={})"
},
{
"code": null,
"e": 3985,
"s": 3722,
"text": "Parameters:time: Time at which the event/action has to be executedpriority: The priority of the eventaction: The function that constitutes an eventargument: Positional arguments to the event functionkwargs: A dictionary of keyword arguments to the event function"
},
{
"code": null,
"e": 3994,
"s": 3985,
"text": "Example:"
},
{
"code": "# library importedimport schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time and# name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # event x with delay of 1 second# enters queue using enterabs methode_x = scheduler.enterabs(time.time()+1, 1, print_event, argument = (\"Event X\", )); # executing the eventsscheduler.run()",
"e": 4540,
"s": 3994,
"text": null
},
{
"code": null,
"e": 4549,
"s": 4540,
"text": "Output :"
},
{
"code": null,
"e": 4610,
"s": 4549,
"text": "START: 1580389960.5845037\nEVENT: 1580389961.5875661 Event X\n"
},
{
"code": null,
"e": 5557,
"s": 4610,
"text": "scheduler.cancel() Remove the event from the queue. If the event is not an event currently in the queue, this method will raise a ValueError.Syntax: scheduler.cancel(event)Parameter:event: The event that should be removed.import schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time and# name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # first event with delay # of 1 seconde1 = scheduler.enter(1, 1, print_event, ('1 st', )) # second event with delay # of 2 secondse2 = scheduler.enter(2, 1, print_event, (' 2nd', )) # removing 1st event from # the event queuescheduler.cancel(e1) # executing the eventsscheduler.run()Output :START: 1580390119.54074\nEVENT: 1580390121.5439944 2nd\n"
},
{
"code": null,
"e": 5589,
"s": 5557,
"text": "Syntax: scheduler.cancel(event)"
},
{
"code": null,
"e": 5640,
"s": 5589,
"text": "Parameter:event: The event that should be removed."
},
{
"code": "import schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time and# name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # first event with delay # of 1 seconde1 = scheduler.enter(1, 1, print_event, ('1 st', )) # second event with delay # of 2 secondse2 = scheduler.enter(2, 1, print_event, (' 2nd', )) # removing 1st event from # the event queuescheduler.cancel(e1) # executing the eventsscheduler.run()",
"e": 6302,
"s": 5640,
"text": null
},
{
"code": null,
"e": 6311,
"s": 6302,
"text": "Output :"
},
{
"code": null,
"e": 6367,
"s": 6311,
"text": "START: 1580390119.54074\nEVENT: 1580390121.5439944 2nd\n"
},
{
"code": null,
"e": 7120,
"s": 6367,
"text": "scheduler.empty() It return True if the event queue is empty. It takes no argument.Example:import schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time # and name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # checking if event queue is# empty or notprint(scheduler.empty()) # event entering into queuee1 = scheduler.enter(2, 1, print_event, ('1 st', )) # checking if event queue is # empty or notprint(scheduler.empty()) # executing the eventsscheduler.run()Output :START: 1580390318.1343799\nTrue\nFalse\nEVENT: 1580390320.136075 1 st\n"
},
{
"code": null,
"e": 7129,
"s": 7120,
"text": "Example:"
},
{
"code": "import schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time # and name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # checking if event queue is# empty or notprint(scheduler.empty()) # event entering into queuee1 = scheduler.enter(2, 1, print_event, ('1 st', )) # checking if event queue is # empty or notprint(scheduler.empty()) # executing the eventsscheduler.run()",
"e": 7716,
"s": 7129,
"text": null
},
{
"code": null,
"e": 7725,
"s": 7716,
"text": "Output :"
},
{
"code": null,
"e": 7793,
"s": 7725,
"text": "START: 1580390318.1343799\nTrue\nFalse\nEVENT: 1580390320.136075 1 st\n"
},
{
"code": null,
"e": 8696,
"s": 7793,
"text": "scheduler.queue Read-only attribute returning a list of upcoming events in the order they will be run. Each event is shown as a named tuple with the following fields: time, priority, action, argument, kwargs.# library importedimport schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time # and name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # event entering into queuee1 = scheduler.enter(2, 1, print_event, ('1 st', )) # printing the details of# upcoming events in event queueprint(scheduler.queue) # executing the eventsscheduler.run()Output :START: 1580390446.8743565[Event(time=1580390448.8743565, priority=1, action=, argument=(‘1 st’, ), kwargs={})]EVENT: 1580390448.876916 1 st"
},
{
"code": "# library importedimport schedimport time # instance is createdscheduler = sched.scheduler(time.time, time.sleep) # function to print time # and name of the eventdef print_event(name): print('EVENT:', time.time(), name) # printing starting timeprint ('START:', time.time()) # event entering into queuee1 = scheduler.enter(2, 1, print_event, ('1 st', )) # printing the details of# upcoming events in event queueprint(scheduler.queue) # executing the eventsscheduler.run()",
"e": 9244,
"s": 8696,
"text": null
},
{
"code": null,
"e": 9253,
"s": 9244,
"text": "Output :"
},
{
"code": null,
"e": 9393,
"s": 9253,
"text": "START: 1580390446.8743565[Event(time=1580390448.8743565, priority=1, action=, argument=(‘1 st’, ), kwargs={})]EVENT: 1580390448.876916 1 st"
},
{
"code": null,
"e": 9408,
"s": 9393,
"text": "python-modules"
},
{
"code": null,
"e": 9415,
"s": 9408,
"text": "Python"
},
{
"code": null,
"e": 9513,
"s": 9415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9531,
"s": 9513,
"text": "Python Dictionary"
},
{
"code": null,
"e": 9573,
"s": 9531,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 9595,
"s": 9573,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 9627,
"s": 9595,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 9656,
"s": 9627,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 9683,
"s": 9656,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 9713,
"s": 9683,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 9734,
"s": 9713,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 9770,
"s": 9734,
"text": "Convert integer to string in Python"
}
] |
How to Create Animated Typing Effect using typed.js ? | 21 Jul, 2020
Typed.js is a JavaScript library which is used to type a set of strings at the speed that you set, backspace what it’s typed and begin the typing with another string you have set.
Let us start by creating a project folder and name it as per your wish. Create two files and name them as “index.html” and “style.css”
Write the following code in “index.html”HTMLHTML<!DOCTYPE html><html lang="en"> <head> <title>Typed.js</title> <!-- Import style.css from root directory --> <link rel="stylesheet" href="./style.css" /></head> <body> <div class="heading"> <h1>GeeksforGeeks</h1> <h3> <span class="text-slider-items"> A computer Science portal for geeks, A place to pratice code </span> <strong class="text-slider"></strong> <!-- classes "text-slider" and "text-slider-items" for typed.js script --> </h3> </div></body> </html>Write the following CSS code into your “style.css” file.<style> body { background-color: white; font-family: Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } .text-slider-items { display: none; } .heading { margin-top: 200px; text-align: center; } .heading h1 { color: limegreen; font-size: 70px; } .heading h3 { color: black; font-size: 20px; }</style>Now you have to download “typed.js” scripts folder from the below link and unzip it and keep it in your project directory.Download Link: https://mattboldt.com/demos/typed-js/Also, you have to include jQuery library to use jQuery functions. There are two ways either by downloading and adding the “jquery.js” file or by adding its CDN file link. Here you will add jQuery by using CDN link.CDN link: https://developers.google.com/speed/libraries/devguide#jqueryWe have to import and add “typed.js” file from the “typed.js” folder. Add all JavaScript files just before the “body” tag. Also add the below script into your “index.html” file.HTMLHTML<script src="./typed.js-master/lib/typed.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.5.1/jquery.min.js"></script><script> if ($(".text-slider").length == 1) { var typed_strings = $(".text-slider-items").text(); var typed = new Typed(".text-slider", { strings: typed_strings.split(", "), typeSpeed: 50, loop: true, backDelay: 900, backSpeed: 30, }); }</script>It should look like this.HTMLHTML<!DOCTYPE html><html lang="en"> <head> <title>Typed.js</title> <!-- Import style.css from root directory --> <link rel="stylesheet" href="./style.css" /></head> <body> <div class="heading"> <h1>GeeksforGeeks</h1> <h3> <span class="text-slider-items"> A computer Science portal for geeks, A place to pratice code </span> <strong class="text-slider"></strong> </h3> </div> <!-- Import typed.min.js file from typed.js folder --> <script src= "./typed.js-master/lib/typed.min.js"> </script> <!-- Add jquery cdn --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!-- Add this script for successful implementation of typed.js --> <script> if ($(".text-slider").length == 1) { var typed_strings = $(".text-slider-items").text(); var typed = new Typed(".text-slider", { strings: typed_strings.split(", "), typeSpeed: 50, loop: true, backDelay: 900, backSpeed: 30, }); } </script></body> </html>Start the “index.html” file and notice the output.
Write the following code in “index.html”HTMLHTML<!DOCTYPE html><html lang="en"> <head> <title>Typed.js</title> <!-- Import style.css from root directory --> <link rel="stylesheet" href="./style.css" /></head> <body> <div class="heading"> <h1>GeeksforGeeks</h1> <h3> <span class="text-slider-items"> A computer Science portal for geeks, A place to pratice code </span> <strong class="text-slider"></strong> <!-- classes "text-slider" and "text-slider-items" for typed.js script --> </h3> </div></body> </html>
Write the following code in “index.html”
HTML
<!DOCTYPE html><html lang="en"> <head> <title>Typed.js</title> <!-- Import style.css from root directory --> <link rel="stylesheet" href="./style.css" /></head> <body> <div class="heading"> <h1>GeeksforGeeks</h1> <h3> <span class="text-slider-items"> A computer Science portal for geeks, A place to pratice code </span> <strong class="text-slider"></strong> <!-- classes "text-slider" and "text-slider-items" for typed.js script --> </h3> </div></body> </html>
Write the following CSS code into your “style.css” file.<style> body { background-color: white; font-family: Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } .text-slider-items { display: none; } .heading { margin-top: 200px; text-align: center; } .heading h1 { color: limegreen; font-size: 70px; } .heading h3 { color: black; font-size: 20px; }</style>
Write the following CSS code into your “style.css” file.
<style> body { background-color: white; font-family: Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } .text-slider-items { display: none; } .heading { margin-top: 200px; text-align: center; } .heading h1 { color: limegreen; font-size: 70px; } .heading h3 { color: black; font-size: 20px; }</style>
Now you have to download “typed.js” scripts folder from the below link and unzip it and keep it in your project directory.Download Link: https://mattboldt.com/demos/typed-js/Also, you have to include jQuery library to use jQuery functions. There are two ways either by downloading and adding the “jquery.js” file or by adding its CDN file link. Here you will add jQuery by using CDN link.CDN link: https://developers.google.com/speed/libraries/devguide#jquery
Now you have to download “typed.js” scripts folder from the below link and unzip it and keep it in your project directory.
Download Link: https://mattboldt.com/demos/typed-js/
Also, you have to include jQuery library to use jQuery functions. There are two ways either by downloading and adding the “jquery.js” file or by adding its CDN file link. Here you will add jQuery by using CDN link.
CDN link: https://developers.google.com/speed/libraries/devguide#jquery
We have to import and add “typed.js” file from the “typed.js” folder. Add all JavaScript files just before the “body” tag. Also add the below script into your “index.html” file.HTMLHTML<script src="./typed.js-master/lib/typed.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.5.1/jquery.min.js"></script><script> if ($(".text-slider").length == 1) { var typed_strings = $(".text-slider-items").text(); var typed = new Typed(".text-slider", { strings: typed_strings.split(", "), typeSpeed: 50, loop: true, backDelay: 900, backSpeed: 30, }); }</script>It should look like this.HTMLHTML<!DOCTYPE html><html lang="en"> <head> <title>Typed.js</title> <!-- Import style.css from root directory --> <link rel="stylesheet" href="./style.css" /></head> <body> <div class="heading"> <h1>GeeksforGeeks</h1> <h3> <span class="text-slider-items"> A computer Science portal for geeks, A place to pratice code </span> <strong class="text-slider"></strong> </h3> </div> <!-- Import typed.min.js file from typed.js folder --> <script src= "./typed.js-master/lib/typed.min.js"> </script> <!-- Add jquery cdn --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!-- Add this script for successful implementation of typed.js --> <script> if ($(".text-slider").length == 1) { var typed_strings = $(".text-slider-items").text(); var typed = new Typed(".text-slider", { strings: typed_strings.split(", "), typeSpeed: 50, loop: true, backDelay: 900, backSpeed: 30, }); } </script></body> </html>Start the “index.html” file and notice the output.
We have to import and add “typed.js” file from the “typed.js” folder. Add all JavaScript files just before the “body” tag. Also add the below script into your “index.html” file.
HTML
<script src="./typed.js-master/lib/typed.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.5.1/jquery.min.js"></script><script> if ($(".text-slider").length == 1) { var typed_strings = $(".text-slider-items").text(); var typed = new Typed(".text-slider", { strings: typed_strings.split(", "), typeSpeed: 50, loop: true, backDelay: 900, backSpeed: 30, }); }</script>
It should look like this.
HTML
<!DOCTYPE html><html lang="en"> <head> <title>Typed.js</title> <!-- Import style.css from root directory --> <link rel="stylesheet" href="./style.css" /></head> <body> <div class="heading"> <h1>GeeksforGeeks</h1> <h3> <span class="text-slider-items"> A computer Science portal for geeks, A place to pratice code </span> <strong class="text-slider"></strong> </h3> </div> <!-- Import typed.min.js file from typed.js folder --> <script src= "./typed.js-master/lib/typed.min.js"> </script> <!-- Add jquery cdn --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!-- Add this script for successful implementation of typed.js --> <script> if ($(".text-slider").length == 1) { var typed_strings = $(".text-slider-items").text(); var typed = new Typed(".text-slider", { strings: typed_strings.split(", "), typeSpeed: 50, loop: true, backDelay: 900, backSpeed: 30, }); } </script></body> </html>
Start the “index.html” file and notice the output.
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jul, 2020"
},
{
"code": null,
"e": 232,
"s": 52,
"text": "Typed.js is a JavaScript library which is used to type a set of strings at the speed that you set, backspace what it’s typed and begin the typing with another string you have set."
},
{
"code": null,
"e": 367,
"s": 232,
"text": "Let us start by creating a project folder and name it as per your wish. Create two files and name them as “index.html” and “style.css”"
},
{
"code": null,
"e": 3958,
"s": 367,
"text": "Write the following code in “index.html”HTMLHTML<!DOCTYPE html><html lang=\"en\"> <head> <title>Typed.js</title> <!-- Import style.css from root directory --> <link rel=\"stylesheet\" href=\"./style.css\" /></head> <body> <div class=\"heading\"> <h1>GeeksforGeeks</h1> <h3> <span class=\"text-slider-items\"> A computer Science portal for geeks, A place to pratice code </span> <strong class=\"text-slider\"></strong> <!-- classes \"text-slider\" and \"text-slider-items\" for typed.js script --> </h3> </div></body> </html>Write the following CSS code into your “style.css” file.<style> body { background-color: white; font-family: Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } .text-slider-items { display: none; } .heading { margin-top: 200px; text-align: center; } .heading h1 { color: limegreen; font-size: 70px; } .heading h3 { color: black; font-size: 20px; }</style>Now you have to download “typed.js” scripts folder from the below link and unzip it and keep it in your project directory.Download Link: https://mattboldt.com/demos/typed-js/Also, you have to include jQuery library to use jQuery functions. There are two ways either by downloading and adding the “jquery.js” file or by adding its CDN file link. Here you will add jQuery by using CDN link.CDN link: https://developers.google.com/speed/libraries/devguide#jqueryWe have to import and add “typed.js” file from the “typed.js” folder. Add all JavaScript files just before the “body” tag. Also add the below script into your “index.html” file.HTMLHTML<script src=\"./typed.js-master/lib/typed.min.js\"></script><script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.5.1/jquery.min.js\"></script><script> if ($(\".text-slider\").length == 1) { var typed_strings = $(\".text-slider-items\").text(); var typed = new Typed(\".text-slider\", { strings: typed_strings.split(\", \"), typeSpeed: 50, loop: true, backDelay: 900, backSpeed: 30, }); }</script>It should look like this.HTMLHTML<!DOCTYPE html><html lang=\"en\"> <head> <title>Typed.js</title> <!-- Import style.css from root directory --> <link rel=\"stylesheet\" href=\"./style.css\" /></head> <body> <div class=\"heading\"> <h1>GeeksforGeeks</h1> <h3> <span class=\"text-slider-items\"> A computer Science portal for geeks, A place to pratice code </span> <strong class=\"text-slider\"></strong> </h3> </div> <!-- Import typed.min.js file from typed.js folder --> <script src= \"./typed.js-master/lib/typed.min.js\"> </script> <!-- Add jquery cdn --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!-- Add this script for successful implementation of typed.js --> <script> if ($(\".text-slider\").length == 1) { var typed_strings = $(\".text-slider-items\").text(); var typed = new Typed(\".text-slider\", { strings: typed_strings.split(\", \"), typeSpeed: 50, loop: true, backDelay: 900, backSpeed: 30, }); } </script></body> </html>Start the “index.html” file and notice the output."
},
{
"code": null,
"e": 4605,
"s": 3958,
"text": "Write the following code in “index.html”HTMLHTML<!DOCTYPE html><html lang=\"en\"> <head> <title>Typed.js</title> <!-- Import style.css from root directory --> <link rel=\"stylesheet\" href=\"./style.css\" /></head> <body> <div class=\"heading\"> <h1>GeeksforGeeks</h1> <h3> <span class=\"text-slider-items\"> A computer Science portal for geeks, A place to pratice code </span> <strong class=\"text-slider\"></strong> <!-- classes \"text-slider\" and \"text-slider-items\" for typed.js script --> </h3> </div></body> </html>"
},
{
"code": null,
"e": 4646,
"s": 4605,
"text": "Write the following code in “index.html”"
},
{
"code": null,
"e": 4651,
"s": 4646,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Typed.js</title> <!-- Import style.css from root directory --> <link rel=\"stylesheet\" href=\"./style.css\" /></head> <body> <div class=\"heading\"> <h1>GeeksforGeeks</h1> <h3> <span class=\"text-slider-items\"> A computer Science portal for geeks, A place to pratice code </span> <strong class=\"text-slider\"></strong> <!-- classes \"text-slider\" and \"text-slider-items\" for typed.js script --> </h3> </div></body> </html>",
"e": 5250,
"s": 4651,
"text": null
},
{
"code": null,
"e": 5749,
"s": 5250,
"text": "Write the following CSS code into your “style.css” file.<style> body { background-color: white; font-family: Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } .text-slider-items { display: none; } .heading { margin-top: 200px; text-align: center; } .heading h1 { color: limegreen; font-size: 70px; } .heading h3 { color: black; font-size: 20px; }</style>"
},
{
"code": null,
"e": 5806,
"s": 5749,
"text": "Write the following CSS code into your “style.css” file."
},
{
"code": "<style> body { background-color: white; font-family: Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } .text-slider-items { display: none; } .heading { margin-top: 200px; text-align: center; } .heading h1 { color: limegreen; font-size: 70px; } .heading h3 { color: black; font-size: 20px; }</style>",
"e": 6249,
"s": 5806,
"text": null
},
{
"code": null,
"e": 6709,
"s": 6249,
"text": "Now you have to download “typed.js” scripts folder from the below link and unzip it and keep it in your project directory.Download Link: https://mattboldt.com/demos/typed-js/Also, you have to include jQuery library to use jQuery functions. There are two ways either by downloading and adding the “jquery.js” file or by adding its CDN file link. Here you will add jQuery by using CDN link.CDN link: https://developers.google.com/speed/libraries/devguide#jquery"
},
{
"code": null,
"e": 6832,
"s": 6709,
"text": "Now you have to download “typed.js” scripts folder from the below link and unzip it and keep it in your project directory."
},
{
"code": null,
"e": 6885,
"s": 6832,
"text": "Download Link: https://mattboldt.com/demos/typed-js/"
},
{
"code": null,
"e": 7100,
"s": 6885,
"text": "Also, you have to include jQuery library to use jQuery functions. There are two ways either by downloading and adding the “jquery.js” file or by adding its CDN file link. Here you will add jQuery by using CDN link."
},
{
"code": null,
"e": 7172,
"s": 7100,
"text": "CDN link: https://developers.google.com/speed/libraries/devguide#jquery"
},
{
"code": null,
"e": 9160,
"s": 7172,
"text": "We have to import and add “typed.js” file from the “typed.js” folder. Add all JavaScript files just before the “body” tag. Also add the below script into your “index.html” file.HTMLHTML<script src=\"./typed.js-master/lib/typed.min.js\"></script><script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.5.1/jquery.min.js\"></script><script> if ($(\".text-slider\").length == 1) { var typed_strings = $(\".text-slider-items\").text(); var typed = new Typed(\".text-slider\", { strings: typed_strings.split(\", \"), typeSpeed: 50, loop: true, backDelay: 900, backSpeed: 30, }); }</script>It should look like this.HTMLHTML<!DOCTYPE html><html lang=\"en\"> <head> <title>Typed.js</title> <!-- Import style.css from root directory --> <link rel=\"stylesheet\" href=\"./style.css\" /></head> <body> <div class=\"heading\"> <h1>GeeksforGeeks</h1> <h3> <span class=\"text-slider-items\"> A computer Science portal for geeks, A place to pratice code </span> <strong class=\"text-slider\"></strong> </h3> </div> <!-- Import typed.min.js file from typed.js folder --> <script src= \"./typed.js-master/lib/typed.min.js\"> </script> <!-- Add jquery cdn --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!-- Add this script for successful implementation of typed.js --> <script> if ($(\".text-slider\").length == 1) { var typed_strings = $(\".text-slider-items\").text(); var typed = new Typed(\".text-slider\", { strings: typed_strings.split(\", \"), typeSpeed: 50, loop: true, backDelay: 900, backSpeed: 30, }); } </script></body> </html>Start the “index.html” file and notice the output."
},
{
"code": null,
"e": 9338,
"s": 9160,
"text": "We have to import and add “typed.js” file from the “typed.js” folder. Add all JavaScript files just before the “body” tag. Also add the below script into your “index.html” file."
},
{
"code": null,
"e": 9343,
"s": 9338,
"text": "HTML"
},
{
"code": "<script src=\"./typed.js-master/lib/typed.min.js\"></script><script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.5.1/jquery.min.js\"></script><script> if ($(\".text-slider\").length == 1) { var typed_strings = $(\".text-slider-items\").text(); var typed = new Typed(\".text-slider\", { strings: typed_strings.split(\", \"), typeSpeed: 50, loop: true, backDelay: 900, backSpeed: 30, }); }</script>",
"e": 9821,
"s": 9343,
"text": null
},
{
"code": null,
"e": 9847,
"s": 9821,
"text": "It should look like this."
},
{
"code": null,
"e": 9852,
"s": 9847,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Typed.js</title> <!-- Import style.css from root directory --> <link rel=\"stylesheet\" href=\"./style.css\" /></head> <body> <div class=\"heading\"> <h1>GeeksforGeeks</h1> <h3> <span class=\"text-slider-items\"> A computer Science portal for geeks, A place to pratice code </span> <strong class=\"text-slider\"></strong> </h3> </div> <!-- Import typed.min.js file from typed.js folder --> <script src= \"./typed.js-master/lib/typed.min.js\"> </script> <!-- Add jquery cdn --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!-- Add this script for successful implementation of typed.js --> <script> if ($(\".text-slider\").length == 1) { var typed_strings = $(\".text-slider-items\").text(); var typed = new Typed(\".text-slider\", { strings: typed_strings.split(\", \"), typeSpeed: 50, loop: true, backDelay: 900, backSpeed: 30, }); } </script></body> </html>",
"e": 11095,
"s": 9852,
"text": null
},
{
"code": null,
"e": 11146,
"s": 11095,
"text": "Start the “index.html” file and notice the output."
},
{
"code": null,
"e": 11154,
"s": 11146,
"text": "Output:"
},
{
"code": null,
"e": 11163,
"s": 11154,
"text": "CSS-Misc"
},
{
"code": null,
"e": 11173,
"s": 11163,
"text": "HTML-Misc"
},
{
"code": null,
"e": 11189,
"s": 11173,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 11193,
"s": 11189,
"text": "CSS"
},
{
"code": null,
"e": 11198,
"s": 11193,
"text": "HTML"
},
{
"code": null,
"e": 11209,
"s": 11198,
"text": "JavaScript"
},
{
"code": null,
"e": 11226,
"s": 11209,
"text": "Web Technologies"
},
{
"code": null,
"e": 11253,
"s": 11226,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 11258,
"s": 11253,
"text": "HTML"
},
{
"code": null,
"e": 11356,
"s": 11258,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11393,
"s": 11356,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 11432,
"s": 11393,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 11471,
"s": 11432,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 11535,
"s": 11471,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 11596,
"s": 11535,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 11620,
"s": 11596,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 11673,
"s": 11620,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 11733,
"s": 11673,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 11794,
"s": 11733,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
How to get key attribute of parent div when button is clicked in ReactJS ? | 07 Apr, 2021
In ReactJs we can pass properties in the child component from the parent component. So, we are going to do the same and pass the key of a parent as a property in the child component.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: Create Parent.js and Child.js components.
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React, { Component } from 'react'; import Parent from './Parent'; class App extends Component { state = { key: "GFG", } render() { return ( <div> <h2>GeeksforGeeks</h2> <Parent key={this.state.key} keyValue={this.state.key}/> </div> ); }} export default App;
Parent.js
import React, { Component } from 'react'; import Child from './Child'; class Parent extends Component { render() { return ( // Passing key in child <div> <h3>(Parent.js) Key = {this.props.keyValue}</h3> <Child keyValue={this.props.keyValue}/> </div> ); }} export default Parent;
Child.js
import React, { Component } from 'react'; class Child extends Component { state = { key: "", } handleClick = () => { this.setState({key: this.props.keyValue}); } render() { return ( <div> <h3>(Child.js) Key = {this.state.key}</h3> <button onClick={this.handleClick}> Get Parent Key </button> </div> ); } } export default Child;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to create a multi-page website using React.js ?
How to do crud operations in ReactJS ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "In ReactJs we can pass properties in the child component from the parent component. So, we are going to do the same and pass the key of a parent as a property in the child component."
},
{
"code": null,
"e": 261,
"s": 211,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 356,
"s": 261,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 420,
"s": 356,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 452,
"s": 420,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 565,
"s": 452,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 665,
"s": 565,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 679,
"s": 665,
"text": "cd foldername"
},
{
"code": null,
"e": 729,
"s": 679,
"text": "Step 3: Create Parent.js and Child.js components."
},
{
"code": null,
"e": 781,
"s": 729,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 911,
"s": 781,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 918,
"s": 911,
"text": "App.js"
},
{
"code": "import React, { Component } from 'react'; import Parent from './Parent'; class App extends Component { state = { key: \"GFG\", } render() { return ( <div> <h2>GeeksforGeeks</h2> <Parent key={this.state.key} keyValue={this.state.key}/> </div> ); }} export default App;",
"e": 1229,
"s": 918,
"text": null
},
{
"code": null,
"e": 1239,
"s": 1229,
"text": "Parent.js"
},
{
"code": "import React, { Component } from 'react'; import Child from './Child'; class Parent extends Component { render() { return ( // Passing key in child <div> <h3>(Parent.js) Key = {this.props.keyValue}</h3> <Child keyValue={this.props.keyValue}/> </div> ); }} export default Parent;",
"e": 1575,
"s": 1239,
"text": null
},
{
"code": null,
"e": 1584,
"s": 1575,
"text": "Child.js"
},
{
"code": "import React, { Component } from 'react'; class Child extends Component { state = { key: \"\", } handleClick = () => { this.setState({key: this.props.keyValue}); } render() { return ( <div> <h3>(Child.js) Key = {this.state.key}</h3> <button onClick={this.handleClick}> Get Parent Key </button> </div> ); } } export default Child;",
"e": 1984,
"s": 1584,
"text": null
},
{
"code": null,
"e": 2097,
"s": 1984,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2107,
"s": 2097,
"text": "npm start"
},
{
"code": null,
"e": 2206,
"s": 2107,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 2213,
"s": 2206,
"text": "Picked"
},
{
"code": null,
"e": 2229,
"s": 2213,
"text": "React-Questions"
},
{
"code": null,
"e": 2237,
"s": 2229,
"text": "ReactJS"
},
{
"code": null,
"e": 2254,
"s": 2237,
"text": "Web Technologies"
},
{
"code": null,
"e": 2352,
"s": 2254,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2390,
"s": 2352,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 2417,
"s": 2390,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 2456,
"s": 2417,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 2508,
"s": 2456,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 2547,
"s": 2508,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 2580,
"s": 2547,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2642,
"s": 2580,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2703,
"s": 2642,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2753,
"s": 2703,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Version Control Systems | 29 Jun, 2022
What is a “version control system”?
Version control systems are a category of software tools that helps in recording changes made to files by keeping a track of modifications done in the code.
Why Version Control system is so Important?
As we know that a software product is developed in collaboration by a group of developers they might be located at different locations and each one of them contributes to some specific kind of functionality/features. So in order to contribute to the product, they made modifications to the source code(either by adding or removing). A version control system is a kind of software that helps the developer team to efficiently communicate and manage(track) all the changes that have been made to the source code along with the information like who made and what changes have been made. A separate branch is created for every contributor who made the changes and the changes aren’t merged into the original source code unless all are analyzed as soon as the changes are green signaled they merged to the main source code. It not only keeps source code organized but also improves productivity by making the development process smooth.
Basically Version control system keeps track on changes made on a particular software and take a snapshot of every modification. Let’s suppose if a team of developer add some new functionalities in an application and the updated version is not working properly so as the version control system keeps track of our work so with the help of version control system we can omit the new changes and continue with the previous version.
Benefits of the version control system:
Enhances the project development speed by providing efficient collaboration,
Leverages the productivity, expedites product delivery, and skills of the employees through better communication and assistance,
Reduce possibilities of errors and conflicts meanwhile project development through traceability to every small change,
Employees or contributors of the project can contribute from anywhere irrespective of the different geographical locations through this VCS,
For each different contributor to the project, a different working copy is maintained and not merged to the main file unless the working copy is validated. The most popular example is Git, Helix core, Microsoft TFS,
Helps in recovery in case of any disaster or contingent situation,
Informs us about Who, What, When, Why changes have been made.
Use of Version Control System:
A repository: It can be thought of as a database of changes. It contains all the edits and historical versions (snapshots) of the project.
Copy of Work (sometimes called as checkout): It is the personal copy of all the files in a project. You can edit to this copy, without affecting the work of others and you can finally commit your changes to a repository when you are done making your changes.
Working in a group: Consider yourself working in a company where you are asked to work on some live project. You can’t change the main code as it is in production, and any change may cause inconvenience to the user, also you are working in a team so you need to collaborate with your team to and adapt their changes. Version control helps you with the, merging different requests to main repository without making any undesirable changes. You may test the functionalities without putting it live, and you don’t need to download and set up each time, just pull the changes and do the changes, test it and merge it back. It may be visualized as.
Types of Version Control Systems:
Local Version Control Systems
Centralized Version Control Systems
Distributed Version Control Systems
Local Version Control Systems: It is one of the simplest forms and has a database that kept all the changes to files under revision control. RCS is one of the most common VCS tools. It keeps patch sets (differences between files) in a special format on disk. By adding up all the patches it can then re-create what any file looked like at any point in time.
Centralized Version Control Systems: Centralized version control systems contain just one repository globally and every user need to commit for reflecting one’s changes in the repository. It is possible for others to see your changes by updating.
Two things are required to make your changes visible to others which are:
You commit
They update
The benefit of CVCS (Centralized Version Control Systems) makes collaboration amongst developers along with providing an insight to a certain extent on what everyone else is doing on the project. It allows administrators to fine-grained control over who can do what.
It has some downsides as well which led to the development of DVS. The most obvious is the single point of failure that the centralized repository represents if it goes down during that period collaboration and saving versioned changes is not possible. What if the hard disk of the central database becomes corrupted, and proper backups haven’t been kept? You lose absolutely everything.
Distributed Version Control Systems: Distributed version control systems contain multiple repositories. Each user has their own repository and working copy. Just committing your changes will not give others access to your changes. This is because commit will reflect those changes in your local repository and you need to push them in order to make them visible on the central repository. Similarly, When you update, you do not get others’ changes unless you have first pulled those changes into your repository.
To make your changes visible to others, 4 things are required:
You commit
You push
They pull
They update
The most popular distributed version control systems are Git, and Mercurial. They help us overcome the problem of single point of failure.
Purpose of Version Control:
Multiple people can work simultaneously on a single project. Everyone works on and edits their own copy of the files and it is up to them when they wish to share the changes made by them with the rest of the team.
It also enables one person to use multiple computers to work on a project, so it is valuable even if you are working by yourself.
It integrates the work that is done simultaneously by different members of the team. In some rare cases, when conflicting edits are made by two people to the same line of a file, then human assistance is requested by the version control system in deciding what should be done.
Version control provides access to the historical versions of a project. This is insurance against computer crashes or data loss. If any mistake is made, you can easily roll back to a previous version. It is also possible to undo specific edits that too without losing the work done in the meanwhile. It can be easily known when, why, and by whom any part of a file was edited.
madhav_mohan
mishrashubham
geeky01adarsh
GitHub
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Roadmap to Learn JavaScript For Beginners
How to float three div side by side using CSS?
How to create footer to stay at the bottom of a Web page?
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 90,
"s": 53,
"text": "What is a “version control system”? "
},
{
"code": null,
"e": 248,
"s": 90,
"text": "Version control systems are a category of software tools that helps in recording changes made to files by keeping a track of modifications done in the code. "
},
{
"code": null,
"e": 292,
"s": 248,
"text": "Why Version Control system is so Important?"
},
{
"code": null,
"e": 1224,
"s": 292,
"text": "As we know that a software product is developed in collaboration by a group of developers they might be located at different locations and each one of them contributes to some specific kind of functionality/features. So in order to contribute to the product, they made modifications to the source code(either by adding or removing). A version control system is a kind of software that helps the developer team to efficiently communicate and manage(track) all the changes that have been made to the source code along with the information like who made and what changes have been made. A separate branch is created for every contributor who made the changes and the changes aren’t merged into the original source code unless all are analyzed as soon as the changes are green signaled they merged to the main source code. It not only keeps source code organized but also improves productivity by making the development process smooth."
},
{
"code": null,
"e": 1653,
"s": 1224,
"text": "Basically Version control system keeps track on changes made on a particular software and take a snapshot of every modification. Let’s suppose if a team of developer add some new functionalities in an application and the updated version is not working properly so as the version control system keeps track of our work so with the help of version control system we can omit the new changes and continue with the previous version."
},
{
"code": null,
"e": 1693,
"s": 1653,
"text": "Benefits of the version control system:"
},
{
"code": null,
"e": 1770,
"s": 1693,
"text": "Enhances the project development speed by providing efficient collaboration,"
},
{
"code": null,
"e": 1899,
"s": 1770,
"text": "Leverages the productivity, expedites product delivery, and skills of the employees through better communication and assistance,"
},
{
"code": null,
"e": 2018,
"s": 1899,
"text": "Reduce possibilities of errors and conflicts meanwhile project development through traceability to every small change,"
},
{
"code": null,
"e": 2159,
"s": 2018,
"text": "Employees or contributors of the project can contribute from anywhere irrespective of the different geographical locations through this VCS,"
},
{
"code": null,
"e": 2375,
"s": 2159,
"text": "For each different contributor to the project, a different working copy is maintained and not merged to the main file unless the working copy is validated. The most popular example is Git, Helix core, Microsoft TFS,"
},
{
"code": null,
"e": 2442,
"s": 2375,
"text": "Helps in recovery in case of any disaster or contingent situation,"
},
{
"code": null,
"e": 2504,
"s": 2442,
"text": "Informs us about Who, What, When, Why changes have been made."
},
{
"code": null,
"e": 2536,
"s": 2504,
"text": "Use of Version Control System: "
},
{
"code": null,
"e": 2675,
"s": 2536,
"text": "A repository: It can be thought of as a database of changes. It contains all the edits and historical versions (snapshots) of the project."
},
{
"code": null,
"e": 2934,
"s": 2675,
"text": "Copy of Work (sometimes called as checkout): It is the personal copy of all the files in a project. You can edit to this copy, without affecting the work of others and you can finally commit your changes to a repository when you are done making your changes."
},
{
"code": null,
"e": 3579,
"s": 2934,
"text": "Working in a group: Consider yourself working in a company where you are asked to work on some live project. You can’t change the main code as it is in production, and any change may cause inconvenience to the user, also you are working in a team so you need to collaborate with your team to and adapt their changes. Version control helps you with the, merging different requests to main repository without making any undesirable changes. You may test the functionalities without putting it live, and you don’t need to download and set up each time, just pull the changes and do the changes, test it and merge it back. It may be visualized as. "
},
{
"code": null,
"e": 3616,
"s": 3581,
"text": "Types of Version Control Systems: "
},
{
"code": null,
"e": 3646,
"s": 3616,
"text": "Local Version Control Systems"
},
{
"code": null,
"e": 3682,
"s": 3646,
"text": "Centralized Version Control Systems"
},
{
"code": null,
"e": 3718,
"s": 3682,
"text": "Distributed Version Control Systems"
},
{
"code": null,
"e": 4077,
"s": 3718,
"text": "Local Version Control Systems: It is one of the simplest forms and has a database that kept all the changes to files under revision control. RCS is one of the most common VCS tools. It keeps patch sets (differences between files) in a special format on disk. By adding up all the patches it can then re-create what any file looked like at any point in time. "
},
{
"code": null,
"e": 4325,
"s": 4077,
"text": "Centralized Version Control Systems: Centralized version control systems contain just one repository globally and every user need to commit for reflecting one’s changes in the repository. It is possible for others to see your changes by updating. "
},
{
"code": null,
"e": 4401,
"s": 4325,
"text": "Two things are required to make your changes visible to others which are: "
},
{
"code": null,
"e": 4412,
"s": 4401,
"text": "You commit"
},
{
"code": null,
"e": 4424,
"s": 4412,
"text": "They update"
},
{
"code": null,
"e": 4692,
"s": 4424,
"text": "The benefit of CVCS (Centralized Version Control Systems) makes collaboration amongst developers along with providing an insight to a certain extent on what everyone else is doing on the project. It allows administrators to fine-grained control over who can do what. "
},
{
"code": null,
"e": 5081,
"s": 4692,
"text": "It has some downsides as well which led to the development of DVS. The most obvious is the single point of failure that the centralized repository represents if it goes down during that period collaboration and saving versioned changes is not possible. What if the hard disk of the central database becomes corrupted, and proper backups haven’t been kept? You lose absolutely everything. "
},
{
"code": null,
"e": 5595,
"s": 5081,
"text": "Distributed Version Control Systems: Distributed version control systems contain multiple repositories. Each user has their own repository and working copy. Just committing your changes will not give others access to your changes. This is because commit will reflect those changes in your local repository and you need to push them in order to make them visible on the central repository. Similarly, When you update, you do not get others’ changes unless you have first pulled those changes into your repository. "
},
{
"code": null,
"e": 5660,
"s": 5595,
"text": "To make your changes visible to others, 4 things are required: "
},
{
"code": null,
"e": 5671,
"s": 5660,
"text": "You commit"
},
{
"code": null,
"e": 5680,
"s": 5671,
"text": "You push"
},
{
"code": null,
"e": 5690,
"s": 5680,
"text": "They pull"
},
{
"code": null,
"e": 5702,
"s": 5690,
"text": "They update"
},
{
"code": null,
"e": 5843,
"s": 5702,
"text": "The most popular distributed version control systems are Git, and Mercurial. They help us overcome the problem of single point of failure. "
},
{
"code": null,
"e": 5872,
"s": 5843,
"text": "Purpose of Version Control: "
},
{
"code": null,
"e": 6086,
"s": 5872,
"text": "Multiple people can work simultaneously on a single project. Everyone works on and edits their own copy of the files and it is up to them when they wish to share the changes made by them with the rest of the team."
},
{
"code": null,
"e": 6216,
"s": 6086,
"text": "It also enables one person to use multiple computers to work on a project, so it is valuable even if you are working by yourself."
},
{
"code": null,
"e": 6493,
"s": 6216,
"text": "It integrates the work that is done simultaneously by different members of the team. In some rare cases, when conflicting edits are made by two people to the same line of a file, then human assistance is requested by the version control system in deciding what should be done."
},
{
"code": null,
"e": 6871,
"s": 6493,
"text": "Version control provides access to the historical versions of a project. This is insurance against computer crashes or data loss. If any mistake is made, you can easily roll back to a previous version. It is also possible to undo specific edits that too without losing the work done in the meanwhile. It can be easily known when, why, and by whom any part of a file was edited."
},
{
"code": null,
"e": 6884,
"s": 6871,
"text": "madhav_mohan"
},
{
"code": null,
"e": 6898,
"s": 6884,
"text": "mishrashubham"
},
{
"code": null,
"e": 6912,
"s": 6898,
"text": "geeky01adarsh"
},
{
"code": null,
"e": 6919,
"s": 6912,
"text": "GitHub"
},
{
"code": null,
"e": 6936,
"s": 6919,
"text": "Web Technologies"
},
{
"code": null,
"e": 7034,
"s": 6936,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7095,
"s": 7034,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 7138,
"s": 7095,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 7210,
"s": 7138,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 7250,
"s": 7210,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 7274,
"s": 7250,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 7316,
"s": 7274,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 7363,
"s": 7316,
"text": "How to float three div side by side using CSS?"
},
{
"code": null,
"e": 7421,
"s": 7363,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 7462,
"s": 7421,
"text": "Difference Between PUT and PATCH Request"
}
] |
restrict keyword in C | 26 Jul, 2021
In the C programming language (after 99 standard), a new keyword is introduced known as restrict.
restrict keyword is mainly used in pointer declarations as a type qualifier for pointers.
It doesn’t add any new functionality. It is only a way for programmer to inform about an optimization that compiler can make.
When we use restrict with a pointer ptr, it tells the compiler that ptr is the only way to access the object pointed by it, in other words, there’s no other pointer pointing to the same object i.e. restrict keyword specifies that a particular pointer argument does not alias any other and the compiler doesn’t need to add any additional checks.
If a programmer uses restrict keyword and violate the above condition, the result is undefined behavior.
restrict is not supported by C++. It is a C only keyword.
C
// C program to use restrict keyword.#include <stdio.h> // Note that the purpose of restrict is to// show only syntax. It doesn't change anything// in output (or logic). It is just a way for// programmer to tell compiler about an// optimizationvoid use(int* a, int* b, int* restrict c){ *a += *c; // Since c is restrict, compiler will // not reload value at address c in // its assembly code. Therefore generated // assembly code is optimized *b += *c; } int main(void){ int a = 50, b = 60, c = 70; use(&a, &b, &c); printf("%d %d %d", a, b, c); return 0;}
Output:
120 130 70
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
gauravpathak129
C-Data Types
C-Pointers
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
Memory Layout of C Programs | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 154,
"s": 54,
"text": "In the C programming language (after 99 standard), a new keyword is introduced known as restrict. "
},
{
"code": null,
"e": 244,
"s": 154,
"text": "restrict keyword is mainly used in pointer declarations as a type qualifier for pointers."
},
{
"code": null,
"e": 370,
"s": 244,
"text": "It doesn’t add any new functionality. It is only a way for programmer to inform about an optimization that compiler can make."
},
{
"code": null,
"e": 715,
"s": 370,
"text": "When we use restrict with a pointer ptr, it tells the compiler that ptr is the only way to access the object pointed by it, in other words, there’s no other pointer pointing to the same object i.e. restrict keyword specifies that a particular pointer argument does not alias any other and the compiler doesn’t need to add any additional checks."
},
{
"code": null,
"e": 820,
"s": 715,
"text": "If a programmer uses restrict keyword and violate the above condition, the result is undefined behavior."
},
{
"code": null,
"e": 878,
"s": 820,
"text": "restrict is not supported by C++. It is a C only keyword."
},
{
"code": null,
"e": 882,
"s": 880,
"text": "C"
},
{
"code": "// C program to use restrict keyword.#include <stdio.h> // Note that the purpose of restrict is to// show only syntax. It doesn't change anything// in output (or logic). It is just a way for// programmer to tell compiler about an// optimizationvoid use(int* a, int* b, int* restrict c){ *a += *c; // Since c is restrict, compiler will // not reload value at address c in // its assembly code. Therefore generated // assembly code is optimized *b += *c; } int main(void){ int a = 50, b = 60, c = 70; use(&a, &b, &c); printf(\"%d %d %d\", a, b, c); return 0;}",
"e": 1469,
"s": 882,
"text": null
},
{
"code": null,
"e": 1479,
"s": 1469,
"text": "Output: "
},
{
"code": null,
"e": 1490,
"s": 1479,
"text": "120 130 70"
},
{
"code": null,
"e": 1917,
"s": 1490,
"text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 1933,
"s": 1917,
"text": "gauravpathak129"
},
{
"code": null,
"e": 1946,
"s": 1933,
"text": "C-Data Types"
},
{
"code": null,
"e": 1957,
"s": 1946,
"text": "C-Pointers"
},
{
"code": null,
"e": 1968,
"s": 1957,
"text": "C Language"
},
{
"code": null,
"e": 2066,
"s": 1968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2083,
"s": 2066,
"text": "Substring in C++"
},
{
"code": null,
"e": 2118,
"s": 2083,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 2140,
"s": 2118,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 2186,
"s": 2140,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 2231,
"s": 2186,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 2256,
"s": 2231,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2304,
"s": 2256,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2332,
"s": 2304,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 2359,
"s": 2332,
"text": "Enumeration (or enum) in C"
}
] |
minsize() method in Tkinter | Python | 29 Nov, 2021
In Tkinter, minsize() method is used to set the minimum size of the Tkinter window. Using this method user can set window’s initialized size to its minimum size, and still be able to maximize and scale the window larger.
Syntax:
master.minsize(height, width)
Here, height and width are in pixels.
Code #1: Root window without minimum size that means you can shrink window as much you want.
# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import *from time import strftime # creating tkinter windowroot = Tk() # Adding widgets to the root windowLabel(root, text = 'GeeksforGeeks', font =('Verdana', 15)).pack(side = TOP, pady = 10) Button(root, text = 'Click Me !').pack(side = TOP) mainloop()
Output:Initial root window without alteration in size
Root window after shrunken down, see the window is completely shrunken because it has no minimum geometry.
Code #2: Root window with minimum size.
# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import * from time import strftime # creating tkinter windowroot = Tk() # setting the minimum size of the root windowroot.minsize(150, 100) # Adding widgets to the root windowLabel(root, text = 'GeeksforGeeks', font =('Verdana', 15)).pack(side = TOP, pady = 10)Button(root, text = 'Click Me !').pack(side = TOP) mainloop()
Output:Initial window
Expanded window (we can expand window as much as we want because we haven’t set the maximum size of the window).
Window shrunken to it’s minimum size (one cannot shrunk it any further).
nidhi_biet
Python-gui
Python-tkinter
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Create a Pandas DataFrame from Lists
Python | os.path.join() method | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 273,
"s": 52,
"text": "In Tkinter, minsize() method is used to set the minimum size of the Tkinter window. Using this method user can set window’s initialized size to its minimum size, and still be able to maximize and scale the window larger."
},
{
"code": null,
"e": 281,
"s": 273,
"text": "Syntax:"
},
{
"code": null,
"e": 311,
"s": 281,
"text": "master.minsize(height, width)"
},
{
"code": null,
"e": 349,
"s": 311,
"text": "Here, height and width are in pixels."
},
{
"code": null,
"e": 442,
"s": 349,
"text": "Code #1: Root window without minimum size that means you can shrink window as much you want."
},
{
"code": "# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import *from time import strftime # creating tkinter windowroot = Tk() # Adding widgets to the root windowLabel(root, text = 'GeeksforGeeks', font =('Verdana', 15)).pack(side = TOP, pady = 10) Button(root, text = 'Click Me !').pack(side = TOP) mainloop()",
"e": 797,
"s": 442,
"text": null
},
{
"code": null,
"e": 851,
"s": 797,
"text": "Output:Initial root window without alteration in size"
},
{
"code": null,
"e": 958,
"s": 851,
"text": "Root window after shrunken down, see the window is completely shrunken because it has no minimum geometry."
},
{
"code": null,
"e": 998,
"s": 958,
"text": "Code #2: Root window with minimum size."
},
{
"code": "# importing only those functions# which are neededfrom tkinter import * from tkinter.ttk import * from time import strftime # creating tkinter windowroot = Tk() # setting the minimum size of the root windowroot.minsize(150, 100) # Adding widgets to the root windowLabel(root, text = 'GeeksforGeeks', font =('Verdana', 15)).pack(side = TOP, pady = 10)Button(root, text = 'Click Me !').pack(side = TOP) mainloop()",
"e": 1421,
"s": 998,
"text": null
},
{
"code": null,
"e": 1443,
"s": 1421,
"text": "Output:Initial window"
},
{
"code": null,
"e": 1556,
"s": 1443,
"text": "Expanded window (we can expand window as much as we want because we haven’t set the maximum size of the window)."
},
{
"code": null,
"e": 1629,
"s": 1556,
"text": "Window shrunken to it’s minimum size (one cannot shrunk it any further)."
},
{
"code": null,
"e": 1640,
"s": 1629,
"text": "nidhi_biet"
},
{
"code": null,
"e": 1651,
"s": 1640,
"text": "Python-gui"
},
{
"code": null,
"e": 1666,
"s": 1651,
"text": "Python-tkinter"
},
{
"code": null,
"e": 1673,
"s": 1666,
"text": "Python"
},
{
"code": null,
"e": 1771,
"s": 1673,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1789,
"s": 1771,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1831,
"s": 1789,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1857,
"s": 1831,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1889,
"s": 1857,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1918,
"s": 1889,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1945,
"s": 1918,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1966,
"s": 1945,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1989,
"s": 1966,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2026,
"s": 1989,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Python – all() function | 15 Aug, 2021
The all() function is an inbuilt function in Python which returns true if all the elements of a given iterable( List, Dictionary, Tuple, set, etc) are True else it returns False. It also returns True if the iterable object is empty.
Syntax: all( iterable )
Parameters: Iterable: It is an iterable object such as a dictionary,tuple,list,set,etc.
Example #1: Working of all() with Lists:
Code:
Python3
# All elements of list are truel = [4, 5, 1]print(all(l)) # All elements of list are falsel = [0, 0, False]print(all(l)) # Some elements of list are# true while others are falsel = [1, 0, 6, 7, False]print(all(l)) # Empty Listl = []print(all(l))
Output:
True
False
False
True
Example #2: Working of all() with Tuples.
Python3
# All elements of tuple are truet = (2, 4, 6)print(all(t)) # All elements of tuple are falset = (0, False, False)print(all(t)) # Some elements of tuple# are true while others are falset = (5, 0, 3, 1, False)print(all(t)) # Empty tuplet = ()print(all(t))
Output:
True
False
False
True
Example #3: Working of all() with Sets.
Python3
# All elements of set are trues = {1, 1, 3}print(all(s)) # All elements of set are falses = {0, 0, False}print(all(s)) # Some elements of set# are true while others are falses = {1, 2, 0, 8, False}print(all(s)) # Empty sets = {}print(all(s))
Output:
True
False
False
True
Example #4: Working of all() with Dictionaries.
Note: In the case of a dictionary if all the keys of the dictionary are true or the dictionary is empty the all() returns true else it returns false.
Python3
# All elements of dictionary are trued = {1: "Hello", 2: "Hi"}print(all(d)) # All elements of dictionary are falsed = {0: "Hello", False: "Hi"}print(all(d)) # Some elements of dictionary# are true while others are falsed = {0: "Salut", 1: "Hello", 2: "Hi"}print(all(d)) # Empty dictionaryd = {}print(all(d))
Output:
True
False
False
True
Example #5: Working of all() with Strings.
Python3
# Non-Empty Strings = "Hi There!"print(all(s)) # Non-Empty Strings = "000"print(all(s)) # Empty strings = ""print(all(s))
Output:
True
True
True
dannyjc16
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n15 Aug, 2021"
},
{
"code": null,
"e": 286,
"s": 53,
"text": "The all() function is an inbuilt function in Python which returns true if all the elements of a given iterable( List, Dictionary, Tuple, set, etc) are True else it returns False. It also returns True if the iterable object is empty."
},
{
"code": null,
"e": 311,
"s": 286,
"text": "Syntax: all( iterable ) "
},
{
"code": null,
"e": 433,
"s": 311,
"text": "Parameters: Iterable: It is an iterable object such as a dictionary,tuple,list,set,etc. "
},
{
"code": null,
"e": 474,
"s": 433,
"text": "Example #1: Working of all() with Lists:"
},
{
"code": null,
"e": 480,
"s": 474,
"text": "Code:"
},
{
"code": null,
"e": 488,
"s": 480,
"text": "Python3"
},
{
"code": "# All elements of list are truel = [4, 5, 1]print(all(l)) # All elements of list are falsel = [0, 0, False]print(all(l)) # Some elements of list are# true while others are falsel = [1, 0, 6, 7, False]print(all(l)) # Empty Listl = []print(all(l))",
"e": 734,
"s": 488,
"text": null
},
{
"code": null,
"e": 742,
"s": 734,
"text": "Output:"
},
{
"code": null,
"e": 764,
"s": 742,
"text": "True\nFalse\nFalse\nTrue"
},
{
"code": null,
"e": 806,
"s": 764,
"text": "Example #2: Working of all() with Tuples."
},
{
"code": null,
"e": 814,
"s": 806,
"text": "Python3"
},
{
"code": "# All elements of tuple are truet = (2, 4, 6)print(all(t)) # All elements of tuple are falset = (0, False, False)print(all(t)) # Some elements of tuple# are true while others are falset = (5, 0, 3, 1, False)print(all(t)) # Empty tuplet = ()print(all(t))",
"e": 1068,
"s": 814,
"text": null
},
{
"code": null,
"e": 1076,
"s": 1068,
"text": "Output:"
},
{
"code": null,
"e": 1098,
"s": 1076,
"text": "True\nFalse\nFalse\nTrue"
},
{
"code": null,
"e": 1138,
"s": 1098,
"text": "Example #3: Working of all() with Sets."
},
{
"code": null,
"e": 1146,
"s": 1138,
"text": "Python3"
},
{
"code": "# All elements of set are trues = {1, 1, 3}print(all(s)) # All elements of set are falses = {0, 0, False}print(all(s)) # Some elements of set# are true while others are falses = {1, 2, 0, 8, False}print(all(s)) # Empty sets = {}print(all(s))",
"e": 1388,
"s": 1146,
"text": null
},
{
"code": null,
"e": 1396,
"s": 1388,
"text": "Output:"
},
{
"code": null,
"e": 1418,
"s": 1396,
"text": "True\nFalse\nFalse\nTrue"
},
{
"code": null,
"e": 1466,
"s": 1418,
"text": "Example #4: Working of all() with Dictionaries."
},
{
"code": null,
"e": 1616,
"s": 1466,
"text": "Note: In the case of a dictionary if all the keys of the dictionary are true or the dictionary is empty the all() returns true else it returns false."
},
{
"code": null,
"e": 1624,
"s": 1616,
"text": "Python3"
},
{
"code": "# All elements of dictionary are trued = {1: \"Hello\", 2: \"Hi\"}print(all(d)) # All elements of dictionary are falsed = {0: \"Hello\", False: \"Hi\"}print(all(d)) # Some elements of dictionary# are true while others are falsed = {0: \"Salut\", 1: \"Hello\", 2: \"Hi\"}print(all(d)) # Empty dictionaryd = {}print(all(d))",
"e": 1932,
"s": 1624,
"text": null
},
{
"code": null,
"e": 1940,
"s": 1932,
"text": "Output:"
},
{
"code": null,
"e": 1962,
"s": 1940,
"text": "True\nFalse\nFalse\nTrue"
},
{
"code": null,
"e": 2005,
"s": 1962,
"text": "Example #5: Working of all() with Strings."
},
{
"code": null,
"e": 2013,
"s": 2005,
"text": "Python3"
},
{
"code": "# Non-Empty Strings = \"Hi There!\"print(all(s)) # Non-Empty Strings = \"000\"print(all(s)) # Empty strings = \"\"print(all(s))",
"e": 2135,
"s": 2013,
"text": null
},
{
"code": null,
"e": 2143,
"s": 2135,
"text": "Output:"
},
{
"code": null,
"e": 2158,
"s": 2143,
"text": "True\nTrue\nTrue"
},
{
"code": null,
"e": 2168,
"s": 2158,
"text": "dannyjc16"
},
{
"code": null,
"e": 2194,
"s": 2168,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 2201,
"s": 2194,
"text": "Python"
}
] |
Minimum Cost Path | Practice | GeeksforGeeks | Given a square grid of size N, each cell of which contains integer cost which represents a cost to traverse through that cell, we need to find a path from top left cell to bottom right cell by which the total cost incurred is minimum.
From the cell (i,j) we can go (i,j-1), (i, j+1), (i-1, j), (i+1, j).
Note: It is assumed that negative cost cycles do not exist in the input matrix.
Example 1:
Input: grid = {{9,4,9,9},{6,7,6,4},
{8,3,3,7},{7,4,9,10}}
Output: 43
Explanation: The grid is-
9 4 9 9
6 7 6 4
8 3 3 7
7 4 9 10
The minimum cost is-
9 + 4 + 7 + 3 + 3 + 7 + 10 = 43.
Example 2:
Input: grid = {{4,4},{3,7}}
Output: 14
Explanation: The grid is-
4 4
3 7
The minimum cost is- 4 + 3 + 7 = 14.
Your Task:
You don't need to read or print anything. Your task is to complete the function minimumCostPath() which takes grid as input parameter and returns the minimum cost to react at bottom right cell from top left cell.
Expected Time Compelxity: O(n2*log(n))
Expected Auxiliary Space: O(n2)
Constraints:
1 ≤ n ≤ 500
1 ≤ cost of cells ≤ 1000
0
ghanshyamsinghal22in 10 hours
why this is showing runtime error please anyone help
class Solution{ public: //Function to return the minimum cost to react at bottom//right cell from top left cell.bool ok(int x,int y,int n,int m){ if((x>=0&&x<n)&&(y>=0&&y<m)){ return 1; } return 0;} int minimumCostPath(vector<vector<int>>& grid) { multiset<vector<int>> d; vector<vector<int>> b; int n = a.size(); int m = a[0].size(); int i; for(i=0;i<n;i++){ vector <int> c (m,INT_MAX); b.push_back(c); } d.insert({a[0][0],0,0}); while(d.size()){ vector <int> x= *d.begin(); if(b[x[1]][x[2]]>x[0]){ b[x[1]][x[2]]=x[0]; d.erase(d.begin()); if(ok(x[1]-1,x[2],n,m)&&b[x[1]-1][x[2]]>x[0]+a[x[1]-1][x[2]]){ d.insert({x[0]+a[x[1]-1][x[2]],x[1]-1,x[2]}); } if(ok(x[1],x[2]+1,n,m)&&b[x[1]][x[2]+1]>x[0]+a[x[1]][x[2]+1]){ d.insert({x[0]+a[x[1]][x[2]+1],x[1],x[2]+1}); } if(ok(x[1]+1,x[2],n,m)&&b[x[1]+1][x[2]]>x[0]+a[x[1]+1][x[2]]){ d.insert({x[0]+a[x[1]+1][x[2]],x[1]+1,x[2]}); } if(ok(x[1],x[2]-1,n,m)&&b[x[1]][x[2]-1]>x[0]+a[x[1]][x[2]-1]){ d.insert({x[0]+a[x[1]][x[2]-1],x[1],x[2]-1}); } }else{ d.erase(d.begin()); } } // vector <int> x= *d.begin(); return b[n-1][m-1]; }};
0
trilokjain3 days ago
// i think this is best code for this but this give error at some edge case
class Solution{ public: //Function to return the minimum cost to react at bottom//right cell from top left cell.int min_cost(int row,int column, vector<vector<int>>& grid, vector<vector<int>>& a,int n){ if(row==0 && column > 0) { return a[row][column] = min_cost(row,column-1,grid,a,n)+grid[row][column]; } if(column==0 && row > 0) { return a[row][column] = min_cost(row-1,column,grid,a,n)+grid[row][column]; } if( row < 0 || column<0||row>n-1 || column>n-1) return 0; if(row==0 && column== 0) return a[row][column]= grid[row][column]; if(a[row][column] != -1) return a[row][column]; int x=min_cost(row-1,column,grid,a,n); int y = min_cost(row,column-1,grid,a,n); a[row][column] = min(x,y)+grid[row][column]; return a[row][column];} int minimumCostPath(vector<vector<int>>& grid) { // Code here int n= grid[0].size(); vector<vector<int>>a(n,vector<int>(n,-1)); return min_cost(n-1,n-1,grid,a,n); }};
+2
prashan1um5l5 days ago
C++ SOLUTION ;)
int n=grid.size(); int m=grid[0].size(); int ans=0; int dist[n][m]; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ dist[i][j]=INT_MAX; } }priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>>pq; dist[0][0]=grid[0][0]; pq.push({dist[0][0], {0, 0}}); int dx[4]={0, 0, -1, 1}; int dy[4]={-1, 1, 0, 0}; while(pq.empty()==false){ auto x=pq.top(); pq.pop(); int cost=x.first; auto y=x.second; int i=y.first; int j=y.second; ans+=cost; if(i==n-1 && j==m-1){ break; } //visted[i][j]=true; for(int k=0; k<4; k++){ int u=i+dx[k]; int v=j+dy[k]; if(u>=0 && u<n && v>=0 && v<m ){ if(dist[u][v]>=dist[i][j]+ grid[u][v]){ dist[u][v]=dist[i][j]+grid[u][v]; pq.push({dist[u][v], {u, v}}); } } } } return dist[n-1][m-1]; //return ans; }
0
mishraaman4356 days ago
java Dijkstra + shortest path
6-7 sec
class Solution{
public int minimumCostPath(int[][] g){
int n=g.length;
int m=g[0].length;
boolean [][] v= new boolean [n][m];
int dx[]={1, -1, 0,0};
int dy[]= {0,0,-1,1};
PriorityQueue <pair> q= new PriorityQueue<pair>((e,f)->(e.z-f.z));
q.offer(new pair(0,0,g[0][0]));
while(!q.isEmpty()){
pair c=q.poll();
if(c.x==n-1 && c.y==m-1) return c.z;
for(int i=0; i<4; i++){
int a= c.x+dx[i];
int b= c.y+dy[i];
if(a>=n ||b>=m ||a<0 ||b<0 ||v[a][b]) continue;
v[a][b]=true;
q.offer(new pair(a,b,c.z+g[a][b]));
}
}
return -1;
}
class pair{
int x;
int y;
int z;
pair(int x, int y, int z){
this.x=x;
this.y=y;
this.z=z;
}
}
}
0
sidsahu09026 days ago
Can anyone help me, I am getting Runtime error in this code
int sol(int i, int j, vector<vector<int>>&grid, vector<vector<int>>&dp,int n){
if(i>n-1 || j>n-1 || i<0 || j<0 ){
return 1e6;
}
if(i==0 && j==0){
return grid[i][j];
}
if(dp[i][j]!=-1){
return dp[i][j];
}
int up = grid[i][j] + sol(i-1, j, grid, dp, n);
iny left = grid[i][j]+ sol(i, j-1, grid, dp, n);
int right = grid[i][j] + sol(i, j+1, grid, dp, n);
int down = grid[i][j] + sol(i+1, j, grid, dp, n);
return dp[i][j]= min(left, min(right, min(up, down)));
}
int minimumCostPath(vector<vector<int>>& grid)
{
// Code here
int n = grid[0].size();
vector<vector<int>>dp(n, vector<int>(n, -1));
return sol(n-1, n-1, grid, dp, n);
}
0
gaurpiyush0011 week ago
Is this Problem can be by Backtracking???,If Yes then why we are using graph??
-1
dflag441 week ago
can anyone tell problem in this approach
int helper(int i,int j,int n,int m,vector<vector<int>>&grid,vector<vector<int>>&dp, vector<vector<bool>>&vst){ if(i<0||j<0||i>n||j>m||vst[i][j])return 1000000; if(dp[i][j]!=-1)return dp[i][j]; if(i==n && j==m)return grid[i][j]; vst[i][j]=true; int x= grid[i][j]+min({ helper(i,j-1,n,m,grid,dp,vst), helper(i,j+1,n,m,grid,dp,vst), helper(i-1,j,n,m,grid,dp,vst), helper(i+1,j,n,m,grid,dp,vst), }); vst[i][j]=false; return dp[i][j]= x; } int minimumCostPath(vector<vector<int>>& grid) { int n=grid.size(); int m=grid[0].size(); vector<vector<int>>dp(n,vector<int>(m,-1)); vector<vector<bool>>vst(n,vector<bool>(m,false)); n--; m--; return helper(0,0,n,m,grid,dp,vst); }
-1
spiderman691 week ago
Code without using pairs
struct cell{ int x; int y; int weight; cell(int x,int y, int weight) { this->x = x; this->y = y; this->weight = weight; } }; struct cellcomp{ bool operator()(cell c1,cell c2) { return c1.weight>c2.weight; } }; bool isvalid(int i, int j, int n) { if(i>=0 && i<n && j>=0 && j<n) { return true; }else return false; } int minimumCostPath(vector<vector<int>>& grid) { // Code int node = grid.size(); vector<vector<bool>> visited(node,vector<bool>(node,false)); vector<vector<int>> weight(node,vector<int>(node,1e8)); int xar[4] = {0,-1,0,1}; int yar[4] = {-1,0,1,0}; weight[0][0] = grid[0][0]; priority_queue<cell,vector<cell>,cellcomp> pq; pq.push({0,0,grid[0][0]}); while(!pq.empty()) { cell temp = pq.top(); pq.pop(); int curr_x = temp.x; int curr_y = temp.y; if(visited[curr_x][curr_y]) continue; visited[curr_x][curr_y] = true; for(int i=0;i<4;i++) { int next_x = curr_x +xar[i]; int next_y = curr_y + yar[i]; if(isvalid(next_x,next_y,node) && !visited[next_x][next_y]) { if(weight[next_x][next_y] > (weight[curr_x][curr_y]+ grid[next_x][next_y])) { weight[next_x][next_y]= weight[curr_x][curr_y]+ grid[next_x][next_y]; } pq.push({next_x,next_y,weight[next_x][next_y]}); } } } return weight[node-1][node-1]; }
-1
anuragtiwariug201 week ago
Anyone know why my code give runtime error
int t[1000][1000];int solve(int i,int j,vector<vector<int>> &grid){ if(i==grid.size()-1 && j==grid[0].size()-1) { return grid[i][j]; } if(i>=grid.size()||j>=grid[0].size()) { return 1e9; } if(t[i][j]!=-1) { return t[i][j]; } int a=grid[i][j]+solve(i+1,j,grid); int b=0,c=0; if(i>1) { b=grid[i][j]+solve(i-1,j,grid); } if(j>1) { c=grid[i][j]+solve(i,j-1,grid); } int d=grid[i][j]+solve(i,j+1,grid); return t[i][j]=min({a,b,c,d});} int minimumCostPath(vector<vector<int>>& grid) { memset(t,-1,sizeof(t)); return solve(0,0,grid); }
+3
roboto7o32oo32 weeks ago
Clean C++ Solution ✨ ✨ (Using Dijkstra's Algorithm and Priority Queue)
class Solution
{
public:
bool isValidPos(pair<int,int> pos, int n){
int x = pos.first;
int y = pos.second;
if(x>=0 and x<n and y>=0 and y<n){
return true;
}
return false;
}
int minimumCostPath(vector<vector<int>>& grid)
{
int n = grid.size();
priority_queue<pair<int,pair<int,int>>, vector<pair<int,pair<int,int>>>, greater<pair<int,pair<int,int>>>> pq;
vector<vector<int>> distance(n, vector<int>(n, INT_MAX));
vector<pair<int,int>> moves{{1,0}, {0,1}, {-1,0}, {0,-1}};
pq.push({grid[0][0], {0,0}});
distance[0][0] = grid[0][0];
while(not pq.empty()){
pair<int,pair<int,int>> curr = pq.top();
pq.pop();
int dist = curr.first;
pair<int,int> pos = curr.second;
int x = pos.first;
int y = pos.second;
for(pair<int,int> move : moves){
int nx = x + move.first;
int ny = y + move.second;
if(isValidPos({nx,ny}, n) and distance[nx][ny] > dist + grid[nx][ny]){
distance[nx][ny] = dist + grid[nx][ny];
pq.push({distance[nx][ny], {nx,ny}});
}
}
}
return distance[n-1][n-1];
}
};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints. | [
{
"code": null,
"e": 543,
"s": 238,
"text": "Given a square grid of size N, each cell of which contains integer cost which represents a cost to traverse through that cell, we need to find a path from top left cell to bottom right cell by which the total cost incurred is minimum.\nFrom the cell (i,j) we can go (i,j-1), (i, j+1), (i-1, j), (i+1, j). "
},
{
"code": null,
"e": 625,
"s": 543,
"text": "Note: It is assumed that negative cost cycles do not exist in the input matrix.\n "
},
{
"code": null,
"e": 636,
"s": 625,
"text": "Example 1:"
},
{
"code": null,
"e": 819,
"s": 636,
"text": "Input: grid = {{9,4,9,9},{6,7,6,4},\n{8,3,3,7},{7,4,9,10}}\nOutput: 43\nExplanation: The grid is-\n9 4 9 9\n6 7 6 4\n8 3 3 7\n7 4 9 10\nThe minimum cost is-\n9 + 4 + 7 + 3 + 3 + 7 + 10 = 43.\n"
},
{
"code": null,
"e": 830,
"s": 819,
"text": "Example 2:"
},
{
"code": null,
"e": 941,
"s": 830,
"text": "Input: grid = {{4,4},{3,7}}\nOutput: 14\nExplanation: The grid is-\n4 4\n3 7\nThe minimum cost is- 4 + 3 + 7 = 14.\n"
},
{
"code": null,
"e": 1169,
"s": 943,
"text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function minimumCostPath() which takes grid as input parameter and returns the minimum cost to react at bottom right cell from top left cell.\n "
},
{
"code": null,
"e": 1243,
"s": 1169,
"text": "Expected Time Compelxity: O(n2*log(n))\nExpected Auxiliary Space: O(n2) \n "
},
{
"code": null,
"e": 1293,
"s": 1243,
"text": "Constraints:\n1 ≤ n ≤ 500\n1 ≤ cost of cells ≤ 1000"
},
{
"code": null,
"e": 1295,
"s": 1293,
"text": "0"
},
{
"code": null,
"e": 1325,
"s": 1295,
"text": "ghanshyamsinghal22in 10 hours"
},
{
"code": null,
"e": 1379,
"s": 1325,
"text": "why this is showing runtime error please anyone help "
},
{
"code": null,
"e": 2846,
"s": 1379,
"text": "class Solution{ public: //Function to return the minimum cost to react at bottom//right cell from top left cell.bool ok(int x,int y,int n,int m){ if((x>=0&&x<n)&&(y>=0&&y<m)){ return 1; } return 0;} int minimumCostPath(vector<vector<int>>& grid) { multiset<vector<int>> d; vector<vector<int>> b; int n = a.size(); int m = a[0].size(); int i; for(i=0;i<n;i++){ vector <int> c (m,INT_MAX); b.push_back(c); } d.insert({a[0][0],0,0}); while(d.size()){ vector <int> x= *d.begin(); if(b[x[1]][x[2]]>x[0]){ b[x[1]][x[2]]=x[0]; d.erase(d.begin()); if(ok(x[1]-1,x[2],n,m)&&b[x[1]-1][x[2]]>x[0]+a[x[1]-1][x[2]]){ d.insert({x[0]+a[x[1]-1][x[2]],x[1]-1,x[2]}); } if(ok(x[1],x[2]+1,n,m)&&b[x[1]][x[2]+1]>x[0]+a[x[1]][x[2]+1]){ d.insert({x[0]+a[x[1]][x[2]+1],x[1],x[2]+1}); } if(ok(x[1]+1,x[2],n,m)&&b[x[1]+1][x[2]]>x[0]+a[x[1]+1][x[2]]){ d.insert({x[0]+a[x[1]+1][x[2]],x[1]+1,x[2]}); } if(ok(x[1],x[2]-1,n,m)&&b[x[1]][x[2]-1]>x[0]+a[x[1]][x[2]-1]){ d.insert({x[0]+a[x[1]][x[2]-1],x[1],x[2]-1}); } }else{ d.erase(d.begin()); } } // vector <int> x= *d.begin(); return b[n-1][m-1]; }};"
},
{
"code": null,
"e": 2848,
"s": 2846,
"text": "0"
},
{
"code": null,
"e": 2869,
"s": 2848,
"text": "trilokjain3 days ago"
},
{
"code": null,
"e": 2945,
"s": 2869,
"text": "// i think this is best code for this but this give error at some edge case"
},
{
"code": null,
"e": 3969,
"s": 2949,
"text": "class Solution{ public: //Function to return the minimum cost to react at bottom//right cell from top left cell.int min_cost(int row,int column, vector<vector<int>>& grid, vector<vector<int>>& a,int n){ if(row==0 && column > 0) { return a[row][column] = min_cost(row,column-1,grid,a,n)+grid[row][column]; } if(column==0 && row > 0) { return a[row][column] = min_cost(row-1,column,grid,a,n)+grid[row][column]; } if( row < 0 || column<0||row>n-1 || column>n-1) return 0; if(row==0 && column== 0) return a[row][column]= grid[row][column]; if(a[row][column] != -1) return a[row][column]; int x=min_cost(row-1,column,grid,a,n); int y = min_cost(row,column-1,grid,a,n); a[row][column] = min(x,y)+grid[row][column]; return a[row][column];} int minimumCostPath(vector<vector<int>>& grid) { // Code here int n= grid[0].size(); vector<vector<int>>a(n,vector<int>(n,-1)); return min_cost(n-1,n-1,grid,a,n); }};"
},
{
"code": null,
"e": 3972,
"s": 3969,
"text": "+2"
},
{
"code": null,
"e": 3995,
"s": 3972,
"text": "prashan1um5l5 days ago"
},
{
"code": null,
"e": 4011,
"s": 3995,
"text": "C++ SOLUTION ;)"
},
{
"code": null,
"e": 5120,
"s": 4011,
"text": "int n=grid.size(); int m=grid[0].size(); int ans=0; int dist[n][m]; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ dist[i][j]=INT_MAX; } }priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>>pq; dist[0][0]=grid[0][0]; pq.push({dist[0][0], {0, 0}}); int dx[4]={0, 0, -1, 1}; int dy[4]={-1, 1, 0, 0}; while(pq.empty()==false){ auto x=pq.top(); pq.pop(); int cost=x.first; auto y=x.second; int i=y.first; int j=y.second; ans+=cost; if(i==n-1 && j==m-1){ break; } //visted[i][j]=true; for(int k=0; k<4; k++){ int u=i+dx[k]; int v=j+dy[k]; if(u>=0 && u<n && v>=0 && v<m ){ if(dist[u][v]>=dist[i][j]+ grid[u][v]){ dist[u][v]=dist[i][j]+grid[u][v]; pq.push({dist[u][v], {u, v}}); } } } } return dist[n-1][m-1]; //return ans; }"
},
{
"code": null,
"e": 5122,
"s": 5120,
"text": "0"
},
{
"code": null,
"e": 5146,
"s": 5122,
"text": "mishraaman4356 days ago"
},
{
"code": null,
"e": 5176,
"s": 5146,
"text": "java Dijkstra + shortest path"
},
{
"code": null,
"e": 5184,
"s": 5176,
"text": "6-7 sec"
},
{
"code": null,
"e": 6100,
"s": 5184,
"text": "class Solution{\n public int minimumCostPath(int[][] g){\n int n=g.length;\n int m=g[0].length;\n boolean [][] v= new boolean [n][m];\n int dx[]={1, -1, 0,0};\n int dy[]= {0,0,-1,1};\n PriorityQueue <pair> q= new PriorityQueue<pair>((e,f)->(e.z-f.z));\n q.offer(new pair(0,0,g[0][0]));\n while(!q.isEmpty()){\n pair c=q.poll();\n if(c.x==n-1 && c.y==m-1) return c.z;\n for(int i=0; i<4; i++){\n int a= c.x+dx[i];\n int b= c.y+dy[i];\n if(a>=n ||b>=m ||a<0 ||b<0 ||v[a][b]) continue;\n v[a][b]=true;\n q.offer(new pair(a,b,c.z+g[a][b]));\n }\n }\n return -1;\n }\n class pair{\n int x;\n int y;\n int z;\n pair(int x, int y, int z){\n this.x=x;\n this.y=y;\n this.z=z;\n }\n }\n}"
},
{
"code": null,
"e": 6102,
"s": 6100,
"text": "0"
},
{
"code": null,
"e": 6124,
"s": 6102,
"text": "sidsahu09026 days ago"
},
{
"code": null,
"e": 6184,
"s": 6124,
"text": "Can anyone help me, I am getting Runtime error in this code"
},
{
"code": null,
"e": 6933,
"s": 6184,
"text": "int sol(int i, int j, vector<vector<int>>&grid, vector<vector<int>>&dp,int n){\n \n if(i>n-1 || j>n-1 || i<0 || j<0 ){\n return 1e6;\n }\n if(i==0 && j==0){\n return grid[i][j];\n }\n if(dp[i][j]!=-1){\n return dp[i][j];\n }\n int up = grid[i][j] + sol(i-1, j, grid, dp, n);\n iny left = grid[i][j]+ sol(i, j-1, grid, dp, n);\n int right = grid[i][j] + sol(i, j+1, grid, dp, n);\n int down = grid[i][j] + sol(i+1, j, grid, dp, n);\n \n return dp[i][j]= min(left, min(right, min(up, down)));\n \n}\n\n int minimumCostPath(vector<vector<int>>& grid) \n {\n // Code here\n int n = grid[0].size();\n vector<vector<int>>dp(n, vector<int>(n, -1));\n return sol(n-1, n-1, grid, dp, n);\n }"
},
{
"code": null,
"e": 6935,
"s": 6933,
"text": "0"
},
{
"code": null,
"e": 6959,
"s": 6935,
"text": "gaurpiyush0011 week ago"
},
{
"code": null,
"e": 7038,
"s": 6959,
"text": "Is this Problem can be by Backtracking???,If Yes then why we are using graph??"
},
{
"code": null,
"e": 7041,
"s": 7038,
"text": "-1"
},
{
"code": null,
"e": 7059,
"s": 7041,
"text": "dflag441 week ago"
},
{
"code": null,
"e": 7101,
"s": 7059,
"text": " can anyone tell problem in this approach"
},
{
"code": null,
"e": 7910,
"s": 7101,
"text": "int helper(int i,int j,int n,int m,vector<vector<int>>&grid,vector<vector<int>>&dp, vector<vector<bool>>&vst){ if(i<0||j<0||i>n||j>m||vst[i][j])return 1000000; if(dp[i][j]!=-1)return dp[i][j]; if(i==n && j==m)return grid[i][j]; vst[i][j]=true; int x= grid[i][j]+min({ helper(i,j-1,n,m,grid,dp,vst), helper(i,j+1,n,m,grid,dp,vst), helper(i-1,j,n,m,grid,dp,vst), helper(i+1,j,n,m,grid,dp,vst), }); vst[i][j]=false; return dp[i][j]= x; } int minimumCostPath(vector<vector<int>>& grid) { int n=grid.size(); int m=grid[0].size(); vector<vector<int>>dp(n,vector<int>(m,-1)); vector<vector<bool>>vst(n,vector<bool>(m,false)); n--; m--; return helper(0,0,n,m,grid,dp,vst); }"
},
{
"code": null,
"e": 7913,
"s": 7910,
"text": "-1"
},
{
"code": null,
"e": 7935,
"s": 7913,
"text": "spiderman691 week ago"
},
{
"code": null,
"e": 7960,
"s": 7935,
"text": "Code without using pairs"
},
{
"code": null,
"e": 9780,
"s": 7962,
"text": " struct cell{ int x; int y; int weight; cell(int x,int y, int weight) { this->x = x; this->y = y; this->weight = weight; } }; struct cellcomp{ bool operator()(cell c1,cell c2) { return c1.weight>c2.weight; } }; bool isvalid(int i, int j, int n) { if(i>=0 && i<n && j>=0 && j<n) { return true; }else return false; } int minimumCostPath(vector<vector<int>>& grid) { // Code int node = grid.size(); vector<vector<bool>> visited(node,vector<bool>(node,false)); vector<vector<int>> weight(node,vector<int>(node,1e8)); int xar[4] = {0,-1,0,1}; int yar[4] = {-1,0,1,0}; weight[0][0] = grid[0][0]; priority_queue<cell,vector<cell>,cellcomp> pq; pq.push({0,0,grid[0][0]}); while(!pq.empty()) { cell temp = pq.top(); pq.pop(); int curr_x = temp.x; int curr_y = temp.y; if(visited[curr_x][curr_y]) continue; visited[curr_x][curr_y] = true; for(int i=0;i<4;i++) { int next_x = curr_x +xar[i]; int next_y = curr_y + yar[i]; if(isvalid(next_x,next_y,node) && !visited[next_x][next_y]) { if(weight[next_x][next_y] > (weight[curr_x][curr_y]+ grid[next_x][next_y])) { weight[next_x][next_y]= weight[curr_x][curr_y]+ grid[next_x][next_y]; } pq.push({next_x,next_y,weight[next_x][next_y]}); } } } return weight[node-1][node-1]; }"
},
{
"code": null,
"e": 9783,
"s": 9780,
"text": "-1"
},
{
"code": null,
"e": 9810,
"s": 9783,
"text": "anuragtiwariug201 week ago"
},
{
"code": null,
"e": 9853,
"s": 9810,
"text": "Anyone know why my code give runtime error"
},
{
"code": null,
"e": 10565,
"s": 9853,
"text": "int t[1000][1000];int solve(int i,int j,vector<vector<int>> &grid){ if(i==grid.size()-1 && j==grid[0].size()-1) { return grid[i][j]; } if(i>=grid.size()||j>=grid[0].size()) { return 1e9; } if(t[i][j]!=-1) { return t[i][j]; } int a=grid[i][j]+solve(i+1,j,grid); int b=0,c=0; if(i>1) { b=grid[i][j]+solve(i-1,j,grid); } if(j>1) { c=grid[i][j]+solve(i,j-1,grid); } int d=grid[i][j]+solve(i,j+1,grid); return t[i][j]=min({a,b,c,d});} int minimumCostPath(vector<vector<int>>& grid) { memset(t,-1,sizeof(t)); return solve(0,0,grid); }"
},
{
"code": null,
"e": 10568,
"s": 10565,
"text": "+3"
},
{
"code": null,
"e": 10593,
"s": 10568,
"text": "roboto7o32oo32 weeks ago"
},
{
"code": null,
"e": 10664,
"s": 10593,
"text": "Clean C++ Solution ✨ ✨ (Using Dijkstra's Algorithm and Priority Queue)"
},
{
"code": null,
"e": 12114,
"s": 10666,
"text": "class Solution\n{\n public:\n \n bool isValidPos(pair<int,int> pos, int n){\n int x = pos.first;\n int y = pos.second;\n \n if(x>=0 and x<n and y>=0 and y<n){\n return true;\n }\n return false;\n }\n \n int minimumCostPath(vector<vector<int>>& grid) \n {\n int n = grid.size();\n \n priority_queue<pair<int,pair<int,int>>, vector<pair<int,pair<int,int>>>, greater<pair<int,pair<int,int>>>> pq;\n \n vector<vector<int>> distance(n, vector<int>(n, INT_MAX));\n \n vector<pair<int,int>> moves{{1,0}, {0,1}, {-1,0}, {0,-1}};\n \n pq.push({grid[0][0], {0,0}});\n distance[0][0] = grid[0][0];\n \n while(not pq.empty()){\n pair<int,pair<int,int>> curr = pq.top();\n pq.pop();\n \n int dist = curr.first;\n pair<int,int> pos = curr.second;\n \n int x = pos.first;\n int y = pos.second;\n \n for(pair<int,int> move : moves){\n int nx = x + move.first;\n int ny = y + move.second;\n \n if(isValidPos({nx,ny}, n) and distance[nx][ny] > dist + grid[nx][ny]){\n distance[nx][ny] = dist + grid[nx][ny];\n pq.push({distance[nx][ny], {nx,ny}});\n }\n }\n }\n \n return distance[n-1][n-1];\n }\n};"
},
{
"code": null,
"e": 12260,
"s": 12114,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 12296,
"s": 12260,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 12306,
"s": 12296,
"text": "\nProblem\n"
},
{
"code": null,
"e": 12316,
"s": 12306,
"text": "\nContest\n"
},
{
"code": null,
"e": 12379,
"s": 12316,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 12564,
"s": 12379,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 12848,
"s": 12564,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 12994,
"s": 12848,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 13071,
"s": 12994,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 13112,
"s": 13071,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 13140,
"s": 13112,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 13211,
"s": 13140,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 13398,
"s": 13211,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Enum with Customized Value in Java | 17 Jul, 2018
Prerequisite : enum in Java
By default enums have their own string values, we can also assign some custom values to enums. Consider below example for that.
Examples:
enum Fruits
{
APPLE(“RED”), BANANA(“YELLOW”), GRAPES(“GREEN”);
}
In above example we can see that the Fruits enum have three members i.e APPLE, BANANA and GRAPES with have their own different custom values RED, YELLOW and GREEN respectively.
Now to use this enum in code, there are some points we have to follow:-
We have to create parameterized constructor for this enum class. Why? Because as we know that enum class’s object can’t be create explicitly so for initializing we use parameterized constructor. And the constructor cannot be the public or protected it must have private or default modifiers. Why? if we create public or protected, it will allow initializing more than one objects. This is totally against enum concept.We have to create one getter method to get the value of enums.
We have to create parameterized constructor for this enum class. Why? Because as we know that enum class’s object can’t be create explicitly so for initializing we use parameterized constructor. And the constructor cannot be the public or protected it must have private or default modifiers. Why? if we create public or protected, it will allow initializing more than one objects. This is totally against enum concept.
We have to create one getter method to get the value of enums.
// Java program to demonstrate how values can// be assigned to enums.enum TrafficSignal{ // This will call enum constructor with one // String argument RED("STOP"), GREEN("GO"), ORANGE("SLOW DOWN"); // declaring private variable for getting values private String action; // getter method public String getAction() { return this.action; } // enum constructor - cannot be public or protected private TrafficSignal(String action) { this.action = action; }} // Driver codepublic class EnumConstructorExample{ public static void main(String args[]) { // let's print name of each enum and there action // - Enum values() examples TrafficSignal[] signals = TrafficSignal.values(); for (TrafficSignal signal : signals) { // use getter method to get the value System.out.println("name : " + signal.name() + " action: " + signal.getAction() ); } }}
Output:
name : RED action: STOP
name : GREEN action: GO
name : ORANGE action: SLOW DOWN
This article is contributed by Vihang Shah. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rss009
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jul, 2018"
},
{
"code": null,
"e": 82,
"s": 54,
"text": "Prerequisite : enum in Java"
},
{
"code": null,
"e": 210,
"s": 82,
"text": "By default enums have their own string values, we can also assign some custom values to enums. Consider below example for that."
},
{
"code": null,
"e": 220,
"s": 210,
"text": "Examples:"
},
{
"code": null,
"e": 291,
"s": 220,
"text": "enum Fruits\n{\n APPLE(“RED”), BANANA(“YELLOW”), GRAPES(“GREEN”);\n}\n"
},
{
"code": null,
"e": 468,
"s": 291,
"text": "In above example we can see that the Fruits enum have three members i.e APPLE, BANANA and GRAPES with have their own different custom values RED, YELLOW and GREEN respectively."
},
{
"code": null,
"e": 540,
"s": 468,
"text": "Now to use this enum in code, there are some points we have to follow:-"
},
{
"code": null,
"e": 1021,
"s": 540,
"text": "We have to create parameterized constructor for this enum class. Why? Because as we know that enum class’s object can’t be create explicitly so for initializing we use parameterized constructor. And the constructor cannot be the public or protected it must have private or default modifiers. Why? if we create public or protected, it will allow initializing more than one objects. This is totally against enum concept.We have to create one getter method to get the value of enums."
},
{
"code": null,
"e": 1440,
"s": 1021,
"text": "We have to create parameterized constructor for this enum class. Why? Because as we know that enum class’s object can’t be create explicitly so for initializing we use parameterized constructor. And the constructor cannot be the public or protected it must have private or default modifiers. Why? if we create public or protected, it will allow initializing more than one objects. This is totally against enum concept."
},
{
"code": null,
"e": 1503,
"s": 1440,
"text": "We have to create one getter method to get the value of enums."
},
{
"code": "// Java program to demonstrate how values can// be assigned to enums.enum TrafficSignal{ // This will call enum constructor with one // String argument RED(\"STOP\"), GREEN(\"GO\"), ORANGE(\"SLOW DOWN\"); // declaring private variable for getting values private String action; // getter method public String getAction() { return this.action; } // enum constructor - cannot be public or protected private TrafficSignal(String action) { this.action = action; }} // Driver codepublic class EnumConstructorExample{ public static void main(String args[]) { // let's print name of each enum and there action // - Enum values() examples TrafficSignal[] signals = TrafficSignal.values(); for (TrafficSignal signal : signals) { // use getter method to get the value System.out.println(\"name : \" + signal.name() + \" action: \" + signal.getAction() ); } }}",
"e": 2500,
"s": 1503,
"text": null
},
{
"code": null,
"e": 2508,
"s": 2500,
"text": "Output:"
},
{
"code": null,
"e": 2591,
"s": 2508,
"text": "name : RED action: STOP\nname : GREEN action: GO \nname : ORANGE action: SLOW DOWN \n"
},
{
"code": null,
"e": 2890,
"s": 2591,
"text": "This article is contributed by Vihang Shah. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3015,
"s": 2890,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3022,
"s": 3015,
"text": "rss009"
},
{
"code": null,
"e": 3027,
"s": 3022,
"text": "Java"
},
{
"code": null,
"e": 3032,
"s": 3027,
"text": "Java"
}
] |
How to replace a specified element in slice of bytes in Golang? | 26 Aug, 2019
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.In the Go slice of bytes, you are allowed to replace a specified element in the given slice using the Replace() functions. This function returns a copy of the slice that contains a new slice which is created by replacing the elements in the old slice. If the given old slice is empty, then it matches at the start of the slice and after each UTF-8 sequence it is yielding up to m+1 replacement for m-rune slice. And if the value of the m is less than zero, then this function can replace any number of elements in the given slice (without any limit). It is defined under the bytes package so, you have to import bytes package in your program for accessing Repeat function.
Syntax:
func Replace(ori_slice, old_slice, new_slice []byte, m int) []byte
Here, ori_slice is the original slice of bytes, old_slice is the slice which you want to replace, new_slice is the new slice which replaces the old_slice, and m is the number of times the old_slice replaced.
Example 1:
// Go program to illustrate how to replace// the element of the slice of bytespackage main import ( "bytes" "fmt") // Main functionfunc main() { // Creating and initializing // the slice of bytes // Using shorthand declaration slice_1 := []byte{'G', 'E', 'E', 'K', 'S'} slice_2 := []byte{'A', 'P', 'P', 'L', 'E'} // Displaying slices fmt.Println("Original slice:") fmt.Printf("Slice 1: %s", slice_1) fmt.Printf("\nSlice 2: %s", slice_2) // Replacing the element // of the given slices // Using Replace function res1 := bytes.Replace(slice_1, []byte("E"), []byte("e"), 2) res2 := bytes.Replace(slice_2, []byte("P"), []byte("p"), 1) // Display the results fmt.Printf("\n\nNew Slice:") fmt.Printf("\nSlice 1: %s", res1) fmt.Printf("\nSlice 2: %s", res2)}
Output:
Original slice:
Slice 1: GEEKS
Slice 2: APPLE
New Slice:
Slice 1: GeeKS
Slice 2: ApPLE
Example 2:
// Go program to illustrate how to replace// the specified element from the given// slice of bytespackage main import ( "bytes" "fmt") // Main functionfunc main() { // Replacing the element // of the given slices // Using Replace function res1 := bytes.Replace([]byte("GeeksforGeeks, Geeks, Geeks"), []byte("eks"), []byte("EKS"), 3) res2 := bytes.Replace([]byte("Hello! i am Puppy, Puppy, Puppy"), []byte("upp"), []byte("ISL"), 2) res3 := bytes.Replace([]byte("GFG, GFG, GFG"), []byte("GFG"), []byte("geeks"), -1) res4 := bytes.Replace([]byte("I like icecream"), []byte("like"), []byte("love"), 0) // Display the results fmt.Printf("Result 1: %s", res1) fmt.Printf("\nResult 2: %s", res2) fmt.Printf("\nResult 3: %s", res3) fmt.Printf("\nResult 4: %s", res4)}
Output:
Result 1: GeEKSforGeEKS, GeEKS, Geeks
Result 2:Hello! i am PISLy, PISLy, Puppy
Result 3:geeks, geeks, geeks
Result 4:I like icecream
Golang
Golang-Slices
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to Trim a String in Golang?
How to convert a string in lower case in Golang?
How to compare times in Golang? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 968,
"s": 28,
"text": "In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.In the Go slice of bytes, you are allowed to replace a specified element in the given slice using the Replace() functions. This function returns a copy of the slice that contains a new slice which is created by replacing the elements in the old slice. If the given old slice is empty, then it matches at the start of the slice and after each UTF-8 sequence it is yielding up to m+1 replacement for m-rune slice. And if the value of the m is less than zero, then this function can replace any number of elements in the given slice (without any limit). It is defined under the bytes package so, you have to import bytes package in your program for accessing Repeat function."
},
{
"code": null,
"e": 976,
"s": 968,
"text": "Syntax:"
},
{
"code": null,
"e": 1043,
"s": 976,
"text": "func Replace(ori_slice, old_slice, new_slice []byte, m int) []byte"
},
{
"code": null,
"e": 1251,
"s": 1043,
"text": "Here, ori_slice is the original slice of bytes, old_slice is the slice which you want to replace, new_slice is the new slice which replaces the old_slice, and m is the number of times the old_slice replaced."
},
{
"code": null,
"e": 1262,
"s": 1251,
"text": "Example 1:"
},
{
"code": "// Go program to illustrate how to replace// the element of the slice of bytespackage main import ( \"bytes\" \"fmt\") // Main functionfunc main() { // Creating and initializing // the slice of bytes // Using shorthand declaration slice_1 := []byte{'G', 'E', 'E', 'K', 'S'} slice_2 := []byte{'A', 'P', 'P', 'L', 'E'} // Displaying slices fmt.Println(\"Original slice:\") fmt.Printf(\"Slice 1: %s\", slice_1) fmt.Printf(\"\\nSlice 2: %s\", slice_2) // Replacing the element // of the given slices // Using Replace function res1 := bytes.Replace(slice_1, []byte(\"E\"), []byte(\"e\"), 2) res2 := bytes.Replace(slice_2, []byte(\"P\"), []byte(\"p\"), 1) // Display the results fmt.Printf(\"\\n\\nNew Slice:\") fmt.Printf(\"\\nSlice 1: %s\", res1) fmt.Printf(\"\\nSlice 2: %s\", res2)}",
"e": 2084,
"s": 1262,
"text": null
},
{
"code": null,
"e": 2092,
"s": 2084,
"text": "Output:"
},
{
"code": null,
"e": 2181,
"s": 2092,
"text": "Original slice:\nSlice 1: GEEKS\nSlice 2: APPLE\n\nNew Slice:\nSlice 1: GeeKS\nSlice 2: ApPLE\n"
},
{
"code": null,
"e": 2192,
"s": 2181,
"text": "Example 2:"
},
{
"code": "// Go program to illustrate how to replace// the specified element from the given// slice of bytespackage main import ( \"bytes\" \"fmt\") // Main functionfunc main() { // Replacing the element // of the given slices // Using Replace function res1 := bytes.Replace([]byte(\"GeeksforGeeks, Geeks, Geeks\"), []byte(\"eks\"), []byte(\"EKS\"), 3) res2 := bytes.Replace([]byte(\"Hello! i am Puppy, Puppy, Puppy\"), []byte(\"upp\"), []byte(\"ISL\"), 2) res3 := bytes.Replace([]byte(\"GFG, GFG, GFG\"), []byte(\"GFG\"), []byte(\"geeks\"), -1) res4 := bytes.Replace([]byte(\"I like icecream\"), []byte(\"like\"), []byte(\"love\"), 0) // Display the results fmt.Printf(\"Result 1: %s\", res1) fmt.Printf(\"\\nResult 2: %s\", res2) fmt.Printf(\"\\nResult 3: %s\", res3) fmt.Printf(\"\\nResult 4: %s\", res4)}",
"e": 3006,
"s": 2192,
"text": null
},
{
"code": null,
"e": 3014,
"s": 3006,
"text": "Output:"
},
{
"code": null,
"e": 3148,
"s": 3014,
"text": "Result 1: GeEKSforGeEKS, GeEKS, Geeks\nResult 2:Hello! i am PISLy, PISLy, Puppy\nResult 3:geeks, geeks, geeks\nResult 4:I like icecream\n"
},
{
"code": null,
"e": 3155,
"s": 3148,
"text": "Golang"
},
{
"code": null,
"e": 3169,
"s": 3155,
"text": "Golang-Slices"
},
{
"code": null,
"e": 3181,
"s": 3169,
"text": "Go Language"
},
{
"code": null,
"e": 3279,
"s": 3181,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3292,
"s": 3279,
"text": "Arrays in Go"
},
{
"code": null,
"e": 3304,
"s": 3292,
"text": "Golang Maps"
},
{
"code": null,
"e": 3337,
"s": 3304,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 3358,
"s": 3337,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 3375,
"s": 3358,
"text": "Slices in Golang"
},
{
"code": null,
"e": 3429,
"s": 3375,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 3458,
"s": 3429,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 3490,
"s": 3458,
"text": "How to Trim a String in Golang?"
},
{
"code": null,
"e": 3539,
"s": 3490,
"text": "How to convert a string in lower case in Golang?"
}
] |
Julia Dictionary | 22 Apr, 2020
Dictionary in Julia is a collection of key-value pairs, where each value in the dictionary can be accessed with its key. These key-value pairs need not be of the same data type, which means a String typed key can hold a value of any type like Integer, String, float, etc. Keys of a dictionary can never be same, each key must be unique. This doesn’t apply to the values, values can be same, as per need. Dictionaries by default are an unordered collection of data i.e. it doesn’t maintain the order in which keys are inserted.
A dictionary is more like an array but in a dictionary, the indices can be of any type while in an array, the indices have to be integers only.Each key in a dictionary maps to a value. Because the keys need to be unique, two keys can be mapped with two same values but two different values can’t be mapped with a single key.
Syntax:
Dictionary_name = Dict(“key1” => value1, “key2” => value2, ...)
A dictionary in Julia can be created with a pre-defined keyword Dict(). This keyword accepts key-value pairs as arguments and generates a dictionary by defining its data type based on the data type of the key-value pairs. One can also pre-define the data type of the dictionary if the data type of the values is known. This can be done by defining the data type within curly braces after the ‘Dict‘ keyword. This dictionary with pre-defined data types is known as Typed Dictionary.
Syntax:
Dictionary_name = Dict{Key_datatype, Value_datatype}("Key1" => value1, "Key2" => value2, ...)
Example:
# Julia program to illustrate # the use of Dictionary # Creating an Empty dictionaryDict1 = Dict()println("Empty Dictionary = ", Dict1) # Creating an Untyped DictionaryDict2 = Dict("a" => 1, "b" => 2, "c" => 3)println("\nUntyped Dictionary = ", Dict2) # Creating a Typed DictionaryDict3 = Dict{String, Integer}("a" => 10, "c" => 20)println("\nTyped Dictionary = ", Dict3)
Output:
Elements from a dictionary can be accessed by using the keys of the dictionary. These keys are unique in a dictionary and hence each key holds a single value. A key-value pair can also be accessed with the use of for-loop.
Syntax:
Dictionary_name[key_name]
or
Dictionary_name[:key_name]
Example:
# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with String keysDict1 = Dict("a" => 1, "b" => 2, "c" => "Hello") # Accessing dictionary values using keysprintln(Dict1["b"])println(Dict1["c"]) # Creating a Dictionary with Integer keysDict2 = Dict(1 => 10, 2 => 20, 3 => "Geeks")println(Dict2[1])println(Dict2[3]) # Creating a Dictionary with SymbolsDict3 = Dict(:a => 1, :b => "one")println(Dict3[:b])
Output: Use of get() function:Julia provides a pre-defined function to access elements of a Dictionary known as get() function. This function takes 3 arguments: dictionary name, key, and a default value to print if the key is not found.Syntax:
get(Dictionary_name, Key_name, Default Value)
Example:
# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with mixed-typed keysDict1 = Dict("a" => 1, "b" => 2, "c" => "Hello", 4 => 10) # Accessing using get() function # Passing '0' as default value println(get(Dict1, "b", 0)) # Passing String as Default valueprintln(get(Dict1, "d", "Sorry, no such key"))
Output:
Dictionaries in Julia allow accessing all the keys and all the values at once. This can be done with the use of pre-defined keywords keys and values.
Syntax:
Keys = keys(Dictionary_name)
Values = values(Dictionary_name)
Example:
# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with mixed-typed keysDict1 = Dict("a" => 1, "b" => 2, "c" => "Hello", 4 => 10) # Accessing all the Keys# using 'keys' keywordKeys = keys(Dict1)println("Keys = ", Keys) # Accessing all the Values# using 'values' keywordValues = values(Dict1)println("Values = ", Values)
Output:Printing Key-value pairs:All the Key-value pairs of a dictionary can be printed at once, with the use of for-loop. This is done by iterating over each key of the dictionary and then accessing the respective value of that key.
Example 1: Using Dictionary as iterable object
# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with mixed-typed keysDict1 = Dict("a" => 1, "b" => 2, "c" => "Hello", 4 => 10) # Printing key-value pair using# Dictionary as an iterable objectfor i in Dict1 println(i)end
Output:Example 2: Accessing each key one by one
# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with mixed-typed keysDict1 = Dict("a" => 1, "b" => 2, "c" => "Hello", 4 => 10) # Printing key-value pair by# accessing each key one-by-onefor i in keys(Dict1) println(i, " => ", Dict1[i])end
Output:Example 3: By using (key, value) tuples
# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with mixed-typed keysDict1 = Dict("a" => 1, "b" => 2, "c" => "Hello", 4 => 10) # Printing key-value pair by# using key and value tuplesfor (i, j) in Dict1 println(i, " => ", j)end
Output:
Modification of elements of a Dictionary includes the process of adding new keys, modifying existing key values, and deleting a key. Modification of elements doesn’t include renaming keys of the dictionary, however, it can be done by deleting the existing key and adding another key with the same value.
# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with mixed-typed keysDict1 = Dict("a" => 1, "b" => 2, "c" => "Hello", 4 => 10)println("Initial Dictionary: \n", Dict1) # Adding a new keyDict1["d"] = 20println("\nUpdated Dictionary after Adding new key: \n", Dict1) # Updating existing keyDict1["c"] = "Hello Geeks"println("\nUpdated Dictionary after Updating a key: \n", Dict1) # Deleting an existing keyDict1 = delete !(Dict1, "d")println("\nUpdated Dictionary after Deleting a key: \n", Dict1)
Output:
Julia-dataTypes
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Storing Output on a File in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Manipulating matrices in Julia
Exception handling in Julia
Tuples in Julia
Creating array with repeated elements in Julia - repeat() Method
while loop in Julia
Comments in Julia | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 580,
"s": 53,
"text": "Dictionary in Julia is a collection of key-value pairs, where each value in the dictionary can be accessed with its key. These key-value pairs need not be of the same data type, which means a String typed key can hold a value of any type like Integer, String, float, etc. Keys of a dictionary can never be same, each key must be unique. This doesn’t apply to the values, values can be same, as per need. Dictionaries by default are an unordered collection of data i.e. it doesn’t maintain the order in which keys are inserted."
},
{
"code": null,
"e": 905,
"s": 580,
"text": "A dictionary is more like an array but in a dictionary, the indices can be of any type while in an array, the indices have to be integers only.Each key in a dictionary maps to a value. Because the keys need to be unique, two keys can be mapped with two same values but two different values can’t be mapped with a single key."
},
{
"code": null,
"e": 913,
"s": 905,
"text": "Syntax:"
},
{
"code": null,
"e": 977,
"s": 913,
"text": "Dictionary_name = Dict(“key1” => value1, “key2” => value2, ...)"
},
{
"code": null,
"e": 1459,
"s": 977,
"text": "A dictionary in Julia can be created with a pre-defined keyword Dict(). This keyword accepts key-value pairs as arguments and generates a dictionary by defining its data type based on the data type of the key-value pairs. One can also pre-define the data type of the dictionary if the data type of the values is known. This can be done by defining the data type within curly braces after the ‘Dict‘ keyword. This dictionary with pre-defined data types is known as Typed Dictionary."
},
{
"code": null,
"e": 1467,
"s": 1459,
"text": "Syntax:"
},
{
"code": null,
"e": 1562,
"s": 1467,
"text": "Dictionary_name = Dict{Key_datatype, Value_datatype}(\"Key1\" => value1, \"Key2\" => value2, ...)\n"
},
{
"code": null,
"e": 1571,
"s": 1562,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of Dictionary # Creating an Empty dictionaryDict1 = Dict()println(\"Empty Dictionary = \", Dict1) # Creating an Untyped DictionaryDict2 = Dict(\"a\" => 1, \"b\" => 2, \"c\" => 3)println(\"\\nUntyped Dictionary = \", Dict2) # Creating a Typed DictionaryDict3 = Dict{String, Integer}(\"a\" => 10, \"c\" => 20)println(\"\\nTyped Dictionary = \", Dict3)",
"e": 1946,
"s": 1571,
"text": null
},
{
"code": null,
"e": 1954,
"s": 1946,
"text": "Output:"
},
{
"code": null,
"e": 2177,
"s": 1954,
"text": "Elements from a dictionary can be accessed by using the keys of the dictionary. These keys are unique in a dictionary and hence each key holds a single value. A key-value pair can also be accessed with the use of for-loop."
},
{
"code": null,
"e": 2185,
"s": 2177,
"text": "Syntax:"
},
{
"code": null,
"e": 2242,
"s": 2185,
"text": "Dictionary_name[key_name]\nor\nDictionary_name[:key_name]\n"
},
{
"code": null,
"e": 2251,
"s": 2242,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with String keysDict1 = Dict(\"a\" => 1, \"b\" => 2, \"c\" => \"Hello\") # Accessing dictionary values using keysprintln(Dict1[\"b\"])println(Dict1[\"c\"]) # Creating a Dictionary with Integer keysDict2 = Dict(1 => 10, 2 => 20, 3 => \"Geeks\")println(Dict2[1])println(Dict2[3]) # Creating a Dictionary with SymbolsDict3 = Dict(:a => 1, :b => \"one\")println(Dict3[:b])",
"e": 2686,
"s": 2251,
"text": null
},
{
"code": null,
"e": 2930,
"s": 2686,
"text": "Output: Use of get() function:Julia provides a pre-defined function to access elements of a Dictionary known as get() function. This function takes 3 arguments: dictionary name, key, and a default value to print if the key is not found.Syntax:"
},
{
"code": null,
"e": 2977,
"s": 2930,
"text": "get(Dictionary_name, Key_name, Default Value)\n"
},
{
"code": null,
"e": 2986,
"s": 2977,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with mixed-typed keysDict1 = Dict(\"a\" => 1, \"b\" => 2, \"c\" => \"Hello\", 4 => 10) # Accessing using get() function # Passing '0' as default value println(get(Dict1, \"b\", 0)) # Passing String as Default valueprintln(get(Dict1, \"d\", \"Sorry, no such key\"))",
"e": 3319,
"s": 2986,
"text": null
},
{
"code": null,
"e": 3327,
"s": 3319,
"text": "Output:"
},
{
"code": null,
"e": 3477,
"s": 3327,
"text": "Dictionaries in Julia allow accessing all the keys and all the values at once. This can be done with the use of pre-defined keywords keys and values."
},
{
"code": null,
"e": 3485,
"s": 3477,
"text": "Syntax:"
},
{
"code": null,
"e": 3548,
"s": 3485,
"text": "Keys = keys(Dictionary_name)\nValues = values(Dictionary_name)\n"
},
{
"code": null,
"e": 3557,
"s": 3548,
"text": "Example:"
},
{
"code": "# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with mixed-typed keysDict1 = Dict(\"a\" => 1, \"b\" => 2, \"c\" => \"Hello\", 4 => 10) # Accessing all the Keys# using 'keys' keywordKeys = keys(Dict1)println(\"Keys = \", Keys) # Accessing all the Values# using 'values' keywordValues = values(Dict1)println(\"Values = \", Values)",
"e": 3907,
"s": 3557,
"text": null
},
{
"code": null,
"e": 4140,
"s": 3907,
"text": "Output:Printing Key-value pairs:All the Key-value pairs of a dictionary can be printed at once, with the use of for-loop. This is done by iterating over each key of the dictionary and then accessing the respective value of that key."
},
{
"code": null,
"e": 4187,
"s": 4140,
"text": "Example 1: Using Dictionary as iterable object"
},
{
"code": "# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with mixed-typed keysDict1 = Dict(\"a\" => 1, \"b\" => 2, \"c\" => \"Hello\", 4 => 10) # Printing key-value pair using# Dictionary as an iterable objectfor i in Dict1 println(i)end",
"e": 4443,
"s": 4187,
"text": null
},
{
"code": null,
"e": 4491,
"s": 4443,
"text": "Output:Example 2: Accessing each key one by one"
},
{
"code": "# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with mixed-typed keysDict1 = Dict(\"a\" => 1, \"b\" => 2, \"c\" => \"Hello\", 4 => 10) # Printing key-value pair by# accessing each key one-by-onefor i in keys(Dict1) println(i, \" => \", Dict1[i])end",
"e": 4765,
"s": 4491,
"text": null
},
{
"code": null,
"e": 4812,
"s": 4765,
"text": "Output:Example 3: By using (key, value) tuples"
},
{
"code": "# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with mixed-typed keysDict1 = Dict(\"a\" => 1, \"b\" => 2, \"c\" => \"Hello\", 4 => 10) # Printing key-value pair by# using key and value tuplesfor (i, j) in Dict1 println(i, \" => \", j)end",
"e": 5075,
"s": 4812,
"text": null
},
{
"code": null,
"e": 5083,
"s": 5075,
"text": "Output:"
},
{
"code": null,
"e": 5387,
"s": 5083,
"text": "Modification of elements of a Dictionary includes the process of adding new keys, modifying existing key values, and deleting a key. Modification of elements doesn’t include renaming keys of the dictionary, however, it can be done by deleting the existing key and adding another key with the same value."
},
{
"code": "# Julia program to illustrate # the use of Dictionary # Creating a Dictionary with mixed-typed keysDict1 = Dict(\"a\" => 1, \"b\" => 2, \"c\" => \"Hello\", 4 => 10)println(\"Initial Dictionary: \\n\", Dict1) # Adding a new keyDict1[\"d\"] = 20println(\"\\nUpdated Dictionary after Adding new key: \\n\", Dict1) # Updating existing keyDict1[\"c\"] = \"Hello Geeks\"println(\"\\nUpdated Dictionary after Updating a key: \\n\", Dict1) # Deleting an existing keyDict1 = delete !(Dict1, \"d\")println(\"\\nUpdated Dictionary after Deleting a key: \\n\", Dict1)",
"e": 5916,
"s": 5387,
"text": null
},
{
"code": null,
"e": 5924,
"s": 5916,
"text": "Output:"
},
{
"code": null,
"e": 5940,
"s": 5924,
"text": "Julia-dataTypes"
},
{
"code": null,
"e": 5946,
"s": 5940,
"text": "Julia"
},
{
"code": null,
"e": 6044,
"s": 5946,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6061,
"s": 6044,
"text": "Vectors in Julia"
},
{
"code": null,
"e": 6121,
"s": 6061,
"text": "Getting rounded value of a number in Julia - round() Method"
},
{
"code": null,
"e": 6155,
"s": 6121,
"text": "Storing Output on a File in Julia"
},
{
"code": null,
"e": 6216,
"s": 6155,
"text": "Reshaping array dimensions in Julia | Array reshape() Method"
},
{
"code": null,
"e": 6247,
"s": 6216,
"text": "Manipulating matrices in Julia"
},
{
"code": null,
"e": 6275,
"s": 6247,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 6291,
"s": 6275,
"text": "Tuples in Julia"
},
{
"code": null,
"e": 6356,
"s": 6291,
"text": "Creating array with repeated elements in Julia - repeat() Method"
},
{
"code": null,
"e": 6376,
"s": 6356,
"text": "while loop in Julia"
}
] |
How to get Post Data in Node.js ? | 20 Nov, 2021
Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isn’t a framework, and it’s not a programming language. In this article, we will discuss how to make post request using node.js
POST is a request method supported by HTTP that sends data to the server. In express, we can use the app.post() method to accept a POST request. The basic syntax to use the app.post() method is mentioned below.
The post data is provided to us on the req object inside the callback function of the app.post() method. We can access the data sent as the body using the syntax mentioned below.
const bodyContent = req.body;
Similarly, if we want to access the header content then we can do so using the syntax mentioned below.
const headerContent = req.headers;
Project Setup:
Step 1: Install Node.js if Node.js is not installed in your machine.
Step 2: Create a folder for your project and created two files named app.js and index.html inside of it.
Step 3: Now, initialize a new Node.js project with default configurations using the following command on the command line.
npm init -y
Step 4: Now install express inside your project using the following command on the command line.
npm install express
Project Structure: After following the steps your project structure will look like.
Filename: app.js
Javascript
// Importing express moduleconst express = require('express');const app = express(); app.use(express.json()); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html');}); app.post('/', (req, res) => { const { username, password } = req.body; const { authorization } = req.headers; res.send({ username, password, authorization, });}); app.listen(3000, () => { console.log('Our express server is up on port 3000');});
Filename: index.html
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <title>POST DEMO</title></head> <body> <form> <div> <label>Username</label> <input type="text" id="user" /> </div> <div> <label>Password</label> <input type="password" id="pass" /> </div> <button type="submit">Submit</button> </form> <script> document.querySelector('button') .addEventListener('click', (e) => { e.preventDefault(); const username = document .querySelector('#user').value; const password = document .querySelector('#pass').value; fetch('/', { method: 'POST', headers: { Authorization: 'Bearer abcdxyz', 'Content-Type': 'application/json', }, body: JSON.stringify({ username, password, }), }) .then((res) => { return res.json(); }) .then((data) => console.log(data)); }); </script></body> </html>
In the above example, we have created an express server that renders the index.html file. This index.html contains a form that has two inputs as username and password. When we press the submit button it sends a POST request to the home route with the body containing the username and password and the header containing the authorization token. We handle this post request inside our app.post() method and send these details i.e., the username, password, and authorization token as a response. We later print these details to the console.
Run app.js file using below command:
node app.js
Output: Open the browser and go to http://localhost:3000 and you will see the following output.
anikakapoor
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": "\n20 Nov, 2021"
},
{
"code": null,
"e": 346,
"s": 28,
"text": "Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isn’t a framework, and it’s not a programming language. In this article, we will discuss how to make post request using node.js"
},
{
"code": null,
"e": 557,
"s": 346,
"text": "POST is a request method supported by HTTP that sends data to the server. In express, we can use the app.post() method to accept a POST request. The basic syntax to use the app.post() method is mentioned below."
},
{
"code": null,
"e": 736,
"s": 557,
"text": "The post data is provided to us on the req object inside the callback function of the app.post() method. We can access the data sent as the body using the syntax mentioned below."
},
{
"code": null,
"e": 766,
"s": 736,
"text": "const bodyContent = req.body;"
},
{
"code": null,
"e": 870,
"s": 766,
"text": "Similarly, if we want to access the header content then we can do so using the syntax mentioned below. "
},
{
"code": null,
"e": 905,
"s": 870,
"text": "const headerContent = req.headers;"
},
{
"code": null,
"e": 920,
"s": 905,
"text": "Project Setup:"
},
{
"code": null,
"e": 989,
"s": 920,
"text": "Step 1: Install Node.js if Node.js is not installed in your machine."
},
{
"code": null,
"e": 1094,
"s": 989,
"text": "Step 2: Create a folder for your project and created two files named app.js and index.html inside of it."
},
{
"code": null,
"e": 1217,
"s": 1094,
"text": "Step 3: Now, initialize a new Node.js project with default configurations using the following command on the command line."
},
{
"code": null,
"e": 1229,
"s": 1217,
"text": "npm init -y"
},
{
"code": null,
"e": 1326,
"s": 1229,
"text": "Step 4: Now install express inside your project using the following command on the command line."
},
{
"code": null,
"e": 1346,
"s": 1326,
"text": "npm install express"
},
{
"code": null,
"e": 1430,
"s": 1346,
"text": "Project Structure: After following the steps your project structure will look like."
},
{
"code": null,
"e": 1447,
"s": 1430,
"text": "Filename: app.js"
},
{
"code": null,
"e": 1458,
"s": 1447,
"text": "Javascript"
},
{
"code": "// Importing express moduleconst express = require('express');const app = express(); app.use(express.json()); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html');}); app.post('/', (req, res) => { const { username, password } = req.body; const { authorization } = req.headers; res.send({ username, password, authorization, });}); app.listen(3000, () => { console.log('Our express server is up on port 3000');});",
"e": 1901,
"s": 1458,
"text": null
},
{
"code": null,
"e": 1922,
"s": 1901,
"text": "Filename: index.html"
},
{
"code": null,
"e": 1927,
"s": 1922,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <title>POST DEMO</title></head> <body> <form> <div> <label>Username</label> <input type=\"text\" id=\"user\" /> </div> <div> <label>Password</label> <input type=\"password\" id=\"pass\" /> </div> <button type=\"submit\">Submit</button> </form> <script> document.querySelector('button') .addEventListener('click', (e) => { e.preventDefault(); const username = document .querySelector('#user').value; const password = document .querySelector('#pass').value; fetch('/', { method: 'POST', headers: { Authorization: 'Bearer abcdxyz', 'Content-Type': 'application/json', }, body: JSON.stringify({ username, password, }), }) .then((res) => { return res.json(); }) .then((data) => console.log(data)); }); </script></body> </html>",
"e": 3232,
"s": 1927,
"text": null
},
{
"code": null,
"e": 3770,
"s": 3232,
"text": "In the above example, we have created an express server that renders the index.html file. This index.html contains a form that has two inputs as username and password. When we press the submit button it sends a POST request to the home route with the body containing the username and password and the header containing the authorization token. We handle this post request inside our app.post() method and send these details i.e., the username, password, and authorization token as a response. We later print these details to the console."
},
{
"code": null,
"e": 3807,
"s": 3770,
"text": "Run app.js file using below command:"
},
{
"code": null,
"e": 3819,
"s": 3807,
"text": "node app.js"
},
{
"code": null,
"e": 3915,
"s": 3819,
"text": "Output: Open the browser and go to http://localhost:3000 and you will see the following output."
},
{
"code": null,
"e": 3927,
"s": 3915,
"text": "anikakapoor"
},
{
"code": null,
"e": 3938,
"s": 3927,
"text": "Express.js"
},
{
"code": null,
"e": 3955,
"s": 3938,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 3962,
"s": 3955,
"text": "Picked"
},
{
"code": null,
"e": 3970,
"s": 3962,
"text": "Node.js"
},
{
"code": null,
"e": 3987,
"s": 3970,
"text": "Web Technologies"
}
] |
Starting a New Thread in Python | To spawn another thread, you need to call following method available in thread module −
thread.start_new_thread ( function, args[, kwargs] )
This method call enables a fast and efficient way to create new threads in both Linux and Windows.
The method call returns immediately and the child thread starts and calls function with the passed list of args. When function returns, the thread terminates.
Here, args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs is an optional dictionary of keyword arguments.
#!/usr/bin/python
import thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
while 1:
pass
When the above code is executed, it produces the following result −
Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009
Although it is very effective for low-level threading, but the thread module is very limited compared to the newer threading module. | [
{
"code": null,
"e": 1275,
"s": 1187,
"text": "To spawn another thread, you need to call following method available in thread module −"
},
{
"code": null,
"e": 1328,
"s": 1275,
"text": "thread.start_new_thread ( function, args[, kwargs] )"
},
{
"code": null,
"e": 1427,
"s": 1328,
"text": "This method call enables a fast and efficient way to create new threads in both Linux and Windows."
},
{
"code": null,
"e": 1586,
"s": 1427,
"text": "The method call returns immediately and the child thread starts and calls function with the passed list of args. When function returns, the thread terminates."
},
{
"code": null,
"e": 1744,
"s": 1586,
"text": "Here, args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs is an optional dictionary of keyword arguments."
},
{
"code": null,
"e": 2219,
"s": 1744,
"text": "#!/usr/bin/python\nimport thread\nimport time\n# Define a function for the thread\ndef print_time( threadName, delay):\n count = 0\n while count < 5:\n time.sleep(delay)\n count += 1\n print \"%s: %s\" % ( threadName, time.ctime(time.time()) )\n# Create two threads as follows\ntry:\n thread.start_new_thread( print_time, (\"Thread-1\", 2, ) )\n thread.start_new_thread( print_time, (\"Thread-2\", 4, ) )\nexcept:\n print \"Error: unable to start thread\"\nwhile 1:\n pass"
},
{
"code": null,
"e": 2287,
"s": 2219,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 2637,
"s": 2287,
"text": "Thread-1: Thu Jan 22 15:42:17 2009\nThread-1: Thu Jan 22 15:42:19 2009\nThread-2: Thu Jan 22 15:42:19 2009\nThread-1: Thu Jan 22 15:42:21 2009\nThread-2: Thu Jan 22 15:42:23 2009\nThread-1: Thu Jan 22 15:42:23 2009\nThread-1: Thu Jan 22 15:42:25 2009\nThread-2: Thu Jan 22 15:42:27 2009\nThread-2: Thu Jan 22 15:42:31 2009\nThread-2: Thu Jan 22 15:42:35 2009"
},
{
"code": null,
"e": 2770,
"s": 2637,
"text": "Although it is very effective for low-level threading, but the thread module is very limited compared to the newer threading module."
}
] |
How to reset/remove CSS styles for element ? | 22 Nov, 2021
The browser uses some pre-defined default values to most of the CSS properties. These default values may vary depending on the browser and also the version of the browser being used. These default values are given in order to ensure uniformity throughout web pages. But in some cases these defaults result in an unexpected action to be performed by the web page, hence removing these defaults is a viable method.In most cases, the reset can be done using some pre-defined reset methods. There are many other reset methods. But the problem with those reset methods is that, they are used to remove all the styling present in a web page (remove all the browser defaults for all elements and their properties), but if we want to remove the default only or some specific style for one element then the value unset comes in handy. Problem Statement: Most of the cases the default buttons provided by web browsers are very bland and not stylized. To make it more stylized and to make it fit into the theme of the web page it could be stylized manually using CSS. But manual styles cannot be applied until the default styles are removed. Hence we apply the following code to remove the default styles present on a button.Example 1: Here you will see how to use unset property by HTML and CSS. This example remove only the default browser style.
html
<!DOCTYPE html><html> <head> <title> How to reset/remove CSS styles for element ? </title> <style> body { display: grid; min-height: 100vh; } .gfg { all: unset; } .geeks { color: green; font-size: 3rem; } </style></head> <body> <center> <div class="geeks"> <button class="gfg"> GeeksforGeeks </button> </div> <p> Here the GeeksforGeeks button is attached with the unset property </p><br> <button class="GFG"> A Online Computer Secience Portal </button> </center></body> </html>
Output:
Example 2: Here you will see how to trigger unset property by HTML, CSS an jQuery.
html
<!DOCTYPE html><html> <head> <title> How to reset/remove CSS styles for element ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <style> .geeks { all:unset; } div { color: Green; font-size: 44px; } </style></head> <body> <center> <div id="myid"> GeeksforGeeks </div><br> <button id="gfg"> Click me to Unset CSS </button> <script> $('#gfg').click(function() { $('#myid').addClass('geeks'); }); </script> </center></body> </html>
Output:
Before clicking the button:
After clicking the Button:
simmytarika5
jQuery-HTML/CSS
Picked
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 1367,
"s": 28,
"text": "The browser uses some pre-defined default values to most of the CSS properties. These default values may vary depending on the browser and also the version of the browser being used. These default values are given in order to ensure uniformity throughout web pages. But in some cases these defaults result in an unexpected action to be performed by the web page, hence removing these defaults is a viable method.In most cases, the reset can be done using some pre-defined reset methods. There are many other reset methods. But the problem with those reset methods is that, they are used to remove all the styling present in a web page (remove all the browser defaults for all elements and their properties), but if we want to remove the default only or some specific style for one element then the value unset comes in handy. Problem Statement: Most of the cases the default buttons provided by web browsers are very bland and not stylized. To make it more stylized and to make it fit into the theme of the web page it could be stylized manually using CSS. But manual styles cannot be applied until the default styles are removed. Hence we apply the following code to remove the default styles present on a button.Example 1: Here you will see how to use unset property by HTML and CSS. This example remove only the default browser style. "
},
{
"code": null,
"e": 1372,
"s": 1367,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to reset/remove CSS styles for element ? </title> <style> body { display: grid; min-height: 100vh; } .gfg { all: unset; } .geeks { color: green; font-size: 3rem; } </style></head> <body> <center> <div class=\"geeks\"> <button class=\"gfg\"> GeeksforGeeks </button> </div> <p> Here the GeeksforGeeks button is attached with the unset property </p><br> <button class=\"GFG\"> A Online Computer Secience Portal </button> </center></body> </html> ",
"e": 2155,
"s": 1372,
"text": null
},
{
"code": null,
"e": 2165,
"s": 2155,
"text": "Output: "
},
{
"code": null,
"e": 2249,
"s": 2165,
"text": "Example 2: Here you will see how to trigger unset property by HTML, CSS an jQuery. "
},
{
"code": null,
"e": 2254,
"s": 2249,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to reset/remove CSS styles for element ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"> </script> <style> .geeks { all:unset; } div { color: Green; font-size: 44px; } </style></head> <body> <center> <div id=\"myid\"> GeeksforGeeks </div><br> <button id=\"gfg\"> Click me to Unset CSS </button> <script> $('#gfg').click(function() { $('#myid').addClass('geeks'); }); </script> </center></body> </html> ",
"e": 2981,
"s": 2254,
"text": null
},
{
"code": null,
"e": 2991,
"s": 2981,
"text": "Output: "
},
{
"code": null,
"e": 3021,
"s": 2991,
"text": "Before clicking the button: "
},
{
"code": null,
"e": 3050,
"s": 3021,
"text": "After clicking the Button: "
},
{
"code": null,
"e": 3065,
"s": 3052,
"text": "simmytarika5"
},
{
"code": null,
"e": 3081,
"s": 3065,
"text": "jQuery-HTML/CSS"
},
{
"code": null,
"e": 3088,
"s": 3081,
"text": "Picked"
},
{
"code": null,
"e": 3105,
"s": 3088,
"text": "Web Technologies"
},
{
"code": null,
"e": 3132,
"s": 3105,
"text": "Web technologies Questions"
}
] |
How to rotate an Image in ImageView by an angle on Android? | This example demonstrates how do I rotate an image in ImageView by an angle on android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<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"
android:orientation="vertical"
android:padding="2dp"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="600dp"
android:layout_gravity="center"
android:layout_margin="20sp"
android:src="@drawable/image"/>
<Button
android:id="@+id/btnRotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginTop="20sp"
android:text="Rotate View"
android:textStyle="bold"
android:layout_marginBottom="10dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
Button btnRotate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
btnRotate = findViewById(R.id.btnRotate);
btnRotate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageView.setRotation(90);
}
});
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code. | [
{
"code": null,
"e": 1275,
"s": 1187,
"text": "This example demonstrates how do I rotate an image in ImageView by an angle on android."
},
{
"code": null,
"e": 1404,
"s": 1275,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1469,
"s": 1404,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2385,
"s": 1469,
"text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"2dp\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"600dp\"\n android:layout_gravity=\"center\"\n android:layout_margin=\"20sp\"\n android:src=\"@drawable/image\"/>\n <Button\n android:id=\"@+id/btnRotate\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"20sp\"\n android:text=\"Rotate View\"\n android:textStyle=\"bold\"\n android:layout_marginBottom=\"10dp\"\n android:layout_alignParentBottom=\"true\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 2442,
"s": 2385,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3147,
"s": 2442,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\npublic class MainActivity extends AppCompatActivity {\n ImageView imageView;\n Button btnRotate;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n imageView = findViewById(R.id.imageView);\n btnRotate = findViewById(R.id.btnRotate);\n btnRotate.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n imageView.setRotation(90);\n }\n });\n }\n}"
},
{
"code": null,
"e": 3202,
"s": 3147,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3872,
"s": 3202,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4219,
"s": 3872,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 4260,
"s": 4219,
"text": "Click here to download the project code."
}
] |
REPLICATE() Function in SQL Server | 30 Dec, 2020
REPLICATE() function :This function in SQL Server is used to repeat the specified string for a given number of times.
Features :
This function is used to return the stated string for a given number of times.
This function accepts only strings and integers as parameter.
This function returns an error if the second parameter is not provided.
The repeated strings returned here has no space in between the former and the latter string.
Syntax :
REPLICATE(string, integer)
Parameter :This method accepts two parameter as given below :
string : Specified string to repeat.
integer : Specified number of times for which the string is to be repeated.
Returns :It returns the stated string for a specified number of times.
Example-1 :Getting the stated string for a specified number of times.
SELECT REPLICATE('Geeks for Geeks ', 2);
Output :
Geeks for Geeks Geeks for Geeks
Example-2 :Using REPLICATE() function with a variable and getting the repeated strings for the specified number of times.
DECLARE @string VARCHAR(4);
SET @string = '123 ';
SELECT REPLICATE(@string, 4);
Output :
123 123 123 123
Example-3 :Using REPLICATE() function with two variables and getting the repeated strings for the specified number of times.
DECLARE @string VARCHAR(6);
DECLARE @int INT;
SET @string = 'Geeks ';
SET @int = 5;
SELECT REPLICATE(@string, @int);
Output :
Geeks Geeks Geeks Geeks Geeks
Example-4 :Getting the stated string for a specified number of times which is a float value.
SELECT REPLICATE('gfg ', 5.9);
Output :
gfg gfg gfg gfg gfg
Application :This function is used to repeat the specified string for a stated number of times.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 146,
"s": 28,
"text": "REPLICATE() function :This function in SQL Server is used to repeat the specified string for a given number of times."
},
{
"code": null,
"e": 157,
"s": 146,
"text": "Features :"
},
{
"code": null,
"e": 236,
"s": 157,
"text": "This function is used to return the stated string for a given number of times."
},
{
"code": null,
"e": 298,
"s": 236,
"text": "This function accepts only strings and integers as parameter."
},
{
"code": null,
"e": 370,
"s": 298,
"text": "This function returns an error if the second parameter is not provided."
},
{
"code": null,
"e": 463,
"s": 370,
"text": "The repeated strings returned here has no space in between the former and the latter string."
},
{
"code": null,
"e": 472,
"s": 463,
"text": "Syntax :"
},
{
"code": null,
"e": 499,
"s": 472,
"text": "REPLICATE(string, integer)"
},
{
"code": null,
"e": 561,
"s": 499,
"text": "Parameter :This method accepts two parameter as given below :"
},
{
"code": null,
"e": 598,
"s": 561,
"text": "string : Specified string to repeat."
},
{
"code": null,
"e": 674,
"s": 598,
"text": "integer : Specified number of times for which the string is to be repeated."
},
{
"code": null,
"e": 745,
"s": 674,
"text": "Returns :It returns the stated string for a specified number of times."
},
{
"code": null,
"e": 815,
"s": 745,
"text": "Example-1 :Getting the stated string for a specified number of times."
},
{
"code": null,
"e": 856,
"s": 815,
"text": "SELECT REPLICATE('Geeks for Geeks ', 2);"
},
{
"code": null,
"e": 865,
"s": 856,
"text": "Output :"
},
{
"code": null,
"e": 897,
"s": 865,
"text": "Geeks for Geeks Geeks for Geeks"
},
{
"code": null,
"e": 1019,
"s": 897,
"text": "Example-2 :Using REPLICATE() function with a variable and getting the repeated strings for the specified number of times."
},
{
"code": null,
"e": 1104,
"s": 1019,
"text": "DECLARE @string VARCHAR(4); \nSET @string = '123 '; \nSELECT REPLICATE(@string, 4);\n"
},
{
"code": null,
"e": 1113,
"s": 1104,
"text": "Output :"
},
{
"code": null,
"e": 1129,
"s": 1113,
"text": "123 123 123 123"
},
{
"code": null,
"e": 1254,
"s": 1129,
"text": "Example-3 :Using REPLICATE() function with two variables and getting the repeated strings for the specified number of times."
},
{
"code": null,
"e": 1378,
"s": 1254,
"text": "DECLARE @string VARCHAR(6); \nDECLARE @int INT; \nSET @string = 'Geeks '; \nSET @int = 5;\nSELECT REPLICATE(@string, @int);\n"
},
{
"code": null,
"e": 1387,
"s": 1378,
"text": "Output :"
},
{
"code": null,
"e": 1417,
"s": 1387,
"text": "Geeks Geeks Geeks Geeks Geeks"
},
{
"code": null,
"e": 1510,
"s": 1417,
"text": "Example-4 :Getting the stated string for a specified number of times which is a float value."
},
{
"code": null,
"e": 1541,
"s": 1510,
"text": "SELECT REPLICATE('gfg ', 5.9);"
},
{
"code": null,
"e": 1550,
"s": 1541,
"text": "Output :"
},
{
"code": null,
"e": 1570,
"s": 1550,
"text": "gfg gfg gfg gfg gfg"
},
{
"code": null,
"e": 1666,
"s": 1570,
"text": "Application :This function is used to repeat the specified string for a stated number of times."
},
{
"code": null,
"e": 1675,
"s": 1666,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1686,
"s": 1675,
"text": "SQL-Server"
},
{
"code": null,
"e": 1690,
"s": 1686,
"text": "SQL"
},
{
"code": null,
"e": 1694,
"s": 1690,
"text": "SQL"
},
{
"code": null,
"e": 1792,
"s": 1694,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1858,
"s": 1792,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 1882,
"s": 1858,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 1914,
"s": 1882,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 1931,
"s": 1914,
"text": "SQL using Python"
},
{
"code": null,
"e": 1964,
"s": 1931,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2042,
"s": 1964,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2072,
"s": 2042,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2108,
"s": 2072,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2139,
"s": 2108,
"text": "SQL Query to Compare Two Dates"
}
] |
Minimum Cost Graph | 20 Dec, 2021
Given N nodes on a 2-D plane represented as (xi, yi). The nodes are said to be connected if the manhattan distance between them is 1. You can connect two nodes that are not connected at the cost of euclidean distance between them. The task is to connect the graph such that every node has a path from any node with minimum cost.
Examples:
Input: N = 3, edges[][] = {{1, 1}, {1, 1}, {2, 2}, {3, 2}} Output: 1.41421 Since (2, 2) and (2, 3) are already connected. So we try to connect either (1, 1) with (2, 2) or (1, 1) with (2, 3) but (1, 1) with (2, 2) yields the minimum cost.
Input: N = 3, edges[][] = {{1, 1}, {2, 2}, {3, 3}} Output: 2.82843
Approach: The brute force approach is to connect each node with every other node and similarly for the other N nodes but in the worst case the time complexity will be NN. The other way is to find the cost of every pair of vertices with the euclidean distance and those pairs which are connected will have the cost as 0. After knowing the cost of each pair we will apply the Kruskal Algorithm for the minimum spanning tree and it will yield the minimum cost for connecting the graph. Note that for Kruskal Algorithm, you have to have the knowledge of Disjoint Set Union (DSU).
Below is the implementation of the above approach:
C++
Java
Python3
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Max number of nodes givenconst int N = 500 + 10; // arr is the parent array// sz is the size of the// subtree in DSUint arr[N], sz[N]; // Function to initialize the parent// and size array for DSUvoid initialize(){ for (int i = 1; i < N; ++i) { arr[i] = i; sz[i] = 1; }} // Function to return the// parent of the nodeint root(int i){ while (arr[i] != i) i = arr[i]; return i;} // Function to perform the// merge operationvoid Union(int a, int b){ a = root(a); b = root(b); if (a != b) { if (sz[a] < sz[b]) swap(a, b); sz[a] += sz[b]; arr[b] = a; }} // Function to return the minimum cost requireddouble minCost(vector<pair<int, int> >& p){ // Number of points int n = (int)p.size(); // To store the cost of every possible pair // as { cost, {to, from}}. vector<pair<double, pair<int, int> > > cost; // Calculating the cost of every possible pair for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i != j) { // Getting Manhattan distance int x = abs(p[i].first - p[j].first) + abs(p[i].second - p[j].second); // If the distance is 1 the cost is 0 // or already connected if (x == 1) { cost.push_back({ 0, { i + 1, j + 1 } }); cost.push_back({ 0, { j + 1, i + 1 } }); } else { // Calculating the euclidean distance int a = p[i].first - p[j].first; int b = p[i].second - p[j].second; a *= a; b *= b; double d = sqrt(a + b); cost.push_back({ d, { i + 1, j + 1 } }); cost.push_back({ d, { j + 1, i + 1 } }); } } } } // Krushkal Algorithm for Minimum // spanning tree sort(cost.begin(), cost.end()); // To initialize the size and // parent array initialize(); double ans = 0.00; for (auto i : cost) { double c = i.first; int a = i.second.first; int b = i.second.second; // If the parents are different if (root(a) != root(b)) { Union(a, b); ans += c; } } return ans;} // Driver codeint main(){ // Vector pairs of points vector<pair<int, int> > points = { { 1, 1 }, { 2, 2 }, { 2, 3 } }; // Function calling and printing // the answer cout << minCost(points); return 0;}
// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Max number of nodes givenstatic int N = 500 + 10; static class pair{ double c; int first, second; pair(double c, int first, int second) { this.c = c; this.first = first; this.second = second; }} // arr is the parent array// sz is the size of the// subtree in DSUstatic int[] arr = new int[N], sz = new int[N]; // Function to initialize the parent// and size array for DSUstatic void initialize(){ for(int i = 1; i < N; ++i) { arr[i] = i; sz[i] = 1; }} // Function to return the// parent of the nodestatic int root(int i){ while (arr[i] != i) i = arr[i]; return i;} // Function to perform the// merge operationstatic void union(int a, int b){ a = root(a); b = root(b); if (a != b) { if (sz[a] < sz[b]) { int tmp = a; a = b; b = tmp; } sz[a] += sz[b]; arr[b] = a; }} // Function to return the minimum// cost requiredstatic double minCost(int[][] p){ // Number of points int n = (int)p.length; // To store the cost of every possible pair // as { cost, {to, from}}. ArrayList<pair> cost = new ArrayList<>(); // Calculating the cost of every possible pair for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { if (i != j) { // Getting Manhattan distance int x = Math.abs(p[i][0] - p[j][0]) + Math.abs(p[i][1] - p[j][1]); // If the distance is 1 the cost is 0 // or already connected if (x == 1) { cost.add(new pair( 0, i + 1, j + 1 )); cost.add(new pair( 0, j + 1, i + 1 )); } else { // Calculating the euclidean // distance int a = p[i][0] - p[j][0]; int b = p[i][1] - p[j][1]; a *= a; b *= b; double d = Math.sqrt(a + b); cost.add(new pair(d, i + 1, j + 1 )); cost.add(new pair(d, j + 1, i + 1)); } } } } // Krushkal Algorithm for Minimum // spanning tree Collections.sort(cost, new Comparator<>() { public int compare(pair a, pair b) { if(a.c <= b.c) return -1; else return 1; } }); // To initialize the size and // parent array initialize(); double ans = 0.00; for(pair i : cost) { double c = i.c; int a = i.first; int b = i.second; // If the parents are different if (root(a) != root(b)) { union(a, b); ans += c; } } return ans;} // Driver codepublic static void main(String[] args){ // Vector pairs of points int[][] points = { { 1, 1 }, { 2, 2 }, { 2, 3 }}; // Function calling and printing // the answer System.out.format("%.5f", minCost(points));}} // This code is contributed by offbeat
# Python3 implementation of the approach # Max number of nodes givenN = 500 + 10 # arr is the parent array# sz is the size of the# subtree in DSUarr = [i for i in range(N)]sz = [0] * N # Function to return the# parent of the nodedef root(i): while arr[i] != i: i = arr[i] return i # Function to perform the# merge operationdef Union(a, b): a = root(a) b = root(b) if a != b: if sz[a] < sz[b]: a, b = b, a sz[a] += sz[b] arr[b] = a # Function to return the minimum cost requireddef minCost(): global points # Number of points n = len(points) # To store the cost of every possible pair # as : cost, :to, from. cost = [] # Calculating the cost of every possible pair for i in range(n): for j in range(n): if i != j: # Getting Manhattan distance x = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]) # If the distance is 1 the cost is 0 # or already connected if x == 1: cost.append((0, (i + 1, j + 1))) cost.append((0, (j + 1, i + 1))) else: # Calculating the euclidean distance a = points[i][0] - points[j][0] b = points[i][1] - points[j][1] a *= a b *= b d = (a + b)**0.5 cost.append((d, (i + 1, j + 1))) cost.append((d, (j + 1, i + 1))) # Krushkal Algorithm for Minimum # spanning tree cost.sort() ans = 0.00 for i in cost: c = i[0] a = i[1][0] b = i[1][1] # If the parents are different if root(a) != root(b): Union(a, b) ans += c return ans # Driver codeif __name__ == "__main__": # Vector pairs of points points = [(1, 1), (2, 2), (2, 3)] # Function calling and printing # the answer print(minCost())
1.41421
Time Complexity: O(N*N)Auxiliary Space: O(N*N)
offbeat
arorakashish0911
pankajsharmagfg
singghakshay
ashutoshsinghgeeksforgeeks
amartyaghoshgfg
disjoint-set
Kruskal'sAlgorithm
Advanced Data Structure
Algorithms
Graph
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ordered Set and GNU C++ PBDS
Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)
2-3 Trees | (Search, Insert and Deletion)
Extendible Hashing (Dynamic approach to DBMS)
Segment Tree | Set 2 (Range Minimum Query)
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
Difference between BFS and DFS
What is Hashing | A Complete Tutorial | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 383,
"s": 54,
"text": "Given N nodes on a 2-D plane represented as (xi, yi). The nodes are said to be connected if the manhattan distance between them is 1. You can connect two nodes that are not connected at the cost of euclidean distance between them. The task is to connect the graph such that every node has a path from any node with minimum cost."
},
{
"code": null,
"e": 394,
"s": 383,
"text": "Examples: "
},
{
"code": null,
"e": 633,
"s": 394,
"text": "Input: N = 3, edges[][] = {{1, 1}, {1, 1}, {2, 2}, {3, 2}} Output: 1.41421 Since (2, 2) and (2, 3) are already connected. So we try to connect either (1, 1) with (2, 2) or (1, 1) with (2, 3) but (1, 1) with (2, 2) yields the minimum cost."
},
{
"code": null,
"e": 700,
"s": 633,
"text": "Input: N = 3, edges[][] = {{1, 1}, {2, 2}, {3, 3}} Output: 2.82843"
},
{
"code": null,
"e": 1276,
"s": 700,
"text": "Approach: The brute force approach is to connect each node with every other node and similarly for the other N nodes but in the worst case the time complexity will be NN. The other way is to find the cost of every pair of vertices with the euclidean distance and those pairs which are connected will have the cost as 0. After knowing the cost of each pair we will apply the Kruskal Algorithm for the minimum spanning tree and it will yield the minimum cost for connecting the graph. Note that for Kruskal Algorithm, you have to have the knowledge of Disjoint Set Union (DSU)."
},
{
"code": null,
"e": 1327,
"s": 1276,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1331,
"s": 1327,
"text": "C++"
},
{
"code": null,
"e": 1336,
"s": 1331,
"text": "Java"
},
{
"code": null,
"e": 1344,
"s": 1336,
"text": "Python3"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Max number of nodes givenconst int N = 500 + 10; // arr is the parent array// sz is the size of the// subtree in DSUint arr[N], sz[N]; // Function to initialize the parent// and size array for DSUvoid initialize(){ for (int i = 1; i < N; ++i) { arr[i] = i; sz[i] = 1; }} // Function to return the// parent of the nodeint root(int i){ while (arr[i] != i) i = arr[i]; return i;} // Function to perform the// merge operationvoid Union(int a, int b){ a = root(a); b = root(b); if (a != b) { if (sz[a] < sz[b]) swap(a, b); sz[a] += sz[b]; arr[b] = a; }} // Function to return the minimum cost requireddouble minCost(vector<pair<int, int> >& p){ // Number of points int n = (int)p.size(); // To store the cost of every possible pair // as { cost, {to, from}}. vector<pair<double, pair<int, int> > > cost; // Calculating the cost of every possible pair for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i != j) { // Getting Manhattan distance int x = abs(p[i].first - p[j].first) + abs(p[i].second - p[j].second); // If the distance is 1 the cost is 0 // or already connected if (x == 1) { cost.push_back({ 0, { i + 1, j + 1 } }); cost.push_back({ 0, { j + 1, i + 1 } }); } else { // Calculating the euclidean distance int a = p[i].first - p[j].first; int b = p[i].second - p[j].second; a *= a; b *= b; double d = sqrt(a + b); cost.push_back({ d, { i + 1, j + 1 } }); cost.push_back({ d, { j + 1, i + 1 } }); } } } } // Krushkal Algorithm for Minimum // spanning tree sort(cost.begin(), cost.end()); // To initialize the size and // parent array initialize(); double ans = 0.00; for (auto i : cost) { double c = i.first; int a = i.second.first; int b = i.second.second; // If the parents are different if (root(a) != root(b)) { Union(a, b); ans += c; } } return ans;} // Driver codeint main(){ // Vector pairs of points vector<pair<int, int> > points = { { 1, 1 }, { 2, 2 }, { 2, 3 } }; // Function calling and printing // the answer cout << minCost(points); return 0;}",
"e": 4028,
"s": 1344,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Max number of nodes givenstatic int N = 500 + 10; static class pair{ double c; int first, second; pair(double c, int first, int second) { this.c = c; this.first = first; this.second = second; }} // arr is the parent array// sz is the size of the// subtree in DSUstatic int[] arr = new int[N], sz = new int[N]; // Function to initialize the parent// and size array for DSUstatic void initialize(){ for(int i = 1; i < N; ++i) { arr[i] = i; sz[i] = 1; }} // Function to return the// parent of the nodestatic int root(int i){ while (arr[i] != i) i = arr[i]; return i;} // Function to perform the// merge operationstatic void union(int a, int b){ a = root(a); b = root(b); if (a != b) { if (sz[a] < sz[b]) { int tmp = a; a = b; b = tmp; } sz[a] += sz[b]; arr[b] = a; }} // Function to return the minimum// cost requiredstatic double minCost(int[][] p){ // Number of points int n = (int)p.length; // To store the cost of every possible pair // as { cost, {to, from}}. ArrayList<pair> cost = new ArrayList<>(); // Calculating the cost of every possible pair for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { if (i != j) { // Getting Manhattan distance int x = Math.abs(p[i][0] - p[j][0]) + Math.abs(p[i][1] - p[j][1]); // If the distance is 1 the cost is 0 // or already connected if (x == 1) { cost.add(new pair( 0, i + 1, j + 1 )); cost.add(new pair( 0, j + 1, i + 1 )); } else { // Calculating the euclidean // distance int a = p[i][0] - p[j][0]; int b = p[i][1] - p[j][1]; a *= a; b *= b; double d = Math.sqrt(a + b); cost.add(new pair(d, i + 1, j + 1 )); cost.add(new pair(d, j + 1, i + 1)); } } } } // Krushkal Algorithm for Minimum // spanning tree Collections.sort(cost, new Comparator<>() { public int compare(pair a, pair b) { if(a.c <= b.c) return -1; else return 1; } }); // To initialize the size and // parent array initialize(); double ans = 0.00; for(pair i : cost) { double c = i.c; int a = i.first; int b = i.second; // If the parents are different if (root(a) != root(b)) { union(a, b); ans += c; } } return ans;} // Driver codepublic static void main(String[] args){ // Vector pairs of points int[][] points = { { 1, 1 }, { 2, 2 }, { 2, 3 }}; // Function calling and printing // the answer System.out.format(\"%.5f\", minCost(points));}} // This code is contributed by offbeat",
"e": 7588,
"s": 4028,
"text": null
},
{
"code": "# Python3 implementation of the approach # Max number of nodes givenN = 500 + 10 # arr is the parent array# sz is the size of the# subtree in DSUarr = [i for i in range(N)]sz = [0] * N # Function to return the# parent of the nodedef root(i): while arr[i] != i: i = arr[i] return i # Function to perform the# merge operationdef Union(a, b): a = root(a) b = root(b) if a != b: if sz[a] < sz[b]: a, b = b, a sz[a] += sz[b] arr[b] = a # Function to return the minimum cost requireddef minCost(): global points # Number of points n = len(points) # To store the cost of every possible pair # as : cost, :to, from. cost = [] # Calculating the cost of every possible pair for i in range(n): for j in range(n): if i != j: # Getting Manhattan distance x = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]) # If the distance is 1 the cost is 0 # or already connected if x == 1: cost.append((0, (i + 1, j + 1))) cost.append((0, (j + 1, i + 1))) else: # Calculating the euclidean distance a = points[i][0] - points[j][0] b = points[i][1] - points[j][1] a *= a b *= b d = (a + b)**0.5 cost.append((d, (i + 1, j + 1))) cost.append((d, (j + 1, i + 1))) # Krushkal Algorithm for Minimum # spanning tree cost.sort() ans = 0.00 for i in cost: c = i[0] a = i[1][0] b = i[1][1] # If the parents are different if root(a) != root(b): Union(a, b) ans += c return ans # Driver codeif __name__ == \"__main__\": # Vector pairs of points points = [(1, 1), (2, 2), (2, 3)] # Function calling and printing # the answer print(minCost())",
"e": 9593,
"s": 7588,
"text": null
},
{
"code": null,
"e": 9601,
"s": 9593,
"text": "1.41421"
},
{
"code": null,
"e": 9650,
"s": 9603,
"text": "Time Complexity: O(N*N)Auxiliary Space: O(N*N)"
},
{
"code": null,
"e": 9658,
"s": 9650,
"text": "offbeat"
},
{
"code": null,
"e": 9675,
"s": 9658,
"text": "arorakashish0911"
},
{
"code": null,
"e": 9691,
"s": 9675,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 9704,
"s": 9691,
"text": "singghakshay"
},
{
"code": null,
"e": 9731,
"s": 9704,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 9747,
"s": 9731,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 9760,
"s": 9747,
"text": "disjoint-set"
},
{
"code": null,
"e": 9779,
"s": 9760,
"text": "Kruskal'sAlgorithm"
},
{
"code": null,
"e": 9803,
"s": 9779,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 9814,
"s": 9803,
"text": "Algorithms"
},
{
"code": null,
"e": 9820,
"s": 9814,
"text": "Graph"
},
{
"code": null,
"e": 9826,
"s": 9820,
"text": "Graph"
},
{
"code": null,
"e": 9837,
"s": 9826,
"text": "Algorithms"
},
{
"code": null,
"e": 9935,
"s": 9837,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9964,
"s": 9935,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 10044,
"s": 9964,
"text": "Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)"
},
{
"code": null,
"e": 10086,
"s": 10044,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 10132,
"s": 10086,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 10175,
"s": 10132,
"text": "Segment Tree | Set 2 (Range Minimum Query)"
},
{
"code": null,
"e": 10200,
"s": 10175,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 10249,
"s": 10200,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 10293,
"s": 10249,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 10324,
"s": 10293,
"text": "Difference between BFS and DFS"
}
] |
Sort linked list which is already sorted on absolute values | 30 Jun, 2022
Given a linked list that is sorted based on absolute values. Sort the list based on actual values.
Examples:
Input : 1 -> -10
output: -10 -> 1
Input : 1 -> -2 -> -3 -> 4 -> -5
output: -5 -> -3 -> -2 -> 1 -> 4
Input : -5 -> -10
Output: -10 -> -5
Input : 5 -> 10
output: 5 -> 10
Source : Amazon Interview
A simple solution is to traverse the linked list from beginning to end. For every visited node, check if it is out of order. If it is, remove it from its current position and insert it at the correct position. This is the implementation of insertion sort for linked list and the time complexity of this solution is O(n*n).
A better solution is to sort the linked list using merge sort. Time complexity of this solution is O(n Log n).
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
An efficient solution can work in O(n) time. An important observation is, all negative elements are present in reverse order. So we traverse the list, whenever we find an element that is out of order, we move it to the front of the linked list.
Below is the implementation of the above idea.
C++
Java
Python3
C#
Javascript
// C++ program to sort a linked list, already// sorted by absolute values#include <bits/stdc++.h>using namespace std; // Linked List Nodestruct Node{ Node* next; int data;}; // Utility function to insert a node at the// beginningvoid push(Node** head, int data){ Node* newNode = new Node; newNode->next = (*head); newNode->data = data; (*head) = newNode;} // Utility function to print a linked listvoid printList(Node* head){ while (head != NULL) { cout << head->data; if (head->next != NULL) cout << " -> "; head = head->next; } cout<<endl;} // To sort a linked list by actual values.// The list is assumed to be sorted by absolute// values.void sortList(Node** head){ // Initialize previous and current nodes Node* prev = (*head); Node* curr = (*head)->next; // Traverse list while (curr != NULL) { // If curr is smaller than prev, then // it must be moved to head if (curr->data < prev->data) { // Detach curr from linked list prev->next = curr->next; // Move current node to beginning curr->next = (*head); (*head) = curr; // Update current curr = prev; } // Nothing to do if current element // is at right place else prev = curr; // Move current curr = curr->next; }} // Driver codeint main(){ Node* head = NULL; push(&head, -5); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, -2); push(&head, 1); push(&head, 0); cout << "Original list :\n"; printList(head); sortList(&head); cout << "\nSorted list :\n"; printList(head); return 0;}
// Java program to sort a linked list, already// sorted by absolute valuesclass SortList{ static Node head; // head of list /* Linked list Node*/ static class Node { int data; Node next; Node(int d) {data = d; next = null; } } // To sort a linked list by actual values. // The list is assumed to be sorted by absolute // values. Node sortedList(Node head) { // Initialize previous and current nodes Node prev = head; Node curr = head.next; // Traverse list while(curr != null) { // If curr is smaller than prev, then // it must be moved to head if(curr.data < prev.data) { // Detach curr from linked list prev.next = curr.next; // Move current node to beginning curr.next = head; head = curr; // Update current curr = prev; } // Nothing to do if current element // is at right place else prev = curr; // Move current curr = curr.next; } return head; } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList(Node head) { Node temp = head; while (temp != null) { System.out.print(temp.data+" "); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { SortList llist = new SortList(); /* Constructed Linked List is 1->2->3->4->5->6-> 7->8->8->9->null */ llist.push(-5); llist.push(5); llist.push(4); llist.push(3); llist.push(-2); llist.push(1); llist.push(0); System.out.println("Original List :"); llist.printList(llist.head); llist.head = llist.sortedList(head); System.out.println("Sorted list :"); llist.printList(llist.head); }} // This code has been contributed by Amit Khandelwal(Amit Khandelwal 1).
# Python3 program to sort a linked list,# already sorted by absolute values # Linked list Nodeclass Node: def __init__(self, d): self.data = d self.next = None class SortList: def __init__(self): self.head = None # To sort a linked list by actual values. # The list is assumed to be sorted by # absolute values. def sortedList(self, head): # Initialize previous and # current nodes prev = self.head curr = self.head.next # Traverse list while(curr != None): # If curr is smaller than prev, # then it must be moved to head if(curr.data < prev.data): # Detach curr from linked list prev.next = curr.next # Move current node to beginning curr.next = self.head self.head = curr # Update current curr = prev # Nothing to do if current element # is at right place else: prev = curr # Move current curr = curr.next return self.head # Inserts a new Node at front of the list def push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # Function to print linked list def printList(self, head): temp = head while (temp != None): print(temp.data, end = " ") temp = temp.next print() # Driver Codellist = SortList() # Constructed Linked List is # 1->2->3->4->5->6->7->8->8->9->nullllist.push(-5)llist.push(5)llist.push(4)llist.push(3)llist.push(-2)llist.push(1)llist.push(0) print("Original List :")llist.printList(llist.head) start = llist.sortedList(llist.head) print("Sorted list :")llist.printList(start) # This code is contributed by# Prerna Saini
// C# program to sort a linked list, already// sorted by absolute valuesusing System; public class SortList{ Node head; // head of list /* Linked list Node*/ class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // To sort a linked list by actual values. // The list is assumed to be sorted by absolute // values. Node sortedList(Node head) { // Initialize previous and current nodes Node prev = head; Node curr = head.next; // Traverse list while(curr != null) { // If curr is smaller than prev, then // it must be moved to head if(curr.data < prev.data) { // Detach curr from linked list prev.next = curr.next; // Move current node to beginning curr.next = head; head = curr; // Update current curr = prev; } // Nothing to do if current element // is at right place else prev = curr; // Move current curr = curr.next; } return head; } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList(Node head) { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String []args) { SortList llist = new SortList(); /* Constructed Linked List is 1->2->3-> 4->5->6->7->8->8->9->null */ llist.push(-5); llist.push(5); llist.push(4); llist.push(3); llist.push(-2); llist.push(1); llist.push(0); Console.WriteLine("Original List :"); llist.printList(llist.head); llist.head = llist.sortedList(llist.head); Console.WriteLine("Sorted list :"); llist.printList(llist.head); }} /* This code is contributed by 29AjayKumar */
<script> // Javascript program to sort a linked list, already// sorted by absolute values var head; // head of list /* Linked list Node */ class Node { constructor(d) { this.data = d; this.next = null; } } // To sort a linked list by actual values. // The list is assumed to be sorted by absolute // values. function sortedList(head) { // Initialize previous and current nodes var prev = head; var curr = head.next; // Traverse list while (curr != null) { // If curr is smaller than prev, then // it must be moved to head if (curr.data < prev.data) { // Detach curr from linked list prev.next = curr.next; // Move current node to beginning curr.next = head; head = curr; // Update current curr = prev; } // Nothing to do if current element // is at right place else prev = curr; // Move current curr = curr.next; } return head; } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ function printList(head) {var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write("<br/>"); } /* Driver program to test above functions */ /* Constructed Linked List is 1->2->3->4->5->6-> 7->8->8->9->null */ push(-5); push(5); push(4); push(3); push(-2); push(1); push(0); document.write("Original List :<br/>"); printList(head); head = sortedList(head); document.write("Sorted list :<br/>"); printList(head); // This code contributed by aashish1995 </script>
Original list :
0 -> 1 -> -2 -> 3 -> 4 -> 5 -> -5
Sorted list :
-5 -> -2 -> 0 -> 1 -> 3 -> 4 -> 5
Output:
Original list :
0 -> 1 -> -2 -> 3 -> 4 -> 5 -> -5
Sorted list :
-5 -> -2 -> 0 -> 1 -> 3 -> 4 -> 5
Time Complexity: O(N)Auxiliary Space: O(1)
This article is contributed by Rahul Titare. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
29AjayKumar
prerna saini
aashish1995
rohitsingh07052
hardikkoriintern
Amazon
Insertion Sort
Linked-List-Sorting
Merge Sort
Linked List
Amazon
Linked List
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 153,
"s": 54,
"text": "Given a linked list that is sorted based on absolute values. Sort the list based on actual values."
},
{
"code": null,
"e": 165,
"s": 153,
"text": "Examples: "
},
{
"code": null,
"e": 342,
"s": 165,
"text": "Input : 1 -> -10 \noutput: -10 -> 1\n\nInput : 1 -> -2 -> -3 -> 4 -> -5 \noutput: -5 -> -3 -> -2 -> 1 -> 4 \n\nInput : -5 -> -10 \nOutput: -10 -> -5\n\nInput : 5 -> 10 \noutput: 5 -> 10"
},
{
"code": null,
"e": 368,
"s": 342,
"text": "Source : Amazon Interview"
},
{
"code": null,
"e": 691,
"s": 368,
"text": "A simple solution is to traverse the linked list from beginning to end. For every visited node, check if it is out of order. If it is, remove it from its current position and insert it at the correct position. This is the implementation of insertion sort for linked list and the time complexity of this solution is O(n*n)."
},
{
"code": null,
"e": 802,
"s": 691,
"text": "A better solution is to sort the linked list using merge sort. Time complexity of this solution is O(n Log n)."
},
{
"code": null,
"e": 811,
"s": 802,
"text": "Chapters"
},
{
"code": null,
"e": 838,
"s": 811,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 888,
"s": 838,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 911,
"s": 888,
"text": "captions off, selected"
},
{
"code": null,
"e": 919,
"s": 911,
"text": "English"
},
{
"code": null,
"e": 943,
"s": 919,
"text": "This is a modal window."
},
{
"code": null,
"e": 1012,
"s": 943,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1034,
"s": 1012,
"text": "End of dialog window."
},
{
"code": null,
"e": 1280,
"s": 1034,
"text": "An efficient solution can work in O(n) time. An important observation is, all negative elements are present in reverse order. So we traverse the list, whenever we find an element that is out of order, we move it to the front of the linked list. "
},
{
"code": null,
"e": 1328,
"s": 1280,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 1332,
"s": 1328,
"text": "C++"
},
{
"code": null,
"e": 1337,
"s": 1332,
"text": "Java"
},
{
"code": null,
"e": 1345,
"s": 1337,
"text": "Python3"
},
{
"code": null,
"e": 1348,
"s": 1345,
"text": "C#"
},
{
"code": null,
"e": 1359,
"s": 1348,
"text": "Javascript"
},
{
"code": "// C++ program to sort a linked list, already// sorted by absolute values#include <bits/stdc++.h>using namespace std; // Linked List Nodestruct Node{ Node* next; int data;}; // Utility function to insert a node at the// beginningvoid push(Node** head, int data){ Node* newNode = new Node; newNode->next = (*head); newNode->data = data; (*head) = newNode;} // Utility function to print a linked listvoid printList(Node* head){ while (head != NULL) { cout << head->data; if (head->next != NULL) cout << \" -> \"; head = head->next; } cout<<endl;} // To sort a linked list by actual values.// The list is assumed to be sorted by absolute// values.void sortList(Node** head){ // Initialize previous and current nodes Node* prev = (*head); Node* curr = (*head)->next; // Traverse list while (curr != NULL) { // If curr is smaller than prev, then // it must be moved to head if (curr->data < prev->data) { // Detach curr from linked list prev->next = curr->next; // Move current node to beginning curr->next = (*head); (*head) = curr; // Update current curr = prev; } // Nothing to do if current element // is at right place else prev = curr; // Move current curr = curr->next; }} // Driver codeint main(){ Node* head = NULL; push(&head, -5); push(&head, 5); push(&head, 4); push(&head, 3); push(&head, -2); push(&head, 1); push(&head, 0); cout << \"Original list :\\n\"; printList(head); sortList(&head); cout << \"\\nSorted list :\\n\"; printList(head); return 0;}",
"e": 3103,
"s": 1359,
"text": null
},
{
"code": "// Java program to sort a linked list, already// sorted by absolute valuesclass SortList{ static Node head; // head of list /* Linked list Node*/ static class Node { int data; Node next; Node(int d) {data = d; next = null; } } // To sort a linked list by actual values. // The list is assumed to be sorted by absolute // values. Node sortedList(Node head) { // Initialize previous and current nodes Node prev = head; Node curr = head.next; // Traverse list while(curr != null) { // If curr is smaller than prev, then // it must be moved to head if(curr.data < prev.data) { // Detach curr from linked list prev.next = curr.next; // Move current node to beginning curr.next = head; head = curr; // Update current curr = prev; } // Nothing to do if current element // is at right place else prev = curr; // Move current curr = curr.next; } return head; } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList(Node head) { Node temp = head; while (temp != null) { System.out.print(temp.data+\" \"); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { SortList llist = new SortList(); /* Constructed Linked List is 1->2->3->4->5->6-> 7->8->8->9->null */ llist.push(-5); llist.push(5); llist.push(4); llist.push(3); llist.push(-2); llist.push(1); llist.push(0); System.out.println(\"Original List :\"); llist.printList(llist.head); llist.head = llist.sortedList(head); System.out.println(\"Sorted list :\"); llist.printList(llist.head); }} // This code has been contributed by Amit Khandelwal(Amit Khandelwal 1).",
"e": 5721,
"s": 3103,
"text": null
},
{
"code": "# Python3 program to sort a linked list,# already sorted by absolute values # Linked list Nodeclass Node: def __init__(self, d): self.data = d self.next = None class SortList: def __init__(self): self.head = None # To sort a linked list by actual values. # The list is assumed to be sorted by # absolute values. def sortedList(self, head): # Initialize previous and # current nodes prev = self.head curr = self.head.next # Traverse list while(curr != None): # If curr is smaller than prev, # then it must be moved to head if(curr.data < prev.data): # Detach curr from linked list prev.next = curr.next # Move current node to beginning curr.next = self.head self.head = curr # Update current curr = prev # Nothing to do if current element # is at right place else: prev = curr # Move current curr = curr.next return self.head # Inserts a new Node at front of the list def push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # Function to print linked list def printList(self, head): temp = head while (temp != None): print(temp.data, end = \" \") temp = temp.next print() # Driver Codellist = SortList() # Constructed Linked List is # 1->2->3->4->5->6->7->8->8->9->nullllist.push(-5)llist.push(5)llist.push(4)llist.push(3)llist.push(-2)llist.push(1)llist.push(0) print(\"Original List :\")llist.printList(llist.head) start = llist.sortedList(llist.head) print(\"Sorted list :\")llist.printList(start) # This code is contributed by# Prerna Saini",
"e": 7897,
"s": 5721,
"text": null
},
{
"code": "// C# program to sort a linked list, already// sorted by absolute valuesusing System; public class SortList{ Node head; // head of list /* Linked list Node*/ class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // To sort a linked list by actual values. // The list is assumed to be sorted by absolute // values. Node sortedList(Node head) { // Initialize previous and current nodes Node prev = head; Node curr = head.next; // Traverse list while(curr != null) { // If curr is smaller than prev, then // it must be moved to head if(curr.data < prev.data) { // Detach curr from linked list prev.next = curr.next; // Move current node to beginning curr.next = head; head = curr; // Update current curr = prev; } // Nothing to do if current element // is at right place else prev = curr; // Move current curr = curr.next; } return head; } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList(Node head) { Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String []args) { SortList llist = new SortList(); /* Constructed Linked List is 1->2->3-> 4->5->6->7->8->8->9->null */ llist.push(-5); llist.push(5); llist.push(4); llist.push(3); llist.push(-2); llist.push(1); llist.push(0); Console.WriteLine(\"Original List :\"); llist.printList(llist.head); llist.head = llist.sortedList(llist.head); Console.WriteLine(\"Sorted list :\"); llist.printList(llist.head); }} /* This code is contributed by 29AjayKumar */",
"e": 10472,
"s": 7897,
"text": null
},
{
"code": "<script> // Javascript program to sort a linked list, already// sorted by absolute values var head; // head of list /* Linked list Node */ class Node { constructor(d) { this.data = d; this.next = null; } } // To sort a linked list by actual values. // The list is assumed to be sorted by absolute // values. function sortedList(head) { // Initialize previous and current nodes var prev = head; var curr = head.next; // Traverse list while (curr != null) { // If curr is smaller than prev, then // it must be moved to head if (curr.data < prev.data) { // Detach curr from linked list prev.next = curr.next; // Move current node to beginning curr.next = head; head = curr; // Update current curr = prev; } // Nothing to do if current element // is at right place else prev = curr; // Move current curr = curr.next; } return head; } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ function printList(head) {var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } document.write(\"<br/>\"); } /* Driver program to test above functions */ /* Constructed Linked List is 1->2->3->4->5->6-> 7->8->8->9->null */ push(-5); push(5); push(4); push(3); push(-2); push(1); push(0); document.write(\"Original List :<br/>\"); printList(head); head = sortedList(head); document.write(\"Sorted list :<br/>\"); printList(head); // This code contributed by aashish1995 </script>",
"e": 12734,
"s": 10472,
"text": null
},
{
"code": null,
"e": 12834,
"s": 12734,
"text": "Original list :\n0 -> 1 -> -2 -> 3 -> 4 -> 5 -> -5\n\nSorted list :\n-5 -> -2 -> 0 -> 1 -> 3 -> 4 -> 5\n"
},
{
"code": null,
"e": 12843,
"s": 12834,
"text": "Output: "
},
{
"code": null,
"e": 12942,
"s": 12843,
"text": "Original list :\n0 -> 1 -> -2 -> 3 -> 4 -> 5 -> -5\n\nSorted list :\n-5 -> -2 -> 0 -> 1 -> 3 -> 4 -> 5"
},
{
"code": null,
"e": 12985,
"s": 12942,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 13155,
"s": 12985,
"text": "This article is contributed by Rahul Titare. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 13167,
"s": 13155,
"text": "29AjayKumar"
},
{
"code": null,
"e": 13180,
"s": 13167,
"text": "prerna saini"
},
{
"code": null,
"e": 13192,
"s": 13180,
"text": "aashish1995"
},
{
"code": null,
"e": 13208,
"s": 13192,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 13225,
"s": 13208,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 13232,
"s": 13225,
"text": "Amazon"
},
{
"code": null,
"e": 13247,
"s": 13232,
"text": "Insertion Sort"
},
{
"code": null,
"e": 13267,
"s": 13247,
"text": "Linked-List-Sorting"
},
{
"code": null,
"e": 13278,
"s": 13267,
"text": "Merge Sort"
},
{
"code": null,
"e": 13290,
"s": 13278,
"text": "Linked List"
},
{
"code": null,
"e": 13297,
"s": 13290,
"text": "Amazon"
},
{
"code": null,
"e": 13309,
"s": 13297,
"text": "Linked List"
},
{
"code": null,
"e": 13320,
"s": 13309,
"text": "Merge Sort"
}
] |
PDFBox - Reading Text | In the previous chapter, we have seen how to add text to an existing PDF document. In this chapter, we will discuss how to read text from an existing PDF document.
Extracting text is one of the main features of the PDF box library. You can extract text using the getText() method of the PDFTextStripper class. This class extracts all the text from the given PDF document.
Following are the steps to extract text from an existing PDF document.
Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File("path of the document")
PDDocument document = PDDocument.load(file);
The PDFTextStripper class provides methods to retrieve text from a PDF document therefore, instantiate this class as shown below.
PDFTextStripper pdfStripper = new PDFTextStripper();
You can read/retrieve the contents of a page from the PDF document using the getText() method of the PDFTextStripper class. To this method you need to pass the document object as a parameter. This method retrieves the text in a given document and returns it in the form of a String object.
String text = pdfStripper.getText(document);
Finally, close the document using the close() method of the PDDocument class as shown below.
document.close();
Suppose, we have a PDF document with some text in it as shown below.
This example demonstrates how to read text from the above mentioned PDF document. Here, we will create a Java program and load a PDF document named new.pdf, which is saved in the path C:/PdfBox_Examples/. Save this code in a file with name ReadingText.java.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class ReadingText {
public static void main(String args[]) throws IOException {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/new.pdf");
PDDocument document = PDDocument.load(file);
//Instantiate PDFTextStripper class
PDFTextStripper pdfStripper = new PDFTextStripper();
//Retrieving text from PDF document
String text = pdfStripper.getText(document);
System.out.println(text);
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac ReadingText.java
java ReadingText
Upon execution, the above program retrieves the text from the given PDF document and displays it as shown below.
This is an example of adding text to a page in the pdf document. we can add as many lines
as we want like this using the ShowText() method of the ContentStream class.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2191,
"s": 2027,
"text": "In the previous chapter, we have seen how to add text to an existing PDF document. In this chapter, we will discuss how to read text from an existing PDF document."
},
{
"code": null,
"e": 2399,
"s": 2191,
"text": "Extracting text is one of the main features of the PDF box library. You can extract text using the getText() method of the PDFTextStripper class. This class extracts all the text from the given PDF document."
},
{
"code": null,
"e": 2470,
"s": 2399,
"text": "Following are the steps to extract text from an existing PDF document."
},
{
"code": null,
"e": 2687,
"s": 2470,
"text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below."
},
{
"code": null,
"e": 2779,
"s": 2687,
"text": "File file = new File(\"path of the document\") \nPDDocument document = PDDocument.load(file);\n"
},
{
"code": null,
"e": 2909,
"s": 2779,
"text": "The PDFTextStripper class provides methods to retrieve text from a PDF document therefore, instantiate this class as shown below."
},
{
"code": null,
"e": 2963,
"s": 2909,
"text": "PDFTextStripper pdfStripper = new PDFTextStripper();\n"
},
{
"code": null,
"e": 3253,
"s": 2963,
"text": "You can read/retrieve the contents of a page from the PDF document using the getText() method of the PDFTextStripper class. To this method you need to pass the document object as a parameter. This method retrieves the text in a given document and returns it in the form of a String object."
},
{
"code": null,
"e": 3299,
"s": 3253,
"text": "String text = pdfStripper.getText(document);\n"
},
{
"code": null,
"e": 3392,
"s": 3299,
"text": "Finally, close the document using the close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 3411,
"s": 3392,
"text": "document.close();\n"
},
{
"code": null,
"e": 3480,
"s": 3411,
"text": "Suppose, we have a PDF document with some text in it as shown below."
},
{
"code": null,
"e": 3738,
"s": 3480,
"text": "This example demonstrates how to read text from the above mentioned PDF document. Here, we will create a Java program and load a PDF document named new.pdf, which is saved in the path C:/PdfBox_Examples/. Save this code in a file with name ReadingText.java."
},
{
"code": null,
"e": 4408,
"s": 3738,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.pdfbox.pdmodel.PDDocument;\nimport org.apache.pdfbox.text.PDFTextStripper;\npublic class ReadingText {\n\n public static void main(String args[]) throws IOException {\n\n //Loading an existing document\n File file = new File(\"C:/PdfBox_Examples/new.pdf\");\n PDDocument document = PDDocument.load(file);\n\n //Instantiate PDFTextStripper class\n PDFTextStripper pdfStripper = new PDFTextStripper();\n\n //Retrieving text from PDF document\n String text = pdfStripper.getText(document);\n System.out.println(text);\n\n //Closing the document\n document.close();\n\n }\n}"
},
{
"code": null,
"e": 4502,
"s": 4408,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 4544,
"s": 4502,
"text": "javac ReadingText.java \njava ReadingText\n"
},
{
"code": null,
"e": 4657,
"s": 4544,
"text": "Upon execution, the above program retrieves the text from the given PDF document and displays it as shown below."
},
{
"code": null,
"e": 4825,
"s": 4657,
"text": "This is an example of adding text to a page in the pdf document. we can add as many lines\nas we want like this using the ShowText() method of the ContentStream class.\n"
},
{
"code": null,
"e": 4832,
"s": 4825,
"text": " Print"
},
{
"code": null,
"e": 4843,
"s": 4832,
"text": " Add Notes"
}
] |
Building a Book Recommender Engine from Scratch and Deploying it to a Web Application | by Zach Alexander | Towards Data Science | Recommendation systems, whether we like them or not, are infiltrating every aspect of our lives. From the queue of shows and movies underneath the “Because you watched” header on your Netflix profile, to the “Made for you” song lists on Spotify, we’ve entered an era where content, media, and information are tailored to our unique interests.
Although this may be common knowledge, what may be less apparent is what goes on behind the scenes to serve these recommendations to users. We often hear about “algorithms” and “machine learning” that make up the backbone of these systems, but beyond that, we typically leave the rest to imagination.
After recently taking a Recommender Systems class in graduate school, I dove into some of the linear algebra and software behind these engines. By the last two weeks of the course, I felt I had enough knowledge of the inner-workings of these systems to build a full production web application that serves book recommendations to users, utilizing PySpark’s distributive computing capabilities, PostgreSQL, Databricks, and Flask.
If interested in adapting the project, the code is available on my GitHub, and a description of my final project, including exploratory analysis and an example of the ALS algorithm in production can be found in a separate repo.
I’ve added the web application link to the end of this piece as well, but if you’d like to create an account and start rating books/receiving book recommendations, you can join here: https://zach-book-recommender.herokuapp.com/.
Now, before we take a look at my own engine, it may be helpful to provide some context of a few overarching topics about these systems. On a very basic level, recommender systems operate via machine learning algorithms. Typically, these algorithms can be classified into two categories — content-based and collaborative filtering.
Content-based methods measure the similarity of item attributes and focus on recommending other items similar to what the user likes, based on their previous actions or explicit feedback (i.e., via surveys or ratings).
Although content-based methods are quite effective in some instances, they do have their drawbacks. Collaborative filtering methods operate differently, and do their best to address some of the limitations of content-based filtering. With collaborative filtering, algorithms use similarities between users and items simultaneously to provide recommendations. Essentially, the underlying models are designed to recommend an item to User A based on interests of a similar User B.
Collaborative filtering can be achieved in myriad ways, however, one common method is to use matrix factorization and dimensionality reduction techniques. Algorithms like Alternating Least Squares (ALS), Singular Value Decomposition (SVD), and Stochastic Gradient Decent (SGD) do this quite well, and while working with large volumes of data (i.e., 1M+ data points), these algorithms in conjunction with distributive computing and parallel processing are good working solutions to build production-ready applications with large volumes of data.
If you are interested in learning more about these techniques, I’d recommend reading more in these excellent TDS pieces:
For Alternating Least Squares (ALS)
For Singular Value Decomposition (SVD)
For Stochastic Gradient Decent (SGD)
With some baseline knowledge of how these algorithms work, I’ll jump into my own project, and use of ALS to serve book recommendations to users.
Before diving into each component of building the application, I’ll outline the overall flow of how it works and the technologies used to serve recommendations to users in the Flask web app:
As we can see, it’s a pretty intricate system that relies heavily on distributed computing in Spark to process around 1 million book ratings and compute updated recommendations to users every hour. It also depends on an important connection between the deployed PostgreSQL database and the Amazon Web Services cluster that contains my ALS algorithm.
With the overall flow established above, we can now break down each step of building the engine.
As a first step, it was imperative to find a large user-book dataset that would work well with my choice of algorithms and would provide reliable predictions and recommendations to users.
Therefore, I did some exploratory analysis and decided to use the goodbooks-10k dataset. According to Kaggle, this dataset contains close to 1 million ratings across 10,000 different books located on a popular book platform, Goodreads. With this dataset in hand, I noticed a few things:
The dataset contained a total of 53,425 users that have supplied ratings for at least 10 books.
The average book rating was about 3.85, with 4 being the most common rating on a likert scale of 1 to 5. Therefore, most ratings were quite positive.
As expected, the dataset was very sparse (~99.82% of the ratings file was blank).
Some of the most highly rated books in the dataset were household favorites, including parts of the Calvin and Hobbes collection, Harry Potter, and a few books with religious principles.
To examine some of this exploratory analysis, you can go to this jupyter notebook.
Next, after doing some exploratory analysis, I decided to build out a simple python Flask application in order to allow new users to do the following:
Register/sign-in under a specific username
Load a profile page that displays a history of a user’s rated books and provides navigation to either rate more books or view recommended books (see an example below):
Incorporate a search feature that interacts with the Goodreads API to allow users to search for a book by title name, and then rate the book on a scale of 1–5 (see example below):
After rating a few books, the user can then see their individualized recommendations on a separate page (will be shown later in the article).
As an important note, these user ratings from the application were then incorporated back into the robust goodbooks dataset and eventually into the ALS algorithm. By setting up a PostgreSQL database, I was able to match new user ids, their ratings and the book ids to this original dataset. Therefore, whenever a new rating comes in from a user, it is appended to the ratings dataset which I used later for my recommender engine.
After doing a lot of testing locally to ensure that book ids and user ids matched in the database, I deployed the application with Heroku.
For instructions on how to deploy a Flask application and a corresponding PostgreSQL database with Heroku, you can refer to this extremely helpful YouTube tutorial by Brad Traversy. Specifics for deploying with Heroku can also be found in this piece.
With the application functionality set up and deployed, I then used Databricks and Pyspark to build out an Alternating Least Squares (ALS) algorithm that absorbs my ratings dataset from my PostgreSQL database, computes the updated predictions based on matrix factorization techniques established in Databricks, and then recommends books to each user based on the highest predicted scores per user.
Here’s a bit of code below that outlines this process:
First, I set up a schema for a Spark dataframe before I read in the ratings table from PostgreSQL:
from pyspark.sql.types import StructType, StructFieldfrom pyspark.sql.types import DoubleType, IntegerType, StringTyperatings_schema = StructType([ StructField("col_id", IntegerType()), StructField("userid", IntegerType()), StructField("rating", DoubleType()), StructField("book_id", IntegerType()), StructField("username", StringType()), StructField("isbn10", StringType())])
Then, after setting up our environment variables and a JDBC connection to my remote PostgreSQL database, I read in the table and saved it as a Spark dataframe:
remote_table = spark.read.format("jdbc")\ .option("driver", driver)\ .option("inferSchema", ratings_schema) \ .option("url", url)\ .option("dbtable", table)\ .option("user", user)\ .option("password", password)\ .load()
With the Spark dataframe loaded into Databricks, I then started to set up the data to run my ALS model. First, I split the dataframe into a training, validation and testing dataset — 60% training, 20% validation and 20% testing. The validation dataset was used to test the fine-tuning of my model parameters, and allowed me to have a hold-out test set that I used to compute the Root Mean Square Error (RMSE) on the final, optimized model.
(training, validation, test) = remote_table.randomSplit([0.6, 0.2, 0.2]) # caching data to cut down on cross-validation time later training.cache() validation.cache() test.cache()
With the data split, I did some fine-tuning of the model to determine the optimal parameters. Then, I ran the ALS model with these optimal parameters, and fit this to the training dataset.
als = ALS(maxIter=10, regParam=0.20, userCol="userid", itemCol="book_id", ratingCol="rating", coldStartStrategy="drop", nonnegative = True, implicitPrefs = False).setRank(50)model = als.fit(training)
You’ll notice, that I set the rank of the matrix to 50, which cut down on processing time and still yielded valuable predictions. I then was able to use this model to compute predictions on the test dataset and determine the RMSE value.
predictions = model.transform(test)rmse = evaluator.evaluate(predictions)
In the end, I was able to get the RMSE value around 0.9, which for our purposes, and a likert scale of 1–5, isn’t too bad. I then was able to use this model to generate predictions and recommendations for the full ratings dataset. To do this, I used the recommendForAllUsers() function in PySpark, to find the 10 highest rated books for each user.
ALS_recommendations = model.recommendForAllUsers(numItems = 10)# Temporary table ALS_recommendations.registerTempTable("ALS_recs_temp") clean_recs = spark.sql("""SELECT userid, bookIds_and_ratings.book_id AS book_id, bookIds_and_ratings.rating AS prediction FROM ALS_recs_temp LATERAL VIEW explode(recommendations) exploded_table AS bookIds_and_ratings""")clean_recs.join(remote_table, ["userid", "book_id"], "left").filter(remote_table.rating.isNull()).show()clean_recs_filtered = clean_recs.select("userid", "book_id", "prediction")
After creating a temporary table to re-orient the recommendations, I then wanted to ensure that books that a user in the application rated (and implicitly read), would not be recommended back to them in the app. Therefore, I did some additional cleaning to only recommend new books to users:
new_books = (clean_recs_filtered.join(remote_table, ["userid", "book_id"], "left").filter(remote_table.rating.isNull()))
As a final step, I identified only user ids that had signed up via my application to append recommendations back to the PostgreSQL database. Because there was such a large number of predictions and ratings from the initial goodbooks dataset that would go back to nonexistent users, I filtered to only include recommendations for users that joined through the web application:
new_books_fnl = new_books.select('userid', 'book_id', 'prediction')new_books_users = new_books_fnl.filter(new_books_fnl['userid'] > 53424)new_books_use = new_books_users.select('userid', 'book_id', 'prediction')
And here’s an example of recommendations served back to users that have joined the web application:
We now have recommendations for users in the web app!
As we can see, some of the predictions aren’t very good — for instance the first user in the table will be served a book that the algorithm predicted they would rate around a 3.5/4. Ideally we want to find books that users will really like (without thinking about components such as serendipity, novelty, etc.). Therefore, with more time and a broader user base, I hope to see recommended books with higher predicted ratings.
With the model working locally in Databricks, I then was able to upload this optimized model and deploy it to an Amazon Web Services cluster, running a cronjob every hour to process any new ratings that are absorbed into my PostgreSQL database. The hourly cronjob essentially will re-run the model, re-compute the predictions and recommendations, and then overwrite a recommendations table in my PostgreSQL with the updated recommendations. This is then connected back to my Flask app to serve to users. For deployment instructions related to AWS and Databricks, you can find some documentation here.
With the recommendations table in my PostgreSQL updated with my recommendations and their corresponding book ids, I could then utilize the Goodreads API to find the book information (i.e. picture, title, etc.) to build out on the front-end application.
In the end, I did some testing and noticed that the recommendations weren’t too bad! For instance, I created a few users that were data science fanatics, and rated a lot of Data Science books. I intentionally had some overlap in ratings of books across users, but also tried to rate a few new books for each user.
When I ran my model to serve up recommendations, I was pleased to see that books that were not rated by one data science fanatic were being recommended to them based on positive ratings from another data science fanatic, which demonstrates that my collaborative filtering technique was working. See an example below:
As we can see from the titles boxed in red, User 2 rated those two books very highly (rating of 5). Therefore, when running our machine learning algorithm, there was some overlap between User 1 and User 2’s book ratings — which meant that the books that weren’t rated by User 1 (and implicitly not read), but were rated highly by User 2, were then served as recommendations to User 1.
To give the application a try, go here: https://zach-book-recommender.herokuapp.com/
Although recommendations for data science books do seem to work pretty well, there is a large gap in other genres and topics. You’ll probably notice that your recommendations will also pull in other very highly rated books from the goodbooks-10k dataset (i.e. Calvin and Hobbes, etc.), until more users that are similar to your tastes join the app. Therefore, I’d recommend sharing it with friends, and see if over time, your recommendations start to get better and better!
If you enjoyed this piece, or found it helpful, please get in touch! I love collaborating with others on projects and learning from peers that are passionate about data science work.
You can also check out my data visualization portfolio, where I primarily work with Javascript and D3.js, and talk more about other projects I’ve done in grad school. | [
{
"code": null,
"e": 515,
"s": 172,
"text": "Recommendation systems, whether we like them or not, are infiltrating every aspect of our lives. From the queue of shows and movies underneath the “Because you watched” header on your Netflix profile, to the “Made for you” song lists on Spotify, we’ve entered an era where content, media, and information are tailored to our unique interests."
},
{
"code": null,
"e": 816,
"s": 515,
"text": "Although this may be common knowledge, what may be less apparent is what goes on behind the scenes to serve these recommendations to users. We often hear about “algorithms” and “machine learning” that make up the backbone of these systems, but beyond that, we typically leave the rest to imagination."
},
{
"code": null,
"e": 1244,
"s": 816,
"text": "After recently taking a Recommender Systems class in graduate school, I dove into some of the linear algebra and software behind these engines. By the last two weeks of the course, I felt I had enough knowledge of the inner-workings of these systems to build a full production web application that serves book recommendations to users, utilizing PySpark’s distributive computing capabilities, PostgreSQL, Databricks, and Flask."
},
{
"code": null,
"e": 1472,
"s": 1244,
"text": "If interested in adapting the project, the code is available on my GitHub, and a description of my final project, including exploratory analysis and an example of the ALS algorithm in production can be found in a separate repo."
},
{
"code": null,
"e": 1701,
"s": 1472,
"text": "I’ve added the web application link to the end of this piece as well, but if you’d like to create an account and start rating books/receiving book recommendations, you can join here: https://zach-book-recommender.herokuapp.com/."
},
{
"code": null,
"e": 2032,
"s": 1701,
"text": "Now, before we take a look at my own engine, it may be helpful to provide some context of a few overarching topics about these systems. On a very basic level, recommender systems operate via machine learning algorithms. Typically, these algorithms can be classified into two categories — content-based and collaborative filtering."
},
{
"code": null,
"e": 2251,
"s": 2032,
"text": "Content-based methods measure the similarity of item attributes and focus on recommending other items similar to what the user likes, based on their previous actions or explicit feedback (i.e., via surveys or ratings)."
},
{
"code": null,
"e": 2729,
"s": 2251,
"text": "Although content-based methods are quite effective in some instances, they do have their drawbacks. Collaborative filtering methods operate differently, and do their best to address some of the limitations of content-based filtering. With collaborative filtering, algorithms use similarities between users and items simultaneously to provide recommendations. Essentially, the underlying models are designed to recommend an item to User A based on interests of a similar User B."
},
{
"code": null,
"e": 3274,
"s": 2729,
"text": "Collaborative filtering can be achieved in myriad ways, however, one common method is to use matrix factorization and dimensionality reduction techniques. Algorithms like Alternating Least Squares (ALS), Singular Value Decomposition (SVD), and Stochastic Gradient Decent (SGD) do this quite well, and while working with large volumes of data (i.e., 1M+ data points), these algorithms in conjunction with distributive computing and parallel processing are good working solutions to build production-ready applications with large volumes of data."
},
{
"code": null,
"e": 3395,
"s": 3274,
"text": "If you are interested in learning more about these techniques, I’d recommend reading more in these excellent TDS pieces:"
},
{
"code": null,
"e": 3431,
"s": 3395,
"text": "For Alternating Least Squares (ALS)"
},
{
"code": null,
"e": 3470,
"s": 3431,
"text": "For Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 3507,
"s": 3470,
"text": "For Stochastic Gradient Decent (SGD)"
},
{
"code": null,
"e": 3652,
"s": 3507,
"text": "With some baseline knowledge of how these algorithms work, I’ll jump into my own project, and use of ALS to serve book recommendations to users."
},
{
"code": null,
"e": 3843,
"s": 3652,
"text": "Before diving into each component of building the application, I’ll outline the overall flow of how it works and the technologies used to serve recommendations to users in the Flask web app:"
},
{
"code": null,
"e": 4193,
"s": 3843,
"text": "As we can see, it’s a pretty intricate system that relies heavily on distributed computing in Spark to process around 1 million book ratings and compute updated recommendations to users every hour. It also depends on an important connection between the deployed PostgreSQL database and the Amazon Web Services cluster that contains my ALS algorithm."
},
{
"code": null,
"e": 4290,
"s": 4193,
"text": "With the overall flow established above, we can now break down each step of building the engine."
},
{
"code": null,
"e": 4478,
"s": 4290,
"text": "As a first step, it was imperative to find a large user-book dataset that would work well with my choice of algorithms and would provide reliable predictions and recommendations to users."
},
{
"code": null,
"e": 4765,
"s": 4478,
"text": "Therefore, I did some exploratory analysis and decided to use the goodbooks-10k dataset. According to Kaggle, this dataset contains close to 1 million ratings across 10,000 different books located on a popular book platform, Goodreads. With this dataset in hand, I noticed a few things:"
},
{
"code": null,
"e": 4861,
"s": 4765,
"text": "The dataset contained a total of 53,425 users that have supplied ratings for at least 10 books."
},
{
"code": null,
"e": 5011,
"s": 4861,
"text": "The average book rating was about 3.85, with 4 being the most common rating on a likert scale of 1 to 5. Therefore, most ratings were quite positive."
},
{
"code": null,
"e": 5093,
"s": 5011,
"text": "As expected, the dataset was very sparse (~99.82% of the ratings file was blank)."
},
{
"code": null,
"e": 5280,
"s": 5093,
"text": "Some of the most highly rated books in the dataset were household favorites, including parts of the Calvin and Hobbes collection, Harry Potter, and a few books with religious principles."
},
{
"code": null,
"e": 5363,
"s": 5280,
"text": "To examine some of this exploratory analysis, you can go to this jupyter notebook."
},
{
"code": null,
"e": 5514,
"s": 5363,
"text": "Next, after doing some exploratory analysis, I decided to build out a simple python Flask application in order to allow new users to do the following:"
},
{
"code": null,
"e": 5557,
"s": 5514,
"text": "Register/sign-in under a specific username"
},
{
"code": null,
"e": 5725,
"s": 5557,
"text": "Load a profile page that displays a history of a user’s rated books and provides navigation to either rate more books or view recommended books (see an example below):"
},
{
"code": null,
"e": 5905,
"s": 5725,
"text": "Incorporate a search feature that interacts with the Goodreads API to allow users to search for a book by title name, and then rate the book on a scale of 1–5 (see example below):"
},
{
"code": null,
"e": 6047,
"s": 5905,
"text": "After rating a few books, the user can then see their individualized recommendations on a separate page (will be shown later in the article)."
},
{
"code": null,
"e": 6477,
"s": 6047,
"text": "As an important note, these user ratings from the application were then incorporated back into the robust goodbooks dataset and eventually into the ALS algorithm. By setting up a PostgreSQL database, I was able to match new user ids, their ratings and the book ids to this original dataset. Therefore, whenever a new rating comes in from a user, it is appended to the ratings dataset which I used later for my recommender engine."
},
{
"code": null,
"e": 6616,
"s": 6477,
"text": "After doing a lot of testing locally to ensure that book ids and user ids matched in the database, I deployed the application with Heroku."
},
{
"code": null,
"e": 6867,
"s": 6616,
"text": "For instructions on how to deploy a Flask application and a corresponding PostgreSQL database with Heroku, you can refer to this extremely helpful YouTube tutorial by Brad Traversy. Specifics for deploying with Heroku can also be found in this piece."
},
{
"code": null,
"e": 7265,
"s": 6867,
"text": "With the application functionality set up and deployed, I then used Databricks and Pyspark to build out an Alternating Least Squares (ALS) algorithm that absorbs my ratings dataset from my PostgreSQL database, computes the updated predictions based on matrix factorization techniques established in Databricks, and then recommends books to each user based on the highest predicted scores per user."
},
{
"code": null,
"e": 7320,
"s": 7265,
"text": "Here’s a bit of code below that outlines this process:"
},
{
"code": null,
"e": 7419,
"s": 7320,
"text": "First, I set up a schema for a Spark dataframe before I read in the ratings table from PostgreSQL:"
},
{
"code": null,
"e": 7802,
"s": 7419,
"text": "from pyspark.sql.types import StructType, StructFieldfrom pyspark.sql.types import DoubleType, IntegerType, StringTyperatings_schema = StructType([ StructField(\"col_id\", IntegerType()), StructField(\"userid\", IntegerType()), StructField(\"rating\", DoubleType()), StructField(\"book_id\", IntegerType()), StructField(\"username\", StringType()), StructField(\"isbn10\", StringType())])"
},
{
"code": null,
"e": 7962,
"s": 7802,
"text": "Then, after setting up our environment variables and a JDBC connection to my remote PostgreSQL database, I read in the table and saved it as a Spark dataframe:"
},
{
"code": null,
"e": 8189,
"s": 7962,
"text": "remote_table = spark.read.format(\"jdbc\")\\ .option(\"driver\", driver)\\ .option(\"inferSchema\", ratings_schema) \\ .option(\"url\", url)\\ .option(\"dbtable\", table)\\ .option(\"user\", user)\\ .option(\"password\", password)\\ .load()"
},
{
"code": null,
"e": 8629,
"s": 8189,
"text": "With the Spark dataframe loaded into Databricks, I then started to set up the data to run my ALS model. First, I split the dataframe into a training, validation and testing dataset — 60% training, 20% validation and 20% testing. The validation dataset was used to test the fine-tuning of my model parameters, and allowed me to have a hold-out test set that I used to compute the Root Mean Square Error (RMSE) on the final, optimized model."
},
{
"code": null,
"e": 8810,
"s": 8629,
"text": "(training, validation, test) = remote_table.randomSplit([0.6, 0.2, 0.2]) # caching data to cut down on cross-validation time later training.cache() validation.cache() test.cache()"
},
{
"code": null,
"e": 8999,
"s": 8810,
"text": "With the data split, I did some fine-tuning of the model to determine the optimal parameters. Then, I ran the ALS model with these optimal parameters, and fit this to the training dataset."
},
{
"code": null,
"e": 9199,
"s": 8999,
"text": "als = ALS(maxIter=10, regParam=0.20, userCol=\"userid\", itemCol=\"book_id\", ratingCol=\"rating\", coldStartStrategy=\"drop\", nonnegative = True, implicitPrefs = False).setRank(50)model = als.fit(training)"
},
{
"code": null,
"e": 9436,
"s": 9199,
"text": "You’ll notice, that I set the rank of the matrix to 50, which cut down on processing time and still yielded valuable predictions. I then was able to use this model to compute predictions on the test dataset and determine the RMSE value."
},
{
"code": null,
"e": 9510,
"s": 9436,
"text": "predictions = model.transform(test)rmse = evaluator.evaluate(predictions)"
},
{
"code": null,
"e": 9858,
"s": 9510,
"text": "In the end, I was able to get the RMSE value around 0.9, which for our purposes, and a likert scale of 1–5, isn’t too bad. I then was able to use this model to generate predictions and recommendations for the full ratings dataset. To do this, I used the recommendForAllUsers() function in PySpark, to find the 10 highest rated books for each user."
},
{
"code": null,
"e": 10473,
"s": 9858,
"text": "ALS_recommendations = model.recommendForAllUsers(numItems = 10)# Temporary table ALS_recommendations.registerTempTable(\"ALS_recs_temp\") clean_recs = spark.sql(\"\"\"SELECT userid, bookIds_and_ratings.book_id AS book_id, bookIds_and_ratings.rating AS prediction FROM ALS_recs_temp LATERAL VIEW explode(recommendations) exploded_table AS bookIds_and_ratings\"\"\")clean_recs.join(remote_table, [\"userid\", \"book_id\"], \"left\").filter(remote_table.rating.isNull()).show()clean_recs_filtered = clean_recs.select(\"userid\", \"book_id\", \"prediction\")"
},
{
"code": null,
"e": 10765,
"s": 10473,
"text": "After creating a temporary table to re-orient the recommendations, I then wanted to ensure that books that a user in the application rated (and implicitly read), would not be recommended back to them in the app. Therefore, I did some additional cleaning to only recommend new books to users:"
},
{
"code": null,
"e": 10886,
"s": 10765,
"text": "new_books = (clean_recs_filtered.join(remote_table, [\"userid\", \"book_id\"], \"left\").filter(remote_table.rating.isNull()))"
},
{
"code": null,
"e": 11262,
"s": 10886,
"text": "As a final step, I identified only user ids that had signed up via my application to append recommendations back to the PostgreSQL database. Because there was such a large number of predictions and ratings from the initial goodbooks dataset that would go back to nonexistent users, I filtered to only include recommendations for users that joined through the web application:"
},
{
"code": null,
"e": 11474,
"s": 11262,
"text": "new_books_fnl = new_books.select('userid', 'book_id', 'prediction')new_books_users = new_books_fnl.filter(new_books_fnl['userid'] > 53424)new_books_use = new_books_users.select('userid', 'book_id', 'prediction')"
},
{
"code": null,
"e": 11574,
"s": 11474,
"text": "And here’s an example of recommendations served back to users that have joined the web application:"
},
{
"code": null,
"e": 11628,
"s": 11574,
"text": "We now have recommendations for users in the web app!"
},
{
"code": null,
"e": 12054,
"s": 11628,
"text": "As we can see, some of the predictions aren’t very good — for instance the first user in the table will be served a book that the algorithm predicted they would rate around a 3.5/4. Ideally we want to find books that users will really like (without thinking about components such as serendipity, novelty, etc.). Therefore, with more time and a broader user base, I hope to see recommended books with higher predicted ratings."
},
{
"code": null,
"e": 12655,
"s": 12054,
"text": "With the model working locally in Databricks, I then was able to upload this optimized model and deploy it to an Amazon Web Services cluster, running a cronjob every hour to process any new ratings that are absorbed into my PostgreSQL database. The hourly cronjob essentially will re-run the model, re-compute the predictions and recommendations, and then overwrite a recommendations table in my PostgreSQL with the updated recommendations. This is then connected back to my Flask app to serve to users. For deployment instructions related to AWS and Databricks, you can find some documentation here."
},
{
"code": null,
"e": 12908,
"s": 12655,
"text": "With the recommendations table in my PostgreSQL updated with my recommendations and their corresponding book ids, I could then utilize the Goodreads API to find the book information (i.e. picture, title, etc.) to build out on the front-end application."
},
{
"code": null,
"e": 13222,
"s": 12908,
"text": "In the end, I did some testing and noticed that the recommendations weren’t too bad! For instance, I created a few users that were data science fanatics, and rated a lot of Data Science books. I intentionally had some overlap in ratings of books across users, but also tried to rate a few new books for each user."
},
{
"code": null,
"e": 13539,
"s": 13222,
"text": "When I ran my model to serve up recommendations, I was pleased to see that books that were not rated by one data science fanatic were being recommended to them based on positive ratings from another data science fanatic, which demonstrates that my collaborative filtering technique was working. See an example below:"
},
{
"code": null,
"e": 13924,
"s": 13539,
"text": "As we can see from the titles boxed in red, User 2 rated those two books very highly (rating of 5). Therefore, when running our machine learning algorithm, there was some overlap between User 1 and User 2’s book ratings — which meant that the books that weren’t rated by User 1 (and implicitly not read), but were rated highly by User 2, were then served as recommendations to User 1."
},
{
"code": null,
"e": 14009,
"s": 13924,
"text": "To give the application a try, go here: https://zach-book-recommender.herokuapp.com/"
},
{
"code": null,
"e": 14483,
"s": 14009,
"text": "Although recommendations for data science books do seem to work pretty well, there is a large gap in other genres and topics. You’ll probably notice that your recommendations will also pull in other very highly rated books from the goodbooks-10k dataset (i.e. Calvin and Hobbes, etc.), until more users that are similar to your tastes join the app. Therefore, I’d recommend sharing it with friends, and see if over time, your recommendations start to get better and better!"
},
{
"code": null,
"e": 14666,
"s": 14483,
"text": "If you enjoyed this piece, or found it helpful, please get in touch! I love collaborating with others on projects and learning from peers that are passionate about data science work."
}
] |
How to flatten a given array up to the specified depth in JavaScript ? - GeeksforGeeks | 08 Apr, 2021
In this article, we will learn how to flatten a given array up to the specified depth in JavaScript.
The flat() method in JavaScript is used to flatten an array up to the required depth. It creates a new array and recursively concatenates the sub-arrays of the original array up to the given depth. The only parameter this method accepts is the optional depth parameter (by default: 1). This method can be also used for removing empty elements from the array.
Syntax:
array.flat(depth);
Example:
HTML
<html> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <b> How to flatten a given array up to the specified depth in JavaScript? </b> <script> // Define the array let arr = [1, [2, [3, [4, 5], 6], 7, 8], 9, 10]; console.log("Original Array:", arr); let flatArrOne = arr.flat(); console.log( "Array flattened to depth of 1:", flatArrOne ); let flatArrTwo = arr.flat(2); console.log( "Array flattened to depth of 2:", flatArrTwo ); let flatArrThree = arr.flat(Infinity); console.log( "Array flattened completely:", flatArrThree ); </script> </body></html>
Output:
Original Array: [1, [2, [3, [4, 5], 6], 7, 8], 9, 10]
Array flattened to depth of 1: [1, 2, [3, [4, 5], 6], 7, 8, 9, 10]
Array flattened to depth of 2: [1, 2, 3, [4, 5], 6, 7, 8, 9, 10]
Array flattened completely: [1, [2, [3, [4, 5], 6], 7, 8], 9, 10]
javascript-array
javascript-math
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 37890,
"s": 37862,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 37991,
"s": 37890,
"text": "In this article, we will learn how to flatten a given array up to the specified depth in JavaScript."
},
{
"code": null,
"e": 38350,
"s": 37991,
"text": "The flat() method in JavaScript is used to flatten an array up to the required depth. It creates a new array and recursively concatenates the sub-arrays of the original array up to the given depth. The only parameter this method accepts is the optional depth parameter (by default: 1). This method can be also used for removing empty elements from the array."
},
{
"code": null,
"e": 38358,
"s": 38350,
"text": "Syntax:"
},
{
"code": null,
"e": 38377,
"s": 38358,
"text": "array.flat(depth);"
},
{
"code": null,
"e": 38386,
"s": 38377,
"text": "Example:"
},
{
"code": null,
"e": 38391,
"s": 38386,
"text": "HTML"
},
{
"code": "<html> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> How to flatten a given array up to the specified depth in JavaScript? </b> <script> // Define the array let arr = [1, [2, [3, [4, 5], 6], 7, 8], 9, 10]; console.log(\"Original Array:\", arr); let flatArrOne = arr.flat(); console.log( \"Array flattened to depth of 1:\", flatArrOne ); let flatArrTwo = arr.flat(2); console.log( \"Array flattened to depth of 2:\", flatArrTwo ); let flatArrThree = arr.flat(Infinity); console.log( \"Array flattened completely:\", flatArrThree ); </script> </body></html>",
"e": 39105,
"s": 38391,
"text": null
},
{
"code": null,
"e": 39113,
"s": 39105,
"text": "Output:"
},
{
"code": null,
"e": 39365,
"s": 39113,
"text": "Original Array: [1, [2, [3, [4, 5], 6], 7, 8], 9, 10]\nArray flattened to depth of 1: [1, 2, [3, [4, 5], 6], 7, 8, 9, 10]\nArray flattened to depth of 2: [1, 2, 3, [4, 5], 6, 7, 8, 9, 10]\nArray flattened completely: [1, [2, [3, [4, 5], 6], 7, 8], 9, 10]"
},
{
"code": null,
"e": 39382,
"s": 39365,
"text": "javascript-array"
},
{
"code": null,
"e": 39398,
"s": 39382,
"text": "javascript-math"
},
{
"code": null,
"e": 39409,
"s": 39398,
"text": "JavaScript"
},
{
"code": null,
"e": 39426,
"s": 39409,
"text": "Web Technologies"
},
{
"code": null,
"e": 39524,
"s": 39426,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39533,
"s": 39524,
"text": "Comments"
},
{
"code": null,
"e": 39546,
"s": 39533,
"text": "Old Comments"
},
{
"code": null,
"e": 39591,
"s": 39546,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 39660,
"s": 39591,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 39721,
"s": 39660,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 39793,
"s": 39721,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 39820,
"s": 39793,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 39862,
"s": 39820,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 39895,
"s": 39862,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 39957,
"s": 39895,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 40007,
"s": 39957,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
SQL Tryit Editor v1.6 | SELECT * FROM Customers
WHERE City LIKE '%es%';
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 24,
"s": 0,
"text": "SELECT * FROM Customers"
},
{
"code": null,
"e": 48,
"s": 24,
"text": "WHERE City LIKE '%es%';"
},
{
"code": null,
"e": 50,
"s": 48,
"text": ""
},
{
"code": null,
"e": 113,
"s": 50,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 173,
"s": 113,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 241,
"s": 173,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 279,
"s": 241,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 364,
"s": 279,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 538,
"s": 364,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 589,
"s": 538,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 657,
"s": 589,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 828,
"s": 657,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 928,
"s": 828,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 988,
"s": 928,
"text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)."
}
] |
Cordova - Contacts | This plugin is used for accessing the contacts database of the device. In this tutorial we will show you how to create, query and delete contacts.
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugincontacts
The button will be used for calling the createContact function. We will place it in the div class = "app" in index.html file.
<button id = "createContact">ADD CONTACT</button>
<button id = "findContact">FIND CONTACT</button>
<button id = "deleteContact">DELETE CONTACT</button>
Open index.js and copy the following code snippet into the onDeviceReady function.
document.getElementById("createContact").addEventListener("click", createContact);
document.getElementById("findContact").addEventListener("click", findContact);
document.getElementById("deleteContact").addEventListener("click", deleteContact);
Now, we do not have any contacts stored on the device.
Our first callback function will call the navigator.contacts.create method where we can specify the new contact data. This will create a contact and assign it to the myContact variable but it will not be stored on the device. To store it, we need to call the save method and create success and error callback functions.
function createContact() {
var myContact = navigator.contacts.create({"displayName": "Test User"});
myContact.save(contactSuccess, contactError);
function contactSuccess() {
alert("Contact is saved!");
}
function contactError(message) {
alert('Failed because: ' + message);
}
}
When we click the ADD CONTACT button, new contact will be stored to the device contact list.
Our second callback function will query all contacts. We will use the navigator.contacts.find method. The options object has filter parameter which is used to specify the search filter. multiple = true is used since we want to return all contacts from device. The field key to search contacts by displayName since we used it when saving contact.
After the options are set, we are using find method to query contacts. The alert message will be triggered for every contact that is found.
function findContacts() {
var options = new ContactFindOptions();
options.filter = "";
options.multiple = true;
fields = ["displayName"];
navigator.contacts.find(fields, contactfindSuccess, contactfindError, options);
function contactfindSuccess(contacts) {
for (var i = 0; i < contacts.length; i++) {
alert("Display Name = " + contacts[i].displayName);
}
}
function contactfindError(message) {
alert('Failed because: ' + message);
}
}
When we press the FIND CONTACT button, one alert popup will be triggered since we have saved only one contact.
In this step, we will use the find method again but this time we will set different options. The options.filter is set to search that Test User which has to be deleted. After the contactfindSuccess callback function has returned the contact we want, we will delete it by using the remove method that requires its own success and error callbacks.
function deleteContact() {
var options = new ContactFindOptions();
options.filter = "Test User";
options.multiple = false;
fields = ["displayName"];
navigator.contacts.find(fields, contactfindSuccess, contactfindError, options);
function contactfindSuccess(contacts) {
var contact = contacts[0];
contact.remove(contactRemoveSuccess, contactRemoveError);
function contactRemoveSuccess(contact) {
alert("Contact Deleted");
}
function contactRemoveError(message) {
alert('Failed because: ' + message);
}
}
function contactfindError(message) {
alert('Failed because: ' + message);
}
}
Now, we have only one contact stored on the device. We will manually add one more to show you the deleting process.
We will now click the DELETE CONTACT button to delete the Test User. If we check the contact list again, we will see that the Test User does not exist anymore.
45 Lectures
2 hours
Skillbakerystudios
16 Lectures
1 hours
Nilay Mehta
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2327,
"s": 2180,
"text": "This plugin is used for accessing the contacts database of the device. In this tutorial we will show you how to create, query and delete contacts."
},
{
"code": null,
"e": 2411,
"s": 2327,
"text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugincontacts\n"
},
{
"code": null,
"e": 2537,
"s": 2411,
"text": "The button will be used for calling the createContact function. We will place it in the div class = \"app\" in index.html file."
},
{
"code": null,
"e": 2689,
"s": 2537,
"text": "<button id = \"createContact\">ADD CONTACT</button>\n<button id = \"findContact\">FIND CONTACT</button>\n<button id = \"deleteContact\">DELETE CONTACT</button>"
},
{
"code": null,
"e": 2772,
"s": 2689,
"text": "Open index.js and copy the following code snippet into the onDeviceReady function."
},
{
"code": null,
"e": 3017,
"s": 2772,
"text": "document.getElementById(\"createContact\").addEventListener(\"click\", createContact);\ndocument.getElementById(\"findContact\").addEventListener(\"click\", findContact);\ndocument.getElementById(\"deleteContact\").addEventListener(\"click\", deleteContact);"
},
{
"code": null,
"e": 3072,
"s": 3017,
"text": "Now, we do not have any contacts stored on the device."
},
{
"code": null,
"e": 3392,
"s": 3072,
"text": "Our first callback function will call the navigator.contacts.create method where we can specify the new contact data. This will create a contact and assign it to the myContact variable but it will not be stored on the device. To store it, we need to call the save method and create success and error callback functions."
},
{
"code": null,
"e": 3709,
"s": 3392,
"text": "function createContact() {\n var myContact = navigator.contacts.create({\"displayName\": \"Test User\"});\n myContact.save(contactSuccess, contactError);\n \n function contactSuccess() {\n alert(\"Contact is saved!\");\n }\n\t\n function contactError(message) {\n alert('Failed because: ' + message);\n }\n\t\n}"
},
{
"code": null,
"e": 3802,
"s": 3709,
"text": "When we click the ADD CONTACT button, new contact will be stored to the device contact list."
},
{
"code": null,
"e": 4148,
"s": 3802,
"text": "Our second callback function will query all contacts. We will use the navigator.contacts.find method. The options object has filter parameter which is used to specify the search filter. multiple = true is used since we want to return all contacts from device. The field key to search contacts by displayName since we used it when saving contact."
},
{
"code": null,
"e": 4288,
"s": 4148,
"text": "After the options are set, we are using find method to query contacts. The alert message will be triggered for every contact that is found."
},
{
"code": null,
"e": 4787,
"s": 4288,
"text": "function findContacts() {\n var options = new ContactFindOptions();\n options.filter = \"\";\n options.multiple = true;\n fields = [\"displayName\"];\n navigator.contacts.find(fields, contactfindSuccess, contactfindError, options);\n \n function contactfindSuccess(contacts) {\n for (var i = 0; i < contacts.length; i++) {\n alert(\"Display Name = \" + contacts[i].displayName);\n }\n }\n\t\n function contactfindError(message) {\n alert('Failed because: ' + message);\n }\n\t\n}"
},
{
"code": null,
"e": 4898,
"s": 4787,
"text": "When we press the FIND CONTACT button, one alert popup will be triggered since we have saved only one contact."
},
{
"code": null,
"e": 5244,
"s": 4898,
"text": "In this step, we will use the find method again but this time we will set different options. The options.filter is set to search that Test User which has to be deleted. After the contactfindSuccess callback function has returned the contact we want, we will delete it by using the remove method that requires its own success and error callbacks."
},
{
"code": null,
"e": 5918,
"s": 5244,
"text": "function deleteContact() {\n var options = new ContactFindOptions();\n options.filter = \"Test User\";\n options.multiple = false;\n fields = [\"displayName\"];\n navigator.contacts.find(fields, contactfindSuccess, contactfindError, options);\n\n function contactfindSuccess(contacts) {\n var contact = contacts[0];\n contact.remove(contactRemoveSuccess, contactRemoveError);\n\n function contactRemoveSuccess(contact) {\n alert(\"Contact Deleted\");\n }\n\n function contactRemoveError(message) {\n alert('Failed because: ' + message);\n }\n }\n\n function contactfindError(message) {\n alert('Failed because: ' + message);\n }\n\t\n}"
},
{
"code": null,
"e": 6034,
"s": 5918,
"text": "Now, we have only one contact stored on the device. We will manually add one more to show you the deleting process."
},
{
"code": null,
"e": 6194,
"s": 6034,
"text": "We will now click the DELETE CONTACT button to delete the Test User. If we check the contact list again, we will see that the Test User does not exist anymore."
},
{
"code": null,
"e": 6227,
"s": 6194,
"text": "\n 45 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6247,
"s": 6227,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 6280,
"s": 6247,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6293,
"s": 6280,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 6300,
"s": 6293,
"text": " Print"
},
{
"code": null,
"e": 6311,
"s": 6300,
"text": " Add Notes"
}
] |
Foundation - Centered Columns | Including the class small-centered to column, you can make the column at the center. The large-centered class is used to center the column in large devices. To uncenter the columns in large devices or screen then include large-uncenter class.
The following example demonstrates the use of Centered Columns in Foundation −
<!DOCTYPE html>
<html>
<head>
<title>Foundation Template</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css" integrity="sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==" crossorigin="anonymous">
<!-- Compressed JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js" integrity="sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==" crossorigin="anonymous"></script>
</head>
<body>
<h2>Centered Columns</h2>
<div class = "row">
<div class = "small-2 small-centered columns" style = "background-color:#8BD6EE;">
Small centered
</div>
</div>
<div class = "row">
<div class = "small-4 small-centered columns" style = "background-color:#C0B0F0;">
Small centered
</div>
</div>
<div class = "row">
<div class = "small-6 small-centered large-uncentered columns" style = "background-color:#808000;">
Large uncentered
</div>
</div>
<div class = "row">
<div class = "small-8 small-centered columns" style = "background-color:#FF6347;">
Small centered
</div>
</div>
<div class = "row">
<div class = "small-10 large-centered columns" style = "background-color:#7B68EE;">
Large centered
</div>
</div>
</body>
</html>
Let us carry out the following steps to see how the above given code works −
Save the above given html code centered_columns.htm file.
Save the above given html code centered_columns.htm file.
Open this HTML file in a browser, an output is displayed as shown below.
Open this HTML file in a browser, an output is displayed as shown below.
117 Lectures
5.5 hours
Shakthi Swaroop
61 Lectures
1.5 hours
Hans Weemaes
17 Lectures
4 hours
Stephen Kahuria
8 Lectures
50 mins
Zenva
28 Lectures
2 hours
Sandra L
16 Lectures
2.5 hours
GreyCampus Inc.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2481,
"s": 2238,
"text": "Including the class small-centered to column, you can make the column at the center. The large-centered class is used to center the column in large devices. To uncenter the columns in large devices or screen then include large-uncenter class."
},
{
"code": null,
"e": 2560,
"s": 2481,
"text": "The following example demonstrates the use of Centered Columns in Foundation −"
},
{
"code": null,
"e": 4578,
"s": 2560,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Foundation Template</title>\n\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css\" integrity=\"sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==\" crossorigin=\"anonymous\">\n\n <!-- Compressed JavaScript -->\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js\" integrity=\"sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==\" crossorigin=\"anonymous\"></script>\n \n </head>\n\n <body>\n <h2>Centered Columns</h2>\n\n <div class = \"row\">\n <div class = \"small-2 small-centered columns\" style = \"background-color:#8BD6EE;\">\n Small centered\n </div>\n </div>\n\n <div class = \"row\">\n <div class = \"small-4 small-centered columns\" style = \"background-color:#C0B0F0;\">\n Small centered\n </div>\n </div>\n\n <div class = \"row\">\n <div class = \"small-6 small-centered large-uncentered columns\" style = \"background-color:#808000;\">\n Large uncentered\n </div>\n </div>\n\n <div class = \"row\">\n <div class = \"small-8 small-centered columns\" style = \"background-color:#FF6347;\">\n Small centered\n </div>\n </div>\n\n <div class = \"row\">\n <div class = \"small-10 large-centered columns\" style = \"background-color:#7B68EE;\">\n Large centered\n </div>\n </div>\n\n </body>\n</html>"
},
{
"code": null,
"e": 4655,
"s": 4578,
"text": "Let us carry out the following steps to see how the above given code works −"
},
{
"code": null,
"e": 4713,
"s": 4655,
"text": "Save the above given html code centered_columns.htm file."
},
{
"code": null,
"e": 4771,
"s": 4713,
"text": "Save the above given html code centered_columns.htm file."
},
{
"code": null,
"e": 4844,
"s": 4771,
"text": "Open this HTML file in a browser, an output is displayed as shown below."
},
{
"code": null,
"e": 4917,
"s": 4844,
"text": "Open this HTML file in a browser, an output is displayed as shown below."
},
{
"code": null,
"e": 4953,
"s": 4917,
"text": "\n 117 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4970,
"s": 4953,
"text": " Shakthi Swaroop"
},
{
"code": null,
"e": 5005,
"s": 4970,
"text": "\n 61 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5019,
"s": 5005,
"text": " Hans Weemaes"
},
{
"code": null,
"e": 5052,
"s": 5019,
"text": "\n 17 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5069,
"s": 5052,
"text": " Stephen Kahuria"
},
{
"code": null,
"e": 5100,
"s": 5069,
"text": "\n 8 Lectures \n 50 mins\n"
},
{
"code": null,
"e": 5107,
"s": 5100,
"text": " Zenva"
},
{
"code": null,
"e": 5140,
"s": 5107,
"text": "\n 28 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5150,
"s": 5140,
"text": " Sandra L"
},
{
"code": null,
"e": 5185,
"s": 5150,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5202,
"s": 5185,
"text": " GreyCampus Inc."
},
{
"code": null,
"e": 5209,
"s": 5202,
"text": " Print"
},
{
"code": null,
"e": 5220,
"s": 5209,
"text": " Add Notes"
}
] |
Playit | This example demonstrates different vertical-aligns.
span#mySpan { background-color:yellow; vertical-align:baseline;} | [
{
"code": null,
"e": 59,
"s": 0,
"text": "\n This example demonstrates different vertical-aligns.\n "
}
] |
Powershell - Read CSV File | Get-Content cmdlet is used to read content of a csv file.
In this example, we're reading content of test.csv.
Get-Content D:\temp\test\test.csv
You can see following output in PowerShell console.
Mahesh,Suresh,Ramesh
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2092,
"s": 2034,
"text": "Get-Content cmdlet is used to read content of a csv file."
},
{
"code": null,
"e": 2144,
"s": 2092,
"text": "In this example, we're reading content of test.csv."
},
{
"code": null,
"e": 2180,
"s": 2144,
"text": "Get-Content D:\\temp\\test\\test.csv \n"
},
{
"code": null,
"e": 2232,
"s": 2180,
"text": "You can see following output in PowerShell console."
},
{
"code": null,
"e": 2254,
"s": 2232,
"text": "Mahesh,Suresh,Ramesh\n"
},
{
"code": null,
"e": 2289,
"s": 2254,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2310,
"s": 2289,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 2345,
"s": 2310,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2358,
"s": 2345,
"text": " Vijay Saini"
},
{
"code": null,
"e": 2395,
"s": 2358,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 2407,
"s": 2395,
"text": " Fettah Ben"
},
{
"code": null,
"e": 2414,
"s": 2407,
"text": " Print"
},
{
"code": null,
"e": 2425,
"s": 2414,
"text": " Add Notes"
}
] |
FuncTools: An Underrated Python Package | by Emmett Boudreau | Towards Data Science | Last month, I wrote an article about some modules in the Python standard library that I have found to be incredibly useful in my programming and Data Science career. The article had such a great reception with quality feedback that I decided to double down on the idea and write another article discussing the same topic with a lot more standard library tools that everyone should be familiar with. It turns out that the Python programming language’s base is actually quite inclusive, and includes a lot of great tools for various programming challenges. If you would like to read either one of those articles, you can check them out here:
towardsdatascience.com
towardsdatascience.com
When going over a lot of these tools, it seemed like some should have an entire article dedicated to them, rather than just a little overview that is required for most of the other modules that were presented with it. The tool that I think most reciprocated this idea to me is the functools module. This is an incredibly powerful module that can be used to improve nearly any function in Python by utilizing simple and classic methods, such as utilizing stack over processor speed. While in some circumstances I could see that being a big negative, there are certainly exceptions to that case.
notebook
Probably the coolest thing that the functools module provides is the ability to cache certain calculations inside of memory rather than throwing them away just to recalculate them later. This is a great way to save processing times, especially if you find yourself in a Python3 time-out scenario where you are unable to get your code interpreted. While this comes with the trade-off of using a lot more memory, it can certainly make sense to utilize in many different situations. The Python programming language itself is quite declarative, and usually the interpreter handles all of the memory management for us. While this is a less efficient method of programming, it also removes a lot of the hassle of allocating memory and things of that nature. Using functools, we can somewhat change this by determining some things about what lands in the stack and what will be recalculated ourselves.
What is great about the caching that functools provides is that it is both easy to use and allows one to take better control of the interpreter underneath their code. Taking advantage of this awesome feature is as simple as calling it above your function. Here is an example with factorial calculation that I really think takes advantage of what this can accomplish quite well:
def factorial(n): return n * factorial(n-1) if n else 1
In order to use caching with this function, we will import lru_cache from functools and call it before our function:
@lru_cachedef factorial(n): return n * factorial(n-1) if n else 1
Now let us assess the performance benefit that we might have endured just from doing this simple addition. Let us take a look at how fast that factorial function will calculate our factorials without it:
Now I am going to run restart the kernel in order to ensure there are no weird memory things going on and run our new function that uses lru_cache.
Already from this example, we can see a massive benefit from using this caching technique. Factorials are notoriously difficult to calculate by a computer. In most circumstances, this is because factorials are a natural mathematical example for recursion. The Cumulative Distribution Function, or CDF, for binomial distribution gives me nightmares as a result. The calculation is so intensive to make that often programming language’s base factorial function will use a look-up table, rather than calculate the number.
That being said, if you are going to be using recursion like this, it might be a great idea to start getting familiar with functools. This standard library tool can bring a lot of speed to problems that are typically very difficult for Python to solve. In a way, it really brings me back to the Numba Python compiler, where one simple call will instantly make your code faster. If you would like to read an article I wrote all about that a while back, you can check it out here:
towardsdatascience.com
Has there ever been a time where you really wanted to use a function from some really old Python code, but the function was compiled to be a comparison function? These types of functions aren’t as well-supported or even used anymore in modern Python 3, and it can be quite difficult to translate one function type into another. That being said, functools is here to easily fix that with another simple method call:
newfn = cmp_to_key(myfunction)
The partial function will return a new partial object which can then later be called using the same exact arguments and will behave exactly like our previous func. The function inside the code ends up looking a little something like this:
def partial(func, /, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = {**keywords, **fkeywords} return func(*args, *fargs, **newkeywords) newfunc.func = func newfunc.args = args newfunc.keywords = keywords return newfunc
We can create a partial using our factorial function before:
from functools import partialfact = partial(factorial)fact(10)
The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. What this results in is an easy way to save memory and speed by creating a simplistic version of a function that is wrapped in an entirely new object.
The reduce function will apply the function of two arguments with cumulative iteration. That in mind, we will need our arguments to be iterables. For this example, I am going to be using a generator, range. This will make it super easy for us to construct a list datatype of essentially any length we desire.
from functools import reducereduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
What will this do? This will reduce the iterable down into its simplist form. The reduce name comes from its mathematical equivalent. This can be handy for saving runtime performance, and like many others on this list is an easy call that there isn’t a good excuse for not using!
Okay — so this is really, really cool.
Readers of my blog will likely note that I am a huge fan of the Julia programming language. This is not only because Julia is an awesome, high-performance scientific programming language, but also because I have a particular attraction to multiple dispatch. The concept is something that I genuinely miss when it is not around, and it makes programming feel almost more natural. In a way, it is great to have the functions be more type-based, rather than just have different calls in order to handle different situations.
The functools module for Python actually provides a way that Python can effectively be made into a programming language with multiple dispatch. On top of that, it is as easy as adding a decorator as before. In order to do this, we are going to first decorate a function with no specific types required for any arguments with the singledispatch decorator:
@singledispatchdef fun(arg, verbose=False): if verbose: print("Let me just say,", end=" ") print(arg)
Now we will use ourfunction.register in order to register dispatching for new types:
@fun.registerdef _(arg: int, verbose=False): if verbose: print("Strength in numbers, eh?", end=" ") print(arg)@fun.registerdef _(arg: list, verbose=False): if verbose: print("Enumerate this:") for i, elem in enumerate(arg): print(i, elem)
Functools is a really awesome package! Furthermore, I think that the package will most certainly come in handy to just about any Python programmer. The package allows you to simplify your code and math with very minimal effort. Additionally, it is relatively easy to get a bit more in touch with the language and its cache, which can be very convenient to improve certain aspects of performance. Pretty much anything you might want to do that is interesting with functions can be done with this module, which is pretty awesome! | [
{
"code": null,
"e": 811,
"s": 171,
"text": "Last month, I wrote an article about some modules in the Python standard library that I have found to be incredibly useful in my programming and Data Science career. The article had such a great reception with quality feedback that I decided to double down on the idea and write another article discussing the same topic with a lot more standard library tools that everyone should be familiar with. It turns out that the Python programming language’s base is actually quite inclusive, and includes a lot of great tools for various programming challenges. If you would like to read either one of those articles, you can check them out here:"
},
{
"code": null,
"e": 834,
"s": 811,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 857,
"s": 834,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1451,
"s": 857,
"text": "When going over a lot of these tools, it seemed like some should have an entire article dedicated to them, rather than just a little overview that is required for most of the other modules that were presented with it. The tool that I think most reciprocated this idea to me is the functools module. This is an incredibly powerful module that can be used to improve nearly any function in Python by utilizing simple and classic methods, such as utilizing stack over processor speed. While in some circumstances I could see that being a big negative, there are certainly exceptions to that case."
},
{
"code": null,
"e": 1460,
"s": 1451,
"text": "notebook"
},
{
"code": null,
"e": 2355,
"s": 1460,
"text": "Probably the coolest thing that the functools module provides is the ability to cache certain calculations inside of memory rather than throwing them away just to recalculate them later. This is a great way to save processing times, especially if you find yourself in a Python3 time-out scenario where you are unable to get your code interpreted. While this comes with the trade-off of using a lot more memory, it can certainly make sense to utilize in many different situations. The Python programming language itself is quite declarative, and usually the interpreter handles all of the memory management for us. While this is a less efficient method of programming, it also removes a lot of the hassle of allocating memory and things of that nature. Using functools, we can somewhat change this by determining some things about what lands in the stack and what will be recalculated ourselves."
},
{
"code": null,
"e": 2733,
"s": 2355,
"text": "What is great about the caching that functools provides is that it is both easy to use and allows one to take better control of the interpreter underneath their code. Taking advantage of this awesome feature is as simple as calling it above your function. Here is an example with factorial calculation that I really think takes advantage of what this can accomplish quite well:"
},
{
"code": null,
"e": 2792,
"s": 2733,
"text": "def factorial(n): return n * factorial(n-1) if n else 1"
},
{
"code": null,
"e": 2909,
"s": 2792,
"text": "In order to use caching with this function, we will import lru_cache from functools and call it before our function:"
},
{
"code": null,
"e": 2978,
"s": 2909,
"text": "@lru_cachedef factorial(n): return n * factorial(n-1) if n else 1"
},
{
"code": null,
"e": 3182,
"s": 2978,
"text": "Now let us assess the performance benefit that we might have endured just from doing this simple addition. Let us take a look at how fast that factorial function will calculate our factorials without it:"
},
{
"code": null,
"e": 3330,
"s": 3182,
"text": "Now I am going to run restart the kernel in order to ensure there are no weird memory things going on and run our new function that uses lru_cache."
},
{
"code": null,
"e": 3849,
"s": 3330,
"text": "Already from this example, we can see a massive benefit from using this caching technique. Factorials are notoriously difficult to calculate by a computer. In most circumstances, this is because factorials are a natural mathematical example for recursion. The Cumulative Distribution Function, or CDF, for binomial distribution gives me nightmares as a result. The calculation is so intensive to make that often programming language’s base factorial function will use a look-up table, rather than calculate the number."
},
{
"code": null,
"e": 4328,
"s": 3849,
"text": "That being said, if you are going to be using recursion like this, it might be a great idea to start getting familiar with functools. This standard library tool can bring a lot of speed to problems that are typically very difficult for Python to solve. In a way, it really brings me back to the Numba Python compiler, where one simple call will instantly make your code faster. If you would like to read an article I wrote all about that a while back, you can check it out here:"
},
{
"code": null,
"e": 4351,
"s": 4328,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4766,
"s": 4351,
"text": "Has there ever been a time where you really wanted to use a function from some really old Python code, but the function was compiled to be a comparison function? These types of functions aren’t as well-supported or even used anymore in modern Python 3, and it can be quite difficult to translate one function type into another. That being said, functools is here to easily fix that with another simple method call:"
},
{
"code": null,
"e": 4797,
"s": 4766,
"text": "newfn = cmp_to_key(myfunction)"
},
{
"code": null,
"e": 5036,
"s": 4797,
"text": "The partial function will return a new partial object which can then later be called using the same exact arguments and will behave exactly like our previous func. The function inside the code ends up looking a little something like this:"
},
{
"code": null,
"e": 5305,
"s": 5036,
"text": "def partial(func, /, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = {**keywords, **fkeywords} return func(*args, *fargs, **newkeywords) newfunc.func = func newfunc.args = args newfunc.keywords = keywords return newfunc"
},
{
"code": null,
"e": 5366,
"s": 5305,
"text": "We can create a partial using our factorial function before:"
},
{
"code": null,
"e": 5429,
"s": 5366,
"text": "from functools import partialfact = partial(factorial)fact(10)"
},
{
"code": null,
"e": 5761,
"s": 5429,
"text": "The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. What this results in is an easy way to save memory and speed by creating a simplistic version of a function that is wrapped in an entirely new object."
},
{
"code": null,
"e": 6070,
"s": 5761,
"text": "The reduce function will apply the function of two arguments with cumulative iteration. That in mind, we will need our arguments to be iterables. For this example, I am going to be using a generator, range. This will make it super easy for us to construct a list datatype of essentially any length we desire."
},
{
"code": null,
"e": 6140,
"s": 6070,
"text": "from functools import reducereduce(lambda x, y: x+y, [1, 2, 3, 4, 5])"
},
{
"code": null,
"e": 6420,
"s": 6140,
"text": "What will this do? This will reduce the iterable down into its simplist form. The reduce name comes from its mathematical equivalent. This can be handy for saving runtime performance, and like many others on this list is an easy call that there isn’t a good excuse for not using!"
},
{
"code": null,
"e": 6459,
"s": 6420,
"text": "Okay — so this is really, really cool."
},
{
"code": null,
"e": 6981,
"s": 6459,
"text": "Readers of my blog will likely note that I am a huge fan of the Julia programming language. This is not only because Julia is an awesome, high-performance scientific programming language, but also because I have a particular attraction to multiple dispatch. The concept is something that I genuinely miss when it is not around, and it makes programming feel almost more natural. In a way, it is great to have the functions be more type-based, rather than just have different calls in order to handle different situations."
},
{
"code": null,
"e": 7336,
"s": 6981,
"text": "The functools module for Python actually provides a way that Python can effectively be made into a programming language with multiple dispatch. On top of that, it is as easy as adding a decorator as before. In order to do this, we are going to first decorate a function with no specific types required for any arguments with the singledispatch decorator:"
},
{
"code": null,
"e": 7463,
"s": 7336,
"text": "@singledispatchdef fun(arg, verbose=False): if verbose: print(\"Let me just say,\", end=\" \") print(arg)"
},
{
"code": null,
"e": 7548,
"s": 7463,
"text": "Now we will use ourfunction.register in order to register dispatching for new types:"
},
{
"code": null,
"e": 7820,
"s": 7548,
"text": "@fun.registerdef _(arg: int, verbose=False): if verbose: print(\"Strength in numbers, eh?\", end=\" \") print(arg)@fun.registerdef _(arg: list, verbose=False): if verbose: print(\"Enumerate this:\") for i, elem in enumerate(arg): print(i, elem)"
}
] |
Find the Platform at which the given Train arrives - GeeksforGeeks | 29 May, 2021
Given a 2D array arr[][3] consisting of information of N trains where arr[i][0] is the train number, arr[i][1] is the arrival time, and arr[i][2] is the duration of stoppage time. Given another integer F representing the train number, the task is to find the platform number on which the train with train number F arrives according to the following rules:
Platform numbering starts from 1 and there is an infinite number of platforms.
The platform which is freed earlier is allocated to the next train.
If two or more platforms are freed at the same time then the train arrives at the platform with the lowest platform number.
If two or more trains arriving at the same time, then the train with a smaller train number is allocated first.
Examples:
Input: arr[] = {{112567, 1, 2}, {112563, 3, 3}, {112569, 4, 7}, {112560, 9, 3}}, F = 112569Output: 1Explanation:Below is the order of the arrival of trains:Train Platform Leaving Time112567 1 4112563 2 7112569 1 12112560 2 13
Therefore, the train with train number 112569 arrives at platform number 1.
Input: arr[] = {{112567, 2, 1}, {112563, 5, 5}, {112569, 7, 3}, {112560, 3, 7}}, F = 112569Output: 3
Approach: The given problem can be solved by using the priority queue. Follow the steps below to solve this problem:
Sort the given array arr[] of N trains according to the arrival time of the trains.
Initialize a priority queue, say PQ of pairs {PlatformNumber, time} that implements the min-heap according to the least departure time. Insert the {platform number, time} i.e., {1, 0} in the priority queue.
Initialize a HashMap, say M that stores the platform number on which any train arrives.
Traverse the given array arr[] and perform the following steps:Pop the top platform of the PQ and store them in free_platform[].If the arrival time of the current train is at least the departure time of the popped platform, then update the departure time of the popped platform as the (sum of the arrival and the stoppage time + 1) and insert the current status of the platform in PQ and the current platform number of the current train in the HashMap M.Otherwise, add the new platform entry to the PQ and the current platform number of the current train in the HashMap M.
Pop the top platform of the PQ and store them in free_platform[].
If the arrival time of the current train is at least the departure time of the popped platform, then update the departure time of the popped platform as the (sum of the arrival and the stoppage time + 1) and insert the current status of the platform in PQ and the current platform number of the current train in the HashMap M.
Otherwise, add the new platform entry to the PQ and the current platform number of the current train in the HashMap M.
After completing the above steps, print the platform number associated with the train number F in the HashMap M.
Below is the implementation of the above approach:
Java
// Java program for the above approach import java.util.*; // Stores the information for each// train as Objectsclass Train { // Stores the train number String train_num; // Stores the arrival time int arrival_time; // Stores the stoppage time int stoppage_time; // Constructor Train(String train_num, int arrival_time, int stoppage_time) { this.train_num = train_num; this.arrival_time = arrival_time; this.stoppage_time = stoppage_time; }} public class GFG { // Function to find the platform // on which train F arrives static int findPlatformOf( ArrayList<Train> trains, int n, String F) { // Sort the array arr[] according // to the arrival time Collections.sort( trains, (a, b) -> a.arrival_time==b.arrival_time ? Integer.parseInt(a.train_num)-Integer.parseInt(b.train_num) : a.arrival_time - b.arrival_time); // Stores the platforms that // is in currently in use PriorityQueue<int[]> pq = new PriorityQueue<>( (a, b) -> a[1] == b[1] ? a[0] - b[0] : a[1] - b[1]); // Insert the platform number 1 // with departure time as 0 pq.add(new int[] { 1, 0 }); // Store the platform number // on which train arrived HashMap<String, Integer> schedule = new HashMap<>(); // Traverse the given array for (Train t : trains) { // Pop the top platform of // the priority queue int[] free_platform = pq.poll(); // If arrival time of the train // >= freeing time of the platform if (t.arrival_time >= free_platform[1]) { // Update the train status free_platform[1] = t.arrival_time + t.stoppage_time + 1; // Add the current platform // to the pq pq.add(free_platform); // Add the platform // number to the HashMap schedule.put(t.train_num, free_platform[0]); } // Otherwise, add a new platform // for the current train else { // Update the priority queue pq.add(free_platform); // Get the platform number int platform_num = pq.size() + 1; // Add the platform to // the priority queue pq.add(new int[] { platform_num, t.arrival_time + t.stoppage_time + 1 }); // Add the platform // number to the HashMap schedule.put(t.train_num, platform_num); } } // Return the platform on // which F train arrived return schedule.get(F); } // Driver Code public static void main(String[] args) { ArrayList<Train> trains = new ArrayList<>(); trains.add(new Train( "112567", 2, 1)); trains.add(new Train( "112569", 5, 5)); trains.add(new Train( "112563", 5, 3)); trains.add(new Train( "112560", 3, 7)); String F = "112563"; System.out.println( findPlatformOf( trains, trains.size(), F)); }}
3
Time Complexity: O(N * log N) Auxiliary Space: O(N)
muvvalaaravind
min-heap
priority-queue
Arrays
Greedy
Heap
Searching
Sorting
Arrays
Searching
Greedy
Sorting
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string | [
{
"code": null,
"e": 25687,
"s": 25659,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 26043,
"s": 25687,
"text": "Given a 2D array arr[][3] consisting of information of N trains where arr[i][0] is the train number, arr[i][1] is the arrival time, and arr[i][2] is the duration of stoppage time. Given another integer F representing the train number, the task is to find the platform number on which the train with train number F arrives according to the following rules:"
},
{
"code": null,
"e": 26122,
"s": 26043,
"text": "Platform numbering starts from 1 and there is an infinite number of platforms."
},
{
"code": null,
"e": 26190,
"s": 26122,
"text": "The platform which is freed earlier is allocated to the next train."
},
{
"code": null,
"e": 26314,
"s": 26190,
"text": "If two or more platforms are freed at the same time then the train arrives at the platform with the lowest platform number."
},
{
"code": null,
"e": 26426,
"s": 26314,
"text": "If two or more trains arriving at the same time, then the train with a smaller train number is allocated first."
},
{
"code": null,
"e": 26436,
"s": 26426,
"text": "Examples:"
},
{
"code": null,
"e": 26753,
"s": 26436,
"text": "Input: arr[] = {{112567, 1, 2}, {112563, 3, 3}, {112569, 4, 7}, {112560, 9, 3}}, F = 112569Output: 1Explanation:Below is the order of the arrival of trains:Train Platform Leaving Time112567 1 4112563 2 7112569 1 12112560 2 13"
},
{
"code": null,
"e": 26829,
"s": 26753,
"text": "Therefore, the train with train number 112569 arrives at platform number 1."
},
{
"code": null,
"e": 26930,
"s": 26829,
"text": "Input: arr[] = {{112567, 2, 1}, {112563, 5, 5}, {112569, 7, 3}, {112560, 3, 7}}, F = 112569Output: 3"
},
{
"code": null,
"e": 27047,
"s": 26930,
"text": "Approach: The given problem can be solved by using the priority queue. Follow the steps below to solve this problem:"
},
{
"code": null,
"e": 27131,
"s": 27047,
"text": "Sort the given array arr[] of N trains according to the arrival time of the trains."
},
{
"code": null,
"e": 27338,
"s": 27131,
"text": "Initialize a priority queue, say PQ of pairs {PlatformNumber, time} that implements the min-heap according to the least departure time. Insert the {platform number, time} i.e., {1, 0} in the priority queue."
},
{
"code": null,
"e": 27426,
"s": 27338,
"text": "Initialize a HashMap, say M that stores the platform number on which any train arrives."
},
{
"code": null,
"e": 27999,
"s": 27426,
"text": "Traverse the given array arr[] and perform the following steps:Pop the top platform of the PQ and store them in free_platform[].If the arrival time of the current train is at least the departure time of the popped platform, then update the departure time of the popped platform as the (sum of the arrival and the stoppage time + 1) and insert the current status of the platform in PQ and the current platform number of the current train in the HashMap M.Otherwise, add the new platform entry to the PQ and the current platform number of the current train in the HashMap M."
},
{
"code": null,
"e": 28065,
"s": 27999,
"text": "Pop the top platform of the PQ and store them in free_platform[]."
},
{
"code": null,
"e": 28392,
"s": 28065,
"text": "If the arrival time of the current train is at least the departure time of the popped platform, then update the departure time of the popped platform as the (sum of the arrival and the stoppage time + 1) and insert the current status of the platform in PQ and the current platform number of the current train in the HashMap M."
},
{
"code": null,
"e": 28511,
"s": 28392,
"text": "Otherwise, add the new platform entry to the PQ and the current platform number of the current train in the HashMap M."
},
{
"code": null,
"e": 28624,
"s": 28511,
"text": "After completing the above steps, print the platform number associated with the train number F in the HashMap M."
},
{
"code": null,
"e": 28676,
"s": 28624,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28681,
"s": 28676,
"text": "Java"
},
{
"code": "// Java program for the above approach import java.util.*; // Stores the information for each// train as Objectsclass Train { // Stores the train number String train_num; // Stores the arrival time int arrival_time; // Stores the stoppage time int stoppage_time; // Constructor Train(String train_num, int arrival_time, int stoppage_time) { this.train_num = train_num; this.arrival_time = arrival_time; this.stoppage_time = stoppage_time; }} public class GFG { // Function to find the platform // on which train F arrives static int findPlatformOf( ArrayList<Train> trains, int n, String F) { // Sort the array arr[] according // to the arrival time Collections.sort( trains, (a, b) -> a.arrival_time==b.arrival_time ? Integer.parseInt(a.train_num)-Integer.parseInt(b.train_num) : a.arrival_time - b.arrival_time); // Stores the platforms that // is in currently in use PriorityQueue<int[]> pq = new PriorityQueue<>( (a, b) -> a[1] == b[1] ? a[0] - b[0] : a[1] - b[1]); // Insert the platform number 1 // with departure time as 0 pq.add(new int[] { 1, 0 }); // Store the platform number // on which train arrived HashMap<String, Integer> schedule = new HashMap<>(); // Traverse the given array for (Train t : trains) { // Pop the top platform of // the priority queue int[] free_platform = pq.poll(); // If arrival time of the train // >= freeing time of the platform if (t.arrival_time >= free_platform[1]) { // Update the train status free_platform[1] = t.arrival_time + t.stoppage_time + 1; // Add the current platform // to the pq pq.add(free_platform); // Add the platform // number to the HashMap schedule.put(t.train_num, free_platform[0]); } // Otherwise, add a new platform // for the current train else { // Update the priority queue pq.add(free_platform); // Get the platform number int platform_num = pq.size() + 1; // Add the platform to // the priority queue pq.add(new int[] { platform_num, t.arrival_time + t.stoppage_time + 1 }); // Add the platform // number to the HashMap schedule.put(t.train_num, platform_num); } } // Return the platform on // which F train arrived return schedule.get(F); } // Driver Code public static void main(String[] args) { ArrayList<Train> trains = new ArrayList<>(); trains.add(new Train( \"112567\", 2, 1)); trains.add(new Train( \"112569\", 5, 5)); trains.add(new Train( \"112563\", 5, 3)); trains.add(new Train( \"112560\", 3, 7)); String F = \"112563\"; System.out.println( findPlatformOf( trains, trains.size(), F)); }}",
"e": 32165,
"s": 28681,
"text": null
},
{
"code": null,
"e": 32167,
"s": 32165,
"text": "3"
},
{
"code": null,
"e": 32221,
"s": 32169,
"text": "Time Complexity: O(N * log N) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 32236,
"s": 32221,
"text": "muvvalaaravind"
},
{
"code": null,
"e": 32245,
"s": 32236,
"text": "min-heap"
},
{
"code": null,
"e": 32260,
"s": 32245,
"text": "priority-queue"
},
{
"code": null,
"e": 32267,
"s": 32260,
"text": "Arrays"
},
{
"code": null,
"e": 32274,
"s": 32267,
"text": "Greedy"
},
{
"code": null,
"e": 32279,
"s": 32274,
"text": "Heap"
},
{
"code": null,
"e": 32289,
"s": 32279,
"text": "Searching"
},
{
"code": null,
"e": 32297,
"s": 32289,
"text": "Sorting"
},
{
"code": null,
"e": 32304,
"s": 32297,
"text": "Arrays"
},
{
"code": null,
"e": 32314,
"s": 32304,
"text": "Searching"
},
{
"code": null,
"e": 32321,
"s": 32314,
"text": "Greedy"
},
{
"code": null,
"e": 32329,
"s": 32321,
"text": "Sorting"
},
{
"code": null,
"e": 32334,
"s": 32329,
"text": "Heap"
},
{
"code": null,
"e": 32349,
"s": 32334,
"text": "priority-queue"
},
{
"code": null,
"e": 32447,
"s": 32349,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32456,
"s": 32447,
"text": "Comments"
},
{
"code": null,
"e": 32469,
"s": 32456,
"text": "Old Comments"
},
{
"code": null,
"e": 32517,
"s": 32469,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 32561,
"s": 32517,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32584,
"s": 32561,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32616,
"s": 32584,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32630,
"s": 32616,
"text": "Linear Search"
},
{
"code": null,
"e": 32681,
"s": 32630,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 32732,
"s": 32681,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 32790,
"s": 32732,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 32821,
"s": 32790,
"text": "Huffman Coding | Greedy Algo-3"
}
] |
Find all distinct palindromic sub-strings of a given String in Python | Suppose we have a string with lowercase ASCII characters, we have to find all distinct continuous palindromic substrings of it.
So, if the input is like "bddaaa", then the output will be [a, aa, aaa, b, d, dd]
To solve this, we will follow these steps −
m := a new map
n := size of s
matrix := make two rows of n number of 0s
s := "@" concatenate s concatenate "#"
for j in range 0 to 1, dotemp := 0matrix[j, 0] := 0i := 1while i <= n, dowhile s[i - temp - 1] is same as s[i + j + temp], dotemp := temp + 1matrix[j, i] := tempk := 1while (matrix[j, i - k] is not same as temp - k) and k < temp, domatrix[j,i+k] := minimum of matrix[j, i-k]k := k + 1temp := maximum of temp - k, 0i := i + k
temp := 0
matrix[j, 0] := 0
i := 1
while i <= n, dowhile s[i - temp - 1] is same as s[i + j + temp], dotemp := temp + 1matrix[j, i] := tempk := 1while (matrix[j, i - k] is not same as temp - k) and k < temp, domatrix[j,i+k] := minimum of matrix[j, i-k]k := k + 1temp := maximum of temp - k, 0i := i + k
while s[i - temp - 1] is same as s[i + j + temp], dotemp := temp + 1
temp := temp + 1
matrix[j, i] := temp
k := 1
while (matrix[j, i - k] is not same as temp - k) and k < temp, domatrix[j,i+k] := minimum of matrix[j, i-k]k := k + 1
matrix[j,i+k] := minimum of matrix[j, i-k]
k := k + 1
temp := maximum of temp - k, 0
i := i + k
s := s from index 1 to end
m[s[0]] := 1
for i in range 1 to n, dofor j in range 0 to 1, dofor temp in range, dom[substring of s from (i - temp - 1) to (i - temp - 1 + 2 * temp + j)] = 1m[s[i]] := 1
for j in range 0 to 1, dofor temp in range, dom[substring of s from (i - temp - 1) to (i - temp - 1 + 2 * temp + j)] = 1
for temp in range, dom[substring of s from (i - temp - 1) to (i - temp - 1 + 2 * temp + j)] = 1
m[substring of s from (i - temp - 1) to (i - temp - 1 + 2 * temp + j)] = 1
m[s[i]] := 1
for each i in m, dodisplay i
display i
Let us see the following implementation to get better understanding −
Live Demo
def find_substr(s):
m = dict()
n = len(s)
matrix = [[0 for x in range(n+1)] for x in range(2)]
s = "@" + s + "#"
for j in range(2):
temp = 0
matrix[j][0] = 0
i = 1
while i <= n:
while s[i - temp - 1] == s[i + j + temp]:
temp += 1
matrix[j][i] = temp
k = 1
while (matrix[j][i - k] != temp - k) and (k < temp):
matrix[j][i+k] = min(matrix[j][i-k], temp - k)
k += 1
temp = max(temp - k, 0)
i += k
s = s[1:len(s)-1]
m[s[0]] = 1
for i in range(1,n):
for j in range(2):
for temp in range(matrix[j][i],0,-1):
m[s[i - temp - 1 : i - temp - 1 + 2 * temp + j]] = 1
m[s[i]] = 1
for i in m:
print (i)
find_substr("bddaaa")
bddaaa
a
aa
b
aaa
d
dd | [
{
"code": null,
"e": 1190,
"s": 1062,
"text": "Suppose we have a string with lowercase ASCII characters, we have to find all distinct continuous palindromic substrings of it."
},
{
"code": null,
"e": 1272,
"s": 1190,
"text": "So, if the input is like \"bddaaa\", then the output will be [a, aa, aaa, b, d, dd]"
},
{
"code": null,
"e": 1316,
"s": 1272,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1331,
"s": 1316,
"text": "m := a new map"
},
{
"code": null,
"e": 1346,
"s": 1331,
"text": "n := size of s"
},
{
"code": null,
"e": 1388,
"s": 1346,
"text": "matrix := make two rows of n number of 0s"
},
{
"code": null,
"e": 1427,
"s": 1388,
"text": "s := \"@\" concatenate s concatenate \"#\""
},
{
"code": null,
"e": 1752,
"s": 1427,
"text": "for j in range 0 to 1, dotemp := 0matrix[j, 0] := 0i := 1while i <= n, dowhile s[i - temp - 1] is same as s[i + j + temp], dotemp := temp + 1matrix[j, i] := tempk := 1while (matrix[j, i - k] is not same as temp - k) and k < temp, domatrix[j,i+k] := minimum of matrix[j, i-k]k := k + 1temp := maximum of temp - k, 0i := i + k"
},
{
"code": null,
"e": 1762,
"s": 1752,
"text": "temp := 0"
},
{
"code": null,
"e": 1780,
"s": 1762,
"text": "matrix[j, 0] := 0"
},
{
"code": null,
"e": 1787,
"s": 1780,
"text": "i := 1"
},
{
"code": null,
"e": 2055,
"s": 1787,
"text": "while i <= n, dowhile s[i - temp - 1] is same as s[i + j + temp], dotemp := temp + 1matrix[j, i] := tempk := 1while (matrix[j, i - k] is not same as temp - k) and k < temp, domatrix[j,i+k] := minimum of matrix[j, i-k]k := k + 1temp := maximum of temp - k, 0i := i + k"
},
{
"code": null,
"e": 2124,
"s": 2055,
"text": "while s[i - temp - 1] is same as s[i + j + temp], dotemp := temp + 1"
},
{
"code": null,
"e": 2141,
"s": 2124,
"text": "temp := temp + 1"
},
{
"code": null,
"e": 2162,
"s": 2141,
"text": "matrix[j, i] := temp"
},
{
"code": null,
"e": 2169,
"s": 2162,
"text": "k := 1"
},
{
"code": null,
"e": 2287,
"s": 2169,
"text": "while (matrix[j, i - k] is not same as temp - k) and k < temp, domatrix[j,i+k] := minimum of matrix[j, i-k]k := k + 1"
},
{
"code": null,
"e": 2330,
"s": 2287,
"text": "matrix[j,i+k] := minimum of matrix[j, i-k]"
},
{
"code": null,
"e": 2341,
"s": 2330,
"text": "k := k + 1"
},
{
"code": null,
"e": 2372,
"s": 2341,
"text": "temp := maximum of temp - k, 0"
},
{
"code": null,
"e": 2383,
"s": 2372,
"text": "i := i + k"
},
{
"code": null,
"e": 2410,
"s": 2383,
"text": "s := s from index 1 to end"
},
{
"code": null,
"e": 2423,
"s": 2410,
"text": "m[s[0]] := 1"
},
{
"code": null,
"e": 2581,
"s": 2423,
"text": "for i in range 1 to n, dofor j in range 0 to 1, dofor temp in range, dom[substring of s from (i - temp - 1) to (i - temp - 1 + 2 * temp + j)] = 1m[s[i]] := 1"
},
{
"code": null,
"e": 2702,
"s": 2581,
"text": "for j in range 0 to 1, dofor temp in range, dom[substring of s from (i - temp - 1) to (i - temp - 1 + 2 * temp + j)] = 1"
},
{
"code": null,
"e": 2798,
"s": 2702,
"text": "for temp in range, dom[substring of s from (i - temp - 1) to (i - temp - 1 + 2 * temp + j)] = 1"
},
{
"code": null,
"e": 2873,
"s": 2798,
"text": "m[substring of s from (i - temp - 1) to (i - temp - 1 + 2 * temp + j)] = 1"
},
{
"code": null,
"e": 2886,
"s": 2873,
"text": "m[s[i]] := 1"
},
{
"code": null,
"e": 2915,
"s": 2886,
"text": "for each i in m, dodisplay i"
},
{
"code": null,
"e": 2925,
"s": 2915,
"text": "display i"
},
{
"code": null,
"e": 2995,
"s": 2925,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3006,
"s": 2995,
"text": " Live Demo"
},
{
"code": null,
"e": 3797,
"s": 3006,
"text": "def find_substr(s):\n m = dict()\n n = len(s)\n matrix = [[0 for x in range(n+1)] for x in range(2)]\n s = \"@\" + s + \"#\"\n for j in range(2):\n temp = 0\n matrix[j][0] = 0\n i = 1\n while i <= n:\n while s[i - temp - 1] == s[i + j + temp]:\n temp += 1\n matrix[j][i] = temp\n k = 1\n while (matrix[j][i - k] != temp - k) and (k < temp):\n matrix[j][i+k] = min(matrix[j][i-k], temp - k)\n k += 1\n temp = max(temp - k, 0)\n i += k\n s = s[1:len(s)-1]\n m[s[0]] = 1\n for i in range(1,n):\n for j in range(2):\n for temp in range(matrix[j][i],0,-1):\n m[s[i - temp - 1 : i - temp - 1 + 2 * temp + j]] = 1\n m[s[i]] = 1\n for i in m:\n print (i)\nfind_substr(\"bddaaa\")"
},
{
"code": null,
"e": 3804,
"s": 3797,
"text": "bddaaa"
},
{
"code": null,
"e": 3820,
"s": 3804,
"text": "a\naa\nb\naaa\nd\ndd"
}
] |