title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
SQL Tryit Editor v1.6
|
SELECT * FROM Customers
WHERE NOT Country='Germany';
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": 53,
"s": 24,
"text": "WHERE NOT Country='Germany';"
},
{
"code": null,
"e": 55,
"s": 53,
"text": ""
},
{
"code": null,
"e": 118,
"s": 55,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 178,
"s": 118,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 246,
"s": 178,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 284,
"s": 246,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 369,
"s": 284,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 543,
"s": 369,
"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": 594,
"s": 543,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 662,
"s": 594,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 833,
"s": 662,
"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": 933,
"s": 833,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 993,
"s": 933,
"text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)."
}
] |
Difference between Perl and Ruby - GeeksforGeeks
|
02 Nov, 2020
Perl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. Perl was originally developed for text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++.
Perl
# Simple Perl program#!/usr/bin/perl # Below line will print# "Welcome to GeeksforGeeks!"print "Welcome to GeeksforGeeks!\n";
Output:
Welcome to GeeksforGeeks!
Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid 1990’s in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s development was to make it act as a sensible buffer between human programmers and the underlying computing machinery. Ruby has a similar syntax to that of many programming languages like C and Java, so it is easy for Java and C programmers to learn. It supports mostly all platforms like Windows, Mac, Linux.
Ruby
# Simple Ruby programputs "Welcome to GeeksforGeeks!"
Output:
Welcome to GeeksforGeeks!
Difference between Perl and Ruby :
Perl
Ruby
Perl is a high level, general-purpose, interpreted, dynamic
programming language.
It has a very good number of libraries when it comes to
supporting regular expression.
Perl is most often used in CGI (Common Gateway Interface)
scripting along with C for web servers and hence used widely in the world of server technology.
balharatanvee
Difference Between
Perl
Ruby
Perl
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
Differences and Applications of List, Tuple, Set and Dictionary in Python
Perl | split() Function
Perl | push() Function
Perl | chomp() Function
Perl | Regular Expressions
Perl | String Operators
|
[
{
"code": null,
"e": 24858,
"s": 24830,
"text": "\n02 Nov, 2020"
},
{
"code": null,
"e": 25317,
"s": 24858,
"text": "Perl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. Perl was originally developed for text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++."
},
{
"code": null,
"e": 25322,
"s": 25317,
"text": "Perl"
},
{
"code": "# Simple Perl program#!/usr/bin/perl # Below line will print# \"Welcome to GeeksforGeeks!\"print \"Welcome to GeeksforGeeks!\\n\";",
"e": 25450,
"s": 25322,
"text": null
},
{
"code": null,
"e": 25459,
"s": 25450,
"text": "Output: "
},
{
"code": null,
"e": 25487,
"s": 25459,
"text": "Welcome to GeeksforGeeks!\n\n"
},
{
"code": null,
"e": 26073,
"s": 25487,
"text": "Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid 1990’s in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s development was to make it act as a sensible buffer between human programmers and the underlying computing machinery. Ruby has a similar syntax to that of many programming languages like C and Java, so it is easy for Java and C programmers to learn. It supports mostly all platforms like Windows, Mac, Linux."
},
{
"code": null,
"e": 26078,
"s": 26073,
"text": "Ruby"
},
{
"code": "# Simple Ruby programputs \"Welcome to GeeksforGeeks!\"",
"e": 26132,
"s": 26078,
"text": null
},
{
"code": null,
"e": 26140,
"s": 26132,
"text": "Output:"
},
{
"code": null,
"e": 26168,
"s": 26140,
"text": "Welcome to GeeksforGeeks!\n\n"
},
{
"code": null,
"e": 26203,
"s": 26168,
"text": "Difference between Perl and Ruby :"
},
{
"code": null,
"e": 26208,
"s": 26203,
"text": "Perl"
},
{
"code": null,
"e": 26213,
"s": 26208,
"text": "Ruby"
},
{
"code": null,
"e": 26274,
"s": 26213,
"text": "Perl is a high level, general-purpose, interpreted, dynamic "
},
{
"code": null,
"e": 26296,
"s": 26274,
"text": "programming language."
},
{
"code": null,
"e": 26353,
"s": 26296,
"text": "It has a very good number of libraries when it comes to "
},
{
"code": null,
"e": 26384,
"s": 26353,
"text": "supporting regular expression."
},
{
"code": null,
"e": 26443,
"s": 26384,
"text": "Perl is most often used in CGI (Common Gateway Interface) "
},
{
"code": null,
"e": 26539,
"s": 26443,
"text": "scripting along with C for web servers and hence used widely in the world of server technology."
},
{
"code": null,
"e": 26553,
"s": 26539,
"text": "balharatanvee"
},
{
"code": null,
"e": 26572,
"s": 26553,
"text": "Difference Between"
},
{
"code": null,
"e": 26577,
"s": 26572,
"text": "Perl"
},
{
"code": null,
"e": 26582,
"s": 26577,
"text": "Ruby"
},
{
"code": null,
"e": 26587,
"s": 26582,
"text": "Perl"
},
{
"code": null,
"e": 26685,
"s": 26587,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26746,
"s": 26685,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26814,
"s": 26746,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 26872,
"s": 26814,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 26927,
"s": 26872,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 27001,
"s": 26927,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 27025,
"s": 27001,
"text": "Perl | split() Function"
},
{
"code": null,
"e": 27048,
"s": 27025,
"text": "Perl | push() Function"
},
{
"code": null,
"e": 27072,
"s": 27048,
"text": "Perl | chomp() Function"
},
{
"code": null,
"e": 27099,
"s": 27072,
"text": "Perl | Regular Expressions"
}
] |
Nearest Neighbour Analysis with Geospatial data | by Abdishakur | Towards Data Science
|
Finding the nearest neighbour of an object to another is a common spatial data analysis task. For example, determining the closest service point to your home is an optimisation problem that requires performing Nearest Neighbour Analysis with spatial data.
In this tutorial, we perform Nearest Neighbourhood Analysis with Bike Sharing dataset from Chicago City. The dataset consists of two separate files. The first one is bike stations and the second is randomly generated points. We want to determine which station is near to any given point in the second dataset — the randomly generated points. The randomly generated dataset can represent a real case where the rider wants to determine which Bike station is nearest to park the bicycle.
We read the data with pandas and call the first data frame stations where we have attributes like station name, capacity and coordinates.
stations = pd.read_csv(“data/stations.csv”)stations.head()
The second table holds the randomly generated points. We call this Dataframe points. We have only three columns in this table, the id and coordinates of X and Y.
points = pd.read_csv(“data/points.csv”)points.head()
To perform any Geographic processing task, including the Nearest Neighbour Analysis for this tutorial, we need to convert the data into a Geodataframe using Geopandas. This will allow us to calculate any Geoprocessing task available in Geopandas as well as any Pandas methods we want to use.
The following function converts both datasets into a Geopandas Geodataframe. This creates an additional column where the Geometry is stored. We also construct a Coordinate reference system for the dataset, in this case, EPSG:4326.
def create_gdf(df, x=”xcoord”, y=”ycoord”): return gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df[y], df[x]), crs={“init”:”EPSG:4326"})stations_gdf = create_gdf(stations)points_gdf = create_gdf(points)
Now, let us visualise the data in a map using Folium Python Library.
m = folium.Map([41.805379, -87.601501], tiles=”CartoDb dark_matter”)locs_stations = zip(stations_gdf.ycoord, stations_gdf.xcoord)locs_points = zip(points_gdf.ycoord, points_gdf.xcoord)for location in locs_stations: folium.CircleMarker(location=location, color=”red”, radius=4).add_to(m)for location in locs_points: folium.CircleMarker(location=location, color=”white”, radius=2).add_to(m)m
The map shown below visualises station_gdf with red colour and points_gdf in white colour. The goal is to find out the closest station for the randomly generated points.
In the next section, we perform the nearest neighbour analysis using Geopandas and Shapely functionality.
We want to find the nearest Bike station to the other random points. We can use Shapely function nearest_points functionality to find out which geometry is closest to each location and in the process also save other attributes, for example, the name of the station. Here, we use caclulate_nearest function that takes the destination (station_gdf ) and the value we want to store from this dataset(station name).
def calculate_nearest(row, destination, val, col=”geometry”): # 1 - create unary union dest_unary = destination[“geometry”].unary_union # 2 - find closest point nearest_geom = nearest_points(row[col], dest_unary) # 3 - Find the corresponding geom match_geom = destination.loc[destination.geometry == nearest_geom[1]] # 4 - get the corresponding value match_value = match_geom[val].to_numpy()[0] return match_value
We apply this function to the second dataset points_gdf to derive each random point’s nearest geometry (from station_gdf) and also the station name of the closest geometry.
# Get the nearest geometrypoints_gdf[“nearest_geom”] = points_gdf.apply(calculate_nearest, destination=stations_gdf, val=”geometry”, axis=1)# Get the nearest Bike station namepoints_gdf[“nearest_station”] = points_gdf.apply(calculate_nearest, destination=stations_gdf, val=”name”, axis=1)points_gdf.head()
The output is the following table where we have the two additional columns we created above.
Now, we have both nearest_station and nearest_geom in the points_gdf . for instance, in id 2, we can see that the nearest station is Lincoln Ave & Belle Plane Ave station. We need to verify our results, let create a line Geodataframe from geometry and nearest_geom which helps us explore the data visually.
# Create LineString Geometrypoints_gdf[‘line’] = points_gdf.apply(lambda row: LineString([row[‘geometry’], row[‘nearest_geom’]]), axis=1)# Create Line Geodataframeline_gdf = points_gdf[["id", "nearest_station", "line"]].set_geometry('line')# Set the Coordinate referenceline_gdf.crs = crs={"init":"epsg:4326"}
We have destination points station_gdf, nearest points inpoints_gdf and now theline_gdf that connects both datasets. Let us visualise all of them in one plot.
m = folium.Map([41.805379, -87.601501],zoom_start = 12, tiles=”CartoDb dark_matter”)locs_stations = zip(stations_gdf.ycoord, stations_gdf.xcoord)locs_points = zip(points_gdf.ycoord, points_gdf.xcoord)for location in locs_stations: folium.CircleMarker(location=location, color=”red”, radius=8).add_to(m)for location in locs_points: folium.CircleMarker(location=location, color=”white”, radius=4).add_to(m)folium.GeoJson(line_gdf).add_to(m)m.save(“map2.html”)m
You can easily explore the dataset and see the connection between the nearest station of each point with the help of the map shown below.
The map shows Bike stations in Red circle, the random points in White and the connection line in Blue. You can explore further the interactive map in the accompanying notebook. The final result is accurate and also can be replicated in any other dataset of your choice.
In this tutorial, we covered how to perform Nearest Neighbourhood Analysis using Geopandas and Shapely using Chicago Bike stations. We also explored how we can easily construct and visualise the result of the analysis with Folium.
The code for this tutorial is available in this Github repository:
github.com
Google Colab Notebook can be accessed directly from here:
|
[
{
"code": null,
"e": 428,
"s": 172,
"text": "Finding the nearest neighbour of an object to another is a common spatial data analysis task. For example, determining the closest service point to your home is an optimisation problem that requires performing Nearest Neighbour Analysis with spatial data."
},
{
"code": null,
"e": 913,
"s": 428,
"text": "In this tutorial, we perform Nearest Neighbourhood Analysis with Bike Sharing dataset from Chicago City. The dataset consists of two separate files. The first one is bike stations and the second is randomly generated points. We want to determine which station is near to any given point in the second dataset — the randomly generated points. The randomly generated dataset can represent a real case where the rider wants to determine which Bike station is nearest to park the bicycle."
},
{
"code": null,
"e": 1051,
"s": 913,
"text": "We read the data with pandas and call the first data frame stations where we have attributes like station name, capacity and coordinates."
},
{
"code": null,
"e": 1110,
"s": 1051,
"text": "stations = pd.read_csv(“data/stations.csv”)stations.head()"
},
{
"code": null,
"e": 1272,
"s": 1110,
"text": "The second table holds the randomly generated points. We call this Dataframe points. We have only three columns in this table, the id and coordinates of X and Y."
},
{
"code": null,
"e": 1325,
"s": 1272,
"text": "points = pd.read_csv(“data/points.csv”)points.head()"
},
{
"code": null,
"e": 1617,
"s": 1325,
"text": "To perform any Geographic processing task, including the Nearest Neighbour Analysis for this tutorial, we need to convert the data into a Geodataframe using Geopandas. This will allow us to calculate any Geoprocessing task available in Geopandas as well as any Pandas methods we want to use."
},
{
"code": null,
"e": 1848,
"s": 1617,
"text": "The following function converts both datasets into a Geopandas Geodataframe. This creates an additional column where the Geometry is stored. We also construct a Coordinate reference system for the dataset, in this case, EPSG:4326."
},
{
"code": null,
"e": 2075,
"s": 1848,
"text": "def create_gdf(df, x=”xcoord”, y=”ycoord”): return gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df[y], df[x]), crs={“init”:”EPSG:4326\"})stations_gdf = create_gdf(stations)points_gdf = create_gdf(points)"
},
{
"code": null,
"e": 2144,
"s": 2075,
"text": "Now, let us visualise the data in a map using Folium Python Library."
},
{
"code": null,
"e": 2558,
"s": 2144,
"text": "m = folium.Map([41.805379, -87.601501], tiles=”CartoDb dark_matter”)locs_stations = zip(stations_gdf.ycoord, stations_gdf.xcoord)locs_points = zip(points_gdf.ycoord, points_gdf.xcoord)for location in locs_stations: folium.CircleMarker(location=location, color=”red”, radius=4).add_to(m)for location in locs_points: folium.CircleMarker(location=location, color=”white”, radius=2).add_to(m)m"
},
{
"code": null,
"e": 2728,
"s": 2558,
"text": "The map shown below visualises station_gdf with red colour and points_gdf in white colour. The goal is to find out the closest station for the randomly generated points."
},
{
"code": null,
"e": 2834,
"s": 2728,
"text": "In the next section, we perform the nearest neighbour analysis using Geopandas and Shapely functionality."
},
{
"code": null,
"e": 3246,
"s": 2834,
"text": "We want to find the nearest Bike station to the other random points. We can use Shapely function nearest_points functionality to find out which geometry is closest to each location and in the process also save other attributes, for example, the name of the station. Here, we use caclulate_nearest function that takes the destination (station_gdf ) and the value we want to store from this dataset(station name)."
},
{
"code": null,
"e": 3707,
"s": 3246,
"text": "def calculate_nearest(row, destination, val, col=”geometry”): # 1 - create unary union dest_unary = destination[“geometry”].unary_union # 2 - find closest point nearest_geom = nearest_points(row[col], dest_unary) # 3 - Find the corresponding geom match_geom = destination.loc[destination.geometry == nearest_geom[1]] # 4 - get the corresponding value match_value = match_geom[val].to_numpy()[0] return match_value"
},
{
"code": null,
"e": 3880,
"s": 3707,
"text": "We apply this function to the second dataset points_gdf to derive each random point’s nearest geometry (from station_gdf) and also the station name of the closest geometry."
},
{
"code": null,
"e": 4186,
"s": 3880,
"text": "# Get the nearest geometrypoints_gdf[“nearest_geom”] = points_gdf.apply(calculate_nearest, destination=stations_gdf, val=”geometry”, axis=1)# Get the nearest Bike station namepoints_gdf[“nearest_station”] = points_gdf.apply(calculate_nearest, destination=stations_gdf, val=”name”, axis=1)points_gdf.head()"
},
{
"code": null,
"e": 4279,
"s": 4186,
"text": "The output is the following table where we have the two additional columns we created above."
},
{
"code": null,
"e": 4586,
"s": 4279,
"text": "Now, we have both nearest_station and nearest_geom in the points_gdf . for instance, in id 2, we can see that the nearest station is Lincoln Ave & Belle Plane Ave station. We need to verify our results, let create a line Geodataframe from geometry and nearest_geom which helps us explore the data visually."
},
{
"code": null,
"e": 4896,
"s": 4586,
"text": "# Create LineString Geometrypoints_gdf[‘line’] = points_gdf.apply(lambda row: LineString([row[‘geometry’], row[‘nearest_geom’]]), axis=1)# Create Line Geodataframeline_gdf = points_gdf[[\"id\", \"nearest_station\", \"line\"]].set_geometry('line')# Set the Coordinate referenceline_gdf.crs = crs={\"init\":\"epsg:4326\"}"
},
{
"code": null,
"e": 5055,
"s": 4896,
"text": "We have destination points station_gdf, nearest points inpoints_gdf and now theline_gdf that connects both datasets. Let us visualise all of them in one plot."
},
{
"code": null,
"e": 5554,
"s": 5055,
"text": "m = folium.Map([41.805379, -87.601501],zoom_start = 12, tiles=”CartoDb dark_matter”)locs_stations = zip(stations_gdf.ycoord, stations_gdf.xcoord)locs_points = zip(points_gdf.ycoord, points_gdf.xcoord)for location in locs_stations: folium.CircleMarker(location=location, color=”red”, radius=8).add_to(m)for location in locs_points: folium.CircleMarker(location=location, color=”white”, radius=4).add_to(m)folium.GeoJson(line_gdf).add_to(m)m.save(“map2.html”)m"
},
{
"code": null,
"e": 5692,
"s": 5554,
"text": "You can easily explore the dataset and see the connection between the nearest station of each point with the help of the map shown below."
},
{
"code": null,
"e": 5962,
"s": 5692,
"text": "The map shows Bike stations in Red circle, the random points in White and the connection line in Blue. You can explore further the interactive map in the accompanying notebook. The final result is accurate and also can be replicated in any other dataset of your choice."
},
{
"code": null,
"e": 6193,
"s": 5962,
"text": "In this tutorial, we covered how to perform Nearest Neighbourhood Analysis using Geopandas and Shapely using Chicago Bike stations. We also explored how we can easily construct and visualise the result of the analysis with Folium."
},
{
"code": null,
"e": 6260,
"s": 6193,
"text": "The code for this tutorial is available in this Github repository:"
},
{
"code": null,
"e": 6271,
"s": 6260,
"text": "github.com"
}
] |
C library function - freopen()
|
The C library function FILE *freopen(const char *filename, const char *mode, FILE *stream) associates a new filename with the given open stream and at the same time closes the old file in the stream.
Following is the declaration for freopen() function.
FILE *freopen(const char *filename, const char *mode, FILE *stream)
filename − This is the C string containing the name of the file to be opened.
filename − This is the C string containing the name of the file to be opened.
mode − This is the C string containing a file access mode. It includes −
mode − This is the C string containing a file access mode. It includes −
"r"
Opens a file for reading. The file must exist.
"w"
Creates an empty file for writing. If a file with the same name already exists then its content is erased and the file is considered as a new empty file.
"a"
Appends to a file. Writing operations appends data at the end of the file. The file is created if it does not exist.
"r+"
Opens a file to update both reading and writing. The file must exist.
"w+"
Creates an empty file for both reading and writing.
"a+"
Opens a file for reading and appending.
stream − This is the pointer to a FILE object that identifies the stream to be re-opened.
stream − This is the pointer to a FILE object that identifies the stream to be re-opened.
If the file was re-opened successfully, the function returns a pointer to an object identifying the stream or else, null pointer is returned.
The following example shows the usage of freopen() function.
#include <stdio.h>
int main () {
FILE *fp;
printf("This text is redirected to stdout\n");
fp = freopen("file.txt", "w+", stdout);
printf("This text is redirected to file.txt\n");
fclose(fp);
return(0);
}
Let us compile and run the above program that will send the following line at STDOUT because initially we did not open stdout −
This text is redirected to stdout
After a call to freopen(), it associates STDOUT to file file.txt, so whatever we write at STDOUT that goes inside file.txt. So, the file file.txt will have the following content.
This text is redirected to file.txt
Now let's see the content of the above file using the following program −
#include <stdio.h>
int main () {
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1) {
c = fgetc(fp);
if( feof(fp) ) {
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2207,
"s": 2007,
"text": "The C library function FILE *freopen(const char *filename, const char *mode, FILE *stream) associates a new filename with the given open stream and at the same time closes the old file in the stream."
},
{
"code": null,
"e": 2260,
"s": 2207,
"text": "Following is the declaration for freopen() function."
},
{
"code": null,
"e": 2328,
"s": 2260,
"text": "FILE *freopen(const char *filename, const char *mode, FILE *stream)"
},
{
"code": null,
"e": 2406,
"s": 2328,
"text": "filename − This is the C string containing the name of the file to be opened."
},
{
"code": null,
"e": 2484,
"s": 2406,
"text": "filename − This is the C string containing the name of the file to be opened."
},
{
"code": null,
"e": 2557,
"s": 2484,
"text": "mode − This is the C string containing a file access mode. It includes −"
},
{
"code": null,
"e": 2630,
"s": 2557,
"text": "mode − This is the C string containing a file access mode. It includes −"
},
{
"code": null,
"e": 2634,
"s": 2630,
"text": "\"r\""
},
{
"code": null,
"e": 2681,
"s": 2634,
"text": "Opens a file for reading. The file must exist."
},
{
"code": null,
"e": 2685,
"s": 2681,
"text": "\"w\""
},
{
"code": null,
"e": 2839,
"s": 2685,
"text": "Creates an empty file for writing. If a file with the same name already exists then its content is erased and the file is considered as a new empty file."
},
{
"code": null,
"e": 2843,
"s": 2839,
"text": "\"a\""
},
{
"code": null,
"e": 2960,
"s": 2843,
"text": "Appends to a file. Writing operations appends data at the end of the file. The file is created if it does not exist."
},
{
"code": null,
"e": 2965,
"s": 2960,
"text": "\"r+\""
},
{
"code": null,
"e": 3035,
"s": 2965,
"text": "Opens a file to update both reading and writing. The file must exist."
},
{
"code": null,
"e": 3040,
"s": 3035,
"text": "\"w+\""
},
{
"code": null,
"e": 3092,
"s": 3040,
"text": "Creates an empty file for both reading and writing."
},
{
"code": null,
"e": 3097,
"s": 3092,
"text": "\"a+\""
},
{
"code": null,
"e": 3137,
"s": 3097,
"text": "Opens a file for reading and appending."
},
{
"code": null,
"e": 3227,
"s": 3137,
"text": "stream − This is the pointer to a FILE object that identifies the stream to be re-opened."
},
{
"code": null,
"e": 3317,
"s": 3227,
"text": "stream − This is the pointer to a FILE object that identifies the stream to be re-opened."
},
{
"code": null,
"e": 3459,
"s": 3317,
"text": "If the file was re-opened successfully, the function returns a pointer to an object identifying the stream or else, null pointer is returned."
},
{
"code": null,
"e": 3520,
"s": 3459,
"text": "The following example shows the usage of freopen() function."
},
{
"code": null,
"e": 3751,
"s": 3520,
"text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n\n printf(\"This text is redirected to stdout\\n\");\n\n fp = freopen(\"file.txt\", \"w+\", stdout);\n\n printf(\"This text is redirected to file.txt\\n\");\n\n fclose(fp);\n \n return(0);\n}"
},
{
"code": null,
"e": 3879,
"s": 3751,
"text": "Let us compile and run the above program that will send the following line at STDOUT because initially we did not open stdout −"
},
{
"code": null,
"e": 3914,
"s": 3879,
"text": "This text is redirected to stdout\n"
},
{
"code": null,
"e": 4093,
"s": 3914,
"text": "After a call to freopen(), it associates STDOUT to file file.txt, so whatever we write at STDOUT that goes inside file.txt. So, the file file.txt will have the following content."
},
{
"code": null,
"e": 4130,
"s": 4093,
"text": "This text is redirected to file.txt\n"
},
{
"code": null,
"e": 4204,
"s": 4130,
"text": "Now let's see the content of the above file using the following program −"
},
{
"code": null,
"e": 4435,
"s": 4204,
"text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n int c;\n\n fp = fopen(\"file.txt\",\"r\");\n while(1) {\n c = fgetc(fp);\n if( feof(fp) ) {\n break ;\n }\n printf(\"%c\", c);\n }\n fclose(fp);\n return(0);\n}"
},
{
"code": null,
"e": 4468,
"s": 4435,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4483,
"s": 4468,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4518,
"s": 4483,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4533,
"s": 4518,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4568,
"s": 4533,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4582,
"s": 4568,
"text": " Asif Hussain"
},
{
"code": null,
"e": 4615,
"s": 4582,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4633,
"s": 4615,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 4668,
"s": 4633,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4687,
"s": 4668,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 4720,
"s": 4687,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4732,
"s": 4720,
"text": " Amit Diwan"
},
{
"code": null,
"e": 4739,
"s": 4732,
"text": " Print"
},
{
"code": null,
"e": 4750,
"s": 4739,
"text": " Add Notes"
}
] |
Tryit Editor v3.7
|
Tryit: JavaScript - change attribute value
|
[] |
How to do groupby on a multiindex in Pandas? - GeeksforGeeks
|
30 May, 2021
In this article, we will be showing how to use the groupby on a Multiindex Dataframe in Pandas. In Data science when we are performing exploratory data analysis, we often use groupby to group the data of one column based on the other column. So, we are able to analyze how the data of one column is grouped or depending based upon the other column. There is also an alternative to groupby, we can also use a Pivot Table.
A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Any groupby operation involves one of the following operations on the original DataFrame. They are −
Splitting the object.Combining the Output.Applying a function.
Splitting the object.
Combining the Output.
Applying a function.
Syntax: DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)
Parameters :
by: mapping, function, label or list of tables
axis: { 0 or ‘index’, 1 or ‘columns’}, default 0
level: level name
sort: bool, default True
Returns : DataFrameGroupBy
We have to pass the name of indexes, in the list to the level argument in groupby function. The ‘region’ index is level (0) index, and ‘state’ index is level (1) index. In this article, we are going to use this CSV file.
Python3
# importing pandas library # as alias pdimport pandas as pd # storing the data in the df dataframe# using pandas 'read_csv()'.df = pd.read_csv('homelessness.csv') print(df.head())
Output:
We can know the columns of the DataFrame by using the Pandas columns attribute.
Python3
# using pandas columns attribute.col = df.columns print(col)
Output:
As there is no indexing in the DataFrame, or we can say this DataFrame has no index. First, we have to make this DataFrame, Multi index DataFrame, or Hierarchical index DataFrame.
The DataFrame which has more than one index is called Multi-index DataFrame. To know more about the multi-index DataFrame, how to make the DataFrame multi-indexed and how to use multi-indexed DataFrame for data exploration, you can refer this article.
To, Make the DataFrame multi-indexed, we will be going to use the Pandas set_index() function. We are going to make the ‘region‘ and ‘state‘ columns of the Dataframe as the index.
Python3
# using the pandas set_index().# passing the name of the columns in the list. df = df.set_index(['region' , 'state']) # sort the data using sort_index()df.sort_index() print(df.head())
Output:
Now, the DataFrame is a multi-indexed DataFrame having the ‘region‘ and ‘state‘ columns as an index.
Here we will represent the levels with the numbering index starting from 0.
Python3
# passing the level of indexes in # the list to the level argument. df.groupby(level=[0,1]).sum()
Output:
Instead of the level number, we can also pass the names of the columns.
Python3
# passing name of the index in # the level argument.y = df.groupby(level=['region'])['individuals'].mean() print(y)
Output:
We can also some methods with groupby to explore more.
Suppose we want to know how many states of each region, have a ‘family_members’ more than 1000. For this kind of problem statement, we can use apply(). Inside apply(), we have to pass the kind of function, which is specially designed for a particular task. So, in this case, we are going to use the lambda function, which is a great way to write functions in one line.
Python3
# import numpy library as alias npimport numpy as np # applying .apply(), inside which passing # the lambda function. lambda function,# counting the no of states in each region# where are more than 1000 family_members.fam_1000 = df.groupby( level=["region"])["family_members].apply(lambda x : np.sum(x>1000)) print(fam_1000)
Output:
The agg() function can be used for performing some statistical operation like min(), max() , mean() etc. If we want to perform more than one statistical operation at a time, then we can pass them in the list.
Python3
# performing max() and min() operation, # on the 'state_pop' column.df_agg = df.groupby( level=["region", "state"])["state_pop"].agg(["max", "min"]) print(df_agg)
Output:
The transform() is used to transform the columns, under a given condition. Inside the transform function, we have to pass the function that will responsible for performing a special task. We are going to use the lambda function.
Python3
# defining the lambda function as 'score'score = (lambda x : (x / x.mean())) # applying transform() on all the # columns of DataFrame inside the# transform(), passing the score df_tra = df.groupby(level=["region"]).transform(score)print(df_tra.head(10))
Output:
Note: There is an alternative of groupby operation, Pivot_table which is also used to group the first column based on the others’ column, but pivot table can be more useful if we want to analyze groups statistically.
Picked
Python pandas-groupby
Python pandas-indexing
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 ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24318,
"s": 24290,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 24739,
"s": 24318,
"text": "In this article, we will be showing how to use the groupby on a Multiindex Dataframe in Pandas. In Data science when we are performing exploratory data analysis, we often use groupby to group the data of one column based on the other column. So, we are able to analyze how the data of one column is grouped or depending based upon the other column. There is also an alternative to groupby, we can also use a Pivot Table."
},
{
"code": null,
"e": 25047,
"s": 24739,
"text": "A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Any groupby operation involves one of the following operations on the original DataFrame. They are −"
},
{
"code": null,
"e": 25110,
"s": 25047,
"text": "Splitting the object.Combining the Output.Applying a function."
},
{
"code": null,
"e": 25132,
"s": 25110,
"text": "Splitting the object."
},
{
"code": null,
"e": 25154,
"s": 25132,
"text": "Combining the Output."
},
{
"code": null,
"e": 25175,
"s": 25154,
"text": "Applying a function."
},
{
"code": null,
"e": 25298,
"s": 25175,
"text": "Syntax: DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)"
},
{
"code": null,
"e": 25319,
"s": 25298,
"text": "Parameters : "
},
{
"code": null,
"e": 25372,
"s": 25319,
"text": "by: mapping, function, label or list of tables"
},
{
"code": null,
"e": 25421,
"s": 25372,
"text": "axis: { 0 or ‘index’, 1 or ‘columns’}, default 0"
},
{
"code": null,
"e": 25439,
"s": 25421,
"text": "level: level name"
},
{
"code": null,
"e": 25464,
"s": 25439,
"text": "sort: bool, default True"
},
{
"code": null,
"e": 25491,
"s": 25464,
"text": "Returns : DataFrameGroupBy"
},
{
"code": null,
"e": 25712,
"s": 25491,
"text": "We have to pass the name of indexes, in the list to the level argument in groupby function. The ‘region’ index is level (0) index, and ‘state’ index is level (1) index. In this article, we are going to use this CSV file."
},
{
"code": null,
"e": 25720,
"s": 25712,
"text": "Python3"
},
{
"code": "# importing pandas library # as alias pdimport pandas as pd # storing the data in the df dataframe# using pandas 'read_csv()'.df = pd.read_csv('homelessness.csv') print(df.head())",
"e": 25902,
"s": 25720,
"text": null
},
{
"code": null,
"e": 25910,
"s": 25902,
"text": "Output:"
},
{
"code": null,
"e": 25990,
"s": 25910,
"text": "We can know the columns of the DataFrame by using the Pandas columns attribute."
},
{
"code": null,
"e": 25998,
"s": 25990,
"text": "Python3"
},
{
"code": "# using pandas columns attribute.col = df.columns print(col)",
"e": 26060,
"s": 25998,
"text": null
},
{
"code": null,
"e": 26068,
"s": 26060,
"text": "Output:"
},
{
"code": null,
"e": 26248,
"s": 26068,
"text": "As there is no indexing in the DataFrame, or we can say this DataFrame has no index. First, we have to make this DataFrame, Multi index DataFrame, or Hierarchical index DataFrame."
},
{
"code": null,
"e": 26501,
"s": 26248,
"text": "The DataFrame which has more than one index is called Multi-index DataFrame. To know more about the multi-index DataFrame, how to make the DataFrame multi-indexed and how to use multi-indexed DataFrame for data exploration, you can refer this article. "
},
{
"code": null,
"e": 26681,
"s": 26501,
"text": "To, Make the DataFrame multi-indexed, we will be going to use the Pandas set_index() function. We are going to make the ‘region‘ and ‘state‘ columns of the Dataframe as the index."
},
{
"code": null,
"e": 26689,
"s": 26681,
"text": "Python3"
},
{
"code": "# using the pandas set_index().# passing the name of the columns in the list. df = df.set_index(['region' , 'state']) # sort the data using sort_index()df.sort_index() print(df.head())",
"e": 26877,
"s": 26689,
"text": null
},
{
"code": null,
"e": 26885,
"s": 26877,
"text": "Output:"
},
{
"code": null,
"e": 26986,
"s": 26885,
"text": "Now, the DataFrame is a multi-indexed DataFrame having the ‘region‘ and ‘state‘ columns as an index."
},
{
"code": null,
"e": 27062,
"s": 26986,
"text": "Here we will represent the levels with the numbering index starting from 0."
},
{
"code": null,
"e": 27070,
"s": 27062,
"text": "Python3"
},
{
"code": "# passing the level of indexes in # the list to the level argument. df.groupby(level=[0,1]).sum()",
"e": 27168,
"s": 27070,
"text": null
},
{
"code": null,
"e": 27176,
"s": 27168,
"text": "Output:"
},
{
"code": null,
"e": 27248,
"s": 27176,
"text": "Instead of the level number, we can also pass the names of the columns."
},
{
"code": null,
"e": 27256,
"s": 27248,
"text": "Python3"
},
{
"code": "# passing name of the index in # the level argument.y = df.groupby(level=['region'])['individuals'].mean() print(y)",
"e": 27373,
"s": 27256,
"text": null
},
{
"code": null,
"e": 27381,
"s": 27373,
"text": "Output:"
},
{
"code": null,
"e": 27436,
"s": 27381,
"text": "We can also some methods with groupby to explore more."
},
{
"code": null,
"e": 27805,
"s": 27436,
"text": "Suppose we want to know how many states of each region, have a ‘family_members’ more than 1000. For this kind of problem statement, we can use apply(). Inside apply(), we have to pass the kind of function, which is specially designed for a particular task. So, in this case, we are going to use the lambda function, which is a great way to write functions in one line."
},
{
"code": null,
"e": 27813,
"s": 27805,
"text": "Python3"
},
{
"code": "# import numpy library as alias npimport numpy as np # applying .apply(), inside which passing # the lambda function. lambda function,# counting the no of states in each region# where are more than 1000 family_members.fam_1000 = df.groupby( level=[\"region\"])[\"family_members].apply(lambda x : np.sum(x>1000)) print(fam_1000)",
"e": 28141,
"s": 27813,
"text": null
},
{
"code": null,
"e": 28149,
"s": 28141,
"text": "Output:"
},
{
"code": null,
"e": 28358,
"s": 28149,
"text": "The agg() function can be used for performing some statistical operation like min(), max() , mean() etc. If we want to perform more than one statistical operation at a time, then we can pass them in the list."
},
{
"code": null,
"e": 28366,
"s": 28358,
"text": "Python3"
},
{
"code": "# performing max() and min() operation, # on the 'state_pop' column.df_agg = df.groupby( level=[\"region\", \"state\"])[\"state_pop\"].agg([\"max\", \"min\"]) print(df_agg)",
"e": 28531,
"s": 28366,
"text": null
},
{
"code": null,
"e": 28539,
"s": 28531,
"text": "Output:"
},
{
"code": null,
"e": 28768,
"s": 28539,
"text": "The transform() is used to transform the columns, under a given condition. Inside the transform function, we have to pass the function that will responsible for performing a special task. We are going to use the lambda function."
},
{
"code": null,
"e": 28776,
"s": 28768,
"text": "Python3"
},
{
"code": "# defining the lambda function as 'score'score = (lambda x : (x / x.mean())) # applying transform() on all the # columns of DataFrame inside the# transform(), passing the score df_tra = df.groupby(level=[\"region\"]).transform(score)print(df_tra.head(10))",
"e": 29032,
"s": 28776,
"text": null
},
{
"code": null,
"e": 29040,
"s": 29032,
"text": "Output:"
},
{
"code": null,
"e": 29257,
"s": 29040,
"text": "Note: There is an alternative of groupby operation, Pivot_table which is also used to group the first column based on the others’ column, but pivot table can be more useful if we want to analyze groups statistically."
},
{
"code": null,
"e": 29264,
"s": 29257,
"text": "Picked"
},
{
"code": null,
"e": 29286,
"s": 29264,
"text": "Python pandas-groupby"
},
{
"code": null,
"e": 29309,
"s": 29286,
"text": "Python pandas-indexing"
},
{
"code": null,
"e": 29323,
"s": 29309,
"text": "Python-pandas"
},
{
"code": null,
"e": 29330,
"s": 29323,
"text": "Python"
},
{
"code": null,
"e": 29428,
"s": 29330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29460,
"s": 29428,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29502,
"s": 29460,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29558,
"s": 29502,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29600,
"s": 29558,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29622,
"s": 29600,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29653,
"s": 29622,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29708,
"s": 29653,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 29747,
"s": 29708,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29776,
"s": 29747,
"text": "Create a directory in Python"
}
] |
How do you plot a vertical line on a time series plot in Pandas?
|
Using Pandas, we will create a dataframe and set the vertical lines on the created axes, using axvline lines.
Using panda we can create a data frame.
Using panda we can create a data frame.
Creating a data frame would help to create help.
Creating a data frame would help to create help.
Using axvline(), add a vertical line across the axes, where color is green, linestyle="dashed".
Using axvline(), add a vertical line across the axes, where color is green, linestyle="dashed".
Using axvline(), add a vertical line across the axes, where color is red, linestyle="dashed".
Using axvline(), add a vertical line across the axes, where color is red, linestyle="dashed".
Using plt.show(), show the plot.
Using plt.show(), show the plot.
import pandas as pd
from matplotlib import pyplot as plt
df = pd.DataFrame(index=pd.date_range("2019-07-01", "2019-07-31"))
df["y"] = 1
ax = df.plot()
ax.axvline("2019-07-24", color="green", linestyle="dashed")
ax.axvline("2019-07-31", color="red", linestyle="dashed")
plt.show()
|
[
{
"code": null,
"e": 1172,
"s": 1062,
"text": "Using Pandas, we will create a dataframe and set the vertical lines on the created axes, using axvline lines."
},
{
"code": null,
"e": 1212,
"s": 1172,
"text": "Using panda we can create a data frame."
},
{
"code": null,
"e": 1252,
"s": 1212,
"text": "Using panda we can create a data frame."
},
{
"code": null,
"e": 1301,
"s": 1252,
"text": "Creating a data frame would help to create help."
},
{
"code": null,
"e": 1350,
"s": 1301,
"text": "Creating a data frame would help to create help."
},
{
"code": null,
"e": 1446,
"s": 1350,
"text": "Using axvline(), add a vertical line across the axes, where color is green, linestyle=\"dashed\"."
},
{
"code": null,
"e": 1542,
"s": 1446,
"text": "Using axvline(), add a vertical line across the axes, where color is green, linestyle=\"dashed\"."
},
{
"code": null,
"e": 1636,
"s": 1542,
"text": "Using axvline(), add a vertical line across the axes, where color is red, linestyle=\"dashed\"."
},
{
"code": null,
"e": 1730,
"s": 1636,
"text": "Using axvline(), add a vertical line across the axes, where color is red, linestyle=\"dashed\"."
},
{
"code": null,
"e": 1763,
"s": 1730,
"text": "Using plt.show(), show the plot."
},
{
"code": null,
"e": 1796,
"s": 1763,
"text": "Using plt.show(), show the plot."
},
{
"code": null,
"e": 2076,
"s": 1796,
"text": "import pandas as pd\nfrom matplotlib import pyplot as plt\ndf = pd.DataFrame(index=pd.date_range(\"2019-07-01\", \"2019-07-31\"))\ndf[\"y\"] = 1\nax = df.plot()\nax.axvline(\"2019-07-24\", color=\"green\", linestyle=\"dashed\")\nax.axvline(\"2019-07-31\", color=\"red\", linestyle=\"dashed\")\nplt.show()"
}
] |
Program to check if an array is sorted or not (Iterative and Recursive) in C
|
Given an array arr[] with n number of elements, our task is to check whether the given array is in sorted order or not, If it is in sorted order then print “The array is in sorted order”, else print “The array is not in sorted order”.
To solve the above stated problem we can use Iterative or Recursive approach, we will be discussing both.
So, what is a Recursive approach? In Recursive approach we recursively call a function again and again until we get the desirable result. In recursive approach the values returned by function is stored in stack memory.
Input
arr[] = {12, 13, 14, 16, 18}
Output
The array is in sorted order
Explanation − 12 < 13 < 14 < 16 < 18, so, yes the array is in sorted
Input
arr[] = {2, 1, 3, 5, 6}
Output
The array is not in sorted order
Explanation − 2 not smaller than 1, so, it is not in the sorted order.
Take an array arr[] as an input and initialize n with the size of an array.
Take an array arr[] as an input and initialize n with the size of an array.
Check if we reached the starting of an array, return true.
Check if we reached the starting of an array, return true.
Check if the previous element of an array is not smaller than the next element, return false.
Check if the previous element of an array is not smaller than the next element, return false.
Decrement n and goto step 2.
Decrement n and goto step 2.
Start
In function int arraySortedCheck(int arr[], int n)
Step 1→ If n == 1 || n == 0 then,
Return 1
Step 2→ If arr[n-1] < arr[n-2] then,
Return 0
Step 3→ Return arraySortedCheck(arr, n-1)
In Function int main(int argc, char const *argv[])
Step 1→ Declare and initialize arr[] as {1,8,3,4,7}
Step 2→ Declare and initialize int n as sizeof(arr)/sizeof(arr[0])
Step 3→ If arraySortedCheck(arr, n) then,
Print "Array is in sorted order”
Step 4→ Else
Print "Array is not in sorted order”
Stop
Live Demo
//Recursive approach
#include <stdio.h>
//Recursive function to check if it
//is in sorted order or not
int arraySortedCheck(int arr[], int n){
//all elements are checked and
//all are in sorted order
if (n == 1 || n == 0)
return 1;
//when an array is not in sorted order
if(arr[n-1] < arr[n-2])
return 0;
return arraySortedCheck(arr, n-1);
}
int main(int argc, char const *argv[]){
int arr[] = {1,8,3,4,7};
int n = sizeof(arr)/sizeof(arr[0]);
if(arraySortedCheck(arr, n)){
printf("Array is in sorted order\n");
}
else
printf("Array is not in sorted order\n");
return 0;
}
If run the above code it will generate the following output −
Array is in sorted order
In iterative approach, we use loops like for-loop, while-loop or do-while loop which executes the statements till the condition holds true which means 1.
Input
arr[] = {12, 13, 14, 16, 18}
Output
The array is in sorted order
Explanation − 12 < 13 < 14 < 16 < 18, so, yes the array is in sorted order
Input
arr[] = {2, 1, 3, 5, 6}
Output
The array is not in sorted order
Explanation 2 not smaller than 1, so, it is not in the sorted order.
Take an input arr[].
Take an input arr[].
Loop until we reach the end of that array.Check if the current element is not smaller than the next element, return false and exit.Else continue.
Loop until we reach the end of that array.
Check if the current element is not smaller than the next element, return false and exit.
Check if the current element is not smaller than the next element, return false and exit.
Else continue.
Else continue.
Goto step 2.
Goto step 2.
Start
In function int arraySortedCheck(int arr[], int n)
Step 1 → Loop For i = 0 and i < n and ++i
If arr[n-1] < arr[n-2] then,
Return 0
Step 2→ Return 1
In Function int main(int argc, char const *argv[])
Step 1→ Declare and initialize arr[] as {1,8,3,4,7}
Step 2→ Declare and initialize int n as sizeof(arr)/sizeof(arr[0])
Step 3→ If arraySortedCheck(arr, n) then,
Print "Array is in sorted order”
Step 4→ Else
Print "Array is not in sorted order”
Stop
Live Demo
//Iterative approach
#include <stdio.h>
int arraySortedCheck(int arr[], int n){
for (int i = 0; i < n; ++i){
//when an array is not in sorted order
if(arr[n-1] < arr[n-2])
return 0;
}
//all elements are checked and
//all are in sorted order
return 1;
}
int main(int argc, char const *argv[]){
int arr[] = {1,8,3,4,7};
int n = sizeof(arr)/sizeof(arr[0]);
if(arraySortedCheck(arr, n)){
printf("Array is in sorted order\n");
}
else
printf("Array is not in sorted order\n");
return 0;
}
If run the above code it will generate the following output −
Array is in sorted order
|
[
{
"code": null,
"e": 1297,
"s": 1062,
"text": "Given an array arr[] with n number of elements, our task is to check whether the given array is in sorted order or not, If it is in sorted order then print “The array is in sorted order”, else print “The array is not in sorted order”."
},
{
"code": null,
"e": 1403,
"s": 1297,
"text": "To solve the above stated problem we can use Iterative or Recursive approach, we will be discussing both."
},
{
"code": null,
"e": 1622,
"s": 1403,
"text": "So, what is a Recursive approach? In Recursive approach we recursively call a function again and again until we get the desirable result. In recursive approach the values returned by function is stored in stack memory."
},
{
"code": null,
"e": 1629,
"s": 1622,
"text": "Input "
},
{
"code": null,
"e": 1658,
"s": 1629,
"text": "arr[] = {12, 13, 14, 16, 18}"
},
{
"code": null,
"e": 1666,
"s": 1658,
"text": "Output "
},
{
"code": null,
"e": 1695,
"s": 1666,
"text": "The array is in sorted order"
},
{
"code": null,
"e": 1764,
"s": 1695,
"text": "Explanation − 12 < 13 < 14 < 16 < 18, so, yes the array is in sorted"
},
{
"code": null,
"e": 1771,
"s": 1764,
"text": "Input "
},
{
"code": null,
"e": 1795,
"s": 1771,
"text": "arr[] = {2, 1, 3, 5, 6}"
},
{
"code": null,
"e": 1803,
"s": 1795,
"text": "Output "
},
{
"code": null,
"e": 1836,
"s": 1803,
"text": "The array is not in sorted order"
},
{
"code": null,
"e": 1907,
"s": 1836,
"text": "Explanation − 2 not smaller than 1, so, it is not in the sorted order."
},
{
"code": null,
"e": 1983,
"s": 1907,
"text": "Take an array arr[] as an input and initialize n with the size of an array."
},
{
"code": null,
"e": 2059,
"s": 1983,
"text": "Take an array arr[] as an input and initialize n with the size of an array."
},
{
"code": null,
"e": 2118,
"s": 2059,
"text": "Check if we reached the starting of an array, return true."
},
{
"code": null,
"e": 2177,
"s": 2118,
"text": "Check if we reached the starting of an array, return true."
},
{
"code": null,
"e": 2271,
"s": 2177,
"text": "Check if the previous element of an array is not smaller than the next element, return false."
},
{
"code": null,
"e": 2365,
"s": 2271,
"text": "Check if the previous element of an array is not smaller than the next element, return false."
},
{
"code": null,
"e": 2394,
"s": 2365,
"text": "Decrement n and goto step 2."
},
{
"code": null,
"e": 2423,
"s": 2394,
"text": "Decrement n and goto step 2."
},
{
"code": null,
"e": 2956,
"s": 2423,
"text": "Start\nIn function int arraySortedCheck(int arr[], int n)\n Step 1→ If n == 1 || n == 0 then,\n Return 1\n Step 2→ If arr[n-1] < arr[n-2] then,\n Return 0\n Step 3→ Return arraySortedCheck(arr, n-1)\nIn Function int main(int argc, char const *argv[])\n Step 1→ Declare and initialize arr[] as {1,8,3,4,7}\n Step 2→ Declare and initialize int n as sizeof(arr)/sizeof(arr[0])\n Step 3→ If arraySortedCheck(arr, n) then,\n Print \"Array is in sorted order”\n Step 4→ Else\n Print \"Array is not in sorted order”\nStop"
},
{
"code": null,
"e": 2967,
"s": 2956,
"text": " Live Demo"
},
{
"code": null,
"e": 3600,
"s": 2967,
"text": "//Recursive approach\n#include <stdio.h>\n//Recursive function to check if it\n//is in sorted order or not\nint arraySortedCheck(int arr[], int n){\n //all elements are checked and\n //all are in sorted order\n if (n == 1 || n == 0)\n return 1;\n //when an array is not in sorted order\n if(arr[n-1] < arr[n-2])\n return 0;\n return arraySortedCheck(arr, n-1);\n}\nint main(int argc, char const *argv[]){\n int arr[] = {1,8,3,4,7};\n int n = sizeof(arr)/sizeof(arr[0]);\n if(arraySortedCheck(arr, n)){\n printf(\"Array is in sorted order\\n\");\n }\n else\n printf(\"Array is not in sorted order\\n\");\n return 0;\n}"
},
{
"code": null,
"e": 3662,
"s": 3600,
"text": "If run the above code it will generate the following output −"
},
{
"code": null,
"e": 3687,
"s": 3662,
"text": "Array is in sorted order"
},
{
"code": null,
"e": 3841,
"s": 3687,
"text": "In iterative approach, we use loops like for-loop, while-loop or do-while loop which executes the statements till the condition holds true which means 1."
},
{
"code": null,
"e": 3848,
"s": 3841,
"text": "Input "
},
{
"code": null,
"e": 3877,
"s": 3848,
"text": "arr[] = {12, 13, 14, 16, 18}"
},
{
"code": null,
"e": 3885,
"s": 3877,
"text": "Output "
},
{
"code": null,
"e": 3914,
"s": 3885,
"text": "The array is in sorted order"
},
{
"code": null,
"e": 3989,
"s": 3914,
"text": "Explanation − 12 < 13 < 14 < 16 < 18, so, yes the array is in sorted order"
},
{
"code": null,
"e": 3996,
"s": 3989,
"text": "Input "
},
{
"code": null,
"e": 4020,
"s": 3996,
"text": "arr[] = {2, 1, 3, 5, 6}"
},
{
"code": null,
"e": 4028,
"s": 4020,
"text": "Output "
},
{
"code": null,
"e": 4061,
"s": 4028,
"text": "The array is not in sorted order"
},
{
"code": null,
"e": 4130,
"s": 4061,
"text": "Explanation 2 not smaller than 1, so, it is not in the sorted order."
},
{
"code": null,
"e": 4151,
"s": 4130,
"text": "Take an input arr[]."
},
{
"code": null,
"e": 4172,
"s": 4151,
"text": "Take an input arr[]."
},
{
"code": null,
"e": 4318,
"s": 4172,
"text": "Loop until we reach the end of that array.Check if the current element is not smaller than the next element, return false and exit.Else continue."
},
{
"code": null,
"e": 4361,
"s": 4318,
"text": "Loop until we reach the end of that array."
},
{
"code": null,
"e": 4451,
"s": 4361,
"text": "Check if the current element is not smaller than the next element, return false and exit."
},
{
"code": null,
"e": 4541,
"s": 4451,
"text": "Check if the current element is not smaller than the next element, return false and exit."
},
{
"code": null,
"e": 4556,
"s": 4541,
"text": "Else continue."
},
{
"code": null,
"e": 4571,
"s": 4556,
"text": "Else continue."
},
{
"code": null,
"e": 4584,
"s": 4571,
"text": "Goto step 2."
},
{
"code": null,
"e": 4597,
"s": 4584,
"text": "Goto step 2."
},
{
"code": null,
"e": 5096,
"s": 4597,
"text": "Start\nIn function int arraySortedCheck(int arr[], int n)\n Step 1 → Loop For i = 0 and i < n and ++i\n If arr[n-1] < arr[n-2] then,\n Return 0\n Step 2→ Return 1\nIn Function int main(int argc, char const *argv[])\n Step 1→ Declare and initialize arr[] as {1,8,3,4,7}\n Step 2→ Declare and initialize int n as sizeof(arr)/sizeof(arr[0])\n Step 3→ If arraySortedCheck(arr, n) then,\n Print \"Array is in sorted order”\n Step 4→ Else\n Print \"Array is not in sorted order”\nStop"
},
{
"code": null,
"e": 5107,
"s": 5096,
"text": " Live Demo"
},
{
"code": null,
"e": 5656,
"s": 5107,
"text": "//Iterative approach\n#include <stdio.h>\nint arraySortedCheck(int arr[], int n){\n for (int i = 0; i < n; ++i){\n //when an array is not in sorted order\n if(arr[n-1] < arr[n-2])\n return 0;\n }\n //all elements are checked and\n //all are in sorted order\n return 1;\n}\nint main(int argc, char const *argv[]){\n int arr[] = {1,8,3,4,7};\n int n = sizeof(arr)/sizeof(arr[0]);\n if(arraySortedCheck(arr, n)){\n printf(\"Array is in sorted order\\n\");\n }\n else\n printf(\"Array is not in sorted order\\n\");\n return 0;\n}"
},
{
"code": null,
"e": 5718,
"s": 5656,
"text": "If run the above code it will generate the following output −"
},
{
"code": null,
"e": 5743,
"s": 5718,
"text": "Array is in sorted order"
}
] |
Elixir - Data Types
|
For using any language, you need to understand the basic data types the language supports. In this chapter, we will discuss 7 basic data types supported by the elixir language: integers, floats, Booleans, atoms, strings, lists and tuples.
Elixir, like any other programming language, supports both integers and floats. If you open your elixir shell and input any integer or float as input, it'll return its value. For example,
42
When the above program is run, it produces the following result −
42
You can also define numbers in octal, hex and binary bases.
To define a number in octal base, prefix it with '0o'. For example, 0o52 in octal is equivalent to 42 in decimal.
To define a number in decimal base, prefix it with '0x'. For example, 0xF1 in hex is equivalent to 241 in decimal.
To define a number in binary base, prefix it with '0b'. For example, 0b1101 in binary is equivalent to 13 in decimal.
Elixir supports 64bit double precision for floating point numbers. And they can also be defined using an exponentiation style. For example, 10145230000 can be written as 1.014523e10
Atoms are constants whose name is their value. They can be created using the color(:) symbol. For example,
:hello
Elixir supports true and false as Booleans. Both these values are in fact attached to atoms :true and :false respectively.
Strings in Elixir are inserted between double quotes, and they are encoded in UTF-8. They can span multiple lines and contain interpolations. To define a string simply enter it in double quotes −
"Hello world"
To define multiline strings, we use a syntax similar to python with triple double quotes −
"""
Hello
World!
"""
We'll learn about strings, binaries and char lists(similar to strings) in depth in the strings chapter.
Binaries are sequences of bytes enclosed in << >> separated with a comma. For example,
<< 65, 68, 75>>
Binaries are mostly used to handle bits and bytes related data, if you have any. They can, by default, store 0 to 255 in each value. This size limit can be increased by using the size function that says how many bits it should take to store that value. For example,
<<65, 255, 289::size(15)>>
Elixir uses square brackets to specify a list of values. Values can be of any type. For example,
[1, "Hello", :an_atom, true]
Lists come with inbuilt functions for head and tail of the list named hd and tl which return the head and tail of the list respectively. Sometimes when you create a list, it'll return a char list. This is because when elixir sees a list of printable ASCII characters, it prints it as a char list. Please note that strings and char lists are not equal. We'll discuss lists further in later chapters.
Elixir uses curly brackets to define tuples. Like lists, tuples can hold any value.
{ 1, "Hello", :an_atom, true
A question arises here, - why provide both lists and tuples when they both work in the same way? Well they have different implementations.
Lists are actually stored as linked lists, so insertions, deletions are very fast in lists.
Lists are actually stored as linked lists, so insertions, deletions are very fast in lists.
Tuples on the other hand, are stored in contiguous memory block, which make accessing them faster but adds an additional cost on insertions and deletions.
Tuples on the other hand, are stored in contiguous memory block, which make accessing them faster but adds an additional cost on insertions and deletions.
35 Lectures
3 hours
Pranjal Srivastava
54 Lectures
6 hours
Pranjal Srivastava, Harshit Srivastava
80 Lectures
9.5 hours
Pranjal Srivastava
43 Lectures
4 hours
Mohammad Nauman
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2421,
"s": 2182,
"text": "For using any language, you need to understand the basic data types the language supports. In this chapter, we will discuss 7 basic data types supported by the elixir language: integers, floats, Booleans, atoms, strings, lists and tuples."
},
{
"code": null,
"e": 2610,
"s": 2421,
"text": "Elixir, like any other programming language, supports both integers and floats. If you open your elixir shell and input any integer or float as input, it'll return its value. For example, "
},
{
"code": null,
"e": 2614,
"s": 2610,
"text": "42\n"
},
{
"code": null,
"e": 2680,
"s": 2614,
"text": "When the above program is run, it produces the following result −"
},
{
"code": null,
"e": 2684,
"s": 2680,
"text": "42\n"
},
{
"code": null,
"e": 2744,
"s": 2684,
"text": "You can also define numbers in octal, hex and binary bases."
},
{
"code": null,
"e": 2858,
"s": 2744,
"text": "To define a number in octal base, prefix it with '0o'. For example, 0o52 in octal is equivalent to 42 in decimal."
},
{
"code": null,
"e": 2973,
"s": 2858,
"text": "To define a number in decimal base, prefix it with '0x'. For example, 0xF1 in hex is equivalent to 241 in decimal."
},
{
"code": null,
"e": 3091,
"s": 2973,
"text": "To define a number in binary base, prefix it with '0b'. For example, 0b1101 in binary is equivalent to 13 in decimal."
},
{
"code": null,
"e": 3273,
"s": 3091,
"text": "Elixir supports 64bit double precision for floating point numbers. And they can also be defined using an exponentiation style. For example, 10145230000 can be written as 1.014523e10"
},
{
"code": null,
"e": 3381,
"s": 3273,
"text": "Atoms are constants whose name is their value. They can be created using the color(:) symbol. For example, "
},
{
"code": null,
"e": 3388,
"s": 3381,
"text": ":hello"
},
{
"code": null,
"e": 3511,
"s": 3388,
"text": "Elixir supports true and false as Booleans. Both these values are in fact attached to atoms :true and :false respectively."
},
{
"code": null,
"e": 3707,
"s": 3511,
"text": "Strings in Elixir are inserted between double quotes, and they are encoded in UTF-8. They can span multiple lines and contain interpolations. To define a string simply enter it in double quotes −"
},
{
"code": null,
"e": 3721,
"s": 3707,
"text": "\"Hello world\""
},
{
"code": null,
"e": 3812,
"s": 3721,
"text": "To define multiline strings, we use a syntax similar to python with triple double quotes −"
},
{
"code": null,
"e": 3833,
"s": 3812,
"text": "\"\"\"\nHello\nWorld!\n\"\"\""
},
{
"code": null,
"e": 3937,
"s": 3833,
"text": "We'll learn about strings, binaries and char lists(similar to strings) in depth in the strings chapter."
},
{
"code": null,
"e": 4025,
"s": 3937,
"text": "Binaries are sequences of bytes enclosed in << >> separated with a comma. For example,"
},
{
"code": null,
"e": 4041,
"s": 4025,
"text": "<< 65, 68, 75>>"
},
{
"code": null,
"e": 4307,
"s": 4041,
"text": "Binaries are mostly used to handle bits and bytes related data, if you have any. They can, by default, store 0 to 255 in each value. This size limit can be increased by using the size function that says how many bits it should take to store that value. For example,"
},
{
"code": null,
"e": 4335,
"s": 4307,
"text": "<<65, 255, 289::size(15)>>\n"
},
{
"code": null,
"e": 4432,
"s": 4335,
"text": "Elixir uses square brackets to specify a list of values. Values can be of any type. For example,"
},
{
"code": null,
"e": 4462,
"s": 4432,
"text": "[1, \"Hello\", :an_atom, true]\n"
},
{
"code": null,
"e": 4861,
"s": 4462,
"text": "Lists come with inbuilt functions for head and tail of the list named hd and tl which return the head and tail of the list respectively. Sometimes when you create a list, it'll return a char list. This is because when elixir sees a list of printable ASCII characters, it prints it as a char list. Please note that strings and char lists are not equal. We'll discuss lists further in later chapters."
},
{
"code": null,
"e": 4945,
"s": 4861,
"text": "Elixir uses curly brackets to define tuples. Like lists, tuples can hold any value."
},
{
"code": null,
"e": 4975,
"s": 4945,
"text": "{ 1, \"Hello\", :an_atom, true "
},
{
"code": null,
"e": 5114,
"s": 4975,
"text": "A question arises here, - why provide both lists and tuples when they both work in the same way? Well they have different implementations."
},
{
"code": null,
"e": 5206,
"s": 5114,
"text": "Lists are actually stored as linked lists, so insertions, deletions are very fast in lists."
},
{
"code": null,
"e": 5298,
"s": 5206,
"text": "Lists are actually stored as linked lists, so insertions, deletions are very fast in lists."
},
{
"code": null,
"e": 5453,
"s": 5298,
"text": "Tuples on the other hand, are stored in contiguous memory block, which make accessing them faster but adds an additional cost on insertions and deletions."
},
{
"code": null,
"e": 5608,
"s": 5453,
"text": "Tuples on the other hand, are stored in contiguous memory block, which make accessing them faster but adds an additional cost on insertions and deletions."
},
{
"code": null,
"e": 5641,
"s": 5608,
"text": "\n 35 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5661,
"s": 5641,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 5694,
"s": 5661,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5734,
"s": 5694,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 5769,
"s": 5734,
"text": "\n 80 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 5789,
"s": 5769,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 5822,
"s": 5789,
"text": "\n 43 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5839,
"s": 5822,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 5846,
"s": 5839,
"text": " Print"
},
{
"code": null,
"e": 5857,
"s": 5846,
"text": " Add Notes"
}
] |
Find total number of distinct years from a string in C++ Program
|
In this tutorial, we are going to write a program that finds distinct years in the given string. Let's see some examples. We are assuming the date format is DD/MM/YYYY.
Input − Sample example with dates 01/11/2020, 02/12/2020, and 03/10/2019.
Output − 2
We have two distinct years in the given text 2020 and 2019.
We are going to use regex to extract all dates from the given string. If you are not familiar with regex in C++, go through this tutorial.
Let's jump into solving the problem.
Initialize the text.
Initialize the text.
Write the regex to extract dates from the text.
Write the regex to extract dates from the text.
Initialize an empty unordered set.
Initialize an empty unordered set.
Iterate over the dates and add year to the unordered set to find unique years.
Iterate over the dates and add year to the unordered set to find unique years.
Print the length of the set.
Print the length of the set.
Let's see the code.
Live Demo
#include <iostream>
#include <bits/stdc++.h>
#include <regex>
using namespace std;
int uniqueYearsCount(string text) {
// regex
regex date_regex("[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}");
smatch matching_date;
// set to store unique dates
unordered_set<string> dates;
// finding all dates
while (regex_search(text, matching_date, date_regex)) {
string date = matching_date[0];
dates.insert(date.substr(date.size() - 4));
text = matching_date.suffix();
}
return dates.size();
}
int main() {
string text = "Sample example with dates 01/11/2020, 02/12/2020, and 03/10/2019.";
cout << uniqueYearsCount(text) << endl;
return 0;
}
If run the above code, then you will get the following result.
2
We can get dates in a different formats. If you get dates in different formats, then update the regex appropriately.
If you have any queries in the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1231,
"s": 1062,
"text": "In this tutorial, we are going to write a program that finds distinct years in the given string. Let's see some examples. We are assuming the date format is DD/MM/YYYY."
},
{
"code": null,
"e": 1305,
"s": 1231,
"text": "Input − Sample example with dates 01/11/2020, 02/12/2020, and 03/10/2019."
},
{
"code": null,
"e": 1316,
"s": 1305,
"text": "Output − 2"
},
{
"code": null,
"e": 1376,
"s": 1316,
"text": "We have two distinct years in the given text 2020 and 2019."
},
{
"code": null,
"e": 1515,
"s": 1376,
"text": "We are going to use regex to extract all dates from the given string. If you are not familiar with regex in C++, go through this tutorial."
},
{
"code": null,
"e": 1552,
"s": 1515,
"text": "Let's jump into solving the problem."
},
{
"code": null,
"e": 1573,
"s": 1552,
"text": "Initialize the text."
},
{
"code": null,
"e": 1594,
"s": 1573,
"text": "Initialize the text."
},
{
"code": null,
"e": 1642,
"s": 1594,
"text": "Write the regex to extract dates from the text."
},
{
"code": null,
"e": 1690,
"s": 1642,
"text": "Write the regex to extract dates from the text."
},
{
"code": null,
"e": 1725,
"s": 1690,
"text": "Initialize an empty unordered set."
},
{
"code": null,
"e": 1760,
"s": 1725,
"text": "Initialize an empty unordered set."
},
{
"code": null,
"e": 1839,
"s": 1760,
"text": "Iterate over the dates and add year to the unordered set to find unique years."
},
{
"code": null,
"e": 1918,
"s": 1839,
"text": "Iterate over the dates and add year to the unordered set to find unique years."
},
{
"code": null,
"e": 1947,
"s": 1918,
"text": "Print the length of the set."
},
{
"code": null,
"e": 1976,
"s": 1947,
"text": "Print the length of the set."
},
{
"code": null,
"e": 1996,
"s": 1976,
"text": "Let's see the code."
},
{
"code": null,
"e": 2007,
"s": 1996,
"text": " Live Demo"
},
{
"code": null,
"e": 2678,
"s": 2007,
"text": "#include <iostream>\n#include <bits/stdc++.h>\n#include <regex>\nusing namespace std;\nint uniqueYearsCount(string text) {\n // regex\n regex date_regex(\"[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}\");\n smatch matching_date;\n // set to store unique dates\n unordered_set<string> dates;\n // finding all dates\n while (regex_search(text, matching_date, date_regex)) {\n string date = matching_date[0];\n dates.insert(date.substr(date.size() - 4));\n text = matching_date.suffix();\n }\n return dates.size();\n}\nint main() {\n string text = \"Sample example with dates 01/11/2020, 02/12/2020, and 03/10/2019.\";\n cout << uniqueYearsCount(text) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2741,
"s": 2678,
"text": "If run the above code, then you will get the following result."
},
{
"code": null,
"e": 2743,
"s": 2741,
"text": "2"
},
{
"code": null,
"e": 2860,
"s": 2743,
"text": "We can get dates in a different formats. If you get dates in different formats, then update the regex appropriately."
},
{
"code": null,
"e": 2938,
"s": 2860,
"text": "If you have any queries in the tutorial, mention them in the comment section."
}
] |
Algorithms in C++. Complete Search, Greedy, Divide and... | by Vadim Smolyakov | Towards Data Science
|
The purpose of this article is to introduce the reader to four main algorithmic paradigms: complete search, greedy algorithms, divide and conquer, and dynamic programming. Many algorithmic problems can be mapped into one of these four categories and the mastery of each one will make you a better programmer.
This article is written from the perspective of competitive programming. In the reference section, you’ll find resources to get you started or improve your programming skills through coding competitions.
Complete search (aka brute force or recursive backtracking) is a method for solving a problem by traversing the entire search space in search of a solution. During the search we can prune parts of the search space that we are sure do not lead to the required solution. In programming contests, complete search will likely lead to Time Limit Exceeded (TLE), however, it’s a good strategy for small input problems.
Our goal is to place 8 queens on a chess board such that no two queens attack each other. In the most naive solution, we would need to enumerate 64 choose 8 ~ 4B possibilities. A better naive solution is to realize that we can put each queen in a separate column, which leads to 88~17M possibilities. We can do better by placing each queen in a separate column and a separate row that results in 8!~40K valid row permutations. In the implementation below, we assume that each queen occupies a different column, and we compute a valid row number for each of the 8 queens.
#include <cstdlib>#include <cstdio>#include <cstring>using namespace std; //row[8]: row # for each queen//TC: traceback counter//(a, b): 1st queen placement at (r=a, c=b)int row[8], TC, a, b, line_counter; bool place(int r, int c){ // check previously placed queens for (int prev = 0; prev < c; prev++) { // check if same row or same diagonal if (row[prev] == r || (abs(row[prev] — r) == abs(prev — c))) return false; } return true;}void backtrack(int c){ // candidate solution; (a, b) has 1 initial queen if (c == 8 && row[b] == a) { printf(“%2d %d”, ++line_counter, row[0] + 1); for (int j=1; j < 8; j++) {printf(“ %d”, row[j] + 1);} printf(“\n”); } //try all possible rows for (int r = 0; r < 8; r++) { if (place(r, c)) { row[c] = r; // place a queen at this col and row backtrack(c + 1); //increment col and recurse } }}int main() { scanf(“%d”, &TC); while (TC--) { scanf(“%d %d”, &a, &b); a--; b--; //0-based indexing memset(row, 0, sizeof(row)); line_counter = 0; printf(“SOLN COLUMN\n”); printf(“ # 1 2 3 4 5 6 7 8\n\n”); backtrack(0); //generate all possible 8! candidate solutions if (TC) printf(“\n”); } return 0;}
For TC=8 and an initial queen position at (a,b) = (1,1) the above code results in the following output:
SOLN COLUMN # 1 2 3 4 5 6 7 8 1 1 5 8 6 3 7 2 4 2 1 6 8 3 7 4 2 5 3 1 7 4 6 8 2 5 3 4 1 7 5 8 2 4 6 3
which indicates that there are four possible placements given the initial queen position at (r=1,c=1). Notice that the use of recursion allows to more easily prune the search space in comparison to an iterative solution.
A greedy algorithm takes a locally optimum choice at each step with the hope of eventually reaching a globally optimal solution. Greedy algorithms often rely on a greedy heuristic and one can often find examples in which greedy algorithms fail to achieve the global optimum.
A greedy knapsack problem consists of selecting what items to place in a knapsack of limited capacity W so as to maximize the total value of knapsack items, where each item has an associated weight and value. We can define a greedy heuristic to be a ratio of item value to item weight, i.e. we would like to greedily choose items that are simultaneously high value and low weight and sort the items based on this criteria. In the fractional knapsack problem, we are allowed to take fractions of an item (as opposed to 0–1 Knapsack).
#include <iostream>#include <algorithm>using namespace std; struct Item{ int value, weight; Item(int value, int weight) : value(value), weight(weight) {}}; bool cmp(struct Item a, struct Item b){ double r1 = (double) a.value / a.weight; double r2 = (double) b.value / b.weight; return r1 > r2;} double fractional_knapsack(int W, struct Item arr[], int n){ sort(arr, arr + n, cmp); int cur_weight = 0; double tot_value = 0.0; for (int i=0; i < n; ++i) { if (cur_weight + arr[i].weight <= W) { cur_weight += arr[i].weight; tot_value += arr[i].value; } else { //add a fraction of the next item int rem_weight = W — cur_weight; tot_value += arr[i].value * ((double) rem_weight / arr[i].weight); break; } } return tot_value;}int main(){ int W = 50; // total knapsack weight Item arr[] = {{60, 10}, {100, 20}, {120, 30}}; //{value, weight} int n = sizeof(arr) / sizeof(arr[0]); cout << “greedy fractional knapsack” << endl; cout << “maximum value: “ << fractional_knapsack(W, arr, n); cout << endl; return 0;}
Since sorting is the most expensive operation, the algorithm runs in O(n log n) time. Given (value, weight) pairs of three items: {(60, 10), (100, 20), (120, 30)}, and the total capacity W=50, the code above produces the following output:
greedy fractional knapsackmaximum value: 240
We can see that the input items are sorted in decreasing ratio of value / cost, after greedily selecting items 1 and 2, we take a 2/3 fraction of item 3 for a total value of 60+100+(2/3)120 = 240.
Divide and Conquer (D&C) is a technique that divides a problem into smaller, independent sub-problems and then combines solutions to each of the sub-problems.
Examples of divide and conquer technique include sorting algorithms such as quick sort, merge sort and heap sort as well as binary search.
The classic use of binary search is in searching for a value in a sorted array. First, we check the middle of the array to see if if contains what we are looking for. If it does or there are no more items to consider, we stop. Otherwise, we decide whether the answer is to the left or the right of the middle element and continue searching. As the size of the search space is halved after each check, the complexity of the algorithm is O(log n).
#include <algorithm>#include <vector>#include <iostream>using namespace std;int bsearch(const vector<int> &arr, int l, int r, int q){ while (l <= r) { int mid = l + (r-l)/2; if (arr[mid] == q) return mid; if (q < arr[mid]) { r = mid — 1; } else { l = mid + 1; } } return -1; //not found}int main(){ int query = 10; int arr[] = {2, 4, 6, 8, 10, 12}; int N = sizeof(arr)/sizeof(arr[0]); vector<int> v(arr, arr + N); //sort input array sort(v.begin(), v.end()); int idx; idx = bsearch(v, 0, v.size(), query); if (idx != -1) cout << "custom binary_search: found at index " << idx; else cout << "custom binary_search: not found"; return 0;}
The code above produces the following output:
custom binary_search: found at index 4
Note if the query element is not found but we would like to find the first entry not smaller than the query or the first entry greater than the query, we can use STL lower_bound and upper_bound.
Dynamic Programming (DP) is a technique that divides a problem into smaller overlapping sub-problems, computes a solution for each sub-problem and stores it in a DP table. The final solution is read off the DP table.
Key skills in mastering dynamic programming is the ability to determine the problem states (entries of the DP table) and the relationships or transitions between the states. Then, having defined base cases and recursive relationships, one can populate the DP table in a top-down or bottom-up fashion.
In the top-down DP, the table is populated recursively, as needed, starting from the top and going down to smaller sub-problems. In the bottom-up DP, the table is populated iteratively starting from the smallest sub-problems and using their solutions to build-on and arrive at solutions to bigger sub-problems. In both cases, if a sub-problem was already encountered, its solution is simply looked up in the table (as opposed to re-computing the solution from scratch). This dramatically reduces computational cost.
We use binomial coefficients example to illustrate the use of top-down and bottom-up DP. The code below is based on the recursion for binomial coefficients with overlapping sub-problems. Let C(n,k) denote n choose k, then, we have:
Base case: C(n,0) = C(n,n) = 1Recursion: C(n,k) = C(n-1, k-1) + C(n-1, k)
Notice that we have multiple over-lapping sub-problems. E.g. For C(n=5, k=2) the recursion tree is as follows:
C(5, 2) / \ C(4, 1) C(4, 2) / \ / \ C(3, 0) C(3, 1) C(3, 1) C(3, 2) / \ / \ / \ C(2, 0) C(2, 1) C(2, 0) C(2, 1) C(2, 1) C(2, 2) / \ / \ / \ C(1, 0) C(1, 1) C(1, 0) C(1, 1) C(1, 0) C(1, 1)
We can implement top-down and bottom-up DP as follows:
#include <iostream>#include <cstring>using namespace std; #define V 8int memo[V][V]; //DP table int min(int a, int b) {return (a < b) ? a : b;} void print_table(int memo[V][V]){ for (int i = 0; i < V; ++i) { for (int j = 0; j < V; ++j) { printf(" %2d", memo[i][j]); } printf("\n"); }} int binomial_coeffs1(int n, int k){ // top-down DP if (k == 0 || k == n) return 1; if (memo[n][k] != -1) return memo[n][k]; return memo[n][k] = binomial_coeffs1(n-1, k-1) + binomial_coeffs1(n-1, k);}int binomial_coeffs2(int n, int k){ // bottom-up DP for (int i = 0; i <= n; ++i) { for (int j = 0; j <= min(i, k); ++j) { if (j == 0 || j == i) { memo[i][j] = 1; } else { memo[i][j] = memo[i-1][j-1] + memo[i-1][j]; } } } return memo[n][k];} int main(){ int n = 5, k = 2; printf("Top-down DP:\n"); memset(memo, -1, sizeof(memo)); int nCk1 = binomial_coeffs1(n, k); print_table(memo); printf("C(n=%d, k=%d): %d\n", n, k, nCk1); printf("Bottom-up DP:\n"); memset(memo, -1, sizeof(memo)); int nCk2 = binomial_coeffs2(n, k); print_table(memo); printf("C(n=%d, k=%d): %d\n", n, k, nCk2); return 0;}
For C(n=5, k=2), the code above produces the following output:
Top-down DP: -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 2 -1 -1 -1 -1 -1 -1 -1 3 3 -1 -1 -1 -1 -1 -1 4 6 -1 -1 -1 -1 -1 -1 -1 10 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1C(n=5, k=2): 10Bottom-up DP: 1 -1 -1 -1 -1 -1 -1 -1 1 1 -1 -1 -1 -1 -1 -1 1 2 1 -1 -1 -1 -1 -1 1 3 3 -1 -1 -1 -1 -1 1 4 6 -1 -1 -1 -1 -1 1 5 10 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1C(n=5, k=2): 10
The time complexity is O(n * k) and the space complexity is O(n * k). In the case of top-down DP, solutions to sub-problems are stored (memoized) as needed, whereas in the bottom-up DP, the entire table is computed starting from the base case. Note: a small DP table size (V=8) was chosen for printing purposes, a much larger table size is recommended.
All code is available at: https://github.com/vsmolyakov/cpp
To compile C++ code you can run the following command:
>> g++ <filename.cpp> --std=c++11 -Wall -o test>> ./test
There are a number of great resources available for learning algorithms. I highly recommend Steven Halim’s book [1] on competitive programming. In addition to the classic Algorithm Design Manual [2] and CLRS [3]. There are a number of great coding challenge web-sites some of which are mentioned in [4]. In addition, [5] has a fantastic collection of algorithms and easy to understand implementations. A great resource if you are building your own library or participating in programming competitions.
Hope you find this article helpful. Happy coding!!
Steven Halim, “Competitive Programming”, 3rd edition, 2013Steven Skiena, “The Algorithm Design Manual”, Springer, 2011Thomas Cormen et al, “Introduction to Algorithms”, The MIT Press, 2009https://medium.freecodecamp.org/the-10-most-popular-coding-challenge-websites-of-2016-fb8a5672d22fhttps://www.geeksforgeeks.org/
Steven Halim, “Competitive Programming”, 3rd edition, 2013
Steven Skiena, “The Algorithm Design Manual”, Springer, 2011
Thomas Cormen et al, “Introduction to Algorithms”, The MIT Press, 2009
|
[
{
"code": null,
"e": 481,
"s": 172,
"text": "The purpose of this article is to introduce the reader to four main algorithmic paradigms: complete search, greedy algorithms, divide and conquer, and dynamic programming. Many algorithmic problems can be mapped into one of these four categories and the mastery of each one will make you a better programmer."
},
{
"code": null,
"e": 685,
"s": 481,
"text": "This article is written from the perspective of competitive programming. In the reference section, you’ll find resources to get you started or improve your programming skills through coding competitions."
},
{
"code": null,
"e": 1098,
"s": 685,
"text": "Complete search (aka brute force or recursive backtracking) is a method for solving a problem by traversing the entire search space in search of a solution. During the search we can prune parts of the search space that we are sure do not lead to the required solution. In programming contests, complete search will likely lead to Time Limit Exceeded (TLE), however, it’s a good strategy for small input problems."
},
{
"code": null,
"e": 1669,
"s": 1098,
"text": "Our goal is to place 8 queens on a chess board such that no two queens attack each other. In the most naive solution, we would need to enumerate 64 choose 8 ~ 4B possibilities. A better naive solution is to realize that we can put each queen in a separate column, which leads to 88~17M possibilities. We can do better by placing each queen in a separate column and a separate row that results in 8!~40K valid row permutations. In the implementation below, we assume that each queen occupies a different column, and we compute a valid row number for each of the 8 queens."
},
{
"code": null,
"e": 3013,
"s": 1669,
"text": "#include <cstdlib>#include <cstdio>#include <cstring>using namespace std; //row[8]: row # for each queen//TC: traceback counter//(a, b): 1st queen placement at (r=a, c=b)int row[8], TC, a, b, line_counter; bool place(int r, int c){ // check previously placed queens for (int prev = 0; prev < c; prev++) { // check if same row or same diagonal if (row[prev] == r || (abs(row[prev] — r) == abs(prev — c))) return false; } return true;}void backtrack(int c){ // candidate solution; (a, b) has 1 initial queen if (c == 8 && row[b] == a) { printf(“%2d %d”, ++line_counter, row[0] + 1); for (int j=1; j < 8; j++) {printf(“ %d”, row[j] + 1);} printf(“\\n”); } //try all possible rows for (int r = 0; r < 8; r++) { if (place(r, c)) { row[c] = r; // place a queen at this col and row backtrack(c + 1); //increment col and recurse } }}int main() { scanf(“%d”, &TC); while (TC--) { scanf(“%d %d”, &a, &b); a--; b--; //0-based indexing memset(row, 0, sizeof(row)); line_counter = 0; printf(“SOLN COLUMN\\n”); printf(“ # 1 2 3 4 5 6 7 8\\n\\n”); backtrack(0); //generate all possible 8! candidate solutions if (TC) printf(“\\n”); } return 0;}"
},
{
"code": null,
"e": 3117,
"s": 3013,
"text": "For TC=8 and an initial queen position at (a,b) = (1,1) the above code results in the following output:"
},
{
"code": null,
"e": 3240,
"s": 3117,
"text": "SOLN COLUMN # 1 2 3 4 5 6 7 8 1 1 5 8 6 3 7 2 4 2 1 6 8 3 7 4 2 5 3 1 7 4 6 8 2 5 3 4 1 7 5 8 2 4 6 3"
},
{
"code": null,
"e": 3461,
"s": 3240,
"text": "which indicates that there are four possible placements given the initial queen position at (r=1,c=1). Notice that the use of recursion allows to more easily prune the search space in comparison to an iterative solution."
},
{
"code": null,
"e": 3736,
"s": 3461,
"text": "A greedy algorithm takes a locally optimum choice at each step with the hope of eventually reaching a globally optimal solution. Greedy algorithms often rely on a greedy heuristic and one can often find examples in which greedy algorithms fail to achieve the global optimum."
},
{
"code": null,
"e": 4269,
"s": 3736,
"text": "A greedy knapsack problem consists of selecting what items to place in a knapsack of limited capacity W so as to maximize the total value of knapsack items, where each item has an associated weight and value. We can define a greedy heuristic to be a ratio of item value to item weight, i.e. we would like to greedily choose items that are simultaneously high value and low weight and sort the items based on this criteria. In the fractional knapsack problem, we are allowed to take fractions of an item (as opposed to 0–1 Knapsack)."
},
{
"code": null,
"e": 5487,
"s": 4269,
"text": "#include <iostream>#include <algorithm>using namespace std; struct Item{ int value, weight; Item(int value, int weight) : value(value), weight(weight) {}}; bool cmp(struct Item a, struct Item b){ double r1 = (double) a.value / a.weight; double r2 = (double) b.value / b.weight; return r1 > r2;} double fractional_knapsack(int W, struct Item arr[], int n){ sort(arr, arr + n, cmp); int cur_weight = 0; double tot_value = 0.0; for (int i=0; i < n; ++i) { if (cur_weight + arr[i].weight <= W) { cur_weight += arr[i].weight; tot_value += arr[i].value; } else { //add a fraction of the next item int rem_weight = W — cur_weight; tot_value += arr[i].value * ((double) rem_weight / arr[i].weight); break; } } return tot_value;}int main(){ int W = 50; // total knapsack weight Item arr[] = {{60, 10}, {100, 20}, {120, 30}}; //{value, weight} int n = sizeof(arr) / sizeof(arr[0]); cout << “greedy fractional knapsack” << endl; cout << “maximum value: “ << fractional_knapsack(W, arr, n); cout << endl; return 0;}"
},
{
"code": null,
"e": 5726,
"s": 5487,
"text": "Since sorting is the most expensive operation, the algorithm runs in O(n log n) time. Given (value, weight) pairs of three items: {(60, 10), (100, 20), (120, 30)}, and the total capacity W=50, the code above produces the following output:"
},
{
"code": null,
"e": 5771,
"s": 5726,
"text": "greedy fractional knapsackmaximum value: 240"
},
{
"code": null,
"e": 5968,
"s": 5771,
"text": "We can see that the input items are sorted in decreasing ratio of value / cost, after greedily selecting items 1 and 2, we take a 2/3 fraction of item 3 for a total value of 60+100+(2/3)120 = 240."
},
{
"code": null,
"e": 6127,
"s": 5968,
"text": "Divide and Conquer (D&C) is a technique that divides a problem into smaller, independent sub-problems and then combines solutions to each of the sub-problems."
},
{
"code": null,
"e": 6266,
"s": 6127,
"text": "Examples of divide and conquer technique include sorting algorithms such as quick sort, merge sort and heap sort as well as binary search."
},
{
"code": null,
"e": 6712,
"s": 6266,
"text": "The classic use of binary search is in searching for a value in a sorted array. First, we check the middle of the array to see if if contains what we are looking for. If it does or there are no more items to consider, we stop. Otherwise, we decide whether the answer is to the left or the right of the middle element and continue searching. As the size of the search space is halved after each check, the complexity of the algorithm is O(log n)."
},
{
"code": null,
"e": 7471,
"s": 6712,
"text": "#include <algorithm>#include <vector>#include <iostream>using namespace std;int bsearch(const vector<int> &arr, int l, int r, int q){ while (l <= r) { int mid = l + (r-l)/2; if (arr[mid] == q) return mid; if (q < arr[mid]) { r = mid — 1; } else { l = mid + 1; } } return -1; //not found}int main(){ int query = 10; int arr[] = {2, 4, 6, 8, 10, 12}; int N = sizeof(arr)/sizeof(arr[0]); vector<int> v(arr, arr + N); //sort input array sort(v.begin(), v.end()); int idx; idx = bsearch(v, 0, v.size(), query); if (idx != -1) cout << \"custom binary_search: found at index \" << idx; else cout << \"custom binary_search: not found\"; return 0;}"
},
{
"code": null,
"e": 7517,
"s": 7471,
"text": "The code above produces the following output:"
},
{
"code": null,
"e": 7556,
"s": 7517,
"text": "custom binary_search: found at index 4"
},
{
"code": null,
"e": 7751,
"s": 7556,
"text": "Note if the query element is not found but we would like to find the first entry not smaller than the query or the first entry greater than the query, we can use STL lower_bound and upper_bound."
},
{
"code": null,
"e": 7968,
"s": 7751,
"text": "Dynamic Programming (DP) is a technique that divides a problem into smaller overlapping sub-problems, computes a solution for each sub-problem and stores it in a DP table. The final solution is read off the DP table."
},
{
"code": null,
"e": 8269,
"s": 7968,
"text": "Key skills in mastering dynamic programming is the ability to determine the problem states (entries of the DP table) and the relationships or transitions between the states. Then, having defined base cases and recursive relationships, one can populate the DP table in a top-down or bottom-up fashion."
},
{
"code": null,
"e": 8785,
"s": 8269,
"text": "In the top-down DP, the table is populated recursively, as needed, starting from the top and going down to smaller sub-problems. In the bottom-up DP, the table is populated iteratively starting from the smallest sub-problems and using their solutions to build-on and arrive at solutions to bigger sub-problems. In both cases, if a sub-problem was already encountered, its solution is simply looked up in the table (as opposed to re-computing the solution from scratch). This dramatically reduces computational cost."
},
{
"code": null,
"e": 9017,
"s": 8785,
"text": "We use binomial coefficients example to illustrate the use of top-down and bottom-up DP. The code below is based on the recursion for binomial coefficients with overlapping sub-problems. Let C(n,k) denote n choose k, then, we have:"
},
{
"code": null,
"e": 9091,
"s": 9017,
"text": "Base case: C(n,0) = C(n,n) = 1Recursion: C(n,k) = C(n-1, k-1) + C(n-1, k)"
},
{
"code": null,
"e": 9202,
"s": 9091,
"text": "Notice that we have multiple over-lapping sub-problems. E.g. For C(n=5, k=2) the recursion tree is as follows:"
},
{
"code": null,
"e": 9722,
"s": 9202,
"text": " C(5, 2) / \\ C(4, 1) C(4, 2) / \\ / \\ C(3, 0) C(3, 1) C(3, 1) C(3, 2) / \\ / \\ / \\ C(2, 0) C(2, 1) C(2, 0) C(2, 1) C(2, 1) C(2, 2) / \\ / \\ / \\ C(1, 0) C(1, 1) C(1, 0) C(1, 1) C(1, 0) C(1, 1)"
},
{
"code": null,
"e": 9777,
"s": 9722,
"text": "We can implement top-down and bottom-up DP as follows:"
},
{
"code": null,
"e": 11197,
"s": 9777,
"text": "#include <iostream>#include <cstring>using namespace std; #define V 8int memo[V][V]; //DP table int min(int a, int b) {return (a < b) ? a : b;} void print_table(int memo[V][V]){ for (int i = 0; i < V; ++i) { for (int j = 0; j < V; ++j) { printf(\" %2d\", memo[i][j]); } printf(\"\\n\"); }} int binomial_coeffs1(int n, int k){ // top-down DP if (k == 0 || k == n) return 1; if (memo[n][k] != -1) return memo[n][k]; return memo[n][k] = binomial_coeffs1(n-1, k-1) + binomial_coeffs1(n-1, k);}int binomial_coeffs2(int n, int k){ // bottom-up DP for (int i = 0; i <= n; ++i) { for (int j = 0; j <= min(i, k); ++j) { if (j == 0 || j == i) { memo[i][j] = 1; } else { memo[i][j] = memo[i-1][j-1] + memo[i-1][j]; } } } return memo[n][k];} int main(){ int n = 5, k = 2; printf(\"Top-down DP:\\n\"); memset(memo, -1, sizeof(memo)); int nCk1 = binomial_coeffs1(n, k); print_table(memo); printf(\"C(n=%d, k=%d): %d\\n\", n, k, nCk1); printf(\"Bottom-up DP:\\n\"); memset(memo, -1, sizeof(memo)); int nCk2 = binomial_coeffs2(n, k); print_table(memo); printf(\"C(n=%d, k=%d): %d\\n\", n, k, nCk2); return 0;}"
},
{
"code": null,
"e": 11260,
"s": 11197,
"text": "For C(n=5, k=2), the code above produces the following output:"
},
{
"code": null,
"e": 11700,
"s": 11260,
"text": "Top-down DP: -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 2 -1 -1 -1 -1 -1 -1 -1 3 3 -1 -1 -1 -1 -1 -1 4 6 -1 -1 -1 -1 -1 -1 -1 10 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1C(n=5, k=2): 10Bottom-up DP: 1 -1 -1 -1 -1 -1 -1 -1 1 1 -1 -1 -1 -1 -1 -1 1 2 1 -1 -1 -1 -1 -1 1 3 3 -1 -1 -1 -1 -1 1 4 6 -1 -1 -1 -1 -1 1 5 10 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1C(n=5, k=2): 10"
},
{
"code": null,
"e": 12053,
"s": 11700,
"text": "The time complexity is O(n * k) and the space complexity is O(n * k). In the case of top-down DP, solutions to sub-problems are stored (memoized) as needed, whereas in the bottom-up DP, the entire table is computed starting from the base case. Note: a small DP table size (V=8) was chosen for printing purposes, a much larger table size is recommended."
},
{
"code": null,
"e": 12113,
"s": 12053,
"text": "All code is available at: https://github.com/vsmolyakov/cpp"
},
{
"code": null,
"e": 12168,
"s": 12113,
"text": "To compile C++ code you can run the following command:"
},
{
"code": null,
"e": 12225,
"s": 12168,
"text": ">> g++ <filename.cpp> --std=c++11 -Wall -o test>> ./test"
},
{
"code": null,
"e": 12727,
"s": 12225,
"text": "There are a number of great resources available for learning algorithms. I highly recommend Steven Halim’s book [1] on competitive programming. In addition to the classic Algorithm Design Manual [2] and CLRS [3]. There are a number of great coding challenge web-sites some of which are mentioned in [4]. In addition, [5] has a fantastic collection of algorithms and easy to understand implementations. A great resource if you are building your own library or participating in programming competitions."
},
{
"code": null,
"e": 12778,
"s": 12727,
"text": "Hope you find this article helpful. Happy coding!!"
},
{
"code": null,
"e": 13095,
"s": 12778,
"text": "Steven Halim, “Competitive Programming”, 3rd edition, 2013Steven Skiena, “The Algorithm Design Manual”, Springer, 2011Thomas Cormen et al, “Introduction to Algorithms”, The MIT Press, 2009https://medium.freecodecamp.org/the-10-most-popular-coding-challenge-websites-of-2016-fb8a5672d22fhttps://www.geeksforgeeks.org/"
},
{
"code": null,
"e": 13154,
"s": 13095,
"text": "Steven Halim, “Competitive Programming”, 3rd edition, 2013"
},
{
"code": null,
"e": 13215,
"s": 13154,
"text": "Steven Skiena, “The Algorithm Design Manual”, Springer, 2011"
}
] |
AVRO - Schemas
|
Avro, being a schema-based serialization utility, accepts schemas as input. In spite of various schemas being available, Avro follows its own standards of defining schemas. These schemas describe the following details −
type of file (record by default)
location of record
name of the record
fields in the record with their corresponding data types
Using these schemas, you can store serialized values in binary format using less space. These values are stored without any metadata.
The Avro schema is created in JavaScript Object Notation (JSON) document format, which is a lightweight text-based data interchange format. It is created in one of the following ways −
A JSON string
A JSON object
A JSON array
Example − The following example shows a schema, which defines a document, under the name space Tutorialspoint, with name Employee, having fields name and age.
{
"type" : "record",
"namespace" : "Tutorialspoint",
"name" : "Employee",
"fields" : [
{ "name" : "Name" , "type" : "string" },
{ "name" : "Age" , "type" : "int" }
]
}
In this example, you can observe that there are four fields for each record −
type − This field comes under the document as well as the under the field named fields.
In case of document, it shows the type of the document, generally a record because there are multiple fields.
When it is field, the type describes data type.
type − This field comes under the document as well as the under the field named fields.
In case of document, it shows the type of the document, generally a record because there are multiple fields.
In case of document, it shows the type of the document, generally a record because there are multiple fields.
When it is field, the type describes data type.
When it is field, the type describes data type.
namespace − This field describes the name of the namespace in which the object resides.
namespace − This field describes the name of the namespace in which the object resides.
name − This field comes under the document as well as the under the field named fields.
In case of document, it describes the schema name. This schema name together with the namespace, uniquely identifies the schema within the store (Namespace.schema name). In the above example, the full name of the schema will be Tutorialspoint.Employee.
In case of fields, it describes name of the field.
name − This field comes under the document as well as the under the field named fields.
In case of document, it describes the schema name. This schema name together with the namespace, uniquely identifies the schema within the store (Namespace.schema name). In the above example, the full name of the schema will be Tutorialspoint.Employee.
In case of document, it describes the schema name. This schema name together with the namespace, uniquely identifies the schema within the store (Namespace.schema name). In the above example, the full name of the schema will be Tutorialspoint.Employee.
In case of fields, it describes name of the field.
In case of fields, it describes name of the field.
Avro schema is having primitive data types as well as complex data types. The following table describes the primitive data types of Avro −
Along with primitive data types, Avro provides six complex data types namely Records, Enums, Arrays, Maps, Unions, and Fixed.
A record data type in Avro is a collection of multiple attributes. It supports the following
attributes −
name − The value of this field holds the name of the record.
name − The value of this field holds the name of the record.
namespace − The value of this field holds the name of the namespace where the
object is stored.
namespace − The value of this field holds the name of the namespace where the
object is stored.
type − The value of this attribute holds either the type of the document (record) or the datatype of the field in the schema.
type − The value of this attribute holds either the type of the document (record) or the datatype of the field in the schema.
fields − This field holds a JSON array, which have the list of all of the fields in the schema, each having name and the type attributes.
fields − This field holds a JSON array, which have the list of all of the fields in the schema, each having name and the type attributes.
Example
Given below is the example of a record.
{
" type " : "record",
" namespace " : "Tutorialspoint",
" name " : "Employee",
" fields " : [
{ "name" : " Name" , "type" : "string" },
{ "name" : "age" , "type" : "int" }
]
}
An enumeration is a list of items in a collection, Avro enumeration supports the following attributes −
name − The value of this field holds the name of the enumeration.
name − The value of this field holds the name of the enumeration.
namespace − The value of this field contains the string that qualifies the name of the Enumeration.
namespace − The value of this field contains the string that qualifies the name of the Enumeration.
symbols − The value of this field holds the enum's symbols as an array of names.
symbols − The value of this field holds the enum's symbols as an array of names.
Example
Given below is the example of an enumeration.
{
"type" : "enum",
"name" : "Numbers",
"namespace": "data",
"symbols" : [ "ONE", "TWO", "THREE", "FOUR" ]
}
This data type defines an array field having a single attribute items. This items attribute specifies the type of items in the array.
Example
{ " type " : " array ", " items " : " int " }
The map data type is an array of key-value pairs, it organizes data as key-value pairs. The
key for an Avro map must be a string. The values of a map hold the data type of the content of map.
Example
{"type" : "map", "values" : "int"}
A union datatype is used whenever the field has one or more datatypes. They are represented as JSON arrays. For example, if a field that could be either an int or null, then the union is represented as ["int", "null"].
Example
Given below is an example document using unions −
{
"type" : "record",
"namespace" : "tutorialspoint",
"name" : "empdetails ",
"fields" :
[
{ "name" : "experience", "type": ["int", "null"] }, { "name" : "age", "type": "int" }
]
}
This data type is used to declare a fixed-sized field that can be used for storing binary data. It has field name and data as attributes. Name holds the name of the field, and size holds the size of the field.
Example
{ "type" : "fixed" , "name" : "bdata", "size" : 1048576}
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2081,
"s": 1861,
"text": "Avro, being a schema-based serialization utility, accepts schemas as input. In spite of various schemas being available, Avro follows its own standards of defining schemas. These schemas describe the following details −"
},
{
"code": null,
"e": 2114,
"s": 2081,
"text": "type of file (record by default)"
},
{
"code": null,
"e": 2133,
"s": 2114,
"text": "location of record"
},
{
"code": null,
"e": 2152,
"s": 2133,
"text": "name of the record"
},
{
"code": null,
"e": 2209,
"s": 2152,
"text": "fields in the record with their corresponding data types"
},
{
"code": null,
"e": 2343,
"s": 2209,
"text": "Using these schemas, you can store serialized values in binary format using less space. These values are stored without any metadata."
},
{
"code": null,
"e": 2528,
"s": 2343,
"text": "The Avro schema is created in JavaScript Object Notation (JSON) document format, which is a lightweight text-based data interchange format. It is created in one of the following ways −"
},
{
"code": null,
"e": 2542,
"s": 2528,
"text": "A JSON string"
},
{
"code": null,
"e": 2556,
"s": 2542,
"text": "A JSON object"
},
{
"code": null,
"e": 2569,
"s": 2556,
"text": "A JSON array"
},
{
"code": null,
"e": 2728,
"s": 2569,
"text": "Example − The following example shows a schema, which defines a document, under the name space Tutorialspoint, with name Employee, having fields name and age."
},
{
"code": null,
"e": 2924,
"s": 2728,
"text": "{\n \"type\" : \"record\",\n \"namespace\" : \"Tutorialspoint\",\n \"name\" : \"Employee\",\n \"fields\" : [\n { \"name\" : \"Name\" , \"type\" : \"string\" },\n { \"name\" : \"Age\" , \"type\" : \"int\" }\n ]\n}\n"
},
{
"code": null,
"e": 3002,
"s": 2924,
"text": "In this example, you can observe that there are four fields for each record −"
},
{
"code": null,
"e": 3251,
"s": 3002,
"text": "type − This field comes under the document as well as the under the field named fields.\n\nIn case of document, it shows the type of the document, generally a record because there are multiple fields.\nWhen it is field, the type describes data type. \n"
},
{
"code": null,
"e": 3339,
"s": 3251,
"text": "type − This field comes under the document as well as the under the field named fields."
},
{
"code": null,
"e": 3449,
"s": 3339,
"text": "In case of document, it shows the type of the document, generally a record because there are multiple fields."
},
{
"code": null,
"e": 3559,
"s": 3449,
"text": "In case of document, it shows the type of the document, generally a record because there are multiple fields."
},
{
"code": null,
"e": 3608,
"s": 3559,
"text": "When it is field, the type describes data type. "
},
{
"code": null,
"e": 3657,
"s": 3608,
"text": "When it is field, the type describes data type. "
},
{
"code": null,
"e": 3745,
"s": 3657,
"text": "namespace − This field describes the name of the namespace in which the object resides."
},
{
"code": null,
"e": 3833,
"s": 3745,
"text": "namespace − This field describes the name of the namespace in which the object resides."
},
{
"code": null,
"e": 4227,
"s": 3833,
"text": "name − This field comes under the document as well as the under the field named fields.\n\nIn case of document, it describes the schema name. This schema name together with the namespace, uniquely identifies the schema within the store (Namespace.schema name). In the above example, the full name of the schema will be Tutorialspoint.Employee.\nIn case of fields, it describes name of the field.\n"
},
{
"code": null,
"e": 4315,
"s": 4227,
"text": "name − This field comes under the document as well as the under the field named fields."
},
{
"code": null,
"e": 4568,
"s": 4315,
"text": "In case of document, it describes the schema name. This schema name together with the namespace, uniquely identifies the schema within the store (Namespace.schema name). In the above example, the full name of the schema will be Tutorialspoint.Employee."
},
{
"code": null,
"e": 4821,
"s": 4568,
"text": "In case of document, it describes the schema name. This schema name together with the namespace, uniquely identifies the schema within the store (Namespace.schema name). In the above example, the full name of the schema will be Tutorialspoint.Employee."
},
{
"code": null,
"e": 4872,
"s": 4821,
"text": "In case of fields, it describes name of the field."
},
{
"code": null,
"e": 4923,
"s": 4872,
"text": "In case of fields, it describes name of the field."
},
{
"code": null,
"e": 5062,
"s": 4923,
"text": "Avro schema is having primitive data types as well as complex data types. The following table describes the primitive data types of Avro −"
},
{
"code": null,
"e": 5188,
"s": 5062,
"text": "Along with primitive data types, Avro provides six complex data types namely Records, Enums, Arrays, Maps, Unions, and Fixed."
},
{
"code": null,
"e": 5294,
"s": 5188,
"text": "A record data type in Avro is a collection of multiple attributes. It supports the following\nattributes −"
},
{
"code": null,
"e": 5355,
"s": 5294,
"text": "name − The value of this field holds the name of the record."
},
{
"code": null,
"e": 5416,
"s": 5355,
"text": "name − The value of this field holds the name of the record."
},
{
"code": null,
"e": 5512,
"s": 5416,
"text": "namespace − The value of this field holds the name of the namespace where the\nobject is stored."
},
{
"code": null,
"e": 5608,
"s": 5512,
"text": "namespace − The value of this field holds the name of the namespace where the\nobject is stored."
},
{
"code": null,
"e": 5734,
"s": 5608,
"text": "type − The value of this attribute holds either the type of the document (record) or the datatype of the field in the schema."
},
{
"code": null,
"e": 5860,
"s": 5734,
"text": "type − The value of this attribute holds either the type of the document (record) or the datatype of the field in the schema."
},
{
"code": null,
"e": 5998,
"s": 5860,
"text": "fields − This field holds a JSON array, which have the list of all of the fields in the schema, each having name and the type attributes."
},
{
"code": null,
"e": 6136,
"s": 5998,
"text": "fields − This field holds a JSON array, which have the list of all of the fields in the schema, each having name and the type attributes."
},
{
"code": null,
"e": 6144,
"s": 6136,
"text": "Example"
},
{
"code": null,
"e": 6184,
"s": 6144,
"text": "Given below is the example of a record."
},
{
"code": null,
"e": 6365,
"s": 6184,
"text": "{\n\" type \" : \"record\",\n\" namespace \" : \"Tutorialspoint\",\n\" name \" : \"Employee\",\n\" fields \" : [\n { \"name\" : \" Name\" , \"type\" : \"string\" },\n { \"name\" : \"age\" , \"type\" : \"int\" }\n ]\n}\n"
},
{
"code": null,
"e": 6469,
"s": 6365,
"text": "An enumeration is a list of items in a collection, Avro enumeration supports the following attributes −"
},
{
"code": null,
"e": 6535,
"s": 6469,
"text": "name − The value of this field holds the name of the enumeration."
},
{
"code": null,
"e": 6601,
"s": 6535,
"text": "name − The value of this field holds the name of the enumeration."
},
{
"code": null,
"e": 6701,
"s": 6601,
"text": "namespace − The value of this field contains the string that qualifies the name of the Enumeration."
},
{
"code": null,
"e": 6801,
"s": 6701,
"text": "namespace − The value of this field contains the string that qualifies the name of the Enumeration."
},
{
"code": null,
"e": 6882,
"s": 6801,
"text": "symbols − The value of this field holds the enum's symbols as an array of names."
},
{
"code": null,
"e": 6963,
"s": 6882,
"text": "symbols − The value of this field holds the enum's symbols as an array of names."
},
{
"code": null,
"e": 6971,
"s": 6963,
"text": "Example"
},
{
"code": null,
"e": 7017,
"s": 6971,
"text": "Given below is the example of an enumeration."
},
{
"code": null,
"e": 7140,
"s": 7017,
"text": "{\n \"type\" : \"enum\",\n \"name\" : \"Numbers\", \n \"namespace\": \"data\", \n \"symbols\" : [ \"ONE\", \"TWO\", \"THREE\", \"FOUR\" ]\n}\n"
},
{
"code": null,
"e": 7274,
"s": 7140,
"text": "This data type defines an array field having a single attribute items. This items attribute specifies the type of items in the array."
},
{
"code": null,
"e": 7282,
"s": 7274,
"text": "Example"
},
{
"code": null,
"e": 7329,
"s": 7282,
"text": "{ \" type \" : \" array \", \" items \" : \" int \" }\n"
},
{
"code": null,
"e": 7521,
"s": 7329,
"text": "The map data type is an array of key-value pairs, it organizes data as key-value pairs. The\nkey for an Avro map must be a string. The values of a map hold the data type of the content of map."
},
{
"code": null,
"e": 7529,
"s": 7521,
"text": "Example"
},
{
"code": null,
"e": 7565,
"s": 7529,
"text": "{\"type\" : \"map\", \"values\" : \"int\"}\n"
},
{
"code": null,
"e": 7784,
"s": 7565,
"text": "A union datatype is used whenever the field has one or more datatypes. They are represented as JSON arrays. For example, if a field that could be either an int or null, then the union is represented as [\"int\", \"null\"]."
},
{
"code": null,
"e": 7792,
"s": 7784,
"text": "Example"
},
{
"code": null,
"e": 7842,
"s": 7792,
"text": "Given below is an example document using unions −"
},
{
"code": null,
"e": 8055,
"s": 7842,
"text": "{ \n \"type\" : \"record\", \n \"namespace\" : \"tutorialspoint\", \n \"name\" : \"empdetails \", \n \"fields\" : \n [ \n { \"name\" : \"experience\", \"type\": [\"int\", \"null\"] }, { \"name\" : \"age\", \"type\": \"int\" } \n ] \n}\n"
},
{
"code": null,
"e": 8265,
"s": 8055,
"text": "This data type is used to declare a fixed-sized field that can be used for storing binary data. It has field name and data as attributes. Name holds the name of the field, and size holds the size of the field."
},
{
"code": null,
"e": 8273,
"s": 8265,
"text": "Example"
},
{
"code": null,
"e": 8331,
"s": 8273,
"text": "{ \"type\" : \"fixed\" , \"name\" : \"bdata\", \"size\" : 1048576}\n"
},
{
"code": null,
"e": 8338,
"s": 8331,
"text": " Print"
},
{
"code": null,
"e": 8349,
"s": 8338,
"text": " Add Notes"
}
] |
What is the difference between attributes and properties in python?
|
In python, everything is an object. And every object has attributes and methods or functions. Attributes are described by data variables for example like name, age, height etc.
Properties are special kind of attributes which have getter, setter and delete methods like __get__, __set__ and __delete__ methods.
However, there is a property decorator in Python which provides getter/setter access to an attribute Properties are a special kind of attributes. Basically, when Python encounters the following code:
foo = SomeObject()
print(foo.bar)
it looks up bar in foo, and then examines bar to see if it has a __get__, __set__, or __delete__ method and if it does, it's a property. If it is a property, instead of just returning the bar object, it will call the __get__ method and return whatever that method returns.
In Python, you can define getters, setters, and delete methods with the property function. If you just want the read property, there is also a @property decorator you can add above your method.
class C(object):
def __init__(self):
self._x = None
#C._x is an attribute
@property
def x(self):
"""I'm the 'x' property."""
return self._x
# C._x is a property This is the getter method
@x.setter # This is the setter method
def x(self, value):
self._x = value
@x.deleter # This is the delete method
def x(self):
del self._x
|
[
{
"code": null,
"e": 1239,
"s": 1062,
"text": "In python, everything is an object. And every object has attributes and methods or functions. Attributes are described by data variables for example like name, age, height etc."
},
{
"code": null,
"e": 1372,
"s": 1239,
"text": "Properties are special kind of attributes which have getter, setter and delete methods like __get__, __set__ and __delete__ methods."
},
{
"code": null,
"e": 1572,
"s": 1372,
"text": "However, there is a property decorator in Python which provides getter/setter access to an attribute Properties are a special kind of attributes. Basically, when Python encounters the following code:"
},
{
"code": null,
"e": 1606,
"s": 1572,
"text": "foo = SomeObject()\nprint(foo.bar)"
},
{
"code": null,
"e": 1879,
"s": 1606,
"text": "it looks up bar in foo, and then examines bar to see if it has a __get__, __set__, or __delete__ method and if it does, it's a property. If it is a property, instead of just returning the bar object, it will call the __get__ method and return whatever that method returns."
},
{
"code": null,
"e": 2073,
"s": 1879,
"text": "In Python, you can define getters, setters, and delete methods with the property function. If you just want the read property, there is also a @property decorator you can add above your method."
},
{
"code": null,
"e": 2456,
"s": 2073,
"text": "class C(object):\n def __init__(self):\n self._x = None\n#C._x is an attribute\n@property\n def x(self):\n \"\"\"I'm the 'x' property.\"\"\"\n return self._x\n# C._x is a property This is the getter method\n@x.setter # This is the setter method\n def x(self, value):\n self._x = value\n@x.deleter # This is the delete method\n def x(self):\n del self._x"
}
] |
How to pass Arrays to Methods in Java?
|
You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the method will affect the array.
Suppose we have two methods min() and max() which accepts an array and these methods calculates the minimum and maximum values of the given array respectively:
Live Demo
import java.util.Scanner;
public class ArraysToMethod {
public int max(int [] array) {
int max = 0;
for(int i=0; i<array.length; i++ ) {
if(array[i]>max) {
max = array[i];
}
}
return max;
}
public int min(int [] array) {
int min = array[0];
for(int i = 0; i<array.length; i++ ) {
if(array[i]<min) {
min = array[i];
}
}
return min;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created::");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array ::");
for(int i=0; i<size; i++) {
myArray[i] = sc.nextInt();
}
ArraysToMethod m = new ArraysToMethod();
System.out.println("Maximum value in the array is::"+m.max(myArray));
System.out.println("Minimum value in the array is::"+m.min(myArray));
}
}
Enter the size of the array that is to be created ::
5
Enter the elements of the array ::
45
12
48
53
55
Maximum value in the array is ::55
Minimum value in the array is ::12
|
[
{
"code": null,
"e": 1317,
"s": 1062,
"text": "You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the method will affect the array."
},
{
"code": null,
"e": 1477,
"s": 1317,
"text": "Suppose we have two methods min() and max() which accepts an array and these methods calculates the minimum and maximum values of the given array respectively:"
},
{
"code": null,
"e": 1488,
"s": 1477,
"text": " Live Demo"
},
{
"code": null,
"e": 2534,
"s": 1488,
"text": "import java.util.Scanner;\n\npublic class ArraysToMethod {\n public int max(int [] array) {\n int max = 0;\n\n for(int i=0; i<array.length; i++ ) {\n if(array[i]>max) {\n max = array[i];\n }\n }\n return max;\n }\n\n public int min(int [] array) {\n int min = array[0];\n \n for(int i = 0; i<array.length; i++ ) {\n if(array[i]<min) {\n min = array[i];\n }\n }\n return min;\n }\n\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the size of the array that is to be created::\");\n int size = sc.nextInt();\n int[] myArray = new int[size];\n System.out.println(\"Enter the elements of the array ::\");\n\n for(int i=0; i<size; i++) {\n myArray[i] = sc.nextInt();\n }\n ArraysToMethod m = new ArraysToMethod();\n System.out.println(\"Maximum value in the array is::\"+m.max(myArray));\n System.out.println(\"Minimum value in the array is::\"+m.min(myArray));\n }\n}"
},
{
"code": null,
"e": 2709,
"s": 2534,
"text": "Enter the size of the array that is to be created ::\n5\nEnter the elements of the array ::\n45\n12\n48\n53\n55\nMaximum value in the array is ::55\nMinimum value in the array is ::12"
}
] |
Find the longest substring with k unique characters in a given string - GeeksforGeeks
|
12 Dec, 2021
Given a string you need to print longest possible substring that has exactly M unique characters. If there are more than one substring of longest possible length, then print any one of them.
Examples:
"aabbcc", k = 1
Max substring can be any one from {"aa" , "bb" , "cc"}.
"aabbcc", k = 2
Max substring can be any one from {"aabb" , "bbcc"}.
"aabbcc", k = 3
There are substrings with exactly 3 unique characters
{"aabbcc" , "abbcc" , "aabbc" , "abbc" }
Max is "aabbcc" with length 6.
"aaabbb", k = 3
There are only two unique characters, thus show error message.
Source: Google Interview Question.
Method 1 (Brute Force) If the length of string is n, then there can be n*(n+1)/2 possible substrings. A simple way is to generate all the substring and check each one whether it has exactly k unique characters or not. If we apply this brute force, it would take O(n2) to generate all substrings and O(n) to do a check on each one. Thus overall it would go O(n3).We can further improve this solution by creating a hash table and while generating the substrings, check the number of unique characters using that hash table. Thus it would improve up to O(n2).
Method 2 (Linear Time) The problem can be solved in O(n). Idea is to maintain a window and add elements to the window till it contains less or equal k, update our result if required while doing so. If unique elements exceeds than required in window, start removing the elements from left side. Below are the implementations of above. The implementations assume that the input string alphabet contains only 26 characters (from ‘a’ to ‘z’). The code can be easily extended to 256 characters.
C++
Java
Python3
C#
Javascript
// C++ program to find the longest substring with k unique// characters in a given string#include <iostream>#include <cstring>#define MAX_CHARS 26using namespace std; // This function calculates number of unique characters// using a associative array count[]. Returns true if// no. of characters are less than required else returns// false.bool isValid(int count[], int k){ int val = 0; for (int i=0; i<MAX_CHARS; i++) if (count[i] > 0) val++; // Return true if k is greater than or equal to val return (k >= val);} // Finds the maximum substring with exactly k unique charsvoid kUniques(string s, int k){ int u = 0; // number of unique characters int n = s.length(); // Associative array to store the count of characters int count[MAX_CHARS]; memset(count, 0, sizeof(count)); // Traverse the string, Fills the associative array // count[] and count number of unique characters for (int i=0; i<n; i++) { if (count[s[i]-'a']==0) u++; count[s[i]-'a']++; } // If there are not enough unique characters, show // an error message. if (u < k) { cout << "Not enough unique characters"; return; } // Otherwise take a window with first element in it. // start and end variables. int curr_start = 0, curr_end = 0; // Also initialize values for result longest window int max_window_size = 1, max_window_start = 0; // Initialize associative array count[] with zero memset(count, 0, sizeof(count)); count[s[0]-'a']++; // put the first character // Start from the second character and add // characters in window according to above // explanation for (int i=1; i<n; i++) { // Add the character 's[i]' to current window count[s[i]-'a']++; curr_end++; // If there are more than k unique characters in // current window, remove from left side while (!isValid(count, k)) { count[s[curr_start]-'a']--; curr_start++; } // Update the max window size if required if (curr_end-curr_start+1 > max_window_size) { max_window_size = curr_end-curr_start+1; max_window_start = curr_start; } } cout << "Max substring is : " << s.substr(max_window_start, max_window_size) << " with length " << max_window_size << endl;} // Driver functionint main(){ string s = "aabacbebebe"; int k = 3; kUniques(s, k); return 0;}
import java.util.Arrays; // Java program to find the longest substring with k unique// characters in a given stringclass GFG { final static int MAX_CHARS = 26; // This function calculates number // of unique characters // using a associative array // count[]. Returns true if // no. of characters are less // than required else returns // false. static boolean isValid(int count[], int k) { int val = 0; for (int i = 0; i < MAX_CHARS; i++) { if (count[i] > 0) { val++; } } // Return true if k is greater // than or equal to val return (k >= val); } // Finds the maximum substring // with exactly k unique chars static void kUniques(String s, int k) { int u = 0; int n = s.length(); // Associative array to store // the count of characters int count[] = new int[MAX_CHARS]; Arrays.fill(count, 0); // Traverse the string, Fills // the associative array // count[] and count number // of unique characters for (int i = 0; i < n; i++) { if (count[s.charAt(i) - 'a'] == 0) { u++; } count[s.charAt(i) - 'a']++; } // If there are not enough // unique characters, show // an error message. if (u < k) { System.out.print("Not enough unique characters"); return; } // Otherwise take a window with // first element in it. // start and end variables. int curr_start = 0, curr_end = 0; // Also initialize values for // result longest window int max_window_size = 1; int max_window_start = 0; // Initialize associative // array count[] with zero Arrays.fill(count, 0); // put the first character count[s.charAt(0) - 'a']++; // Start from the second character and add // characters in window according to above // explanation for (int i = 1; i < n; i++) { // Add the character 's[i]' // to current window count[s.charAt(i) - 'a']++; curr_end++; // If there are more than k // unique characters in // current window, remove from left side while (!isValid(count, k)) { count[s.charAt(curr_start) - 'a']--; curr_start++; } // Update the max window size if required if (curr_end - curr_start + 1 > max_window_size) { max_window_size = curr_end - curr_start + 1; max_window_start = curr_start; } } System.out.println("Max substring is : " + s.substring(max_window_start, max_window_start + max_window_size) + " with length " + max_window_size); } // Driver Code static public void main(String[] args) { String s = "aabacbebebe"; int k = 3; kUniques(s, k); }} // This code is contributed by 29AjayKumar
# Python program to find the longest substring with k unique# characters in a given stringMAX_CHARS = 26 # This function calculates number of unique characters# using a associative array count[]. Returns true if# no. of characters are less than required else returns# false.def isValid(count, k): val = 0 for i in range(MAX_CHARS): if count[i] > 0: val += 1 # Return true if k is greater than or equal to val return (k >= val) # Finds the maximum substring with exactly k unique charactersdef kUniques(s, k): u = 0 # number of unique characters n = len(s) # Associative array to store the count count = [0] * MAX_CHARS # Traverse the string, fills the associative array # count[] and count number of unique characters for i in range(n): if count[ord(s[i])-ord('a')] == 0: u += 1 count[ord(s[i])-ord('a')] += 1 # If there are not enough unique characters, show # an error message. if u < k: print ("Not enough unique characters") return # Otherwise take a window with first element in it. # start and end variables. curr_start = 0 curr_end = 0 # Also initialize values for result longest window max_window_size = 1 max_window_start = 0 # Initialize associative array count[] with zero count = [0] * len(count) count[ord(s[0])-ord('a')] += 1 # put the first character # Start from the second character and add # characters in window according to above # explanation for i in range(1,n): # Add the character 's[i]' to current window count[ord(s[i])-ord('a')] += 1 curr_end+=1 # If there are more than k unique characters in # current window, remove from left side while not isValid(count, k): count[ord(s[curr_start])-ord('a')] -= 1 curr_start += 1 # Update the max window size if required if curr_end-curr_start+1 > max_window_size: max_window_size = curr_end-curr_start+1 max_window_start = curr_start print ("Max substring is : " + s[max_window_start:max_window_start + max_window_size] + " with length " + str(max_window_size)) # Driver functions = "aabacbebebe"k = 3kUniques(s, k) # This code is contributed by BHAVYA JAIN
// C# program to find the longest substring with k unique // characters in a given string using System;public class GFG{ static int MAX_CHARS = 26; // This function calculates number // of unique characters // using a associative array // count[]. Returns true if // no. of characters are less // than required else returns // false. static bool isValid(int[] count, int k) { int val = 0; for (int i = 0; i < MAX_CHARS; i++) { if (count[i] > 0) { val++; } } // Return true if k is greater // than or equal to val return (k >= val); } // Finds the maximum substring // with exactly k unique chars static void kUniques(string s, int k) { int u = 0; int n = s.Length; // Associative array to store // the count of characters int[] count = new int[MAX_CHARS]; Array.Fill(count, 0); // Traverse the string, Fills // the associative array // count[] and count number // of unique characters for (int i = 0; i < n; i++) { if (count[s[i] - 'a'] == 0) { u++; } count[s[i] - 'a']++; } // If there are not enough // unique characters, show // an error message. if (u < k) { Console.Write("Not enough unique characters"); return; } // Otherwise take a window with // first element in it. // start and end variables. int curr_start = 0, curr_end = 0; // Also initialize values for // result longest window int max_window_size = 1; int max_window_start = 0; // Initialize associative // array count[] with zero Array.Fill(count, 0); // put the first character count[s[0] - 'a']++; // Start from the second character and add // characters in window according to above // explanation for (int i = 1; i < n; i++) { // Add the character 's[i]' // to current window count[s[i] - 'a']++; curr_end++; // If there are more than k // unique characters in // current window, remove from left side while (!isValid(count, k)) { count[s[curr_start] - 'a']--; curr_start++; } // Update the max window size if required if (curr_end - curr_start + 1 > max_window_size) { max_window_size = curr_end - curr_start + 1; max_window_start = curr_start; } } Console.WriteLine("Max substring is : "+ s.Substring(max_window_start, max_window_size) + " with length " + max_window_size); } // Driver code static public void Main (){ string s = "aabacbebebe"; int k = 3; kUniques(s, k); }} // This code is contributed by avanitrachhadiya2155
<script> // Javascript program to find the longest// substring with k unique characters in// a given stringlet MAX_CHARS = 26; // This function calculates number of// unique characters using a associative// array count[]. Returns true if no. of// characters are less than required else// returns false.function isValid(count, k){ let val = 0; for(let i = 0; i < MAX_CHARS; i++) { if (count[i] > 0) { val++; } } // Return true if k is greater // than or equal to val return (k >= val);} // Finds the maximum substring// with exactly k unique charsfunction kUniques(s,k){ // Number of unique characters let u = 0; let n = s.length; let count = new Array(MAX_CHARS); for(let i = 0; i < MAX_CHARS; i++) { count[i] = 0; } // Traverse the string, Fills // the associative array // count[] and count number // of unique characters for(let i = 0; i < n; i++) { if (count[s[i].charCodeAt(0) - 'a'.charCodeAt(0)] == 0) { u++; } count[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // If there are not enough // unique characters, show // an error message. if (u < k) { document.write("Not enough unique characters"); return; } // Otherwise take a window with // first element in it. // start and end variables. let curr_start = 0, curr_end = 0; // Also initialize values for // result longest window let max_window_size = 1; let max_window_start = 0; // Initialize associative // array count[] with zero for(let i = 0; i < MAX_CHARS; i++) { count[i] = 0; } // put the first character count[s[0].charCodeAt(0) - 'a'.charCodeAt(0)]++; // Start from the second character and add // characters in window according to above // explanation for(let i = 1; i < n; i++) { // Add the character 's[i]' // to current window count[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; curr_end++; // If there are more than k // unique characters in // current window, remove from left side while (!isValid(count, k)) { count[s[curr_start].charCodeAt(0) - 'a'.charCodeAt(0)]--; curr_start++; } // Update the max window size if required if (curr_end - curr_start + 1 > max_window_size) { max_window_size = curr_end - curr_start + 1; max_window_start = curr_start; } } document.write("Max substring is : " + s.substring(max_window_start, max_window_start + max_window_size + 1) + " with length " + max_window_size);} // Driver Codelet s = "aabacbebebe";let k = 3; kUniques(s, k); // This code is contributed by rag2127 </script>
Output:
Max substring is : cbebebe with length 7
Time Complexity: Considering function “isValid()” takes constant time, time complexity of above solution is O(n).This article is contributed by Gaurav Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
29AjayKumar
ukasp
rishavghosh
avanitrachhadiya2155
rag2127
varshagumber28
sooda367
Amazon
Google
SAP Labs
Hash
Strings
Amazon
Google
SAP Labs
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashing | Set 2 (Separate Chaining)
Counting frequencies of array elements
Most frequent element in an array
Double Hashing
Check if two arrays are equal or not
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 25060,
"s": 25032,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 25251,
"s": 25060,
"text": "Given a string you need to print longest possible substring that has exactly M unique characters. If there are more than one substring of longest possible length, then print any one of them."
},
{
"code": null,
"e": 25262,
"s": 25251,
"text": "Examples: "
},
{
"code": null,
"e": 25628,
"s": 25262,
"text": "\"aabbcc\", k = 1\nMax substring can be any one from {\"aa\" , \"bb\" , \"cc\"}.\n\n\"aabbcc\", k = 2\nMax substring can be any one from {\"aabb\" , \"bbcc\"}.\n\n\"aabbcc\", k = 3\nThere are substrings with exactly 3 unique characters\n{\"aabbcc\" , \"abbcc\" , \"aabbc\" , \"abbc\" }\nMax is \"aabbcc\" with length 6.\n\n\"aaabbb\", k = 3\nThere are only two unique characters, thus show error message. "
},
{
"code": null,
"e": 25663,
"s": 25628,
"text": "Source: Google Interview Question."
},
{
"code": null,
"e": 26220,
"s": 25663,
"text": "Method 1 (Brute Force) If the length of string is n, then there can be n*(n+1)/2 possible substrings. A simple way is to generate all the substring and check each one whether it has exactly k unique characters or not. If we apply this brute force, it would take O(n2) to generate all substrings and O(n) to do a check on each one. Thus overall it would go O(n3).We can further improve this solution by creating a hash table and while generating the substrings, check the number of unique characters using that hash table. Thus it would improve up to O(n2)."
},
{
"code": null,
"e": 26711,
"s": 26220,
"text": "Method 2 (Linear Time) The problem can be solved in O(n). Idea is to maintain a window and add elements to the window till it contains less or equal k, update our result if required while doing so. If unique elements exceeds than required in window, start removing the elements from left side. Below are the implementations of above. The implementations assume that the input string alphabet contains only 26 characters (from ‘a’ to ‘z’). The code can be easily extended to 256 characters. "
},
{
"code": null,
"e": 26715,
"s": 26711,
"text": "C++"
},
{
"code": null,
"e": 26720,
"s": 26715,
"text": "Java"
},
{
"code": null,
"e": 26728,
"s": 26720,
"text": "Python3"
},
{
"code": null,
"e": 26731,
"s": 26728,
"text": "C#"
},
{
"code": null,
"e": 26742,
"s": 26731,
"text": "Javascript"
},
{
"code": "// C++ program to find the longest substring with k unique// characters in a given string#include <iostream>#include <cstring>#define MAX_CHARS 26using namespace std; // This function calculates number of unique characters// using a associative array count[]. Returns true if// no. of characters are less than required else returns// false.bool isValid(int count[], int k){ int val = 0; for (int i=0; i<MAX_CHARS; i++) if (count[i] > 0) val++; // Return true if k is greater than or equal to val return (k >= val);} // Finds the maximum substring with exactly k unique charsvoid kUniques(string s, int k){ int u = 0; // number of unique characters int n = s.length(); // Associative array to store the count of characters int count[MAX_CHARS]; memset(count, 0, sizeof(count)); // Traverse the string, Fills the associative array // count[] and count number of unique characters for (int i=0; i<n; i++) { if (count[s[i]-'a']==0) u++; count[s[i]-'a']++; } // If there are not enough unique characters, show // an error message. if (u < k) { cout << \"Not enough unique characters\"; return; } // Otherwise take a window with first element in it. // start and end variables. int curr_start = 0, curr_end = 0; // Also initialize values for result longest window int max_window_size = 1, max_window_start = 0; // Initialize associative array count[] with zero memset(count, 0, sizeof(count)); count[s[0]-'a']++; // put the first character // Start from the second character and add // characters in window according to above // explanation for (int i=1; i<n; i++) { // Add the character 's[i]' to current window count[s[i]-'a']++; curr_end++; // If there are more than k unique characters in // current window, remove from left side while (!isValid(count, k)) { count[s[curr_start]-'a']--; curr_start++; } // Update the max window size if required if (curr_end-curr_start+1 > max_window_size) { max_window_size = curr_end-curr_start+1; max_window_start = curr_start; } } cout << \"Max substring is : \" << s.substr(max_window_start, max_window_size) << \" with length \" << max_window_size << endl;} // Driver functionint main(){ string s = \"aabacbebebe\"; int k = 3; kUniques(s, k); return 0;}",
"e": 29253,
"s": 26742,
"text": null
},
{
"code": "import java.util.Arrays; // Java program to find the longest substring with k unique// characters in a given stringclass GFG { final static int MAX_CHARS = 26; // This function calculates number // of unique characters // using a associative array // count[]. Returns true if // no. of characters are less // than required else returns // false. static boolean isValid(int count[], int k) { int val = 0; for (int i = 0; i < MAX_CHARS; i++) { if (count[i] > 0) { val++; } } // Return true if k is greater // than or equal to val return (k >= val); } // Finds the maximum substring // with exactly k unique chars static void kUniques(String s, int k) { int u = 0; int n = s.length(); // Associative array to store // the count of characters int count[] = new int[MAX_CHARS]; Arrays.fill(count, 0); // Traverse the string, Fills // the associative array // count[] and count number // of unique characters for (int i = 0; i < n; i++) { if (count[s.charAt(i) - 'a'] == 0) { u++; } count[s.charAt(i) - 'a']++; } // If there are not enough // unique characters, show // an error message. if (u < k) { System.out.print(\"Not enough unique characters\"); return; } // Otherwise take a window with // first element in it. // start and end variables. int curr_start = 0, curr_end = 0; // Also initialize values for // result longest window int max_window_size = 1; int max_window_start = 0; // Initialize associative // array count[] with zero Arrays.fill(count, 0); // put the first character count[s.charAt(0) - 'a']++; // Start from the second character and add // characters in window according to above // explanation for (int i = 1; i < n; i++) { // Add the character 's[i]' // to current window count[s.charAt(i) - 'a']++; curr_end++; // If there are more than k // unique characters in // current window, remove from left side while (!isValid(count, k)) { count[s.charAt(curr_start) - 'a']--; curr_start++; } // Update the max window size if required if (curr_end - curr_start + 1 > max_window_size) { max_window_size = curr_end - curr_start + 1; max_window_start = curr_start; } } System.out.println(\"Max substring is : \" + s.substring(max_window_start, max_window_start + max_window_size) + \" with length \" + max_window_size); } // Driver Code static public void main(String[] args) { String s = \"aabacbebebe\"; int k = 3; kUniques(s, k); }} // This code is contributed by 29AjayKumar",
"e": 32452,
"s": 29253,
"text": null
},
{
"code": "# Python program to find the longest substring with k unique# characters in a given stringMAX_CHARS = 26 # This function calculates number of unique characters# using a associative array count[]. Returns true if# no. of characters are less than required else returns# false.def isValid(count, k): val = 0 for i in range(MAX_CHARS): if count[i] > 0: val += 1 # Return true if k is greater than or equal to val return (k >= val) # Finds the maximum substring with exactly k unique charactersdef kUniques(s, k): u = 0 # number of unique characters n = len(s) # Associative array to store the count count = [0] * MAX_CHARS # Traverse the string, fills the associative array # count[] and count number of unique characters for i in range(n): if count[ord(s[i])-ord('a')] == 0: u += 1 count[ord(s[i])-ord('a')] += 1 # If there are not enough unique characters, show # an error message. if u < k: print (\"Not enough unique characters\") return # Otherwise take a window with first element in it. # start and end variables. curr_start = 0 curr_end = 0 # Also initialize values for result longest window max_window_size = 1 max_window_start = 0 # Initialize associative array count[] with zero count = [0] * len(count) count[ord(s[0])-ord('a')] += 1 # put the first character # Start from the second character and add # characters in window according to above # explanation for i in range(1,n): # Add the character 's[i]' to current window count[ord(s[i])-ord('a')] += 1 curr_end+=1 # If there are more than k unique characters in # current window, remove from left side while not isValid(count, k): count[ord(s[curr_start])-ord('a')] -= 1 curr_start += 1 # Update the max window size if required if curr_end-curr_start+1 > max_window_size: max_window_size = curr_end-curr_start+1 max_window_start = curr_start print (\"Max substring is : \" + s[max_window_start:max_window_start + max_window_size] + \" with length \" + str(max_window_size)) # Driver functions = \"aabacbebebe\"k = 3kUniques(s, k) # This code is contributed by BHAVYA JAIN",
"e": 34738,
"s": 32452,
"text": null
},
{
"code": "// C# program to find the longest substring with k unique // characters in a given string using System;public class GFG{ static int MAX_CHARS = 26; // This function calculates number // of unique characters // using a associative array // count[]. Returns true if // no. of characters are less // than required else returns // false. static bool isValid(int[] count, int k) { int val = 0; for (int i = 0; i < MAX_CHARS; i++) { if (count[i] > 0) { val++; } } // Return true if k is greater // than or equal to val return (k >= val); } // Finds the maximum substring // with exactly k unique chars static void kUniques(string s, int k) { int u = 0; int n = s.Length; // Associative array to store // the count of characters int[] count = new int[MAX_CHARS]; Array.Fill(count, 0); // Traverse the string, Fills // the associative array // count[] and count number // of unique characters for (int i = 0; i < n; i++) { if (count[s[i] - 'a'] == 0) { u++; } count[s[i] - 'a']++; } // If there are not enough // unique characters, show // an error message. if (u < k) { Console.Write(\"Not enough unique characters\"); return; } // Otherwise take a window with // first element in it. // start and end variables. int curr_start = 0, curr_end = 0; // Also initialize values for // result longest window int max_window_size = 1; int max_window_start = 0; // Initialize associative // array count[] with zero Array.Fill(count, 0); // put the first character count[s[0] - 'a']++; // Start from the second character and add // characters in window according to above // explanation for (int i = 1; i < n; i++) { // Add the character 's[i]' // to current window count[s[i] - 'a']++; curr_end++; // If there are more than k // unique characters in // current window, remove from left side while (!isValid(count, k)) { count[s[curr_start] - 'a']--; curr_start++; } // Update the max window size if required if (curr_end - curr_start + 1 > max_window_size) { max_window_size = curr_end - curr_start + 1; max_window_start = curr_start; } } Console.WriteLine(\"Max substring is : \"+ s.Substring(max_window_start, max_window_size) + \" with length \" + max_window_size); } // Driver code static public void Main (){ string s = \"aabacbebebe\"; int k = 3; kUniques(s, k); }} // This code is contributed by avanitrachhadiya2155",
"e": 37524,
"s": 34738,
"text": null
},
{
"code": "<script> // Javascript program to find the longest// substring with k unique characters in// a given stringlet MAX_CHARS = 26; // This function calculates number of// unique characters using a associative// array count[]. Returns true if no. of// characters are less than required else// returns false.function isValid(count, k){ let val = 0; for(let i = 0; i < MAX_CHARS; i++) { if (count[i] > 0) { val++; } } // Return true if k is greater // than or equal to val return (k >= val);} // Finds the maximum substring// with exactly k unique charsfunction kUniques(s,k){ // Number of unique characters let u = 0; let n = s.length; let count = new Array(MAX_CHARS); for(let i = 0; i < MAX_CHARS; i++) { count[i] = 0; } // Traverse the string, Fills // the associative array // count[] and count number // of unique characters for(let i = 0; i < n; i++) { if (count[s[i].charCodeAt(0) - 'a'.charCodeAt(0)] == 0) { u++; } count[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // If there are not enough // unique characters, show // an error message. if (u < k) { document.write(\"Not enough unique characters\"); return; } // Otherwise take a window with // first element in it. // start and end variables. let curr_start = 0, curr_end = 0; // Also initialize values for // result longest window let max_window_size = 1; let max_window_start = 0; // Initialize associative // array count[] with zero for(let i = 0; i < MAX_CHARS; i++) { count[i] = 0; } // put the first character count[s[0].charCodeAt(0) - 'a'.charCodeAt(0)]++; // Start from the second character and add // characters in window according to above // explanation for(let i = 1; i < n; i++) { // Add the character 's[i]' // to current window count[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; curr_end++; // If there are more than k // unique characters in // current window, remove from left side while (!isValid(count, k)) { count[s[curr_start].charCodeAt(0) - 'a'.charCodeAt(0)]--; curr_start++; } // Update the max window size if required if (curr_end - curr_start + 1 > max_window_size) { max_window_size = curr_end - curr_start + 1; max_window_start = curr_start; } } document.write(\"Max substring is : \" + s.substring(max_window_start, max_window_start + max_window_size + 1) + \" with length \" + max_window_size);} // Driver Codelet s = \"aabacbebebe\";let k = 3; kUniques(s, k); // This code is contributed by rag2127 </script>",
"e": 40494,
"s": 37524,
"text": null
},
{
"code": null,
"e": 40503,
"s": 40494,
"text": "Output: "
},
{
"code": null,
"e": 40544,
"s": 40503,
"text": "Max substring is : cbebebe with length 7"
},
{
"code": null,
"e": 40828,
"s": 40544,
"text": "Time Complexity: Considering function “isValid()” takes constant time, time complexity of above solution is O(n).This article is contributed by Gaurav Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 40840,
"s": 40828,
"text": "29AjayKumar"
},
{
"code": null,
"e": 40846,
"s": 40840,
"text": "ukasp"
},
{
"code": null,
"e": 40858,
"s": 40846,
"text": "rishavghosh"
},
{
"code": null,
"e": 40879,
"s": 40858,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 40887,
"s": 40879,
"text": "rag2127"
},
{
"code": null,
"e": 40902,
"s": 40887,
"text": "varshagumber28"
},
{
"code": null,
"e": 40911,
"s": 40902,
"text": "sooda367"
},
{
"code": null,
"e": 40918,
"s": 40911,
"text": "Amazon"
},
{
"code": null,
"e": 40925,
"s": 40918,
"text": "Google"
},
{
"code": null,
"e": 40934,
"s": 40925,
"text": "SAP Labs"
},
{
"code": null,
"e": 40939,
"s": 40934,
"text": "Hash"
},
{
"code": null,
"e": 40947,
"s": 40939,
"text": "Strings"
},
{
"code": null,
"e": 40954,
"s": 40947,
"text": "Amazon"
},
{
"code": null,
"e": 40961,
"s": 40954,
"text": "Google"
},
{
"code": null,
"e": 40970,
"s": 40961,
"text": "SAP Labs"
},
{
"code": null,
"e": 40975,
"s": 40970,
"text": "Hash"
},
{
"code": null,
"e": 40983,
"s": 40975,
"text": "Strings"
},
{
"code": null,
"e": 41081,
"s": 40983,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41090,
"s": 41081,
"text": "Comments"
},
{
"code": null,
"e": 41103,
"s": 41090,
"text": "Old Comments"
},
{
"code": null,
"e": 41139,
"s": 41103,
"text": "Hashing | Set 2 (Separate Chaining)"
},
{
"code": null,
"e": 41178,
"s": 41139,
"text": "Counting frequencies of array elements"
},
{
"code": null,
"e": 41212,
"s": 41178,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 41227,
"s": 41212,
"text": "Double Hashing"
},
{
"code": null,
"e": 41264,
"s": 41227,
"text": "Check if two arrays are equal or not"
},
{
"code": null,
"e": 41289,
"s": 41264,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 41335,
"s": 41289,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 41369,
"s": 41335,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 41384,
"s": 41369,
"text": "C++ Data Types"
}
] |
DateTime.DaysInMonth() Method in C# - GeeksforGeeks
|
22 Jan, 2019
This method returns the number of days in the specified month and year. This method always interprets month and year as the month and year of the Gregorian calendar even if the Gregorian calendar is not the current culture’s current calendar.
Syntax:
public static int DaysInMonth (int year, int month);
Return Value: This method return the number of days in the month for the specified year. For example, if month equals 2 for February, the return value will be 28 or 29 depending upon whether the year is a leap year.
Exception: This method will give ArgumentOutOfRangeException if month is less than 1 or greater than 12 or year is less than 1 or greater than 9999.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# code to demonstrate the// DaysInMonth(Int32, Int32) Methodusing System; class GFG { // Main Method static void Main() { // taking month values int Dec = 12; int Feb = 2; // using the method int daysindec = DateTime.DaysInMonth(2008, Dec); Console.WriteLine(daysindec); // daysinfeb1 gets 29 because the // year 2016 was a leap year. int daysinfeb1 = DateTime.DaysInMonth(2016, Feb); Console.WriteLine(daysinfeb1); // daysinfeb2 gets 28 because // the year 2018 was not a leap year. int daysinfeb2 = DateTime.DaysInMonth(2018, Feb); Console.WriteLine(daysinfeb2); }}
Output:
31
29
28
Example 2:
// C# code to demonstrate the// DaysInMonth(Int32, Int32) Methodusing System; class GFG { // Main Method static void Main() { // taking month and year's value int y = 10000; int m = 7; // using the method will give error // as the value of the year is greater // than 10000 int res = DateTime.DaysInMonth(y, m); Console.WriteLine(res); }}
Runtime Error:
Unhandled Exception:System.ArgumentOutOfRangeException: Year must be between 1 and 9999.Parameter name: year
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.daysinmonth?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
Extension Method in C#
C# | Abstract Classes
C# | String.IndexOf( ) Method | Set - 1
Common Language Runtime (CLR) in C#
Different ways to sort an array in descending order in C#
C# | Arrays
HashSet in C# with Examples
|
[
{
"code": null,
"e": 23879,
"s": 23851,
"text": "\n22 Jan, 2019"
},
{
"code": null,
"e": 24122,
"s": 23879,
"text": "This method returns the number of days in the specified month and year. This method always interprets month and year as the month and year of the Gregorian calendar even if the Gregorian calendar is not the current culture’s current calendar."
},
{
"code": null,
"e": 24130,
"s": 24122,
"text": "Syntax:"
},
{
"code": null,
"e": 24183,
"s": 24130,
"text": "public static int DaysInMonth (int year, int month);"
},
{
"code": null,
"e": 24399,
"s": 24183,
"text": "Return Value: This method return the number of days in the month for the specified year. For example, if month equals 2 for February, the return value will be 28 or 29 depending upon whether the year is a leap year."
},
{
"code": null,
"e": 24548,
"s": 24399,
"text": "Exception: This method will give ArgumentOutOfRangeException if month is less than 1 or greater than 12 or year is less than 1 or greater than 9999."
},
{
"code": null,
"e": 24613,
"s": 24548,
"text": "Below programs illustrate the use of the above-discussed method:"
},
{
"code": null,
"e": 24624,
"s": 24613,
"text": "Example 1:"
},
{
"code": "// C# code to demonstrate the// DaysInMonth(Int32, Int32) Methodusing System; class GFG { // Main Method static void Main() { // taking month values int Dec = 12; int Feb = 2; // using the method int daysindec = DateTime.DaysInMonth(2008, Dec); Console.WriteLine(daysindec); // daysinfeb1 gets 29 because the // year 2016 was a leap year. int daysinfeb1 = DateTime.DaysInMonth(2016, Feb); Console.WriteLine(daysinfeb1); // daysinfeb2 gets 28 because // the year 2018 was not a leap year. int daysinfeb2 = DateTime.DaysInMonth(2018, Feb); Console.WriteLine(daysinfeb2); }}",
"e": 25323,
"s": 24624,
"text": null
},
{
"code": null,
"e": 25331,
"s": 25323,
"text": "Output:"
},
{
"code": null,
"e": 25341,
"s": 25331,
"text": "31\n29\n28\n"
},
{
"code": null,
"e": 25352,
"s": 25341,
"text": "Example 2:"
},
{
"code": "// C# code to demonstrate the// DaysInMonth(Int32, Int32) Methodusing System; class GFG { // Main Method static void Main() { // taking month and year's value int y = 10000; int m = 7; // using the method will give error // as the value of the year is greater // than 10000 int res = DateTime.DaysInMonth(y, m); Console.WriteLine(res); }}",
"e": 25768,
"s": 25352,
"text": null
},
{
"code": null,
"e": 25783,
"s": 25768,
"text": "Runtime Error:"
},
{
"code": null,
"e": 25892,
"s": 25783,
"text": "Unhandled Exception:System.ArgumentOutOfRangeException: Year must be between 1 and 9999.Parameter name: year"
},
{
"code": null,
"e": 25903,
"s": 25892,
"text": "Reference:"
},
{
"code": null,
"e": 25999,
"s": 25903,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.daysinmonth?view=netframework-4.7.2"
},
{
"code": null,
"e": 26022,
"s": 25999,
"text": "CSharp DateTime Struct"
},
{
"code": null,
"e": 26036,
"s": 26022,
"text": "CSharp-method"
},
{
"code": null,
"e": 26039,
"s": 26036,
"text": "C#"
},
{
"code": null,
"e": 26137,
"s": 26039,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26146,
"s": 26137,
"text": "Comments"
},
{
"code": null,
"e": 26159,
"s": 26146,
"text": "Old Comments"
},
{
"code": null,
"e": 26174,
"s": 26159,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26214,
"s": 26174,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26245,
"s": 26214,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 26268,
"s": 26245,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26290,
"s": 26268,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 26330,
"s": 26290,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 26366,
"s": 26330,
"text": "Common Language Runtime (CLR) in C#"
},
{
"code": null,
"e": 26424,
"s": 26366,
"text": "Different ways to sort an array in descending order in C#"
},
{
"code": null,
"e": 26436,
"s": 26424,
"text": "C# | Arrays"
}
] |
Implementing a Binary Search Tree in JavaScript
|
A tree is a collection of nodes connected by some edges. Conventionally, each node of a tree
holds some data and reference to its children.
Binary Search tree is a binary tree in which nodes that have lesser value are stored on the left while the nodes with a higher value are stored at the right.
For instance, visual representation of a valid BST is −
25
/ \
20 36
/ \ / \
10 22 30 40
Let’s now implement our very own Binary Search Tree in JavaScript language.
This class will represent a single node present at various points in the BST. A BST is nothing
but a collection of nodes storing data and child references placed according to the rules
described above.
class Node{
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
};
};
To create a new Node instance, we can call this class like this with some data −
const newNode = new Node(23);
This will create a new Node instance with data set to 23 and left and right reference both being null.
class BinarySearchTree{
constructor(){
this.root = null;
};
};
This will create the Binary Search Tree class which we can call with the new keyword to make a
tree instance.
Now as we are done with the basic stuff let’s move on to inserting a new node at the right place (according to the rules of BST described in definition).
class BinarySearchTree{
constructor(){
this.root = null;
}
insert(data){
var newNode = new Node(data);
if(this.root === null){
this.root = newNode;
}else{
this.insertNode(this.root, newNode);
};
};
insertNode(node, newNode){
if(newNode.data < node.data){
if(node.left === null){
node.left = newNode;
}else{
this.insertNode(node.left, newNode);
};
} else {
if(node.right === null){
node.right = newNode;
}else{
this.insertNode(node.right,newNode);
};
};
};
};
class Node{
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
};
};
class BinarySearchTree{
constructor(){
this.root = null;
}
insert(data){
var newNode = new Node(data);
if(this.root === null){
this.root = newNode;
}else{
this.insertNode(this.root, newNode);
};
};
insertNode(node, newNode){
if(newNode.data < node.data){
if(node.left === null){
node.left = newNode;
}else{
this.insertNode(node.left, newNode);
};
} else {
if(node.right === null){
node.right = newNode;
}else{
this.insertNode(node.right,newNode);
};
};
};
};
const BST = new BinarySearchTree();
BST.insert(1);
BST.insert(3);
BST.insert(2);
|
[
{
"code": null,
"e": 1202,
"s": 1062,
"text": "A tree is a collection of nodes connected by some edges. Conventionally, each node of a tree\nholds some data and reference to its children."
},
{
"code": null,
"e": 1360,
"s": 1202,
"text": "Binary Search tree is a binary tree in which nodes that have lesser value are stored on the left while the nodes with a higher value are stored at the right."
},
{
"code": null,
"e": 1416,
"s": 1360,
"text": "For instance, visual representation of a valid BST is −"
},
{
"code": null,
"e": 1466,
"s": 1416,
"text": " 25\n / \\\n 20 36\n / \\ / \\\n10 22 30 40"
},
{
"code": null,
"e": 1542,
"s": 1466,
"text": "Let’s now implement our very own Binary Search Tree in JavaScript language."
},
{
"code": null,
"e": 1744,
"s": 1542,
"text": "This class will represent a single node present at various points in the BST. A BST is nothing\nbut a collection of nodes storing data and child references placed according to the rules\ndescribed above."
},
{
"code": null,
"e": 1861,
"s": 1744,
"text": "class Node{\n constructor(data) {\n this.data = data;\n this.left = null;\n this.right = null;\n };\n};"
},
{
"code": null,
"e": 1942,
"s": 1861,
"text": "To create a new Node instance, we can call this class like this with some data −"
},
{
"code": null,
"e": 1972,
"s": 1942,
"text": "const newNode = new Node(23);"
},
{
"code": null,
"e": 2075,
"s": 1972,
"text": "This will create a new Node instance with data set to 23 and left and right reference both being null."
},
{
"code": null,
"e": 2150,
"s": 2075,
"text": "class BinarySearchTree{\n constructor(){\n this.root = null;\n };\n};"
},
{
"code": null,
"e": 2260,
"s": 2150,
"text": "This will create the Binary Search Tree class which we can call with the new keyword to make a\ntree instance."
},
{
"code": null,
"e": 2414,
"s": 2260,
"text": "Now as we are done with the basic stuff let’s move on to inserting a new node at the right place (according to the rules of BST described in definition)."
},
{
"code": null,
"e": 3059,
"s": 2414,
"text": "class BinarySearchTree{\n constructor(){\n this.root = null;\n }\n insert(data){\n var newNode = new Node(data);\n if(this.root === null){\n this.root = newNode;\n }else{\n this.insertNode(this.root, newNode);\n };\n };\n insertNode(node, newNode){\n if(newNode.data < node.data){\n if(node.left === null){\n node.left = newNode;\n }else{\n this.insertNode(node.left, newNode);\n };\n } else {\n if(node.right === null){\n node.right = newNode;\n }else{\n this.insertNode(node.right,newNode);\n };\n };\n };\n};"
},
{
"code": null,
"e": 3902,
"s": 3059,
"text": "class Node{\n constructor(data) {\n this.data = data;\n this.left = null;\n this.right = null;\n };\n};\nclass BinarySearchTree{\n constructor(){\n this.root = null;\n }\n insert(data){\n var newNode = new Node(data);\n if(this.root === null){\n this.root = newNode;\n }else{\n this.insertNode(this.root, newNode);\n };\n };\n insertNode(node, newNode){\n if(newNode.data < node.data){\n if(node.left === null){\n node.left = newNode;\n }else{\n this.insertNode(node.left, newNode);\n };\n } else {\n if(node.right === null){\n node.right = newNode;\n }else{\n this.insertNode(node.right,newNode);\n };\n };\n };\n};\nconst BST = new BinarySearchTree();\nBST.insert(1);\nBST.insert(3);\nBST.insert(2);"
}
] |
How do I get rid of the Python Tkinter root window?
|
Sometimes, while testing a Tkinter application, we may need to hide the Tkinter
default window or frame. There are two general methods through which we can either hide our Tkinter window, or destroy it.
The mainloop() keeps running the Tkinter window until it is not closed by external events. In order to destroy the window we can use the destroy() callable method.
However, to hide the Tkinter window, we generally use the “withdraw” method that
can be invoked on the root window or the main window.
In this example, we have created a text widget and a button “Quit” that will close the root window immediately. However, we can also use the withdraw method to avoid displaying it on the screen.
#Import the library
from tkinter import *
#Create an instance of window
win= Tk()
#Set the geometry of the window
win.geometry("700x400")
def disable_button():
win.destroy()
#Create a Label
Label(win,text="Type Something",font=('Helvetica bold', 25),
fg="green").pack(pady=20)
#Create a Text widget
text= Text(win, height= 10,width= 40)
text.pack()
#Create a Disable Button
Button(win, text= "Quit", command= disable_button,fg= "white",
bg="black", width= 20).pack(pady=20)
#win.withdraw()
win.mainloop()
The above python code hides the root window using the withdraw method. However, to destroy the window, we can use the destroy method.
When you click the Quit button, it will hide the root window.
|
[
{
"code": null,
"e": 1265,
"s": 1062,
"text": "Sometimes, while testing a Tkinter application, we may need to hide the Tkinter\ndefault window or frame. There are two general methods through which we can either hide our Tkinter window, or destroy it."
},
{
"code": null,
"e": 1429,
"s": 1265,
"text": "The mainloop() keeps running the Tkinter window until it is not closed by external events. In order to destroy the window we can use the destroy() callable method."
},
{
"code": null,
"e": 1564,
"s": 1429,
"text": "However, to hide the Tkinter window, we generally use the “withdraw” method that\ncan be invoked on the root window or the main window."
},
{
"code": null,
"e": 1759,
"s": 1564,
"text": "In this example, we have created a text widget and a button “Quit” that will close the root window immediately. However, we can also use the withdraw method to avoid displaying it on the screen."
},
{
"code": null,
"e": 2273,
"s": 1759,
"text": "#Import the library\nfrom tkinter import *\n\n#Create an instance of window\nwin= Tk()\n\n#Set the geometry of the window\nwin.geometry(\"700x400\")\n\ndef disable_button():\n win.destroy()\n#Create a Label\nLabel(win,text=\"Type Something\",font=('Helvetica bold', 25),\nfg=\"green\").pack(pady=20)\n\n#Create a Text widget\ntext= Text(win, height= 10,width= 40)\ntext.pack()\n\n#Create a Disable Button\nButton(win, text= \"Quit\", command= disable_button,fg= \"white\",\nbg=\"black\", width= 20).pack(pady=20)\n\n#win.withdraw()\nwin.mainloop()"
},
{
"code": null,
"e": 2407,
"s": 2273,
"text": "The above python code hides the root window using the withdraw method. However, to destroy the window, we can use the destroy method."
},
{
"code": null,
"e": 2469,
"s": 2407,
"text": "When you click the Quit button, it will hide the root window."
}
] |
How to Create a Bland-Altman Plot in R? - GeeksforGeeks
|
04 Jan, 2022
In this article, we will discuss how to create a Bland-Altman Plot in the R programming Language.
The Bland-Altman plot helps us to visualize the difference in measurements between two different measurement techniques. It is used vastly in the field of biochemistry. It is useful for determining how similar two instruments/techniques are at measuring the same construct in chemical reactions.
Step 1: Create sample dataframe
To create a sample data frame in the R language, we can either import dataset from a CSV file by using the read.csv() function or can create our own data frame by using the data.frame() function.
Step 2: Calculate the difference in measurements
Next, we will add two new columns to data frame that will store the average and difference of both variables for plotting afterward. We will use the assignment function for that purpose.
Syntax:
Sample_Data$average <- rowMeans( Sample_Data )
Sample_Data$difference <- Sample_Data$var1 – Sample_Data$var2
Step 3: Calculate mean difference and Limits of the confidence interval
To calculate the mean difference, we will use the mean() function of the R Language. To calculate the lower and upper limit of 90% confidence interval, we will use the sd() function.
Syntax:
mean_difference <- mean( Sample_Data$difference )
lower_limit <- mean_difference – 1.91*sd( Sample_Data$difference )
upper_limit <- mean_difference + 1.91*sd( Sample_Data$difference )
Step 4: Plot the mean difference, Confidence interval, and scatter plot
To plot the Bland-Altman Plot we will use the ggplot() function of the ggplot2 package library along with the geom_hline() function for mean_difference and confidence interval.
Syntax:
ggplot( Sample_Data, aes( x = average, y = difference ) ) + geom_point( ) +
geom_hline( yintercept = mean_differnce ) + geom_hline( yintercept = lower_limit ) +
geom_hline( yintercept = upper_limit )
This gives the Bland-Altmon Plot finally.
Example: A sample Bland-Altmon Plot
R
# create sample dataSample_Data <- data.frame( var1=c(5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 11), var2=c(4, 4, 5, 5, 5, 7, 8, 6, 9, 7, 7, 8, 9, 14)) # create new column for average measurementSample_Data$average <- rowMeans(Sample_Data) # create new column for difference measurementSample_Data$difference <- Sample_Data$var1 - Sample_Data$var2 # calculate mean differencemean_difference <- mean(Sample_Data$difference) # calculate uppr and lower limits of the # Confidence interval of 90%lower_limit <- mean_difference - 1.91*sd( Sample_Data$difference )upper_limit <- mean_difference + 1.91*sd( Sample_Data$difference ) # load library ggplot2library(ggplot2) # Plot the Bland-Altmon Plotggplot(Sample_Data, aes(x = average, y = difference)) + geom_point(size=3) + geom_hline(yintercept = mean_difference, color= "red", lwd=1.5) + geom_hline(yintercept = lower_limit, color = "green", lwd=1.5) + geom_hline(yintercept = upper_limit, color = "green", lwd=1.5)
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
Time Series Analysis in R
R - if statement
Logistic Regression in R Programming
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 26585,
"s": 26487,
"text": "In this article, we will discuss how to create a Bland-Altman Plot in the R programming Language."
},
{
"code": null,
"e": 26882,
"s": 26585,
"text": "The Bland-Altman plot helps us to visualize the difference in measurements between two different measurement techniques. It is used vastly in the field of biochemistry. It is useful for determining how similar two instruments/techniques are at measuring the same construct in chemical reactions. "
},
{
"code": null,
"e": 26914,
"s": 26882,
"text": "Step 1: Create sample dataframe"
},
{
"code": null,
"e": 27110,
"s": 26914,
"text": "To create a sample data frame in the R language, we can either import dataset from a CSV file by using the read.csv() function or can create our own data frame by using the data.frame() function."
},
{
"code": null,
"e": 27159,
"s": 27110,
"text": "Step 2: Calculate the difference in measurements"
},
{
"code": null,
"e": 27346,
"s": 27159,
"text": "Next, we will add two new columns to data frame that will store the average and difference of both variables for plotting afterward. We will use the assignment function for that purpose."
},
{
"code": null,
"e": 27354,
"s": 27346,
"text": "Syntax:"
},
{
"code": null,
"e": 27403,
"s": 27354,
"text": "Sample_Data$average <- rowMeans( Sample_Data ) "
},
{
"code": null,
"e": 27465,
"s": 27403,
"text": "Sample_Data$difference <- Sample_Data$var1 – Sample_Data$var2"
},
{
"code": null,
"e": 27537,
"s": 27465,
"text": "Step 3: Calculate mean difference and Limits of the confidence interval"
},
{
"code": null,
"e": 27720,
"s": 27537,
"text": "To calculate the mean difference, we will use the mean() function of the R Language. To calculate the lower and upper limit of 90% confidence interval, we will use the sd() function."
},
{
"code": null,
"e": 27728,
"s": 27720,
"text": "Syntax:"
},
{
"code": null,
"e": 27778,
"s": 27728,
"text": "mean_difference <- mean( Sample_Data$difference )"
},
{
"code": null,
"e": 27845,
"s": 27778,
"text": "lower_limit <- mean_difference – 1.91*sd( Sample_Data$difference )"
},
{
"code": null,
"e": 27912,
"s": 27845,
"text": "upper_limit <- mean_difference + 1.91*sd( Sample_Data$difference )"
},
{
"code": null,
"e": 27984,
"s": 27912,
"text": "Step 4: Plot the mean difference, Confidence interval, and scatter plot"
},
{
"code": null,
"e": 28161,
"s": 27984,
"text": "To plot the Bland-Altman Plot we will use the ggplot() function of the ggplot2 package library along with the geom_hline() function for mean_difference and confidence interval."
},
{
"code": null,
"e": 28169,
"s": 28161,
"text": "Syntax:"
},
{
"code": null,
"e": 28245,
"s": 28169,
"text": "ggplot( Sample_Data, aes( x = average, y = difference ) ) + geom_point( ) +"
},
{
"code": null,
"e": 28331,
"s": 28245,
"text": " geom_hline( yintercept = mean_differnce ) + geom_hline( yintercept = lower_limit ) +"
},
{
"code": null,
"e": 28371,
"s": 28331,
"text": " geom_hline( yintercept = upper_limit )"
},
{
"code": null,
"e": 28413,
"s": 28371,
"text": "This gives the Bland-Altmon Plot finally."
},
{
"code": null,
"e": 28449,
"s": 28413,
"text": "Example: A sample Bland-Altmon Plot"
},
{
"code": null,
"e": 28451,
"s": 28449,
"text": "R"
},
{
"code": "# create sample dataSample_Data <- data.frame( var1=c(5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9, 10, 10, 11), var2=c(4, 4, 5, 5, 5, 7, 8, 6, 9, 7, 7, 8, 9, 14)) # create new column for average measurementSample_Data$average <- rowMeans(Sample_Data) # create new column for difference measurementSample_Data$difference <- Sample_Data$var1 - Sample_Data$var2 # calculate mean differencemean_difference <- mean(Sample_Data$difference) # calculate uppr and lower limits of the # Confidence interval of 90%lower_limit <- mean_difference - 1.91*sd( Sample_Data$difference )upper_limit <- mean_difference + 1.91*sd( Sample_Data$difference ) # load library ggplot2library(ggplot2) # Plot the Bland-Altmon Plotggplot(Sample_Data, aes(x = average, y = difference)) + geom_point(size=3) + geom_hline(yintercept = mean_difference, color= \"red\", lwd=1.5) + geom_hline(yintercept = lower_limit, color = \"green\", lwd=1.5) + geom_hline(yintercept = upper_limit, color = \"green\", lwd=1.5)",
"e": 29426,
"s": 28451,
"text": null
},
{
"code": null,
"e": 29434,
"s": 29426,
"text": "Output:"
},
{
"code": null,
"e": 29441,
"s": 29434,
"text": "Picked"
},
{
"code": null,
"e": 29450,
"s": 29441,
"text": "R-Charts"
},
{
"code": null,
"e": 29459,
"s": 29450,
"text": "R-Graphs"
},
{
"code": null,
"e": 29467,
"s": 29459,
"text": "R-plots"
},
{
"code": null,
"e": 29478,
"s": 29467,
"text": "R Language"
},
{
"code": null,
"e": 29576,
"s": 29478,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29628,
"s": 29576,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29663,
"s": 29628,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29701,
"s": 29663,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29759,
"s": 29701,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29802,
"s": 29759,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29839,
"s": 29802,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 29888,
"s": 29839,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29914,
"s": 29888,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 29931,
"s": 29914,
"text": "R - if statement"
}
] |
Reverse the content of a file and store it in another - GeeksforGeeks
|
16 Jul, 2020
The article explains how to store the reverse of the first text file’s data to a second text file. In this post, it has been assumed that there is no text in the first text file. So we will write some text in a first text file by passing data to reverse function and then in reverse function we will copy the reverse of its data to another text file.
Prerequisite:In text file the data is stored in the ASCII format and the data can be read in the text editor with each alphabet in the file given a specific index in the memory similar to that of an array
Example:
// Sample input 1
Input to the reverse function:
reverse
Output:
esrever
// Sample input 2
Input to the reverse function:
Geeks For Geeks
Output:
skeeG roF skeeG
Approach:Step 1: Calling reverse function with text that is needed to be contained in the first text file i.e. passing sample input of text file.Working of Reverse functionStep 2: Opening file in writing mode and writing “str” into first text file here: in file Geeks.txtStep 3: Storing the location of end of first text file in the variable “pos” and the closing the file.Step 4: Opening first text file in reading mode and placing the reading pointer at position pos.Step 5: Opening new text file “Geeks2.txt” in writing mode.Step 6: Reading first text file character by character from the end and storing each character to the second text file.Step 7: Shifting the read pointer one alphabet backwards in the text file.Step 8: Closing the text files.Step 9: Reading second text file (you can skip it if not necessary).
**name of first text file ="Geeks.txt"
**name of second text file="Geeks2.txt"
Example:
#include <conio.h>#include <fstream.h>#include <iostream.h>#include <stdio.h> // function to perform the task// accepts the parameter str as the text to// be stored in text filevoid reverse(char str[]){ char ch; ofstream ofs; // created text file ofs.open("Geeks.txt", ios::out); for (int i = 0; str[i] != '\0'; i++) { // writing into the file ofs.put(str[i]); } // storing the position of end of the file int pos = ofs.tellp(); ofs.close(); // object for reading the contents of the // first text file ifstream ifs; ifs.open("Geeks.txt", ios::in); // object for writing in to the text file 2 ofstream ofs1; ofs1.open("Geeks2.txt", ios::out); // putting the read pointer to the last alphabet // of the file ifs.seekg(--pos); while (pos >= 0) { // reading from the file 1 ifs.get(ch); // writing to the file 2 ofs1.put(ch); /* shifting read pointer position one alphabet backwards in the text file */ pos--; ifs.seekg(pos); } ifs.close(); ofs1.close(); ifstream ifs1; ifs1.open("Geeks2.txt", ios::in); // file.eof() checks the end of the text file while (!ifs1.eof()) { ifs1.get(ch); cout << ch; } ifs1.close();} // Driver codeint main(){ clrscr(); // sample input 1 cout << "example 1: (Geeks For Geeks) \n"; // passing first text file's text // through reverse function reverse("Geeks For Geeks"); // sample input 2 cout << "\n example 2:(reverse)\n"; reverse("reverse"); getch(); return 0;}
Output:
Akanksha_Rai
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 25718,
"s": 25367,
"text": "The article explains how to store the reverse of the first text file’s data to a second text file. In this post, it has been assumed that there is no text in the first text file. So we will write some text in a first text file by passing data to reverse function and then in reverse function we will copy the reverse of its data to another text file."
},
{
"code": null,
"e": 25923,
"s": 25718,
"text": "Prerequisite:In text file the data is stored in the ASCII format and the data can be read in the text editor with each alphabet in the file given a specific index in the memory similar to that of an array"
},
{
"code": null,
"e": 25932,
"s": 25923,
"text": "Example:"
},
{
"code": null,
"e": 26101,
"s": 25932,
"text": "// Sample input 1 \nInput to the reverse function:\nreverse\n\nOutput:\nesrever\n\n// Sample input 2\nInput to the reverse function: \nGeeks For Geeks\n\nOutput:\nskeeG roF skeeG\n"
},
{
"code": null,
"e": 26922,
"s": 26101,
"text": "Approach:Step 1: Calling reverse function with text that is needed to be contained in the first text file i.e. passing sample input of text file.Working of Reverse functionStep 2: Opening file in writing mode and writing “str” into first text file here: in file Geeks.txtStep 3: Storing the location of end of first text file in the variable “pos” and the closing the file.Step 4: Opening first text file in reading mode and placing the reading pointer at position pos.Step 5: Opening new text file “Geeks2.txt” in writing mode.Step 6: Reading first text file character by character from the end and storing each character to the second text file.Step 7: Shifting the read pointer one alphabet backwards in the text file.Step 8: Closing the text files.Step 9: Reading second text file (you can skip it if not necessary)."
},
{
"code": null,
"e": 27002,
"s": 26922,
"text": "**name of first text file =\"Geeks.txt\"\n**name of second text file=\"Geeks2.txt\"\n"
},
{
"code": null,
"e": 27011,
"s": 27002,
"text": "Example:"
},
{
"code": "#include <conio.h>#include <fstream.h>#include <iostream.h>#include <stdio.h> // function to perform the task// accepts the parameter str as the text to// be stored in text filevoid reverse(char str[]){ char ch; ofstream ofs; // created text file ofs.open(\"Geeks.txt\", ios::out); for (int i = 0; str[i] != '\\0'; i++) { // writing into the file ofs.put(str[i]); } // storing the position of end of the file int pos = ofs.tellp(); ofs.close(); // object for reading the contents of the // first text file ifstream ifs; ifs.open(\"Geeks.txt\", ios::in); // object for writing in to the text file 2 ofstream ofs1; ofs1.open(\"Geeks2.txt\", ios::out); // putting the read pointer to the last alphabet // of the file ifs.seekg(--pos); while (pos >= 0) { // reading from the file 1 ifs.get(ch); // writing to the file 2 ofs1.put(ch); /* shifting read pointer position one alphabet backwards in the text file */ pos--; ifs.seekg(pos); } ifs.close(); ofs1.close(); ifstream ifs1; ifs1.open(\"Geeks2.txt\", ios::in); // file.eof() checks the end of the text file while (!ifs1.eof()) { ifs1.get(ch); cout << ch; } ifs1.close();} // Driver codeint main(){ clrscr(); // sample input 1 cout << \"example 1: (Geeks For Geeks) \\n\"; // passing first text file's text // through reverse function reverse(\"Geeks For Geeks\"); // sample input 2 cout << \"\\n example 2:(reverse)\\n\"; reverse(\"reverse\"); getch(); return 0;}",
"e": 28646,
"s": 27011,
"text": null
},
{
"code": null,
"e": 28654,
"s": 28646,
"text": "Output:"
},
{
"code": null,
"e": 28667,
"s": 28654,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 28671,
"s": 28667,
"text": "C++"
},
{
"code": null,
"e": 28684,
"s": 28671,
"text": "C++ Programs"
},
{
"code": null,
"e": 28688,
"s": 28684,
"text": "CPP"
},
{
"code": null,
"e": 28786,
"s": 28688,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28814,
"s": 28786,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28834,
"s": 28814,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 28867,
"s": 28834,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 28891,
"s": 28867,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 28916,
"s": 28891,
"text": "std::string class in C++"
},
{
"code": null,
"e": 28951,
"s": 28916,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 28995,
"s": 28951,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 29054,
"s": 28995,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 29080,
"s": 29054,
"text": "C++ Program for QuickSort"
}
] |
Python - Characters Index occurrences in String - GeeksforGeeks
|
09 Mar, 2020
Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using set() + regex + list comprehension + replace()The combination of above functions can be used to perform this task. In this, set() is used to get elements whose frequency has to be computed. The task of assembling to dictionary accordingly is performed using regex function and list comprehension.
# Python3 code to demonstrate working of # Characters Index occurrences in String# Using regex + set() + list comprehension + replace()import re # initializing stringtest_str = "Gfg is best for geeks" # printing original stringprint("The original string is : " + test_str) # Characters Index occurrences in String# Using regex + set() + list comprehension + replace()temp = set(test_str.replace(' ', ''))res = {ele: [sub.start() for sub in re.finditer(ele, test_str)] for ele in temp} # printing result print("Characters frequency index dictionary : " + str(res))
The original string is : Gfg is best for geeks
Characters frequency index dictionary : {'g': [2, 16], 'k': [19], 't': [10], 'G': [0], 'b': [7], 'i': [4], 'r': [14], 'f': [1, 12], 's': [5, 9, 20], 'o': [13], 'e': [8, 17, 18]}
Method #2 : Using loop + enumerate()This is yet another way in which this task can be performed. In this we create a dictionary and then iterate the string to map the characters with their respective characters.
# Python3 code to demonstrate working of # Characters Index occurrences in String# Using loop + enumerate()import re # initializing stringtest_str = "Gfg is best for geeks" # printing original stringprint("The original string is : " + test_str) # Characters Index occurrences in String# Using loop + enumerate()res = {ele : [] for ele in test_str} for idx, ele in enumerate(test_str): res[ele].append(idx) # printing result print("Characters frequency index dictionary : " + str(res))
The original string is : Gfg is best for geeks
Characters frequency index dictionary : {'g': [2, 16], 'k': [19], 't': [10], 'G': [0], 'b': [7], 'i': [4], 'r': [14], 'f': [1, 12], 's': [5, 9, 20], 'o': [13], 'e': [8, 17, 18]}
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
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": 26125,
"s": 26097,
"text": "\n09 Mar, 2020"
},
{
"code": null,
"e": 26396,
"s": 26125,
"text": "Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 26711,
"s": 26396,
"text": "Method #1 : Using set() + regex + list comprehension + replace()The combination of above functions can be used to perform this task. In this, set() is used to get elements whose frequency has to be computed. The task of assembling to dictionary accordingly is performed using regex function and list comprehension."
},
{
"code": "# Python3 code to demonstrate working of # Characters Index occurrences in String# Using regex + set() + list comprehension + replace()import re # initializing stringtest_str = \"Gfg is best for geeks\" # printing original stringprint(\"The original string is : \" + test_str) # Characters Index occurrences in String# Using regex + set() + list comprehension + replace()temp = set(test_str.replace(' ', ''))res = {ele: [sub.start() for sub in re.finditer(ele, test_str)] for ele in temp} # printing result print(\"Characters frequency index dictionary : \" + str(res)) ",
"e": 27281,
"s": 26711,
"text": null
},
{
"code": null,
"e": 27507,
"s": 27281,
"text": "The original string is : Gfg is best for geeks\nCharacters frequency index dictionary : {'g': [2, 16], 'k': [19], 't': [10], 'G': [0], 'b': [7], 'i': [4], 'r': [14], 'f': [1, 12], 's': [5, 9, 20], 'o': [13], 'e': [8, 17, 18]}\n"
},
{
"code": null,
"e": 27721,
"s": 27509,
"text": "Method #2 : Using loop + enumerate()This is yet another way in which this task can be performed. In this we create a dictionary and then iterate the string to map the characters with their respective characters."
},
{
"code": "# Python3 code to demonstrate working of # Characters Index occurrences in String# Using loop + enumerate()import re # initializing stringtest_str = \"Gfg is best for geeks\" # printing original stringprint(\"The original string is : \" + test_str) # Characters Index occurrences in String# Using loop + enumerate()res = {ele : [] for ele in test_str} for idx, ele in enumerate(test_str): res[ele].append(idx) # printing result print(\"Characters frequency index dictionary : \" + str(res)) ",
"e": 28217,
"s": 27721,
"text": null
},
{
"code": null,
"e": 28443,
"s": 28217,
"text": "The original string is : Gfg is best for geeks\nCharacters frequency index dictionary : {'g': [2, 16], 'k': [19], 't': [10], 'G': [0], 'b': [7], 'i': [4], 'r': [14], 'f': [1, 12], 's': [5, 9, 20], 'o': [13], 'e': [8, 17, 18]}\n"
},
{
"code": null,
"e": 28466,
"s": 28443,
"text": "Python string-programs"
},
{
"code": null,
"e": 28473,
"s": 28466,
"text": "Python"
},
{
"code": null,
"e": 28489,
"s": 28473,
"text": "Python Programs"
},
{
"code": null,
"e": 28587,
"s": 28489,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28605,
"s": 28587,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28637,
"s": 28605,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28659,
"s": 28637,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28701,
"s": 28659,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28727,
"s": 28701,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28749,
"s": 28727,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28788,
"s": 28749,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28834,
"s": 28788,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28872,
"s": 28834,
"text": "Python | Convert a list to dictionary"
}
] |
R - Matrices - GeeksforGeeks
|
29 Apr, 2022
Matrix is a rectangular arrangement of numbers in rows and columns. In a matrix, as we know rows are the ones that run horizontally and columns are the ones that run vertically. In R programming, matrices are two-dimensional, homogeneous data structures. These are some examples of matrices:
To create a matrix in R you need to use the function called matrix(). The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix.
Note: By default, matrices are in column-wise order.
R
# R program to create a matrix A = matrix( # Taking sequence of elements c(1, 2, 3, 4, 5, 6, 7, 8, 9), # No of rows nrow = 3, # No of columns ncol = 3, # By default matrices are in column-wise order # So this parameter decides how to arrange the matrix byrow = TRUE ) # Naming rowsrownames(A) = c("a", "b", "c") # Naming columnscolnames(A) = c("c", "d", "e") cat("The 3x3 matrix:\n")print(A)
Output:
The 3x3 matrix:
c d e
a 1 2 3
b 4 5 6
c 7 8 9
R allows creation of various different types of matrices with the use of arguments passed to the matrix() function.
Matrix where all rows and columns are filled by a single constant ‘k’: To create such a matrix the syntax is given below:
Syntax: matrix(k, m, n)Parameters: k: the constant m: no of rows n: no of columns
Example:
R
# R program to illustrate# special matrices # Matrix having 3 rows and 3 columns# filled by a single constant 5print(matrix(5, 3, 3))
Output:
[,1] [,2] [,3]
[1,] 5 5 5
[2,] 5 5 5
[3,] 5 5 5
Diagonal matrix: A diagonal matrix is a matrix in which the entries outside the main diagonal are all zero. To create such a matrix the syntax is given below:
Syntax: diag(k, m, n)Parameters: k: the constants/array m: no of rows n: no of columns
Example:
R
# R program to illustrate# special matrices # Diagonal matrix having 3 rows and 3 columns# filled by array of elements (5, 3, 3)print(diag(c(5, 3, 3), 3, 3))
Output:
[,1] [,2] [,3]
[1,] 5 0 0
[2,] 0 3 0
[3,] 0 0 3
Identity matrix: A square matrix in which all the elements of the principal diagonal are ones and all other elements are zeros. To create such a matrix the syntax is given below:
Syntax: diag(k, m, n)Parameters: k: 1 m: no of rows n: no of columns
Example:
R
# R program to illustrate# special matrices # Identity matrix having# 3 rows and 3 columnsprint(diag(1, 3, 3))
Output:
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
Matrix metrics mean once a matrix is created then
How can you know the dimension of the matrix?
How can you know how many rows are there in the matrix?
How many columns are in the matrix?
How many elements are there in the matrix? are the questions we generally wanted to answer.
Example:
R
# R program to illustrate# matrix metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat("The 3x3 matrix:\n")print(A) cat("Dimension of the matrix:\n")print(dim(A)) cat("Number of rows:\n")print(nrow(A)) cat("Number of columns:\n")print(ncol(A)) cat("Number of elements:\n")print(length(A))# ORprint(prod(dim(A)))
Output:
The 3x3 matrix:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Dimension of the matrix:
[1] 3 3
Number of rows:
[1] 3
Number of columns:
[1] 3
Number of elements:
[1] 9
[1] 9
We can access elements in the matrices using the same convention that is followed in data frames. So, you will have a matrix and followed by a square bracket with a comma in between array. Value before the comma is used to access rows and value that is after the comma is used to access columns. Let’s illustrate this by taking a simple R code.Accessing rows:
R
# R program to illustrate# access rows in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat("The 3x3 matrix:\n")print(A) # Accessing first and second rowcat("Accessing first and second row\n")print(A[1:2, ])
Output:
The 3x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
Accessing first and second row
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
Accessing columns:
R
# R program to illustrate# access columns in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat("The 3x3 matrix:\n")print(A) # Accessing first and second columncat("Accessing first and second column\n")print(A[, 1:2])
Output:
The 3x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
Accessing first and second column
[, 1] [, 2]
[1, ] 1 2
[2, ] 4 5
[3, ] 7 8
Accessing elements of a matrix:
R
# R program to illustrate# access an entry in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat("The 3x3 matrix:\n")print(A) # Accessing 2print(A[1, 2]) # Accessing 6print(A[2, 3])
Output:
The 3x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
[1] 2
[1] 6
Accessing Submatrices:We can access submatrix in a matrix using the colon(:) operator.
R
# R program to illustrate# access submatrices in a matrix # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat("The 3x3 matrix:\n")print(A) cat("Accessing the first three rows and the first two columns\n")print(A[1:3, 1:2])
Output:
The 3x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
Accessing the first three rows and the first two columns
[, 1] [, 2]
[1, ] 1 2
[2, ] 4 5
[3, ] 7 8
In R you can modify the elements of the matrices by a direct assignment. Example:
R
# R program to illustrate# editing elements in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat("The 3x3 matrix:\n")print(A) # Editing the 3rd rows and 3rd column element# from 9 to 30# by direct assignmentsA[3, 3] = 30 cat("After edited the matrix\n")print(A)
Output:
The 3x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
After edited the matrix
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 30
Matrix concatenation refers to the merging of rows or columns of an existing matrix. Concatenation of a row: The concatenation of a row to a matrix is done using rbind().
R
# R program to illustrate# concatenation of a row in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat("The 3x3 matrix:\n")print(A) # Creating another 1x3 matrixB = matrix( c(10, 11, 12), nrow = 1, ncol = 3)cat("The 1x3 matrix:\n")print(B) # Add a new row using rbind()C = rbind(A, B) cat("After concatenation of a row:\n")print(C)
Output:
The 3x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
The 1x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 10 11 12
After concatenation of a row:
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
[4, ] 10 11 12
Concatenation of a column: The concatenation of a column to a matrix is done using cbind().
R
# R program to illustrate# concatenation of a column in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat("The 3x3 matrix:\n")print(A) # Creating another 3x1 matrixB = matrix( c(10, 11, 12), nrow = 3, ncol = 1, byrow = TRUE)cat("The 3x1 matrix:\n")print(B) # Add a new column using cbind()C = cbind(A, B) cat("After concatenation of a column:\n")print(C)
Output:
The 3x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
The 3x1 matrix:
[, 1]
[1, ] 10
[2, ] 11
[3, ] 12
After concatenation of a column:
[, 1] [, 2] [, 3] [, 4]
[1, ] 1 2 3 10
[2, ] 4 5 6 11
[3, ] 7 8 9 12
Dimension inconsistency: Note that you have to make sure the consistency of dimensions between the matrix before you do this matrix concatenation.
R
# R program to illustrate# Dimension inconsistency in metrics concatenation # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat("The 3x3 matrix:\n")print(A) # Creating another 1x3 matrixB = matrix( c(10, 11, 12), nrow = 1, ncol = 3,)cat("The 1x3 matrix:\n")print(B) # This will give an error# because of dimension inconsistencyC = cbind(A, B) cat("After concatenation of a column:\n")print(C)
Output:
The 3x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
The 1x3 matrix:
[, 1] [, 2] [, 3]
[1, ] 10 11 12
Error in cbind(A, B) : number of rows of matrices must match (see arg 2)
To delete a row or a column, first of all, you need to access that row or column and then insert a negative sign before that row or column. It indicates that you had to delete that row or column. Row deletion:
R
# R program to illustrate# row deletion in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat("Before deleting the 2nd row\n")print(A) # 2nd-row deletionA = A[-2, ] cat("After deleted the 2nd row\n")print(A)
Output:
Before deleting the 2nd row
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
After deleted the 2nd row
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 7 8 9
Column deletion:
R
# R program to illustrate# column deletion in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat("Before deleting the 2nd column\n")print(A) # 2nd-row deletionA = A[, -2] cat("After deleted the 2nd column\n")print(A)
Output:
Before deleting the 2nd column
[, 1] [, 2] [, 3]
[1, ] 1 2 3
[2, ] 4 5 6
[3, ] 7 8 9
After deleted the 2nd column
[, 1] [, 2]
[1, ] 1 3
[2, ] 4 6
[3, ] 7 9
sweetyty
sravankumar8128
R-Matrix
Programming Language
R Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrow operator -> in C/C++ with Examples
Modulo Operator (%) in C/C++ with Examples
Differences between Procedural and Object Oriented Programming
Structures in C++
Decorators with parameters in Python
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
|
[
{
"code": null,
"e": 30289,
"s": 30261,
"text": "\n29 Apr, 2022"
},
{
"code": null,
"e": 30582,
"s": 30289,
"text": "Matrix is a rectangular arrangement of numbers in rows and columns. In a matrix, as we know rows are the ones that run horizontally and columns are the ones that run vertically. In R programming, matrices are two-dimensional, homogeneous data structures. These are some examples of matrices: "
},
{
"code": null,
"e": 30832,
"s": 30584,
"text": "To create a matrix in R you need to use the function called matrix(). The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix. "
},
{
"code": null,
"e": 30885,
"s": 30832,
"text": "Note: By default, matrices are in column-wise order."
},
{
"code": null,
"e": 30889,
"s": 30887,
"text": "R"
},
{
"code": "# R program to create a matrix A = matrix( # Taking sequence of elements c(1, 2, 3, 4, 5, 6, 7, 8, 9), # No of rows nrow = 3, # No of columns ncol = 3, # By default matrices are in column-wise order # So this parameter decides how to arrange the matrix byrow = TRUE ) # Naming rowsrownames(A) = c(\"a\", \"b\", \"c\") # Naming columnscolnames(A) = c(\"c\", \"d\", \"e\") cat(\"The 3x3 matrix:\\n\")print(A)",
"e": 31327,
"s": 30889,
"text": null
},
{
"code": null,
"e": 31337,
"s": 31327,
"text": "Output: "
},
{
"code": null,
"e": 31385,
"s": 31337,
"text": "The 3x3 matrix:\n c d e\na 1 2 3\nb 4 5 6\nc 7 8 9"
},
{
"code": null,
"e": 31504,
"s": 31387,
"text": "R allows creation of various different types of matrices with the use of arguments passed to the matrix() function. "
},
{
"code": null,
"e": 31627,
"s": 31504,
"text": "Matrix where all rows and columns are filled by a single constant ‘k’: To create such a matrix the syntax is given below: "
},
{
"code": null,
"e": 31711,
"s": 31627,
"text": "Syntax: matrix(k, m, n)Parameters: k: the constant m: no of rows n: no of columns "
},
{
"code": null,
"e": 31722,
"s": 31711,
"text": "Example: "
},
{
"code": null,
"e": 31724,
"s": 31722,
"text": "R"
},
{
"code": "# R program to illustrate# special matrices # Matrix having 3 rows and 3 columns# filled by a single constant 5print(matrix(5, 3, 3))",
"e": 31858,
"s": 31724,
"text": null
},
{
"code": null,
"e": 31868,
"s": 31858,
"text": "Output: "
},
{
"code": null,
"e": 31948,
"s": 31868,
"text": " [,1] [,2] [,3]\n[1,] 5 5 5\n[2,] 5 5 5\n[3,] 5 5 5"
},
{
"code": null,
"e": 32110,
"s": 31950,
"text": "Diagonal matrix: A diagonal matrix is a matrix in which the entries outside the main diagonal are all zero. To create such a matrix the syntax is given below: "
},
{
"code": null,
"e": 32199,
"s": 32110,
"text": "Syntax: diag(k, m, n)Parameters: k: the constants/array m: no of rows n: no of columns "
},
{
"code": null,
"e": 32210,
"s": 32199,
"text": "Example: "
},
{
"code": null,
"e": 32212,
"s": 32210,
"text": "R"
},
{
"code": "# R program to illustrate# special matrices # Diagonal matrix having 3 rows and 3 columns# filled by array of elements (5, 3, 3)print(diag(c(5, 3, 3), 3, 3))",
"e": 32370,
"s": 32212,
"text": null
},
{
"code": null,
"e": 32380,
"s": 32370,
"text": "Output: "
},
{
"code": null,
"e": 32460,
"s": 32380,
"text": " [,1] [,2] [,3]\n[1,] 5 0 0\n[2,] 0 3 0\n[3,] 0 0 3"
},
{
"code": null,
"e": 32642,
"s": 32462,
"text": "Identity matrix: A square matrix in which all the elements of the principal diagonal are ones and all other elements are zeros. To create such a matrix the syntax is given below: "
},
{
"code": null,
"e": 32713,
"s": 32642,
"text": "Syntax: diag(k, m, n)Parameters: k: 1 m: no of rows n: no of columns "
},
{
"code": null,
"e": 32724,
"s": 32713,
"text": "Example: "
},
{
"code": null,
"e": 32726,
"s": 32724,
"text": "R"
},
{
"code": "# R program to illustrate# special matrices # Identity matrix having# 3 rows and 3 columnsprint(diag(1, 3, 3))",
"e": 32837,
"s": 32726,
"text": null
},
{
"code": null,
"e": 32847,
"s": 32837,
"text": "Output: "
},
{
"code": null,
"e": 32927,
"s": 32847,
"text": " [,1] [,2] [,3]\n[1,] 1 0 0\n[2,] 0 1 0\n[3,] 0 0 1"
},
{
"code": null,
"e": 32983,
"s": 32931,
"text": "Matrix metrics mean once a matrix is created then "
},
{
"code": null,
"e": 33029,
"s": 32983,
"text": "How can you know the dimension of the matrix?"
},
{
"code": null,
"e": 33085,
"s": 33029,
"text": "How can you know how many rows are there in the matrix?"
},
{
"code": null,
"e": 33121,
"s": 33085,
"text": "How many columns are in the matrix?"
},
{
"code": null,
"e": 33213,
"s": 33121,
"text": "How many elements are there in the matrix? are the questions we generally wanted to answer."
},
{
"code": null,
"e": 33224,
"s": 33213,
"text": "Example: "
},
{
"code": null,
"e": 33226,
"s": 33224,
"text": "R"
},
{
"code": "# R program to illustrate# matrix metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat(\"The 3x3 matrix:\\n\")print(A) cat(\"Dimension of the matrix:\\n\")print(dim(A)) cat(\"Number of rows:\\n\")print(nrow(A)) cat(\"Number of columns:\\n\")print(ncol(A)) cat(\"Number of elements:\\n\")print(length(A))# ORprint(prod(dim(A)))",
"e": 33630,
"s": 33226,
"text": null
},
{
"code": null,
"e": 33640,
"s": 33630,
"text": "Output: "
},
{
"code": null,
"e": 33848,
"s": 33640,
"text": "The 3x3 matrix:\n [,1] [,2] [,3]\n[1,] 1 2 3\n[2,] 4 5 6\n[3,] 7 8 9\nDimension of the matrix:\n[1] 3 3\nNumber of rows:\n[1] 3\nNumber of columns:\n[1] 3\nNumber of elements:\n[1] 9\n[1] 9"
},
{
"code": null,
"e": 34212,
"s": 33850,
"text": "We can access elements in the matrices using the same convention that is followed in data frames. So, you will have a matrix and followed by a square bracket with a comma in between array. Value before the comma is used to access rows and value that is after the comma is used to access columns. Let’s illustrate this by taking a simple R code.Accessing rows: "
},
{
"code": null,
"e": 34214,
"s": 34212,
"text": "R"
},
{
"code": "# R program to illustrate# access rows in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat(\"The 3x3 matrix:\\n\")print(A) # Accessing first and second rowcat(\"Accessing first and second row\\n\")print(A[1:2, ])",
"e": 34517,
"s": 34214,
"text": null
},
{
"code": null,
"e": 34527,
"s": 34517,
"text": "Output: "
},
{
"code": null,
"e": 34726,
"s": 34527,
"text": "The 3x3 matrix:\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 9\n\nAccessing first and second row\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6"
},
{
"code": null,
"e": 34747,
"s": 34726,
"text": "Accessing columns: "
},
{
"code": null,
"e": 34749,
"s": 34747,
"text": "R"
},
{
"code": "# R program to illustrate# access columns in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat(\"The 3x3 matrix:\\n\")print(A) # Accessing first and second columncat(\"Accessing first and second column\\n\")print(A[, 1:2])",
"e": 35061,
"s": 34749,
"text": null
},
{
"code": null,
"e": 35071,
"s": 35061,
"text": "Output: "
},
{
"code": null,
"e": 35273,
"s": 35071,
"text": "The 3x3 matrix:\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 9\n\nAccessing first and second column\n [, 1] [, 2]\n[1, ] 1 2\n[2, ] 4 5\n[3, ] 7 8"
},
{
"code": null,
"e": 35307,
"s": 35273,
"text": "Accessing elements of a matrix: "
},
{
"code": null,
"e": 35309,
"s": 35307,
"text": "R"
},
{
"code": "# R program to illustrate# access an entry in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat(\"The 3x3 matrix:\\n\")print(A) # Accessing 2print(A[1, 2]) # Accessing 6print(A[2, 3])",
"e": 35585,
"s": 35309,
"text": null
},
{
"code": null,
"e": 35595,
"s": 35585,
"text": "Output: "
},
{
"code": null,
"e": 35710,
"s": 35595,
"text": "The 3x3 matrix:\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 9\n\n[1] 2\n[1] 6"
},
{
"code": null,
"e": 35799,
"s": 35710,
"text": "Accessing Submatrices:We can access submatrix in a matrix using the colon(:) operator. "
},
{
"code": null,
"e": 35801,
"s": 35799,
"text": "R"
},
{
"code": "# R program to illustrate# access submatrices in a matrix # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat(\"The 3x3 matrix:\\n\")print(A) cat(\"Accessing the first three rows and the first two columns\\n\")print(A[1:3, 1:2])",
"e": 36109,
"s": 35801,
"text": null
},
{
"code": null,
"e": 36119,
"s": 36109,
"text": "Output: "
},
{
"code": null,
"e": 36344,
"s": 36119,
"text": "The 3x3 matrix:\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 9\n\nAccessing the first three rows and the first two columns\n [, 1] [, 2]\n[1, ] 1 2\n[2, ] 4 5\n[3, ] 7 8"
},
{
"code": null,
"e": 36430,
"s": 36346,
"text": "In R you can modify the elements of the matrices by a direct assignment. Example: "
},
{
"code": null,
"e": 36432,
"s": 36430,
"text": "R"
},
{
"code": "# R program to illustrate# editing elements in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat(\"The 3x3 matrix:\\n\")print(A) # Editing the 3rd rows and 3rd column element# from 9 to 30# by direct assignmentsA[3, 3] = 30 cat(\"After edited the matrix\\n\")print(A)",
"e": 36789,
"s": 36432,
"text": null
},
{
"code": null,
"e": 36799,
"s": 36789,
"text": "Output: "
},
{
"code": null,
"e": 37012,
"s": 36799,
"text": "The 3x3 matrix:\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 9\n\nAfter edited the matrix\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 30"
},
{
"code": null,
"e": 37187,
"s": 37014,
"text": "Matrix concatenation refers to the merging of rows or columns of an existing matrix. Concatenation of a row: The concatenation of a row to a matrix is done using rbind(). "
},
{
"code": null,
"e": 37189,
"s": 37187,
"text": "R"
},
{
"code": "# R program to illustrate# concatenation of a row in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat(\"The 3x3 matrix:\\n\")print(A) # Creating another 1x3 matrixB = matrix( c(10, 11, 12), nrow = 1, ncol = 3)cat(\"The 1x3 matrix:\\n\")print(B) # Add a new row using rbind()C = rbind(A, B) cat(\"After concatenation of a row:\\n\")print(C)",
"e": 37619,
"s": 37189,
"text": null
},
{
"code": null,
"e": 37629,
"s": 37619,
"text": "Output: "
},
{
"code": null,
"e": 37930,
"s": 37629,
"text": "The 3x3 matrix:\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 9\n\nThe 1x3 matrix:\n [, 1] [, 2] [, 3]\n[1, ] 10 11 12\n\nAfter concatenation of a row:\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 9\n[4, ] 10 11 12"
},
{
"code": null,
"e": 38024,
"s": 37930,
"text": "Concatenation of a column: The concatenation of a column to a matrix is done using cbind(). "
},
{
"code": null,
"e": 38026,
"s": 38024,
"text": "R"
},
{
"code": "# R program to illustrate# concatenation of a column in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat(\"The 3x3 matrix:\\n\")print(A) # Creating another 3x1 matrixB = matrix( c(10, 11, 12), nrow = 3, ncol = 1, byrow = TRUE)cat(\"The 3x1 matrix:\\n\")print(B) # Add a new column using cbind()C = cbind(A, B) cat(\"After concatenation of a column:\\n\")print(C)",
"e": 38480,
"s": 38026,
"text": null
},
{
"code": null,
"e": 38490,
"s": 38480,
"text": "Output: "
},
{
"code": null,
"e": 38794,
"s": 38490,
"text": "The 3x3 matrix:\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 9\n\nThe 3x1 matrix:\n [, 1]\n[1, ] 10\n[2, ] 11\n[3, ] 12\n\nAfter concatenation of a column:\n [, 1] [, 2] [, 3] [, 4]\n[1, ] 1 2 3 10\n[2, ] 4 5 6 11\n[3, ] 7 8 9 12"
},
{
"code": null,
"e": 38943,
"s": 38794,
"text": "Dimension inconsistency: Note that you have to make sure the consistency of dimensions between the matrix before you do this matrix concatenation. "
},
{
"code": null,
"e": 38945,
"s": 38943,
"text": "R"
},
{
"code": "# R program to illustrate# Dimension inconsistency in metrics concatenation # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat(\"The 3x3 matrix:\\n\")print(A) # Creating another 1x3 matrixB = matrix( c(10, 11, 12), nrow = 1, ncol = 3,)cat(\"The 1x3 matrix:\\n\")print(B) # This will give an error# because of dimension inconsistencyC = cbind(A, B) cat(\"After concatenation of a column:\\n\")print(C)",
"e": 39426,
"s": 38945,
"text": null
},
{
"code": null,
"e": 39436,
"s": 39426,
"text": "Output: "
},
{
"code": null,
"e": 39673,
"s": 39436,
"text": "The 3x3 matrix:\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 9\n\nThe 1x3 matrix:\n [, 1] [, 2] [, 3]\n[1, ] 10 11 12\n\nError in cbind(A, B) : number of rows of matrices must match (see arg 2)"
},
{
"code": null,
"e": 39887,
"s": 39675,
"text": "To delete a row or a column, first of all, you need to access that row or column and then insert a negative sign before that row or column. It indicates that you had to delete that row or column. Row deletion: "
},
{
"code": null,
"e": 39889,
"s": 39887,
"text": "R"
},
{
"code": "# R program to illustrate# row deletion in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat(\"Before deleting the 2nd row\\n\")print(A) # 2nd-row deletionA = A[-2, ] cat(\"After deleted the 2nd row\\n\")print(A)",
"e": 40191,
"s": 39889,
"text": null
},
{
"code": null,
"e": 40201,
"s": 40191,
"text": "Output: "
},
{
"code": null,
"e": 40407,
"s": 40201,
"text": "Before deleting the 2nd row\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 9\n\nAfter deleted the 2nd row\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 7 8 9"
},
{
"code": null,
"e": 40426,
"s": 40407,
"text": "Column deletion: "
},
{
"code": null,
"e": 40428,
"s": 40426,
"text": "R"
},
{
"code": "# R program to illustrate# column deletion in metrics # Create a 3x3 matrixA = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE )cat(\"Before deleting the 2nd column\\n\")print(A) # 2nd-row deletionA = A[, -2] cat(\"After deleted the 2nd column\\n\")print(A)",
"e": 40739,
"s": 40428,
"text": null
},
{
"code": null,
"e": 40749,
"s": 40739,
"text": "Output: "
},
{
"code": null,
"e": 40961,
"s": 40749,
"text": "Before deleting the 2nd column\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 4 5 6\n[3, ] 7 8 9\n\nAfter deleted the 2nd column\n [, 1] [, 2]\n[1, ] 1 3\n[2, ] 4 6\n[3, ] 7 9"
},
{
"code": null,
"e": 40972,
"s": 40963,
"text": "sweetyty"
},
{
"code": null,
"e": 40988,
"s": 40972,
"text": "sravankumar8128"
},
{
"code": null,
"e": 40997,
"s": 40988,
"text": "R-Matrix"
},
{
"code": null,
"e": 41018,
"s": 40997,
"text": "Programming Language"
},
{
"code": null,
"e": 41029,
"s": 41018,
"text": "R Language"
},
{
"code": null,
"e": 41045,
"s": 41029,
"text": "Write From Home"
},
{
"code": null,
"e": 41143,
"s": 41045,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41184,
"s": 41143,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 41227,
"s": 41184,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 41290,
"s": 41227,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 41308,
"s": 41290,
"text": "Structures in C++"
},
{
"code": null,
"e": 41345,
"s": 41308,
"text": "Decorators with parameters in Python"
},
{
"code": null,
"e": 41390,
"s": 41345,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 41448,
"s": 41390,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 41500,
"s": 41448,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 41532,
"s": 41500,
"text": "Loops in R (for, while, repeat)"
}
] |
Double isNaN() method in Java with examples - GeeksforGeeks
|
26 Oct, 2018
The isNaN() method of Java Double class is a built in method in Java returns true if this Double value or the specified double value is Not-a-Number (NaN), or false otherwise.
Syntax:
public boolean isNaN()
or
public static boolean isNaN(double val)
Parameters: The function accepts a single parameter val which specifies the value to be checked when called directly with the Double class as static method. The parameter is not required when the method is used as instance method.
Return Value: It returns true if the val is NaN else it return false.
Below programs illustrate isNaN() method in Java:
Program 1:
// Java code to demonstrate// Double isNaN() method// without parameter class GFG { public static void main(String[] args) { // first example Double f1 = new Double(1.0 / 0.0); boolean res = f1.isNaN(); // printing the output if (res) System.out.println(f1 + " is NaN"); else System.out.println(f1 + " is not NaN"); // second example f1 = new Double(0.0 / 0.0); res = f1.isNaN(); // printing the output if (res) System.out.println(f1 + " is NaN"); else System.out.println(f1 + " is not NaN"); }}
Infinity is not NaN
NaN is NaN
Program 2:
// Java code to demonstrate// Double isNaN() method// with parameter class GFG { public static void main(String[] args) { // first example Double f1 = new Double(1.0 / 0.0); boolean res = f1.isNaN(f1); // printing the output if (res) System.out.println(f1 + " is NaN"); else System.out.println(f1 + " is not NaN"); // second example f1 = new Double(0.0 / 0.0); res = f1.isNaN(f1); // printing the output if (res) System.out.println(f1 + " is NaN"); else System.out.println(f1 + " is not NaN"); }}
Infinity is not NaN
NaN is NaN
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#isNaN()
java-basics
Java-Double
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 25691,
"s": 25663,
"text": "\n26 Oct, 2018"
},
{
"code": null,
"e": 25867,
"s": 25691,
"text": "The isNaN() method of Java Double class is a built in method in Java returns true if this Double value or the specified double value is Not-a-Number (NaN), or false otherwise."
},
{
"code": null,
"e": 25875,
"s": 25867,
"text": "Syntax:"
},
{
"code": null,
"e": 25949,
"s": 25875,
"text": "public boolean isNaN()\n or\npublic static boolean isNaN(double val)"
},
{
"code": null,
"e": 26180,
"s": 25949,
"text": "Parameters: The function accepts a single parameter val which specifies the value to be checked when called directly with the Double class as static method. The parameter is not required when the method is used as instance method."
},
{
"code": null,
"e": 26250,
"s": 26180,
"text": "Return Value: It returns true if the val is NaN else it return false."
},
{
"code": null,
"e": 26300,
"s": 26250,
"text": "Below programs illustrate isNaN() method in Java:"
},
{
"code": null,
"e": 26311,
"s": 26300,
"text": "Program 1:"
},
{
"code": "// Java code to demonstrate// Double isNaN() method// without parameter class GFG { public static void main(String[] args) { // first example Double f1 = new Double(1.0 / 0.0); boolean res = f1.isNaN(); // printing the output if (res) System.out.println(f1 + \" is NaN\"); else System.out.println(f1 + \" is not NaN\"); // second example f1 = new Double(0.0 / 0.0); res = f1.isNaN(); // printing the output if (res) System.out.println(f1 + \" is NaN\"); else System.out.println(f1 + \" is not NaN\"); }}",
"e": 26957,
"s": 26311,
"text": null
},
{
"code": null,
"e": 26989,
"s": 26957,
"text": "Infinity is not NaN\nNaN is NaN\n"
},
{
"code": null,
"e": 27000,
"s": 26989,
"text": "Program 2:"
},
{
"code": "// Java code to demonstrate// Double isNaN() method// with parameter class GFG { public static void main(String[] args) { // first example Double f1 = new Double(1.0 / 0.0); boolean res = f1.isNaN(f1); // printing the output if (res) System.out.println(f1 + \" is NaN\"); else System.out.println(f1 + \" is not NaN\"); // second example f1 = new Double(0.0 / 0.0); res = f1.isNaN(f1); // printing the output if (res) System.out.println(f1 + \" is NaN\"); else System.out.println(f1 + \" is not NaN\"); }}",
"e": 27647,
"s": 27000,
"text": null
},
{
"code": null,
"e": 27679,
"s": 27647,
"text": "Infinity is not NaN\nNaN is NaN\n"
},
{
"code": null,
"e": 27761,
"s": 27679,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#isNaN()"
},
{
"code": null,
"e": 27773,
"s": 27761,
"text": "java-basics"
},
{
"code": null,
"e": 27785,
"s": 27773,
"text": "Java-Double"
},
{
"code": null,
"e": 27800,
"s": 27785,
"text": "Java-Functions"
},
{
"code": null,
"e": 27818,
"s": 27800,
"text": "Java-lang package"
},
{
"code": null,
"e": 27823,
"s": 27818,
"text": "Java"
},
{
"code": null,
"e": 27828,
"s": 27823,
"text": "Java"
},
{
"code": null,
"e": 27926,
"s": 27828,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27977,
"s": 27926,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28007,
"s": 27977,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28022,
"s": 28007,
"text": "Stream In Java"
},
{
"code": null,
"e": 28041,
"s": 28022,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28072,
"s": 28041,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28090,
"s": 28072,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 28122,
"s": 28090,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28142,
"s": 28122,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28174,
"s": 28142,
"text": "Multidimensional Arrays in Java"
}
] |
Count the Number of matching characters in a pair of strings - GeeksforGeeks
|
21 May, 2021
Given a pair of non-empty strings str1 and str2, the task is to count the number of matching characters in these strings. Consider the single count for the character which have duplicates in the strings.Examples:
Input: str1 = “abcdef”, str2 = “defghia” Output: 4 Matching characters are: a, d, e, fInput: str1 = “aabcddekll12”, str2 = “bb22ll@55k” Output: 5 Matching characters are: b, 1, 2, @, k
Approach:
Initialize a counter variable with 0. Iterate over the first string from the starting character to ending character. If the character extracted from the first string is found in the second string, then increment the value of the counter by 1.The final answer will be count/2 as the duplicates are not being considered.Output the value of counter
Initialize a counter variable with 0.
Iterate over the first string from the starting character to ending character.
If the character extracted from the first string is found in the second string, then increment the value of the counter by 1.
The final answer will be count/2 as the duplicates are not being considered.
Output the value of counter
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ code to count number of matching// characters in a pair of strings #include <bits/stdc++.h>using namespace std; // Function to count the matching charactersvoid count(string str1, string str2){ int c = 0, j = 0; // Traverse the string 1 char by char for (int i = 0; i < str1.length(); i++) { // This will check if str1[i] // is present in str2 or not // str2.find(str1[i]) returns -1 if not found // otherwise it returns the starting occurrence // index of that character in str2 if (str2.find(str1[i]) >= 0 and j == str1.find(str1[i])) c += 1; j += 1; } cout << "No. of matching characters are: " << c / 2;} // Driver codeint main(){ string str1 = "aabcddekll12@"; string str2 = "bb2211@55k"; count(str1, str2);}
// Java code to count number of matching// characters in a pair of stringsclass GFG{ // Function to count the matching characters static void count(String str1, String str2) { int c = 0, j = 0; // Traverse the string 1 char by char for (int i = 0; i < str1.length(); i++) { // This will check if str1[i] // is present in str2 or not // str2.find(str1[i]) returns -1 if not found // otherwise it returns the starting occurrence // index of that character in str2 if (str2. indexOf(str1.charAt(i)) >= 0) { c += 1; } } System.out.println("No. of matching characters are: " + c); } // Driver code public static void main (String[] args) { String str1 = "aabcddekll12@"; String str2 = "bb2211@55k"; count(str1, str2); }} // This code is contributed by AnkitRai01
# Python3 code to count number of matching# characters in a pair of strings # Function to count the matching charactersdef count(str1, str2) : c = 0; j = 0; # Traverse the string 1 char by char for i in range(len(str1)) : # This will check if str1[i] # is present in str2 or not # str2.find(str1[i]) returns -1 if not found # otherwise it returns the starting occurrence # index of that character in str2 if str1[i] in str2 : c += 1; #print(str1[i]) j += 1; print("No. of matching characters are: ", c ); # Driver codeif __name__ == "__main__" : str1 = "aabcddekll12@"; str2 = "bb2211@55k"; count(str1, str2); # This code is contributed by AnkitRai01
// C# code to count number of matching// characters in a pair of stringsusing System; class GFG{ // Function to count the matching characters static void count(string str1, string str2) { int c = 0, j = 0; // Traverse the string 1 char by char for (int i = 0; i < str1.Length; i++) { // This will check if str1[i] // is present in str2 or not // str2.find(str1[i]) returns -1 if not found // otherwise it returns the starting occurrence // index of that character in str2 if (str2.IndexOf(str1[i]) >= 0) { c += 1; } } Console.WriteLine("No. of matching characters are: " + c); } // Driver code public static void Main() { string str1 = "aabcddekll12@"; string str2 = "bb2211@55k"; count(str1, str2); }} // This code is contributed by AnkitRai01
<script> // JavaScript code to count number of matching// characters in a pair of strings // Function to count the matching charactersfunction count(str1, str2){ var c = 0; // Traverse the string 1 char by char for (var i = 0; i < str1.length; i++) { // This will check if str1[i] // is present in str2 or not // str2.find(str1[i]) returns -1 if not found // otherwise it returns the starting occurrence // index of that character in str2 if (str2.includes(str1[i])) c += 1; } document.write( "No. of matching characters are: " + + parseInt(c));} // Driver code var str1 = "aabcddekll12@";var str2 = "bb2211@55k";count(str1, str2); </script>
No. of matching characters are: 5
ankthon
importantly
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Print all the duplicates in the input string
Vigenère Cipher
sprintf() in C
String class in Java | Set 1
Convert character array to string in C++
Print all subsequences of a string
Program to count occurrence of a given character in a string
How to Append a Character to a String in C
Naive algorithm for Pattern Searching
|
[
{
"code": null,
"e": 26098,
"s": 26070,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 26313,
"s": 26098,
"text": "Given a pair of non-empty strings str1 and str2, the task is to count the number of matching characters in these strings. Consider the single count for the character which have duplicates in the strings.Examples: "
},
{
"code": null,
"e": 26500,
"s": 26313,
"text": "Input: str1 = “abcdef”, str2 = “defghia” Output: 4 Matching characters are: a, d, e, fInput: str1 = “aabcddekll12”, str2 = “bb22ll@55k” Output: 5 Matching characters are: b, 1, 2, @, k "
},
{
"code": null,
"e": 26514,
"s": 26502,
"text": "Approach: "
},
{
"code": null,
"e": 26860,
"s": 26514,
"text": "Initialize a counter variable with 0. Iterate over the first string from the starting character to ending character. If the character extracted from the first string is found in the second string, then increment the value of the counter by 1.The final answer will be count/2 as the duplicates are not being considered.Output the value of counter"
},
{
"code": null,
"e": 26899,
"s": 26860,
"text": "Initialize a counter variable with 0. "
},
{
"code": null,
"e": 26979,
"s": 26899,
"text": "Iterate over the first string from the starting character to ending character. "
},
{
"code": null,
"e": 27105,
"s": 26979,
"text": "If the character extracted from the first string is found in the second string, then increment the value of the counter by 1."
},
{
"code": null,
"e": 27182,
"s": 27105,
"text": "The final answer will be count/2 as the duplicates are not being considered."
},
{
"code": null,
"e": 27210,
"s": 27182,
"text": "Output the value of counter"
},
{
"code": null,
"e": 27263,
"s": 27210,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 27267,
"s": 27263,
"text": "C++"
},
{
"code": null,
"e": 27272,
"s": 27267,
"text": "Java"
},
{
"code": null,
"e": 27280,
"s": 27272,
"text": "Python3"
},
{
"code": null,
"e": 27283,
"s": 27280,
"text": "C#"
},
{
"code": null,
"e": 27294,
"s": 27283,
"text": "Javascript"
},
{
"code": "// C++ code to count number of matching// characters in a pair of strings #include <bits/stdc++.h>using namespace std; // Function to count the matching charactersvoid count(string str1, string str2){ int c = 0, j = 0; // Traverse the string 1 char by char for (int i = 0; i < str1.length(); i++) { // This will check if str1[i] // is present in str2 or not // str2.find(str1[i]) returns -1 if not found // otherwise it returns the starting occurrence // index of that character in str2 if (str2.find(str1[i]) >= 0 and j == str1.find(str1[i])) c += 1; j += 1; } cout << \"No. of matching characters are: \" << c / 2;} // Driver codeint main(){ string str1 = \"aabcddekll12@\"; string str2 = \"bb2211@55k\"; count(str1, str2);}",
"e": 28121,
"s": 27294,
"text": null
},
{
"code": "// Java code to count number of matching// characters in a pair of stringsclass GFG{ // Function to count the matching characters static void count(String str1, String str2) { int c = 0, j = 0; // Traverse the string 1 char by char for (int i = 0; i < str1.length(); i++) { // This will check if str1[i] // is present in str2 or not // str2.find(str1[i]) returns -1 if not found // otherwise it returns the starting occurrence // index of that character in str2 if (str2. indexOf(str1.charAt(i)) >= 0) { c += 1; } } System.out.println(\"No. of matching characters are: \" + c); } // Driver code public static void main (String[] args) { String str1 = \"aabcddekll12@\"; String str2 = \"bb2211@55k\"; count(str1, str2); }} // This code is contributed by AnkitRai01",
"e": 29086,
"s": 28121,
"text": null
},
{
"code": "# Python3 code to count number of matching# characters in a pair of strings # Function to count the matching charactersdef count(str1, str2) : c = 0; j = 0; # Traverse the string 1 char by char for i in range(len(str1)) : # This will check if str1[i] # is present in str2 or not # str2.find(str1[i]) returns -1 if not found # otherwise it returns the starting occurrence # index of that character in str2 if str1[i] in str2 : c += 1; #print(str1[i]) j += 1; print(\"No. of matching characters are: \", c ); # Driver codeif __name__ == \"__main__\" : str1 = \"aabcddekll12@\"; str2 = \"bb2211@55k\"; count(str1, str2); # This code is contributed by AnkitRai01",
"e": 29847,
"s": 29086,
"text": null
},
{
"code": "// C# code to count number of matching// characters in a pair of stringsusing System; class GFG{ // Function to count the matching characters static void count(string str1, string str2) { int c = 0, j = 0; // Traverse the string 1 char by char for (int i = 0; i < str1.Length; i++) { // This will check if str1[i] // is present in str2 or not // str2.find(str1[i]) returns -1 if not found // otherwise it returns the starting occurrence // index of that character in str2 if (str2.IndexOf(str1[i]) >= 0) { c += 1; } } Console.WriteLine(\"No. of matching characters are: \" + c); } // Driver code public static void Main() { string str1 = \"aabcddekll12@\"; string str2 = \"bb2211@55k\"; count(str1, str2); }} // This code is contributed by AnkitRai01",
"e": 30799,
"s": 29847,
"text": null
},
{
"code": "<script> // JavaScript code to count number of matching// characters in a pair of strings // Function to count the matching charactersfunction count(str1, str2){ var c = 0; // Traverse the string 1 char by char for (var i = 0; i < str1.length; i++) { // This will check if str1[i] // is present in str2 or not // str2.find(str1[i]) returns -1 if not found // otherwise it returns the starting occurrence // index of that character in str2 if (str2.includes(str1[i])) c += 1; } document.write( \"No. of matching characters are: \" + + parseInt(c));} // Driver code var str1 = \"aabcddekll12@\";var str2 = \"bb2211@55k\";count(str1, str2); </script>",
"e": 31520,
"s": 30799,
"text": null
},
{
"code": null,
"e": 31554,
"s": 31520,
"text": "No. of matching characters are: 5"
},
{
"code": null,
"e": 31564,
"s": 31556,
"text": "ankthon"
},
{
"code": null,
"e": 31576,
"s": 31564,
"text": "importantly"
},
{
"code": null,
"e": 31584,
"s": 31576,
"text": "Strings"
},
{
"code": null,
"e": 31592,
"s": 31584,
"text": "Strings"
},
{
"code": null,
"e": 31690,
"s": 31592,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31735,
"s": 31690,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 31780,
"s": 31735,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 31797,
"s": 31780,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 31812,
"s": 31797,
"text": "sprintf() in C"
},
{
"code": null,
"e": 31841,
"s": 31812,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 31882,
"s": 31841,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 31917,
"s": 31882,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 31978,
"s": 31917,
"text": "Program to count occurrence of a given character in a string"
},
{
"code": null,
"e": 32021,
"s": 31978,
"text": "How to Append a Character to a String in C"
}
] |
How to Append Two Tables and Put the Result in a Table in SQL? - GeeksforGeeks
|
14 Sep, 2021
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, SQL Server, PostGre, etc. In this article, we will learn how to append two tables and store the result into a new table using UNION, UNION ALL.
Syntax:
SELECT column_one, column_two,..column_N INTO Table_name FROM table_name
UNION SELECT column_one,column_two,column_three,.. column_N FROM table_name;
Syntax:
SELECT column_one, column_two,column_three,.. column_N INTO Table_name FROM
table_name UNION SELECT column_one, column_two, column_three,..column_N
FROM table_name;
The difference between Union and Union All is UNION doesn’t include duplicates, but UNION ALL includes duplicates too. Both are used with similar syntax.
Consider the following tables of two departmental stores data
Database: Shop1
Command used to create the table
Query:
CREATE TABLE Shop1(Item_Id int,Name varchar(20),Count int)
Output:
Database: Shop2
Command used to create the table
Query:
CREATE TABLE Shop2(Item_Id int,Name varchar(20),Count int)
Output:
Method 1: Using UNION Keyword
In order to join the two tables i.e. Shop1 and Shop2 we run the following command:
Query:
SELECT * INTO joined FROM Shop1 UNION SELECT * FROM Shop2;
The above command joins Shop1 and Shop2 into a new table joined which is as follows and can be viewed by the following command:
Query:
SELECT * FROM joined;
So the joined table doesn’t include duplicates as we have used UNION Keyword
Here is the output when we execute the query
Output:
Method 2: Using UNION ALL Keyword
Query:
SELECT * INTO joined2 FROM Shop1 UNION ALL SELECT * FROM Shop2;
The above command creates a new table names joined2 which includes all the values of Shop1 and Shop2.
We run the following command for viewing the table
Query:
SELECT * FROM joined2;
Here is the output when we execute the query.
Output:
Picked
SQL-Query
How To
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
SQL | DDL, DQL, DML, DCL and TCL Commands
SQL | WITH clause
SQL | Join (Inner, Left, Right and Full Joins)
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
|
[
{
"code": null,
"e": 26197,
"s": 26169,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 26507,
"s": 26197,
"text": "Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, SQL Server, PostGre, etc. In this article, we will learn how to append two tables and store the result into a new table using UNION, UNION ALL."
},
{
"code": null,
"e": 26515,
"s": 26507,
"text": "Syntax:"
},
{
"code": null,
"e": 26666,
"s": 26515,
"text": "SELECT column_one, column_two,..column_N INTO Table_name FROM table_name\nUNION SELECT column_one,column_two,column_three,.. column_N FROM table_name;"
},
{
"code": null,
"e": 26674,
"s": 26666,
"text": "Syntax:"
},
{
"code": null,
"e": 26840,
"s": 26674,
"text": "SELECT column_one, column_two,column_three,.. column_N INTO Table_name FROM\ntable_name UNION SELECT column_one, column_two, column_three,..column_N\n FROM table_name;"
},
{
"code": null,
"e": 26994,
"s": 26840,
"text": "The difference between Union and Union All is UNION doesn’t include duplicates, but UNION ALL includes duplicates too. Both are used with similar syntax."
},
{
"code": null,
"e": 27056,
"s": 26994,
"text": "Consider the following tables of two departmental stores data"
},
{
"code": null,
"e": 27072,
"s": 27056,
"text": "Database: Shop1"
},
{
"code": null,
"e": 27105,
"s": 27072,
"text": "Command used to create the table"
},
{
"code": null,
"e": 27112,
"s": 27105,
"text": "Query:"
},
{
"code": null,
"e": 27171,
"s": 27112,
"text": "CREATE TABLE Shop1(Item_Id int,Name varchar(20),Count int)"
},
{
"code": null,
"e": 27179,
"s": 27171,
"text": "Output:"
},
{
"code": null,
"e": 27195,
"s": 27179,
"text": "Database: Shop2"
},
{
"code": null,
"e": 27228,
"s": 27195,
"text": "Command used to create the table"
},
{
"code": null,
"e": 27235,
"s": 27228,
"text": "Query:"
},
{
"code": null,
"e": 27294,
"s": 27235,
"text": "CREATE TABLE Shop2(Item_Id int,Name varchar(20),Count int)"
},
{
"code": null,
"e": 27302,
"s": 27294,
"text": "Output:"
},
{
"code": null,
"e": 27332,
"s": 27302,
"text": "Method 1: Using UNION Keyword"
},
{
"code": null,
"e": 27415,
"s": 27332,
"text": "In order to join the two tables i.e. Shop1 and Shop2 we run the following command:"
},
{
"code": null,
"e": 27422,
"s": 27415,
"text": "Query:"
},
{
"code": null,
"e": 27481,
"s": 27422,
"text": "SELECT * INTO joined FROM Shop1 UNION SELECT * FROM Shop2;"
},
{
"code": null,
"e": 27609,
"s": 27481,
"text": "The above command joins Shop1 and Shop2 into a new table joined which is as follows and can be viewed by the following command:"
},
{
"code": null,
"e": 27616,
"s": 27609,
"text": "Query:"
},
{
"code": null,
"e": 27638,
"s": 27616,
"text": "SELECT * FROM joined;"
},
{
"code": null,
"e": 27715,
"s": 27638,
"text": "So the joined table doesn’t include duplicates as we have used UNION Keyword"
},
{
"code": null,
"e": 27760,
"s": 27715,
"text": "Here is the output when we execute the query"
},
{
"code": null,
"e": 27768,
"s": 27760,
"text": "Output:"
},
{
"code": null,
"e": 27802,
"s": 27768,
"text": "Method 2: Using UNION ALL Keyword"
},
{
"code": null,
"e": 27809,
"s": 27802,
"text": "Query:"
},
{
"code": null,
"e": 27873,
"s": 27809,
"text": "SELECT * INTO joined2 FROM Shop1 UNION ALL SELECT * FROM Shop2;"
},
{
"code": null,
"e": 27975,
"s": 27873,
"text": "The above command creates a new table names joined2 which includes all the values of Shop1 and Shop2."
},
{
"code": null,
"e": 28026,
"s": 27975,
"text": "We run the following command for viewing the table"
},
{
"code": null,
"e": 28033,
"s": 28026,
"text": "Query:"
},
{
"code": null,
"e": 28056,
"s": 28033,
"text": "SELECT * FROM joined2;"
},
{
"code": null,
"e": 28102,
"s": 28056,
"text": "Here is the output when we execute the query."
},
{
"code": null,
"e": 28110,
"s": 28102,
"text": "Output:"
},
{
"code": null,
"e": 28117,
"s": 28110,
"text": "Picked"
},
{
"code": null,
"e": 28127,
"s": 28117,
"text": "SQL-Query"
},
{
"code": null,
"e": 28134,
"s": 28127,
"text": "How To"
},
{
"code": null,
"e": 28138,
"s": 28134,
"text": "SQL"
},
{
"code": null,
"e": 28142,
"s": 28138,
"text": "SQL"
},
{
"code": null,
"e": 28240,
"s": 28142,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28274,
"s": 28240,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28332,
"s": 28274,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 28381,
"s": 28332,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 28428,
"s": 28381,
"text": "How to create a nested RecyclerView in Android"
},
{
"code": null,
"e": 28470,
"s": 28428,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 28512,
"s": 28470,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 28530,
"s": 28512,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 28577,
"s": 28530,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 28621,
"s": 28577,
"text": "How to find Nth highest salary from a table"
}
] |
How to show or hide element in React ? - GeeksforGeeks
|
23 Dec, 2020
ReactJS is an entire architecture based on components that are used to create awesome UI and developer components. In any React app, it is all about components, so usually, we have to work with new components to develop a rich user interface. Hence, as per different circumstances we have to hide or show some components if we need them somewhere.
To implement such functionality of showing and hiding components we should have some id, some key values, by using those values we can modify the visibility of the components in our UI using different operators that work on certain conditions.
Creating React Application:
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
cd foldername
Hide or Show Component in ReactJS As we discussed above we have to create few components and render them into a single parent file to execute the conditions so that we can apply the functionality of showing or hiding to some particular components. Let’s create three child components and name them Child1.js, Child2.js, and Child3.js in the src folder and paste the following code into respective files.
Child1.js:JavascriptJavascriptimport React, { Component } from "react"; class Child1 extends Component { constructor() { super(); this.state = { name: "React" }; } render() { return <div>This is how GFG child component number 1 looks like.</div>; }} export default Child1;
Javascript
import React, { Component } from "react"; class Child1 extends Component { constructor() { super(); this.state = { name: "React" }; } render() { return <div>This is how GFG child component number 1 looks like.</div>; }} export default Child1;
Child2.js:JavascriptJavascriptimport React, { Component } from "react"; class Child2 extends Component { constructor() { super(); this.state = { name: "React" }; } render() { return <div>This is how GFG child component number 2 looks like.</div>; }} export default Child2;
Javascript
import React, { Component } from "react"; class Child2 extends Component { constructor() { super(); this.state = { name: "React" }; } render() { return <div>This is how GFG child component number 2 looks like.</div>; }} export default Child2;
Child3.js:JavascriptJavascriptimport React, { Component } from "react"; class Child3 extends Component { constructor() { super(); this.state = { name: "React" }; } render() { return <div>This is how GFG child component number 3 looks like.</div>; }} export default Child3;
Javascript
import React, { Component } from "react"; class Child3 extends Component { constructor() { super(); this.state = { name: "React" }; } render() { return <div>This is how GFG child component number 3 looks like.</div>; }} export default Child3;
Now it’s time to merge all these child JS files into the main parent file where we can set some particular conditions to show or hide some particular components. So let’s create the main file name App.js and paste the following code into it.
Now define three different boolean variables into the App.js file.
constructor() {
super();
this.state = {
name: "React",
shchild1: false,
shchild2: false,
shchild3: false
};
}
Initially, we allocate the default value into all the three boolean variables as false, and further, we will use these variables to show to hide any particular component in the App.js file.
App.js:JavascriptJavascriptimport React, { Component } from "react";import { render } from "react-dom";import Child1 from "./Child1";import Child2 from "./Child2";import Child3 from "./Child3"; class App extends Component { constructor() { super(); this.state = { name: "React", shchild1: false, shchild2: false, shchild3: false }; this.hideComponent = this.hideComponent.bind(this); } hideComponent(varname) { console.log(varname); switch (varname) { case "shchild1": this.setState({ shchild1: !this.state.shchild1 }); break; case "shchild2": this.setState({ shchild2: !this.state.shchild2 }); break; case "shchild3": this.setState({ shchild3: !this.state.shchild3 }); break; default: return; } } render() { const { shchild1, shchild2, shchild3 } = this.state; return ( <div> {shchild1 && <Child1 />} <hr /> {shchild2 && <Child2 />} <hr /> {shchild3 && <Child3 />} <hr /> <div> <button onClick={() => this.hideComponent("shchild1")}> Click here to hide GFG child1 component </button> <button onClick={() => this.hideComponent("shchild2")}> Click here to hide GFG child2 component </button> <button onClick={() => this.hideComponent("shchild3")}> Click here to hide GFG child3 component </button> </div> </div> ); }} export default App;
Javascript
import React, { Component } from "react";import { render } from "react-dom";import Child1 from "./Child1";import Child2 from "./Child2";import Child3 from "./Child3"; class App extends Component { constructor() { super(); this.state = { name: "React", shchild1: false, shchild2: false, shchild3: false }; this.hideComponent = this.hideComponent.bind(this); } hideComponent(varname) { console.log(varname); switch (varname) { case "shchild1": this.setState({ shchild1: !this.state.shchild1 }); break; case "shchild2": this.setState({ shchild2: !this.state.shchild2 }); break; case "shchild3": this.setState({ shchild3: !this.state.shchild3 }); break; default: return; } } render() { const { shchild1, shchild2, shchild3 } = this.state; return ( <div> {shchild1 && <Child1 />} <hr /> {shchild2 && <Child2 />} <hr /> {shchild3 && <Child3 />} <hr /> <div> <button onClick={() => this.hideComponent("shchild1")}> Click here to hide GFG child1 component </button> <button onClick={() => this.hideComponent("shchild2")}> Click here to hide GFG child2 component </button> <button onClick={() => this.hideComponent("shchild3")}> Click here to hide GFG child3 component </button> </div> </div> ); }} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: As we have declared three boolean variables in starting and set the default value to be false, and we have also made three child component which is further rendered in the main file as we need to hide or show the components. If we set the boolean value to be true then only that particular component will be rendered otherwise by default it will not render hence will be in a hidden phase. By clicking on different buttons created we can switch the cases to change the values of boolean variables.
When we click the click event button it simply updates the value of variables by sending the string as an input for which case that button has been clicked and based on the value updated in the variables it will decide that whether that component has to be shown or hidden. Using a similar method we can also hide or show elements also in ReactJS.
Following will be the output if the user does not click on any button:
Following will be the output if the user does not click on any button:
Following will be the output if the user clicks on all button:
Following will be the output if the user clicks on all button:
Picked
react-js
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to filter object array based on attributes?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Angular File Upload
Lodash _.debounce() Method
|
[
{
"code": null,
"e": 26569,
"s": 26541,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 26917,
"s": 26569,
"text": "ReactJS is an entire architecture based on components that are used to create awesome UI and developer components. In any React app, it is all about components, so usually, we have to work with new components to develop a rich user interface. Hence, as per different circumstances we have to hide or show some components if we need them somewhere."
},
{
"code": null,
"e": 27161,
"s": 26917,
"text": "To implement such functionality of showing and hiding components we should have some id, some key values, by using those values we can modify the visibility of the components in our UI using different operators that work on certain conditions."
},
{
"code": null,
"e": 27189,
"s": 27161,
"text": "Creating React Application:"
},
{
"code": null,
"e": 27284,
"s": 27189,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 27348,
"s": 27284,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27380,
"s": 27348,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27492,
"s": 27380,
"text": "Step 2:After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 27506,
"s": 27492,
"text": "cd foldername"
},
{
"code": null,
"e": 27910,
"s": 27506,
"text": "Hide or Show Component in ReactJS As we discussed above we have to create few components and render them into a single parent file to execute the conditions so that we can apply the functionality of showing or hiding to some particular components. Let’s create three child components and name them Child1.js, Child2.js, and Child3.js in the src folder and paste the following code into respective files."
},
{
"code": null,
"e": 28224,
"s": 27910,
"text": "Child1.js:JavascriptJavascriptimport React, { Component } from \"react\"; class Child1 extends Component { constructor() { super(); this.state = { name: \"React\" }; } render() { return <div>This is how GFG child component number 1 looks like.</div>; }} export default Child1;"
},
{
"code": null,
"e": 28235,
"s": 28224,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\"; class Child1 extends Component { constructor() { super(); this.state = { name: \"React\" }; } render() { return <div>This is how GFG child component number 1 looks like.</div>; }} export default Child1;",
"e": 28519,
"s": 28235,
"text": null
},
{
"code": null,
"e": 28833,
"s": 28519,
"text": "Child2.js:JavascriptJavascriptimport React, { Component } from \"react\"; class Child2 extends Component { constructor() { super(); this.state = { name: \"React\" }; } render() { return <div>This is how GFG child component number 2 looks like.</div>; }} export default Child2;"
},
{
"code": null,
"e": 28844,
"s": 28833,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\"; class Child2 extends Component { constructor() { super(); this.state = { name: \"React\" }; } render() { return <div>This is how GFG child component number 2 looks like.</div>; }} export default Child2;",
"e": 29128,
"s": 28844,
"text": null
},
{
"code": null,
"e": 29442,
"s": 29128,
"text": "Child3.js:JavascriptJavascriptimport React, { Component } from \"react\"; class Child3 extends Component { constructor() { super(); this.state = { name: \"React\" }; } render() { return <div>This is how GFG child component number 3 looks like.</div>; }} export default Child3;"
},
{
"code": null,
"e": 29453,
"s": 29442,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\"; class Child3 extends Component { constructor() { super(); this.state = { name: \"React\" }; } render() { return <div>This is how GFG child component number 3 looks like.</div>; }} export default Child3;",
"e": 29737,
"s": 29453,
"text": null
},
{
"code": null,
"e": 29979,
"s": 29737,
"text": "Now it’s time to merge all these child JS files into the main parent file where we can set some particular conditions to show or hide some particular components. So let’s create the main file name App.js and paste the following code into it."
},
{
"code": null,
"e": 30046,
"s": 29979,
"text": "Now define three different boolean variables into the App.js file."
},
{
"code": null,
"e": 30178,
"s": 30046,
"text": "constructor() {\n super();\n this.state = {\n name: \"React\",\n shchild1: false,\n shchild2: false,\n shchild3: false\n };\n}"
},
{
"code": null,
"e": 30368,
"s": 30178,
"text": "Initially, we allocate the default value into all the three boolean variables as false, and further, we will use these variables to show to hide any particular component in the App.js file."
},
{
"code": null,
"e": 31882,
"s": 30368,
"text": "App.js:JavascriptJavascriptimport React, { Component } from \"react\";import { render } from \"react-dom\";import Child1 from \"./Child1\";import Child2 from \"./Child2\";import Child3 from \"./Child3\"; class App extends Component { constructor() { super(); this.state = { name: \"React\", shchild1: false, shchild2: false, shchild3: false }; this.hideComponent = this.hideComponent.bind(this); } hideComponent(varname) { console.log(varname); switch (varname) { case \"shchild1\": this.setState({ shchild1: !this.state.shchild1 }); break; case \"shchild2\": this.setState({ shchild2: !this.state.shchild2 }); break; case \"shchild3\": this.setState({ shchild3: !this.state.shchild3 }); break; default: return; } } render() { const { shchild1, shchild2, shchild3 } = this.state; return ( <div> {shchild1 && <Child1 />} <hr /> {shchild2 && <Child2 />} <hr /> {shchild3 && <Child3 />} <hr /> <div> <button onClick={() => this.hideComponent(\"shchild1\")}> Click here to hide GFG child1 component </button> <button onClick={() => this.hideComponent(\"shchild2\")}> Click here to hide GFG child2 component </button> <button onClick={() => this.hideComponent(\"shchild3\")}> Click here to hide GFG child3 component </button> </div> </div> ); }} export default App;"
},
{
"code": null,
"e": 31893,
"s": 31882,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\";import { render } from \"react-dom\";import Child1 from \"./Child1\";import Child2 from \"./Child2\";import Child3 from \"./Child3\"; class App extends Component { constructor() { super(); this.state = { name: \"React\", shchild1: false, shchild2: false, shchild3: false }; this.hideComponent = this.hideComponent.bind(this); } hideComponent(varname) { console.log(varname); switch (varname) { case \"shchild1\": this.setState({ shchild1: !this.state.shchild1 }); break; case \"shchild2\": this.setState({ shchild2: !this.state.shchild2 }); break; case \"shchild3\": this.setState({ shchild3: !this.state.shchild3 }); break; default: return; } } render() { const { shchild1, shchild2, shchild3 } = this.state; return ( <div> {shchild1 && <Child1 />} <hr /> {shchild2 && <Child2 />} <hr /> {shchild3 && <Child3 />} <hr /> <div> <button onClick={() => this.hideComponent(\"shchild1\")}> Click here to hide GFG child1 component </button> <button onClick={() => this.hideComponent(\"shchild2\")}> Click here to hide GFG child2 component </button> <button onClick={() => this.hideComponent(\"shchild3\")}> Click here to hide GFG child3 component </button> </div> </div> ); }} export default App;",
"e": 33380,
"s": 31893,
"text": null
},
{
"code": null,
"e": 33493,
"s": 33380,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 33503,
"s": 33493,
"text": "npm start"
},
{
"code": null,
"e": 34011,
"s": 33503,
"text": "Output: As we have declared three boolean variables in starting and set the default value to be false, and we have also made three child component which is further rendered in the main file as we need to hide or show the components. If we set the boolean value to be true then only that particular component will be rendered otherwise by default it will not render hence will be in a hidden phase. By clicking on different buttons created we can switch the cases to change the values of boolean variables."
},
{
"code": null,
"e": 34359,
"s": 34011,
"text": "When we click the click event button it simply updates the value of variables by sending the string as an input for which case that button has been clicked and based on the value updated in the variables it will decide that whether that component has to be shown or hidden. Using a similar method we can also hide or show elements also in ReactJS."
},
{
"code": null,
"e": 34430,
"s": 34359,
"text": "Following will be the output if the user does not click on any button:"
},
{
"code": null,
"e": 34501,
"s": 34430,
"text": "Following will be the output if the user does not click on any button:"
},
{
"code": null,
"e": 34564,
"s": 34501,
"text": "Following will be the output if the user clicks on all button:"
},
{
"code": null,
"e": 34627,
"s": 34564,
"text": "Following will be the output if the user clicks on all button:"
},
{
"code": null,
"e": 34634,
"s": 34627,
"text": "Picked"
},
{
"code": null,
"e": 34643,
"s": 34634,
"text": "react-js"
},
{
"code": null,
"e": 34654,
"s": 34643,
"text": "JavaScript"
},
{
"code": null,
"e": 34752,
"s": 34654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34792,
"s": 34752,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 34853,
"s": 34792,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 34894,
"s": 34853,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 34916,
"s": 34894,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 34970,
"s": 34916,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 35018,
"s": 34970,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 35075,
"s": 35018,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 35137,
"s": 35075,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 35157,
"s": 35137,
"text": "Angular File Upload"
}
] |
Add one to a number represented as linked list | Set 2 - GeeksforGeeks
|
06 Jul, 2021
Given a singly linked list which represents a number where each node contains only one digit [0 – 9]. The task is to add 1 to the number represented by the given linked list and print the new linked list.Examples:
Input: 1 -> 2 -> 9 -> 9 -> NULL Output: Original list is : 1 2 9 9 Resultant list is : 1 3 0 0
Input: 9 -> 9 -> 9 -> 9 -> NULL Output: Original list is : 9 9 9 9 Resultant list is : 1 0 0 0 0
Approach: A previous implementation of the above problem was discussed in this post. However, one of the implementations requires the linked list to be reversed and the other makes use of recursion. An O(1) space complexity solution is been discussed here which doesn’t require the linked list to be reversed. The main focus in this question is on the digit 9 which creates all the changes otherwise for other digits we have to just increment their value by 1 but if we change the node’s value with the value 9 it makes a carry which then has to be passed through the linked list.Find the last node in the linked list which is not equal to 9. Now there are three cases:
If there is no such node i.e. the value of every node is 9 then the new linked list will contain all 0s and a single 1 inserted at the head of the linked list.If the rightmost node which is not equal to 9 is the last node in the linked list then add 1 to this node and return the head of the linked list.If the node is other than the last node i.e. every node after it is equal to 9 then add 1 to the current node and change all the nodes after it to 0.
If there is no such node i.e. the value of every node is 9 then the new linked list will contain all 0s and a single 1 inserted at the head of the linked list.
If the rightmost node which is not equal to 9 is the last node in the linked list then add 1 to this node and return the head of the linked list.
If the node is other than the last node i.e. every node after it is equal to 9 then add 1 to the current node and change all the nodes after it to 0.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Node of the linked liststruct Node { int data; Node* next;}; // Function to create a new nodeNode* create_Node(int data){ Node* temp = new Node(); temp->data = data; temp->next = NULL; return temp;} // Function to print the linked listvoid print(Node* head){ Node* temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl;} // Function to add one to a number// represented as linked listNode* addOne(Node* head){ // To store the last node in the linked // list which is not equal to 9 Node* last = NULL; Node* cur = head; // Iterate till the last node while (cur->next != NULL) { if (cur->data != 9) { last = cur; } cur = cur->next; } // If last node is not equal to 9 // add 1 to it and return the head if (cur->data != 9) { cur->data++; return head; } // If list is of the type 9 -> 9 -> 9 ... if (last == NULL) { last = new Node(); last->data = 0; last->next = head; head = last; } // For cases when the rightmost node which // is not equal to 9 is not the last // node in the linked list last->data++; last = last->next; while (last != NULL) { last->data = 0; last = last->next; } return head;} // Driver codeint main(){ Node* head = create_Node(1); head->next = create_Node(2); head->next->next = create_Node(9); head->next->next->next = create_Node(9); cout << "Original list is : "; print(head); head = addOne(head); cout << "Resultant list is : "; print(head); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Node of the linked liststatic class Node{ int data; Node next;}; // Function to create a new nodestatic Node create_Node(int data){ Node temp = new Node(); temp.data = data; temp.next = null; return temp;} // Function to print the linked liststatic void print(Node head){ Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println();} // Function to add one to a number// represented as linked liststatic Node addOne(Node head){ // To store the last node in the linked // list which is not equal to 9 Node last = null; Node cur = head; // Iterate till the last node while (cur.next != null) { if (cur.data != 9) { last = cur; } cur = cur.next; } // If last node is not equal to 9 // add 1 to it and return the head if (cur.data != 9) { cur.data++; return head; } // If list is of the type 9 . 9 . 9 ... if (last == null) { last = new Node(); last.data = 0; last.next = head; head = last; } // For cases when the rightmost node which // is not equal to 9 is not the last // node in the linked list last.data++; last = last.next; while (last != null) { last.data = 0; last = last.next; } return head;} // Driver codepublic static void main(String[] args){ Node head = create_Node(1); head.next = create_Node(2); head.next.next = create_Node(9); head.next.next.next = create_Node(9); System.out.print("Original list is : "); print(head); head = addOne(head); System.out.print("Resultant list is : "); print(head);}} // This code is contributed// by PrinciRaj1992
# A Python3 implementation of the approach # Node of the linked listclass Node(): def __init__(self): self.data = None self.next = None # Function to create a new nodedef create_Node(data): temp = Node() temp.data = data temp.next = None return temp # Function to print the linked listdef printList(head): temp = head while (temp != None): print(temp.data, end = ' ') temp = temp.next print() # Function to add one to a number# represented as linked listdef addOne(head): # To store the last node in the # linked list which is not equal to 9 last = None cur = head # Iterate till the last node while(cur.next != None): if(cur.data != 9): last = cur cur = cur.next # If last node is not equal to 9 # add 1 to it and return the head if(cur.data != 9): cur.data += 1 return head # If list is of the type 9 -> 9 -> 9 ... if(last == None): last = Node() last.data = 0 last.next = head head = last # For cases when the rightmost node which # is not equal to 9 is not the last # node in the linked list last.data += 1 last = last.next while(last != None): last.data = 0 last = last.next return head # Driver codeif __name__=='__main__': head = create_Node(1) head.next = create_Node(2) head.next.next = create_Node(9) head.next.next.next = create_Node(9) print("Original list is : ", end = "") printList(head) head = addOne(head) print("Resultant list is : ", end = "") printList(head) # This code is contributed by Yashyasvi Agarwal
// C# implementation of the approachusing System; class GFG{ // Node of the linked listpublic class Node{ public int data; public Node next;}; // Function to create a new nodestatic Node create_Node(int data){ Node temp = new Node(); temp.data = data; temp.next = null; return temp;} // Function to print the linked liststatic void print(Node head){ Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine();} // Function to add one to a number// represented as linked liststatic Node addOne(Node head){ // To store the last node in the linked // list which is not equal to 9 Node last = null; Node cur = head; // Iterate till the last node while (cur.next != null) { if (cur.data != 9) { last = cur; } cur = cur.next; } // If last node is not equal to 9 // add 1 to it and return the head if (cur.data != 9) { cur.data++; return head; } // If list is of the type 9 . 9 . 9 ... if (last == null) { last = new Node(); last.data = 0; last.next = head; head = last; } // For cases when the rightmost node which // is not equal to 9 is not the last // node in the linked list last.data++; last = last.next; while (last != null) { last.data = 0; last = last.next; } return head;} // Driver codepublic static void Main(String[] args){ Node head = create_Node(1); head.next = create_Node(2); head.next.next = create_Node(9); head.next.next.next = create_Node(9); Console.Write("Original list is : "); print(head); head = addOne(head); Console.Write("Resultant list is : "); print(head);}} // This code is contributed by 29AjayKumar
<script> // Javascript implementation of the approach // Node of the linked listclass Node { constructor() { this.data =0; this.next = null; }}; // Function to create a new nodefunction create_Node(data){ var temp = new Node(); temp.data = data; temp.next = null; return temp;} // Function to print the linked listfunction print(head){ var temp = head; while (temp != null) { document.write( temp.data + " "); temp = temp.next; } document.write("<br>");} // Function to add one to a number// represented as linked listfunction addOne(head){ // To store the last node in the linked // list which is not equal to 9 var last = null; var cur = head; // Iterate till the last node while (cur.next != null) { if (cur.data != 9) { last = cur; } cur = cur.next; } // If last node is not equal to 9 // add 1 to it and return the head if (cur.data != 9) { cur.data++; return head; } // If list is of the type 9 . 9 . 9 ... if (last == null) { last = new Node(); last.data = 0; last.next = head; head = last; } // For cases when the rightmost node which // is not equal to 9 is not the last // node in the linked list last.data++; last = last.next; while (last != null) { last.data = 0; last = last.next; } return head;} // Driver codevar head = create_Node(1);head.next = create_Node(2);head.next.next = create_Node(9);head.next.next.next = create_Node(9);document.write( "Original list is : ");print(head);head = addOne(head);document.write( "Resultant list is : ");print(head); // This code is contributed by rrrtnx.</script>
Original list is : 1 2 9 9
Resultant list is : 1 3 0 0
Time Complexity: O(N)
Space Complexity: O(1)
princiraj1992
29AjayKumar
yashyasviagarwal
shrey25
user_ztnc
rrrtnx
sooda367
Linked List
Recursion
Linked List
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Linked List | Set 2 (Traversal)
Swap nodes in a linked list without swapping data
Program to implement Singly Linked List in C++ using class
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
|
[
{
"code": null,
"e": 26205,
"s": 26177,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 26420,
"s": 26205,
"text": "Given a singly linked list which represents a number where each node contains only one digit [0 – 9]. The task is to add 1 to the number represented by the given linked list and print the new linked list.Examples: "
},
{
"code": null,
"e": 26515,
"s": 26420,
"text": "Input: 1 -> 2 -> 9 -> 9 -> NULL Output: Original list is : 1 2 9 9 Resultant list is : 1 3 0 0"
},
{
"code": null,
"e": 26613,
"s": 26515,
"text": "Input: 9 -> 9 -> 9 -> 9 -> NULL Output: Original list is : 9 9 9 9 Resultant list is : 1 0 0 0 0 "
},
{
"code": null,
"e": 27284,
"s": 26613,
"text": "Approach: A previous implementation of the above problem was discussed in this post. However, one of the implementations requires the linked list to be reversed and the other makes use of recursion. An O(1) space complexity solution is been discussed here which doesn’t require the linked list to be reversed. The main focus in this question is on the digit 9 which creates all the changes otherwise for other digits we have to just increment their value by 1 but if we change the node’s value with the value 9 it makes a carry which then has to be passed through the linked list.Find the last node in the linked list which is not equal to 9. Now there are three cases: "
},
{
"code": null,
"e": 27738,
"s": 27284,
"text": "If there is no such node i.e. the value of every node is 9 then the new linked list will contain all 0s and a single 1 inserted at the head of the linked list.If the rightmost node which is not equal to 9 is the last node in the linked list then add 1 to this node and return the head of the linked list.If the node is other than the last node i.e. every node after it is equal to 9 then add 1 to the current node and change all the nodes after it to 0."
},
{
"code": null,
"e": 27898,
"s": 27738,
"text": "If there is no such node i.e. the value of every node is 9 then the new linked list will contain all 0s and a single 1 inserted at the head of the linked list."
},
{
"code": null,
"e": 28044,
"s": 27898,
"text": "If the rightmost node which is not equal to 9 is the last node in the linked list then add 1 to this node and return the head of the linked list."
},
{
"code": null,
"e": 28194,
"s": 28044,
"text": "If the node is other than the last node i.e. every node after it is equal to 9 then add 1 to the current node and change all the nodes after it to 0."
},
{
"code": null,
"e": 28247,
"s": 28194,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28251,
"s": 28247,
"text": "C++"
},
{
"code": null,
"e": 28256,
"s": 28251,
"text": "Java"
},
{
"code": null,
"e": 28264,
"s": 28256,
"text": "Python3"
},
{
"code": null,
"e": 28267,
"s": 28264,
"text": "C#"
},
{
"code": null,
"e": 28278,
"s": 28267,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Node of the linked liststruct Node { int data; Node* next;}; // Function to create a new nodeNode* create_Node(int data){ Node* temp = new Node(); temp->data = data; temp->next = NULL; return temp;} // Function to print the linked listvoid print(Node* head){ Node* temp = head; while (temp != NULL) { cout << temp->data << \" \"; temp = temp->next; } cout << endl;} // Function to add one to a number// represented as linked listNode* addOne(Node* head){ // To store the last node in the linked // list which is not equal to 9 Node* last = NULL; Node* cur = head; // Iterate till the last node while (cur->next != NULL) { if (cur->data != 9) { last = cur; } cur = cur->next; } // If last node is not equal to 9 // add 1 to it and return the head if (cur->data != 9) { cur->data++; return head; } // If list is of the type 9 -> 9 -> 9 ... if (last == NULL) { last = new Node(); last->data = 0; last->next = head; head = last; } // For cases when the rightmost node which // is not equal to 9 is not the last // node in the linked list last->data++; last = last->next; while (last != NULL) { last->data = 0; last = last->next; } return head;} // Driver codeint main(){ Node* head = create_Node(1); head->next = create_Node(2); head->next->next = create_Node(9); head->next->next->next = create_Node(9); cout << \"Original list is : \"; print(head); head = addOne(head); cout << \"Resultant list is : \"; print(head); return 0;}",
"e": 30024,
"s": 28278,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Node of the linked liststatic class Node{ int data; Node next;}; // Function to create a new nodestatic Node create_Node(int data){ Node temp = new Node(); temp.data = data; temp.next = null; return temp;} // Function to print the linked liststatic void print(Node head){ Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } System.out.println();} // Function to add one to a number// represented as linked liststatic Node addOne(Node head){ // To store the last node in the linked // list which is not equal to 9 Node last = null; Node cur = head; // Iterate till the last node while (cur.next != null) { if (cur.data != 9) { last = cur; } cur = cur.next; } // If last node is not equal to 9 // add 1 to it and return the head if (cur.data != 9) { cur.data++; return head; } // If list is of the type 9 . 9 . 9 ... if (last == null) { last = new Node(); last.data = 0; last.next = head; head = last; } // For cases when the rightmost node which // is not equal to 9 is not the last // node in the linked list last.data++; last = last.next; while (last != null) { last.data = 0; last = last.next; } return head;} // Driver codepublic static void main(String[] args){ Node head = create_Node(1); head.next = create_Node(2); head.next.next = create_Node(9); head.next.next.next = create_Node(9); System.out.print(\"Original list is : \"); print(head); head = addOne(head); System.out.print(\"Resultant list is : \"); print(head);}} // This code is contributed// by PrinciRaj1992",
"e": 31868,
"s": 30024,
"text": null
},
{
"code": "# A Python3 implementation of the approach # Node of the linked listclass Node(): def __init__(self): self.data = None self.next = None # Function to create a new nodedef create_Node(data): temp = Node() temp.data = data temp.next = None return temp # Function to print the linked listdef printList(head): temp = head while (temp != None): print(temp.data, end = ' ') temp = temp.next print() # Function to add one to a number# represented as linked listdef addOne(head): # To store the last node in the # linked list which is not equal to 9 last = None cur = head # Iterate till the last node while(cur.next != None): if(cur.data != 9): last = cur cur = cur.next # If last node is not equal to 9 # add 1 to it and return the head if(cur.data != 9): cur.data += 1 return head # If list is of the type 9 -> 9 -> 9 ... if(last == None): last = Node() last.data = 0 last.next = head head = last # For cases when the rightmost node which # is not equal to 9 is not the last # node in the linked list last.data += 1 last = last.next while(last != None): last.data = 0 last = last.next return head # Driver codeif __name__=='__main__': head = create_Node(1) head.next = create_Node(2) head.next.next = create_Node(9) head.next.next.next = create_Node(9) print(\"Original list is : \", end = \"\") printList(head) head = addOne(head) print(\"Resultant list is : \", end = \"\") printList(head) # This code is contributed by Yashyasvi Agarwal",
"e": 33519,
"s": 31868,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Node of the linked listpublic class Node{ public int data; public Node next;}; // Function to create a new nodestatic Node create_Node(int data){ Node temp = new Node(); temp.data = data; temp.next = null; return temp;} // Function to print the linked liststatic void print(Node head){ Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.WriteLine();} // Function to add one to a number// represented as linked liststatic Node addOne(Node head){ // To store the last node in the linked // list which is not equal to 9 Node last = null; Node cur = head; // Iterate till the last node while (cur.next != null) { if (cur.data != 9) { last = cur; } cur = cur.next; } // If last node is not equal to 9 // add 1 to it and return the head if (cur.data != 9) { cur.data++; return head; } // If list is of the type 9 . 9 . 9 ... if (last == null) { last = new Node(); last.data = 0; last.next = head; head = last; } // For cases when the rightmost node which // is not equal to 9 is not the last // node in the linked list last.data++; last = last.next; while (last != null) { last.data = 0; last = last.next; } return head;} // Driver codepublic static void Main(String[] args){ Node head = create_Node(1); head.next = create_Node(2); head.next.next = create_Node(9); head.next.next.next = create_Node(9); Console.Write(\"Original list is : \"); print(head); head = addOne(head); Console.Write(\"Resultant list is : \"); print(head);}} // This code is contributed by 29AjayKumar",
"e": 35359,
"s": 33519,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Node of the linked listclass Node { constructor() { this.data =0; this.next = null; }}; // Function to create a new nodefunction create_Node(data){ var temp = new Node(); temp.data = data; temp.next = null; return temp;} // Function to print the linked listfunction print(head){ var temp = head; while (temp != null) { document.write( temp.data + \" \"); temp = temp.next; } document.write(\"<br>\");} // Function to add one to a number// represented as linked listfunction addOne(head){ // To store the last node in the linked // list which is not equal to 9 var last = null; var cur = head; // Iterate till the last node while (cur.next != null) { if (cur.data != 9) { last = cur; } cur = cur.next; } // If last node is not equal to 9 // add 1 to it and return the head if (cur.data != 9) { cur.data++; return head; } // If list is of the type 9 . 9 . 9 ... if (last == null) { last = new Node(); last.data = 0; last.next = head; head = last; } // For cases when the rightmost node which // is not equal to 9 is not the last // node in the linked list last.data++; last = last.next; while (last != null) { last.data = 0; last = last.next; } return head;} // Driver codevar head = create_Node(1);head.next = create_Node(2);head.next.next = create_Node(9);head.next.next.next = create_Node(9);document.write( \"Original list is : \");print(head);head = addOne(head);document.write( \"Resultant list is : \");print(head); // This code is contributed by rrrtnx.</script>",
"e": 37106,
"s": 35359,
"text": null
},
{
"code": null,
"e": 37162,
"s": 37106,
"text": "Original list is : 1 2 9 9 \nResultant list is : 1 3 0 0"
},
{
"code": null,
"e": 37186,
"s": 37164,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 37209,
"s": 37186,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 37223,
"s": 37209,
"text": "princiraj1992"
},
{
"code": null,
"e": 37235,
"s": 37223,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37252,
"s": 37235,
"text": "yashyasviagarwal"
},
{
"code": null,
"e": 37260,
"s": 37252,
"text": "shrey25"
},
{
"code": null,
"e": 37270,
"s": 37260,
"text": "user_ztnc"
},
{
"code": null,
"e": 37277,
"s": 37270,
"text": "rrrtnx"
},
{
"code": null,
"e": 37286,
"s": 37277,
"text": "sooda367"
},
{
"code": null,
"e": 37298,
"s": 37286,
"text": "Linked List"
},
{
"code": null,
"e": 37308,
"s": 37298,
"text": "Recursion"
},
{
"code": null,
"e": 37320,
"s": 37308,
"text": "Linked List"
},
{
"code": null,
"e": 37330,
"s": 37320,
"text": "Recursion"
},
{
"code": null,
"e": 37428,
"s": 37330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37469,
"s": 37428,
"text": "Circular Linked List | Set 2 (Traversal)"
},
{
"code": null,
"e": 37519,
"s": 37469,
"text": "Swap nodes in a linked list without swapping data"
},
{
"code": null,
"e": 37578,
"s": 37519,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 37618,
"s": 37578,
"text": "Circular Singly Linked List | Insertion"
},
{
"code": null,
"e": 37689,
"s": 37618,
"text": "Given a linked list which is sorted, how will you insert in sorted way"
},
{
"code": null,
"e": 37749,
"s": 37689,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37834,
"s": 37749,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 37844,
"s": 37834,
"text": "Recursion"
},
{
"code": null,
"e": 37871,
"s": 37844,
"text": "Program for Tower of Hanoi"
}
] |
Streamline Plots in Plotly using Python - GeeksforGeeks
|
05 Sep, 2020
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
In plotly, streamline plots are based on the representation on a 2-D vector field which is explained as velocity fields, which are consist of closed curves that are tangent to the velocity field. Streamlining is the fastest technique and more efficient for getting the data. Velocity values are interpolated when determining the streamlines. Streamlines are initialized on the boundary of the x-y domain.
Syntax: create_streamline(x, y, u, v, density=1, angle=0.3490658503988659, arrow_scale=0.09)
Parameters:
x: 1 dimensional, evenly spaced list or array
y: 1 dimensional, evenly spaced list or array
u: 2 dimensional array
v: 2 dimensional array
density: controls the density of streamlines in plot. This is multiplied by 30 to scale similiarly to other available streamline functions such as matplotlib. Default = 1
angle: angle of arrowhead. Default = pi/9
arrow_scale: value to scale length of arrowhead Default = .09
Example:
Python3
import plotly.figure_factory as ffimport numpy as np x = np.linspace(-1, 1, 10)y = np.linspace(-1, 1, 10)Y, X = np.meshgrid(x, y)u = 1 - X**2 + Yv = -1 + X - Y**2 # Create streamline figurefig = ff.create_streamline(x, y, u, v, arrow_scale=.1)fig.show()
Output:
The source point can be plot using the scatterplot() method of the graph_objects class. In this, the streamline plot and the position of the marker in the scatterplot are tweaked in such a way that it seems that all the stream is originating from a particular source.
Example:
Python3
import plotly.figure_factory as ffimport plotly.graph_objects as goimport numpy as np x = np.linspace(-1, 2, 50)y = np.linspace(-1, 1, 50)Y, X = np.meshgrid(x, y)u = np.cos(X)*Yv = np.cos(y)*X # Source for x and y coordinate# of scatter plotX, Y = 0, 0 # Create streamline figurefig = ff.create_streamline(x, y, u, v, arrow_scale=.1) fig.add_trace(go.Scatter(x=[X], y=[Y], mode='markers', marker_size=15, )) fig.show()
Output:
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
|
[
{
"code": null,
"e": 25429,
"s": 25401,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 25733,
"s": 25429,
"text": "A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library."
},
{
"code": null,
"e": 26138,
"s": 25733,
"text": "In plotly, streamline plots are based on the representation on a 2-D vector field which is explained as velocity fields, which are consist of closed curves that are tangent to the velocity field. Streamlining is the fastest technique and more efficient for getting the data. Velocity values are interpolated when determining the streamlines. Streamlines are initialized on the boundary of the x-y domain."
},
{
"code": null,
"e": 26231,
"s": 26138,
"text": "Syntax: create_streamline(x, y, u, v, density=1, angle=0.3490658503988659, arrow_scale=0.09)"
},
{
"code": null,
"e": 26243,
"s": 26231,
"text": "Parameters:"
},
{
"code": null,
"e": 26289,
"s": 26243,
"text": "x: 1 dimensional, evenly spaced list or array"
},
{
"code": null,
"e": 26335,
"s": 26289,
"text": "y: 1 dimensional, evenly spaced list or array"
},
{
"code": null,
"e": 26358,
"s": 26335,
"text": "u: 2 dimensional array"
},
{
"code": null,
"e": 26381,
"s": 26358,
"text": "v: 2 dimensional array"
},
{
"code": null,
"e": 26552,
"s": 26381,
"text": "density: controls the density of streamlines in plot. This is multiplied by 30 to scale similiarly to other available streamline functions such as matplotlib. Default = 1"
},
{
"code": null,
"e": 26594,
"s": 26552,
"text": "angle: angle of arrowhead. Default = pi/9"
},
{
"code": null,
"e": 26656,
"s": 26594,
"text": "arrow_scale: value to scale length of arrowhead Default = .09"
},
{
"code": null,
"e": 26665,
"s": 26656,
"text": "Example:"
},
{
"code": null,
"e": 26673,
"s": 26665,
"text": "Python3"
},
{
"code": "import plotly.figure_factory as ffimport numpy as np x = np.linspace(-1, 1, 10)y = np.linspace(-1, 1, 10)Y, X = np.meshgrid(x, y)u = 1 - X**2 + Yv = -1 + X - Y**2 # Create streamline figurefig = ff.create_streamline(x, y, u, v, arrow_scale=.1)fig.show()",
"e": 26929,
"s": 26673,
"text": null
},
{
"code": null,
"e": 26937,
"s": 26929,
"text": "Output:"
},
{
"code": null,
"e": 27205,
"s": 26937,
"text": "The source point can be plot using the scatterplot() method of the graph_objects class. In this, the streamline plot and the position of the marker in the scatterplot are tweaked in such a way that it seems that all the stream is originating from a particular source."
},
{
"code": null,
"e": 27214,
"s": 27205,
"text": "Example:"
},
{
"code": null,
"e": 27222,
"s": 27214,
"text": "Python3"
},
{
"code": "import plotly.figure_factory as ffimport plotly.graph_objects as goimport numpy as np x = np.linspace(-1, 2, 50)y = np.linspace(-1, 1, 50)Y, X = np.meshgrid(x, y)u = np.cos(X)*Yv = np.cos(y)*X # Source for x and y coordinate# of scatter plotX, Y = 0, 0 # Create streamline figurefig = ff.create_streamline(x, y, u, v, arrow_scale=.1) fig.add_trace(go.Scatter(x=[X], y=[Y], mode='markers', marker_size=15, )) fig.show()",
"e": 27719,
"s": 27222,
"text": null
},
{
"code": null,
"e": 27727,
"s": 27719,
"text": "Output:"
},
{
"code": null,
"e": 27741,
"s": 27727,
"text": "Python-Plotly"
},
{
"code": null,
"e": 27748,
"s": 27741,
"text": "Python"
},
{
"code": null,
"e": 27846,
"s": 27748,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27881,
"s": 27846,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27913,
"s": 27881,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27935,
"s": 27913,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27977,
"s": 27935,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28007,
"s": 27977,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28033,
"s": 28007,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28062,
"s": 28033,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28106,
"s": 28062,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28143,
"s": 28106,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Python - turtle.pencolor() method - GeeksforGeeks
|
29 Jul, 2021
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to change the color of the ink of the turtle drawing. The default color is black.
Syntax: turtle.pencolor(*args)
Arguments: This method have following arguments:
colorstring: (optional) colorstring A string of color name like “red”, “green”, etc.
(r, g, b): (optional) A tuple of three values r, g, and b using rgb color code.
r, g, b: (optional) Three values r, g, and b using rgb color code.
Return: None
Below is the implementation of above method with an example :
Python3
# importing turtle packageimport turtle # set turtle shapeturtle.shape("turtle") # set the colormodeturtle.colormode(255) # use forward by 100 pixel# default pen color is blackturtle.forward(100) # change the pencolor# pencolor is redturtle.pencolor("red") # use forward by 100 pixel# then 90 degrees rightturtle.right(90)turtle.forward(100) # change the pencolor# pencolor is blueturtle.pencolor((41,41,253)) # use forward by 100 pixel# then 90 degrees rightturtle.right(90)turtle.forward(100) # change the pencolor# pencolor is greenturtle.pencolor(41,253,41) # use forward by 100 pixel# then 90 degrees rightturtle.right(90)turtle.forward(100) # This code is contributed# by Deepanshu Rustagi.
Output :
surindertarika1234
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
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": 25562,
"s": 25534,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 25779,
"s": 25562,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 25881,
"s": 25779,
"text": "This method is used to change the color of the ink of the turtle drawing. The default color is black."
},
{
"code": null,
"e": 25913,
"s": 25881,
"text": "Syntax: turtle.pencolor(*args) "
},
{
"code": null,
"e": 25962,
"s": 25913,
"text": "Arguments: This method have following arguments:"
},
{
"code": null,
"e": 26047,
"s": 25962,
"text": "colorstring: (optional) colorstring A string of color name like “red”, “green”, etc."
},
{
"code": null,
"e": 26127,
"s": 26047,
"text": "(r, g, b): (optional) A tuple of three values r, g, and b using rgb color code."
},
{
"code": null,
"e": 26194,
"s": 26127,
"text": "r, g, b: (optional) Three values r, g, and b using rgb color code."
},
{
"code": null,
"e": 26207,
"s": 26194,
"text": "Return: None"
},
{
"code": null,
"e": 26269,
"s": 26207,
"text": "Below is the implementation of above method with an example :"
},
{
"code": null,
"e": 26277,
"s": 26269,
"text": "Python3"
},
{
"code": "# importing turtle packageimport turtle # set turtle shapeturtle.shape(\"turtle\") # set the colormodeturtle.colormode(255) # use forward by 100 pixel# default pen color is blackturtle.forward(100) # change the pencolor# pencolor is redturtle.pencolor(\"red\") # use forward by 100 pixel# then 90 degrees rightturtle.right(90)turtle.forward(100) # change the pencolor# pencolor is blueturtle.pencolor((41,41,253)) # use forward by 100 pixel# then 90 degrees rightturtle.right(90)turtle.forward(100) # change the pencolor# pencolor is greenturtle.pencolor(41,253,41) # use forward by 100 pixel# then 90 degrees rightturtle.right(90)turtle.forward(100) # This code is contributed# by Deepanshu Rustagi.",
"e": 26975,
"s": 26277,
"text": null
},
{
"code": null,
"e": 26988,
"s": 26979,
"text": "Output :"
},
{
"code": null,
"e": 27011,
"s": 26992,
"text": "surindertarika1234"
},
{
"code": null,
"e": 27025,
"s": 27011,
"text": "Python-turtle"
},
{
"code": null,
"e": 27032,
"s": 27025,
"text": "Python"
},
{
"code": null,
"e": 27130,
"s": 27032,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27162,
"s": 27130,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27204,
"s": 27162,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27246,
"s": 27204,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27273,
"s": 27246,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27329,
"s": 27273,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27351,
"s": 27329,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27390,
"s": 27351,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27421,
"s": 27390,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27450,
"s": 27421,
"text": "Create a directory in Python"
}
] |
PostgreSQL - Restore Database - GeeksforGeeks
|
28 Jul, 2021
Restoring a database, is the action of copying the backed up data and restoring it at its original or new place. We perform restore action on a database so as to return the data to its original state before being lost, stolen or corrupted. There are several causes due to which one needs to restore a database like – due as human errors sometimes data gets corrupted; some malicious attacks on the database might infect it; due to power outages; natural calamities like floods, storms etc. Thus, in these cases, a data restore makes a usable copy of data and ensures that restored backup data is inline and consistent with the state of the data before the damage occurred.
Approach:
In PostgreSQL also, we can back up and restore the data. To restore a database, we have 2 main approaches:
To restore via PgAdmin4 GUITo restore via command line
To restore via PgAdmin4 GUI
To restore via command line
Here we are going to see both the approaches in detail.
In the first approach, we are going to restore our database from the pgAdmin4. This is a very simple and straightforward process. For this we are going to follow the steps listed as below –
1. Start the pgAdmin database server and login to the pgAdmin4 control panel via valid credentials.
2. Expand the Servers section and navigate till Databases. Now, here you will find all your databases the server is currently hosting (if any).
3. Now we need to create a new database which will serve as a placeholder for our database which is to be restored. For this, right click on the Databases section, select Create -> Database.
4. In the General tab specify the name of your database which is to be restored. Owner must be same as the current postgres Admin username. You can also add optional comments.
5. Now to go Definition tab, select appropriate character encoding, tablespaces etc. Fill all the required details of any in similar ways on the alongside tabs like Security, Parameters tabs as well.
6. After filling all necessary details, select Save option. Database will now be created successfully and will be listed alongside the existing databases in the Databases section.
7. Right-click on the newly created database by you and select Restore option from the list.
8. After clicking Restore option, a new pop-up dialogue box menu of Restore will show up on the screen as below.
9. Now specify the Format of the file. Right-click on the horizontal kebab menu to browse for the location of file, select the role name as postgres (root owner). Hit Restore button.
10. A new restore job is now created on the pgAdmin4 server and usually appears in the bottom right corner of the window.
11. After successful restore operation is a success prompt is displayed at the same position as said above with the success message. In case of a failure of the restore option, a failure message is also given when we click on the More Details (i) button.
12. Success !! Our PostgreSQL database is now completely restored. It is now in fully up and running state.
To restore a database via the command line, we are going to follow the following procedure –
1. Firstly, we need to login to the PostgreSQL terminal via command line. To do so, type in the following command :-
psql -U <username>
2. We can now see that we are successfully logged into the psql client terminal and have got the postgres command line input prompt.
3. We will now follow the same process as we followed in the above part I, the only difference being here is that, we are going to do this time via the command line terminal of PostgreSQL.
4. Let’s now create a placeholder database for our purpose which will be used to restore the backup. To do so, run the below script.
CREATE DATABASE BackupDB ENCODING='UTF-8' OWNER='postgres';
5. Database is now created. Let us restore it now. To restore the database, we are going to use the pg_restore command supplied with some arguments. It is important to note here that, we need to exit from the psql terminal in order to run pg_restore command. To exit from psql terminal, type “\q” to exit.
6. Key in the pg_restore command with the following arguments –
pg_restore -U postgres -d backupdb -v "D:\Backup.sql"
The detailed explanation of the arguments for PostgreSQL can be found on the PostgreSQL’s official website on the documentation section of pg_restore.
7. After successful restoration of database, we will se that our schema are restored alongwith the tables and their data.
Thus, in this article, we have successfully explored the two ways of successfully restoring the database.
Picked
postgreSQL-administration
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - REPLACE Function
PostgreSQL - TIME Data Type
PostgreSQL - CREATE SCHEMA
PostgreSQL - ROW_NUMBER Function
PostgreSQL - SELECT
PostgreSQL - Cursor
PostgreSQL - RENAME COLUMN
|
[
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 26040,
"s": 25367,
"text": "Restoring a database, is the action of copying the backed up data and restoring it at its original or new place. We perform restore action on a database so as to return the data to its original state before being lost, stolen or corrupted. There are several causes due to which one needs to restore a database like – due as human errors sometimes data gets corrupted; some malicious attacks on the database might infect it; due to power outages; natural calamities like floods, storms etc. Thus, in these cases, a data restore makes a usable copy of data and ensures that restored backup data is inline and consistent with the state of the data before the damage occurred."
},
{
"code": null,
"e": 26050,
"s": 26040,
"text": "Approach:"
},
{
"code": null,
"e": 26157,
"s": 26050,
"text": "In PostgreSQL also, we can back up and restore the data. To restore a database, we have 2 main approaches:"
},
{
"code": null,
"e": 26212,
"s": 26157,
"text": "To restore via PgAdmin4 GUITo restore via command line"
},
{
"code": null,
"e": 26240,
"s": 26212,
"text": "To restore via PgAdmin4 GUI"
},
{
"code": null,
"e": 26268,
"s": 26240,
"text": "To restore via command line"
},
{
"code": null,
"e": 26324,
"s": 26268,
"text": "Here we are going to see both the approaches in detail."
},
{
"code": null,
"e": 26514,
"s": 26324,
"text": "In the first approach, we are going to restore our database from the pgAdmin4. This is a very simple and straightforward process. For this we are going to follow the steps listed as below –"
},
{
"code": null,
"e": 26614,
"s": 26514,
"text": "1. Start the pgAdmin database server and login to the pgAdmin4 control panel via valid credentials."
},
{
"code": null,
"e": 26758,
"s": 26614,
"text": "2. Expand the Servers section and navigate till Databases. Now, here you will find all your databases the server is currently hosting (if any)."
},
{
"code": null,
"e": 26949,
"s": 26758,
"text": "3. Now we need to create a new database which will serve as a placeholder for our database which is to be restored. For this, right click on the Databases section, select Create -> Database."
},
{
"code": null,
"e": 27126,
"s": 26949,
"text": "4. In the General tab specify the name of your database which is to be restored. Owner must be same as the current postgres Admin username. You can also add optional comments."
},
{
"code": null,
"e": 27326,
"s": 27126,
"text": "5. Now to go Definition tab, select appropriate character encoding, tablespaces etc. Fill all the required details of any in similar ways on the alongside tabs like Security, Parameters tabs as well."
},
{
"code": null,
"e": 27506,
"s": 27326,
"text": "6. After filling all necessary details, select Save option. Database will now be created successfully and will be listed alongside the existing databases in the Databases section."
},
{
"code": null,
"e": 27599,
"s": 27506,
"text": "7. Right-click on the newly created database by you and select Restore option from the list."
},
{
"code": null,
"e": 27712,
"s": 27599,
"text": "8. After clicking Restore option, a new pop-up dialogue box menu of Restore will show up on the screen as below."
},
{
"code": null,
"e": 27895,
"s": 27712,
"text": "9. Now specify the Format of the file. Right-click on the horizontal kebab menu to browse for the location of file, select the role name as postgres (root owner). Hit Restore button."
},
{
"code": null,
"e": 28018,
"s": 27895,
"text": "10. A new restore job is now created on the pgAdmin4 server and usually appears in the bottom right corner of the window. "
},
{
"code": null,
"e": 28273,
"s": 28018,
"text": "11. After successful restore operation is a success prompt is displayed at the same position as said above with the success message. In case of a failure of the restore option, a failure message is also given when we click on the More Details (i) button."
},
{
"code": null,
"e": 28381,
"s": 28273,
"text": "12. Success !! Our PostgreSQL database is now completely restored. It is now in fully up and running state."
},
{
"code": null,
"e": 28474,
"s": 28381,
"text": "To restore a database via the command line, we are going to follow the following procedure –"
},
{
"code": null,
"e": 28591,
"s": 28474,
"text": "1. Firstly, we need to login to the PostgreSQL terminal via command line. To do so, type in the following command :-"
},
{
"code": null,
"e": 28610,
"s": 28591,
"text": "psql -U <username>"
},
{
"code": null,
"e": 28743,
"s": 28610,
"text": "2. We can now see that we are successfully logged into the psql client terminal and have got the postgres command line input prompt."
},
{
"code": null,
"e": 28932,
"s": 28743,
"text": "3. We will now follow the same process as we followed in the above part I, the only difference being here is that, we are going to do this time via the command line terminal of PostgreSQL."
},
{
"code": null,
"e": 29066,
"s": 28932,
"text": "4. Let’s now create a placeholder database for our purpose which will be used to restore the backup. To do so, run the below script."
},
{
"code": null,
"e": 29126,
"s": 29066,
"text": "CREATE DATABASE BackupDB ENCODING='UTF-8' OWNER='postgres';"
},
{
"code": null,
"e": 29432,
"s": 29126,
"text": "5. Database is now created. Let us restore it now. To restore the database, we are going to use the pg_restore command supplied with some arguments. It is important to note here that, we need to exit from the psql terminal in order to run pg_restore command. To exit from psql terminal, type “\\q” to exit."
},
{
"code": null,
"e": 29496,
"s": 29432,
"text": "6. Key in the pg_restore command with the following arguments –"
},
{
"code": null,
"e": 29550,
"s": 29496,
"text": "pg_restore -U postgres -d backupdb -v \"D:\\Backup.sql\""
},
{
"code": null,
"e": 29701,
"s": 29550,
"text": "The detailed explanation of the arguments for PostgreSQL can be found on the PostgreSQL’s official website on the documentation section of pg_restore."
},
{
"code": null,
"e": 29824,
"s": 29701,
"text": "7. After successful restoration of database, we will se that our schema are restored alongwith the tables and their data."
},
{
"code": null,
"e": 29930,
"s": 29824,
"text": "Thus, in this article, we have successfully explored the two ways of successfully restoring the database."
},
{
"code": null,
"e": 29937,
"s": 29930,
"text": "Picked"
},
{
"code": null,
"e": 29963,
"s": 29937,
"text": "postgreSQL-administration"
},
{
"code": null,
"e": 29974,
"s": 29963,
"text": "PostgreSQL"
},
{
"code": null,
"e": 30072,
"s": 29974,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30102,
"s": 30072,
"text": "PostgreSQL - CREATE PROCEDURE"
},
{
"code": null,
"e": 30131,
"s": 30102,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 30155,
"s": 30131,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 30185,
"s": 30155,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 30213,
"s": 30185,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 30240,
"s": 30213,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 30273,
"s": 30240,
"text": "PostgreSQL - ROW_NUMBER Function"
},
{
"code": null,
"e": 30293,
"s": 30273,
"text": "PostgreSQL - SELECT"
},
{
"code": null,
"e": 30313,
"s": 30293,
"text": "PostgreSQL - Cursor"
}
] |
Fork and Join Constructs in Concurrency
|
06 Jul, 2020
Prerequisite – Process SynchronizationFork :The fork instruction is the that instruction in the process execution that produces two concurrent executions in a program. One of the concurrent executions starts at statement labeled and other execution is the continuation of the execution at the statement following the fork instruction. The fork systems call assignment has one parameter i.e. Label (L).
Join :The join instruction is the that instruction in the process execution that provides the medium to recombine two concurrent computations into a single one. The join instruction has one parameter integer count that specifies the number of computations which are to be joined. It decrements the integer by one. If the value of the integer after decrement is non-zero then the process terminates otherwise the process continues execution with the next statement.
Example-1:Construct the precedence graph for the following fork/join program.
S1;
count1: = 2;
fork L1;
S2;
S4;
count2: = 2;
fork L2;
S5;
Go to L3;
L1: S3;
L2: join count1;
S6;
L3: join count2;
S7;
Solution :
Example-2 :Write a fork/join program for the following precedence graph.
Solution :After S1 fork statement is required to create a child.After S4 fork statement is required to create a child.All processes need to join before S7.
S1;
count: = 3;
fork L1;
S2;
S4;
fork L2;
S5;
Go to L3;
L2: S6;
GOTO L3;
L1: S3;
L3: join count;
S7;
Process Synchronization
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jul, 2020"
},
{
"code": null,
"e": 430,
"s": 28,
"text": "Prerequisite – Process SynchronizationFork :The fork instruction is the that instruction in the process execution that produces two concurrent executions in a program. One of the concurrent executions starts at statement labeled and other execution is the continuation of the execution at the statement following the fork instruction. The fork systems call assignment has one parameter i.e. Label (L)."
},
{
"code": null,
"e": 895,
"s": 430,
"text": "Join :The join instruction is the that instruction in the process execution that provides the medium to recombine two concurrent computations into a single one. The join instruction has one parameter integer count that specifies the number of computations which are to be joined. It decrements the integer by one. If the value of the integer after decrement is non-zero then the process terminates otherwise the process continues execution with the next statement."
},
{
"code": null,
"e": 973,
"s": 895,
"text": "Example-1:Construct the precedence graph for the following fork/join program."
},
{
"code": null,
"e": 1152,
"s": 973,
"text": " S1;\n count1: = 2;\n fork L1;\n S2;\n S4;\n count2: = 2;\n fork L2;\n S5;\n Go to L3;\nL1: S3;\nL2: join count1;\n S6;\nL3: join count2;\n S7;\n"
},
{
"code": null,
"e": 1163,
"s": 1152,
"text": "Solution :"
},
{
"code": null,
"e": 1236,
"s": 1163,
"text": "Example-2 :Write a fork/join program for the following precedence graph."
},
{
"code": null,
"e": 1392,
"s": 1236,
"text": "Solution :After S1 fork statement is required to create a child.After S4 fork statement is required to create a child.All processes need to join before S7."
},
{
"code": null,
"e": 1547,
"s": 1392,
"text": " S1;\n count: = 3;\n fork L1;\n S2;\n S4;\n fork L2;\n S5;\n Go to L3;\nL2: S6;\n GOTO L3;\nL1: S3;\nL3: join count;\n S7; "
},
{
"code": null,
"e": 1571,
"s": 1547,
"text": "Process Synchronization"
},
{
"code": null,
"e": 1589,
"s": 1571,
"text": "Operating Systems"
},
{
"code": null,
"e": 1607,
"s": 1589,
"text": "Operating Systems"
}
] |
How to Create a MySQL Sequence?
|
In MySQL, a sequence refers to a list of integers that is generated in the ascending order beginning from 1 or 0 if specified. Many applications require sequences that will be used to generate unique numbers especially for identification.
Examples include customer ID in CRM, employee numbers in HR, and equipment numbers in the services management system.
To create a sequence in MySQL automatically, the AUTO_INCREMENT attribute for a column needs to be set. This would typically be a primary key column.
The following rules need to be followed while using the AUTO_INCREMENT attribute −
Every table has only one AUTO_INCREMENT column whose data type would be an integer
typically.
The AUTO_INCREMENT column needs to be indexed. This means it can either be a PRIMARY
KEY or a UNIQUE index.
The AUTO_INCREMENT column must have a NOT NULL constraint on it.
When the AUTO_INCREMENT attribute is set to a column, MySQL automatically adds the
NOT NULL constraint to the column on its own.
Let us see an example of creating a MySQL sequence −
CREATE TABLE tableName (
emp_no INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50)
)
Let us understand how the AUTO_INCREMENT column works −
The starting value of an AUTO_INCREMENT column is usually 1. It is increased by 1 when a NULL value is inserted into the column or when a value is omitted in the INSERT statement.
The starting value of an AUTO_INCREMENT column is usually 1. It is increased by 1 when a NULL value is inserted into the column or when a value is omitted in the INSERT statement.
To obtain the last generated sequence number, the LAST_INSERT_ID() function can be used.
To obtain the last generated sequence number, the LAST_INSERT_ID() function can be used.
The last generated sequence is unique across sessions.
The last generated sequence is unique across sessions.
If another connection generates a sequence number, it can be obtained by using the LAST_INSERT_ID() function.
If another connection generates a sequence number, it can be obtained by using the LAST_INSERT_ID() function.
If a new row is inserted into a table and a value is specified for the sequence column, MySQL ensures to insert the sequence number if the sequence number doesn’t exist in the column.
If a new row is inserted into a table and a value is specified for the sequence column, MySQL ensures to insert the sequence number if the sequence number doesn’t exist in the column.
|
[
{
"code": null,
"e": 1426,
"s": 1187,
"text": "In MySQL, a sequence refers to a list of integers that is generated in the ascending order beginning from 1 or 0 if specified. Many applications require sequences that will be used to generate unique numbers especially for identification."
},
{
"code": null,
"e": 1544,
"s": 1426,
"text": "Examples include customer ID in CRM, employee numbers in HR, and equipment numbers in the services management system."
},
{
"code": null,
"e": 1694,
"s": 1544,
"text": "To create a sequence in MySQL automatically, the AUTO_INCREMENT attribute for a column needs to be set. This would typically be a primary key column."
},
{
"code": null,
"e": 1777,
"s": 1694,
"text": "The following rules need to be followed while using the AUTO_INCREMENT attribute −"
},
{
"code": null,
"e": 1871,
"s": 1777,
"text": "Every table has only one AUTO_INCREMENT column whose data type would be an integer\ntypically."
},
{
"code": null,
"e": 1979,
"s": 1871,
"text": "The AUTO_INCREMENT column needs to be indexed. This means it can either be a PRIMARY\nKEY or a UNIQUE index."
},
{
"code": null,
"e": 2044,
"s": 1979,
"text": "The AUTO_INCREMENT column must have a NOT NULL constraint on it."
},
{
"code": null,
"e": 2173,
"s": 2044,
"text": "When the AUTO_INCREMENT attribute is set to a column, MySQL automatically adds the\nNOT NULL constraint to the column on its own."
},
{
"code": null,
"e": 2226,
"s": 2173,
"text": "Let us see an example of creating a MySQL sequence −"
},
{
"code": null,
"e": 2347,
"s": 2226,
"text": "CREATE TABLE tableName (\n emp_no INT AUTO_INCREMENT PRIMARY KEY,\n first_name VARCHAR(50),\n last_name VARCHAR(50)\n)"
},
{
"code": null,
"e": 2403,
"s": 2347,
"text": "Let us understand how the AUTO_INCREMENT column works −"
},
{
"code": null,
"e": 2583,
"s": 2403,
"text": "The starting value of an AUTO_INCREMENT column is usually 1. It is increased by 1 when a NULL value is inserted into the column or when a value is omitted in the INSERT statement."
},
{
"code": null,
"e": 2763,
"s": 2583,
"text": "The starting value of an AUTO_INCREMENT column is usually 1. It is increased by 1 when a NULL value is inserted into the column or when a value is omitted in the INSERT statement."
},
{
"code": null,
"e": 2852,
"s": 2763,
"text": "To obtain the last generated sequence number, the LAST_INSERT_ID() function can be used."
},
{
"code": null,
"e": 2941,
"s": 2852,
"text": "To obtain the last generated sequence number, the LAST_INSERT_ID() function can be used."
},
{
"code": null,
"e": 2996,
"s": 2941,
"text": "The last generated sequence is unique across sessions."
},
{
"code": null,
"e": 3051,
"s": 2996,
"text": "The last generated sequence is unique across sessions."
},
{
"code": null,
"e": 3161,
"s": 3051,
"text": "If another connection generates a sequence number, it can be obtained by using the LAST_INSERT_ID() function."
},
{
"code": null,
"e": 3271,
"s": 3161,
"text": "If another connection generates a sequence number, it can be obtained by using the LAST_INSERT_ID() function."
},
{
"code": null,
"e": 3455,
"s": 3271,
"text": "If a new row is inserted into a table and a value is specified for the sequence column, MySQL ensures to insert the sequence number if the sequence number doesn’t exist in the column."
},
{
"code": null,
"e": 3639,
"s": 3455,
"text": "If a new row is inserted into a table and a value is specified for the sequence column, MySQL ensures to insert the sequence number if the sequence number doesn’t exist in the column."
}
] |
Python | Insert character after every character pair
|
04 Jul, 2019
Sometimes, we can have a problem in which we need to insert a specific character after pair(second) character. This kind of problem can occur while working with data, that require insertion of commas or any other special character mainly in Machine Learning domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using join() + list comprehensionThe combination of above method can be used to perform this particular task. List comprehension along with slicing can be used to convert string to list and join function can be used to rejoin them inserting required character between them.
# Python3 code to demonstrate working of# Insert character after every character pair# Using join() + list comprehension # initializing string test_str = "GeeksforGeeks" # printing original string print("The original string is : " + test_str) # Using join() + list comprehension# Insert character after every character pairres = ', '.join(test_str[i:i + 2] for i in range(0, len(test_str), 2)) # printing result print("The string after inserting comma after every character pair : " + res)
The original string is : GeeksforGeeks
The string after inserting comma after every character pair : Ge, ek, sf, or, Ge, ek, s
Method #2 : Using zip() + join()The combination of above functions can be used to perform this particular task. In this, zip function converts the characters to iterable tuples, split function is used to separate odd and even characters. Then list comprehension is responsible to convert the tuples to list of strings and at last result is joined using the join function.
# Python3 code to demonstrate working of# Insert character after every character pair# Using zip() + join() # initializing string test_str = "GeeksforGeeks" # printing original string print("The original string is : " + test_str) # Using zip() + join()# Insert character after every character pairres = ', '.join(a + b for a, b in zip(test_str[::2], test_str[1::2])) # printing result print("The string after inserting comma after every character pair : " + res)
The original string is : GeeksforGeeks
The string after inserting comma after every character pair : Ge, ek, sf, or, Ge, ek
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jul, 2019"
},
{
"code": null,
"e": 358,
"s": 28,
"text": "Sometimes, we can have a problem in which we need to insert a specific character after pair(second) character. This kind of problem can occur while working with data, that require insertion of commas or any other special character mainly in Machine Learning domain. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 644,
"s": 358,
"text": "Method #1 : Using join() + list comprehensionThe combination of above method can be used to perform this particular task. List comprehension along with slicing can be used to convert string to list and join function can be used to rejoin them inserting required character between them."
},
{
"code": "# Python3 code to demonstrate working of# Insert character after every character pair# Using join() + list comprehension # initializing string test_str = \"GeeksforGeeks\" # printing original string print(\"The original string is : \" + test_str) # Using join() + list comprehension# Insert character after every character pairres = ', '.join(test_str[i:i + 2] for i in range(0, len(test_str), 2)) # printing result print(\"The string after inserting comma after every character pair : \" + res)",
"e": 1138,
"s": 644,
"text": null
},
{
"code": null,
"e": 1266,
"s": 1138,
"text": "The original string is : GeeksforGeeks\nThe string after inserting comma after every character pair : Ge, ek, sf, or, Ge, ek, s\n"
},
{
"code": null,
"e": 1640,
"s": 1268,
"text": "Method #2 : Using zip() + join()The combination of above functions can be used to perform this particular task. In this, zip function converts the characters to iterable tuples, split function is used to separate odd and even characters. Then list comprehension is responsible to convert the tuples to list of strings and at last result is joined using the join function."
},
{
"code": "# Python3 code to demonstrate working of# Insert character after every character pair# Using zip() + join() # initializing string test_str = \"GeeksforGeeks\" # printing original string print(\"The original string is : \" + test_str) # Using zip() + join()# Insert character after every character pairres = ', '.join(a + b for a, b in zip(test_str[::2], test_str[1::2])) # printing result print(\"The string after inserting comma after every character pair : \" + res)",
"e": 2107,
"s": 1640,
"text": null
},
{
"code": null,
"e": 2232,
"s": 2107,
"text": "The original string is : GeeksforGeeks\nThe string after inserting comma after every character pair : Ge, ek, sf, or, Ge, ek\n"
},
{
"code": null,
"e": 2255,
"s": 2232,
"text": "Python string-programs"
},
{
"code": null,
"e": 2262,
"s": 2255,
"text": "Python"
},
{
"code": null,
"e": 2278,
"s": 2262,
"text": "Python Programs"
},
{
"code": null,
"e": 2376,
"s": 2278,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2394,
"s": 2376,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2436,
"s": 2394,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2458,
"s": 2436,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2493,
"s": 2458,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2519,
"s": 2493,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2562,
"s": 2519,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2584,
"s": 2562,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2623,
"s": 2584,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2661,
"s": 2623,
"text": "Python | Convert a list to dictionary"
}
] |
How to Install Eclipse for C++ on Linux?
|
16 Oct, 2021
Eclipse is an IDE (integrated development environment) used for building software. It was initially released by IBM on 7 November 2001. Using eclipse, we can develop applications with Java, PHP, and C/C++ programming languages. It’s one of the most popular open-source IDE among developers. In today’s article, we are going to cover how we can install Eclipse for C/C++ Developers to develop applications in C or C++ on a Linux machine.
Follow the below step-by-step guide to install Eclipse for C/C++:
Step 1: Download the eclipse launcher by going through this link:
downloading the eclipse
Step 2: Extract the downloaded file using the following command:
tar -xvf eclipse-cpp-2021-09-R-linux-gtk-x86_54.tar.gz
The tar is a utility tool to make operations on archives, to extract, to make, to list, and to rename the archives. Here, -xvf flag stands for extract, verbose, and file.
Extracting
Step 3: Navigate to the extracted folder and run the following commands to install Alacarte menu that will help us to create a desktop shortcut for Eclipse.
After extracting the eclipse installer, create a shortcut for the launcher:
Alacarte is a menu editor for the GNOME desktop. It is written in Python. It has been part of GNOME since the 2.16 release. To install the Alacarte for creating a custom shortcut icon.
sudo apt-get install alacarte
installing alacarte
Step 4: Configuring the shortcut by running the alacarte:
alacarte
Creating shortcut
In the first step click on the New item button on the right side, a pop-up window will open as in the above figure. Select executable from the extracted folder and click on the ok button. This will create a shortcut application in the programs.
Step 5: To launch the eclipse simple search for Eclipse, a icon will appear and click enter. This will launch the Eclipse IDE.
Eclipse installed
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install and Use NVM on Windows?
How to Install Jupyter Notebook on MacOS?
How to Permanently Disable Swap in Linux?
How to Import JSON Data into SQL Server?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install and Use NVM on Windows?
How to Install Jupyter Notebook on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Oct, 2021"
},
{
"code": null,
"e": 465,
"s": 28,
"text": "Eclipse is an IDE (integrated development environment) used for building software. It was initially released by IBM on 7 November 2001. Using eclipse, we can develop applications with Java, PHP, and C/C++ programming languages. It’s one of the most popular open-source IDE among developers. In today’s article, we are going to cover how we can install Eclipse for C/C++ Developers to develop applications in C or C++ on a Linux machine."
},
{
"code": null,
"e": 531,
"s": 465,
"text": "Follow the below step-by-step guide to install Eclipse for C/C++:"
},
{
"code": null,
"e": 597,
"s": 531,
"text": "Step 1: Download the eclipse launcher by going through this link:"
},
{
"code": null,
"e": 621,
"s": 597,
"text": "downloading the eclipse"
},
{
"code": null,
"e": 686,
"s": 621,
"text": "Step 2: Extract the downloaded file using the following command:"
},
{
"code": null,
"e": 741,
"s": 686,
"text": "tar -xvf eclipse-cpp-2021-09-R-linux-gtk-x86_54.tar.gz"
},
{
"code": null,
"e": 912,
"s": 741,
"text": "The tar is a utility tool to make operations on archives, to extract, to make, to list, and to rename the archives. Here, -xvf flag stands for extract, verbose, and file."
},
{
"code": null,
"e": 923,
"s": 912,
"text": "Extracting"
},
{
"code": null,
"e": 1080,
"s": 923,
"text": "Step 3: Navigate to the extracted folder and run the following commands to install Alacarte menu that will help us to create a desktop shortcut for Eclipse."
},
{
"code": null,
"e": 1156,
"s": 1080,
"text": "After extracting the eclipse installer, create a shortcut for the launcher:"
},
{
"code": null,
"e": 1341,
"s": 1156,
"text": "Alacarte is a menu editor for the GNOME desktop. It is written in Python. It has been part of GNOME since the 2.16 release. To install the Alacarte for creating a custom shortcut icon."
},
{
"code": null,
"e": 1371,
"s": 1341,
"text": "sudo apt-get install alacarte"
},
{
"code": null,
"e": 1391,
"s": 1371,
"text": "installing alacarte"
},
{
"code": null,
"e": 1449,
"s": 1391,
"text": "Step 4: Configuring the shortcut by running the alacarte:"
},
{
"code": null,
"e": 1458,
"s": 1449,
"text": "alacarte"
},
{
"code": null,
"e": 1476,
"s": 1458,
"text": "Creating shortcut"
},
{
"code": null,
"e": 1721,
"s": 1476,
"text": "In the first step click on the New item button on the right side, a pop-up window will open as in the above figure. Select executable from the extracted folder and click on the ok button. This will create a shortcut application in the programs."
},
{
"code": null,
"e": 1848,
"s": 1721,
"text": "Step 5: To launch the eclipse simple search for Eclipse, a icon will appear and click enter. This will launch the Eclipse IDE."
},
{
"code": null,
"e": 1866,
"s": 1848,
"text": "Eclipse installed"
},
{
"code": null,
"e": 1881,
"s": 1866,
"text": "how-to-install"
},
{
"code": null,
"e": 1888,
"s": 1881,
"text": "Picked"
},
{
"code": null,
"e": 1895,
"s": 1888,
"text": "How To"
},
{
"code": null,
"e": 1914,
"s": 1895,
"text": "Installation Guide"
},
{
"code": null,
"e": 2012,
"s": 1914,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2061,
"s": 2012,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 2100,
"s": 2061,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 2142,
"s": 2100,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2184,
"s": 2142,
"text": "How to Permanently Disable Swap in Linux?"
},
{
"code": null,
"e": 2225,
"s": 2184,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 2258,
"s": 2225,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2293,
"s": 2258,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2332,
"s": 2293,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 2374,
"s": 2332,
"text": "How to Install Jupyter Notebook on MacOS?"
}
] |
Create digital clock using Python-Turtle
|
02 Jul, 2021
Prerequisites: Turtle Programming in PythonTurtle is a special feature of Python. Using Turtle, we can easily draw on a drawing board. First, we import the turtle module. Then create a window, next we create a turtle object and using the turtle methods we can draw in the drawing board.Installation: To install this module type the below command in the terminal.
pip install turtle
Note: To create a clock we will use the ‘time’ and ‘DateTime’ module of Python also, To install time use the following command:
Below is the implementation.
Python3
import timeimport datetime as dtimport turtle # create a turtle to display timet = turtle.Turtle() # create a turtle to create rectangle boxt1 = turtle.Turtle() # create screens = turtle.Screen() # set background color of the screens.bgcolor("green") # obtain current hour, minute and second# from the systemsec = dt.datetime.now().secondmin = dt.datetime.now().minutehr = dt.datetime.now().hourt1.pensize(3)t1.color('black')t1.penup() # set the position of turtlet1.goto(-20, 0)t1.pendown() # create rectangular boxfor i in range(2): t1.forward(200) t1.left(90) t1.forward(70) t1.left(90) # hide the turtlet1.hideturtle() while True: t.hideturtle() t.clear() # display the time t.write(str(hr).zfill(2) +":"+str(min).zfill(2)+":" +str(sec).zfill(2), font =("Arial Narrow", 35, "bold")) time.sleep(1) sec+= 1 if sec == 60: sec = 0 min+= 1 if min == 60: min = 0 hr+= 1 if hr == 13: hr = 1
Output:
romy421kumari
anikaseth98
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 419,
"s": 54,
"text": "Prerequisites: Turtle Programming in PythonTurtle is a special feature of Python. Using Turtle, we can easily draw on a drawing board. First, we import the turtle module. Then create a window, next we create a turtle object and using the turtle methods we can draw in the drawing board.Installation: To install this module type the below command in the terminal. "
},
{
"code": null,
"e": 438,
"s": 419,
"text": "pip install turtle"
},
{
"code": null,
"e": 566,
"s": 438,
"text": "Note: To create a clock we will use the ‘time’ and ‘DateTime’ module of Python also, To install time use the following command:"
},
{
"code": null,
"e": 597,
"s": 566,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 605,
"s": 597,
"text": "Python3"
},
{
"code": "import timeimport datetime as dtimport turtle # create a turtle to display timet = turtle.Turtle() # create a turtle to create rectangle boxt1 = turtle.Turtle() # create screens = turtle.Screen() # set background color of the screens.bgcolor(\"green\") # obtain current hour, minute and second# from the systemsec = dt.datetime.now().secondmin = dt.datetime.now().minutehr = dt.datetime.now().hourt1.pensize(3)t1.color('black')t1.penup() # set the position of turtlet1.goto(-20, 0)t1.pendown() # create rectangular boxfor i in range(2): t1.forward(200) t1.left(90) t1.forward(70) t1.left(90) # hide the turtlet1.hideturtle() while True: t.hideturtle() t.clear() # display the time t.write(str(hr).zfill(2) +\":\"+str(min).zfill(2)+\":\" +str(sec).zfill(2), font =(\"Arial Narrow\", 35, \"bold\")) time.sleep(1) sec+= 1 if sec == 60: sec = 0 min+= 1 if min == 60: min = 0 hr+= 1 if hr == 13: hr = 1",
"e": 1628,
"s": 605,
"text": null
},
{
"code": null,
"e": 1638,
"s": 1628,
"text": "Output: "
},
{
"code": null,
"e": 1654,
"s": 1640,
"text": "romy421kumari"
},
{
"code": null,
"e": 1666,
"s": 1654,
"text": "anikaseth98"
},
{
"code": null,
"e": 1680,
"s": 1666,
"text": "Python-turtle"
},
{
"code": null,
"e": 1687,
"s": 1680,
"text": "Python"
}
] |
Python – Regex Lookahead
|
03 Jan, 2021
Lookahead is used as an assertion in Python regular expressions to determine success or failure whether the pattern is ahead i.e to the right of the parser’s current position. They don’t match anything. Hence, they are called as zero-width assertions.
Syntax:
# Positive lookahead
(?=<lookahead_regex>)
Example 1:
Python3
# importing regeximport re # lookahead exampleexample = re.search(r'geeks(?=[a-z])', "geeksforgeeks") # display outputprint("Pattern:", example.group())print("Pattern found from index:", example.start(), "to", example.end())
Output:
Pattern: geeks
Pattern found from index: 0 to 5
The lookahead assertion (?=[a-z]) specifies that what follows geeks must be a lowercase alphabetic character. In this case, it’s the character f, a match is found.
Example 2:
Python3
# importing regeximport re # Lookahead exampleexample = re.search(r'geeks(?=[a-z])', "geeks123") # outputprint(example)
Output:
None
In the above example, the output is None because the next character after geeks is 1. It is not a lowercase alphabetic character.
Lookahead portion is not part of the search string. Hence, it is termed as zero width assertion. They are important when you don’t want the output to return lookahead portion present in search string but want to use it to match pattern which is followed by a particular section. Below example will make this clear.
Example 3:
Python3
# import required moduleimport re # using lookaheadexample1 = re.search(r'geeks(?=[a-z])', "geeksforgeeks") print('Using lookahead:', example1.group()) # without using lookaheadexample2 = re.search(r'geeks([a-z])', "geeksforgeeks") print('Without using lookahead:', example2.group())
Output:
Using lookahead: geeks
Without using lookahead: geeksf
Using lookahead the output generated is ‘geeks’ whereas without using lookahead the output generated is geeksf. The f is consumed by regex and it becomes part of the search string.
Negative lookahead is opposite of lookahead. It is to assure that the search string is not followed by <lookahead_regex>.
Syntax:
# Negative Lookahead
(?!<lookahead_regex>)
Example 4:
Python3
# import required moduleimport re # positive lookaheadexample1 = re.search('geeks(?=[a-z])', 'geeksforgeeks')print('Positive Lookahead:', example1.group()) # negative lookaheadexample2 = re.search('geeks(?![a-z])', 'geeks123')print('Negative Lookahead:', example2.group())
Output:
Positive Lookahead: geeks
Negative Lookahead: geeks
In the above example, the output is geeks because search string geeks here is not followed by lowercase letters.
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 304,
"s": 52,
"text": "Lookahead is used as an assertion in Python regular expressions to determine success or failure whether the pattern is ahead i.e to the right of the parser’s current position. They don’t match anything. Hence, they are called as zero-width assertions."
},
{
"code": null,
"e": 312,
"s": 304,
"text": "Syntax:"
},
{
"code": null,
"e": 356,
"s": 312,
"text": "# Positive lookahead\n(?=<lookahead_regex>)\n"
},
{
"code": null,
"e": 367,
"s": 356,
"text": "Example 1:"
},
{
"code": null,
"e": 375,
"s": 367,
"text": "Python3"
},
{
"code": "# importing regeximport re # lookahead exampleexample = re.search(r'geeks(?=[a-z])', \"geeksforgeeks\") # display outputprint(\"Pattern:\", example.group())print(\"Pattern found from index:\", example.start(), \"to\", example.end())",
"e": 612,
"s": 375,
"text": null
},
{
"code": null,
"e": 620,
"s": 612,
"text": "Output:"
},
{
"code": null,
"e": 668,
"s": 620,
"text": "Pattern: geeks\nPattern found from index: 0 to 5"
},
{
"code": null,
"e": 832,
"s": 668,
"text": "The lookahead assertion (?=[a-z]) specifies that what follows geeks must be a lowercase alphabetic character. In this case, it’s the character f, a match is found."
},
{
"code": null,
"e": 843,
"s": 832,
"text": "Example 2:"
},
{
"code": null,
"e": 851,
"s": 843,
"text": "Python3"
},
{
"code": "# importing regeximport re # Lookahead exampleexample = re.search(r'geeks(?=[a-z])', \"geeks123\") # outputprint(example)",
"e": 993,
"s": 851,
"text": null
},
{
"code": null,
"e": 1001,
"s": 993,
"text": "Output:"
},
{
"code": null,
"e": 1006,
"s": 1001,
"text": "None"
},
{
"code": null,
"e": 1136,
"s": 1006,
"text": "In the above example, the output is None because the next character after geeks is 1. It is not a lowercase alphabetic character."
},
{
"code": null,
"e": 1451,
"s": 1136,
"text": "Lookahead portion is not part of the search string. Hence, it is termed as zero width assertion. They are important when you don’t want the output to return lookahead portion present in search string but want to use it to match pattern which is followed by a particular section. Below example will make this clear."
},
{
"code": null,
"e": 1462,
"s": 1451,
"text": "Example 3:"
},
{
"code": null,
"e": 1470,
"s": 1462,
"text": "Python3"
},
{
"code": "# import required moduleimport re # using lookaheadexample1 = re.search(r'geeks(?=[a-z])', \"geeksforgeeks\") print('Using lookahead:', example1.group()) # without using lookaheadexample2 = re.search(r'geeks([a-z])', \"geeksforgeeks\") print('Without using lookahead:', example2.group())",
"e": 1798,
"s": 1470,
"text": null
},
{
"code": null,
"e": 1806,
"s": 1798,
"text": "Output:"
},
{
"code": null,
"e": 1861,
"s": 1806,
"text": "Using lookahead: geeks\nWithout using lookahead: geeksf"
},
{
"code": null,
"e": 2043,
"s": 1861,
"text": "Using lookahead the output generated is ‘geeks’ whereas without using lookahead the output generated is geeksf. The f is consumed by regex and it becomes part of the search string. "
},
{
"code": null,
"e": 2165,
"s": 2043,
"text": "Negative lookahead is opposite of lookahead. It is to assure that the search string is not followed by <lookahead_regex>."
},
{
"code": null,
"e": 2173,
"s": 2165,
"text": "Syntax:"
},
{
"code": null,
"e": 2218,
"s": 2173,
"text": "# Negative Lookahead\n(?!<lookahead_regex>) \n"
},
{
"code": null,
"e": 2229,
"s": 2218,
"text": "Example 4:"
},
{
"code": null,
"e": 2237,
"s": 2229,
"text": "Python3"
},
{
"code": "# import required moduleimport re # positive lookaheadexample1 = re.search('geeks(?=[a-z])', 'geeksforgeeks')print('Positive Lookahead:', example1.group()) # negative lookaheadexample2 = re.search('geeks(?![a-z])', 'geeks123')print('Negative Lookahead:', example2.group())",
"e": 2552,
"s": 2237,
"text": null
},
{
"code": null,
"e": 2560,
"s": 2552,
"text": "Output:"
},
{
"code": null,
"e": 2612,
"s": 2560,
"text": "Positive Lookahead: geeks\nNegative Lookahead: geeks"
},
{
"code": null,
"e": 2725,
"s": 2612,
"text": "In the above example, the output is geeks because search string geeks here is not followed by lowercase letters."
},
{
"code": null,
"e": 2738,
"s": 2725,
"text": "python-regex"
},
{
"code": null,
"e": 2745,
"s": 2738,
"text": "Python"
},
{
"code": null,
"e": 2843,
"s": 2745,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2861,
"s": 2843,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2903,
"s": 2861,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2925,
"s": 2903,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2960,
"s": 2925,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2986,
"s": 2960,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3018,
"s": 2986,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3047,
"s": 3018,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3077,
"s": 3047,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3104,
"s": 3077,
"text": "Python Classes and Objects"
}
] |
CONVERT_TZ() function in MySQL
|
25 Nov, 2020
CONVERT_TZ() function in MySQL is used to convert the given DateTime from One time zone to another time zone. If the arguments are invalid, the function will return NULL.
Syntax :
CONVERT_TZ (dt, from_tz,to_tz)
Parameters: This method accepts a three-parameter.
dt: The given DateTime which we want to convert.
from_tz: The time zone from which we want to convert DateTime.
to_tz: The time zone in which we want to convert DateTime.
Returns :It returns the DateTime after converting into a specified timezone.
Example-1 :
Converting the DateTime from GMT(Greenwich Mean Time) to IST(Indian Standard time)
SELECT CONVERT_TZ('2020-11-19 19:59:00', '+00:00', '+05:30')
As IST_TIME;
Output :
Example-2 :
Converting the DateTime from GMT(Greenwich Mean Time) to GST (Gulf Standard Time)
SELECT CONVERT_TZ('2020-11-19 10:53:00', '+00:00', '+04:00')
As GST_TIME;
Output :
Example-3 :
The CONVERT_TZ function can be used to set the value of columns. To demonstrate create a table named FlightDetails.
CREATE TABLE FlightDetails(
FlightId INT NOT NULL,
Source VARCHAR(20) NOT NULL,
Destination VARCHAR(20) NOT NULL,
DepartureTime DATETIME NOT NULL,
ArrivalTime DATETIME NOT NULL,
PRIMARY KEY(FlightId )
);
Now inserting values in FlightDetails table. We will use the CONVERT_TZ function to check departure and arrival times in both source and destination airports.
INSERT INTO
FlightDetails(FlightId, Source, Destination,
DepartureTime , ArrivalTime )
VALUES
(12345, 'New York', 'New Delhi', '2020-11-19 10:53:00',
'2020-11-20 12:53:00');
Now, checking the FlightDetails
SELECT
FlightId , Source ,Destination ,
DepartureTime AS DepTimeInEST ,
CONVERT_TZ(DepartureTime, '-05:00', '+05:30')
As DepTimeInIST ,
ArrivalTime AS ArrTimeInIST ,
CONVERT_TZ(ArrivalTime , '+05:30', '-05:00')
As ArrTimeInEST
FROM FlightDetails;
Output :
DBMS-SQL
mysql
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
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Nov, 2020"
},
{
"code": null,
"e": 200,
"s": 28,
"text": "CONVERT_TZ() function in MySQL is used to convert the given DateTime from One time zone to another time zone. If the arguments are invalid, the function will return NULL. "
},
{
"code": null,
"e": 209,
"s": 200,
"text": "Syntax :"
},
{
"code": null,
"e": 241,
"s": 209,
"text": "CONVERT_TZ (dt, from_tz,to_tz) "
},
{
"code": null,
"e": 292,
"s": 241,
"text": "Parameters: This method accepts a three-parameter."
},
{
"code": null,
"e": 341,
"s": 292,
"text": "dt: The given DateTime which we want to convert."
},
{
"code": null,
"e": 404,
"s": 341,
"text": "from_tz: The time zone from which we want to convert DateTime."
},
{
"code": null,
"e": 463,
"s": 404,
"text": "to_tz: The time zone in which we want to convert DateTime."
},
{
"code": null,
"e": 540,
"s": 463,
"text": "Returns :It returns the DateTime after converting into a specified timezone."
},
{
"code": null,
"e": 552,
"s": 540,
"text": "Example-1 :"
},
{
"code": null,
"e": 635,
"s": 552,
"text": "Converting the DateTime from GMT(Greenwich Mean Time) to IST(Indian Standard time)"
},
{
"code": null,
"e": 711,
"s": 635,
"text": "SELECT CONVERT_TZ('2020-11-19 19:59:00', '+00:00', '+05:30') \nAs IST_TIME;\n"
},
{
"code": null,
"e": 720,
"s": 711,
"text": "Output :"
},
{
"code": null,
"e": 732,
"s": 720,
"text": "Example-2 :"
},
{
"code": null,
"e": 814,
"s": 732,
"text": "Converting the DateTime from GMT(Greenwich Mean Time) to GST (Gulf Standard Time)"
},
{
"code": null,
"e": 890,
"s": 814,
"text": "SELECT CONVERT_TZ('2020-11-19 10:53:00', '+00:00', '+04:00') \nAs GST_TIME;\n"
},
{
"code": null,
"e": 899,
"s": 890,
"text": "Output :"
},
{
"code": null,
"e": 911,
"s": 899,
"text": "Example-3 :"
},
{
"code": null,
"e": 1027,
"s": 911,
"text": "The CONVERT_TZ function can be used to set the value of columns. To demonstrate create a table named FlightDetails."
},
{
"code": null,
"e": 1234,
"s": 1027,
"text": "CREATE TABLE FlightDetails(\nFlightId INT NOT NULL,\nSource VARCHAR(20) NOT NULL,\nDestination VARCHAR(20) NOT NULL,\nDepartureTime DATETIME NOT NULL,\nArrivalTime DATETIME NOT NULL,\nPRIMARY KEY(FlightId )\n);\n\n\n"
},
{
"code": null,
"e": 1393,
"s": 1234,
"text": "Now inserting values in FlightDetails table. We will use the CONVERT_TZ function to check departure and arrival times in both source and destination airports."
},
{
"code": null,
"e": 1618,
"s": 1393,
"text": "INSERT INTO \nFlightDetails(FlightId, Source, Destination, \n DepartureTime , ArrivalTime )\nVALUES\n(12345, 'New York', 'New Delhi', '2020-11-19 10:53:00',\n '2020-11-20 12:53:00');\n"
},
{
"code": null,
"e": 1650,
"s": 1618,
"text": "Now, checking the FlightDetails"
},
{
"code": null,
"e": 1906,
"s": 1650,
"text": "SELECT \nFlightId , Source ,Destination , \nDepartureTime AS DepTimeInEST ,\nCONVERT_TZ(DepartureTime, '-05:00', '+05:30') \nAs DepTimeInIST ,\n\nArrivalTime AS ArrTimeInIST ,\nCONVERT_TZ(ArrivalTime , '+05:30', '-05:00') \nAs ArrTimeInEST \nFROM FlightDetails;\n"
},
{
"code": null,
"e": 1915,
"s": 1906,
"text": "Output :"
},
{
"code": null,
"e": 1924,
"s": 1915,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1930,
"s": 1924,
"text": "mysql"
},
{
"code": null,
"e": 1934,
"s": 1930,
"text": "SQL"
},
{
"code": null,
"e": 1938,
"s": 1934,
"text": "SQL"
},
{
"code": null,
"e": 2036,
"s": 1938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2102,
"s": 2036,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2126,
"s": 2102,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2159,
"s": 2126,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2191,
"s": 2159,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2208,
"s": 2191,
"text": "SQL using Python"
},
{
"code": null,
"e": 2286,
"s": 2208,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2322,
"s": 2286,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2352,
"s": 2322,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2383,
"s": 2352,
"text": "SQL Query to Compare Two Dates"
}
] |
Check if sums of i-th row and i-th column are same in matrix
|
15 Jun, 2022
Given a matrix mat[][], we have to check if the sum of i-th row is equal to the sum of i-th column or not.
Examples:
Input : 1 2 3 4
9 5 3 1
0 3 5 6
0 4 5 6
Output : Yes
Sums of 1st row = 10 and 1st column
are same, i.e., 10
Expected time complexity is O(m x n) where m is a number of rows and n is a number of columns.
The idea is really simple. We use a nested loop to calculate the sum of each row and column and then check whether their sum is equal or not.
The implementation of the above idea is given below.
C++
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std;const int MAX = 100; // Function to check the if sum of a row// is same as corresponding columnbool areSumSame(int a[][MAX], int n, int m){ int sum1 = 0, sum2 = 0; for (int i = 0; i < n; i++) { sum1 = 0, sum2 = 0; for (int j = 0; j < m; j++) { sum1 += a[i][j]; sum2 += a[j][i]; } if (sum1 == sum2) return true; } return false;} // Driver Codeint main(){ int n = 4; // number of rows int m = 4; // number of columns int M[n][MAX] = { { 1, 2, 3, 4 }, { 9, 5, 3, 1 }, { 0, 3, 5, 6 }, { 0, 4, 5, 6 } }; cout << areSumSame(M, n, m) << "\n"; return 0;}
// Java program to check if there are two// adjacent set bits.public class GFG { // Function to check the if sum of a row // is same as corresponding column static boolean areSumSame(int a[][], int n, int m) { int sum1 = 0, sum2 = 0; for (int i = 0; i < n; i++) { sum1 = 0; sum2 = 0; for (int j = 0; j < m; j++) { sum1 += a[i][j]; sum2 += a[j][i]; } if (sum1 == sum2) return true; } return false; } // Driver code public static void main(String args[]) { int n = 4; // number of rows int m = 4; // number of columns int M[][] = { { 1, 2, 3, 4 }, { 9, 5, 3, 1 }, { 0, 3, 5, 6 }, { 0, 4, 5, 6 } }; if(areSumSame(M, n, m) == true) System.out.print("1\n"); else System.out.print("0\n"); }} // This code is contributed by Sam007.
# Python3 program to check the if# sum of a row is same as# corresponding columnMAX = 100; # Function to check the if sum# of a row is same as# corresponding columndef areSumSame(a, n, m): sum1 = 0 sum2 = 0 for i in range(0, n): sum1 = 0 sum2 = 0 for j in range(0, m): sum1 += a[i][j] sum2 += a[j][i] if (sum1 == sum2): return 1 return 0 # Driver Coden = 4; # number of rowsm = 4; # number of columnsM = [ [ 1, 2, 3, 4 ], [ 9, 5, 3, 1 ], [ 0, 3, 5, 6 ], [ 0, 4, 5, 6 ] ] print(areSumSame(M, n, m)) # This code is contributed by Sam007.
// C# program to check if there are two// adjacent set bits.using System; class GFG { // Function to check the if sum of a row // is same as corresponding column static bool areSumSame(int [,]a, int n, int m) { int sum1 = 0, sum2 = 0; for (int i = 0; i < n; i++) { sum1 = 0; sum2 = 0; for (int j = 0; j < m; j++) { sum1 += a[i,j]; sum2 += a[j,i]; } if (sum1 == sum2) return true; } return false; } // Driver code public static void Main () { int n = 4; // number of rows int m = 4; // number of columns int [,] M = { { 1, 2, 3, 4 }, { 9, 5, 3, 1 }, { 0, 3, 5, 6 }, { 0, 4, 5, 6 } }; if(areSumSame(M, n, m) == true) Console.Write("1\n"); else Console.Write("0\n"); }} // This code is contributed by Sam007.
<?php// Function to check the if// sum of a row is same as// corresponding columnfunction areSumSame($a, $n, $m){ $sum1 = 0; $sum2 = 0; for($i = 0; $i < $n; $i++) { $sum1 = 0; $sum2 = 0; for($j = 0; $j < $m; $j++) { $sum1 += $a[$i][$j]; $sum2 += $a[$j][$i]; } if ($sum1 == $sum2) return true ; } return false ;} // Driver code$n = 4 ; // number of rows$m = 4 ; // number of columns$M = array(array(1, 2, 3, 4), array(9, 5, 3, 1), array(0, 3, 5, 6), array(0, 4, 5, 6)); echo areSumSame($M, $n, $m) ; // This code is contributed// by ANKITRAI1?>
<script>// Java script program to check if there are two// adjacent set bits. // Function to check the if sum of a row // is same as corresponding column function areSumSame(a,n,m) { let sum1 = 0, sum2 = 0; for (let i = 0; i < n; i++) { sum1 = 0; sum2 = 0; for (let j = 0; j < m; j++) { sum1 += a[i][j]; sum2 += a[j][i]; } if (sum1 == sum2) return true; } return false; } // Driver code let n = 4; // number of rows let m = 4; // number of columns let M = [[1, 2, 3, 4 ], [ 9, 5, 3, 1], [ 0, 3, 5, 6 ], [ 0, 4, 5, 6 ]]; if(areSumSame(M, n, m) == true) document.write("1\n"); else document.write("0\n"); // This code is contributed by Bobby</script>
Output:
1
Time Complexity: O(n x m) Auxiliary Space: O(1)
This article is contributed by Aarti_Rathi and Sarthak Kohli. 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.
Sam007
ankthon
dilipkn13082001
gottumukkalabobby
sachinvinod1904
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
The Celebrity Problem
Find the number of islands | Set 1 (Using DFS)
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Count all possible paths from top left to bottom right of a mXn matrix
Unique paths in a Grid with Obstacles
Printing all solutions in N-Queen Problem
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 160,
"s": 52,
"text": "Given a matrix mat[][], we have to check if the sum of i-th row is equal to the sum of i-th column or not. "
},
{
"code": null,
"e": 171,
"s": 160,
"text": "Examples: "
},
{
"code": null,
"e": 306,
"s": 171,
"text": "Input : 1 2 3 4 \n 9 5 3 1\n 0 3 5 6 \n 0 4 5 6\nOutput : Yes\nSums of 1st row = 10 and 1st column \nare same, i.e., 10"
},
{
"code": null,
"e": 401,
"s": 306,
"text": "Expected time complexity is O(m x n) where m is a number of rows and n is a number of columns."
},
{
"code": null,
"e": 544,
"s": 401,
"text": "The idea is really simple. We use a nested loop to calculate the sum of each row and column and then check whether their sum is equal or not. "
},
{
"code": null,
"e": 599,
"s": 544,
"text": "The implementation of the above idea is given below. "
},
{
"code": null,
"e": 603,
"s": 599,
"text": "C++"
},
{
"code": null,
"e": 608,
"s": 603,
"text": "Java"
},
{
"code": null,
"e": 616,
"s": 608,
"text": "Python3"
},
{
"code": null,
"e": 619,
"s": 616,
"text": "C#"
},
{
"code": null,
"e": 623,
"s": 619,
"text": "PHP"
},
{
"code": null,
"e": 634,
"s": 623,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;const int MAX = 100; // Function to check the if sum of a row// is same as corresponding columnbool areSumSame(int a[][MAX], int n, int m){ int sum1 = 0, sum2 = 0; for (int i = 0; i < n; i++) { sum1 = 0, sum2 = 0; for (int j = 0; j < m; j++) { sum1 += a[i][j]; sum2 += a[j][i]; } if (sum1 == sum2) return true; } return false;} // Driver Codeint main(){ int n = 4; // number of rows int m = 4; // number of columns int M[n][MAX] = { { 1, 2, 3, 4 }, { 9, 5, 3, 1 }, { 0, 3, 5, 6 }, { 0, 4, 5, 6 } }; cout << areSumSame(M, n, m) << \"\\n\"; return 0;}",
"e": 1376,
"s": 634,
"text": null
},
{
"code": "// Java program to check if there are two// adjacent set bits.public class GFG { // Function to check the if sum of a row // is same as corresponding column static boolean areSumSame(int a[][], int n, int m) { int sum1 = 0, sum2 = 0; for (int i = 0; i < n; i++) { sum1 = 0; sum2 = 0; for (int j = 0; j < m; j++) { sum1 += a[i][j]; sum2 += a[j][i]; } if (sum1 == sum2) return true; } return false; } // Driver code public static void main(String args[]) { int n = 4; // number of rows int m = 4; // number of columns int M[][] = { { 1, 2, 3, 4 }, { 9, 5, 3, 1 }, { 0, 3, 5, 6 }, { 0, 4, 5, 6 } }; if(areSumSame(M, n, m) == true) System.out.print(\"1\\n\"); else System.out.print(\"0\\n\"); }} // This code is contributed by Sam007.",
"e": 2489,
"s": 1376,
"text": null
},
{
"code": "# Python3 program to check the if# sum of a row is same as# corresponding columnMAX = 100; # Function to check the if sum# of a row is same as# corresponding columndef areSumSame(a, n, m): sum1 = 0 sum2 = 0 for i in range(0, n): sum1 = 0 sum2 = 0 for j in range(0, m): sum1 += a[i][j] sum2 += a[j][i] if (sum1 == sum2): return 1 return 0 # Driver Coden = 4; # number of rowsm = 4; # number of columnsM = [ [ 1, 2, 3, 4 ], [ 9, 5, 3, 1 ], [ 0, 3, 5, 6 ], [ 0, 4, 5, 6 ] ] print(areSumSame(M, n, m)) # This code is contributed by Sam007.",
"e": 3133,
"s": 2489,
"text": null
},
{
"code": "// C# program to check if there are two// adjacent set bits.using System; class GFG { // Function to check the if sum of a row // is same as corresponding column static bool areSumSame(int [,]a, int n, int m) { int sum1 = 0, sum2 = 0; for (int i = 0; i < n; i++) { sum1 = 0; sum2 = 0; for (int j = 0; j < m; j++) { sum1 += a[i,j]; sum2 += a[j,i]; } if (sum1 == sum2) return true; } return false; } // Driver code public static void Main () { int n = 4; // number of rows int m = 4; // number of columns int [,] M = { { 1, 2, 3, 4 }, { 9, 5, 3, 1 }, { 0, 3, 5, 6 }, { 0, 4, 5, 6 } }; if(areSumSame(M, n, m) == true) Console.Write(\"1\\n\"); else Console.Write(\"0\\n\"); }} // This code is contributed by Sam007.",
"e": 4199,
"s": 3133,
"text": null
},
{
"code": "<?php// Function to check the if// sum of a row is same as// corresponding columnfunction areSumSame($a, $n, $m){ $sum1 = 0; $sum2 = 0; for($i = 0; $i < $n; $i++) { $sum1 = 0; $sum2 = 0; for($j = 0; $j < $m; $j++) { $sum1 += $a[$i][$j]; $sum2 += $a[$j][$i]; } if ($sum1 == $sum2) return true ; } return false ;} // Driver code$n = 4 ; // number of rows$m = 4 ; // number of columns$M = array(array(1, 2, 3, 4), array(9, 5, 3, 1), array(0, 3, 5, 6), array(0, 4, 5, 6)); echo areSumSame($M, $n, $m) ; // This code is contributed// by ANKITRAI1?>",
"e": 4880,
"s": 4199,
"text": null
},
{
"code": "<script>// Java script program to check if there are two// adjacent set bits. // Function to check the if sum of a row // is same as corresponding column function areSumSame(a,n,m) { let sum1 = 0, sum2 = 0; for (let i = 0; i < n; i++) { sum1 = 0; sum2 = 0; for (let j = 0; j < m; j++) { sum1 += a[i][j]; sum2 += a[j][i]; } if (sum1 == sum2) return true; } return false; } // Driver code let n = 4; // number of rows let m = 4; // number of columns let M = [[1, 2, 3, 4 ], [ 9, 5, 3, 1], [ 0, 3, 5, 6 ], [ 0, 4, 5, 6 ]]; if(areSumSame(M, n, m) == true) document.write(\"1\\n\"); else document.write(\"0\\n\"); // This code is contributed by Bobby</script>",
"e": 5885,
"s": 4880,
"text": null
},
{
"code": null,
"e": 5894,
"s": 5885,
"text": "Output: "
},
{
"code": null,
"e": 5896,
"s": 5894,
"text": "1"
},
{
"code": null,
"e": 5944,
"s": 5896,
"text": "Time Complexity: O(n x m) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6382,
"s": 5944,
"text": "This article is contributed by Aarti_Rathi and Sarthak Kohli. 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": 6389,
"s": 6382,
"text": "Sam007"
},
{
"code": null,
"e": 6397,
"s": 6389,
"text": "ankthon"
},
{
"code": null,
"e": 6413,
"s": 6397,
"text": "dilipkn13082001"
},
{
"code": null,
"e": 6431,
"s": 6413,
"text": "gottumukkalabobby"
},
{
"code": null,
"e": 6447,
"s": 6431,
"text": "sachinvinod1904"
},
{
"code": null,
"e": 6454,
"s": 6447,
"text": "Matrix"
},
{
"code": null,
"e": 6461,
"s": 6454,
"text": "Matrix"
},
{
"code": null,
"e": 6559,
"s": 6461,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6594,
"s": 6559,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 6638,
"s": 6594,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 6669,
"s": 6638,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 6693,
"s": 6669,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 6715,
"s": 6693,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 6762,
"s": 6715,
"text": "Find the number of islands | Set 1 (Using DFS)"
},
{
"code": null,
"e": 6844,
"s": 6762,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 6915,
"s": 6844,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 6953,
"s": 6915,
"text": "Unique paths in a Grid with Obstacles"
}
] |
Iterators in Java
|
21 Apr, 2022
A Java Cursor is an Iterator, which is used to iterate or traverse or retrieve a Collection or Stream object’s elements one by one. There are three cursors in Java.
IteratorEnumerationListIterator
Iterator
Enumeration
ListIterator
Note: SplitIterator can also be considered as a cursor as it is a type of Iterator only.
Iterators in Java are used in the Collection framework to retrieve elements one by one. It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can perform both read and remove operations. It is an improved version of Enumeration with the additional functionality of removing an element.
Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque, and all implemented classes of Map interface. Iterator is the only cursor available for the entire collection framework.Iterator object can be created by calling iterator() method present in Collection interface.
Syntax:
Iterator itr = c.iterator();
Note: Here “c” is any Collection object. itr is of type Iterator interface and refers to “c”.
Iterator interface defines three methods as listed below:
1. hasNext(): Returns true if the iteration has more elements.
public boolean hasNext();
2. next(): Returns the next element in the iteration. It throws NoSuchElementException if no more element is present.
public Object next();
3. remove(): Removes the next element in the iteration. This method can be called only once per call to next().
public void remove();
Note: remove() method can throw two exceptions namely as follows:
UnsupportedOperationException : If the remove operation is not supported by this iterator
IllegalStateException : If the next method has not yet been called, or the remove method has already been called after the last call to the next method.
In this section, we will try to understand how Java Iterator and its methods work internally. Let us take the following LinkedList object to understand this functionality.
List<String> cities = new LinkedList<>();
cities.add("G-1");
cities.add("G-2");
cities.add("G-3");
.
.
.
cities.add("G-n");
Now, let us create an Iterator object on List object as shown below:
Iterator<String> citiesIterator = cities.iterator();
The “citiesIteartor” iterator will look like –
Here Iterator’s Cursor is pointing before the first element of the List.
Now, we will run the following code snippet.
citiesIterator.hasNext();
citiesIterator.next();
When we run the above code snippet, Iterator’s Cursor points to the first element in the list as shown in the above diagram.
Now, we will run the following code snippet.
citiesIterator.hasNext();
citiesIterator.next();
When we run the above code snippet, Iterator’s Cursor points to the second element in the list as shown in the above diagram. Do this process to reach the Iterator’s Cursor to the end element of the List.
After reading the final element, if we run the below code snippet, it returns a “false” value.
citiesIterator.hasNext();
As Iterator’s Cursor points to the after the final element of the List, hasNext() method returns a false value.
Note: After observing all these diagrams, we can say that Java Iterator supports only Forward Direction Iteration as shown in the below diagram. So it is also known as Uni-Directional Cursor.
Example:
Java
// Java program to Demonstrate Iterator // Importing ArrayList and Iterator classes// from java.util packageimport java.util.ArrayList;import java.util.Iterator; // Main classpublic class Test { // Main driver method public static void main(String[] args) { // Creating an ArrayList class object // Declaring object of integer type ArrayList<Integer> al = new ArrayList<Integer>(); // Iterating over the List for (int i = 0; i < 10; i++) al.add(i); // Printing the elements in the List System.out.println(al); // At the beginning itr(cursor) will point to // index just before the first element in al Iterator<Integer> itr = al.iterator(); // Checking the next element where // condition holds true till there is single element // in the List using hasnext() method while (itr.hasNext()) { // Moving cursor to next element int i = itr.next(); // Getting elements one by one System.out.print(i + " "); // Removing odd elements if (i % 2 != 0) itr.remove(); } // Command for next line System.out.println(); // Printing the elements inside the object System.out.println(al); }}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9
[0, 2, 4, 6, 8]
Spliterators, like other Iterators, are for traversing the elements of a source. A source can be a Collection, an IO channel, or a generator function. It is included in JDK 8 for support of efficient parallel traversal(parallel programming) in addition to sequential traversal. Java Spliterator interface is an internal iterator that breaks the stream into smaller parts. These smaller parts can be processed in parallel.
Note: In real life programming, we may never need to use Spliterator directly. Under normal operations, it will behave exactly the same as Java Iterator.
We can use it for any Collection class.
It supports both READ and REMOVE operations.
It is a Universal Cursor for Collection API.
Method names are simple and easy to use them.
Also, there are certain limitations of Iterator which are listed as follows:
In CRUD Operations, it does NOT support CREATE and UPDATE operations.
It supports only Forward direction iteration that is a Uni-Directional Iterator.
Compare to Spliterator, it does NOT support iterating elements parallel which means it supports only Sequential iteration.
Compare to Spliterator, it does NOT support better performance to iterate large volume of data.
It is an interface used to get elements of legacy collections(Vector, Hashtable). Enumeration is the first iterator present from JDK 1.0, rests are included in JDK 1.2 with more functionality. Enumerations are also used to specify the input streams to a SequenceInputStream. We can create an Enumeration object by calling elements() method of vector class on any vector object
// Here "v" is an Vector class object. e is of
// type Enumeration interface and refers to "v"
Enumeration e = v.elements();
There are two methods in the Enumeration interface namely :
1. public boolean hasMoreElements(): This method tests if this enumeration contains more elements or not.
2. public Object nextElement(): This method returns the next element of this enumeration. It throws NoSuchElementException if no more element is present
Java
// Java program to demonstrate Enumeration // Importing Enumeration and Vector classes// from java.util packageimport java.util.Enumeration;import java.util.Vector; // Main classpublic class Test{ // Main driver method public static void main(String[] args) { // Creating a vector object Vector v = new Vector(); // Iterating over vector object for (int i = 0; i < 10; i++) v.addElement(i); // Printing elements in vector object System.out.println(v); // At beginning e(cursor) will point to // index just before the first element in v Enumeration e = v.elements(); // Checking the next element availability where // condition holds true till there is a single element // remaining in the List while (e.hasMoreElements()) { // Moving cursor to next element int i = (Integer)e.nextElement(); // Print above elements in object System.out.print(i + " "); } }}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9
There are certain limitations of enumeration which are as follows:
Enumeration is for legacy classes(Vector, Hashtable) only. Hence it is not a universal iterator.
Remove operations can’t be performed using Enumeration.
Only forward direction iterating is possible.
Both are Java Cursors.
Both are used to iterate a Collection of object elements one by one.
Both support READ or Retrieval operation.
Both are Uni-directional Java Cursors which means support only Forward Direction Iteration.
The following table describes the differences between Java Enumeration and Iterator:
It is only applicable for List collection implemented classes like ArrayList, LinkedList, etc. It provides bi-directional iteration. ListIterator must be used when we want to enumerate elements of List. This cursor has more functionality(methods) than iterator. ListIterator object can be created by calling listIterator() method present in the List interface.
ListIterator ltr = l.listIterator();
Note: Here “l” is any List object, ltr is of type. ListIterator interface and refers to “l”. ListIterator interface extends the Iterator interface. So all three methods of Iterator interface are available for ListIterator. In addition, there are six more methods.
1.1 hasNext(): Returns true if the iteration has more elements
public boolean hasNext();
1.2 next(): Same as next() method of Iterator. Returns the next element in the iteration.
public Object next();
1.3 nextIndex(): Returns the next element index or list size if the list iterator is at the end of the list.
public int nextIndex();
2.1 hasPrevious(): Returns true if the iteration has more elements while traversing backward.
public boolean hasPrevious();
2.2 previous(): Returns the previous element in the iteration and can throw NoSuchElementException if no more element present.
public Object previous();
2.3 previousIndex(): Returns the previous element index or -1 if the list iterator is at the beginning of the list,
public int previousIndex();
3.1 remove(): Same as remove() method of Iterator. Removes the next element in the iteration.
public void remove();
3.2 set(Object obj): Replaces the last element returned by next() or previous() with the specified element.
public void set(Object obj);
3.3 add(Object obj): Inserts the specified element into the list at the position before the element that would be returned by next()
public void add(Object obj);
Clearly, the three methods that ListIterator inherits from Iterator (hasNext(), next(), and remove()) do exactly the same thing in both interfaces. The hasPrevious() and the previous operations are exact analogues of hasNext() and next(). The former operations refer to the element before the (implicit) cursor, whereas the latter refers to the element after the cursor. The previous operation moves the cursor backward, whereas the next moves it forward.
ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().
1. set() method can throw 4 exceptions.
UnsupportedOperationException: if the set operation is not supported by this list iterator
ClassCastException: If the class of the specified element prevents it from being added to this list
IllegalArgumentException: If some aspect of the specified element prevents it from being added to this list
IllegalStateException: If neither next nor previous have been called, or remove or add have been called after the last call to next or previous
2. add() method can throw 3 exceptions.
UnsupportedOperationException: If the add method is not supported by this list iterator
ClassCastException: If the class of the specified element prevents it from being added to this list
IllegalArgumentException: If some aspect of this element prevents it from being added to this list
Example:
Java
// Java program to demonstrate ListIterator // Importing ArrayList and List iterator classes// from java.util packageimport java.util.ArrayList;import java.util.ListIterator; // Main classpublic class Test { // Main driver method public static void main(String[] args) { // Creating an object of ArrayList class ArrayList al = new ArrayList(); // Iterating over Arraylist object for (int i = 0; i < 10; i++) // Adding elements to the Arraylist object al.add(i); // Print and display all elements inside object // created above System.out.println(al); // At beginning ltr(cursor) will point to // index just before the first element in al ListIterator ltr = al.listIterator(); // Checking the next element availability while (ltr.hasNext()) { // Moving cursor to next element int i = (Integer)ltr.next(); // Getting even elements one by one System.out.print(i + " "); // Changing even numbers to odd and // adding modified number again in // iterator if (i % 2 == 0) { // Change to odd i++; // Set method to change value ltr.set(i); // To add ltr.add(i); } } // Print and display statements System.out.println(); System.out.println(al); }}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9
[1, 1, 1, 3, 3, 3, 5, 5, 5, 7, 7, 7, 9, 9, 9]
Note: Similarly, there are certain limitations with ListIterator. It is the most powerful iterator but it is only applicable for List implemented classes, so it is not a universal iterator.
Please note that initially, any iterator reference will point to the index just before the index of the first element in a collection.We don’t create objects of Enumeration, Iterator, ListIterator because they are interfaces. We use methods like elements(), iterator(), listIterator() to create objects. These methods have an anonymous Inner Class that extends respective interfaces and return this class object.
Please note that initially, any iterator reference will point to the index just before the index of the first element in a collection.
We don’t create objects of Enumeration, Iterator, ListIterator because they are interfaces. We use methods like elements(), iterator(), listIterator() to create objects. These methods have an anonymous Inner Class that extends respective interfaces and return this class object.
Note: The $ symbol in reference class name is a proof that concept of inner classes is used and these class objects are created.
This can be verified by the below code. For more on inner class refer
Java
// Java program to demonstrate iterators references // Importing required classes from java.util packageimport java.util.Enumeration;import java.util.Iterator;import java.util.ListIterator;import java.util.Vector; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of Vector class Vector v = new Vector(); // Creating three iterators Enumeration e = v.elements(); Iterator itr = v.iterator(); ListIterator ltr = v.listIterator(); // Print class names of iterators // using getClass() and getName() methods System.out.println(e.getClass().getName()); System.out.println(itr.getClass().getName()); System.out.println(ltr.getClass().getName()); }}
java.util.Vector$1
java.util.Vector$Itr
java.util.Vector$ListItr
RajivSingh2
simranarora5sos
solankimayank
arorakashish0911
nishkarshgandhi
surinderdawra388
arcsinrad3
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 219,
"s": 54,
"text": "A Java Cursor is an Iterator, which is used to iterate or traverse or retrieve a Collection or Stream object’s elements one by one. There are three cursors in Java."
},
{
"code": null,
"e": 251,
"s": 219,
"text": "IteratorEnumerationListIterator"
},
{
"code": null,
"e": 260,
"s": 251,
"text": "Iterator"
},
{
"code": null,
"e": 272,
"s": 260,
"text": "Enumeration"
},
{
"code": null,
"e": 285,
"s": 272,
"text": "ListIterator"
},
{
"code": null,
"e": 374,
"s": 285,
"text": "Note: SplitIterator can also be considered as a cursor as it is a type of Iterator only."
},
{
"code": null,
"e": 700,
"s": 374,
"text": "Iterators in Java are used in the Collection framework to retrieve elements one by one. It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can perform both read and remove operations. It is an improved version of Enumeration with the additional functionality of removing an element."
},
{
"code": null,
"e": 1055,
"s": 700,
"text": "Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque, and all implemented classes of Map interface. Iterator is the only cursor available for the entire collection framework.Iterator object can be created by calling iterator() method present in Collection interface."
},
{
"code": null,
"e": 1063,
"s": 1055,
"text": "Syntax:"
},
{
"code": null,
"e": 1092,
"s": 1063,
"text": "Iterator itr = c.iterator();"
},
{
"code": null,
"e": 1186,
"s": 1092,
"text": "Note: Here “c” is any Collection object. itr is of type Iterator interface and refers to “c”."
},
{
"code": null,
"e": 1244,
"s": 1186,
"text": "Iterator interface defines three methods as listed below:"
},
{
"code": null,
"e": 1307,
"s": 1244,
"text": "1. hasNext(): Returns true if the iteration has more elements."
},
{
"code": null,
"e": 1333,
"s": 1307,
"text": "public boolean hasNext();"
},
{
"code": null,
"e": 1451,
"s": 1333,
"text": "2. next(): Returns the next element in the iteration. It throws NoSuchElementException if no more element is present."
},
{
"code": null,
"e": 1473,
"s": 1451,
"text": "public Object next();"
},
{
"code": null,
"e": 1585,
"s": 1473,
"text": "3. remove(): Removes the next element in the iteration. This method can be called only once per call to next()."
},
{
"code": null,
"e": 1607,
"s": 1585,
"text": "public void remove();"
},
{
"code": null,
"e": 1673,
"s": 1607,
"text": "Note: remove() method can throw two exceptions namely as follows:"
},
{
"code": null,
"e": 1763,
"s": 1673,
"text": "UnsupportedOperationException : If the remove operation is not supported by this iterator"
},
{
"code": null,
"e": 1916,
"s": 1763,
"text": "IllegalStateException : If the next method has not yet been called, or the remove method has already been called after the last call to the next method."
},
{
"code": null,
"e": 2089,
"s": 1916,
"text": " In this section, we will try to understand how Java Iterator and its methods work internally. Let us take the following LinkedList object to understand this functionality."
},
{
"code": null,
"e": 2220,
"s": 2089,
"text": "List<String> cities = new LinkedList<>(); \ncities.add(\"G-1\"); \ncities.add(\"G-2\"); \ncities.add(\"G-3\"); \n. \n. \n. \ncities.add(\"G-n\");"
},
{
"code": null,
"e": 2289,
"s": 2220,
"text": "Now, let us create an Iterator object on List object as shown below:"
},
{
"code": null,
"e": 2342,
"s": 2289,
"text": "Iterator<String> citiesIterator = cities.iterator();"
},
{
"code": null,
"e": 2389,
"s": 2342,
"text": "The “citiesIteartor” iterator will look like –"
},
{
"code": null,
"e": 2462,
"s": 2389,
"text": "Here Iterator’s Cursor is pointing before the first element of the List."
},
{
"code": null,
"e": 2507,
"s": 2462,
"text": "Now, we will run the following code snippet."
},
{
"code": null,
"e": 2556,
"s": 2507,
"text": "citiesIterator.hasNext();\ncitiesIterator.next();"
},
{
"code": null,
"e": 2681,
"s": 2556,
"text": "When we run the above code snippet, Iterator’s Cursor points to the first element in the list as shown in the above diagram."
},
{
"code": null,
"e": 2726,
"s": 2681,
"text": "Now, we will run the following code snippet."
},
{
"code": null,
"e": 2775,
"s": 2726,
"text": "citiesIterator.hasNext();\ncitiesIterator.next();"
},
{
"code": null,
"e": 2980,
"s": 2775,
"text": "When we run the above code snippet, Iterator’s Cursor points to the second element in the list as shown in the above diagram. Do this process to reach the Iterator’s Cursor to the end element of the List."
},
{
"code": null,
"e": 3075,
"s": 2980,
"text": "After reading the final element, if we run the below code snippet, it returns a “false” value."
},
{
"code": null,
"e": 3101,
"s": 3075,
"text": "citiesIterator.hasNext();"
},
{
"code": null,
"e": 3213,
"s": 3101,
"text": "As Iterator’s Cursor points to the after the final element of the List, hasNext() method returns a false value."
},
{
"code": null,
"e": 3405,
"s": 3213,
"text": "Note: After observing all these diagrams, we can say that Java Iterator supports only Forward Direction Iteration as shown in the below diagram. So it is also known as Uni-Directional Cursor."
},
{
"code": null,
"e": 3414,
"s": 3405,
"text": "Example:"
},
{
"code": null,
"e": 3419,
"s": 3414,
"text": "Java"
},
{
"code": "// Java program to Demonstrate Iterator // Importing ArrayList and Iterator classes// from java.util packageimport java.util.ArrayList;import java.util.Iterator; // Main classpublic class Test { // Main driver method public static void main(String[] args) { // Creating an ArrayList class object // Declaring object of integer type ArrayList<Integer> al = new ArrayList<Integer>(); // Iterating over the List for (int i = 0; i < 10; i++) al.add(i); // Printing the elements in the List System.out.println(al); // At the beginning itr(cursor) will point to // index just before the first element in al Iterator<Integer> itr = al.iterator(); // Checking the next element where // condition holds true till there is single element // in the List using hasnext() method while (itr.hasNext()) { // Moving cursor to next element int i = itr.next(); // Getting elements one by one System.out.print(i + \" \"); // Removing odd elements if (i % 2 != 0) itr.remove(); } // Command for next line System.out.println(); // Printing the elements inside the object System.out.println(al); }}",
"e": 4741,
"s": 3419,
"text": null
},
{
"code": null,
"e": 4812,
"s": 4744,
"text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n0 1 2 3 4 5 6 7 8 9 \n[0, 2, 4, 6, 8]"
},
{
"code": null,
"e": 5236,
"s": 4814,
"text": "Spliterators, like other Iterators, are for traversing the elements of a source. A source can be a Collection, an IO channel, or a generator function. It is included in JDK 8 for support of efficient parallel traversal(parallel programming) in addition to sequential traversal. Java Spliterator interface is an internal iterator that breaks the stream into smaller parts. These smaller parts can be processed in parallel."
},
{
"code": null,
"e": 5392,
"s": 5238,
"text": "Note: In real life programming, we may never need to use Spliterator directly. Under normal operations, it will behave exactly the same as Java Iterator."
},
{
"code": null,
"e": 5432,
"s": 5392,
"text": "We can use it for any Collection class."
},
{
"code": null,
"e": 5477,
"s": 5432,
"text": "It supports both READ and REMOVE operations."
},
{
"code": null,
"e": 5522,
"s": 5477,
"text": "It is a Universal Cursor for Collection API."
},
{
"code": null,
"e": 5568,
"s": 5522,
"text": "Method names are simple and easy to use them."
},
{
"code": null,
"e": 5648,
"s": 5570,
"text": "Also, there are certain limitations of Iterator which are listed as follows: "
},
{
"code": null,
"e": 5720,
"s": 5650,
"text": "In CRUD Operations, it does NOT support CREATE and UPDATE operations."
},
{
"code": null,
"e": 5801,
"s": 5720,
"text": "It supports only Forward direction iteration that is a Uni-Directional Iterator."
},
{
"code": null,
"e": 5924,
"s": 5801,
"text": "Compare to Spliterator, it does NOT support iterating elements parallel which means it supports only Sequential iteration."
},
{
"code": null,
"e": 6020,
"s": 5924,
"text": "Compare to Spliterator, it does NOT support better performance to iterate large volume of data."
},
{
"code": null,
"e": 6401,
"s": 6022,
"text": "It is an interface used to get elements of legacy collections(Vector, Hashtable). Enumeration is the first iterator present from JDK 1.0, rests are included in JDK 1.2 with more functionality. Enumerations are also used to specify the input streams to a SequenceInputStream. We can create an Enumeration object by calling elements() method of vector class on any vector object "
},
{
"code": null,
"e": 6528,
"s": 6403,
"text": "// Here \"v\" is an Vector class object. e is of\n// type Enumeration interface and refers to \"v\"\nEnumeration e = v.elements();"
},
{
"code": null,
"e": 6591,
"s": 6530,
"text": "There are two methods in the Enumeration interface namely : "
},
{
"code": null,
"e": 6699,
"s": 6593,
"text": "1. public boolean hasMoreElements(): This method tests if this enumeration contains more elements or not."
},
{
"code": null,
"e": 6854,
"s": 6701,
"text": "2. public Object nextElement(): This method returns the next element of this enumeration. It throws NoSuchElementException if no more element is present"
},
{
"code": null,
"e": 6861,
"s": 6856,
"text": "Java"
},
{
"code": "// Java program to demonstrate Enumeration // Importing Enumeration and Vector classes// from java.util packageimport java.util.Enumeration;import java.util.Vector; // Main classpublic class Test{ // Main driver method public static void main(String[] args) { // Creating a vector object Vector v = new Vector(); // Iterating over vector object for (int i = 0; i < 10; i++) v.addElement(i); // Printing elements in vector object System.out.println(v); // At beginning e(cursor) will point to // index just before the first element in v Enumeration e = v.elements(); // Checking the next element availability where // condition holds true till there is a single element // remaining in the List while (e.hasMoreElements()) { // Moving cursor to next element int i = (Integer)e.nextElement(); // Print above elements in object System.out.print(i + \" \"); } }}",
"e": 7898,
"s": 6861,
"text": null
},
{
"code": null,
"e": 7910,
"s": 7901,
"text": "Output: "
},
{
"code": null,
"e": 7964,
"s": 7912,
"text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n0 1 2 3 4 5 6 7 8 9 "
},
{
"code": null,
"e": 8034,
"s": 7966,
"text": "There are certain limitations of enumeration which are as follows: "
},
{
"code": null,
"e": 8133,
"s": 8036,
"text": "Enumeration is for legacy classes(Vector, Hashtable) only. Hence it is not a universal iterator."
},
{
"code": null,
"e": 8189,
"s": 8133,
"text": "Remove operations can’t be performed using Enumeration."
},
{
"code": null,
"e": 8235,
"s": 8189,
"text": "Only forward direction iterating is possible."
},
{
"code": null,
"e": 8258,
"s": 8235,
"text": "Both are Java Cursors."
},
{
"code": null,
"e": 8327,
"s": 8258,
"text": "Both are used to iterate a Collection of object elements one by one."
},
{
"code": null,
"e": 8369,
"s": 8327,
"text": "Both support READ or Retrieval operation."
},
{
"code": null,
"e": 8461,
"s": 8369,
"text": "Both are Uni-directional Java Cursors which means support only Forward Direction Iteration."
},
{
"code": null,
"e": 8548,
"s": 8463,
"text": "The following table describes the differences between Java Enumeration and Iterator:"
},
{
"code": null,
"e": 8914,
"s": 8552,
"text": "It is only applicable for List collection implemented classes like ArrayList, LinkedList, etc. It provides bi-directional iteration. ListIterator must be used when we want to enumerate elements of List. This cursor has more functionality(methods) than iterator. ListIterator object can be created by calling listIterator() method present in the List interface. "
},
{
"code": null,
"e": 8953,
"s": 8916,
"text": "ListIterator ltr = l.listIterator();"
},
{
"code": null,
"e": 9218,
"s": 8953,
"text": "Note: Here “l” is any List object, ltr is of type. ListIterator interface and refers to “l”. ListIterator interface extends the Iterator interface. So all three methods of Iterator interface are available for ListIterator. In addition, there are six more methods. "
},
{
"code": null,
"e": 9283,
"s": 9220,
"text": "1.1 hasNext(): Returns true if the iteration has more elements"
},
{
"code": null,
"e": 9311,
"s": 9285,
"text": "public boolean hasNext();"
},
{
"code": null,
"e": 9403,
"s": 9313,
"text": "1.2 next(): Same as next() method of Iterator. Returns the next element in the iteration."
},
{
"code": null,
"e": 9427,
"s": 9405,
"text": "public Object next();"
},
{
"code": null,
"e": 9538,
"s": 9429,
"text": "1.3 nextIndex(): Returns the next element index or list size if the list iterator is at the end of the list."
},
{
"code": null,
"e": 9564,
"s": 9540,
"text": "public int nextIndex();"
},
{
"code": null,
"e": 9660,
"s": 9566,
"text": "2.1 hasPrevious(): Returns true if the iteration has more elements while traversing backward."
},
{
"code": null,
"e": 9692,
"s": 9662,
"text": "public boolean hasPrevious();"
},
{
"code": null,
"e": 9821,
"s": 9694,
"text": "2.2 previous(): Returns the previous element in the iteration and can throw NoSuchElementException if no more element present."
},
{
"code": null,
"e": 9849,
"s": 9823,
"text": "public Object previous();"
},
{
"code": null,
"e": 9967,
"s": 9851,
"text": "2.3 previousIndex(): Returns the previous element index or -1 if the list iterator is at the beginning of the list,"
},
{
"code": null,
"e": 9997,
"s": 9969,
"text": "public int previousIndex();"
},
{
"code": null,
"e": 10093,
"s": 9999,
"text": "3.1 remove(): Same as remove() method of Iterator. Removes the next element in the iteration."
},
{
"code": null,
"e": 10117,
"s": 10095,
"text": "public void remove();"
},
{
"code": null,
"e": 10227,
"s": 10119,
"text": "3.2 set(Object obj): Replaces the last element returned by next() or previous() with the specified element."
},
{
"code": null,
"e": 10259,
"s": 10229,
"text": "public void set(Object obj); "
},
{
"code": null,
"e": 10394,
"s": 10261,
"text": "3.3 add(Object obj): Inserts the specified element into the list at the position before the element that would be returned by next()"
},
{
"code": null,
"e": 10425,
"s": 10396,
"text": "public void add(Object obj);"
},
{
"code": null,
"e": 10883,
"s": 10427,
"text": "Clearly, the three methods that ListIterator inherits from Iterator (hasNext(), next(), and remove()) do exactly the same thing in both interfaces. The hasPrevious() and the previous operations are exact analogues of hasNext() and next(). The former operations refer to the element before the (implicit) cursor, whereas the latter refers to the element after the cursor. The previous operation moves the cursor backward, whereas the next moves it forward."
},
{
"code": null,
"e": 11081,
"s": 10885,
"text": "ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next()."
},
{
"code": null,
"e": 11124,
"s": 11083,
"text": "1. set() method can throw 4 exceptions. "
},
{
"code": null,
"e": 11217,
"s": 11126,
"text": "UnsupportedOperationException: if the set operation is not supported by this list iterator"
},
{
"code": null,
"e": 11317,
"s": 11217,
"text": "ClassCastException: If the class of the specified element prevents it from being added to this list"
},
{
"code": null,
"e": 11425,
"s": 11317,
"text": "IllegalArgumentException: If some aspect of the specified element prevents it from being added to this list"
},
{
"code": null,
"e": 11569,
"s": 11425,
"text": "IllegalStateException: If neither next nor previous have been called, or remove or add have been called after the last call to next or previous"
},
{
"code": null,
"e": 11612,
"s": 11571,
"text": "2. add() method can throw 3 exceptions. "
},
{
"code": null,
"e": 11702,
"s": 11614,
"text": "UnsupportedOperationException: If the add method is not supported by this list iterator"
},
{
"code": null,
"e": 11802,
"s": 11702,
"text": "ClassCastException: If the class of the specified element prevents it from being added to this list"
},
{
"code": null,
"e": 11901,
"s": 11802,
"text": "IllegalArgumentException: If some aspect of this element prevents it from being added to this list"
},
{
"code": null,
"e": 11912,
"s": 11903,
"text": "Example:"
},
{
"code": null,
"e": 11919,
"s": 11914,
"text": "Java"
},
{
"code": "// Java program to demonstrate ListIterator // Importing ArrayList and List iterator classes// from java.util packageimport java.util.ArrayList;import java.util.ListIterator; // Main classpublic class Test { // Main driver method public static void main(String[] args) { // Creating an object of ArrayList class ArrayList al = new ArrayList(); // Iterating over Arraylist object for (int i = 0; i < 10; i++) // Adding elements to the Arraylist object al.add(i); // Print and display all elements inside object // created above System.out.println(al); // At beginning ltr(cursor) will point to // index just before the first element in al ListIterator ltr = al.listIterator(); // Checking the next element availability while (ltr.hasNext()) { // Moving cursor to next element int i = (Integer)ltr.next(); // Getting even elements one by one System.out.print(i + \" \"); // Changing even numbers to odd and // adding modified number again in // iterator if (i % 2 == 0) { // Change to odd i++; // Set method to change value ltr.set(i); // To add ltr.add(i); } } // Print and display statements System.out.println(); System.out.println(al); }}",
"e": 13402,
"s": 11919,
"text": null
},
{
"code": null,
"e": 13414,
"s": 13405,
"text": "Output: "
},
{
"code": null,
"e": 13514,
"s": 13416,
"text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n0 1 2 3 4 5 6 7 8 9 \n[1, 1, 1, 3, 3, 3, 5, 5, 5, 7, 7, 7, 9, 9, 9]"
},
{
"code": null,
"e": 13704,
"s": 13514,
"text": "Note: Similarly, there are certain limitations with ListIterator. It is the most powerful iterator but it is only applicable for List implemented classes, so it is not a universal iterator."
},
{
"code": null,
"e": 14117,
"s": 13704,
"text": "Please note that initially, any iterator reference will point to the index just before the index of the first element in a collection.We don’t create objects of Enumeration, Iterator, ListIterator because they are interfaces. We use methods like elements(), iterator(), listIterator() to create objects. These methods have an anonymous Inner Class that extends respective interfaces and return this class object."
},
{
"code": null,
"e": 14252,
"s": 14117,
"text": "Please note that initially, any iterator reference will point to the index just before the index of the first element in a collection."
},
{
"code": null,
"e": 14531,
"s": 14252,
"text": "We don’t create objects of Enumeration, Iterator, ListIterator because they are interfaces. We use methods like elements(), iterator(), listIterator() to create objects. These methods have an anonymous Inner Class that extends respective interfaces and return this class object."
},
{
"code": null,
"e": 14661,
"s": 14531,
"text": "Note: The $ symbol in reference class name is a proof that concept of inner classes is used and these class objects are created. "
},
{
"code": null,
"e": 14732,
"s": 14661,
"text": "This can be verified by the below code. For more on inner class refer "
},
{
"code": null,
"e": 14739,
"s": 14734,
"text": "Java"
},
{
"code": "// Java program to demonstrate iterators references // Importing required classes from java.util packageimport java.util.Enumeration;import java.util.Iterator;import java.util.ListIterator;import java.util.Vector; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of Vector class Vector v = new Vector(); // Creating three iterators Enumeration e = v.elements(); Iterator itr = v.iterator(); ListIterator ltr = v.listIterator(); // Print class names of iterators // using getClass() and getName() methods System.out.println(e.getClass().getName()); System.out.println(itr.getClass().getName()); System.out.println(ltr.getClass().getName()); }}",
"e": 15544,
"s": 14739,
"text": null
},
{
"code": null,
"e": 15612,
"s": 15547,
"text": "java.util.Vector$1\njava.util.Vector$Itr\njava.util.Vector$ListItr"
},
{
"code": null,
"e": 15626,
"s": 15614,
"text": "RajivSingh2"
},
{
"code": null,
"e": 15642,
"s": 15626,
"text": "simranarora5sos"
},
{
"code": null,
"e": 15656,
"s": 15642,
"text": "solankimayank"
},
{
"code": null,
"e": 15673,
"s": 15656,
"text": "arorakashish0911"
},
{
"code": null,
"e": 15689,
"s": 15673,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 15706,
"s": 15689,
"text": "surinderdawra388"
},
{
"code": null,
"e": 15717,
"s": 15706,
"text": "arcsinrad3"
},
{
"code": null,
"e": 15734,
"s": 15717,
"text": "Java-Collections"
},
{
"code": null,
"e": 15739,
"s": 15734,
"text": "Java"
},
{
"code": null,
"e": 15744,
"s": 15739,
"text": "Java"
},
{
"code": null,
"e": 15761,
"s": 15744,
"text": "Java-Collections"
},
{
"code": null,
"e": 15859,
"s": 15761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15910,
"s": 15859,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 15941,
"s": 15910,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 15960,
"s": 15941,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 15990,
"s": 15960,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 16008,
"s": 15990,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 16023,
"s": 16008,
"text": "Stream In Java"
},
{
"code": null,
"e": 16043,
"s": 16023,
"text": "Collections in Java"
},
{
"code": null,
"e": 16075,
"s": 16043,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 16099,
"s": 16075,
"text": "Singleton Class in Java"
}
] |
How to Detect Idle Time in JavaScript ?
|
31 Dec, 2019
The idle time is the time that the user doesn’t interact with a web-page. This interaction can be either moving the mouse, clicking on the page or using the keyboard. This time can be detected to execute certain events that may need to occur after a certain period of idle time.
Method 1: Using JavaScript: For the implementation, two functions are created, one is the function that resets the timer whenever user interaction is detected and the other is the function that would be executed periodically during the time the user is idle. The reset function consists of the setInterval() function, which is used to create a new interval that will repeatedly invoke another function. The timer created is assigned to a variable that will be used to clear out the old-timer whenever this function is called again on user interaction.
This function is invoked by binding it to the events that cause interaction to the page. These include methods like onload, onmousemove, onmousedown, ontouchstart, onclick and onkeypress.
The other function which will be invoked when the user is idle can be used to keep track of the time and perform actions when the user has been inactive for a longer time. An example of this would be to log out the user when inactive for more than a specified time.
Example:
<!DOCTYPE html><html> <head> <title> How to detect idle time in JavaScript ? </title></head> <body> <h1 style="color:green"> GeeksforGeeks </h1> <b> How to detect idle time in JavaScript elegantly? </b> <p> The timer will be incremented every second to denote the idle time. Interaction with the mouse or keyboard will reset and hide the timer. </p> <p class="timertext" style="font-size: 1.5rem;"> You are idle for <span class="secs"></span> seconds. </p> <script type="text/javascript"> let timer, currSeconds = 0; function resetTimer() { /* Hide the timer text */ document.querySelector(".timertext") .style.display = 'none'; /* Clear the previous interval */ clearInterval(timer); /* Reset the seconds of the timer */ currSeconds = 0; /* Set a new interval */ timer = setInterval(startIdleTimer, 1000); } // Define the events that // would reset the timer window.onload = resetTimer; window.onmousemove = resetTimer; window.onmousedown = resetTimer; window.ontouchstart = resetTimer; window.onclick = resetTimer; window.onkeypress = resetTimer; function startIdleTimer() { /* Increment the timer seconds */ currSeconds++; /* Set the timer text to the new value */ document.querySelector(".secs") .textContent = currSeconds; /* Display the timer text */ document.querySelector(".timertext") .style.display = 'block'; } </script></body> </html>
Output:
After Interacting with the page:
After Not interacting with the page:
Method 2: Using jQuery: It similar to the above method, however here a new timer is not created every time when user interaction is detected. Instead, the running timer is reset to 0 whenever user interaction is detected. For the implementation, two functions are created, one is the function that resets the timer to 0 whenever user interaction is detected and the other is the function that would be executed periodically during the time the user is idle.A new variable is defined which will globally represent the current time of the idle timer.
Using the document.ready() event, a timer with the setInterval() function is created which repeatedly invokes another function that handles what will happen when the user is idle for a specified time. The reset function consists of a simple statement that will change the value of the timer variable to 0, effectively resetting the current idle time. This function is invoked by binding it to the events that cause interaction to the page. These include methods like onload, onmousemove, onmousedown, ontouchstart, onclick and onkeypress.
Example:
<!DOCTYPE html><html> <head> <title> How to detect idle time in JavaScript ? </title> <script src="https://code.jquery.com/jquery-3.4.1.min.js"> </script></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to detect idle time in JavaScript elegantly? </b> <p> The timer will be incremented every second to denote the idle time. Interaction with the mouse or keyboard will reset and hide the timer. </p> <p class="timertext" style="font-size: 1.5rem;"> You are idle for <span class="secs"></span> seconds. </p> <script type="text/javascript"> var currSeconds = 0; $(document).ready(function() { /* Increment the idle time counter every second */ let idleInterval = setInterval(timerIncrement, 1000); /* Zero the idle timer on mouse movement */ $(this).mousemove(resetTimer); $(this).keypress(resetTimer); }); function resetTimer() { /* Hide the timer text */ document.querySelector(".timertext") .style.display = 'none'; currSeconds = 0; } function timerIncrement() { currSeconds = currSeconds + 1; /* Set the timer text to the new value */ document.querySelector(".secs") .textContent = currSeconds; /* Display the timer text */ document.querySelector(".timertext") .style.display = 'block'; } </script></body> </html>
Output:
After Interacting with the page:
After Not interacting with the page:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Dec, 2019"
},
{
"code": null,
"e": 307,
"s": 28,
"text": "The idle time is the time that the user doesn’t interact with a web-page. This interaction can be either moving the mouse, clicking on the page or using the keyboard. This time can be detected to execute certain events that may need to occur after a certain period of idle time."
},
{
"code": null,
"e": 859,
"s": 307,
"text": "Method 1: Using JavaScript: For the implementation, two functions are created, one is the function that resets the timer whenever user interaction is detected and the other is the function that would be executed periodically during the time the user is idle. The reset function consists of the setInterval() function, which is used to create a new interval that will repeatedly invoke another function. The timer created is assigned to a variable that will be used to clear out the old-timer whenever this function is called again on user interaction."
},
{
"code": null,
"e": 1047,
"s": 859,
"text": "This function is invoked by binding it to the events that cause interaction to the page. These include methods like onload, onmousemove, onmousedown, ontouchstart, onclick and onkeypress."
},
{
"code": null,
"e": 1313,
"s": 1047,
"text": "The other function which will be invoked when the user is idle can be used to keep track of the time and perform actions when the user has been inactive for a longer time. An example of this would be to log out the user when inactive for more than a specified time."
},
{
"code": null,
"e": 1322,
"s": 1313,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to detect idle time in JavaScript ? </title></head> <body> <h1 style=\"color:green\"> GeeksforGeeks </h1> <b> How to detect idle time in JavaScript elegantly? </b> <p> The timer will be incremented every second to denote the idle time. Interaction with the mouse or keyboard will reset and hide the timer. </p> <p class=\"timertext\" style=\"font-size: 1.5rem;\"> You are idle for <span class=\"secs\"></span> seconds. </p> <script type=\"text/javascript\"> let timer, currSeconds = 0; function resetTimer() { /* Hide the timer text */ document.querySelector(\".timertext\") .style.display = 'none'; /* Clear the previous interval */ clearInterval(timer); /* Reset the seconds of the timer */ currSeconds = 0; /* Set a new interval */ timer = setInterval(startIdleTimer, 1000); } // Define the events that // would reset the timer window.onload = resetTimer; window.onmousemove = resetTimer; window.onmousedown = resetTimer; window.ontouchstart = resetTimer; window.onclick = resetTimer; window.onkeypress = resetTimer; function startIdleTimer() { /* Increment the timer seconds */ currSeconds++; /* Set the timer text to the new value */ document.querySelector(\".secs\") .textContent = currSeconds; /* Display the timer text */ document.querySelector(\".timertext\") .style.display = 'block'; } </script></body> </html>",
"e": 3181,
"s": 1322,
"text": null
},
{
"code": null,
"e": 3189,
"s": 3181,
"text": "Output:"
},
{
"code": null,
"e": 3222,
"s": 3189,
"text": "After Interacting with the page:"
},
{
"code": null,
"e": 3259,
"s": 3222,
"text": "After Not interacting with the page:"
},
{
"code": null,
"e": 3808,
"s": 3259,
"text": "Method 2: Using jQuery: It similar to the above method, however here a new timer is not created every time when user interaction is detected. Instead, the running timer is reset to 0 whenever user interaction is detected. For the implementation, two functions are created, one is the function that resets the timer to 0 whenever user interaction is detected and the other is the function that would be executed periodically during the time the user is idle.A new variable is defined which will globally represent the current time of the idle timer."
},
{
"code": null,
"e": 4347,
"s": 3808,
"text": "Using the document.ready() event, a timer with the setInterval() function is created which repeatedly invokes another function that handles what will happen when the user is idle for a specified time. The reset function consists of a simple statement that will change the value of the timer variable to 0, effectively resetting the current idle time. This function is invoked by binding it to the events that cause interaction to the page. These include methods like onload, onmousemove, onmousedown, ontouchstart, onclick and onkeypress."
},
{
"code": null,
"e": 4356,
"s": 4347,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to detect idle time in JavaScript ? </title> <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\"> </script></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to detect idle time in JavaScript elegantly? </b> <p> The timer will be incremented every second to denote the idle time. Interaction with the mouse or keyboard will reset and hide the timer. </p> <p class=\"timertext\" style=\"font-size: 1.5rem;\"> You are idle for <span class=\"secs\"></span> seconds. </p> <script type=\"text/javascript\"> var currSeconds = 0; $(document).ready(function() { /* Increment the idle time counter every second */ let idleInterval = setInterval(timerIncrement, 1000); /* Zero the idle timer on mouse movement */ $(this).mousemove(resetTimer); $(this).keypress(resetTimer); }); function resetTimer() { /* Hide the timer text */ document.querySelector(\".timertext\") .style.display = 'none'; currSeconds = 0; } function timerIncrement() { currSeconds = currSeconds + 1; /* Set the timer text to the new value */ document.querySelector(\".secs\") .textContent = currSeconds; /* Display the timer text */ document.querySelector(\".timertext\") .style.display = 'block'; } </script></body> </html>",
"e": 6087,
"s": 4356,
"text": null
},
{
"code": null,
"e": 6095,
"s": 6087,
"text": "Output:"
},
{
"code": null,
"e": 6128,
"s": 6095,
"text": "After Interacting with the page:"
},
{
"code": null,
"e": 6165,
"s": 6128,
"text": "After Not interacting with the page:"
},
{
"code": null,
"e": 6181,
"s": 6165,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 6188,
"s": 6181,
"text": "Picked"
},
{
"code": null,
"e": 6199,
"s": 6188,
"text": "JavaScript"
},
{
"code": null,
"e": 6216,
"s": 6199,
"text": "Web Technologies"
},
{
"code": null,
"e": 6243,
"s": 6216,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 6341,
"s": 6243,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6402,
"s": 6341,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6474,
"s": 6402,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 6514,
"s": 6474,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 6555,
"s": 6514,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 6607,
"s": 6555,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 6640,
"s": 6607,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 6701,
"s": 6640,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6751,
"s": 6701,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 6794,
"s": 6751,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
HTML | <frame> scrolling Attribute
|
28 Jun, 2021
The HTML <frame> scrolling attribute is used to specify that whether the scrollbar will be displayed or not in the <frame> element. Basically, the scrollbar is used when the content is larger than the Iframe Element.Syntax:
<frame scrolling="auto|yes|no">
Attribute Values:
auto: It has the default value. The scrollbar appears when needed.
yes: This value shows the scrollbar in the iframe element.
no: This value does not show the scrollbar in the iframe element.
Note: The <frame> tag is not supported by HTML 5.Example:
html
<!DOCTYPE html><html> <head> <title> HTML frame scrolling Attribute </title></head> <frameset cols="30%, 40%, 30%"> <frame name = "left" src ="https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png" scrolling="auto" /> <frame name="middle" src="https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png" scrolling="yes" /> <frame name="right" src="https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png" scrolling="no" /> </frameset> </html>
Output:
Supported Browsers: The browsers supported by HTML <frame> scrolling attribute are listed below:
Internet Explorer (before IE 9)
Firefox
Opera (upto 12.0)
ysachin2314
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 254,
"s": 28,
"text": "The HTML <frame> scrolling attribute is used to specify that whether the scrollbar will be displayed or not in the <frame> element. Basically, the scrollbar is used when the content is larger than the Iframe Element.Syntax: "
},
{
"code": null,
"e": 286,
"s": 254,
"text": "<frame scrolling=\"auto|yes|no\">"
},
{
"code": null,
"e": 306,
"s": 286,
"text": "Attribute Values: "
},
{
"code": null,
"e": 373,
"s": 306,
"text": "auto: It has the default value. The scrollbar appears when needed."
},
{
"code": null,
"e": 432,
"s": 373,
"text": "yes: This value shows the scrollbar in the iframe element."
},
{
"code": null,
"e": 498,
"s": 432,
"text": "no: This value does not show the scrollbar in the iframe element."
},
{
"code": null,
"e": 558,
"s": 498,
"text": "Note: The <frame> tag is not supported by HTML 5.Example: "
},
{
"code": null,
"e": 563,
"s": 558,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML frame scrolling Attribute </title></head> <frameset cols=\"30%, 40%, 30%\"> <frame name = \"left\" src =\"https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png\" scrolling=\"auto\" /> <frame name=\"middle\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png\" scrolling=\"yes\" /> <frame name=\"right\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png\" scrolling=\"no\" /> </frameset> </html> ",
"e": 1133,
"s": 563,
"text": null
},
{
"code": null,
"e": 1143,
"s": 1133,
"text": "Output: "
},
{
"code": null,
"e": 1241,
"s": 1143,
"text": "Supported Browsers: The browsers supported by HTML <frame> scrolling attribute are listed below: "
},
{
"code": null,
"e": 1273,
"s": 1241,
"text": "Internet Explorer (before IE 9)"
},
{
"code": null,
"e": 1281,
"s": 1273,
"text": "Firefox"
},
{
"code": null,
"e": 1300,
"s": 1281,
"text": "Opera (upto 12.0) "
},
{
"code": null,
"e": 1312,
"s": 1300,
"text": "ysachin2314"
},
{
"code": null,
"e": 1328,
"s": 1312,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1333,
"s": 1328,
"text": "HTML"
},
{
"code": null,
"e": 1350,
"s": 1333,
"text": "Web Technologies"
},
{
"code": null,
"e": 1355,
"s": 1350,
"text": "HTML"
}
] |
Python program to represent floating number as hexadecimal by IEEE 754 standard
|
26 May, 2021
Prerequisite : IEEE Standard 754 Floating Point NumbersGiven a floating point number, the task is to find the hexadecimal representation for the number by IEEE 754 standard.The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation which was established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE). The standard addressed many problems found in the diverse floating point implementations that made them difficult to use reliably and reduced their portability. IEEE Standard 754 floating point is the most common representation today for real numbers on computers, including Intel-based PC’s, Macs, and most Unix platforms.
Examples :
Input : -6744.90
Output : C5D2C733
Input : -263.3
Output : C383A666
Approach :
Check whether the number is positive or negative. Save the sign as 0 for positive and 1 for negative, and then convert the number into positive if it is negative.
Convert the floating point number to binary.
Separate the decimal part and the whole number part.
Calculate the exponent(E) and convert it to binary.
Find the mantissa.
Concatenate the sign of mantissa, exponent and the mantissa.
Convert it into hexadecimal.
Let’s write a Python program to represent a floating number as hexadecimal by IEEE 754 standard.
Python3
# Function for converting decimal to binarydef float_bin(my_number, places = 3): my_whole, my_dec = str(my_number).split(".") my_whole = int(my_whole) res = (str(bin(my_whole))+".").replace('0b','') for x in range(places): my_dec = str('0.')+str(my_dec) temp = '%1.20f' %(float(my_dec)*2) my_whole, my_dec = temp.split(".") res += my_whole return res def IEEE754(n) : # identifying whether the number # is positive or negative sign = 0 if n < 0 : sign = 1 n = n * (-1) p = 30 # convert float to binary dec = float_bin (n, places = p) dotPlace = dec.find('.') onePlace = dec.find('1') # finding the mantissa if onePlace > dotPlace: dec = dec.replace(".","") onePlace -= 1 dotPlace -= 1 elif onePlace < dotPlace: dec = dec.replace(".","") dotPlace -= 1 mantissa = dec[onePlace+1:] # calculating the exponent(E) exponent = dotPlace - onePlace exponent_bits = exponent + 127 # converting the exponent from # decimal to binary exponent_bits = bin(exponent_bits).replace("0b",'') mantissa = mantissa[0:23] # the IEEE754 notation in binary final = str(sign) + exponent_bits.zfill(8) + mantissa # convert the binary to hexadecimal hstr = '0x%0*X' %((len(final) + 3) // 4, int(final, 2)) return (hstr, final) # Driver Codeif __name__ == "__main__" : print (IEEE754(263.3)) print (IEEE754(-263.3))
4383A666
C383A666
mumairanwar
saurabh1990aror
Computer Organization and Architecture
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced RISC Machine (ARM) Processor
Difference between Cache Coherence and Memory Consistency
8085 program to subtract two BCD numbers
Basic Cache Optimization Techniques
Difference between Hardware and Peripherals
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 736,
"s": 28,
"text": "Prerequisite : IEEE Standard 754 Floating Point NumbersGiven a floating point number, the task is to find the hexadecimal representation for the number by IEEE 754 standard.The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation which was established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE). The standard addressed many problems found in the diverse floating point implementations that made them difficult to use reliably and reduced their portability. IEEE Standard 754 floating point is the most common representation today for real numbers on computers, including Intel-based PC’s, Macs, and most Unix platforms. "
},
{
"code": null,
"e": 749,
"s": 736,
"text": "Examples : "
},
{
"code": null,
"e": 822,
"s": 749,
"text": "Input : -6744.90\nOutput : C5D2C733\n\nInput : -263.3\nOutput : C383A666"
},
{
"code": null,
"e": 835,
"s": 822,
"text": "Approach : "
},
{
"code": null,
"e": 998,
"s": 835,
"text": "Check whether the number is positive or negative. Save the sign as 0 for positive and 1 for negative, and then convert the number into positive if it is negative."
},
{
"code": null,
"e": 1043,
"s": 998,
"text": "Convert the floating point number to binary."
},
{
"code": null,
"e": 1096,
"s": 1043,
"text": "Separate the decimal part and the whole number part."
},
{
"code": null,
"e": 1148,
"s": 1096,
"text": "Calculate the exponent(E) and convert it to binary."
},
{
"code": null,
"e": 1167,
"s": 1148,
"text": "Find the mantissa."
},
{
"code": null,
"e": 1228,
"s": 1167,
"text": "Concatenate the sign of mantissa, exponent and the mantissa."
},
{
"code": null,
"e": 1257,
"s": 1228,
"text": "Convert it into hexadecimal."
},
{
"code": null,
"e": 1356,
"s": 1257,
"text": "Let’s write a Python program to represent a floating number as hexadecimal by IEEE 754 standard. "
},
{
"code": null,
"e": 1364,
"s": 1356,
"text": "Python3"
},
{
"code": "# Function for converting decimal to binarydef float_bin(my_number, places = 3): my_whole, my_dec = str(my_number).split(\".\") my_whole = int(my_whole) res = (str(bin(my_whole))+\".\").replace('0b','') for x in range(places): my_dec = str('0.')+str(my_dec) temp = '%1.20f' %(float(my_dec)*2) my_whole, my_dec = temp.split(\".\") res += my_whole return res def IEEE754(n) : # identifying whether the number # is positive or negative sign = 0 if n < 0 : sign = 1 n = n * (-1) p = 30 # convert float to binary dec = float_bin (n, places = p) dotPlace = dec.find('.') onePlace = dec.find('1') # finding the mantissa if onePlace > dotPlace: dec = dec.replace(\".\",\"\") onePlace -= 1 dotPlace -= 1 elif onePlace < dotPlace: dec = dec.replace(\".\",\"\") dotPlace -= 1 mantissa = dec[onePlace+1:] # calculating the exponent(E) exponent = dotPlace - onePlace exponent_bits = exponent + 127 # converting the exponent from # decimal to binary exponent_bits = bin(exponent_bits).replace(\"0b\",'') mantissa = mantissa[0:23] # the IEEE754 notation in binary final = str(sign) + exponent_bits.zfill(8) + mantissa # convert the binary to hexadecimal hstr = '0x%0*X' %((len(final) + 3) // 4, int(final, 2)) return (hstr, final) # Driver Codeif __name__ == \"__main__\" : print (IEEE754(263.3)) print (IEEE754(-263.3))",
"e": 2838,
"s": 1364,
"text": null
},
{
"code": null,
"e": 2856,
"s": 2838,
"text": "4383A666\nC383A666"
},
{
"code": null,
"e": 2870,
"s": 2858,
"text": "mumairanwar"
},
{
"code": null,
"e": 2886,
"s": 2870,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2925,
"s": 2886,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 2932,
"s": 2925,
"text": "Python"
},
{
"code": null,
"e": 2948,
"s": 2932,
"text": "Python Programs"
},
{
"code": null,
"e": 3046,
"s": 2948,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3084,
"s": 3046,
"text": "Advanced RISC Machine (ARM) Processor"
},
{
"code": null,
"e": 3142,
"s": 3084,
"text": "Difference between Cache Coherence and Memory Consistency"
},
{
"code": null,
"e": 3183,
"s": 3142,
"text": "8085 program to subtract two BCD numbers"
},
{
"code": null,
"e": 3219,
"s": 3183,
"text": "Basic Cache Optimization Techniques"
},
{
"code": null,
"e": 3263,
"s": 3219,
"text": "Difference between Hardware and Peripherals"
},
{
"code": null,
"e": 3291,
"s": 3263,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3341,
"s": 3291,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3363,
"s": 3341,
"text": "Python map() function"
},
{
"code": null,
"e": 3381,
"s": 3363,
"text": "Python Dictionary"
}
] |
Working with Radio buttons and Check boxes in Selenium with Python
|
26 Oct, 2021
Prerequisite: Browser Automation Using Selenium
Requirement: You need to install chrome driver and set path. Click here to download.
Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python.
Approach:
Take any URL.
Select radio button.
Navigate radio button using xpath.
Select check boxes.
Navigate check box using xpath.
Use the copied xpaths in the below program.
Python3
# Import selenium modulefrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.common.keys import Keysimport time # Using chrome driverdriver = webdriver.Chrome() # Web page urldriver.get("https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407") # Selecting raido button# Select maledriver.find_element_by_xpath( '//*[@id="q26"]/table/tbody/tr[1]/td/label').click() # Selecting check box# Select sundaydriver.find_element_by_xpath( '//*[@id="q15"]/table/tbody/tr[1]/td/label').click() # Select mondaydriver.find_element_by_xpath( '//*[@id="q15"]/table/tbody/tr[2]/td/label').click()
Output:
simranarora5sos
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Oct, 2021"
},
{
"code": null,
"e": 76,
"s": 28,
"text": "Prerequisite: Browser Automation Using Selenium"
},
{
"code": null,
"e": 162,
"s": 76,
"text": "Requirement: You need to install chrome driver and set path. Click here to download. "
},
{
"code": null,
"e": 422,
"s": 162,
"text": "Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python."
},
{
"code": null,
"e": 432,
"s": 422,
"text": "Approach:"
},
{
"code": null,
"e": 446,
"s": 432,
"text": "Take any URL."
},
{
"code": null,
"e": 467,
"s": 446,
"text": "Select radio button."
},
{
"code": null,
"e": 502,
"s": 467,
"text": "Navigate radio button using xpath."
},
{
"code": null,
"e": 522,
"s": 502,
"text": "Select check boxes."
},
{
"code": null,
"e": 554,
"s": 522,
"text": "Navigate check box using xpath."
},
{
"code": null,
"e": 598,
"s": 554,
"text": "Use the copied xpaths in the below program."
},
{
"code": null,
"e": 606,
"s": 598,
"text": "Python3"
},
{
"code": "# Import selenium modulefrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.common.keys import Keysimport time # Using chrome driverdriver = webdriver.Chrome() # Web page urldriver.get(\"https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407\") # Selecting raido button# Select maledriver.find_element_by_xpath( '//*[@id=\"q26\"]/table/tbody/tr[1]/td/label').click() # Selecting check box# Select sundaydriver.find_element_by_xpath( '//*[@id=\"q15\"]/table/tbody/tr[1]/td/label').click() # Select mondaydriver.find_element_by_xpath( '//*[@id=\"q15\"]/table/tbody/tr[2]/td/label').click()",
"e": 1257,
"s": 606,
"text": null
},
{
"code": null,
"e": 1265,
"s": 1257,
"text": "Output:"
},
{
"code": null,
"e": 1281,
"s": 1265,
"text": "simranarora5sos"
},
{
"code": null,
"e": 1286,
"s": 1281,
"text": "Misc"
},
{
"code": null,
"e": 1291,
"s": 1286,
"text": "Misc"
},
{
"code": null,
"e": 1296,
"s": 1291,
"text": "Misc"
}
] |
Arrays in JavaScript - GeeksforGeeks
|
21 Jul, 2021
In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. Unlike most languages where array is a reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements.Declaration of an Array There are basically two ways to declare an array. Example:
var House = [ ]; // method 1 var House = new Array(); // method 2
But generally method 1 is preferred over the method 2. Let us understand the reason for this. Initialization of an Array Example (for Method 1):
javascript
// Initializing while declaringvar house = ["1BHK", "2BHK", "3BHK", "4BHK"];
Example (for Method 2):
javascript
// Initializing while declaring// Creates an array having elements 10, 20, 30, 40, 50var house = new Array(10, 20, 30, 40, 50); //Creates an array of 5 undefined elementsvar house1 = new Array(5); //Creates an array with element 1BHKvar home = new Array("!BHK");
As shown in above example the house contains 5 elements i.e. (10 , 20, 30, 40, 50) while house1 contains 5 undefined elements instead of having a single element 5. Hence, while working with numbers this method is generally not preferred but it works fine with Strings and Boolean as shown in the example above home contains a single element 1BHK.We can also update after initialization.
javascript
// Creates an array of 4 undefined elementsvar house1 = new Array(4); // Now assign valueshouse1[0] = "1BHK"house1[1] = "2BHK"house1[2] = "3BHK"house1[3] = "4BHK"
An array in JavaScript can hold different elements We can store Numbers, Strings and Boolean in a single array. Example:
javascript
// Storing number, boolean, strings in an Array var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];
Accessing Array Elements Array in JavaScript are indexed from 0 so we can access array elements as follows:
javascript
var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];alert(house[0]+" cost= "+house[1]);var cost_1BHK = house[1];var is_for_rent = house[5];alert("Cost of 1BHK = "+ cost_1BHK);alert("Is house for rent = ")+ is_for_rent);
Length property of an Array Length property of an Array returns the length of an Array. Length of an Array is always one more than the highest index of an Array. Example below illustrates the length property of an Array:
javascript
var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true]; //len contains the length of the arrayvar len = house.length;for (var i = 0; i < len; i++) alert(house[i]);
Note : All the above examples can be tested by typing them within the script tag of HTML For commonly used Array methods refer to the links below:
Functions Part 1
Functions Part 2
Functions Part 3
This article is contributed by Sumit Ghosh. 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.
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Shivam_k
gabaa406
himanimishra
javascript-array
javascript-basics
JavaScript-Misc
GBlog
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Socket Programming in C/C++
Top 10 Front End Developer Skills That You Need in 2022
DSA Sheet by Love Babbar
Must Do Coding Questions for Product Based Companies
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
|
[
{
"code": null,
"e": 29691,
"s": 29663,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 30100,
"s": 29691,
"text": "In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. Unlike most languages where array is a reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements.Declaration of an Array There are basically two ways to declare an array. Example: "
},
{
"code": null,
"e": 30168,
"s": 30100,
"text": "var House = [ ]; // method 1 var House = new Array(); // method 2 "
},
{
"code": null,
"e": 30314,
"s": 30168,
"text": "But generally method 1 is preferred over the method 2. Let us understand the reason for this. Initialization of an Array Example (for Method 1): "
},
{
"code": null,
"e": 30325,
"s": 30314,
"text": "javascript"
},
{
"code": "// Initializing while declaringvar house = [\"1BHK\", \"2BHK\", \"3BHK\", \"4BHK\"];",
"e": 30402,
"s": 30325,
"text": null
},
{
"code": null,
"e": 30427,
"s": 30402,
"text": "Example (for Method 2): "
},
{
"code": null,
"e": 30438,
"s": 30427,
"text": "javascript"
},
{
"code": "// Initializing while declaring// Creates an array having elements 10, 20, 30, 40, 50var house = new Array(10, 20, 30, 40, 50); //Creates an array of 5 undefined elementsvar house1 = new Array(5); //Creates an array with element 1BHKvar home = new Array(\"!BHK\");",
"e": 30703,
"s": 30438,
"text": null
},
{
"code": null,
"e": 31092,
"s": 30703,
"text": "As shown in above example the house contains 5 elements i.e. (10 , 20, 30, 40, 50) while house1 contains 5 undefined elements instead of having a single element 5. Hence, while working with numbers this method is generally not preferred but it works fine with Strings and Boolean as shown in the example above home contains a single element 1BHK.We can also update after initialization. "
},
{
"code": null,
"e": 31103,
"s": 31092,
"text": "javascript"
},
{
"code": "// Creates an array of 4 undefined elementsvar house1 = new Array(4); // Now assign valueshouse1[0] = \"1BHK\"house1[1] = \"2BHK\"house1[2] = \"3BHK\"house1[3] = \"4BHK\"",
"e": 31267,
"s": 31103,
"text": null
},
{
"code": null,
"e": 31390,
"s": 31267,
"text": "An array in JavaScript can hold different elements We can store Numbers, Strings and Boolean in a single array. Example: "
},
{
"code": null,
"e": 31401,
"s": 31390,
"text": "javascript"
},
{
"code": "// Storing number, boolean, strings in an Array var house = [\"1BHK\", 25000, \"2BHK\", 50000, \"Rent\", true]; ",
"e": 31508,
"s": 31401,
"text": null
},
{
"code": null,
"e": 31617,
"s": 31508,
"text": "Accessing Array Elements Array in JavaScript are indexed from 0 so we can access array elements as follows: "
},
{
"code": null,
"e": 31628,
"s": 31617,
"text": "javascript"
},
{
"code": "var house = [\"1BHK\", 25000, \"2BHK\", 50000, \"Rent\", true];alert(house[0]+\" cost= \"+house[1]);var cost_1BHK = house[1];var is_for_rent = house[5];alert(\"Cost of 1BHK = \"+ cost_1BHK);alert(\"Is house for rent = \")+ is_for_rent);",
"e": 31853,
"s": 31628,
"text": null
},
{
"code": null,
"e": 32075,
"s": 31853,
"text": "Length property of an Array Length property of an Array returns the length of an Array. Length of an Array is always one more than the highest index of an Array. Example below illustrates the length property of an Array: "
},
{
"code": null,
"e": 32086,
"s": 32075,
"text": "javascript"
},
{
"code": "var house = [\"1BHK\", 25000, \"2BHK\", 50000, \"Rent\", true]; //len contains the length of the arrayvar len = house.length;for (var i = 0; i < len; i++) alert(house[i]);",
"e": 32256,
"s": 32086,
"text": null
},
{
"code": null,
"e": 32405,
"s": 32256,
"text": "Note : All the above examples can be tested by typing them within the script tag of HTML For commonly used Array methods refer to the links below: "
},
{
"code": null,
"e": 32422,
"s": 32405,
"text": "Functions Part 1"
},
{
"code": null,
"e": 32439,
"s": 32422,
"text": "Functions Part 2"
},
{
"code": null,
"e": 32456,
"s": 32439,
"text": "Functions Part 3"
},
{
"code": null,
"e": 32876,
"s": 32456,
"text": "This article is contributed by Sumit Ghosh. 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": 33095,
"s": 32876,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 33104,
"s": 33095,
"text": "Shivam_k"
},
{
"code": null,
"e": 33113,
"s": 33104,
"text": "gabaa406"
},
{
"code": null,
"e": 33126,
"s": 33113,
"text": "himanimishra"
},
{
"code": null,
"e": 33143,
"s": 33126,
"text": "javascript-array"
},
{
"code": null,
"e": 33161,
"s": 33143,
"text": "javascript-basics"
},
{
"code": null,
"e": 33177,
"s": 33161,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 33183,
"s": 33177,
"text": "GBlog"
},
{
"code": null,
"e": 33194,
"s": 33183,
"text": "JavaScript"
},
{
"code": null,
"e": 33292,
"s": 33194,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33301,
"s": 33292,
"text": "Comments"
},
{
"code": null,
"e": 33314,
"s": 33301,
"text": "Old Comments"
},
{
"code": null,
"e": 33388,
"s": 33314,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 33416,
"s": 33388,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 33472,
"s": 33416,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 33497,
"s": 33472,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33550,
"s": 33497,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 33611,
"s": 33550,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 33656,
"s": 33611,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 33728,
"s": 33656,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 33797,
"s": 33728,
"text": "How to calculate the number of days between two dates in javascript?"
}
] |
How to Compress Files Faster with Pigz Tool in Linux - GeeksforGeeks
|
28 Jul, 2021
Pigz (parallel implementation of gzip) is a free, open-source multi-threaded compression software for Linux that compresses and uncompresses files. Pigz is pronounced as “pig-zee”, it compresses data using the zlib and pthread libraries and takes full advantage of many processors and cores. Pigz can archive larger files significantly quicker than gzip since it compresses using threads to make use of multiple CPUs and cores. To put it another way, pigz performs the same thing as gzip, but it distributes the work across multiple processors and cores while compressing, considerably speeding up the compression/decompression process. Let’s look at how to use Pigz in Linux to compress and decompress files in parallel.
Install Pigz in your Linux system using the following command:
$ sudo apt install pigz
Pigz breaks the input file into 128 KB chunks and compresses each one in turn. The compressed data is created in the gzip, zlib, or single-entry zip formats using the deflate compression method. It compresses files in the gzip (.gz) format by default.
For compressing a single file in a zip format, use the following syntax.
$ pigz archlinux-2021.07.01-x86-64.iso
The above command will compress the specified file, archlinux.iso, and save it in the current working directory as archlinux.iso.gz.
Please note that after compressing archlinux.iso, the above operation will erase the original file. Use -k (keep) to tell Pigz not to remove the original file after processing it if you don’t want it to be deleted.
Pigz does not have the ability to compress a folder by itself; it only compresses single files. Pigz is used in conjunction with the tar command for zip the directories as a workaround.
$ tar --use-compress-program="pigz -k " -cf test.tar.gz test
Pigz, as previously stated, takes full advantage of several CPUs and cores while compressing files. The -p switch can be used to change this behavior.
The following command, for example, will compress a file using the best compression algorithm and four processors while keeping the original file:
$ pigz -9 -k -p4 archlinux-2021.07.01-86x_64.iso
Use the -l flag to list the contents of the above-archived file without extracting it.
$ pigz -l archlinux-2021.07.01-x86-64.iso.gz
Use the -d option or the unpigz command to decompress a file or directory with pigz. The command for our compressed ISO file will be:
$ unpigz archlinux-2021.07.01-x86-64.iso.gz
or
$ pigz -d archlinux-2021.07.01-x86-64.iso
So, if you have a contemporary multi-processor, multi-core machine and want to compress larger files as quickly as possible while utilizing all of your CPU cores, pigz is an excellent option! Give it a shot and let us know what you think of the Pigz compression application in the comments below.
$ time gzip <file name>
$ time pigz <file name>
$ time gzip -d test.tar.gz
$ time pigz -d test.tar.gz
We can clearly see that in both the vases of compression and decompression pigz is faster than gzip.
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C
|
[
{
"code": null,
"e": 24561,
"s": 24533,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 25283,
"s": 24561,
"text": "Pigz (parallel implementation of gzip) is a free, open-source multi-threaded compression software for Linux that compresses and uncompresses files. Pigz is pronounced as “pig-zee”, it compresses data using the zlib and pthread libraries and takes full advantage of many processors and cores. Pigz can archive larger files significantly quicker than gzip since it compresses using threads to make use of multiple CPUs and cores. To put it another way, pigz performs the same thing as gzip, but it distributes the work across multiple processors and cores while compressing, considerably speeding up the compression/decompression process. Let’s look at how to use Pigz in Linux to compress and decompress files in parallel."
},
{
"code": null,
"e": 25346,
"s": 25283,
"text": "Install Pigz in your Linux system using the following command:"
},
{
"code": null,
"e": 25370,
"s": 25346,
"text": "$ sudo apt install pigz"
},
{
"code": null,
"e": 25622,
"s": 25370,
"text": "Pigz breaks the input file into 128 KB chunks and compresses each one in turn. The compressed data is created in the gzip, zlib, or single-entry zip formats using the deflate compression method. It compresses files in the gzip (.gz) format by default."
},
{
"code": null,
"e": 25695,
"s": 25622,
"text": "For compressing a single file in a zip format, use the following syntax."
},
{
"code": null,
"e": 25734,
"s": 25695,
"text": "$ pigz archlinux-2021.07.01-x86-64.iso"
},
{
"code": null,
"e": 25867,
"s": 25734,
"text": "The above command will compress the specified file, archlinux.iso, and save it in the current working directory as archlinux.iso.gz."
},
{
"code": null,
"e": 26082,
"s": 25867,
"text": "Please note that after compressing archlinux.iso, the above operation will erase the original file. Use -k (keep) to tell Pigz not to remove the original file after processing it if you don’t want it to be deleted."
},
{
"code": null,
"e": 26268,
"s": 26082,
"text": "Pigz does not have the ability to compress a folder by itself; it only compresses single files. Pigz is used in conjunction with the tar command for zip the directories as a workaround."
},
{
"code": null,
"e": 26329,
"s": 26268,
"text": "$ tar --use-compress-program=\"pigz -k \" -cf test.tar.gz test"
},
{
"code": null,
"e": 26480,
"s": 26329,
"text": "Pigz, as previously stated, takes full advantage of several CPUs and cores while compressing files. The -p switch can be used to change this behavior."
},
{
"code": null,
"e": 26627,
"s": 26480,
"text": "The following command, for example, will compress a file using the best compression algorithm and four processors while keeping the original file:"
},
{
"code": null,
"e": 26676,
"s": 26627,
"text": "$ pigz -9 -k -p4 archlinux-2021.07.01-86x_64.iso"
},
{
"code": null,
"e": 26763,
"s": 26676,
"text": "Use the -l flag to list the contents of the above-archived file without extracting it."
},
{
"code": null,
"e": 26808,
"s": 26763,
"text": "$ pigz -l archlinux-2021.07.01-x86-64.iso.gz"
},
{
"code": null,
"e": 26942,
"s": 26808,
"text": "Use the -d option or the unpigz command to decompress a file or directory with pigz. The command for our compressed ISO file will be:"
},
{
"code": null,
"e": 27031,
"s": 26942,
"text": "$ unpigz archlinux-2021.07.01-x86-64.iso.gz\nor\n$ pigz -d archlinux-2021.07.01-x86-64.iso"
},
{
"code": null,
"e": 27328,
"s": 27031,
"text": "So, if you have a contemporary multi-processor, multi-core machine and want to compress larger files as quickly as possible while utilizing all of your CPU cores, pigz is an excellent option! Give it a shot and let us know what you think of the Pigz compression application in the comments below."
},
{
"code": null,
"e": 27352,
"s": 27328,
"text": "$ time gzip <file name>"
},
{
"code": null,
"e": 27376,
"s": 27352,
"text": "$ time pigz <file name>"
},
{
"code": null,
"e": 27403,
"s": 27376,
"text": "$ time gzip -d test.tar.gz"
},
{
"code": null,
"e": 27430,
"s": 27403,
"text": "$ time pigz -d test.tar.gz"
},
{
"code": null,
"e": 27531,
"s": 27430,
"text": "We can clearly see that in both the vases of compression and decompression pigz is faster than gzip."
},
{
"code": null,
"e": 27538,
"s": 27531,
"text": "How To"
},
{
"code": null,
"e": 27549,
"s": 27538,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27647,
"s": 27549,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27656,
"s": 27647,
"text": "Comments"
},
{
"code": null,
"e": 27669,
"s": 27656,
"text": "Old Comments"
},
{
"code": null,
"e": 27703,
"s": 27669,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27752,
"s": 27703,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 27810,
"s": 27752,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 27852,
"s": 27810,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 27912,
"s": 27852,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 27952,
"s": 27912,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 27992,
"s": 27952,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 28019,
"s": 27992,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 28054,
"s": 28019,
"text": "cut command in Linux with examples"
}
] |
Insertion, Searching and Deletion in AVL trees containing a parent node pointer - GeeksforGeeks
|
14 Jul, 2021
AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes. The insertion and deletion in AVL trees have been discussed in the previous article. In this article, insert, search and delete operations are discussed on AVL trees that also have a parent pointer in their structure.
Definition of AVL tree node:
C++
struct AVLwithparent { // Pointer to the left and the // right subtree struct AVLwithparent* left; struct AVLwithparent* right; // Stores the data in the node int key; // Stores the parent pointer struct AVLwithparent* par; // Stores the height of the // current tree int height;}
Node: 30, Parent Node: NULL
Node: 20, Parent Node: 30
Node: 10, Parent Node: 20
Node: 25, Parent Node: 20
Node: 40, Parent Node: 30
Node: 50, Parent Node: 40
Representation of the Node:
Below is the example of an AVL tree containing a parent pointer:
Insert Operation: The insertion procedure is similar to that of a normal AVL tree without a parent pointer, but in this case, the parent pointers need to be updated with every insertion and rotation accordingly. Follow the steps below to perform insert operation:
Perform standard BST insert for the node to be placed at its correct position.
Increase the height of each node encountered by 1 while finding the correct position for the node to be inserted.
Update the parent and child pointers of the inserted node and its parent respectively.
Starting from the inserted node till the root node check if the AVL condition is satisfied for each node on this path.
If w is the node where the AVL condition is not satisfied then we have 4 cases:Left Left Case: (If the left subtree of the left child of w has the inserted node)Left Right Case: (If the right subtree of the left child of w has the inserted node)Right Left Case: (If the left subtree of the right child of w has the inserted node)Right Right Case: (If the right subtree of the right child of w has the inserted node)
Left Left Case: (If the left subtree of the left child of w has the inserted node)
Left Right Case: (If the right subtree of the left child of w has the inserted node)
Right Left Case: (If the left subtree of the right child of w has the inserted node)
Right Right Case: (If the right subtree of the right child of w has the inserted node)
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // AVL tree nodestruct AVLwithparent { struct AVLwithparent* left; struct AVLwithparent* right; int key; struct AVLwithparent* par; int height;}; // Function to update the height of// a node according to its children's// node's heightsvoid Updateheight( struct AVLwithparent* root){ if (root != NULL) { // Store the height of the // current node int val = 1; // Store the height of the left // and right substree if (root->left != NULL) val = root->left->height + 1; if (root->right != NULL) val = max( val, root->right->height + 1); // Update the height of the // current node root->height = val; }} // Function to handle Left Left Casestruct AVLwithparent* LLR( struct AVLwithparent* root){ // Create a reference to the // left child struct AVLwithparent* tmpnode = root->left; // Update the left child of the // root to the right child of the // current left child of the root root->left = tmpnode->right; // Update parent pointer of the // left child of the root node if (tmpnode->right != NULL) tmpnode->right->par = root; // Update the right child of // tmpnode to root tmpnode->right = root; // Update parent pointer of // the tmpnode tmpnode->par = root->par; // Update the parent pointer // of the root root->par = tmpnode; // Update tmpnode as the left or the // right child of its parent pointer // according to its key value if (tmpnode->par != NULL && root->key < tmpnode->par->key) { tmpnode->par->left = tmpnode; } else { if (tmpnode->par != NULL) tmpnode->par->right = tmpnode; } // Make tmpnode as the new root root = tmpnode; // Update the heights Updateheight(root->left); Updateheight(root->right); Updateheight(root); Updateheight(root->par); // Return the root node return root;} // Function to handle Right Right Casestruct AVLwithparent* RRR( struct AVLwithparent* root){ // Create a reference to the // right child struct AVLwithparent* tmpnode = root->right; // Update the right child of the // root as the left child of the // current right child of the root root->right = tmpnode->left; // Update parent pointer of the // right child of the root node if (tmpnode->left != NULL) tmpnode->left->par = root; // Update the left child of the // tmpnode to root tmpnode->left = root; // Update parent pointer of // the tmpnode tmpnode->par = root->par; // Update the parent pointer // of the root root->par = tmpnode; // Update tmpnode as the left or // the right child of its parent // pointer according to its key value if (tmpnode->par != NULL && root->key < tmpnode->par->key) { tmpnode->par->left = tmpnode; } else { if (tmpnode->par != NULL) tmpnode->par->right = tmpnode; } // Make tmpnode as the new root root = tmpnode; // Update the heights Updateheight(root->left); Updateheight(root->right); Updateheight(root); Updateheight(root->par); // Return the root node return root;} // Function to handle Left Right Casestruct AVLwithparent* LRR( struct AVLwithparent* root){ root->left = RRR(root->left); return LLR(root);} // Function to handle right left casestruct AVLwithparent* RLR( struct AVLwithparent* root){ root->right = LLR(root->right); return RRR(root);} // Function to insert a node in// the AVL treestruct AVLwithparent* Insert( struct AVLwithparent* root, struct AVLwithparent* parent, int key){ if (root == NULL) { // Create and assign values // to a new node root = new struct AVLwithparent; // If the root is NULL if (root == NULL) { cout << "Error in memory" << endl; } // Otherwise else { root->height = 1; root->left = NULL; root->right = NULL; root->par = parent; root->key = key; } } else if (root->key > key) { // Recur to the left subtree // to insert the node root->left = Insert(root->left, root, key); // Store the heights of the // left and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // Balance the tree if the // current node is not balanced if (abs(firstheight - secondheight) == 2) { if (root->left != NULL && key < root->left->key) { // Left Left Case root = LLR(root); } else { // Left Right Case root = LRR(root); } } } else if (root->key < key) { // Recur to the right subtree // to insert the node root->right = Insert(root->right, root, key); // Store the heights of the // left and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // Balance the tree if the // current node is not balanced if (abs(firstheight - secondheight) == 2) { if (root->right != NULL && key < root->right->key) { // Right Left Case root = RLR(root); } else { // Right Right Case root = RRR(root); } } } // Case when given key is already // in the tree else { } // Update the height of the // root node Updateheight(root); // Return the root node return root;} // Function to print the preorder// traversal of the AVL treevoid printpreorder( struct AVLwithparent* root){ // Print the node's value along // with its parent value cout << "Node: " << root->key << ", Parent Node: "; if (root->par != NULL) cout << root->par->key << endl; else cout << "NULL" << endl; // Recur to the left subtree if (root->left != NULL) { printpreorder(root->left); } // Recur to the right subtree if (root->right != NULL) { printpreorder(root->right); }} // Driver Codeint main(){ struct AVLwithparent* root; root = NULL; // Function Call to insert nodes root = Insert(root, NULL, 10); root = Insert(root, NULL, 20); root = Insert(root, NULL, 30); root = Insert(root, NULL, 40); root = Insert(root, NULL, 50); root = Insert(root, NULL, 25); // Function call to print the tree printpreorder(root);}
Node: 30, Parent Node: NULL
Node: 20, Parent Node: 30
Node: 10, Parent Node: 20
Node: 25, Parent Node: 20
Node: 40, Parent Node: 30
Node: 50, Parent Node: 40
Time Complexity: O(log N), where N is the number of nodes of the tree.Auxiliary Space: O(1)
Search Operation: The search operation in an AVL tree with parent pointers is similar to the search operation in a normal Binary Search Tree. Follow the steps below to perform search operation:
Start from the root node.
If the root node is NULL, return false.
Check if the current node’s value is equal to the value of the node to be searched. If yes, return true.
If the current node’s value is less than searched key then recur to the right subtree.
If the current node’s value is greater than searched key then recur to the left subtree.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // AVL tree nodestruct AVLwithparent { struct AVLwithparent* left; struct AVLwithparent* right; int key; struct AVLwithparent* par; int height;}; // Function to update the height of// a node according to its children's// node's heightsvoid Updateheight(struct AVLwithparent* root){ if (root != NULL) { // Store the height of the // current node int val = 1; // Store the height of the left // and the right substree if (root->left != NULL) val = root->left->height + 1; if (root->right != NULL) val = max( val, root->right->height + 1); // Update the height of the // current node root->height = val; }} // Function to handle Left Left Casestruct AVLwithparent* LLR( struct AVLwithparent* root){ // Create a reference to the // left child struct AVLwithparent* tmpnode = root->left; // Update the left child of the // root to the right child of the // current left child of the root root->left = tmpnode->right; // Update parent pointer of the left // child of the root node if (tmpnode->right != NULL) tmpnode->right->par = root; // Update the right child of // tmpnode to root tmpnode->right = root; // Update parent pointer of tmpnode tmpnode->par = root->par; // Update the parent pointer of root root->par = tmpnode; // Update tmpnode as the left or // the right child of its parent // pointer according to its key value if (tmpnode->par != NULL && root->key < tmpnode->par->key) { tmpnode->par->left = tmpnode; } else { if (tmpnode->par != NULL) tmpnode->par->right = tmpnode; } // Make tmpnode as the new root root = tmpnode; // Update the heights Updateheight(root->left); Updateheight(root->right); Updateheight(root); Updateheight(root->par); // Return the root node return root;} // Function to handle Right Right Casestruct AVLwithparent* RRR( struct AVLwithparent* root){ // Create a reference to the // right child struct AVLwithparent* tmpnode = root->right; // Update the right child of the // root as the left child of the // current right child of the root root->right = tmpnode->left; // Update parent pointer of the right // child of the root node if (tmpnode->left != NULL) tmpnode->left->par = root; // Update the left child of the // tmpnode to root tmpnode->left = root; // Update parent pointer of tmpnode tmpnode->par = root->par; // Update the parent pointer of root root->par = tmpnode; // Update tmpnode as the left or // the right child of its parent // pointer according to its key value if (tmpnode->par != NULL && root->key < tmpnode->par->key) { tmpnode->par->left = tmpnode; } else { if (tmpnode->par != NULL) tmpnode->par->right = tmpnode; } // Make tmpnode as the new root root = tmpnode; // Update the heights Updateheight(root->left); Updateheight(root->right); Updateheight(root); Updateheight(root->par); // Return the root node return root;} // Function to handle Left Right Casestruct AVLwithparent* LRR( struct AVLwithparent* root){ root->left = RRR(root->left); return LLR(root);} // Function to handle right left casestruct AVLwithparent* RLR( struct AVLwithparent* root){ root->right = LLR(root->right); return RRR(root);} // Function to insert a node in// the AVL treestruct AVLwithparent* Insert( struct AVLwithparent* root, struct AVLwithparent* parent, int key){ if (root == NULL) { // Create and assign values // to a new node root = new struct AVLwithparent; if (root == NULL) { cout << "Error in memory" << endl; } // Otherwise else { root->height = 1; root->left = NULL; root->right = NULL; root->par = parent; root->key = key; } } else if (root->key > key) { // Recur to the left subtree // to insert the node root->left = Insert(root->left, root, key); // Stores the heights of the // left and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // Balance the tree if the // current node is not balanced if (abs(firstheight - secondheight) == 2) { if (root->left != NULL && key < root->left->key) { // Left Left Case root = LLR(root); } else { // Left Right Case root = LRR(root); } } } else if (root->key < key) { // Recur to the right subtree // to insert the node root->right = Insert(root->right, root, key); // Store the heights of the left // and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // Balance the tree if the // current node is not balanced if (abs(firstheight - secondheight) == 2) { if (root->right != NULL && key < root->right->key) { // Right Left Case root = RLR(root); } else { // Right Right Case root = RRR(root); } } } // Case when given key is // already in tree else { } // Update the height of the // root node Updateheight(root); // Return the root node return root;} // Function to find a key in AVL treebool AVLsearch( struct AVLwithparent* root, int key){ // If root is NULL if (root == NULL) return false; // If found, return true else if (root->key == key) return true; // Recur to the left subtree if // the current node's value is // greater than key else if (root->key > key) { bool val = AVLsearch(root->left, key); return val; } // Otherwise, recur to the // right subtree else { bool val = AVLsearch(root->right, key); return val; }} // Driver Codeint main(){ struct AVLwithparent* root; root = NULL; // Function call to insert the nodes root = Insert(root, NULL, 10); root = Insert(root, NULL, 20); root = Insert(root, NULL, 30); root = Insert(root, NULL, 40); root = Insert(root, NULL, 50); root = Insert(root, NULL, 25); // Function call to search for a node bool found = AVLsearch(root, 40); if (found) cout << "value found"; else cout << "value not found"; return 0;}
value found
Time Complexity: O(log N), where N is the number of nodes of the treeAuxiliary Space: O(1)
Delete Operation: The deletion procedure is similar to that of a normal AVL tree without a parent pointer, but in this case, the references to the parent pointers need to be updated with every deletion and rotation accordingly. Follow the steps below to perform the delete operation:
Perform the delete procedure as in a normal BST.
From the node that has been deleted, move towards the root.
At each node on the path, update the height of the node.
Check for AVL conditions at each node. Let there be 3 nodes: w, x, y where w is the current node, x is the root of the subtree of w which has greater height and y is the root of the subtree of x which has greater height.
If the node w is unbalanced, there exists one of the following 4 cases:Left Left Case (x is left child of w and y is left child of x)Left Right Case (x is left child of w and y is right child of x)Right Left Case (x is right child of w and y is left child of x)Right Right Case (x is right child of w and y is right child of x)
Left Left Case (x is left child of w and y is left child of x)
Left Right Case (x is left child of w and y is right child of x)
Right Left Case (x is right child of w and y is left child of x)
Right Right Case (x is right child of w and y is right child of x)
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // AVL tree nodestruct AVLwithparent { struct AVLwithparent* left; struct AVLwithparent* right; int key; struct AVLwithparent* par; int height;}; // Function to print the preorder// traversal of the AVL treevoid printpreorder(struct AVLwithparent* root){ // Print the node's value along // with its parent value cout << "Node: " << root->key << ", Parent Node: "; if (root->par != NULL) cout << root->par->key << endl; else cout << "NULL" << endl; // Recur to the left subtree if (root->left != NULL) { printpreorder(root->left); } // Recur to the right subtree if (root->right != NULL) { printpreorder(root->right); }} // Function to update the height of// a node according to its children's// node's heightsvoid Updateheight( struct AVLwithparent* root){ if (root != NULL) { // Store the height of the // current node int val = 1; // Store the height of the left // and right substree if (root->left != NULL) val = root->left->height + 1; if (root->right != NULL) val = max( val, root->right->height + 1); // Update the height of the // current node root->height = val; }} // Function to handle Left Left Casestruct AVLwithparent* LLR( struct AVLwithparent* root){ // Create a reference to the // left child struct AVLwithparent* tmpnode = root->left; // Update the left child of the // root to the right child of the // current left child of the root root->left = tmpnode->right; // Update parent pointer of left // child of the root node if (tmpnode->right != NULL) tmpnode->right->par = root; // Update the right child of // tmpnode to root tmpnode->right = root; // Update parent pointer of tmpnode tmpnode->par = root->par; // Update the parent pointer of root root->par = tmpnode; // Update tmpnode as the left or // the right child of its parent // pointer according to its key value if (tmpnode->par != NULL && root->key < tmpnode->par->key) { tmpnode->par->left = tmpnode; } else { if (tmpnode->par != NULL) tmpnode->par->right = tmpnode; } // Make tmpnode as the new root root = tmpnode; // Update the heights Updateheight(root->left); Updateheight(root->right); Updateheight(root); Updateheight(root->par); // Return the root node return root;} // Function to handle Right Right Casestruct AVLwithparent* RRR( struct AVLwithparent* root){ // Create a reference to the // right child struct AVLwithparent* tmpnode = root->right; // Update the right child of the // root as the left child of the // current right child of the root root->right = tmpnode->left; // Update parent pointer of the // right child of the root node if (tmpnode->left != NULL) tmpnode->left->par = root; // Update the left child of the // tmpnode to root tmpnode->left = root; // Update parent pointer of tmpnode tmpnode->par = root->par; // Update the parent pointer of root root->par = tmpnode; // Update tmpnode as the left or // the right child of its parent // pointer according to its key value if (tmpnode->par != NULL && root->key < tmpnode->par->key) { tmpnode->par->left = tmpnode; } else { if (tmpnode->par != NULL) tmpnode->par->right = tmpnode; } // Make tmpnode as the new root root = tmpnode; // Update the heights Updateheight(root->left); Updateheight(root->right); Updateheight(root); Updateheight(root->par); // Return the root node return root;} // Function to handle Left Right Casestruct AVLwithparent* LRR( struct AVLwithparent* root){ root->left = RRR(root->left); return LLR(root);} // Function to handle right left casestruct AVLwithparent* RLR( struct AVLwithparent* root){ root->right = LLR(root->right); return RRR(root);} // Function to balance the tree after// deletion of a nodestruct AVLwithparent* Balance( struct AVLwithparent* root){ // Store the current height of // the left and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // If current node is not balanced if (abs(firstheight - secondheight) == 2) { if (firstheight < secondheight) { // Store the height of the // left and right subtree // of the current node's // right subtree int rightheight1 = 0; int rightheight2 = 0; if (root->right->right != NULL) rightheight2 = root->right->right->height; if (root->right->left != NULL) rightheight1 = root->right->left->height; if (rightheight1 > rightheight2) { // Right Left Case root = RLR(root); } else { // Right Right Case root = RRR(root); } } else { // Store the height of the // left and right subtree // of the current node's // left subtree int leftheight1 = 0; int leftheight2 = 0; if (root->left->right != NULL) leftheight2 = root->left->right->height; if (root->left->left != NULL) leftheight1 = root->left->left->height; if (leftheight1 > leftheight2) { // Left Left Case root = LLR(root); } else { // Left Right Case root = LRR(root); } } } // Return the root node return root;} // Function to insert a node in// the AVL treestruct AVLwithparent* Insert( struct AVLwithparent* root, struct AVLwithparent* parent, int key){ if (root == NULL) { // Create and assign values // to a new node root = new struct AVLwithparent; if (root == NULL) cout << "Error in memory" << endl; else { root->height = 1; root->left = NULL; root->right = NULL; root->par = parent; root->key = key; } } else if (root->key > key) { // Recur to the left subtree // to insert the node root->left = Insert(root->left, root, key); // Store the heights of the // left and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // Balance the tree if the // current node is not balanced if (abs(firstheight - secondheight) == 2) { if (root->left != NULL && key < root->left->key) { // Left Left Case root = LLR(root); } else { // Left Right Case root = LRR(root); } } } else if (root->key < key) { // Recur to the right subtree // to insert the node root->right = Insert(root->right, root, key); // Store the heights of the left // and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // Balance the tree if the // current node is not balanced if (abs(firstheight - secondheight) == 2) { if (root->right != NULL && key < root->right->key) { // Right Left Case root = RLR(root); } else { // Right Right Case root = RRR(root); } } } // Case when given key is // already in tree else { } // Update the height of the // root node Updateheight(root); // Return the root node return root;} // Function to delete a node from// the AVL treestruct AVLwithparent* Delete( struct AVLwithparent* root, int key){ if (root != NULL) { // If the node is found if (root->key == key) { // Replace root with its // left child if (root->right == NULL && root->left != NULL) { if (root->par != NULL) { if (root->par->key < root->key) root->par->right = root->left; else root->par->left = root->left; // Update the height // of root's parent Updateheight(root->par); } root->left->par = root->par; // Balance the node // after deletion root->left = Balance( root->left); return root->left; } // Replace root with its // right child else if (root->left == NULL && root->right != NULL) { if (root->par != NULL) { if (root->par->key < root->key) root->par->right = root->right; else root->par->left = root->right; // Update the height // of the root's parent Updateheight(root->par); } root->right->par = root->par; // Balance the node after // deletion root->right = Balance(root->right); return root->right; } // Remove the references of // the current node else if (root->left == NULL && root->right == NULL) { if (root->par->key < root->key) { root->par->right = NULL; } else { root->par->left = NULL; } if (root->par != NULL) Updateheight(root->par); root = NULL; return NULL; } // Otherwise, replace the // current node with its // successor and then // recursively call Delete() else { struct AVLwithparent* tmpnode = root; tmpnode = tmpnode->right; while (tmpnode->left != NULL) { tmpnode = tmpnode->left; } int val = tmpnode->key; root->right = Delete(root->right, tmpnode->key); root->key = val; // Balance the node // after deletion root = Balance(root); } } // Recur to the right subtree to // delete the current node else if (root->key < key) { root->right = Delete(root->right, key); root = Balance(root); } // Recur into the right subtree // to delete the current node else if (root->key > key) { root->left = Delete(root->left, key); root = Balance(root); } // Update height of the root if (root != NULL) { Updateheight(root); } } // Handle the case when the key to be // deleted could not be found else { cout << "Key to be deleted " << "could not be found\n"; } // Return the root node return root;} // Driver Codeint main(){ struct AVLwithparent* root; root = NULL; // Function call to insert the nodes root = Insert(root, NULL, 9); root = Insert(root, NULL, 5); root = Insert(root, NULL, 10); root = Insert(root, NULL, 0); root = Insert(root, NULL, 6); // Print the tree before deleting node cout << "Before deletion:\n"; printpreorder(root); // Function Call to delete node 10 root = Delete(root, 10); // Print the tree after deleting node cout << "After deletion:\n"; printpreorder(root);}
Before deletion:
Node: 9, Parent Node: NULL
Node: 5, Parent Node: 9
Node: 0, Parent Node: 5
Node: 6, Parent Node: 5
Node: 10, Parent Node: 9
After deletion:
Node: 6, Parent Node: NULL
Node: 5, Parent Node: 6
Node: 0, Parent Node: 5
Node: 9, Parent Node: 6
Time Complexity: O(log N), where N is the number of nodes of the treeAuxiliary Space: O(1)
AVL-Tree
Balanced Binary Search Trees
Picked
Self-Balancing-BST
Data Structures
Tree
Data Structures
Tree
AVL-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Tree Data Structure
Program to implement Singly Linked List in C++ using class
Hash Functions and list/types of Hash functions
Insertion in a B+ tree
TCS NQT Coding Sheet
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
|
[
{
"code": null,
"e": 25054,
"s": 25026,
"text": "\n14 Jul, 2021"
},
{
"code": null,
"e": 25429,
"s": 25054,
"text": "AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes. The insertion and deletion in AVL trees have been discussed in the previous article. In this article, insert, search and delete operations are discussed on AVL trees that also have a parent pointer in their structure."
},
{
"code": null,
"e": 25458,
"s": 25429,
"text": "Definition of AVL tree node:"
},
{
"code": null,
"e": 25462,
"s": 25458,
"text": "C++"
},
{
"code": "struct AVLwithparent { // Pointer to the left and the // right subtree struct AVLwithparent* left; struct AVLwithparent* right; // Stores the data in the node int key; // Stores the parent pointer struct AVLwithparent* par; // Stores the height of the // current tree int height;}",
"e": 25784,
"s": 25462,
"text": null
},
{
"code": null,
"e": 25943,
"s": 25784,
"text": "Node: 30, Parent Node: NULL\nNode: 20, Parent Node: 30\nNode: 10, Parent Node: 20\nNode: 25, Parent Node: 20\nNode: 40, Parent Node: 30\nNode: 50, Parent Node: 40\n"
},
{
"code": null,
"e": 25971,
"s": 25943,
"text": "Representation of the Node:"
},
{
"code": null,
"e": 26036,
"s": 25971,
"text": "Below is the example of an AVL tree containing a parent pointer:"
},
{
"code": null,
"e": 26300,
"s": 26036,
"text": "Insert Operation: The insertion procedure is similar to that of a normal AVL tree without a parent pointer, but in this case, the parent pointers need to be updated with every insertion and rotation accordingly. Follow the steps below to perform insert operation:"
},
{
"code": null,
"e": 26379,
"s": 26300,
"text": "Perform standard BST insert for the node to be placed at its correct position."
},
{
"code": null,
"e": 26493,
"s": 26379,
"text": "Increase the height of each node encountered by 1 while finding the correct position for the node to be inserted."
},
{
"code": null,
"e": 26580,
"s": 26493,
"text": "Update the parent and child pointers of the inserted node and its parent respectively."
},
{
"code": null,
"e": 26699,
"s": 26580,
"text": "Starting from the inserted node till the root node check if the AVL condition is satisfied for each node on this path."
},
{
"code": null,
"e": 27115,
"s": 26699,
"text": "If w is the node where the AVL condition is not satisfied then we have 4 cases:Left Left Case: (If the left subtree of the left child of w has the inserted node)Left Right Case: (If the right subtree of the left child of w has the inserted node)Right Left Case: (If the left subtree of the right child of w has the inserted node)Right Right Case: (If the right subtree of the right child of w has the inserted node)"
},
{
"code": null,
"e": 27198,
"s": 27115,
"text": "Left Left Case: (If the left subtree of the left child of w has the inserted node)"
},
{
"code": null,
"e": 27283,
"s": 27198,
"text": "Left Right Case: (If the right subtree of the left child of w has the inserted node)"
},
{
"code": null,
"e": 27368,
"s": 27283,
"text": "Right Left Case: (If the left subtree of the right child of w has the inserted node)"
},
{
"code": null,
"e": 27455,
"s": 27368,
"text": "Right Right Case: (If the right subtree of the right child of w has the inserted node)"
},
{
"code": null,
"e": 27506,
"s": 27455,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27510,
"s": 27506,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // AVL tree nodestruct AVLwithparent { struct AVLwithparent* left; struct AVLwithparent* right; int key; struct AVLwithparent* par; int height;}; // Function to update the height of// a node according to its children's// node's heightsvoid Updateheight( struct AVLwithparent* root){ if (root != NULL) { // Store the height of the // current node int val = 1; // Store the height of the left // and right substree if (root->left != NULL) val = root->left->height + 1; if (root->right != NULL) val = max( val, root->right->height + 1); // Update the height of the // current node root->height = val; }} // Function to handle Left Left Casestruct AVLwithparent* LLR( struct AVLwithparent* root){ // Create a reference to the // left child struct AVLwithparent* tmpnode = root->left; // Update the left child of the // root to the right child of the // current left child of the root root->left = tmpnode->right; // Update parent pointer of the // left child of the root node if (tmpnode->right != NULL) tmpnode->right->par = root; // Update the right child of // tmpnode to root tmpnode->right = root; // Update parent pointer of // the tmpnode tmpnode->par = root->par; // Update the parent pointer // of the root root->par = tmpnode; // Update tmpnode as the left or the // right child of its parent pointer // according to its key value if (tmpnode->par != NULL && root->key < tmpnode->par->key) { tmpnode->par->left = tmpnode; } else { if (tmpnode->par != NULL) tmpnode->par->right = tmpnode; } // Make tmpnode as the new root root = tmpnode; // Update the heights Updateheight(root->left); Updateheight(root->right); Updateheight(root); Updateheight(root->par); // Return the root node return root;} // Function to handle Right Right Casestruct AVLwithparent* RRR( struct AVLwithparent* root){ // Create a reference to the // right child struct AVLwithparent* tmpnode = root->right; // Update the right child of the // root as the left child of the // current right child of the root root->right = tmpnode->left; // Update parent pointer of the // right child of the root node if (tmpnode->left != NULL) tmpnode->left->par = root; // Update the left child of the // tmpnode to root tmpnode->left = root; // Update parent pointer of // the tmpnode tmpnode->par = root->par; // Update the parent pointer // of the root root->par = tmpnode; // Update tmpnode as the left or // the right child of its parent // pointer according to its key value if (tmpnode->par != NULL && root->key < tmpnode->par->key) { tmpnode->par->left = tmpnode; } else { if (tmpnode->par != NULL) tmpnode->par->right = tmpnode; } // Make tmpnode as the new root root = tmpnode; // Update the heights Updateheight(root->left); Updateheight(root->right); Updateheight(root); Updateheight(root->par); // Return the root node return root;} // Function to handle Left Right Casestruct AVLwithparent* LRR( struct AVLwithparent* root){ root->left = RRR(root->left); return LLR(root);} // Function to handle right left casestruct AVLwithparent* RLR( struct AVLwithparent* root){ root->right = LLR(root->right); return RRR(root);} // Function to insert a node in// the AVL treestruct AVLwithparent* Insert( struct AVLwithparent* root, struct AVLwithparent* parent, int key){ if (root == NULL) { // Create and assign values // to a new node root = new struct AVLwithparent; // If the root is NULL if (root == NULL) { cout << \"Error in memory\" << endl; } // Otherwise else { root->height = 1; root->left = NULL; root->right = NULL; root->par = parent; root->key = key; } } else if (root->key > key) { // Recur to the left subtree // to insert the node root->left = Insert(root->left, root, key); // Store the heights of the // left and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // Balance the tree if the // current node is not balanced if (abs(firstheight - secondheight) == 2) { if (root->left != NULL && key < root->left->key) { // Left Left Case root = LLR(root); } else { // Left Right Case root = LRR(root); } } } else if (root->key < key) { // Recur to the right subtree // to insert the node root->right = Insert(root->right, root, key); // Store the heights of the // left and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // Balance the tree if the // current node is not balanced if (abs(firstheight - secondheight) == 2) { if (root->right != NULL && key < root->right->key) { // Right Left Case root = RLR(root); } else { // Right Right Case root = RRR(root); } } } // Case when given key is already // in the tree else { } // Update the height of the // root node Updateheight(root); // Return the root node return root;} // Function to print the preorder// traversal of the AVL treevoid printpreorder( struct AVLwithparent* root){ // Print the node's value along // with its parent value cout << \"Node: \" << root->key << \", Parent Node: \"; if (root->par != NULL) cout << root->par->key << endl; else cout << \"NULL\" << endl; // Recur to the left subtree if (root->left != NULL) { printpreorder(root->left); } // Recur to the right subtree if (root->right != NULL) { printpreorder(root->right); }} // Driver Codeint main(){ struct AVLwithparent* root; root = NULL; // Function Call to insert nodes root = Insert(root, NULL, 10); root = Insert(root, NULL, 20); root = Insert(root, NULL, 30); root = Insert(root, NULL, 40); root = Insert(root, NULL, 50); root = Insert(root, NULL, 25); // Function call to print the tree printpreorder(root);}",
"e": 34689,
"s": 27510,
"text": null
},
{
"code": null,
"e": 34848,
"s": 34689,
"text": "Node: 30, Parent Node: NULL\nNode: 20, Parent Node: 30\nNode: 10, Parent Node: 20\nNode: 25, Parent Node: 20\nNode: 40, Parent Node: 30\nNode: 50, Parent Node: 40\n"
},
{
"code": null,
"e": 34940,
"s": 34848,
"text": "Time Complexity: O(log N), where N is the number of nodes of the tree.Auxiliary Space: O(1)"
},
{
"code": null,
"e": 35134,
"s": 34940,
"text": "Search Operation: The search operation in an AVL tree with parent pointers is similar to the search operation in a normal Binary Search Tree. Follow the steps below to perform search operation:"
},
{
"code": null,
"e": 35160,
"s": 35134,
"text": "Start from the root node."
},
{
"code": null,
"e": 35200,
"s": 35160,
"text": "If the root node is NULL, return false."
},
{
"code": null,
"e": 35305,
"s": 35200,
"text": "Check if the current node’s value is equal to the value of the node to be searched. If yes, return true."
},
{
"code": null,
"e": 35392,
"s": 35305,
"text": "If the current node’s value is less than searched key then recur to the right subtree."
},
{
"code": null,
"e": 35481,
"s": 35392,
"text": "If the current node’s value is greater than searched key then recur to the left subtree."
},
{
"code": null,
"e": 35532,
"s": 35481,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 35536,
"s": 35532,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // AVL tree nodestruct AVLwithparent { struct AVLwithparent* left; struct AVLwithparent* right; int key; struct AVLwithparent* par; int height;}; // Function to update the height of// a node according to its children's// node's heightsvoid Updateheight(struct AVLwithparent* root){ if (root != NULL) { // Store the height of the // current node int val = 1; // Store the height of the left // and the right substree if (root->left != NULL) val = root->left->height + 1; if (root->right != NULL) val = max( val, root->right->height + 1); // Update the height of the // current node root->height = val; }} // Function to handle Left Left Casestruct AVLwithparent* LLR( struct AVLwithparent* root){ // Create a reference to the // left child struct AVLwithparent* tmpnode = root->left; // Update the left child of the // root to the right child of the // current left child of the root root->left = tmpnode->right; // Update parent pointer of the left // child of the root node if (tmpnode->right != NULL) tmpnode->right->par = root; // Update the right child of // tmpnode to root tmpnode->right = root; // Update parent pointer of tmpnode tmpnode->par = root->par; // Update the parent pointer of root root->par = tmpnode; // Update tmpnode as the left or // the right child of its parent // pointer according to its key value if (tmpnode->par != NULL && root->key < tmpnode->par->key) { tmpnode->par->left = tmpnode; } else { if (tmpnode->par != NULL) tmpnode->par->right = tmpnode; } // Make tmpnode as the new root root = tmpnode; // Update the heights Updateheight(root->left); Updateheight(root->right); Updateheight(root); Updateheight(root->par); // Return the root node return root;} // Function to handle Right Right Casestruct AVLwithparent* RRR( struct AVLwithparent* root){ // Create a reference to the // right child struct AVLwithparent* tmpnode = root->right; // Update the right child of the // root as the left child of the // current right child of the root root->right = tmpnode->left; // Update parent pointer of the right // child of the root node if (tmpnode->left != NULL) tmpnode->left->par = root; // Update the left child of the // tmpnode to root tmpnode->left = root; // Update parent pointer of tmpnode tmpnode->par = root->par; // Update the parent pointer of root root->par = tmpnode; // Update tmpnode as the left or // the right child of its parent // pointer according to its key value if (tmpnode->par != NULL && root->key < tmpnode->par->key) { tmpnode->par->left = tmpnode; } else { if (tmpnode->par != NULL) tmpnode->par->right = tmpnode; } // Make tmpnode as the new root root = tmpnode; // Update the heights Updateheight(root->left); Updateheight(root->right); Updateheight(root); Updateheight(root->par); // Return the root node return root;} // Function to handle Left Right Casestruct AVLwithparent* LRR( struct AVLwithparent* root){ root->left = RRR(root->left); return LLR(root);} // Function to handle right left casestruct AVLwithparent* RLR( struct AVLwithparent* root){ root->right = LLR(root->right); return RRR(root);} // Function to insert a node in// the AVL treestruct AVLwithparent* Insert( struct AVLwithparent* root, struct AVLwithparent* parent, int key){ if (root == NULL) { // Create and assign values // to a new node root = new struct AVLwithparent; if (root == NULL) { cout << \"Error in memory\" << endl; } // Otherwise else { root->height = 1; root->left = NULL; root->right = NULL; root->par = parent; root->key = key; } } else if (root->key > key) { // Recur to the left subtree // to insert the node root->left = Insert(root->left, root, key); // Stores the heights of the // left and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // Balance the tree if the // current node is not balanced if (abs(firstheight - secondheight) == 2) { if (root->left != NULL && key < root->left->key) { // Left Left Case root = LLR(root); } else { // Left Right Case root = LRR(root); } } } else if (root->key < key) { // Recur to the right subtree // to insert the node root->right = Insert(root->right, root, key); // Store the heights of the left // and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // Balance the tree if the // current node is not balanced if (abs(firstheight - secondheight) == 2) { if (root->right != NULL && key < root->right->key) { // Right Left Case root = RLR(root); } else { // Right Right Case root = RRR(root); } } } // Case when given key is // already in tree else { } // Update the height of the // root node Updateheight(root); // Return the root node return root;} // Function to find a key in AVL treebool AVLsearch( struct AVLwithparent* root, int key){ // If root is NULL if (root == NULL) return false; // If found, return true else if (root->key == key) return true; // Recur to the left subtree if // the current node's value is // greater than key else if (root->key > key) { bool val = AVLsearch(root->left, key); return val; } // Otherwise, recur to the // right subtree else { bool val = AVLsearch(root->right, key); return val; }} // Driver Codeint main(){ struct AVLwithparent* root; root = NULL; // Function call to insert the nodes root = Insert(root, NULL, 10); root = Insert(root, NULL, 20); root = Insert(root, NULL, 30); root = Insert(root, NULL, 40); root = Insert(root, NULL, 50); root = Insert(root, NULL, 25); // Function call to search for a node bool found = AVLsearch(root, 40); if (found) cout << \"value found\"; else cout << \"value not found\"; return 0;}",
"e": 42742,
"s": 35536,
"text": null
},
{
"code": null,
"e": 42755,
"s": 42742,
"text": "value found\n"
},
{
"code": null,
"e": 42846,
"s": 42755,
"text": "Time Complexity: O(log N), where N is the number of nodes of the treeAuxiliary Space: O(1)"
},
{
"code": null,
"e": 43130,
"s": 42846,
"text": "Delete Operation: The deletion procedure is similar to that of a normal AVL tree without a parent pointer, but in this case, the references to the parent pointers need to be updated with every deletion and rotation accordingly. Follow the steps below to perform the delete operation:"
},
{
"code": null,
"e": 43179,
"s": 43130,
"text": "Perform the delete procedure as in a normal BST."
},
{
"code": null,
"e": 43239,
"s": 43179,
"text": "From the node that has been deleted, move towards the root."
},
{
"code": null,
"e": 43296,
"s": 43239,
"text": "At each node on the path, update the height of the node."
},
{
"code": null,
"e": 43517,
"s": 43296,
"text": "Check for AVL conditions at each node. Let there be 3 nodes: w, x, y where w is the current node, x is the root of the subtree of w which has greater height and y is the root of the subtree of x which has greater height."
},
{
"code": null,
"e": 43845,
"s": 43517,
"text": "If the node w is unbalanced, there exists one of the following 4 cases:Left Left Case (x is left child of w and y is left child of x)Left Right Case (x is left child of w and y is right child of x)Right Left Case (x is right child of w and y is left child of x)Right Right Case (x is right child of w and y is right child of x)"
},
{
"code": null,
"e": 43908,
"s": 43845,
"text": "Left Left Case (x is left child of w and y is left child of x)"
},
{
"code": null,
"e": 43973,
"s": 43908,
"text": "Left Right Case (x is left child of w and y is right child of x)"
},
{
"code": null,
"e": 44038,
"s": 43973,
"text": "Right Left Case (x is right child of w and y is left child of x)"
},
{
"code": null,
"e": 44105,
"s": 44038,
"text": "Right Right Case (x is right child of w and y is right child of x)"
},
{
"code": null,
"e": 44156,
"s": 44105,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 44160,
"s": 44156,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // AVL tree nodestruct AVLwithparent { struct AVLwithparent* left; struct AVLwithparent* right; int key; struct AVLwithparent* par; int height;}; // Function to print the preorder// traversal of the AVL treevoid printpreorder(struct AVLwithparent* root){ // Print the node's value along // with its parent value cout << \"Node: \" << root->key << \", Parent Node: \"; if (root->par != NULL) cout << root->par->key << endl; else cout << \"NULL\" << endl; // Recur to the left subtree if (root->left != NULL) { printpreorder(root->left); } // Recur to the right subtree if (root->right != NULL) { printpreorder(root->right); }} // Function to update the height of// a node according to its children's// node's heightsvoid Updateheight( struct AVLwithparent* root){ if (root != NULL) { // Store the height of the // current node int val = 1; // Store the height of the left // and right substree if (root->left != NULL) val = root->left->height + 1; if (root->right != NULL) val = max( val, root->right->height + 1); // Update the height of the // current node root->height = val; }} // Function to handle Left Left Casestruct AVLwithparent* LLR( struct AVLwithparent* root){ // Create a reference to the // left child struct AVLwithparent* tmpnode = root->left; // Update the left child of the // root to the right child of the // current left child of the root root->left = tmpnode->right; // Update parent pointer of left // child of the root node if (tmpnode->right != NULL) tmpnode->right->par = root; // Update the right child of // tmpnode to root tmpnode->right = root; // Update parent pointer of tmpnode tmpnode->par = root->par; // Update the parent pointer of root root->par = tmpnode; // Update tmpnode as the left or // the right child of its parent // pointer according to its key value if (tmpnode->par != NULL && root->key < tmpnode->par->key) { tmpnode->par->left = tmpnode; } else { if (tmpnode->par != NULL) tmpnode->par->right = tmpnode; } // Make tmpnode as the new root root = tmpnode; // Update the heights Updateheight(root->left); Updateheight(root->right); Updateheight(root); Updateheight(root->par); // Return the root node return root;} // Function to handle Right Right Casestruct AVLwithparent* RRR( struct AVLwithparent* root){ // Create a reference to the // right child struct AVLwithparent* tmpnode = root->right; // Update the right child of the // root as the left child of the // current right child of the root root->right = tmpnode->left; // Update parent pointer of the // right child of the root node if (tmpnode->left != NULL) tmpnode->left->par = root; // Update the left child of the // tmpnode to root tmpnode->left = root; // Update parent pointer of tmpnode tmpnode->par = root->par; // Update the parent pointer of root root->par = tmpnode; // Update tmpnode as the left or // the right child of its parent // pointer according to its key value if (tmpnode->par != NULL && root->key < tmpnode->par->key) { tmpnode->par->left = tmpnode; } else { if (tmpnode->par != NULL) tmpnode->par->right = tmpnode; } // Make tmpnode as the new root root = tmpnode; // Update the heights Updateheight(root->left); Updateheight(root->right); Updateheight(root); Updateheight(root->par); // Return the root node return root;} // Function to handle Left Right Casestruct AVLwithparent* LRR( struct AVLwithparent* root){ root->left = RRR(root->left); return LLR(root);} // Function to handle right left casestruct AVLwithparent* RLR( struct AVLwithparent* root){ root->right = LLR(root->right); return RRR(root);} // Function to balance the tree after// deletion of a nodestruct AVLwithparent* Balance( struct AVLwithparent* root){ // Store the current height of // the left and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // If current node is not balanced if (abs(firstheight - secondheight) == 2) { if (firstheight < secondheight) { // Store the height of the // left and right subtree // of the current node's // right subtree int rightheight1 = 0; int rightheight2 = 0; if (root->right->right != NULL) rightheight2 = root->right->right->height; if (root->right->left != NULL) rightheight1 = root->right->left->height; if (rightheight1 > rightheight2) { // Right Left Case root = RLR(root); } else { // Right Right Case root = RRR(root); } } else { // Store the height of the // left and right subtree // of the current node's // left subtree int leftheight1 = 0; int leftheight2 = 0; if (root->left->right != NULL) leftheight2 = root->left->right->height; if (root->left->left != NULL) leftheight1 = root->left->left->height; if (leftheight1 > leftheight2) { // Left Left Case root = LLR(root); } else { // Left Right Case root = LRR(root); } } } // Return the root node return root;} // Function to insert a node in// the AVL treestruct AVLwithparent* Insert( struct AVLwithparent* root, struct AVLwithparent* parent, int key){ if (root == NULL) { // Create and assign values // to a new node root = new struct AVLwithparent; if (root == NULL) cout << \"Error in memory\" << endl; else { root->height = 1; root->left = NULL; root->right = NULL; root->par = parent; root->key = key; } } else if (root->key > key) { // Recur to the left subtree // to insert the node root->left = Insert(root->left, root, key); // Store the heights of the // left and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // Balance the tree if the // current node is not balanced if (abs(firstheight - secondheight) == 2) { if (root->left != NULL && key < root->left->key) { // Left Left Case root = LLR(root); } else { // Left Right Case root = LRR(root); } } } else if (root->key < key) { // Recur to the right subtree // to insert the node root->right = Insert(root->right, root, key); // Store the heights of the left // and right subtree int firstheight = 0; int secondheight = 0; if (root->left != NULL) firstheight = root->left->height; if (root->right != NULL) secondheight = root->right->height; // Balance the tree if the // current node is not balanced if (abs(firstheight - secondheight) == 2) { if (root->right != NULL && key < root->right->key) { // Right Left Case root = RLR(root); } else { // Right Right Case root = RRR(root); } } } // Case when given key is // already in tree else { } // Update the height of the // root node Updateheight(root); // Return the root node return root;} // Function to delete a node from// the AVL treestruct AVLwithparent* Delete( struct AVLwithparent* root, int key){ if (root != NULL) { // If the node is found if (root->key == key) { // Replace root with its // left child if (root->right == NULL && root->left != NULL) { if (root->par != NULL) { if (root->par->key < root->key) root->par->right = root->left; else root->par->left = root->left; // Update the height // of root's parent Updateheight(root->par); } root->left->par = root->par; // Balance the node // after deletion root->left = Balance( root->left); return root->left; } // Replace root with its // right child else if (root->left == NULL && root->right != NULL) { if (root->par != NULL) { if (root->par->key < root->key) root->par->right = root->right; else root->par->left = root->right; // Update the height // of the root's parent Updateheight(root->par); } root->right->par = root->par; // Balance the node after // deletion root->right = Balance(root->right); return root->right; } // Remove the references of // the current node else if (root->left == NULL && root->right == NULL) { if (root->par->key < root->key) { root->par->right = NULL; } else { root->par->left = NULL; } if (root->par != NULL) Updateheight(root->par); root = NULL; return NULL; } // Otherwise, replace the // current node with its // successor and then // recursively call Delete() else { struct AVLwithparent* tmpnode = root; tmpnode = tmpnode->right; while (tmpnode->left != NULL) { tmpnode = tmpnode->left; } int val = tmpnode->key; root->right = Delete(root->right, tmpnode->key); root->key = val; // Balance the node // after deletion root = Balance(root); } } // Recur to the right subtree to // delete the current node else if (root->key < key) { root->right = Delete(root->right, key); root = Balance(root); } // Recur into the right subtree // to delete the current node else if (root->key > key) { root->left = Delete(root->left, key); root = Balance(root); } // Update height of the root if (root != NULL) { Updateheight(root); } } // Handle the case when the key to be // deleted could not be found else { cout << \"Key to be deleted \" << \"could not be found\\n\"; } // Return the root node return root;} // Driver Codeint main(){ struct AVLwithparent* root; root = NULL; // Function call to insert the nodes root = Insert(root, NULL, 9); root = Insert(root, NULL, 5); root = Insert(root, NULL, 10); root = Insert(root, NULL, 0); root = Insert(root, NULL, 6); // Print the tree before deleting node cout << \"Before deletion:\\n\"; printpreorder(root); // Function Call to delete node 10 root = Delete(root, 10); // Print the tree after deleting node cout << \"After deletion:\\n\"; printpreorder(root);}",
"e": 56842,
"s": 44160,
"text": null
},
{
"code": null,
"e": 57099,
"s": 56842,
"text": "Before deletion:\nNode: 9, Parent Node: NULL\nNode: 5, Parent Node: 9\nNode: 0, Parent Node: 5\nNode: 6, Parent Node: 5\nNode: 10, Parent Node: 9\nAfter deletion:\nNode: 6, Parent Node: NULL\nNode: 5, Parent Node: 6\nNode: 0, Parent Node: 5\nNode: 9, Parent Node: 6\n"
},
{
"code": null,
"e": 57190,
"s": 57099,
"text": "Time Complexity: O(log N), where N is the number of nodes of the treeAuxiliary Space: O(1)"
},
{
"code": null,
"e": 57199,
"s": 57190,
"text": "AVL-Tree"
},
{
"code": null,
"e": 57228,
"s": 57199,
"text": "Balanced Binary Search Trees"
},
{
"code": null,
"e": 57235,
"s": 57228,
"text": "Picked"
},
{
"code": null,
"e": 57254,
"s": 57235,
"text": "Self-Balancing-BST"
},
{
"code": null,
"e": 57270,
"s": 57254,
"text": "Data Structures"
},
{
"code": null,
"e": 57275,
"s": 57270,
"text": "Tree"
},
{
"code": null,
"e": 57291,
"s": 57275,
"text": "Data Structures"
},
{
"code": null,
"e": 57296,
"s": 57291,
"text": "Tree"
},
{
"code": null,
"e": 57305,
"s": 57296,
"text": "AVL-Tree"
},
{
"code": null,
"e": 57403,
"s": 57305,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 57439,
"s": 57403,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 57498,
"s": 57439,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 57546,
"s": 57498,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 57569,
"s": 57546,
"text": "Insertion in a B+ tree"
},
{
"code": null,
"e": 57590,
"s": 57569,
"text": "TCS NQT Coding Sheet"
},
{
"code": null,
"e": 57640,
"s": 57590,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 57675,
"s": 57640,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 57709,
"s": 57675,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 57738,
"s": 57709,
"text": "AVL Tree | Set 1 (Insertion)"
}
] |
PostgreSQL - DELETE Query
|
The PostgreSQL DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete the selected rows. Otherwise, all the records would be deleted.
The basic syntax of DELETE query with WHERE clause is as follows −
DELETE FROM table_name
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Consider the table COMPANY, having records as follows −
# select * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
The following is an example, which would DELETE a customer whose ID is 7 −
testdb=# DELETE FROM COMPANY WHERE ID = 2;
Now, COMPANY table will have the following records −
id | name | age | address | salary
----+-------+-----+-------------+--------
1 | Paul | 32 | California | 20000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall | 45000
7 | James | 24 | Houston | 10000
(6 rows)
If you want to DELETE all the records from COMPANY table, you do not need to use WHERE clause with DELETE queries, which would be as follows −
testdb=# DELETE FROM COMPANY;
Now, COMPANY table does not have any record because all the records have been deleted by the DELETE statement.
23 Lectures
1.5 hours
John Elder
49 Lectures
3.5 hours
Niyazi Erdogan
126 Lectures
10.5 hours
Abhishek And Pukhraj
35 Lectures
5 hours
Karthikeya T
5 Lectures
51 mins
Vinay Kumar
5 Lectures
52 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3023,
"s": 2825,
"text": "The PostgreSQL DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete the selected rows. Otherwise, all the records would be deleted."
},
{
"code": null,
"e": 3090,
"s": 3023,
"text": "The basic syntax of DELETE query with WHERE clause is as follows −"
},
{
"code": null,
"e": 3133,
"s": 3090,
"text": "DELETE FROM table_name\nWHERE [condition];\n"
},
{
"code": null,
"e": 3199,
"s": 3133,
"text": "You can combine N number of conditions using AND or OR operators."
},
{
"code": null,
"e": 3255,
"s": 3199,
"text": "Consider the table COMPANY, having records as follows −"
},
{
"code": null,
"e": 3641,
"s": 3255,
"text": "# select * from COMPANY;\n id | name | age | address | salary\n----+-------+-----+-----------+--------\n 1 | Paul | 32 | California| 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall| 45000\n 7 | James | 24 | Houston | 10000\n(7 rows)"
},
{
"code": null,
"e": 3716,
"s": 3641,
"text": "The following is an example, which would DELETE a customer whose ID is 7 −"
},
{
"code": null,
"e": 3759,
"s": 3716,
"text": "testdb=# DELETE FROM COMPANY WHERE ID = 2;"
},
{
"code": null,
"e": 3812,
"s": 3759,
"text": "Now, COMPANY table will have the following records −"
},
{
"code": null,
"e": 4150,
"s": 3812,
"text": " id | name | age | address | salary\n----+-------+-----+-------------+--------\n 1 | Paul | 32 | California | 20000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall | 45000\n 7 | James | 24 | Houston | 10000\n(6 rows)"
},
{
"code": null,
"e": 4293,
"s": 4150,
"text": "If you want to DELETE all the records from COMPANY table, you do not need to use WHERE clause with DELETE queries, which would be as follows −"
},
{
"code": null,
"e": 4323,
"s": 4293,
"text": "testdb=# DELETE FROM COMPANY;"
},
{
"code": null,
"e": 4434,
"s": 4323,
"text": "Now, COMPANY table does not have any record because all the records have been deleted by the DELETE statement."
},
{
"code": null,
"e": 4469,
"s": 4434,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4481,
"s": 4469,
"text": " John Elder"
},
{
"code": null,
"e": 4516,
"s": 4481,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4532,
"s": 4516,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 4569,
"s": 4532,
"text": "\n 126 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 4591,
"s": 4569,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4624,
"s": 4591,
"text": "\n 35 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4638,
"s": 4624,
"text": " Karthikeya T"
},
{
"code": null,
"e": 4669,
"s": 4638,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 4682,
"s": 4669,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 4713,
"s": 4682,
"text": "\n 5 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 4726,
"s": 4713,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 4733,
"s": 4726,
"text": " Print"
},
{
"code": null,
"e": 4744,
"s": 4733,
"text": " Add Notes"
}
] |
Algorithms Quiz | Bit Algorithms | Question 4 - GeeksforGeeks
|
28 Sep, 2018
Consider the following code snippet for checking whether a number is power of 2 or not.
/* Incorrect function to check if x is power of 2*/bool isPowerOfTwo (unsigned int x) { return (!(x&(x-1))); }
What is wrong with above function?(A) It does reverse of what is required(B) It works perfectly fine for all values of x.(C) It does not work for x = 0(D) It does not work for x = 1Answer: (C)Explanation: Please see https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Quiz of this Question
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms | Analysis of Algorithms | Question 17
Algorithms | Sorting | Question 11
Algorithms | Sorting | Question 1
Algorithms | Greedy Algorithms | Question 1
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Analysis of Algorithms | Question 8
Algorithms | Divide and Conquer | Question 6
Algorithms | Graph Traversals | Question 12
|
[
{
"code": null,
"e": 24980,
"s": 24952,
"text": "\n28 Sep, 2018"
},
{
"code": null,
"e": 25068,
"s": 24980,
"text": "Consider the following code snippet for checking whether a number is power of 2 or not."
},
{
"code": "/* Incorrect function to check if x is power of 2*/bool isPowerOfTwo (unsigned int x) { return (!(x&(x-1))); }",
"e": 25181,
"s": 25068,
"text": null
},
{
"code": null,
"e": 25494,
"s": 25181,
"text": "What is wrong with above function?(A) It does reverse of what is required(B) It works perfectly fine for all values of x.(C) It does not work for x = 0(D) It does not work for x = 1Answer: (C)Explanation: Please see https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Quiz of this Question"
},
{
"code": null,
"e": 25510,
"s": 25494,
"text": "Algorithms Quiz"
},
{
"code": null,
"e": 25608,
"s": 25510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25654,
"s": 25608,
"text": "Algorithms | Dynamic Programming | Question 2"
},
{
"code": null,
"e": 25700,
"s": 25654,
"text": "Algorithms | Dynamic Programming | Question 3"
},
{
"code": null,
"e": 25750,
"s": 25700,
"text": "Algorithms | Analysis of Algorithms | Question 17"
},
{
"code": null,
"e": 25785,
"s": 25750,
"text": "Algorithms | Sorting | Question 11"
},
{
"code": null,
"e": 25819,
"s": 25785,
"text": "Algorithms | Sorting | Question 1"
},
{
"code": null,
"e": 25863,
"s": 25819,
"text": "Algorithms | Greedy Algorithms | Question 1"
},
{
"code": null,
"e": 25914,
"s": 25863,
"text": "Algorithms Quiz | Dynamic Programming | Question 8"
},
{
"code": null,
"e": 25963,
"s": 25914,
"text": "Algorithms | Analysis of Algorithms | Question 8"
},
{
"code": null,
"e": 26008,
"s": 25963,
"text": "Algorithms | Divide and Conquer | Question 6"
}
] |
MapStruct - Implicit Type Conversion
|
MapStruct handles conversion of type conversions automatically in most of the cases. For example, int to Long or String conversion. Conversion handles null values as well. Following are the some of the important automatic conversions.
Between primitive types and Corresponding Wrapper Classes.
Between primitive types and Corresponding Wrapper Classes.
Between primitive types and String.
Between primitive types and String.
Between enum types and String.
Between enum types and String.
Between BigInt, BigDecimal and String.
Between BigInt, BigDecimal and String.
Between Calendar/Date and XMLGregorianCalendar.
Between Calendar/Date and XMLGregorianCalendar.
Between XMLGregorianCalendar and String.
Between XMLGregorianCalendar and String.
Between Jodas date types and String.
Between Jodas date types and String.
Open project mapping as updated in Mapping Using Builder chapter in Eclipse.
Update StudentEntity.java with following code −
StudentEntity.java
package com.tutorialspoint.entity;
public class StudentEntity {
private String id;
private String name;
private String classVal;
private SubjectEntity subject;
public String section;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassVal() {
return classVal;
}
public void setClassVal(String classVal) {
this.classVal = classVal;
}
public SubjectEntity getSubject() {
return subject;
}
public void setSubject(SubjectEntity subject) {
this.subject = subject;
}
}
Student.java is unchanged with following code −
Student.java
package com.tutorialspoint.model;
public class Student {
private final String name;
private final int id;
protected Student(Student.Builder builder) {
this.name = builder.name;
this.id = builder.id;
}
public static Student.Builder builder() {
return new Student.Builder();
}
public static class Builder {
private String name;
private int id;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder id(int id) {
this.id = id;
return this;
}
public Student create() {
return new Student( this );
}
}
public String getName() {
return name;
}
public int getId() {
ret+urn id;
}
}
Update DeliveryAddressMapperTest.java with following code −
DeliveryAddressMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.AddressEntity;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.mapper.DeliveryAddressMapper;
import com.tutorialspoint.model.DeliveryAddress;
public class DeliveryAddressMapperTest {
private DeliveryAddressMapper deliveryAddressMapper = Mappers.getMapper(DeliveryAddressMapper.class);
@Test
public void testEntityToModel() {
StudentEntity student = new StudentEntity();
student.setClassVal("X");
student.setName("John");
student.setId("1");
AddressEntity address = new AddressEntity();
address.setCity("Y");
address.setState("Z");
address.setHouseNo(1);
DeliveryAddress deliveryAddress = deliveryAddressMapper.getDeliveryAddress(student, address);
assertEquals(deliveryAddress.getName(), student.getName());
assertEquals(deliveryAddress.getCity(), address.getCity());
assertEquals(deliveryAddress.getState(), address.getState());
assertEquals(deliveryAddress.getHouseNumber(), address.getHouseNo());
}
}
Update StudentMapperTest.java with following code −
StudentMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.entity.SubjectEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;
public class StudentMapperTest {
private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);
@Test
public void testEntityToModel() {
StudentEntity entity = new StudentEntity();
entity.setName("John");
entity.setId("1");
Student model = studentMapper.getModelFromEntity(entity);
assertEquals(entity.getName(), model.getName());
assertEquals(Integer.parseInt(entity.getId()), model.getId());
}
@Test
public void testModelToEntity() {
Student.Builder builder = Student.builder().id(1).name("John");
Student model = builder.create();
StudentEntity entity = studentMapper.getEntityFromModel(model);
assertEquals(entity.getName(), model.getName());
assertEquals(Integer.parseInt(entity.getId()), model.getId());
}
}
Run the following command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec
Results :
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
...
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2495,
"s": 2260,
"text": "MapStruct handles conversion of type conversions automatically in most of the cases. For example, int to Long or String conversion. Conversion handles null values as well. Following are the some of the important automatic conversions."
},
{
"code": null,
"e": 2554,
"s": 2495,
"text": "Between primitive types and Corresponding Wrapper Classes."
},
{
"code": null,
"e": 2613,
"s": 2554,
"text": "Between primitive types and Corresponding Wrapper Classes."
},
{
"code": null,
"e": 2649,
"s": 2613,
"text": "Between primitive types and String."
},
{
"code": null,
"e": 2685,
"s": 2649,
"text": "Between primitive types and String."
},
{
"code": null,
"e": 2716,
"s": 2685,
"text": "Between enum types and String."
},
{
"code": null,
"e": 2747,
"s": 2716,
"text": "Between enum types and String."
},
{
"code": null,
"e": 2786,
"s": 2747,
"text": "Between BigInt, BigDecimal and String."
},
{
"code": null,
"e": 2825,
"s": 2786,
"text": "Between BigInt, BigDecimal and String."
},
{
"code": null,
"e": 2873,
"s": 2825,
"text": "Between Calendar/Date and XMLGregorianCalendar."
},
{
"code": null,
"e": 2921,
"s": 2873,
"text": "Between Calendar/Date and XMLGregorianCalendar."
},
{
"code": null,
"e": 2962,
"s": 2921,
"text": "Between XMLGregorianCalendar and String."
},
{
"code": null,
"e": 3003,
"s": 2962,
"text": "Between XMLGregorianCalendar and String."
},
{
"code": null,
"e": 3040,
"s": 3003,
"text": "Between Jodas date types and String."
},
{
"code": null,
"e": 3077,
"s": 3040,
"text": "Between Jodas date types and String."
},
{
"code": null,
"e": 3154,
"s": 3077,
"text": "Open project mapping as updated in Mapping Using Builder chapter in Eclipse."
},
{
"code": null,
"e": 3202,
"s": 3154,
"text": "Update StudentEntity.java with following code −"
},
{
"code": null,
"e": 3221,
"s": 3202,
"text": "StudentEntity.java"
},
{
"code": null,
"e": 3946,
"s": 3221,
"text": "package com.tutorialspoint.entity;\n\npublic class StudentEntity {\n private String id;\n private String name;\n private String classVal;\n private SubjectEntity subject;\n public String section;\n public String getId() {\n return id;\n }\n public void setId(String id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassVal() {\n return classVal;\n }\n public void setClassVal(String classVal) {\n this.classVal = classVal;\n }\n public SubjectEntity getSubject() {\n return subject;\n }\n public void setSubject(SubjectEntity subject) {\n this.subject = subject;\n }\n}"
},
{
"code": null,
"e": 3994,
"s": 3946,
"text": "Student.java is unchanged with following code −"
},
{
"code": null,
"e": 4007,
"s": 3994,
"text": "Student.java"
},
{
"code": null,
"e": 4772,
"s": 4007,
"text": "package com.tutorialspoint.model;\n\npublic class Student {\n private final String name;\n private final int id;\n\n protected Student(Student.Builder builder) {\n this.name = builder.name;\n this.id = builder.id;\n }\n public static Student.Builder builder() {\n return new Student.Builder();\n }\n public static class Builder {\n private String name;\n private int id;\n\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n public Builder id(int id) {\n this.id = id;\n return this;\n }\n public Student create() {\n return new Student( this );\n }\n }\n public String getName() {\n return name;\n }\n public int getId() {\n ret+urn id;\n }\n}"
},
{
"code": null,
"e": 4832,
"s": 4772,
"text": "Update DeliveryAddressMapperTest.java with following code −"
},
{
"code": null,
"e": 4863,
"s": 4832,
"text": "DeliveryAddressMapperTest.java"
},
{
"code": null,
"e": 6092,
"s": 4863,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\nimport com.tutorialspoint.entity.AddressEntity;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.mapper.DeliveryAddressMapper;\nimport com.tutorialspoint.model.DeliveryAddress;\n\npublic class DeliveryAddressMapperTest {\n private DeliveryAddressMapper deliveryAddressMapper = Mappers.getMapper(DeliveryAddressMapper.class);\n\n @Test\n public void testEntityToModel() {\n StudentEntity student = new StudentEntity();\n student.setClassVal(\"X\");\n student.setName(\"John\");\n student.setId(\"1\");\n\n AddressEntity address = new AddressEntity();\n address.setCity(\"Y\");\n address.setState(\"Z\");\n address.setHouseNo(1);\n\n DeliveryAddress deliveryAddress = deliveryAddressMapper.getDeliveryAddress(student, address);\n\n assertEquals(deliveryAddress.getName(), student.getName());\n assertEquals(deliveryAddress.getCity(), address.getCity());\n assertEquals(deliveryAddress.getState(), address.getState());\n assertEquals(deliveryAddress.getHouseNumber(), address.getHouseNo());\n }\n}"
},
{
"code": null,
"e": 6144,
"s": 6092,
"text": "Update StudentMapperTest.java with following code −"
},
{
"code": null,
"e": 6167,
"s": 6144,
"text": "StudentMapperTest.java"
},
{
"code": null,
"e": 7342,
"s": 6167,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.entity.SubjectEntity;\nimport com.tutorialspoint.mapper.StudentMapper;\nimport com.tutorialspoint.model.Student;\n\npublic class StudentMapperTest {\n private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);\n\n @Test\n public void testEntityToModel() {\n StudentEntity entity = new StudentEntity();\n entity.setName(\"John\");\n entity.setId(\"1\");\n\n Student model = studentMapper.getModelFromEntity(entity);\n assertEquals(entity.getName(), model.getName());\n assertEquals(Integer.parseInt(entity.getId()), model.getId());\n }\n @Test\n public void testModelToEntity() {\n Student.Builder builder = Student.builder().id(1).name(\"John\");\n Student model = builder.create();\n StudentEntity entity = studentMapper.getEntityFromModel(model);\n\n assertEquals(entity.getName(), model.getName());\n assertEquals(Integer.parseInt(entity.getId()), model.getId());\n }\n}"
},
{
"code": null,
"e": 7390,
"s": 7342,
"text": "Run the following command to test the mappings."
},
{
"code": null,
"e": 7406,
"s": 7390,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 7453,
"s": 7406,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 8101,
"s": 7453,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec\n\nResults :\n\nTests run: 3, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 8108,
"s": 8101,
"text": " Print"
},
{
"code": null,
"e": 8119,
"s": 8108,
"text": " Add Notes"
}
] |
YAML - Block Sequences
|
The block sequences of YAML represent a series of nodes. Each item is denoted by a leading “-“ indicator. Note that the “-“ indicator in YAML should be separated from the node with a white space.
The basic representation of block sequence is given below −
block sequence:
··- one↓
- two : three↓
Observe the following examples for a better understanding of block sequences.
port: &ports
adapter: postgres
host: localhost
development:
database: myapp_development
<<: *ports
The output of block sequences in JSON format is given below −
{
"port": {
"adapter": "postgres",
"host": "localhost"
},
"development": {
"database": "myapp_development",
"adapter": "postgres",
"host": "localhost"
}
}
33 Lectures
44 mins
Tarun Telang
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2245,
"s": 2048,
"text": "The block sequences of YAML represent a series of nodes. Each item is denoted by a leading “-“ indicator. Note that the “-“ indicator in YAML should be separated from the node with a white space."
},
{
"code": null,
"e": 2305,
"s": 2245,
"text": "The basic representation of block sequence is given below −"
},
{
"code": null,
"e": 2348,
"s": 2305,
"text": "block sequence:\n··- one↓\n - two : three↓\n"
},
{
"code": null,
"e": 2426,
"s": 2348,
"text": "Observe the following examples for a better understanding of block sequences."
},
{
"code": null,
"e": 2539,
"s": 2426,
"text": "port: &ports\n adapter: postgres\n host: localhost\n\ndevelopment:\n database: myapp_development\n <<: *ports"
},
{
"code": null,
"e": 2601,
"s": 2539,
"text": "The output of block sequences in JSON format is given below −"
},
{
"code": null,
"e": 2799,
"s": 2601,
"text": "{\n \"port\": {\n \"adapter\": \"postgres\",\n \"host\": \"localhost\"\n },\n \"development\": {\n \"database\": \"myapp_development\",\n \"adapter\": \"postgres\",\n \"host\": \"localhost\"\n }\n}\n"
},
{
"code": null,
"e": 2831,
"s": 2799,
"text": "\n 33 Lectures \n 44 mins\n"
},
{
"code": null,
"e": 2845,
"s": 2831,
"text": " Tarun Telang"
},
{
"code": null,
"e": 2852,
"s": 2845,
"text": " Print"
},
{
"code": null,
"e": 2863,
"s": 2852,
"text": " Add Notes"
}
] |
Bootstrap show.bs.modal Event
|
The show.bs.modal event in Bootstrap fires when the modal is about to be displayed.
Here the alert is set using the same event and when the model is ready to be displayed, the event fires. This results in dispaying the alert to the visitor.
With that, I have also set a button that clicks the modal to open as shown in the below code snippet −
$(document).ready(function(){
$("#button1").click(function(){
$("#newModal").modal("show");
});
$("#newModal").on('show.bs.modal', function () {
alert('The modal will be displayed now!');
});
});
The following is an example to implement the show.bs.modal event in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Entrance Exams</h2>
<p>The following is the result of the entrance exam:</p>
<button type="button" class="btn btn-default btn-lg" id="button1">Result</button>
<div class="modal fade" id="newModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Selected Students</h4>
</div>
<div class="modal-body">
<p>Harry and Chris cleared the entrance exam.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#button1").click(function(){
$("#newModal").modal("show");
});
$("#newModal").on('show.bs.modal', function () {
alert('The modal will be displayed now!');
});
});
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1146,
"s": 1062,
"text": "The show.bs.modal event in Bootstrap fires when the modal is about to be displayed."
},
{
"code": null,
"e": 1303,
"s": 1146,
"text": "Here the alert is set using the same event and when the model is ready to be displayed, the event fires. This results in dispaying the alert to the visitor."
},
{
"code": null,
"e": 1406,
"s": 1303,
"text": "With that, I have also set a button that clicks the modal to open as shown in the below code snippet −"
},
{
"code": null,
"e": 1618,
"s": 1406,
"text": "$(document).ready(function(){\n $(\"#button1\").click(function(){\n $(\"#newModal\").modal(\"show\");\n });\n $(\"#newModal\").on('show.bs.modal', function () {\n alert('The modal will be displayed now!');\n });\n});"
},
{
"code": null,
"e": 1698,
"s": 1618,
"text": "The following is an example to implement the show.bs.modal event in Bootstrap −"
},
{
"code": null,
"e": 1708,
"s": 1698,
"text": "Live Demo"
},
{
"code": null,
"e": 3199,
"s": 1708,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<title>Bootstrap Example</title>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n</head>\n<body>\n\n<div class=\"container\">\n <h2>Entrance Exams</h2>\n <p>The following is the result of the entrance exam:</p>\n <button type=\"button\" class=\"btn btn-default btn-lg\" id=\"button1\">Result</button>\n\n <div class=\"modal fade\" id=\"newModal\" role=\"dialog\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n <h4 class=\"modal-title\">Selected Students</h4>\n </div>\n <div class=\"modal-body\">\n <p>Harry and Chris cleared the entrance exam.</p>\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-primary\" data-dismiss=\"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n</div>\n\n<script>\n$(document).ready(function(){\n $(\"#button1\").click(function(){\n $(\"#newModal\").modal(\"show\");\n });\n $(\"#newModal\").on('show.bs.modal', function () {\n alert('The modal will be displayed now!');\n });\n});\n</script>\n\n</body>\n</html>"
}
] |
Python program to find the highest 3 values in a dictionary
|
In this article, we will learn about the solution and approach to solve the given problem statement.
Given a dictionary, we need to find the three highest valued values and display them.
Live Demo
from collections import Counter
# Initial Dictionary
my_dict = {'t': 3, 'u': 4, 't': 6, 'o': 5, 'r': 21}
k = Counter(my_dict)
# Finding 3 highest values
high = k.most_common(3)
print("Dictionary with 3 highest values:")
print("Keys: Values")
for i in high:
print(i[0]," :",i[1]," ")
Dictionary with 3 highest values:
Keys: Values
r : 21
t : 6
o : 5
Live Demo
from collections import Counter
# Initial Dictionary
my_dict = {'t': 3, 'u': 4, 't': 6, 'o': 5, 'r': 21}
k = Counter(my_dict)
# Finding 3 highest values
high = k.most_common(3)
print("Dictionary with 3 highest values:")
print("Keys: Values")
for i in high:
print(i[0]," :",i[1]," ")
Dictionary with 3 highest values:
Keys: Values
r : 21
t : 6
o : 5
In this article, we learned about the approach to convert a decimal number to a binary number.
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "In this article, we will learn about the solution and approach to solve the given problem statement."
},
{
"code": null,
"e": 1249,
"s": 1163,
"text": "Given a dictionary, we need to find the three highest valued values and display them."
},
{
"code": null,
"e": 1260,
"s": 1249,
"text": " Live Demo"
},
{
"code": null,
"e": 1546,
"s": 1260,
"text": "from collections import Counter\n# Initial Dictionary\nmy_dict = {'t': 3, 'u': 4, 't': 6, 'o': 5, 'r': 21}\nk = Counter(my_dict)\n# Finding 3 highest values\nhigh = k.most_common(3)\nprint(\"Dictionary with 3 highest values:\")\nprint(\"Keys: Values\")\nfor i in high:\n print(i[0],\" :\",i[1],\" \")"
},
{
"code": null,
"e": 1612,
"s": 1546,
"text": "Dictionary with 3 highest values:\nKeys: Values\nr : 21\nt : 6\no : 5"
},
{
"code": null,
"e": 1623,
"s": 1612,
"text": " Live Demo"
},
{
"code": null,
"e": 1909,
"s": 1623,
"text": "from collections import Counter\n# Initial Dictionary\nmy_dict = {'t': 3, 'u': 4, 't': 6, 'o': 5, 'r': 21}\nk = Counter(my_dict)\n# Finding 3 highest values\nhigh = k.most_common(3)\nprint(\"Dictionary with 3 highest values:\")\nprint(\"Keys: Values\")\nfor i in high:\n print(i[0],\" :\",i[1],\" \")"
},
{
"code": null,
"e": 1975,
"s": 1909,
"text": "Dictionary with 3 highest values:\nKeys: Values\nr : 21\nt : 6\no : 5"
},
{
"code": null,
"e": 2070,
"s": 1975,
"text": "In this article, we learned about the approach to convert a decimal number to a binary number."
}
] |
How to update array of subdocuments in MongoDB?
|
To update, use update() along with $set. Let us create a collection with documents −
>db.demo134.insertOne({"EmployeeId":101,"EmployeeDetails":[{"EmployeeName":"Chris","EmployeeAge":27},{"EmployeeName":"Bob","EmployeeAge":28}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e319b2f68e7f832db1a7f7c")
}
>db.demo134.insertOne({"EmployeeId":102,"EmployeeDetails":[{"EmployeeName":"David","EmployeeAge":24},{"EmployeeName":"Carol","EmployeeAge":29}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e319b4468e7f832db1a7f7d")
}
Display all documents from a collection with the help of find() method −
> db.demo134.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e319b2f68e7f832db1a7f7c"),
"EmployeeId" : 101,
"EmployeeDetails" : [
{
"EmployeeName" : "Chris",
"EmployeeAge" : 27
},
{
"EmployeeName" : "Bob",
"EmployeeAge" : 28
}
]
}
{
"_id" : ObjectId("5e319b4468e7f832db1a7f7d"),
"EmployeeId" : 102,
"EmployeeDetails" : [
{
"EmployeeName" : "David",
"EmployeeAge" : 24
},
{
"EmployeeName" : "Carol",
"EmployeeAge" : 29
}
]
}
Following is the query to update array of subdocuments in MongoDB −
> db.demo134.update(
... {
... "EmployeeId":101,
... "EmployeeDetails.EmployeeName":"Chris"
... },
... {
... $set: {
... "EmployeeDetails.$.EmployeeName" : "Robert"
... }
... }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo134.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e319b2f68e7f832db1a7f7c"),
"EmployeeId" : 101,
"EmployeeDetails" : [
{
"EmployeeName" : "Robert",
"EmployeeAge" : 27
},
{
"EmployeeName" : "Bob",
"EmployeeAge" : 28
}
]
}
{
"_id" : ObjectId("5e319b4468e7f832db1a7f7d"),
"EmployeeId" : 102,
"EmployeeDetails" : [
{
"EmployeeName" : "David",
"EmployeeAge" : 24
},
{
"EmployeeName" : "Carol",
"EmployeeAge" : 29
}
]
}
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "To update, use update() along with $set. Let us create a collection with documents −"
},
{
"code": null,
"e": 1609,
"s": 1147,
"text": ">db.demo134.insertOne({\"EmployeeId\":101,\"EmployeeDetails\":[{\"EmployeeName\":\"Chris\",\"EmployeeAge\":27},{\"EmployeeName\":\"Bob\",\"EmployeeAge\":28}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e319b2f68e7f832db1a7f7c\")\n}\n>db.demo134.insertOne({\"EmployeeId\":102,\"EmployeeDetails\":[{\"EmployeeName\":\"David\",\"EmployeeAge\":24},{\"EmployeeName\":\"Carol\",\"EmployeeAge\":29}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e319b4468e7f832db1a7f7d\")\n}"
},
{
"code": null,
"e": 1682,
"s": 1609,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1712,
"s": 1682,
"text": "> db.demo134.find().pretty();"
},
{
"code": null,
"e": 1753,
"s": 1712,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2281,
"s": 1753,
"text": "{\n \"_id\" : ObjectId(\"5e319b2f68e7f832db1a7f7c\"),\n \"EmployeeId\" : 101,\n \"EmployeeDetails\" : [\n {\n \"EmployeeName\" : \"Chris\",\n \"EmployeeAge\" : 27\n },\n {\n \"EmployeeName\" : \"Bob\",\n \"EmployeeAge\" : 28\n }\n ]\n}\n{\n \"_id\" : ObjectId(\"5e319b4468e7f832db1a7f7d\"),\n \"EmployeeId\" : 102,\n \"EmployeeDetails\" : [\n {\n \"EmployeeName\" : \"David\",\n \"EmployeeAge\" : 24\n },\n {\n \"EmployeeName\" : \"Carol\",\n \"EmployeeAge\" : 29\n }\n ]\n}"
},
{
"code": null,
"e": 2349,
"s": 2281,
"text": "Following is the query to update array of subdocuments in MongoDB −"
},
{
"code": null,
"e": 2644,
"s": 2349,
"text": "> db.demo134.update(\n... {\n... \"EmployeeId\":101,\n... \"EmployeeDetails.EmployeeName\":\"Chris\"\n... },\n... {\n... $set: {\n... \"EmployeeDetails.$.EmployeeName\" : \"Robert\"\n... }\n... }\n... );\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 2717,
"s": 2644,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2747,
"s": 2717,
"text": "> db.demo134.find().pretty();"
},
{
"code": null,
"e": 2788,
"s": 2747,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3317,
"s": 2788,
"text": "{\n \"_id\" : ObjectId(\"5e319b2f68e7f832db1a7f7c\"),\n \"EmployeeId\" : 101,\n \"EmployeeDetails\" : [\n {\n \"EmployeeName\" : \"Robert\",\n \"EmployeeAge\" : 27\n },\n {\n \"EmployeeName\" : \"Bob\",\n \"EmployeeAge\" : 28\n }\n ]\n}\n{\n \"_id\" : ObjectId(\"5e319b4468e7f832db1a7f7d\"),\n \"EmployeeId\" : 102,\n \"EmployeeDetails\" : [\n {\n \"EmployeeName\" : \"David\",\n \"EmployeeAge\" : 24\n },\n {\n \"EmployeeName\" : \"Carol\",\n \"EmployeeAge\" : 29\n }\n ]\n}"
}
] |
MongoDB query to get specific month|year (not date)?
|
You can use aggregate framework along with $month projection operator. Let us first create a collection with documents −
> db.specificMonthDemo.insertOne({"StudentName":"Larry","StudentDateOfBirth":new ISODate('1995-01-12')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cb9a9ca8f1d1b97daf71819")
}
> db.specificMonthDemo.insertOne({"StudentName":"Chris","StudentDateOfBirth":new ISODate('1999-12-31')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cb9a9db8f1d1b97daf7181a")
}
> db.specificMonthDemo.insertOne({"StudentName":"David","StudentDateOfBirth":new ISODate('2000-06-01')});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cb9a9ee8f1d1b97daf7181b")
}
Following is the query to display all documents from the collection with the help of find() method −
> db.specificMonthDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cb9a9ca8f1d1b97daf71819"),
"StudentName" : "Larry",
"StudentDateOfBirth" : ISODate("1995-01-12T00:00:00Z")
}
{
"_id" : ObjectId("5cb9a9db8f1d1b97daf7181a"),
"StudentName" : "Chris",
"StudentDateOfBirth" : ISODate("1999-12-31T00:00:00Z")
}
{
"_id" : ObjectId("5cb9a9ee8f1d1b97daf7181b"),
"StudentName" : "David",
"StudentDateOfBirth" : ISODate("2000-06-01T00:00:00Z")
}
Following is the query to get specific month|year, not date −
> db.specificMonthDemo.aggregate([ {$project: {StudentName: 1, StudentDateOfBirth:
{$month: '$StudentDateOfBirth'}}}, {$match: {StudentDateOfBirth: 01}} ]).pretty();
This will produce the following output −
{
"_id" : ObjectId("5cb9a9ca8f1d1b97daf71819"),
"StudentName" : "Larry",
"StudentDateOfBirth" : 1
}
|
[
{
"code": null,
"e": 1183,
"s": 1062,
"text": "You can use aggregate framework along with $month projection operator. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1756,
"s": 1183,
"text": "> db.specificMonthDemo.insertOne({\"StudentName\":\"Larry\",\"StudentDateOfBirth\":new ISODate('1995-01-12')});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cb9a9ca8f1d1b97daf71819\")\n}\n> db.specificMonthDemo.insertOne({\"StudentName\":\"Chris\",\"StudentDateOfBirth\":new ISODate('1999-12-31')});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cb9a9db8f1d1b97daf7181a\")\n}\n> db.specificMonthDemo.insertOne({\"StudentName\":\"David\",\"StudentDateOfBirth\":new ISODate('2000-06-01')});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cb9a9ee8f1d1b97daf7181b\")\n}"
},
{
"code": null,
"e": 1857,
"s": 1756,
"text": "Following is the query to display all documents from the collection with the help of find() method −"
},
{
"code": null,
"e": 1897,
"s": 1857,
"text": "> db.specificMonthDemo.find().pretty();"
},
{
"code": null,
"e": 1938,
"s": 1897,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2355,
"s": 1938,
"text": "{\n \"_id\" : ObjectId(\"5cb9a9ca8f1d1b97daf71819\"),\n \"StudentName\" : \"Larry\",\n \"StudentDateOfBirth\" : ISODate(\"1995-01-12T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5cb9a9db8f1d1b97daf7181a\"),\n \"StudentName\" : \"Chris\",\n \"StudentDateOfBirth\" : ISODate(\"1999-12-31T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5cb9a9ee8f1d1b97daf7181b\"),\n \"StudentName\" : \"David\",\n \"StudentDateOfBirth\" : ISODate(\"2000-06-01T00:00:00Z\")\n}"
},
{
"code": null,
"e": 2417,
"s": 2355,
"text": "Following is the query to get specific month|year, not date −"
},
{
"code": null,
"e": 2586,
"s": 2417,
"text": "> db.specificMonthDemo.aggregate([ {$project: {StudentName: 1, StudentDateOfBirth:\n {$month: '$StudentDateOfBirth'}}}, {$match: {StudentDateOfBirth: 01}} ]).pretty();"
},
{
"code": null,
"e": 2627,
"s": 2586,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2736,
"s": 2627,
"text": "{\n \"_id\" : ObjectId(\"5cb9a9ca8f1d1b97daf71819\"),\n \"StudentName\" : \"Larry\",\n \"StudentDateOfBirth\" : 1\n}"
}
] |
What is unmanaged code in C#?
|
The following states what is an unmanaged code −
Applications that are not under the control of the CLR are unmanaged
The unsafe code or the unmanaged code is a code block that uses a pointer variable.
The unsafe modifier allows pointer usage in unmanaged code.
Here is the module showing how to declare and use a pointer variable. We have used the unsafe modifier here.
Let us see the example −
static unsafe void Main(string[] args) {
int var = 20;
int* p = &var;
Console.WriteLine("Data is: {0} ", var);
Console.WriteLine("Address is: {0}", (int)p);
Console.ReadKey();
}
|
[
{
"code": null,
"e": 1111,
"s": 1062,
"text": "The following states what is an unmanaged code −"
},
{
"code": null,
"e": 1180,
"s": 1111,
"text": "Applications that are not under the control of the CLR are unmanaged"
},
{
"code": null,
"e": 1264,
"s": 1180,
"text": "The unsafe code or the unmanaged code is a code block that uses a pointer variable."
},
{
"code": null,
"e": 1324,
"s": 1264,
"text": "The unsafe modifier allows pointer usage in unmanaged code."
},
{
"code": null,
"e": 1433,
"s": 1324,
"text": "Here is the module showing how to declare and use a pointer variable. We have used the unsafe modifier here."
},
{
"code": null,
"e": 1458,
"s": 1433,
"text": "Let us see the example −"
},
{
"code": null,
"e": 1652,
"s": 1458,
"text": "static unsafe void Main(string[] args) {\n int var = 20;\n int* p = &var;\n\n Console.WriteLine(\"Data is: {0} \", var);\n Console.WriteLine(\"Address is: {0}\", (int)p);\n Console.ReadKey();\n}"
}
] |
C/C++ Program to check whether it is possible to make a divisible by 3 number using all digits in an array?
|
In this section we will see if one array is given with n numbers, we have to check if we make a number using all of the elements of these numbers, that number will be divisible by 3 or not. If the array elements are {15, 24, 23, 13}, then the we can make integer like 15242313. It will be
divisible by 3.
Begin
rem := 0
for each element e in arr, do
rem := (rem + e) mod 3
done
if rem is 0, then
return true
end if
return false
End
#include<iostream>
#define MAX 4
using namespace std;
bool checkDivThree(int arr[], int n){
int rem = 0;
for(int i = 0; i<n; i++){
rem = (rem + arr[i]) % 3;
}
if(rem == 0){
return true;
}
return false;
}
main() {
int arr[] = {15, 24, 23, 13};
int n = sizeof(arr)/sizeof(arr[0]);
if(checkDivThree(arr, n)){
cout << "Divisible";
}else{
cout << "Not Divisible";
}
}
Divisible
|
[
{
"code": null,
"e": 1367,
"s": 1062,
"text": "In this section we will see if one array is given with n numbers, we have to check if we make a number using all of the elements of these numbers, that number will be divisible by 3 or not. If the array elements are {15, 24, 23, 13}, then the we can make integer like 15242313. It will be\ndivisible by 3."
},
{
"code": null,
"e": 1524,
"s": 1367,
"text": "Begin\n rem := 0\n for each element e in arr, do\n rem := (rem + e) mod 3\n done\n if rem is 0, then\n return true\n end if\n return false\nEnd"
},
{
"code": null,
"e": 1944,
"s": 1524,
"text": "#include<iostream>\n#define MAX 4\nusing namespace std;\nbool checkDivThree(int arr[], int n){\n int rem = 0;\n for(int i = 0; i<n; i++){\n rem = (rem + arr[i]) % 3;\n }\n if(rem == 0){\n return true;\n }\n return false;\n}\nmain() {\n int arr[] = {15, 24, 23, 13};\n int n = sizeof(arr)/sizeof(arr[0]);\n if(checkDivThree(arr, n)){\n cout << \"Divisible\";\n }else{\n cout << \"Not Divisible\";\n }\n}"
},
{
"code": null,
"e": 1954,
"s": 1944,
"text": "Divisible"
}
] |
JavaScript - Create an alert on clicking an HTML button
|
To fire an alert on click of a button, use addEventListener(). Let’s say the following is our button on an HTML web page −
<button type="button">Please Press Me</button>
Following is the code −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<button type="button">Please Press Me</button>
</body>
<script>
var pressedButton = document.getElementsByTagName("button")[0];
pressedButton.addEventListener("click", function (event) {
alert("You have pressed the button..........")
})
</script>
</html>
To run the above program, save the file name anyName.html(index.html). Right click on the file and select the option “Open with live server” in VS Code editor −
The output is as follows −
Whenever you press the button, you will get an alert message.
The output is as follows −
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "To fire an alert on click of a button, use addEventListener(). Let’s say the following is our button on an HTML web page −"
},
{
"code": null,
"e": 1232,
"s": 1185,
"text": "<button type=\"button\">Please Press Me</button>"
},
{
"code": null,
"e": 1256,
"s": 1232,
"text": "Following is the code −"
},
{
"code": null,
"e": 1267,
"s": 1256,
"text": " Live Demo"
},
{
"code": null,
"e": 1943,
"s": 1267,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<body>\n <button type=\"button\">Please Press Me</button>\n</body>\n<script>\n var pressedButton = document.getElementsByTagName(\"button\")[0];\n pressedButton.addEventListener(\"click\", function (event) {\n alert(\"You have pressed the button..........\")\n })\n</script>\n</html>"
},
{
"code": null,
"e": 2104,
"s": 1943,
"text": "To run the above program, save the file name anyName.html(index.html). Right click on the file and select the option “Open with live server” in VS Code editor −"
},
{
"code": null,
"e": 2131,
"s": 2104,
"text": "The output is as follows −"
},
{
"code": null,
"e": 2193,
"s": 2131,
"text": "Whenever you press the button, you will get an alert message."
},
{
"code": null,
"e": 2220,
"s": 2193,
"text": "The output is as follows −"
}
] |
Clojure - Atoms swap!
|
Atomically swaps the value of the atom with a new one based on a particular function.
Following is the syntax.
(swap! atom-name function)
Parameters − ‘atom-name’ is the name of the atom whose value needs to be reset. ‘function’ is the function which is used to generate the new value of the atom.
Return Value − The atom with the new value will be set based on the function provided.
An example on how this is used is shown in the following program.
(ns clojure.examples.example
(:gen-class))
(defn example []
(def myatom (atom 1))
(println @myatom)
(swap! myatom inc)
(println @myatom))
(example)
The above program produces the following output.
1
2
From the above program you can see that the ‘inc’ (Increment function) is used to increment the value of the atom and with the help of the swap! function, the new value is automatically associated with the atom.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2460,
"s": 2374,
"text": "Atomically swaps the value of the atom with a new one based on a particular function."
},
{
"code": null,
"e": 2485,
"s": 2460,
"text": "Following is the syntax."
},
{
"code": null,
"e": 2513,
"s": 2485,
"text": "(swap! atom-name function)\n"
},
{
"code": null,
"e": 2673,
"s": 2513,
"text": "Parameters − ‘atom-name’ is the name of the atom whose value needs to be reset. ‘function’ is the function which is used to generate the new value of the atom."
},
{
"code": null,
"e": 2760,
"s": 2673,
"text": "Return Value − The atom with the new value will be set based on the function provided."
},
{
"code": null,
"e": 2826,
"s": 2760,
"text": "An example on how this is used is shown in the following program."
},
{
"code": null,
"e": 2993,
"s": 2826,
"text": "(ns clojure.examples.example\n (:gen-class))\n(defn example []\n (def myatom (atom 1))\n (println @myatom)\n \n (swap! myatom inc)\n (println @myatom))\n(example)"
},
{
"code": null,
"e": 3042,
"s": 2993,
"text": "The above program produces the following output."
},
{
"code": null,
"e": 3047,
"s": 3042,
"text": "1\n2\n"
},
{
"code": null,
"e": 3259,
"s": 3047,
"text": "From the above program you can see that the ‘inc’ (Increment function) is used to increment the value of the atom and with the help of the swap! function, the new value is automatically associated with the atom."
},
{
"code": null,
"e": 3266,
"s": 3259,
"text": " Print"
},
{
"code": null,
"e": 3277,
"s": 3266,
"text": " Add Notes"
}
] |
Should You Become a Data Engineer in 2021? | by Nicholas Leong | Towards Data Science
|
All of us have heard about the title — Data Scientist, the sexiest job of the 21st Century.But is it really?
For many people who are new to the data industry, Data Science will be the first thing they hear about, and the title just sticks. Suddenly, everyone is either already a Data Scientist, or aspiring to be one.
However, that is not the only job title in the industry.
There are many more job titles that are related to data.Data Scientists have been on the frontier of data for way too long, it is time for the emerging of Data Engineers and other data-related roles.
Looking at 2020 data, it is already happening.Data Science might be slowing down.
According to the 2021 Data Science Interview Report by interviewquery.com that takes in over 10,000 Data Science interview experiences, Data Science interviews grew by 10% compared to Data Engineering interviews which grew by 40% in 2020.
On job growth, data was taken from over 450+ tech companies. For the data scientist role, there was actually a 15% decrease in job growth in 2020 versus 2019. This dip was offset by the growth in other data-related roles like business analysts and data engineers.
Hence, stop spreading the news that Data Scientist is still the sexiest job.There are ‘hotter’ roles in data right now, and Data Engineer is one of them.
Let’s talk about job growth and the demand for data engineers.According to DICE’s 2020 Tech Job Report, Data Engineer is the fastest-growing job in 2019, growing by 50% YoY. Data Scientist is also up there on the list, growing by 32% YoY.
But that’s not all, other salary studies have also found similar results about the Data Engineer role —
Hired State of Software Engineers Report— 45% YoY Job Growth
LinkedIn’s Emerging Job Report 2020–33% YoY Job Growth
Burning Glass Nova Platform — 88% YoY Job Growth
As data practitioners, we understand that data doesn’t lie. The data states that Data Engineering is one of the fastest-growing jobs in recent years, even as far as surpassing Data Science roles.
According to the IDG Cloud Survey, which collects data from 551 large tech buyers, states that only 38% of their total IT environments are on the cloud as of today (2020).
In 18 months, these IT environments are expected to hit 59% on the cloud. The same tech buyers are also allocating 32% of the IT budget to cloud computing, which amounts to $73.8M per Tech Firm (59% increase from 2018).
After a huge influx of Data Scientists, companies realized they needed the proper data infrastructure to perform any meaningful analysis on the data. Companies have started to spend money on proper cloud infrastructure, data architecture, and hiring new data engineering talents.
One solid proof of demand for Data Engineers is the growth in big data.If you’ve been living under a rock, data is the new oil.
New data is being generated every day, and it will only continue to grow. With the insane amount of data, there will be an increase in the demand for engineers to handle data.
Another giveaway is the growth in big data engineering services provided by consulting firms like Accenture and other tech companies like Cognizant. With the increase in data, proper data engineering services is increasing as well. The data engineering services market is experiencing an 18% growth p.a, which is expected to hit 31% p.a by 2025.
Data Engineers' salaries are very high. Even higher than Data Scientists’ in many cases. Many salary studies (summarized below), have shown that Data Engineers are among the highest-paid talent, and their salaries do not see any slowing down anytime soon.
According to Hired’s 2019 State of Software Engineers report, average salaries for data engineers increased 7% in New York and 6% in the Bay area, vs. an average of 3.5% for the rest of Americans.
Here are the salary studies on Data Engineers —
As seen from the data, Data Engineers comfortably make anywhereabove $110k which is considered a respectable number by most people. Furthermore, the salaries are expected to increase due to the shortage of supply of Data Engineers.
Based on a study done by Ori Rafael (CEO of Upsolver), there are about 2.5 candidates per job listing on LinkedIn for the Data Engineer role compared to the other roles which have much more applicants.
The number suggests that there is a shortage in the supply of Data Engineers. Hence, applicants are much more likely to negotiate a higher salary range for themselves in the hiring process.
It goes without saying the hiring process is different for everyone, and the negotiation range depends on a wide range of factors. These factors include but are not limited to —
Years of Experience
Skills
Previous Achievements
Location of Company
Industry
Speaking from experience, I have personally seen companies that value their data greatly offer higher salaries compared to other companies. A good example of these companies are companies that offer some sort of data product, as well as having some sort of goals for their data.
So, what do Data Engineers do?Well, I’ve written all about it here in one of my previous posts.
towardsdatascience.com
Essentially, Data Engineers manage the core foundation on how the data of the company is structured in the data warehouse. Tasks range from designing table structures to building ETL/ELT pipelines to ensure a scalable, high-performance infrastructure to satisfy all data needs of the company.
They also deal with pretty much anything that has to do with automation with data. One of the examples I have worked on before is the Gmail Data Pipeline I created.
towardsdatascience.com
Data Engineers are able to answer questions like —
When an event happens on the site, what happens in the master database?
Why are the tables in the data warehouse structured like that?
Why do we extract data on a daily basis instead of hourly?
More advanced Data Engineers also work on streaming data pipelines that ingest data into a data sink in real-time. This is extremely useful for Machine Learning products that take in data and perform something with it in real-time.
There is a wide range of skills required to be a Data Engineer. Besides mastering programming languages, Data Engineers need to understand how databases work, as well as how to properly design pipelines to load data into databases. I’ll make it easier for you by summarizing it into 5 main competencies —
Programming Language — Python and SQL
SQL and NoSQL Databases
ETL/ELT Technologies — Apache Airflow, Hadoop
Streaming — Apache Beam
Infrastructure — Cloud Infrastructure
These skills combine perfectly to form a Data Engineer.To really get a feel on how to build pipelines, take a look at a guide I wrote on how to build your first pipeline using Apache Airflow.
towardsdatascience.com
If you have made it this far, you must be really interested in Data Engineering.
What’s there not to like?
It is one of the fastest-growing jobs in one of the fastest-growing industries while having one of the highest average salaries in the world. It almost sounds too good to be true. In this article, we have discussed the following on the position —
- Job Outlook- Pay- Responsibilies- Skills
As usual, I end with a quote.
You can have data without information, but you cannot have information without data — Daniel Keys Moran
You can also support me by signing up for a medium membership through my link. You will be able to read an unlimited amount of stories from me and other incredible writers!
I am working on more stories, writings, and guides in the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data.
Thanks for reading! If you want to get in touch with me, feel free to reach me at nickmydata@gmail.com or my LinkedIn Profile. You can also view the code for previous write-ups in my Github.
|
[
{
"code": null,
"e": 280,
"s": 171,
"text": "All of us have heard about the title — Data Scientist, the sexiest job of the 21st Century.But is it really?"
},
{
"code": null,
"e": 489,
"s": 280,
"text": "For many people who are new to the data industry, Data Science will be the first thing they hear about, and the title just sticks. Suddenly, everyone is either already a Data Scientist, or aspiring to be one."
},
{
"code": null,
"e": 546,
"s": 489,
"text": "However, that is not the only job title in the industry."
},
{
"code": null,
"e": 746,
"s": 546,
"text": "There are many more job titles that are related to data.Data Scientists have been on the frontier of data for way too long, it is time for the emerging of Data Engineers and other data-related roles."
},
{
"code": null,
"e": 828,
"s": 746,
"text": "Looking at 2020 data, it is already happening.Data Science might be slowing down."
},
{
"code": null,
"e": 1067,
"s": 828,
"text": "According to the 2021 Data Science Interview Report by interviewquery.com that takes in over 10,000 Data Science interview experiences, Data Science interviews grew by 10% compared to Data Engineering interviews which grew by 40% in 2020."
},
{
"code": null,
"e": 1331,
"s": 1067,
"text": "On job growth, data was taken from over 450+ tech companies. For the data scientist role, there was actually a 15% decrease in job growth in 2020 versus 2019. This dip was offset by the growth in other data-related roles like business analysts and data engineers."
},
{
"code": null,
"e": 1485,
"s": 1331,
"text": "Hence, stop spreading the news that Data Scientist is still the sexiest job.There are ‘hotter’ roles in data right now, and Data Engineer is one of them."
},
{
"code": null,
"e": 1724,
"s": 1485,
"text": "Let’s talk about job growth and the demand for data engineers.According to DICE’s 2020 Tech Job Report, Data Engineer is the fastest-growing job in 2019, growing by 50% YoY. Data Scientist is also up there on the list, growing by 32% YoY."
},
{
"code": null,
"e": 1828,
"s": 1724,
"text": "But that’s not all, other salary studies have also found similar results about the Data Engineer role —"
},
{
"code": null,
"e": 1889,
"s": 1828,
"text": "Hired State of Software Engineers Report— 45% YoY Job Growth"
},
{
"code": null,
"e": 1944,
"s": 1889,
"text": "LinkedIn’s Emerging Job Report 2020–33% YoY Job Growth"
},
{
"code": null,
"e": 1993,
"s": 1944,
"text": "Burning Glass Nova Platform — 88% YoY Job Growth"
},
{
"code": null,
"e": 2189,
"s": 1993,
"text": "As data practitioners, we understand that data doesn’t lie. The data states that Data Engineering is one of the fastest-growing jobs in recent years, even as far as surpassing Data Science roles."
},
{
"code": null,
"e": 2361,
"s": 2189,
"text": "According to the IDG Cloud Survey, which collects data from 551 large tech buyers, states that only 38% of their total IT environments are on the cloud as of today (2020)."
},
{
"code": null,
"e": 2581,
"s": 2361,
"text": "In 18 months, these IT environments are expected to hit 59% on the cloud. The same tech buyers are also allocating 32% of the IT budget to cloud computing, which amounts to $73.8M per Tech Firm (59% increase from 2018)."
},
{
"code": null,
"e": 2861,
"s": 2581,
"text": "After a huge influx of Data Scientists, companies realized they needed the proper data infrastructure to perform any meaningful analysis on the data. Companies have started to spend money on proper cloud infrastructure, data architecture, and hiring new data engineering talents."
},
{
"code": null,
"e": 2989,
"s": 2861,
"text": "One solid proof of demand for Data Engineers is the growth in big data.If you’ve been living under a rock, data is the new oil."
},
{
"code": null,
"e": 3165,
"s": 2989,
"text": "New data is being generated every day, and it will only continue to grow. With the insane amount of data, there will be an increase in the demand for engineers to handle data."
},
{
"code": null,
"e": 3511,
"s": 3165,
"text": "Another giveaway is the growth in big data engineering services provided by consulting firms like Accenture and other tech companies like Cognizant. With the increase in data, proper data engineering services is increasing as well. The data engineering services market is experiencing an 18% growth p.a, which is expected to hit 31% p.a by 2025."
},
{
"code": null,
"e": 3767,
"s": 3511,
"text": "Data Engineers' salaries are very high. Even higher than Data Scientists’ in many cases. Many salary studies (summarized below), have shown that Data Engineers are among the highest-paid talent, and their salaries do not see any slowing down anytime soon."
},
{
"code": null,
"e": 3964,
"s": 3767,
"text": "According to Hired’s 2019 State of Software Engineers report, average salaries for data engineers increased 7% in New York and 6% in the Bay area, vs. an average of 3.5% for the rest of Americans."
},
{
"code": null,
"e": 4012,
"s": 3964,
"text": "Here are the salary studies on Data Engineers —"
},
{
"code": null,
"e": 4244,
"s": 4012,
"text": "As seen from the data, Data Engineers comfortably make anywhereabove $110k which is considered a respectable number by most people. Furthermore, the salaries are expected to increase due to the shortage of supply of Data Engineers."
},
{
"code": null,
"e": 4446,
"s": 4244,
"text": "Based on a study done by Ori Rafael (CEO of Upsolver), there are about 2.5 candidates per job listing on LinkedIn for the Data Engineer role compared to the other roles which have much more applicants."
},
{
"code": null,
"e": 4636,
"s": 4446,
"text": "The number suggests that there is a shortage in the supply of Data Engineers. Hence, applicants are much more likely to negotiate a higher salary range for themselves in the hiring process."
},
{
"code": null,
"e": 4814,
"s": 4636,
"text": "It goes without saying the hiring process is different for everyone, and the negotiation range depends on a wide range of factors. These factors include but are not limited to —"
},
{
"code": null,
"e": 4834,
"s": 4814,
"text": "Years of Experience"
},
{
"code": null,
"e": 4841,
"s": 4834,
"text": "Skills"
},
{
"code": null,
"e": 4863,
"s": 4841,
"text": "Previous Achievements"
},
{
"code": null,
"e": 4883,
"s": 4863,
"text": "Location of Company"
},
{
"code": null,
"e": 4892,
"s": 4883,
"text": "Industry"
},
{
"code": null,
"e": 5171,
"s": 4892,
"text": "Speaking from experience, I have personally seen companies that value their data greatly offer higher salaries compared to other companies. A good example of these companies are companies that offer some sort of data product, as well as having some sort of goals for their data."
},
{
"code": null,
"e": 5267,
"s": 5171,
"text": "So, what do Data Engineers do?Well, I’ve written all about it here in one of my previous posts."
},
{
"code": null,
"e": 5290,
"s": 5267,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5583,
"s": 5290,
"text": "Essentially, Data Engineers manage the core foundation on how the data of the company is structured in the data warehouse. Tasks range from designing table structures to building ETL/ELT pipelines to ensure a scalable, high-performance infrastructure to satisfy all data needs of the company."
},
{
"code": null,
"e": 5748,
"s": 5583,
"text": "They also deal with pretty much anything that has to do with automation with data. One of the examples I have worked on before is the Gmail Data Pipeline I created."
},
{
"code": null,
"e": 5771,
"s": 5748,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5822,
"s": 5771,
"text": "Data Engineers are able to answer questions like —"
},
{
"code": null,
"e": 5894,
"s": 5822,
"text": "When an event happens on the site, what happens in the master database?"
},
{
"code": null,
"e": 5957,
"s": 5894,
"text": "Why are the tables in the data warehouse structured like that?"
},
{
"code": null,
"e": 6016,
"s": 5957,
"text": "Why do we extract data on a daily basis instead of hourly?"
},
{
"code": null,
"e": 6248,
"s": 6016,
"text": "More advanced Data Engineers also work on streaming data pipelines that ingest data into a data sink in real-time. This is extremely useful for Machine Learning products that take in data and perform something with it in real-time."
},
{
"code": null,
"e": 6553,
"s": 6248,
"text": "There is a wide range of skills required to be a Data Engineer. Besides mastering programming languages, Data Engineers need to understand how databases work, as well as how to properly design pipelines to load data into databases. I’ll make it easier for you by summarizing it into 5 main competencies —"
},
{
"code": null,
"e": 6591,
"s": 6553,
"text": "Programming Language — Python and SQL"
},
{
"code": null,
"e": 6615,
"s": 6591,
"text": "SQL and NoSQL Databases"
},
{
"code": null,
"e": 6661,
"s": 6615,
"text": "ETL/ELT Technologies — Apache Airflow, Hadoop"
},
{
"code": null,
"e": 6685,
"s": 6661,
"text": "Streaming — Apache Beam"
},
{
"code": null,
"e": 6723,
"s": 6685,
"text": "Infrastructure — Cloud Infrastructure"
},
{
"code": null,
"e": 6915,
"s": 6723,
"text": "These skills combine perfectly to form a Data Engineer.To really get a feel on how to build pipelines, take a look at a guide I wrote on how to build your first pipeline using Apache Airflow."
},
{
"code": null,
"e": 6938,
"s": 6915,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7019,
"s": 6938,
"text": "If you have made it this far, you must be really interested in Data Engineering."
},
{
"code": null,
"e": 7045,
"s": 7019,
"text": "What’s there not to like?"
},
{
"code": null,
"e": 7292,
"s": 7045,
"text": "It is one of the fastest-growing jobs in one of the fastest-growing industries while having one of the highest average salaries in the world. It almost sounds too good to be true. In this article, we have discussed the following on the position —"
},
{
"code": null,
"e": 7335,
"s": 7292,
"text": "- Job Outlook- Pay- Responsibilies- Skills"
},
{
"code": null,
"e": 7365,
"s": 7335,
"text": "As usual, I end with a quote."
},
{
"code": null,
"e": 7469,
"s": 7365,
"text": "You can have data without information, but you cannot have information without data — Daniel Keys Moran"
},
{
"code": null,
"e": 7642,
"s": 7469,
"text": "You can also support me by signing up for a medium membership through my link. You will be able to read an unlimited amount of stories from me and other incredible writers!"
},
{
"code": null,
"e": 7863,
"s": 7642,
"text": "I am working on more stories, writings, and guides in the data industry. You can absolutely expect more posts like this. In the meantime, feel free to check out my other articles to temporarily fill your hunger for data."
}
] |
Perl List and its Types - GeeksforGeeks
|
12 Jun, 2021
A list is a collection of scalar values. We can access the elements of a list using indexes. Index starts with 0 (0th index refers to the first element of the list). We use parenthesis and comma operators to construct a list. In Perl, scalar variables start with a $ symbol whereas list variables start with @ symbol.Important Note : List in perl is not a data structure. They are only some subexpressions/expressions in code. They are typically assigned to an array.
Perl
#!/usr/bin/perl # Empty List assigned to an array# Note that the expression () is a# list and "empty_list" variable is an# array variable.@empty_list = (); # Note that the expression (1, 2, 3) is a# list and "integer_list" variable is an# array variable.@integer_list = (1, 2, 3);
Lists are of multiple types as described below:
Simple Lists: A list with same datatypes is referred to as a Simple List Example :
Perl
#!/usr/bin/perl # Empty List assigned to an array@empty_list = (); # List of integers@integer_list = (1, 2, 3); # List of strings assigned to an array@string_list = ("Geeks", "for", "Geeks"); print "Empty list: @empty_list\n";print "Integer list: @integer_list\n";print "String list: @string_list\n";
Output:
Empty list:
Integer list: 1 2 3
String list: Geeks for Geeks
Complex Lists: A list may contain various different datatypes. These type of lists are referred to as Complex Lists. Example :
Perl
#!/usr/bin/perl # List of strings and integers assigned to an array@complex_list = (1, 2, "Geeks", "for", "Geeks"); # printing this Listprint "Complex List: @complex_list";
Output:
Complex List: 1 2 Geeks for Geeks
Flattening List: A list may contain another list within it but Perl will flatten the internal list and the elements of this list will be treated as the elements of the outer list. Example :
Perl
#!/usr/bin/perl # Defining Internal list as an array@Internal_list = (5, 6, 7); # Defining External list.@External_list = (1, "Geeks", 3, "For", @Internal_list); # Printing Flattening listprint "Printing list within list: @External_list";
Output:
Printing list within list: 1 Geeks 3 For 5 6 7
List elements can be accessed with the use of a scalar variable. While accessing a List element, $ is used, because a scalar variable in Perl is accessed with the use of $ symbol. Example :
Perl
#!/usr/bin/perl # Defining a list@List = (1, 2, 3, 4, 5); # Accessing list elementprint "Second element of List is: $List[2]";
Output:
Second element of List is: 3
Slicing a list in Perl can be done by giving comma(,) separated index values to another list. Example:
Perl
#!/usr/bin/perl # Defining 1st List@list1 = (1, "Geeks", 3, "For", 5); # Defining 2nd List@list2 = @list1[1, 2, 4]; # Printing Sliced Listprint "Sliced List: @list2";
Output:
Sliced List: Geeks 3 5
Range operator in Perl is used as a short way to create a list. When used with list, the range operator simplifies the process of creating a list with contiguous sequences of numbers and letters. The range operator can also be used for slicing the list.
Syntax: leftValue..rightValue
Note: If leftValue is greater than rightValue then it will create an empty list otherwise it will contiguously allocate values from leftValue till rightValue.Examples :
Perl
#!/usr/bin/perl # Defining list with range of a to j@x = ("a".."j"); # Defining list with range of 1 to 15@y = (1..15); # Defining list with range of A to J@z = ("A".."J"); # Printing these listsprint "List with elements from a to j: @x\n";print "List with elements from 1 to 15: @y\n";print "List with elements from A to J: @z";
Output:
List with elements from a to j: a b c d e f g h i j
List with elements from 1 to 15: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
List with elements from A to J: A B C D E F G H I J
Combining Ranges and Slices: Range and slice operators can be combined together to perform slicing operation on a list. Example:
Perl
#!/usr/bin/perl # Defining a list of elements@x = ("Geeks", 2, 3, "For", 5); # Use of Range and slice operator@z = @x[2..4]; # Printing the sliced Listprint "Sliced List: @z";
Output:
Sliced List: 3 For 5
simranarora5sos
Marketing
Perl-Arrays
perl-data-types
perl-list
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | split() Function
Perl | exists() Function
Perl | chomp() Function
Perl | push() Function
Perl | length() Function
Perl | grep() Function
Perl Tutorial - Learn Perl With Examples
Perl | Removing leading and trailing white spaces (trim)
Perl | join() Function
Perl | substr() function
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n12 Jun, 2021"
},
{
"code": null,
"e": 25694,
"s": 25225,
"text": "A list is a collection of scalar values. We can access the elements of a list using indexes. Index starts with 0 (0th index refers to the first element of the list). We use parenthesis and comma operators to construct a list. In Perl, scalar variables start with a $ symbol whereas list variables start with @ symbol.Important Note : List in perl is not a data structure. They are only some subexpressions/expressions in code. They are typically assigned to an array. "
},
{
"code": null,
"e": 25699,
"s": 25694,
"text": "Perl"
},
{
"code": "#!/usr/bin/perl # Empty List assigned to an array# Note that the expression () is a# list and \"empty_list\" variable is an# array variable.@empty_list = (); # Note that the expression (1, 2, 3) is a# list and \"integer_list\" variable is an# array variable.@integer_list = (1, 2, 3);",
"e": 25980,
"s": 25699,
"text": null
},
{
"code": null,
"e": 26032,
"s": 25980,
"text": " Lists are of multiple types as described below: "
},
{
"code": null,
"e": 26117,
"s": 26032,
"text": "Simple Lists: A list with same datatypes is referred to as a Simple List Example : "
},
{
"code": null,
"e": 26122,
"s": 26117,
"text": "Perl"
},
{
"code": "#!/usr/bin/perl # Empty List assigned to an array@empty_list = (); # List of integers@integer_list = (1, 2, 3); # List of strings assigned to an array@string_list = (\"Geeks\", \"for\", \"Geeks\"); print \"Empty list: @empty_list\\n\";print \"Integer list: @integer_list\\n\";print \"String list: @string_list\\n\";",
"e": 26423,
"s": 26122,
"text": null
},
{
"code": null,
"e": 26433,
"s": 26423,
"text": "Output: "
},
{
"code": null,
"e": 26495,
"s": 26433,
"text": "Empty list: \nInteger list: 1 2 3\nString list: Geeks for Geeks"
},
{
"code": null,
"e": 26626,
"s": 26497,
"text": "Complex Lists: A list may contain various different datatypes. These type of lists are referred to as Complex Lists. Example : "
},
{
"code": null,
"e": 26631,
"s": 26626,
"text": "Perl"
},
{
"code": "#!/usr/bin/perl # List of strings and integers assigned to an array@complex_list = (1, 2, \"Geeks\", \"for\", \"Geeks\"); # printing this Listprint \"Complex List: @complex_list\";",
"e": 26804,
"s": 26631,
"text": null
},
{
"code": null,
"e": 26814,
"s": 26804,
"text": "Output: "
},
{
"code": null,
"e": 26848,
"s": 26814,
"text": "Complex List: 1 2 Geeks for Geeks"
},
{
"code": null,
"e": 27042,
"s": 26850,
"text": "Flattening List: A list may contain another list within it but Perl will flatten the internal list and the elements of this list will be treated as the elements of the outer list. Example : "
},
{
"code": null,
"e": 27047,
"s": 27042,
"text": "Perl"
},
{
"code": "#!/usr/bin/perl # Defining Internal list as an array@Internal_list = (5, 6, 7); # Defining External list.@External_list = (1, \"Geeks\", 3, \"For\", @Internal_list); # Printing Flattening listprint \"Printing list within list: @External_list\";",
"e": 27286,
"s": 27047,
"text": null
},
{
"code": null,
"e": 27296,
"s": 27286,
"text": "Output: "
},
{
"code": null,
"e": 27343,
"s": 27296,
"text": "Printing list within list: 1 Geeks 3 For 5 6 7"
},
{
"code": null,
"e": 27539,
"s": 27347,
"text": "List elements can be accessed with the use of a scalar variable. While accessing a List element, $ is used, because a scalar variable in Perl is accessed with the use of $ symbol. Example : "
},
{
"code": null,
"e": 27544,
"s": 27539,
"text": "Perl"
},
{
"code": "#!/usr/bin/perl # Defining a list@List = (1, 2, 3, 4, 5); # Accessing list elementprint \"Second element of List is: $List[2]\";",
"e": 27671,
"s": 27544,
"text": null
},
{
"code": null,
"e": 27681,
"s": 27671,
"text": "Output: "
},
{
"code": null,
"e": 27710,
"s": 27681,
"text": "Second element of List is: 3"
},
{
"code": null,
"e": 27817,
"s": 27712,
"text": "Slicing a list in Perl can be done by giving comma(,) separated index values to another list. Example: "
},
{
"code": null,
"e": 27822,
"s": 27817,
"text": "Perl"
},
{
"code": "#!/usr/bin/perl # Defining 1st List@list1 = (1, \"Geeks\", 3, \"For\", 5); # Defining 2nd List@list2 = @list1[1, 2, 4]; # Printing Sliced Listprint \"Sliced List: @list2\";",
"e": 27989,
"s": 27822,
"text": null
},
{
"code": null,
"e": 27999,
"s": 27989,
"text": "Output: "
},
{
"code": null,
"e": 28022,
"s": 27999,
"text": "Sliced List: Geeks 3 5"
},
{
"code": null,
"e": 28280,
"s": 28024,
"text": "Range operator in Perl is used as a short way to create a list. When used with list, the range operator simplifies the process of creating a list with contiguous sequences of numbers and letters. The range operator can also be used for slicing the list. "
},
{
"code": null,
"e": 28312,
"s": 28280,
"text": "Syntax: leftValue..rightValue "
},
{
"code": null,
"e": 28483,
"s": 28312,
"text": "Note: If leftValue is greater than rightValue then it will create an empty list otherwise it will contiguously allocate values from leftValue till rightValue.Examples : "
},
{
"code": null,
"e": 28488,
"s": 28483,
"text": "Perl"
},
{
"code": "#!/usr/bin/perl # Defining list with range of a to j@x = (\"a\"..\"j\"); # Defining list with range of 1 to 15@y = (1..15); # Defining list with range of A to J@z = (\"A\"..\"J\"); # Printing these listsprint \"List with elements from a to j: @x\\n\";print \"List with elements from 1 to 15: @y\\n\";print \"List with elements from A to J: @z\";",
"e": 28818,
"s": 28488,
"text": null
},
{
"code": null,
"e": 28828,
"s": 28818,
"text": "Output: "
},
{
"code": null,
"e": 29001,
"s": 28828,
"text": "List with elements from a to j: a b c d e f g h i j\nList with elements from 1 to 15: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\nList with elements from A to J: A B C D E F G H I J"
},
{
"code": null,
"e": 29132,
"s": 29001,
"text": "Combining Ranges and Slices: Range and slice operators can be combined together to perform slicing operation on a list. Example: "
},
{
"code": null,
"e": 29137,
"s": 29132,
"text": "Perl"
},
{
"code": "#!/usr/bin/perl # Defining a list of elements@x = (\"Geeks\", 2, 3, \"For\", 5); # Use of Range and slice operator@z = @x[2..4]; # Printing the sliced Listprint \"Sliced List: @z\";",
"e": 29313,
"s": 29137,
"text": null
},
{
"code": null,
"e": 29323,
"s": 29313,
"text": "Output: "
},
{
"code": null,
"e": 29344,
"s": 29323,
"text": "Sliced List: 3 For 5"
},
{
"code": null,
"e": 29362,
"s": 29346,
"text": "simranarora5sos"
},
{
"code": null,
"e": 29372,
"s": 29362,
"text": "Marketing"
},
{
"code": null,
"e": 29384,
"s": 29372,
"text": "Perl-Arrays"
},
{
"code": null,
"e": 29400,
"s": 29384,
"text": "perl-data-types"
},
{
"code": null,
"e": 29410,
"s": 29400,
"text": "perl-list"
},
{
"code": null,
"e": 29417,
"s": 29410,
"text": "Picked"
},
{
"code": null,
"e": 29422,
"s": 29417,
"text": "Perl"
},
{
"code": null,
"e": 29427,
"s": 29422,
"text": "Perl"
},
{
"code": null,
"e": 29525,
"s": 29427,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29534,
"s": 29525,
"text": "Comments"
},
{
"code": null,
"e": 29547,
"s": 29534,
"text": "Old Comments"
},
{
"code": null,
"e": 29571,
"s": 29547,
"text": "Perl | split() Function"
},
{
"code": null,
"e": 29596,
"s": 29571,
"text": "Perl | exists() Function"
},
{
"code": null,
"e": 29620,
"s": 29596,
"text": "Perl | chomp() Function"
},
{
"code": null,
"e": 29643,
"s": 29620,
"text": "Perl | push() Function"
},
{
"code": null,
"e": 29668,
"s": 29643,
"text": "Perl | length() Function"
},
{
"code": null,
"e": 29691,
"s": 29668,
"text": "Perl | grep() Function"
},
{
"code": null,
"e": 29732,
"s": 29691,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 29789,
"s": 29732,
"text": "Perl | Removing leading and trailing white spaces (trim)"
},
{
"code": null,
"e": 29812,
"s": 29789,
"text": "Perl | join() Function"
}
] |
Java switch Keyword
|
❮ Java Keywords
Use the switch statement to calculate the weekday name:
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)
Try it Yourself »
The switch keyword selects one of many code blocks to be executed.
From the example above, it works like this:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The break keyword is used to break out of the switch block when a match is found
Read more about the switch statement in our Java Switch Tutorial.
❮ Java Keywords
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 18,
"s": 0,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 75,
"s": 18,
"text": "Use the switch statement to calculate the weekday name:"
},
{
"code": null,
"e": 529,
"s": 75,
"text": "int day = 4;\nswitch (day) {\n case 1:\n System.out.println(\"Monday\");\n break;\n case 2:\n System.out.println(\"Tuesday\");\n break;\n case 3:\n System.out.println(\"Wednesday\");\n break;\n case 4:\n System.out.println(\"Thursday\");\n break;\n case 5:\n System.out.println(\"Friday\");\n break;\n case 6:\n System.out.println(\"Saturday\");\n break;\n case 7:\n System.out.println(\"Sunday\");\n break;\n}\n// Outputs \"Thursday\" (day 4)\n"
},
{
"code": null,
"e": 549,
"s": 529,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 616,
"s": 549,
"text": "The switch keyword selects one of many code blocks to be executed."
},
{
"code": null,
"e": 660,
"s": 616,
"text": "From the example above, it works like this:"
},
{
"code": null,
"e": 701,
"s": 660,
"text": "The switch expression is evaluated once."
},
{
"code": null,
"e": 771,
"s": 701,
"text": "The value of the expression is compared with the values of each case."
},
{
"code": null,
"e": 834,
"s": 771,
"text": "If there is a match, the associated block of code is executed."
},
{
"code": null,
"e": 915,
"s": 834,
"text": "The break keyword is used to break out of the switch block when a match is found"
},
{
"code": null,
"e": 981,
"s": 915,
"text": "Read more about the switch statement in our Java Switch Tutorial."
},
{
"code": null,
"e": 999,
"s": 981,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 1032,
"s": 999,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1074,
"s": 1032,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1181,
"s": 1074,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1200,
"s": 1181,
"text": "help@w3schools.com"
}
] |
Java Swing | JTextField - GeeksforGeeks
|
03 Dec, 2021
JTextField is a part of javax.swing package. The class JTextField is a component that allows editing of a single line of text. JTextField inherits the JTextComponent class and uses the interface SwingConstants.The constructor of the class are :
JTextField() : constructor that creates a new TextFieldJTextField(int columns) : constructor that creates a new empty TextField with specified number of columns.JTextField(String text) : constructor that creates a new empty text field initialized with the given string.JTextField(String text, int columns) : constructor that creates a new empty textField with the given string and a specified number of columns .JTextField(Document doc, String text, int columns) : constructor that creates a textfield that uses the given text storage model and the given number of columns.
JTextField() : constructor that creates a new TextField
JTextField(int columns) : constructor that creates a new empty TextField with specified number of columns.
JTextField(String text) : constructor that creates a new empty text field initialized with the given string.
JTextField(String text, int columns) : constructor that creates a new empty textField with the given string and a specified number of columns .
JTextField(Document doc, String text, int columns) : constructor that creates a textfield that uses the given text storage model and the given number of columns.
Methods of the JTextField are:
setColumns(int n) :set the number of columns of the text field.setFont(Font f) : set the font of text displayed in text field.addActionListener(ActionListener l) : set an ActionListener to the text field.int getColumns() :get the number of columns in the textfield.
setColumns(int n) :set the number of columns of the text field.
setFont(Font f) : set the font of text displayed in text field.
addActionListener(ActionListener l) : set an ActionListener to the text field.
int getColumns() :get the number of columns in the textfield.
Following are the programs to implement JTextField. 1. Program to create a blank text field of definite number of columns.
Java
// Java program to create a blank text// field of definite number of columns.import java.awt.event.*;import javax.swing.*;class text extends JFrame implements ActionListener { // JTextField static JTextField t; // JFrame static JFrame f; // JButton static JButton b; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame("textfield"); // create a label to display text l = new JLabel("nothing entered"); // create a new button b = new JButton("submit"); // create a object of the text class text te = new text(); // addActionListener to button b.addActionListener(te); // create a object of JTextField with 16 columns t = new JTextField(16); // create a panel to add buttons and textfield JPanel p = new JPanel(); // add buttons and textfield to panel p.add(t); p.add(b); p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("submit")) { // set the text of the label to the text of the field l.setText(t.getText()); // set the text of field to blank t.setText(" "); } }}
output:
2. Program to create a blank text field with a given initial text and given number of columns
Java
// Java program to create a blank text field with a// given initial text and given number of columnsimport java.awt.event.*;import javax.swing.*;class text extends JFrame implements ActionListener { // JTextField static JTextField t; // JFrame static JFrame f; // JButton static JButton b; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame("textfield"); // create a label to display text l = new JLabel("nothing entered"); // create a new button b = new JButton("submit"); // create a object of the text class text te = new text(); // addActionListener to button b.addActionListener(te); // create a object of JTextField with 16 columns and a given initial text t = new JTextField("enter the text", 16); // create a panel to add buttons and textfield JPanel p = new JPanel(); // add buttons and textfield to panel p.add(t); p.add(b); p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("submit")) { // set the text of the label to the text of the field l.setText(t.getText()); // set the text of field to blank t.setText(" "); } }}
output :
3. Program to create a blank text field and set BOLD font type
Java
// Java program to create a blank text field and set BOLD font typeimport java.awt.event.*;import java.awt.*;import javax.swing.*;class text extends JFrame implements ActionListener { // JTextField static JTextField t; // JFrame static JFrame f; // JButton static JButton b; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame("textfield"); // create a label to display text l = new JLabel("nothing entered"); // create a new button b = new JButton("submit"); // create a object of the text class text te = new text(); // addActionListener to button b.addActionListener(te); // create a object of JTextField with 16 columns t = new JTextField(16); // create an object of font type Font fo = new Font("Serif", Font.BOLD, 20); // set the font of the textfield t.setFont(fo); // create a panel to add buttons and textfield JPanel p = new JPanel(); // add buttons and textfield to panel p.add(t); p.add(b); p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("submit")) { // set the text of the label to the text of the field l.setText(t.getText()); // set the text of field to blank t.setText(" "); } }}
output :
Note : The above programs might not run in an online compiler use an offline IDE. The initial text, the font and the number of columns of the textfield are arbitrary and can be changed by the programmer as per their need.
nidhi_biet
Akanksha_Rai
sweetyty
clintra
java-swing
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
|
[
{
"code": null,
"e": 24168,
"s": 24140,
"text": "\n03 Dec, 2021"
},
{
"code": null,
"e": 24415,
"s": 24168,
"text": "JTextField is a part of javax.swing package. The class JTextField is a component that allows editing of a single line of text. JTextField inherits the JTextComponent class and uses the interface SwingConstants.The constructor of the class are : "
},
{
"code": null,
"e": 24989,
"s": 24415,
"text": "JTextField() : constructor that creates a new TextFieldJTextField(int columns) : constructor that creates a new empty TextField with specified number of columns.JTextField(String text) : constructor that creates a new empty text field initialized with the given string.JTextField(String text, int columns) : constructor that creates a new empty textField with the given string and a specified number of columns .JTextField(Document doc, String text, int columns) : constructor that creates a textfield that uses the given text storage model and the given number of columns."
},
{
"code": null,
"e": 25045,
"s": 24989,
"text": "JTextField() : constructor that creates a new TextField"
},
{
"code": null,
"e": 25152,
"s": 25045,
"text": "JTextField(int columns) : constructor that creates a new empty TextField with specified number of columns."
},
{
"code": null,
"e": 25261,
"s": 25152,
"text": "JTextField(String text) : constructor that creates a new empty text field initialized with the given string."
},
{
"code": null,
"e": 25405,
"s": 25261,
"text": "JTextField(String text, int columns) : constructor that creates a new empty textField with the given string and a specified number of columns ."
},
{
"code": null,
"e": 25567,
"s": 25405,
"text": "JTextField(Document doc, String text, int columns) : constructor that creates a textfield that uses the given text storage model and the given number of columns."
},
{
"code": null,
"e": 25599,
"s": 25567,
"text": "Methods of the JTextField are: "
},
{
"code": null,
"e": 25865,
"s": 25599,
"text": "setColumns(int n) :set the number of columns of the text field.setFont(Font f) : set the font of text displayed in text field.addActionListener(ActionListener l) : set an ActionListener to the text field.int getColumns() :get the number of columns in the textfield."
},
{
"code": null,
"e": 25929,
"s": 25865,
"text": "setColumns(int n) :set the number of columns of the text field."
},
{
"code": null,
"e": 25993,
"s": 25929,
"text": "setFont(Font f) : set the font of text displayed in text field."
},
{
"code": null,
"e": 26072,
"s": 25993,
"text": "addActionListener(ActionListener l) : set an ActionListener to the text field."
},
{
"code": null,
"e": 26134,
"s": 26072,
"text": "int getColumns() :get the number of columns in the textfield."
},
{
"code": null,
"e": 26258,
"s": 26134,
"text": "Following are the programs to implement JTextField. 1. Program to create a blank text field of definite number of columns. "
},
{
"code": null,
"e": 26263,
"s": 26258,
"text": "Java"
},
{
"code": "// Java program to create a blank text// field of definite number of columns.import java.awt.event.*;import javax.swing.*;class text extends JFrame implements ActionListener { // JTextField static JTextField t; // JFrame static JFrame f; // JButton static JButton b; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame(\"textfield\"); // create a label to display text l = new JLabel(\"nothing entered\"); // create a new button b = new JButton(\"submit\"); // create a object of the text class text te = new text(); // addActionListener to button b.addActionListener(te); // create a object of JTextField with 16 columns t = new JTextField(16); // create a panel to add buttons and textfield JPanel p = new JPanel(); // add buttons and textfield to panel p.add(t); p.add(b); p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals(\"submit\")) { // set the text of the label to the text of the field l.setText(t.getText()); // set the text of field to blank t.setText(\" \"); } }}",
"e": 27849,
"s": 26263,
"text": null
},
{
"code": null,
"e": 27859,
"s": 27849,
"text": "output: "
},
{
"code": null,
"e": 27956,
"s": 27861,
"text": "2. Program to create a blank text field with a given initial text and given number of columns "
},
{
"code": null,
"e": 27961,
"s": 27956,
"text": "Java"
},
{
"code": "// Java program to create a blank text field with a// given initial text and given number of columnsimport java.awt.event.*;import javax.swing.*;class text extends JFrame implements ActionListener { // JTextField static JTextField t; // JFrame static JFrame f; // JButton static JButton b; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame(\"textfield\"); // create a label to display text l = new JLabel(\"nothing entered\"); // create a new button b = new JButton(\"submit\"); // create a object of the text class text te = new text(); // addActionListener to button b.addActionListener(te); // create a object of JTextField with 16 columns and a given initial text t = new JTextField(\"enter the text\", 16); // create a panel to add buttons and textfield JPanel p = new JPanel(); // add buttons and textfield to panel p.add(t); p.add(b); p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals(\"submit\")) { // set the text of the label to the text of the field l.setText(t.getText()); // set the text of field to blank t.setText(\" \"); } }}",
"e": 29613,
"s": 27961,
"text": null
},
{
"code": null,
"e": 29624,
"s": 29613,
"text": "output : "
},
{
"code": null,
"e": 29690,
"s": 29626,
"text": "3. Program to create a blank text field and set BOLD font type "
},
{
"code": null,
"e": 29695,
"s": 29690,
"text": "Java"
},
{
"code": "// Java program to create a blank text field and set BOLD font typeimport java.awt.event.*;import java.awt.*;import javax.swing.*;class text extends JFrame implements ActionListener { // JTextField static JTextField t; // JFrame static JFrame f; // JButton static JButton b; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame(\"textfield\"); // create a label to display text l = new JLabel(\"nothing entered\"); // create a new button b = new JButton(\"submit\"); // create a object of the text class text te = new text(); // addActionListener to button b.addActionListener(te); // create a object of JTextField with 16 columns t = new JTextField(16); // create an object of font type Font fo = new Font(\"Serif\", Font.BOLD, 20); // set the font of the textfield t.setFont(fo); // create a panel to add buttons and textfield JPanel p = new JPanel(); // add buttons and textfield to panel p.add(t); p.add(b); p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals(\"submit\")) { // set the text of the label to the text of the field l.setText(t.getText()); // set the text of field to blank t.setText(\" \"); } }}",
"e": 31444,
"s": 29695,
"text": null
},
{
"code": null,
"e": 31455,
"s": 31444,
"text": "output : "
},
{
"code": null,
"e": 31681,
"s": 31459,
"text": "Note : The above programs might not run in an online compiler use an offline IDE. The initial text, the font and the number of columns of the textfield are arbitrary and can be changed by the programmer as per their need."
},
{
"code": null,
"e": 31692,
"s": 31681,
"text": "nidhi_biet"
},
{
"code": null,
"e": 31705,
"s": 31692,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31714,
"s": 31705,
"text": "sweetyty"
},
{
"code": null,
"e": 31722,
"s": 31714,
"text": "clintra"
},
{
"code": null,
"e": 31733,
"s": 31722,
"text": "java-swing"
},
{
"code": null,
"e": 31738,
"s": 31733,
"text": "Java"
},
{
"code": null,
"e": 31743,
"s": 31738,
"text": "Java"
},
{
"code": null,
"e": 31841,
"s": 31743,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31850,
"s": 31841,
"text": "Comments"
},
{
"code": null,
"e": 31863,
"s": 31850,
"text": "Old Comments"
},
{
"code": null,
"e": 31914,
"s": 31863,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 31944,
"s": 31914,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31975,
"s": 31944,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 32007,
"s": 31975,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 32026,
"s": 32007,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 32044,
"s": 32026,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 32076,
"s": 32044,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32096,
"s": 32076,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 32120,
"s": 32096,
"text": "Singleton Class in Java"
}
] |
Plot lines from a list of dataframes using ggplot2 in R - GeeksforGeeks
|
05 Nov, 2021
In this article, we will discuss how to plotlines in ggplot from a list of dataframes in the R programming language.
The ggplot2 package is used to visualize and analyze the data. The package can be downloaded and installed using the following command in R :
install.packages("ggplot2")
The ggplot method in R is used to do graph visualizations using the specified data frame. It is used to instantiate a ggplot object. Aesthetic mappings can be created to the plot object to determine the relationship between the x and y axis respectively. Additional components can be added to the created ggplot object.
Syntax: ggplot(data = NULL, mapping = aes(), colour())
Arguments :
data – Default dataset to use for plot.
mapping – List of aesthetic mappings to use for plot.
Geoms can be added to the plot using various methods. The geom_line() method in R can be used to add graphical lines in the plots made. It is added as a component to the existing plot. Aesthetic mappings can also contain color attributes that are assigned differently based on different dataframes. The geom_line() method has the following syntax :
geom_line()
Example 1:
R
# importing required librarieslibrary("dplyr")library("ggplot2") # creating the dataframesdf1 = data.frame(col1=c(1: 10), col2=rnorm(10))df2 = data.frame(col1=c(5: 10), col2=rnorm(6))df3 = data.frame(col1=c(2: 12), col2=rnorm(11)) # creating a list of dataframessamplelist = list(df1, df2, df3)# plotting the datagraph < - ggplot(bind_rows(samplelist, .id="data_frame"), aes(col1, col2, colour=data_frame)) +geom_line() # printing the graphprint(graph)
Output
[1] "First Dataframe"
> print(df1)
col1 col2
1 1 2.6799001
2 2 1.6732359
3 3 -0.2821830
4 4 0.6951255
5 5 0.3629730
6 6 1.6543411
7 7 0.9301622
8 8 0.6858366
9 9 1.3150289
10 10 -0.9306804
> print("Second Dataframe")
[1] "Second Dataframe"
> print(df2)
col1 col2
1 5 -0.1813050
2 6 1.3543525
3 7 0.0810269
4 8 0.1788353
5 9 1.5264921
6 10 0.3677910
> print("Third Dataframe")
[1] "Third Dataframe"
> print(df3)
col1 col2
1 2 -1.0602057
2 3 -0.6040208
3 4 1.9346507
4 5 0.5183120
5 6 0.7176499
6 7 0.2908290
7 8 1.4760342
8 9 0.5935123
9 10 0.3882407
10 11 0.8871490
11 12 -0.3974801
Example 2:
R
# importing required librarieslibrary("dplyr")library("ggplot2") # creating the dataframesdf1 = data.frame(col1=c(1: 10), col2=letters[1:5])df2 = data.frame(col1=c(7: 9), col2=letters[5:7])df3 = data.frame(col1=c(1: 6), col2=rep('e', 6))df4 = data.frame(col1=c(5, 9, 10), col2=c('x', 'm', 'n')) print("First DataFrame")print(df1) print("Second DataFrame")print(df2) print("Third DataFrame")print(df3) print("Fourth DataFrame")print(df4) # creating a list of dataframessamplelist = list(df1, df2, df3, df4) # plotting the datagraph < - ggplot(bind_rows(samplelist, .id="data_frame"), aes(col1, col2, colour=data_frame)) +geom_line() # printing the graphprint(graph)
Output
[1] "First DataFrame"
> print(df1)
col1 col2
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
6 6 a
7 7 b
8 8 c
9 9 d
10 10 e
> print ("Second DataFrame")
[1] "Second DataFrame"
> print(df2)
col1 col2
1 7 e
2 8 f
3 9 g
> print ("Third DataFrame")
[1] "Third DataFrame"
> print(df3)
col1 col2
1 1 e
2 2 e
3 3 e
4 4 e
5 5 e
6 6 e
> print ("Fourth DataFrame")
[1] "Fourth DataFrame"
> print(df4)
col1 col2
1 5 x
2 9 m
3 10 n
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
R - if statement
Time Series Analysis in R
How to filter R dataframe by multiple conditions?
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 26604,
"s": 26487,
"text": "In this article, we will discuss how to plotlines in ggplot from a list of dataframes in the R programming language."
},
{
"code": null,
"e": 26747,
"s": 26604,
"text": "The ggplot2 package is used to visualize and analyze the data. The package can be downloaded and installed using the following command in R : "
},
{
"code": null,
"e": 26775,
"s": 26747,
"text": "install.packages(\"ggplot2\")"
},
{
"code": null,
"e": 27095,
"s": 26775,
"text": "The ggplot method in R is used to do graph visualizations using the specified data frame. It is used to instantiate a ggplot object. Aesthetic mappings can be created to the plot object to determine the relationship between the x and y axis respectively. Additional components can be added to the created ggplot object."
},
{
"code": null,
"e": 27150,
"s": 27095,
"text": "Syntax: ggplot(data = NULL, mapping = aes(), colour())"
},
{
"code": null,
"e": 27162,
"s": 27150,
"text": "Arguments :"
},
{
"code": null,
"e": 27202,
"s": 27162,
"text": "data – Default dataset to use for plot."
},
{
"code": null,
"e": 27256,
"s": 27202,
"text": "mapping – List of aesthetic mappings to use for plot."
},
{
"code": null,
"e": 27606,
"s": 27256,
"text": "Geoms can be added to the plot using various methods. The geom_line() method in R can be used to add graphical lines in the plots made. It is added as a component to the existing plot. Aesthetic mappings can also contain color attributes that are assigned differently based on different dataframes. The geom_line() method has the following syntax : "
},
{
"code": null,
"e": 27618,
"s": 27606,
"text": "geom_line()"
},
{
"code": null,
"e": 27630,
"s": 27618,
"text": "Example 1: "
},
{
"code": null,
"e": 27632,
"s": 27630,
"text": "R"
},
{
"code": "# importing required librarieslibrary(\"dplyr\")library(\"ggplot2\") # creating the dataframesdf1 = data.frame(col1=c(1: 10), col2=rnorm(10))df2 = data.frame(col1=c(5: 10), col2=rnorm(6))df3 = data.frame(col1=c(2: 12), col2=rnorm(11)) # creating a list of dataframessamplelist = list(df1, df2, df3)# plotting the datagraph < - ggplot(bind_rows(samplelist, .id=\"data_frame\"), aes(col1, col2, colour=data_frame)) +geom_line() # printing the graphprint(graph)",
"e": 28107,
"s": 27632,
"text": null
},
{
"code": null,
"e": 28114,
"s": 28107,
"text": "Output"
},
{
"code": null,
"e": 28835,
"s": 28114,
"text": "[1] \"First Dataframe\"\n> print(df1)\n col1 col2\n1 1 2.6799001\n2 2 1.6732359\n3 3 -0.2821830\n4 4 0.6951255\n5 5 0.3629730\n6 6 1.6543411\n7 7 0.9301622\n8 8 0.6858366\n9 9 1.3150289\n10 10 -0.9306804\n> print(\"Second Dataframe\")\n[1] \"Second Dataframe\"\n> print(df2)\n col1 col2\n1 5 -0.1813050\n2 6 1.3543525\n3 7 0.0810269\n4 8 0.1788353\n5 9 1.5264921\n6 10 0.3677910\n> print(\"Third Dataframe\")\n[1] \"Third Dataframe\"\n> print(df3)\n col1 col2\n1 2 -1.0602057\n2 3 -0.6040208\n3 4 1.9346507\n4 5 0.5183120\n5 6 0.7176499\n6 7 0.2908290\n7 8 1.4760342\n8 9 0.5935123\n9 10 0.3882407\n10 11 0.8871490\n11 12 -0.3974801"
},
{
"code": null,
"e": 28846,
"s": 28835,
"text": "Example 2:"
},
{
"code": null,
"e": 28848,
"s": 28846,
"text": "R"
},
{
"code": "# importing required librarieslibrary(\"dplyr\")library(\"ggplot2\") # creating the dataframesdf1 = data.frame(col1=c(1: 10), col2=letters[1:5])df2 = data.frame(col1=c(7: 9), col2=letters[5:7])df3 = data.frame(col1=c(1: 6), col2=rep('e', 6))df4 = data.frame(col1=c(5, 9, 10), col2=c('x', 'm', 'n')) print(\"First DataFrame\")print(df1) print(\"Second DataFrame\")print(df2) print(\"Third DataFrame\")print(df3) print(\"Fourth DataFrame\")print(df4) # creating a list of dataframessamplelist = list(df1, df2, df3, df4) # plotting the datagraph < - ggplot(bind_rows(samplelist, .id=\"data_frame\"), aes(col1, col2, colour=data_frame)) +geom_line() # printing the graphprint(graph)",
"e": 29540,
"s": 28848,
"text": null
},
{
"code": null,
"e": 29547,
"s": 29540,
"text": "Output"
},
{
"code": null,
"e": 30094,
"s": 29547,
"text": "[1] \"First DataFrame\"\n> print(df1)\n col1 col2\n1 1 a\n2 2 b\n3 3 c\n4 4 d\n5 5 e\n6 6 a\n7 7 b\n8 8 c\n9 9 d\n10 10 e\n> print (\"Second DataFrame\")\n[1] \"Second DataFrame\"\n> print(df2)\n col1 col2\n1 7 e\n2 8 f\n3 9 g\n> print (\"Third DataFrame\")\n[1] \"Third DataFrame\"\n> print(df3)\n col1 col2\n1 1 e\n2 2 e\n3 3 e\n4 4 e\n5 5 e\n6 6 e\n> print (\"Fourth DataFrame\")\n[1] \"Fourth DataFrame\"\n> print(df4)\n col1 col2\n1 5 x\n2 9 m\n3 10 n"
},
{
"code": null,
"e": 30101,
"s": 30094,
"text": "Picked"
},
{
"code": null,
"e": 30110,
"s": 30101,
"text": "R-ggplot"
},
{
"code": null,
"e": 30121,
"s": 30110,
"text": "R Language"
},
{
"code": null,
"e": 30219,
"s": 30121,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30271,
"s": 30219,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30306,
"s": 30271,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30344,
"s": 30306,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 30402,
"s": 30344,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30445,
"s": 30402,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30494,
"s": 30445,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30531,
"s": 30494,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 30548,
"s": 30531,
"text": "R - if statement"
},
{
"code": null,
"e": 30574,
"s": 30548,
"text": "Time Series Analysis in R"
}
] |
Python | Numpy np.heaviside() method - GeeksforGeeks
|
02 Dec, 2019
With the help of np.heaviside() method, we can get the heaviside step function by using np.heaviside() method.
Syntax : np.heaviside(array1, array2 or value)Return : Return the heaviside series.
Example #1 :In this example we can see that by using np.heaviside() method, we are able to get the array of series of heaviside step function by using this method.
# import numpyimport numpy as np x = np.array([-1.5, 0.5, 0, 0.5, 1.5])# using np.heaviside() methodgfg = np.heaviside(x, 0.5) print(gfg)
Output :
[0. 1. 0.5 1. 1.]
Example #2 :
# import numpyimport numpy as np x = np.zeros(5)y = np.array([-1.5, 0.5, 0, 0.5, -1.5]) # using np.heaviside() methodgfg = np.heaviside(x, y) print(gfg)
Output :
[-1.5 0.5 0. 0.5 -1.5]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
|
[
{
"code": null,
"e": 25721,
"s": 25693,
"text": "\n02 Dec, 2019"
},
{
"code": null,
"e": 25832,
"s": 25721,
"text": "With the help of np.heaviside() method, we can get the heaviside step function by using np.heaviside() method."
},
{
"code": null,
"e": 25916,
"s": 25832,
"text": "Syntax : np.heaviside(array1, array2 or value)Return : Return the heaviside series."
},
{
"code": null,
"e": 26080,
"s": 25916,
"text": "Example #1 :In this example we can see that by using np.heaviside() method, we are able to get the array of series of heaviside step function by using this method."
},
{
"code": "# import numpyimport numpy as np x = np.array([-1.5, 0.5, 0, 0.5, 1.5])# using np.heaviside() methodgfg = np.heaviside(x, 0.5) print(gfg)",
"e": 26220,
"s": 26080,
"text": null
},
{
"code": null,
"e": 26229,
"s": 26220,
"text": "Output :"
},
{
"code": null,
"e": 26247,
"s": 26229,
"text": "[0. 1. 0.5 1. 1.]"
},
{
"code": null,
"e": 26260,
"s": 26247,
"text": "Example #2 :"
},
{
"code": "# import numpyimport numpy as np x = np.zeros(5)y = np.array([-1.5, 0.5, 0, 0.5, -1.5]) # using np.heaviside() methodgfg = np.heaviside(x, y) print(gfg)",
"e": 26416,
"s": 26260,
"text": null
},
{
"code": null,
"e": 26425,
"s": 26416,
"text": "Output :"
},
{
"code": null,
"e": 26448,
"s": 26425,
"text": "[-1.5 0.5 0. 0.5 -1.5]"
},
{
"code": null,
"e": 26461,
"s": 26448,
"text": "Python-numpy"
},
{
"code": null,
"e": 26468,
"s": 26461,
"text": "Python"
},
{
"code": null,
"e": 26566,
"s": 26468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26584,
"s": 26566,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26616,
"s": 26584,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26638,
"s": 26616,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26680,
"s": 26638,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26706,
"s": 26680,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26735,
"s": 26706,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26772,
"s": 26735,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26808,
"s": 26772,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 26850,
"s": 26808,
"text": "Check if element exists in list in Python"
}
] |
Count elements in a vector that match a target value or condition in C++
|
We are given a vector and the task is to calculate the count of those elements in a vector that matches a target value or condition.
Vectors are sequence containers that can change size. Container is an object that holds data of the same type. Sequence containers store elements strictly in linear sequence.
Vector stores elements in contiguous memory locations and enables direct access to any element using subscript operator []. Unlike arrays, vectors can shrink or expand as needed at run time. The storage of the vector is handled automatically.
To support shrink and expand functionality at runtime, vector containers may allocate some extra storage to accommodate for possible growth thus containers have actual capacity greater than the size. Therefore, compared to array, vector consumes more memory in exchange for the ability to manage storage and grow dynamically in an efficient way.
Input − vector vec = {1, 2, 3, 4, 4, 4, 4}
Target = 4
Output − count is: 4
Explanation − in the given vector the target is occurring 4 times so the count is 4
Input − vector vec = {1, 2, 3}
Target = 4
Output − count is: 0
Explanation − in the given vector the target is occurring 0 times so the count is 0
Input the vector and store it in a vector type variable let’s say vec
Input the vector and store it in a vector type variable let’s say vec
Set the target value as an integer value
Set the target value as an integer value
Take a temporary variable that will store the count
Take a temporary variable that will store the count
Call the inbuilt count function available in C++ STL and pass vec.begin(), vec.end(), target to the function call
Call the inbuilt count function available in C++ STL and pass vec.begin(), vec.end(), target to the function call
Print the result.
Print the result.
Live Demo
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> myvector{ 1, 2, 3, 4, 4, 4, 4, 4 };
int target = 4;
int res = count(myvector.begin(), myvector.end(), target);
cout << "Target is: " << target << "\nCount is: " << res << endl;
return 0;
}
If we run the above code we will get the following output −
Target is: 4
Count is: 5
|
[
{
"code": null,
"e": 1195,
"s": 1062,
"text": "We are given a vector and the task is to calculate the count of those elements in a vector that matches a target value or condition."
},
{
"code": null,
"e": 1370,
"s": 1195,
"text": "Vectors are sequence containers that can change size. Container is an object that holds data of the same type. Sequence containers store elements strictly in linear sequence."
},
{
"code": null,
"e": 1613,
"s": 1370,
"text": "Vector stores elements in contiguous memory locations and enables direct access to any element using subscript operator []. Unlike arrays, vectors can shrink or expand as needed at run time. The storage of the vector is handled automatically."
},
{
"code": null,
"e": 1959,
"s": 1613,
"text": "To support shrink and expand functionality at runtime, vector containers may allocate some extra storage to accommodate for possible growth thus containers have actual capacity greater than the size. Therefore, compared to array, vector consumes more memory in exchange for the ability to manage storage and grow dynamically in an efficient way."
},
{
"code": null,
"e": 2040,
"s": 1959,
"text": "Input − vector vec = {1, 2, 3, 4, 4, 4, 4}\n Target = 4\nOutput − count is: 4"
},
{
"code": null,
"e": 2124,
"s": 2040,
"text": "Explanation − in the given vector the target is occurring 4 times so the count is 4"
},
{
"code": null,
"e": 2193,
"s": 2124,
"text": "Input − vector vec = {1, 2, 3}\n Target = 4\nOutput − count is: 0"
},
{
"code": null,
"e": 2277,
"s": 2193,
"text": "Explanation − in the given vector the target is occurring 0 times so the count is 0"
},
{
"code": null,
"e": 2347,
"s": 2277,
"text": "Input the vector and store it in a vector type variable let’s say vec"
},
{
"code": null,
"e": 2417,
"s": 2347,
"text": "Input the vector and store it in a vector type variable let’s say vec"
},
{
"code": null,
"e": 2458,
"s": 2417,
"text": "Set the target value as an integer value"
},
{
"code": null,
"e": 2499,
"s": 2458,
"text": "Set the target value as an integer value"
},
{
"code": null,
"e": 2551,
"s": 2499,
"text": "Take a temporary variable that will store the count"
},
{
"code": null,
"e": 2603,
"s": 2551,
"text": "Take a temporary variable that will store the count"
},
{
"code": null,
"e": 2717,
"s": 2603,
"text": "Call the inbuilt count function available in C++ STL and pass vec.begin(), vec.end(), target to the function call"
},
{
"code": null,
"e": 2831,
"s": 2717,
"text": "Call the inbuilt count function available in C++ STL and pass vec.begin(), vec.end(), target to the function call"
},
{
"code": null,
"e": 2849,
"s": 2831,
"text": "Print the result."
},
{
"code": null,
"e": 2867,
"s": 2849,
"text": "Print the result."
},
{
"code": null,
"e": 2878,
"s": 2867,
"text": " Live Demo"
},
{
"code": null,
"e": 3186,
"s": 2878,
"text": "#include <algorithm>\n#include <iostream>\n#include <vector>\nusing namespace std;\nint main(){\n vector<int> myvector{ 1, 2, 3, 4, 4, 4, 4, 4 };\n int target = 4;\n int res = count(myvector.begin(), myvector.end(), target);\n cout << \"Target is: \" << target << \"\\nCount is: \" << res << endl;\n return 0;\n}"
},
{
"code": null,
"e": 3246,
"s": 3186,
"text": "If we run the above code we will get the following output −"
},
{
"code": null,
"e": 3271,
"s": 3246,
"text": "Target is: 4\nCount is: 5"
}
] |
Left-Child Right-Sibling Representation of Tree
|
Left-Child Right-Sibling Representation is a different representation of an n-ary tree where instead of maintaining a pointer to each and every child node, a node holds just two pointers, first a pointer to its first child, and the other pointer to its immediate next sibling. This new transformation not only eliminates the need of prior knowledge of the number of children a node has, but also restricts the number of pointers to a maximum of two, so making it so much simpler to code.
At each node, link or connect children of same parent from left to right.
Parent should be linked with only first child.
Left Child Right Sibling tree representation
10
|
2 -> 3 -> 4 -> 5
| |
6 7 -> 8 -> 9
This representation saves up memory by restricting the maximum number of pointers required per node to two.
It is simpler to code.
Basic operations like searching/insertion/deletion consume longer time because in order to select the exact position we would have to traverse through all the siblings of the node to be searched/inserted/deleted (according to the worst case).
|
[
{
"code": null,
"e": 1550,
"s": 1062,
"text": "Left-Child Right-Sibling Representation is a different representation of an n-ary tree where instead of maintaining a pointer to each and every child node, a node holds just two pointers, first a pointer to its first child, and the other pointer to its immediate next sibling. This new transformation not only eliminates the need of prior knowledge of the number of children a node has, but also restricts the number of pointers to a maximum of two, so making it so much simpler to code."
},
{
"code": null,
"e": 1624,
"s": 1550,
"text": "At each node, link or connect children of same parent from left to right."
},
{
"code": null,
"e": 1671,
"s": 1624,
"text": "Parent should be linked with only first child."
},
{
"code": null,
"e": 1716,
"s": 1671,
"text": "Left Child Right Sibling tree representation"
},
{
"code": null,
"e": 1756,
"s": 1716,
"text": "10\n|\n2 -> 3 -> 4 -> 5\n| |\n6 7 -> 8 -> 9"
},
{
"code": null,
"e": 1864,
"s": 1756,
"text": "This representation saves up memory by restricting the maximum number of pointers required per node to two."
},
{
"code": null,
"e": 1887,
"s": 1864,
"text": "It is simpler to code."
},
{
"code": null,
"e": 2130,
"s": 1887,
"text": "Basic operations like searching/insertion/deletion consume longer time because in order to select the exact position we would have to traverse through all the siblings of the node to be searched/inserted/deleted (according to the worst case)."
}
] |
Creating Python Functions for Exploratory Data Analysis and Data Cleaning | by Freda Xin | Towards Data Science
|
Update (2021–02–05): The Python library used in this blog post is now published on PyPi. The package also includes new features: it provides a class that includes methods to streamline the modeling process for Scikit-Learn models. Part II of this blog post is coming up and will cover how to utilize OOP in Python to automate your modeling process.
Exploratory Data Analysis and Data Cleaning are two essential steps before we start to develop Machine Learning Models, and they can be time-consuming, especially for people who are still familiarizing themselves with this whole process.
EDA and Data Cleaning is rarely a one-time, linear process: you might find yourself going back to earlier sections and modifying the way you treat the dataset quite often. One way to speed up this process is to recycle some of the code you find yourself using over and over again. This is why we should create functions to automate the repetitive parts of EDA and Data Cleaning. Another benefit of using functions in the EDA and Data Cleaning is to eliminate the inconsistency of results caused by accidental differences in the code.
In this blog post, I will walk you through a few useful python functions that I created for EDA and Data Cleaning. The library containing all these functions can be cloned from my repository eda_and_beyond. Special thanks to all the people who contributed to this small (but growing) library.
One important step in the EDA is to inspect missing values, study if there are any patterns in the missing values, and make a decision about how to deal with them accordingly.
The first function here is to give you a general idea of the total and percentage of missing data in each column:
def intitial_eda_checks(df): ''' Takes df Checks nulls ''' if df.isnull().sum().sum() > 0: mask_total = df.isnull().sum().sort_values(ascending=False) total = mask_total[mask_total > 0] mask_percent = df.isnull().mean().sort_values(ascending=False) percent = mask_percent[mask_percent > 0] missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent']) print(f'Total and Percentage of NaN:\n {missing_data}') else: print('No NaN found.')
After the initial inspection, you can decide if you want to have a closer inspection on those columns with excessive missing values. With specification of the threshold of the missing value percentage, the following function will give you a list of columns that have missing values over that threshold:
def view_columns_w_many_nans(df, missing_percent): ''' Checks which columns have over specified percentage of missing values Takes df, missing percentage Returns columns as a list ''' mask_percent = df.isnull().mean() series = mask_percent[mask_percent > missing_percent] columns = series.index.to_list() print(columns) return columns
There are many ways to deal with missing values. If you decide to drop the columns with too many missing values (over a certain threshold you specify), you can use this function to accomplish the task:
def drop_columns_w_many_nans(df, missing_percent): ''' Takes df, missing percentage Drops the columns whose missing value is bigger than missing percentage Returns df ''' series = view_columns_w_many_nans(df, missing_percent=missing_percent) list_of_cols = series.index.to_list() df.drop(columns=list_of_cols) print(list_of_cols) return df
However, there are many downsides of deleting missing values from your dataset, such as reduced statistical power. If you decide to impute the missing values instead, check out Sklearn’s SimpleImputer module, which is an easy-to-use tool to impute missing values whichever way strikes your fancy.
In addition, if you’d like to read more about how to deal with missing values, check out this helpful slide created by Melissa Humphries at Population Research Center.
The human brain is very good at identify patterns, and this is why visualizing your dataset during the EDA process and identifying the patterns can be very beneficial. For instance, histograms make analyzing the distribution of the data an easier task; Boxplot is great for identifying outliers; Scatter plot is very useful when it comes to checking the correlations between two variables. Matplotlib and Seaborn are your best friends when it comes to data visualization. However, creating individual plot(s) for each features can become tedious if you have a large number of features. In this section, I will walk you through a few functions for creating group plots that can help you to kill many birds with one function.
We often want to look at the distributions of columns with numerical values. The following function will create a group of plots for all numerical columns in your dataset. (This function is adapted from Dominik Gawlik’s blog post, which is a great read for the entire EDA process with a real dataset):
def histograms_numeric_columns(df, numerical_columns): ''' Takes df, numerical columns as list Returns a group of histagrams ''' f = pd.melt(df, value_vars=numerical_columns) g = sns.FacetGrid(f, col='variable', col_wrap=4, sharex=False, sharey=False) g = g.map(sns.distplot, 'value') return g
Here is what the output looks like:
Another helpful visualization tool is a heatmap. Heatmaps come in very handy when you want to check the correlation between your dependent and independent variables. Oftentimes, heatmaps can be visually cluttered if you have too many features. One way to avoid it is to create a heatmap just for the dependent variable (target) and independent variables (features). The following function will assist you with this task:
def heatmap_numeric_w_dependent_variable(df, dependent_variable): ''' Takes df, a dependant variable as str Returns a heatmap of all independent variables' correlations with dependent variable ''' plt.figure(figsize=(8, 10)) g = sns.heatmap(df.corr()[[dependent_variable]].sort_values(by=dependent_variable), annot=True, cmap='coolwarm', vmin=-1, vmax=1) return g
Ensuring your features are of the correct datatypes is another important step during the EDA and Data Cleaning process. It happens quite often that Pandas’ .read_csv() method would interpret datatypes differently than the original data file. Reading the data dictionary is very illuminating during this step. Additionally, if you are planning to do some feature engineering, changing data types is required. The following two functions work hand in hand to transform categorical features into numerical (ordinal) features:
The first function is to output a function, i.e. a transformer, that will transform each str in a list into a int, where the int is the index of that element in the list.
def categorical_to_ordinal_transformer(categories): ''' Returns a function that will map categories to ordinal values based on the order of the list of `categories` given. Ex. If categories is ['A', 'B', 'C'] then the transformer will map 'A' -> 0, 'B' -> 1, 'C' -> 2. ''' return lambda categorical_value: categories.index(categorical_value)
The second function has two parts: first, it takes a dictionary of the following form:
categorical_numerical_mapping = { 'Utilities': ['ELO', 'NoSeWa', 'NoSewr', 'AllPub'], 'Exter Qual': ['Po', 'Fa', 'TA', 'Gd', 'Ex'], 'Exter Cond': ['Po', 'Fa', 'TA', 'Gd', 'Ex']}
Using the previous function we define earlier, it turns the dictionary into this:
transformers = {'Utilities': <utilties_transformer>, 'Exter Qual': <exter_qual_transformer>, 'Exter Cond': <exter_cond_transfomer>}
The second part of the function uses the .map() method to map each transformer function onto the dataframe. Note that a copy of the original dataframe will be created during this function.
def transform_categorical_to_numercial(df, categorical_numerical_mapping): ''' Transforms categorical columns to numerical columns Takes a df, a dictionary Returns df ''' transformers = {k: categorical_to_ordinal_transformer(v) for k, v in categorical_numerical_mapping.items()} new_df = df.copy() for col, transformer in transformers.items(): new_df[col] = new_df[col].map(transformer).astype('int64') return new_df
This will conclude my blog post. I aim to create an open source library to make the EDA and Data Cleaning process more streamlined. As always, I’d love to hear your feedback. If you have any corrections or want to contribute to this small open source project, please make a pull request. Thank you for reading!
Resources: Check out this awesome (and free!) textbook on Python Programming: Automate the Boring Stuff with Python by Al Sweigart.
Originally published at https://github.com.
|
[
{
"code": null,
"e": 521,
"s": 172,
"text": "Update (2021–02–05): The Python library used in this blog post is now published on PyPi. The package also includes new features: it provides a class that includes methods to streamline the modeling process for Scikit-Learn models. Part II of this blog post is coming up and will cover how to utilize OOP in Python to automate your modeling process."
},
{
"code": null,
"e": 759,
"s": 521,
"text": "Exploratory Data Analysis and Data Cleaning are two essential steps before we start to develop Machine Learning Models, and they can be time-consuming, especially for people who are still familiarizing themselves with this whole process."
},
{
"code": null,
"e": 1293,
"s": 759,
"text": "EDA and Data Cleaning is rarely a one-time, linear process: you might find yourself going back to earlier sections and modifying the way you treat the dataset quite often. One way to speed up this process is to recycle some of the code you find yourself using over and over again. This is why we should create functions to automate the repetitive parts of EDA and Data Cleaning. Another benefit of using functions in the EDA and Data Cleaning is to eliminate the inconsistency of results caused by accidental differences in the code."
},
{
"code": null,
"e": 1586,
"s": 1293,
"text": "In this blog post, I will walk you through a few useful python functions that I created for EDA and Data Cleaning. The library containing all these functions can be cloned from my repository eda_and_beyond. Special thanks to all the people who contributed to this small (but growing) library."
},
{
"code": null,
"e": 1762,
"s": 1586,
"text": "One important step in the EDA is to inspect missing values, study if there are any patterns in the missing values, and make a decision about how to deal with them accordingly."
},
{
"code": null,
"e": 1876,
"s": 1762,
"text": "The first function here is to give you a general idea of the total and percentage of missing data in each column:"
},
{
"code": null,
"e": 2404,
"s": 1876,
"text": "def intitial_eda_checks(df): ''' Takes df Checks nulls ''' if df.isnull().sum().sum() > 0: mask_total = df.isnull().sum().sort_values(ascending=False) total = mask_total[mask_total > 0] mask_percent = df.isnull().mean().sort_values(ascending=False) percent = mask_percent[mask_percent > 0] missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent']) print(f'Total and Percentage of NaN:\\n {missing_data}') else: print('No NaN found.')"
},
{
"code": null,
"e": 2707,
"s": 2404,
"text": "After the initial inspection, you can decide if you want to have a closer inspection on those columns with excessive missing values. With specification of the threshold of the missing value percentage, the following function will give you a list of columns that have missing values over that threshold:"
},
{
"code": null,
"e": 3073,
"s": 2707,
"text": "def view_columns_w_many_nans(df, missing_percent): ''' Checks which columns have over specified percentage of missing values Takes df, missing percentage Returns columns as a list ''' mask_percent = df.isnull().mean() series = mask_percent[mask_percent > missing_percent] columns = series.index.to_list() print(columns) return columns"
},
{
"code": null,
"e": 3275,
"s": 3073,
"text": "There are many ways to deal with missing values. If you decide to drop the columns with too many missing values (over a certain threshold you specify), you can use this function to accomplish the task:"
},
{
"code": null,
"e": 3645,
"s": 3275,
"text": "def drop_columns_w_many_nans(df, missing_percent): ''' Takes df, missing percentage Drops the columns whose missing value is bigger than missing percentage Returns df ''' series = view_columns_w_many_nans(df, missing_percent=missing_percent) list_of_cols = series.index.to_list() df.drop(columns=list_of_cols) print(list_of_cols) return df"
},
{
"code": null,
"e": 3942,
"s": 3645,
"text": "However, there are many downsides of deleting missing values from your dataset, such as reduced statistical power. If you decide to impute the missing values instead, check out Sklearn’s SimpleImputer module, which is an easy-to-use tool to impute missing values whichever way strikes your fancy."
},
{
"code": null,
"e": 4110,
"s": 3942,
"text": "In addition, if you’d like to read more about how to deal with missing values, check out this helpful slide created by Melissa Humphries at Population Research Center."
},
{
"code": null,
"e": 4834,
"s": 4110,
"text": "The human brain is very good at identify patterns, and this is why visualizing your dataset during the EDA process and identifying the patterns can be very beneficial. For instance, histograms make analyzing the distribution of the data an easier task; Boxplot is great for identifying outliers; Scatter plot is very useful when it comes to checking the correlations between two variables. Matplotlib and Seaborn are your best friends when it comes to data visualization. However, creating individual plot(s) for each features can become tedious if you have a large number of features. In this section, I will walk you through a few functions for creating group plots that can help you to kill many birds with one function."
},
{
"code": null,
"e": 5136,
"s": 4834,
"text": "We often want to look at the distributions of columns with numerical values. The following function will create a group of plots for all numerical columns in your dataset. (This function is adapted from Dominik Gawlik’s blog post, which is a great read for the entire EDA process with a real dataset):"
},
{
"code": null,
"e": 5456,
"s": 5136,
"text": "def histograms_numeric_columns(df, numerical_columns): ''' Takes df, numerical columns as list Returns a group of histagrams ''' f = pd.melt(df, value_vars=numerical_columns) g = sns.FacetGrid(f, col='variable', col_wrap=4, sharex=False, sharey=False) g = g.map(sns.distplot, 'value') return g"
},
{
"code": null,
"e": 5492,
"s": 5456,
"text": "Here is what the output looks like:"
},
{
"code": null,
"e": 5913,
"s": 5492,
"text": "Another helpful visualization tool is a heatmap. Heatmaps come in very handy when you want to check the correlation between your dependent and independent variables. Oftentimes, heatmaps can be visually cluttered if you have too many features. One way to avoid it is to create a heatmap just for the dependent variable (target) and independent variables (features). The following function will assist you with this task:"
},
{
"code": null,
"e": 6379,
"s": 5913,
"text": "def heatmap_numeric_w_dependent_variable(df, dependent_variable): ''' Takes df, a dependant variable as str Returns a heatmap of all independent variables' correlations with dependent variable ''' plt.figure(figsize=(8, 10)) g = sns.heatmap(df.corr()[[dependent_variable]].sort_values(by=dependent_variable), annot=True, cmap='coolwarm', vmin=-1, vmax=1) return g"
},
{
"code": null,
"e": 6902,
"s": 6379,
"text": "Ensuring your features are of the correct datatypes is another important step during the EDA and Data Cleaning process. It happens quite often that Pandas’ .read_csv() method would interpret datatypes differently than the original data file. Reading the data dictionary is very illuminating during this step. Additionally, if you are planning to do some feature engineering, changing data types is required. The following two functions work hand in hand to transform categorical features into numerical (ordinal) features:"
},
{
"code": null,
"e": 7073,
"s": 6902,
"text": "The first function is to output a function, i.e. a transformer, that will transform each str in a list into a int, where the int is the index of that element in the list."
},
{
"code": null,
"e": 7437,
"s": 7073,
"text": "def categorical_to_ordinal_transformer(categories): ''' Returns a function that will map categories to ordinal values based on the order of the list of `categories` given. Ex. If categories is ['A', 'B', 'C'] then the transformer will map 'A' -> 0, 'B' -> 1, 'C' -> 2. ''' return lambda categorical_value: categories.index(categorical_value)"
},
{
"code": null,
"e": 7524,
"s": 7437,
"text": "The second function has two parts: first, it takes a dictionary of the following form:"
},
{
"code": null,
"e": 7711,
"s": 7524,
"text": "categorical_numerical_mapping = { 'Utilities': ['ELO', 'NoSeWa', 'NoSewr', 'AllPub'], 'Exter Qual': ['Po', 'Fa', 'TA', 'Gd', 'Ex'], 'Exter Cond': ['Po', 'Fa', 'TA', 'Gd', 'Ex']}"
},
{
"code": null,
"e": 7793,
"s": 7711,
"text": "Using the previous function we define earlier, it turns the dictionary into this:"
},
{
"code": null,
"e": 7955,
"s": 7793,
"text": "transformers = {'Utilities': <utilties_transformer>, 'Exter Qual': <exter_qual_transformer>, 'Exter Cond': <exter_cond_transfomer>}"
},
{
"code": null,
"e": 8144,
"s": 7955,
"text": "The second part of the function uses the .map() method to map each transformer function onto the dataframe. Note that a copy of the original dataframe will be created during this function."
},
{
"code": null,
"e": 8616,
"s": 8144,
"text": "def transform_categorical_to_numercial(df, categorical_numerical_mapping): ''' Transforms categorical columns to numerical columns Takes a df, a dictionary Returns df ''' transformers = {k: categorical_to_ordinal_transformer(v) for k, v in categorical_numerical_mapping.items()} new_df = df.copy() for col, transformer in transformers.items(): new_df[col] = new_df[col].map(transformer).astype('int64') return new_df"
},
{
"code": null,
"e": 8927,
"s": 8616,
"text": "This will conclude my blog post. I aim to create an open source library to make the EDA and Data Cleaning process more streamlined. As always, I’d love to hear your feedback. If you have any corrections or want to contribute to this small open source project, please make a pull request. Thank you for reading!"
},
{
"code": null,
"e": 9059,
"s": 8927,
"text": "Resources: Check out this awesome (and free!) textbook on Python Programming: Automate the Boring Stuff with Python by Al Sweigart."
}
] |
How to check if a list element is greater than a certain value in R?
|
If we have a list that contains numeric elements and we want to check whether the elements are greater than a certain value then as.numeric function can be used. The output of the function will be in 0/1 format where 0 represents FALSE and 1 represents TRUE. For example, if we have a list called LIST then to check whether elements in LIST are greater than 2 can be done as as.numeric(LIST>2).
Live Demo
List1<−list(1,2,2,2,4,1,2,5,5,2,3,5,2,2,2,2,5,5,8,9,6,5,5)
List1
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 2
[[4]]
[1] 2
[[5]]
[1] 4
[[6]]
[1] 1
[[7]]
[1] 2
[[8]]
[1] 5
[[9]]
[1] 5
[[10]]
[1] 2
[[11]]
[1] 3
[[12]]
[1] 5
[[13]]
[1] 2
[[14]]
[1] 2
[[15]]
[1] 2
[[16]]
[1] 2
[[17]]
[1] 5
[[18]]
[1] 5
[[19]]
[1] 8
[[20]]
[1] 9
[[21]]
[1] 6
[[22]]
[1] 5
[[23]]
[1] 5
Checking whether elements in List1 are greater than 5 or not −
as.numeric(List1>5)
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0
Live Demo
List2<−list(4,7,5,4,1,2,5,2,3,6,5,7,7,1,1,2,5,5,9,2)
List2
[[1]]
[1] 4
[[2]]
[1] 7
[[3]]
[1] 5
[[4]]
[1] 4
[[5]]
[1] 1
[[6]]
[1] 2
[[7]]
[1] 5
[[8]]
[1] 2
[[9]]
[1] 3
[[10]]
[1] 6
[[11]]
[1] 5
[[12]]
[1] 7
[[13]]
[1] 7
[[14]]
[1] 1
[[15]]
[1] 1
[[16]]
[1] 2
[[17]]
[1] 5
[[18]]
[1] 5
[[19]]
[1] 9
[[20]]
[1] 2
Checking whether elements in List2 are greater than 2 or not −
as.numeric(List2>2)
[1] 1 1 1 1 0 0 1 0 1 1 1 1 1 0 0 0 1 1 1 0
|
[
{
"code": null,
"e": 1457,
"s": 1062,
"text": "If we have a list that contains numeric elements and we want to check whether the elements are greater than a certain value then as.numeric function can be used. The output of the function will be in 0/1 format where 0 represents FALSE and 1 represents TRUE. For example, if we have a list called LIST then to check whether elements in LIST are greater than 2 can be done as as.numeric(LIST>2)."
},
{
"code": null,
"e": 1468,
"s": 1457,
"text": " Live Demo"
},
{
"code": null,
"e": 1533,
"s": 1468,
"text": "List1<−list(1,2,2,2,4,1,2,5,5,2,3,5,2,2,2,2,5,5,8,9,6,5,5)\nList1"
},
{
"code": null,
"e": 1823,
"s": 1533,
"text": "[[1]]\n[1] 1\n[[2]]\n[1] 2\n[[3]]\n[1] 2\n[[4]]\n[1] 2\n[[5]]\n[1] 4\n[[6]]\n[1] 1\n[[7]]\n[1] 2\n[[8]]\n[1] 5\n[[9]]\n[1] 5\n[[10]]\n[1] 2\n[[11]]\n[1] 3\n[[12]]\n[1] 5\n[[13]]\n[1] 2\n[[14]]\n[1] 2\n[[15]]\n[1] 2\n[[16]]\n[1] 2\n[[17]]\n[1] 5\n[[18]]\n[1] 5\n[[19]]\n[1] 8\n[[20]]\n[1] 9\n[[21]]\n[1] 6\n[[22]]\n[1] 5\n[[23]]\n[1] 5"
},
{
"code": null,
"e": 1886,
"s": 1823,
"text": "Checking whether elements in List1 are greater than 5 or not −"
},
{
"code": null,
"e": 1906,
"s": 1886,
"text": "as.numeric(List1>5)"
},
{
"code": null,
"e": 1956,
"s": 1906,
"text": "[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0"
},
{
"code": null,
"e": 1967,
"s": 1956,
"text": " Live Demo"
},
{
"code": null,
"e": 2026,
"s": 1967,
"text": "List2<−list(4,7,5,4,1,2,5,2,3,6,5,7,7,1,1,2,5,5,9,2)\nList2"
},
{
"code": null,
"e": 2277,
"s": 2026,
"text": "[[1]]\n[1] 4\n[[2]]\n[1] 7\n[[3]]\n[1] 5\n[[4]]\n[1] 4\n[[5]]\n[1] 1\n[[6]]\n[1] 2\n[[7]]\n[1] 5\n[[8]]\n[1] 2\n[[9]]\n[1] 3\n[[10]]\n[1] 6\n[[11]]\n[1] 5\n[[12]]\n[1] 7\n[[13]]\n[1] 7\n[[14]]\n[1] 1\n[[15]]\n[1] 1\n[[16]]\n[1] 2\n[[17]]\n[1] 5\n[[18]]\n[1] 5\n[[19]]\n[1] 9\n[[20]]\n[1] 2"
},
{
"code": null,
"e": 2340,
"s": 2277,
"text": "Checking whether elements in List2 are greater than 2 or not −"
},
{
"code": null,
"e": 2360,
"s": 2340,
"text": "as.numeric(List2>2)"
},
{
"code": null,
"e": 2404,
"s": 2360,
"text": "[1] 1 1 1 1 0 0 1 0 1 1 1 1 1 0 0 0 1 1 1 0"
}
] |
How to Create a New Ext4 File System in Linux?
|
The hard disk in a computer is formatted with specific file system so that the operating system can read and write into it. For UNIX based systems we have various type of file systems. In this article we will see how to format a new partition in hard disk with ext4 file system.
First we see what are the different file systems available for the current operating system. The below command lists all those file systems.
$ ls -1 /sbin/mkfs*
Running the above code gives us the following result −
/sbin/mkfs
/sbin/mkfs.bfs
/sbin/mkfs.cramfs
/sbin/mkfs.ext2
/sbin/mkfs.ext3
/sbin/mkfs.ext4
/sbin/mkfs.ext4dev
/sbin/mkfs.fat
/sbin/mkfs.minix
/sbin/mkfs.msdos
/sbin/mkfs.ntfs
/sbin/mkfs.vfat
Next let's look at the the current hard disk and their partitions available to the operating system. Based on this output we can decide to add a new hard disk or create a new partition in the existing desk and format it as ext4.
$ sudo fdisk -l
[sudo] password for ubuntu:
Running the above code gives us the following result −
Disk /dev/sda: 20 GiB, 21474836480 bytes, 41943040 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x06807e05
Device Boot Start End Sectors Size Id Type
/dev/sda1 * 2048 33554431 33552384 16G 83 Linux
/dev/sda2 33556478 41940991 8384514 4G 5 Extended
/dev/sda5 33556480 41940991 8384512 4G 82 Linux swap / Solaris
Using the same command but choosing a different argument as shown below. We see all the available formats that the OS can support and available for formatting.
$ sudo fdisk /dev/sda
Command (m for help): l
Running the above code gives us the following result −
0 Empty 24 NEC DOS 81 Minix / old Lin bf Solaris
1 FAT12 27 Hidden NTFS Win 82 Linux swap / So c1 DRDOS/sec (FAT-
2 XENIX root 39 Plan 9 83 Linux c4 DRDOS/sec (FAT-
3 XENIX usr 3c PartitionMagic 84 OS/2 hidden or c6 DRDOS/sec (FAT-
4 FAT16 <32M 40 Venix 80286 85 Linux extended c7 Syrinx
5 Extended 41 PPC PReP Boot 86 NTFS volume set da Non-FS data
6 FAT16 42 SFS 87 NTFS volume set db CP/M / CTOS / .
7 HPFS/NTFS/exFAT 4d QNX4.x 88 Linux plaintext de Dell Utility
8 AIX 4e QNX4.x 2nd part 8e Linux LVM df BootIt
9 AIX bootable 4f QNX4.x 3rd part 93 Amoeba e1 DOS access
a OS/2 Boot Manag 50 OnTrack DM 94 Amoeba BBT e3 DOS R/O
b W95 FAT32 51 OnTrack DM6 Aux 9f BSD/OS e4 SpeedStor
c W95 FAT32 (LBA) 52 CP/M a0 IBM Thinkpad hi ea Rufus alignment
e W95 FAT16 (LBA) 53 OnTrack DM6 Aux a5 FreeBSD eb BeOS fs
f W95 Ext'd (LBA) 54 OnTrackDM6 a6 OpenBSD ee GPT
10 OPUS 55 EZ-Drive a7 NeXTSTEP ef EFI (FAT-12/16/
11 Hidden FAT12 56 Golden Bow a8 Darwin UFS f0 Linux/PA-RISC b
12 Compaq diagnost 5c Priam Edisk a9 NetBSD f1 SpeedStor
14 Hidden FAT16 <3 61 SpeedStor ab Darwin boot f4 SpeedStor
16 Hidden FAT16 63 GNU HURD or Sys af HFS / HFS+ f2 DOS secondary
17 Hidden HPFS/NTF 64 Novell Netware b7 BSDI fs fb VMware VMFS
18 AST SmartSleep 65 Novell Netware b8 BSDI swap fc VMware VMKCORE
1b Hidden W95 FAT3 70 DiskSecure Mult bb Boot Wizard hid fd Linux raid auto
1c Hidden W95 FAT3 75 PC/IX bc Acronis FAT32 L fe LANstep
1e Hidden W95 FAT1 80 Old Minix be Solaris boot ff BBT
Next we choose the n option to create a new partition.
Command (m for help): n
Command action
l logical (5 or over)
p primary partition (1-4)
First sector (39849982-41940991, default 39849982):
Using default value 39849982
Last sector, +sectors or +stze(K,M,G} (39849982-41940991, default 4
1940991):
Using default value 41940991
Now we issue the below command to make the sda5 partiton as a ext4 partition.
sudo mkfs.ext4 /dev/sda5
|
[
{
"code": null,
"e": 1341,
"s": 1062,
"text": "The hard disk in a computer is formatted with specific file system so that the operating system can read and write into it. For UNIX based systems we have various type of file systems. In this article we will see how to format a new partition in hard disk with ext4 file system."
},
{
"code": null,
"e": 1482,
"s": 1341,
"text": "First we see what are the different file systems available for the current operating system. The below command lists all those file systems."
},
{
"code": null,
"e": 1502,
"s": 1482,
"text": "$ ls -1 /sbin/mkfs*"
},
{
"code": null,
"e": 1557,
"s": 1502,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1749,
"s": 1557,
"text": "/sbin/mkfs\n/sbin/mkfs.bfs\n/sbin/mkfs.cramfs\n/sbin/mkfs.ext2\n/sbin/mkfs.ext3\n/sbin/mkfs.ext4\n/sbin/mkfs.ext4dev\n/sbin/mkfs.fat\n/sbin/mkfs.minix\n/sbin/mkfs.msdos\n/sbin/mkfs.ntfs\n/sbin/mkfs.vfat"
},
{
"code": null,
"e": 1978,
"s": 1749,
"text": "Next let's look at the the current hard disk and their partitions available to the operating system. Based on this output we can decide to add a new hard disk or create a new partition in the existing desk and format it as ext4."
},
{
"code": null,
"e": 2022,
"s": 1978,
"text": "$ sudo fdisk -l\n[sudo] password for ubuntu:"
},
{
"code": null,
"e": 2077,
"s": 2022,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2613,
"s": 2077,
"text": "Disk /dev/sda: 20 GiB, 21474836480 bytes, 41943040 sectors\nUnits: sectors of 1 * 512 = 512 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\nDisklabel type: dos\nDisk identifier: 0x06807e05\n\nDevice Boot Start End Sectors Size Id Type\n/dev/sda1 * 2048 33554431 33552384 16G 83 Linux\n/dev/sda2 33556478 41940991 8384514 4G 5 Extended\n/dev/sda5 33556480 41940991 8384512 4G 82 Linux swap / Solaris"
},
{
"code": null,
"e": 2773,
"s": 2613,
"text": "Using the same command but choosing a different argument as shown below. We see all the available formats that the OS can support and available for formatting."
},
{
"code": null,
"e": 2819,
"s": 2773,
"text": "$ sudo fdisk /dev/sda\nCommand (m for help): l"
},
{
"code": null,
"e": 2874,
"s": 2819,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 5224,
"s": 2874,
"text": "0 Empty 24 NEC DOS 81 Minix / old Lin bf Solaris\n1 FAT12 27 Hidden NTFS Win 82 Linux swap / So c1 DRDOS/sec (FAT-\n2 XENIX root 39 Plan 9 83 Linux c4 DRDOS/sec (FAT-\n3 XENIX usr 3c PartitionMagic 84 OS/2 hidden or c6 DRDOS/sec (FAT-\n4 FAT16 <32M 40 Venix 80286 85 Linux extended c7 Syrinx\n5 Extended 41 PPC PReP Boot 86 NTFS volume set da Non-FS data\n6 FAT16 42 SFS 87 NTFS volume set db CP/M / CTOS / .\n7 HPFS/NTFS/exFAT 4d QNX4.x 88 Linux plaintext de Dell Utility\n8 AIX 4e QNX4.x 2nd part 8e Linux LVM df BootIt\n9 AIX bootable 4f QNX4.x 3rd part 93 Amoeba e1 DOS access\na OS/2 Boot Manag 50 OnTrack DM 94 Amoeba BBT e3 DOS R/O\nb W95 FAT32 51 OnTrack DM6 Aux 9f BSD/OS e4 SpeedStor\nc W95 FAT32 (LBA) 52 CP/M a0 IBM Thinkpad hi ea Rufus alignment\ne W95 FAT16 (LBA) 53 OnTrack DM6 Aux a5 FreeBSD eb BeOS fs\nf W95 Ext'd (LBA) 54 OnTrackDM6 a6 OpenBSD ee GPT\n10 OPUS 55 EZ-Drive a7 NeXTSTEP ef EFI (FAT-12/16/\n11 Hidden FAT12 56 Golden Bow a8 Darwin UFS f0 Linux/PA-RISC b\n12 Compaq diagnost 5c Priam Edisk a9 NetBSD f1 SpeedStor\n14 Hidden FAT16 <3 61 SpeedStor ab Darwin boot f4 SpeedStor\n16 Hidden FAT16 63 GNU HURD or Sys af HFS / HFS+ f2 DOS secondary\n17 Hidden HPFS/NTF 64 Novell Netware b7 BSDI fs fb VMware VMFS\n18 AST SmartSleep 65 Novell Netware b8 BSDI swap fc VMware VMKCORE\n1b Hidden W95 FAT3 70 DiskSecure Mult bb Boot Wizard hid fd Linux raid auto\n1c Hidden W95 FAT3 75 PC/IX bc Acronis FAT32 L fe LANstep\n1e Hidden W95 FAT1 80 Old Minix be Solaris boot ff BBT"
},
{
"code": null,
"e": 5279,
"s": 5224,
"text": "Next we choose the n option to create a new partition."
},
{
"code": null,
"e": 5560,
"s": 5279,
"text": "Command (m for help): n\nCommand action\n l logical (5 or over)\n p primary partition (1-4)\nFirst sector (39849982-41940991, default 39849982):\nUsing default value 39849982\nLast sector, +sectors or +stze(K,M,G} (39849982-41940991, default 4\n1940991):\nUsing default value 41940991"
},
{
"code": null,
"e": 5638,
"s": 5560,
"text": "Now we issue the below command to make the sda5 partiton as a ext4 partition."
},
{
"code": null,
"e": 5663,
"s": 5638,
"text": "sudo mkfs.ext4 /dev/sda5"
}
] |
How to use chrome webdriver in Selenium to download files in Python?
|
We can use chrome webdriver in Selenium to download files in Python. We shall use the ChromeOptions class for this purpose. First, we shall create an object of the ChromeOptions class.
Then apply the add_experimental_option method on the object created. We shall set the download.default_directory:<location of downloaded file> parameter. Finally, this information shall be passed to the driver object.
op = webdriver.ChromeOptions()
p = {'download.default_directory':'C:\\Users\\ghs6kor\\Downloads\\Test'}
op.add_experimental_option('prefs', p)
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#object of Options class
op = webdriver.ChromeOptions()
#browser preferences
p = {'download.default_directory':'C:\\Users\\ghs6kor\\Downloads\\Test'}
#add options to browser
op.add_experimental_option('prefs', p)
#set chromedriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe",
options=op)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.seleniumhq.org/download/");
#click download link
l = driver.find_element_by_link_text("32 bit Windows IE")
l.click()
Also, the file gets downloaded at the desired location.
|
[
{
"code": null,
"e": 1247,
"s": 1062,
"text": "We can use chrome webdriver in Selenium to download files in Python. We shall use the ChromeOptions class for this purpose. First, we shall create an object of the ChromeOptions class."
},
{
"code": null,
"e": 1465,
"s": 1247,
"text": "Then apply the add_experimental_option method on the object created. We shall set the download.default_directory:<location of downloaded file> parameter. Finally, this information shall be passed to the driver object."
},
{
"code": null,
"e": 1608,
"s": 1465,
"text": "op = webdriver.ChromeOptions()\np = {'download.default_directory':'C:\\\\Users\\\\ghs6kor\\\\Downloads\\\\Test'}\nop.add_experimental_option('prefs', p)"
},
{
"code": null,
"e": 2207,
"s": 1608,
"text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n#object of Options class\nop = webdriver.ChromeOptions()\n#browser preferences\np = {'download.default_directory':'C:\\\\Users\\\\ghs6kor\\\\Downloads\\\\Test'}\n#add options to browser\nop.add_experimental_option('prefs', p)\n#set chromedriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\",\noptions=op)\n#maximize browser\ndriver.maximize_window()\n#launch URL\ndriver.get(\"https://www.seleniumhq.org/download/\");\n#click download link\nl = driver.find_element_by_link_text(\"32 bit Windows IE\")\nl.click()"
},
{
"code": null,
"e": 2263,
"s": 2207,
"text": "Also, the file gets downloaded at the desired location."
}
] |
How to preselect a value in a dropdown list of items in HTML forms?
|
With HTML, you can easily create a simple drop down list of items to get user input in HTML forms. A select box also called drop down box provides an option to list down various options in the form of drop down list.
You can also preselect a value in dropdown list of items in HTML forms. For that, add selected in the <option> tag for the value you want to preselect.
You can try to run the following code to learn how to preselect value in a dropdown list of items works in HTML form −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Select Box Control</title>
</head>
<body>
<p> Select any one:</p>
<form>
<select name = "dropdown">
<option value = "Java" selected>Java</option>
<option value = "Discrete Mathematics">Discrete Mathematics</option>
</select>
</form>
</body>
</html>
|
[
{
"code": null,
"e": 1279,
"s": 1062,
"text": "With HTML, you can easily create a simple drop down list of items to get user input in HTML forms. A select box also called drop down box provides an option to list down various options in the form of drop down list."
},
{
"code": null,
"e": 1431,
"s": 1279,
"text": "You can also preselect a value in dropdown list of items in HTML forms. For that, add selected in the <option> tag for the value you want to preselect."
},
{
"code": null,
"e": 1550,
"s": 1431,
"text": "You can try to run the following code to learn how to preselect value in a dropdown list of items works in HTML form −"
},
{
"code": null,
"e": 1560,
"s": 1550,
"text": "Live Demo"
},
{
"code": null,
"e": 1924,
"s": 1560,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Select Box Control</title>\n </head>\n <body>\n <p> Select any one:</p>\n <form>\n <select name = \"dropdown\">\n <option value = \"Java\" selected>Java</option>\n <option value = \"Discrete Mathematics\">Discrete Mathematics</option>\n </select>\n </form>\n </body>\n</html>"
}
] |
How to use z-index in svg elements ?
|
14 Jul, 2020
The z-index only works on the complete content. This is because the HTML rendered controls the positioning before handing off to the SVG rendered to place the internal SVG contents. So, basically there is no z-index for SVG, it uses the painters model.
Painter’s model: According to this model, paint is applied in successive operations onto some area of the output device, covering up the paint from the earlier operations. This is because, after each object is painted, it becomes part of the background for the next painting operation. To summarize, according to this model, the order in which the element is painted or displayed is defined by the order in which the element appears in the document. So, to change the z-index of the element, it can be done in the following ways.
Manually change the order of the element in the SVG document:Example:<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 30 220 420"> <g> <g id="one"> <circle fill="green" cx="100" cy="85" r="20" /> </g> <g id="two"> <circle fill="grey" cx="100" cy="115" r="20" /> </g> <g id="three"> <circle fill="green" cx="100" cy="145" r="20" /> </g> </g></svg>Output:Now, our aim is to increase the z-index of the “grey” element. As discussed, according to the painter’s model, for the element to have the highest z-index, it should be placed as the latest object to be drawn. So to increase the z-index of the “grey” circle, we will just change the position of the “grey” circle element to the last.Example:<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 30 220 420"> <g> <g id="one"> <circle fill="green" cx="100" cy="85" r="20" /> </g> <g id="three"> <circle fill="green" cx="100" cy="145" r="20" /> </g> <g id="two"> <circle fill="grey" cx="100" cy="115" r="20" /> </g> </g></svg>Output:Using use: The use element takes elements from the SVG document and duplicates them at the place where you place it. So, basically instead of changing the order of the element in the document, we are duplicating the element to keep up the uniformity.Example:<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 30 220 420"> <g> <g id="one"> <rect x="30" y="70" width="80" height="80" fill="green"></rect> </g> <g id="two"> <rect x="60" y="110" width="80" height="80" fill="grey"></rect> </g> <g id="three"> <rect x="90" y="150" width="80" height="80" fill="black"></rect> </g> </g> </svg>Output:To increase the z-index of the “green” element, we will use the use feature.<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 30 220 420"> <g> <g id="one"> <rect x="30" y="70" width="80" height="80" fill="green"></rect> </g> <g id="two"> <rect x="60" y="110" width="80" height="80" fill="grey"></rect> </g> <g id="three"> <rect x="90" y="150" width="80" height="80" fill="black"></rect> </g> </g> <use xlink:href="#one" /></svg>Output:My Personal Notes
arrow_drop_upSave
Manually change the order of the element in the SVG document:Example:<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 30 220 420"> <g> <g id="one"> <circle fill="green" cx="100" cy="85" r="20" /> </g> <g id="two"> <circle fill="grey" cx="100" cy="115" r="20" /> </g> <g id="three"> <circle fill="green" cx="100" cy="145" r="20" /> </g> </g></svg>Output:Now, our aim is to increase the z-index of the “grey” element. As discussed, according to the painter’s model, for the element to have the highest z-index, it should be placed as the latest object to be drawn. So to increase the z-index of the “grey” circle, we will just change the position of the “grey” circle element to the last.Example:<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 30 220 420"> <g> <g id="one"> <circle fill="green" cx="100" cy="85" r="20" /> </g> <g id="three"> <circle fill="green" cx="100" cy="145" r="20" /> </g> <g id="two"> <circle fill="grey" cx="100" cy="115" r="20" /> </g> </g></svg>Output:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 30 220 420"> <g> <g id="one"> <circle fill="green" cx="100" cy="85" r="20" /> </g> <g id="two"> <circle fill="grey" cx="100" cy="115" r="20" /> </g> <g id="three"> <circle fill="green" cx="100" cy="145" r="20" /> </g> </g></svg>
Output:
Now, our aim is to increase the z-index of the “grey” element. As discussed, according to the painter’s model, for the element to have the highest z-index, it should be placed as the latest object to be drawn. So to increase the z-index of the “grey” circle, we will just change the position of the “grey” circle element to the last.
Example:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 30 220 420"> <g> <g id="one"> <circle fill="green" cx="100" cy="85" r="20" /> </g> <g id="three"> <circle fill="green" cx="100" cy="145" r="20" /> </g> <g id="two"> <circle fill="grey" cx="100" cy="115" r="20" /> </g> </g></svg>
Output:
Using use: The use element takes elements from the SVG document and duplicates them at the place where you place it. So, basically instead of changing the order of the element in the document, we are duplicating the element to keep up the uniformity.Example:<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 30 220 420"> <g> <g id="one"> <rect x="30" y="70" width="80" height="80" fill="green"></rect> </g> <g id="two"> <rect x="60" y="110" width="80" height="80" fill="grey"></rect> </g> <g id="three"> <rect x="90" y="150" width="80" height="80" fill="black"></rect> </g> </g> </svg>Output:To increase the z-index of the “green” element, we will use the use feature.<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 30 220 420"> <g> <g id="one"> <rect x="30" y="70" width="80" height="80" fill="green"></rect> </g> <g id="two"> <rect x="60" y="110" width="80" height="80" fill="grey"></rect> </g> <g id="three"> <rect x="90" y="150" width="80" height="80" fill="black"></rect> </g> </g> <use xlink:href="#one" /></svg>Output:My Personal Notes
arrow_drop_upSave
Example:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 30 220 420"> <g> <g id="one"> <rect x="30" y="70" width="80" height="80" fill="green"></rect> </g> <g id="two"> <rect x="60" y="110" width="80" height="80" fill="grey"></rect> </g> <g id="three"> <rect x="90" y="150" width="80" height="80" fill="black"></rect> </g> </g> </svg>
Output:
To increase the z-index of the “green” element, we will use the use feature.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 30 220 420"> <g> <g id="one"> <rect x="30" y="70" width="80" height="80" fill="green"></rect> </g> <g id="two"> <rect x="60" y="110" width="80" height="80" fill="grey"></rect> </g> <g id="three"> <rect x="90" y="150" width="80" height="80" fill="black"></rect> </g> </g> <use xlink:href="#one" /></svg>
Output:
HTML-Misc
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 281,
"s": 28,
"text": "The z-index only works on the complete content. This is because the HTML rendered controls the positioning before handing off to the SVG rendered to place the internal SVG contents. So, basically there is no z-index for SVG, it uses the painters model."
},
{
"code": null,
"e": 811,
"s": 281,
"text": "Painter’s model: According to this model, paint is applied in successive operations onto some area of the output device, covering up the paint from the earlier operations. This is because, after each object is painted, it becomes part of the background for the next painting operation. To summarize, according to this model, the order in which the element is painted or displayed is defined by the order in which the element appears in the document. So, to change the z-index of the element, it can be done in the following ways."
},
{
"code": null,
"e": 3442,
"s": 811,
"text": "Manually change the order of the element in the SVG document:Example:<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"10 30 220 420\"> <g> <g id=\"one\"> <circle fill=\"green\" cx=\"100\" cy=\"85\" r=\"20\" /> </g> <g id=\"two\"> <circle fill=\"grey\" cx=\"100\" cy=\"115\" r=\"20\" /> </g> <g id=\"three\"> <circle fill=\"green\" cx=\"100\" cy=\"145\" r=\"20\" /> </g> </g></svg>Output:Now, our aim is to increase the z-index of the “grey” element. As discussed, according to the painter’s model, for the element to have the highest z-index, it should be placed as the latest object to be drawn. So to increase the z-index of the “grey” circle, we will just change the position of the “grey” circle element to the last.Example:<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"10 30 220 420\"> <g> <g id=\"one\"> <circle fill=\"green\" cx=\"100\" cy=\"85\" r=\"20\" /> </g> <g id=\"three\"> <circle fill=\"green\" cx=\"100\" cy=\"145\" r=\"20\" /> </g> <g id=\"two\"> <circle fill=\"grey\" cx=\"100\" cy=\"115\" r=\"20\" /> </g> </g></svg>Output:Using use: The use element takes elements from the SVG document and duplicates them at the place where you place it. So, basically instead of changing the order of the element in the document, we are duplicating the element to keep up the uniformity.Example:<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"10 30 220 420\"> <g> <g id=\"one\"> <rect x=\"30\" y=\"70\" width=\"80\" height=\"80\" fill=\"green\"></rect> </g> <g id=\"two\"> <rect x=\"60\" y=\"110\" width=\"80\" height=\"80\" fill=\"grey\"></rect> </g> <g id=\"three\"> <rect x=\"90\" y=\"150\" width=\"80\" height=\"80\" fill=\"black\"></rect> </g> </g> </svg>Output:To increase the z-index of the “green” element, we will use the use feature.<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"10 30 220 420\"> <g> <g id=\"one\"> <rect x=\"30\" y=\"70\" width=\"80\" height=\"80\" fill=\"green\"></rect> </g> <g id=\"two\"> <rect x=\"60\" y=\"110\" width=\"80\" height=\"80\" fill=\"grey\"></rect> </g> <g id=\"three\"> <rect x=\"90\" y=\"150\" width=\"80\" height=\"80\" fill=\"black\"></rect> </g> </g> <use xlink:href=\"#one\" /></svg>Output:My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 4729,
"s": 3442,
"text": "Manually change the order of the element in the SVG document:Example:<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"10 30 220 420\"> <g> <g id=\"one\"> <circle fill=\"green\" cx=\"100\" cy=\"85\" r=\"20\" /> </g> <g id=\"two\"> <circle fill=\"grey\" cx=\"100\" cy=\"115\" r=\"20\" /> </g> <g id=\"three\"> <circle fill=\"green\" cx=\"100\" cy=\"145\" r=\"20\" /> </g> </g></svg>Output:Now, our aim is to increase the z-index of the “grey” element. As discussed, according to the painter’s model, for the element to have the highest z-index, it should be placed as the latest object to be drawn. So to increase the z-index of the “grey” circle, we will just change the position of the “grey” circle element to the last.Example:<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"10 30 220 420\"> <g> <g id=\"one\"> <circle fill=\"green\" cx=\"100\" cy=\"85\" r=\"20\" /> </g> <g id=\"three\"> <circle fill=\"green\" cx=\"100\" cy=\"145\" r=\"20\" /> </g> <g id=\"two\"> <circle fill=\"grey\" cx=\"100\" cy=\"115\" r=\"20\" /> </g> </g></svg>Output:"
},
{
"code": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"10 30 220 420\"> <g> <g id=\"one\"> <circle fill=\"green\" cx=\"100\" cy=\"85\" r=\"20\" /> </g> <g id=\"two\"> <circle fill=\"grey\" cx=\"100\" cy=\"115\" r=\"20\" /> </g> <g id=\"three\"> <circle fill=\"green\" cx=\"100\" cy=\"145\" r=\"20\" /> </g> </g></svg>",
"e": 5161,
"s": 4729,
"text": null
},
{
"code": null,
"e": 5169,
"s": 5161,
"text": "Output:"
},
{
"code": null,
"e": 5503,
"s": 5169,
"text": "Now, our aim is to increase the z-index of the “grey” element. As discussed, according to the painter’s model, for the element to have the highest z-index, it should be placed as the latest object to be drawn. So to increase the z-index of the “grey” circle, we will just change the position of the “grey” circle element to the last."
},
{
"code": null,
"e": 5512,
"s": 5503,
"text": "Example:"
},
{
"code": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"10 30 220 420\"> <g> <g id=\"one\"> <circle fill=\"green\" cx=\"100\" cy=\"85\" r=\"20\" /> </g> <g id=\"three\"> <circle fill=\"green\" cx=\"100\" cy=\"145\" r=\"20\" /> </g> <g id=\"two\"> <circle fill=\"grey\" cx=\"100\" cy=\"115\" r=\"20\" /> </g> </g></svg>",
"e": 5944,
"s": 5512,
"text": null
},
{
"code": null,
"e": 5952,
"s": 5944,
"text": "Output:"
},
{
"code": null,
"e": 7297,
"s": 5952,
"text": "Using use: The use element takes elements from the SVG document and duplicates them at the place where you place it. So, basically instead of changing the order of the element in the document, we are duplicating the element to keep up the uniformity.Example:<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"10 30 220 420\"> <g> <g id=\"one\"> <rect x=\"30\" y=\"70\" width=\"80\" height=\"80\" fill=\"green\"></rect> </g> <g id=\"two\"> <rect x=\"60\" y=\"110\" width=\"80\" height=\"80\" fill=\"grey\"></rect> </g> <g id=\"three\"> <rect x=\"90\" y=\"150\" width=\"80\" height=\"80\" fill=\"black\"></rect> </g> </g> </svg>Output:To increase the z-index of the “green” element, we will use the use feature.<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"10 30 220 420\"> <g> <g id=\"one\"> <rect x=\"30\" y=\"70\" width=\"80\" height=\"80\" fill=\"green\"></rect> </g> <g id=\"two\"> <rect x=\"60\" y=\"110\" width=\"80\" height=\"80\" fill=\"grey\"></rect> </g> <g id=\"three\"> <rect x=\"90\" y=\"150\" width=\"80\" height=\"80\" fill=\"black\"></rect> </g> </g> <use xlink:href=\"#one\" /></svg>Output:My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 7306,
"s": 7297,
"text": "Example:"
},
{
"code": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"10 30 220 420\"> <g> <g id=\"one\"> <rect x=\"30\" y=\"70\" width=\"80\" height=\"80\" fill=\"green\"></rect> </g> <g id=\"two\"> <rect x=\"60\" y=\"110\" width=\"80\" height=\"80\" fill=\"grey\"></rect> </g> <g id=\"three\"> <rect x=\"90\" y=\"150\" width=\"80\" height=\"80\" fill=\"black\"></rect> </g> </g> </svg>",
"e": 7774,
"s": 7306,
"text": null
},
{
"code": null,
"e": 7782,
"s": 7774,
"text": "Output:"
},
{
"code": null,
"e": 7859,
"s": 7782,
"text": "To increase the z-index of the “green” element, we will use the use feature."
},
{
"code": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"10 30 220 420\"> <g> <g id=\"one\"> <rect x=\"30\" y=\"70\" width=\"80\" height=\"80\" fill=\"green\"></rect> </g> <g id=\"two\"> <rect x=\"60\" y=\"110\" width=\"80\" height=\"80\" fill=\"grey\"></rect> </g> <g id=\"three\"> <rect x=\"90\" y=\"150\" width=\"80\" height=\"80\" fill=\"black\"></rect> </g> </g> <use xlink:href=\"#one\" /></svg>",
"e": 8354,
"s": 7859,
"text": null
},
{
"code": null,
"e": 8362,
"s": 8354,
"text": "Output:"
},
{
"code": null,
"e": 8372,
"s": 8362,
"text": "HTML-Misc"
},
{
"code": null,
"e": 8379,
"s": 8372,
"text": "Picked"
},
{
"code": null,
"e": 8384,
"s": 8379,
"text": "HTML"
},
{
"code": null,
"e": 8401,
"s": 8384,
"text": "Web Technologies"
},
{
"code": null,
"e": 8406,
"s": 8401,
"text": "HTML"
}
] |
How to compress images using Python and PIL?
|
18 Aug, 2020
There are organizations who receive data form lakhs or more persons, which is mostly in form of text, with a few images. Most of you know that the text part is stored in databases in the form of tables, but what about the images? The images are small compared to the textual data but constitute a much higher space in terms of storage. Hence, to save on the part of space and keep running the processes smoothly, they ask the users to submit the compressed images. As most of the readers have a bit of CS background(either in school or college), they understand that using online free tools to compress images is not a good practice for them.
Till Windows 7, Microsoft used to give MS Office Picture Manager which could be used to compress images till an extent, but it also had some limitations.
Those who know a bit of python can install python and use pip install pillow in command prompt(terminal for Linux users) to install pillow fork.
You’ll get a screen like this
Assemble all the files in a folder and keep the file Compress.py in the same folder.
Run the python file with python.
Below is the Source Code of the file:
Python3
# run this in any directory # add -v for verbose # get Pillow (fork of PIL) from# pip before running --># pip install Pillow # import required librariesimport osimport sysfrom PIL import Image # define a function for# compressing an imagedef compressMe(file, verbose = False): # Get the path of the file filepath = os.path.join(os.getcwd(), file) # open the image picture = Image.open(filepath) # Save the picture with desired quality # To change the quality of image, # set the quality variable at # your desired level, The more # the value of quality variable # and lesser the compression picture.save("Compressed_"+file, "JPEG", optimize = True, quality = 10) return # Define a main functiondef main(): verbose = False # checks for verbose flag if (len(sys.argv)>1): if (sys.argv[1].lower()=="-v"): verbose = True # finds current working dir cwd = os.getcwd() formats = ('.jpg', '.jpeg') # looping through all the files # in a current directory for file in os.listdir(cwd): # If the file format is JPG or JPEG if os.path.splitext(file)[1].lower() in formats: print('compressing', file) compressMe(file, verbose) print("Done") # Driver codeif __name__ == "__main__": main()
Folder before running file
PS: Please run code after getting into the directory.
Command Line for executing Code
Folder after running code
You can clearly see the compressed file.
Image-Processing
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 671,
"s": 28,
"text": "There are organizations who receive data form lakhs or more persons, which is mostly in form of text, with a few images. Most of you know that the text part is stored in databases in the form of tables, but what about the images? The images are small compared to the textual data but constitute a much higher space in terms of storage. Hence, to save on the part of space and keep running the processes smoothly, they ask the users to submit the compressed images. As most of the readers have a bit of CS background(either in school or college), they understand that using online free tools to compress images is not a good practice for them."
},
{
"code": null,
"e": 825,
"s": 671,
"text": "Till Windows 7, Microsoft used to give MS Office Picture Manager which could be used to compress images till an extent, but it also had some limitations."
},
{
"code": null,
"e": 970,
"s": 825,
"text": "Those who know a bit of python can install python and use pip install pillow in command prompt(terminal for Linux users) to install pillow fork."
},
{
"code": null,
"e": 1001,
"s": 970,
"text": "You’ll get a screen like this "
},
{
"code": null,
"e": 1086,
"s": 1001,
"text": "Assemble all the files in a folder and keep the file Compress.py in the same folder."
},
{
"code": null,
"e": 1119,
"s": 1086,
"text": "Run the python file with python."
},
{
"code": null,
"e": 1157,
"s": 1119,
"text": "Below is the Source Code of the file:"
},
{
"code": null,
"e": 1165,
"s": 1157,
"text": "Python3"
},
{
"code": "# run this in any directory # add -v for verbose # get Pillow (fork of PIL) from# pip before running --># pip install Pillow # import required librariesimport osimport sysfrom PIL import Image # define a function for# compressing an imagedef compressMe(file, verbose = False): # Get the path of the file filepath = os.path.join(os.getcwd(), file) # open the image picture = Image.open(filepath) # Save the picture with desired quality # To change the quality of image, # set the quality variable at # your desired level, The more # the value of quality variable # and lesser the compression picture.save(\"Compressed_\"+file, \"JPEG\", optimize = True, quality = 10) return # Define a main functiondef main(): verbose = False # checks for verbose flag if (len(sys.argv)>1): if (sys.argv[1].lower()==\"-v\"): verbose = True # finds current working dir cwd = os.getcwd() formats = ('.jpg', '.jpeg') # looping through all the files # in a current directory for file in os.listdir(cwd): # If the file format is JPG or JPEG if os.path.splitext(file)[1].lower() in formats: print('compressing', file) compressMe(file, verbose) print(\"Done\") # Driver codeif __name__ == \"__main__\": main()",
"e": 2625,
"s": 1165,
"text": null
},
{
"code": null,
"e": 2652,
"s": 2625,
"text": "Folder before running file"
},
{
"code": null,
"e": 2706,
"s": 2652,
"text": "PS: Please run code after getting into the directory."
},
{
"code": null,
"e": 2738,
"s": 2706,
"text": "Command Line for executing Code"
},
{
"code": null,
"e": 2764,
"s": 2738,
"text": "Folder after running code"
},
{
"code": null,
"e": 2805,
"s": 2764,
"text": "You can clearly see the compressed file."
},
{
"code": null,
"e": 2822,
"s": 2805,
"text": "Image-Processing"
},
{
"code": null,
"e": 2833,
"s": 2822,
"text": "Python-pil"
},
{
"code": null,
"e": 2840,
"s": 2833,
"text": "Python"
}
] |
CSS | element element Selector
|
31 Dec, 2018
The element element selector in CSS is used to select elements inside the elements i.e it combines two selectors such that elements matched by the second selector are selected if they have an ancestor element matching the first selector.
Syntax:
element element {
// CSS Property
}
Example 1:
<!-- HTML code to illustrates space selector --><!DOCTYPE html><html> <head> <title> element element Selector </title> <style> div p { background-color: green; color: white; } </style> </head> <body style="text-align: center;"> <h1 style = "color: green;"> GeeksforGeeks </h1> <div> <h2>element element Selector</h2> <!-- CSS property is used here --> <p>A computer science portal for geeks.</p> </div> <p>This paragraph will not be selected.</p> </body></html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <title> element element Selector </title> <style> li { color: black; } li li { color: white; background: green; } </style> </head> <body style="text-align: center;"> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2>element element Selector</h2> <ul> <li> <div>Searching Algo</div> <ul> <li>Binary Search</li> <li>Linear Search</li> </ul> </li> <li> <div>Sorting Algo</div> <ul> <li>Bubble Sort</li> <li>Merge Sort</li> </ul> </li> </ul> </body></html>
Output:
Supported Browsers: The browser supported by element element selector are listed below:
Apple Safari
Google Chrome
Firefox
Opera
Internet Explorer
CSS-Selectors
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Dec, 2018"
},
{
"code": null,
"e": 266,
"s": 28,
"text": "The element element selector in CSS is used to select elements inside the elements i.e it combines two selectors such that elements matched by the second selector are selected if they have an ancestor element matching the first selector."
},
{
"code": null,
"e": 274,
"s": 266,
"text": "Syntax:"
},
{
"code": null,
"e": 315,
"s": 274,
"text": "element element {\n // CSS Property\n}\n"
},
{
"code": null,
"e": 326,
"s": 315,
"text": "Example 1:"
},
{
"code": "<!-- HTML code to illustrates space selector --><!DOCTYPE html><html> <head> <title> element element Selector </title> <style> div p { background-color: green; color: white; } </style> </head> <body style=\"text-align: center;\"> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <div> <h2>element element Selector</h2> <!-- CSS property is used here --> <p>A computer science portal for geeks.</p> </div> <p>This paragraph will not be selected.</p> </body></html> ",
"e": 1050,
"s": 326,
"text": null
},
{
"code": null,
"e": 1058,
"s": 1050,
"text": "Output:"
},
{
"code": null,
"e": 1069,
"s": 1058,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> element element Selector </title> <style> li { color: black; } li li { color: white; background: green; } </style> </head> <body style=\"text-align: center;\"> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2>element element Selector</h2> <ul> <li> <div>Searching Algo</div> <ul> <li>Binary Search</li> <li>Linear Search</li> </ul> </li> <li> <div>Sorting Algo</div> <ul> <li>Bubble Sort</li> <li>Merge Sort</li> </ul> </li> </ul> </body></html> ",
"e": 2015,
"s": 1069,
"text": null
},
{
"code": null,
"e": 2023,
"s": 2015,
"text": "Output:"
},
{
"code": null,
"e": 2111,
"s": 2023,
"text": "Supported Browsers: The browser supported by element element selector are listed below:"
},
{
"code": null,
"e": 2124,
"s": 2111,
"text": "Apple Safari"
},
{
"code": null,
"e": 2138,
"s": 2124,
"text": "Google Chrome"
},
{
"code": null,
"e": 2146,
"s": 2138,
"text": "Firefox"
},
{
"code": null,
"e": 2152,
"s": 2146,
"text": "Opera"
},
{
"code": null,
"e": 2170,
"s": 2152,
"text": "Internet Explorer"
},
{
"code": null,
"e": 2184,
"s": 2170,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 2188,
"s": 2184,
"text": "CSS"
},
{
"code": null,
"e": 2205,
"s": 2188,
"text": "Web Technologies"
},
{
"code": null,
"e": 2303,
"s": 2205,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2351,
"s": 2303,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2413,
"s": 2351,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2463,
"s": 2413,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2521,
"s": 2463,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 2571,
"s": 2521,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 2604,
"s": 2571,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2666,
"s": 2604,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2727,
"s": 2666,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2777,
"s": 2727,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Shared Element Transition in Android with Example
|
27 May, 2021
Shared Element Transition is one of the most seen animations in Android apps. This type of animation is used when we have to open an item from a ListView or RecyclerView. Shared Element Transition in Android determines how shared element views are animated from activity to activity or fragment to fragment. Now we will see the implementation of Shared Element Transition in our app with a simple example.
In this example, we will create a simple app where we will create two activities with ImageView and implement transition animation between these two activities. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Create a New Empty Activity
Navigate to the app > java > your package name > right-click > New > Activity > Empty Activity and name the activity as MainActivity2.
Step 3: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Transition name is a simple string that will be given to two views between which we are applying transition--> <!--Transition name should be same for both the views in which we are making transition--> <ImageView android:id="@+id/image" android:layout_width="180dp" android:layout_height="100dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="120dp" android:contentDescription="@string/image_desc" android:scaleType="centerCrop" android:src="@drawable/gfgimage" android:transitionName="fade" /> </RelativeLayout>
Step 4: Working with the activity_main2.xml file
Go to the activity_main2.xml file and refer to the following code. Below is the code for the activity_main2.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity2"> <!--Transition name is same as that we have used in previous imageview--> <ImageView android:layout_width="match_parent" android:layout_height="250dp" android:layout_alignParentTop="true" android:contentDescription="@string/image_desc" android:scaleType="centerCrop" android:src="@drawable/gfgimage" android:transitionName="fade" /> </RelativeLayout>
Step 5: Working with the MainActivity2.java file
Go to the MainActivity2.java file and refer to the following code. Below is the code for the MainActivity2.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Build;import android.os.Bundle;import android.transition.Fade;import android.view.View; import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity; public class MainActivity2 extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); // here we are initializing // fade animation. Fade fade = new Fade(); View decor = getWindow().getDecorView(); // here also we are excluding status bar, // action bar and navigation bar from animation. fade.excludeTarget(decor.findViewById(R.id.action_bar_container), true); fade.excludeTarget(android.R.id.statusBarBackground, true); fade.excludeTarget(android.R.id.navigationBarBackground, true); // below methods are used for adding // enter and exit transition. getWindow().setEnterTransition(fade); getWindow().setExitTransition(fade); }}
Step 6: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Intent;import android.os.Build;import android.os.Bundle;import android.transition.Fade;import android.view.View;import android.widget.ImageView; import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityOptionsCompat;import androidx.core.view.ViewCompat; public class MainActivity extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // we are adding fade animation // between two imageviews. Fade fade = new Fade(); View decor = getWindow().getDecorView(); // below 3 lines of code is to exclude // action bar,title bar and navigation // bar from animation. fade.excludeTarget(decor.findViewById(R.id.action_bar_container), true); fade.excludeTarget(android.R.id.statusBarBackground, true); fade.excludeTarget(android.R.id.navigationBarBackground, true); // we are adding fade animation // for enter transition. getWindow().setEnterTransition(fade); // we are also setting fade // animation for exit transition. getWindow().setExitTransition(fade); // initializing our imageview. final ImageView imageView = findViewById(R.id.image); // setting on click listener for our imageview. imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on image click we are opening new activity // and adding animation between this two activities. Intent intent = new Intent(MainActivity.this, MainActivity2.class); // below method is used to make scene transition // and adding fade animation in it. ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation( MainActivity.this, imageView, ViewCompat.getTransitionName(imageView)); // starting our activity with below method. startActivity(intent, options.toBundle()); } }); }}
Check out the app’s code: https://github.com/ChaitanyaMunje/GFGImageSlider/tree/SharedElementTransition
adnanirshad158
Android-Animation
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 435,
"s": 28,
"text": "Shared Element Transition is one of the most seen animations in Android apps. This type of animation is used when we have to open an item from a ListView or RecyclerView. Shared Element Transition in Android determines how shared element views are animated from activity to activity or fragment to fragment. Now we will see the implementation of Shared Element Transition in our app with a simple example. "
},
{
"code": null,
"e": 761,
"s": 435,
"text": "In this example, we will create a simple app where we will create two activities with ImageView and implement transition animation between these two activities. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 790,
"s": 761,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 952,
"s": 790,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 988,
"s": 952,
"text": "Step 2: Create a New Empty Activity"
},
{
"code": null,
"e": 1123,
"s": 988,
"text": "Navigate to the app > java > your package name > right-click > New > Activity > Empty Activity and name the activity as MainActivity2."
},
{
"code": null,
"e": 1171,
"s": 1123,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1287,
"s": 1171,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 1291,
"s": 1287,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Transition name is a simple string that will be given to two views between which we are applying transition--> <!--Transition name should be same for both the views in which we are making transition--> <ImageView android:id=\"@+id/image\" android:layout_width=\"180dp\" android:layout_height=\"100dp\" android:layout_alignParentBottom=\"true\" android:layout_centerHorizontal=\"true\" android:layout_marginBottom=\"120dp\" android:contentDescription=\"@string/image_desc\" android:scaleType=\"centerCrop\" android:src=\"@drawable/gfgimage\" android:transitionName=\"fade\" /> </RelativeLayout>",
"e": 2271,
"s": 1291,
"text": null
},
{
"code": null,
"e": 2324,
"s": 2275,
"text": "Step 4: Working with the activity_main2.xml file"
},
{
"code": null,
"e": 2444,
"s": 2326,
"text": "Go to the activity_main2.xml file and refer to the following code. Below is the code for the activity_main2.xml file."
},
{
"code": null,
"e": 2450,
"s": 2446,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity2\"> <!--Transition name is same as that we have used in previous imageview--> <ImageView android:layout_width=\"match_parent\" android:layout_height=\"250dp\" android:layout_alignParentTop=\"true\" android:contentDescription=\"@string/image_desc\" android:scaleType=\"centerCrop\" android:src=\"@drawable/gfgimage\" android:transitionName=\"fade\" /> </RelativeLayout>",
"e": 3156,
"s": 2450,
"text": null
},
{
"code": null,
"e": 3209,
"s": 3160,
"text": "Step 5: Working with the MainActivity2.java file"
},
{
"code": null,
"e": 3403,
"s": 3211,
"text": "Go to the MainActivity2.java file and refer to the following code. Below is the code for the MainActivity2.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 3410,
"s": 3405,
"text": "Java"
},
{
"code": "import android.os.Build;import android.os.Bundle;import android.transition.Fade;import android.view.View; import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity; public class MainActivity2 extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); // here we are initializing // fade animation. Fade fade = new Fade(); View decor = getWindow().getDecorView(); // here also we are excluding status bar, // action bar and navigation bar from animation. fade.excludeTarget(decor.findViewById(R.id.action_bar_container), true); fade.excludeTarget(android.R.id.statusBarBackground, true); fade.excludeTarget(android.R.id.navigationBarBackground, true); // below methods are used for adding // enter and exit transition. getWindow().setEnterTransition(fade); getWindow().setExitTransition(fade); }}",
"e": 4538,
"s": 3410,
"text": null
},
{
"code": null,
"e": 4590,
"s": 4542,
"text": "Step 6: Working with the MainActivity.java file"
},
{
"code": null,
"e": 4782,
"s": 4592,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 4789,
"s": 4784,
"text": "Java"
},
{
"code": "import android.content.Intent;import android.os.Build;import android.os.Bundle;import android.transition.Fade;import android.view.View;import android.widget.ImageView; import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;import androidx.core.app.ActivityOptionsCompat;import androidx.core.view.ViewCompat; public class MainActivity extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // we are adding fade animation // between two imageviews. Fade fade = new Fade(); View decor = getWindow().getDecorView(); // below 3 lines of code is to exclude // action bar,title bar and navigation // bar from animation. fade.excludeTarget(decor.findViewById(R.id.action_bar_container), true); fade.excludeTarget(android.R.id.statusBarBackground, true); fade.excludeTarget(android.R.id.navigationBarBackground, true); // we are adding fade animation // for enter transition. getWindow().setEnterTransition(fade); // we are also setting fade // animation for exit transition. getWindow().setExitTransition(fade); // initializing our imageview. final ImageView imageView = findViewById(R.id.image); // setting on click listener for our imageview. imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on image click we are opening new activity // and adding animation between this two activities. Intent intent = new Intent(MainActivity.this, MainActivity2.class); // below method is used to make scene transition // and adding fade animation in it. ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation( MainActivity.this, imageView, ViewCompat.getTransitionName(imageView)); // starting our activity with below method. startActivity(intent, options.toBundle()); } }); }}",
"e": 7110,
"s": 4789,
"text": null
},
{
"code": null,
"e": 7219,
"s": 7115,
"text": "Check out the app’s code: https://github.com/ChaitanyaMunje/GFGImageSlider/tree/SharedElementTransition"
},
{
"code": null,
"e": 7236,
"s": 7221,
"text": "adnanirshad158"
},
{
"code": null,
"e": 7254,
"s": 7236,
"text": "Android-Animation"
},
{
"code": null,
"e": 7278,
"s": 7254,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 7286,
"s": 7278,
"text": "Android"
},
{
"code": null,
"e": 7291,
"s": 7286,
"text": "Java"
},
{
"code": null,
"e": 7310,
"s": 7291,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7315,
"s": 7310,
"text": "Java"
},
{
"code": null,
"e": 7323,
"s": 7315,
"text": "Android"
}
] |
Python | Convert string List to Nested Character List
|
29 Nov, 2019
Sometimes, while working with Python, we can have a problem in which we need to perform interconversion of data. In this article we discuss converting String list to Nested Character list split by comma. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + split()The combination of above functionalities can be used to perform this task. In this, we iterate through list using list comprehension and can perform split using split().
# Python3 code to demonstrate working of# Convert String List to Nested Character List# using split() + list comprehension # initialize list test_list = ["a, b, c", "gfg, is, best", "1, 2, 3"] # printing original list print("The original list : " + str(test_list)) # Convert String List to Nested Character List# using split() + list comprehensionres = [char.split(', ') for char in test_list] # printing resultprint("List after performing conversion : " + str(res))
The original list : [‘a, b, c’, ‘gfg, is, best’, ‘1, 2, 3’]List after performing conversion : [[‘a’, ‘b’, ‘c’], [‘gfg’, ‘is’, ‘best’], [‘1’, ‘2’, ‘3’]]
Method #2 : Using map() + split() + lambdaThe combination of above functions can be used to perform this task. In this, we perform the task of iteration using map() and lambda function is used to apply the logic of split using split() to all the list elements.
# Python3 code to demonstrate working of# Convert String List to Nested Character List# using map() + split() + lambda # initialize list test_list = ["a, b, c", "gfg, is, best", "1, 2, 3"] # printing original list print("The original list : " + str(test_list)) # Convert String List to Nested Character List# using map() + split() + lambdares = list(map(lambda ele: ele.split(', '), test_list)) # printing resultprint("List after performing conversion : " + str(res))
The original list : [‘a, b, c’, ‘gfg, is, best’, ‘1, 2, 3’]List after performing conversion : [[‘a’, ‘b’, ‘c’], [‘gfg’, ‘is’, ‘best’], [‘1’, ‘2’, ‘3’]]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2019"
},
{
"code": null,
"e": 296,
"s": 28,
"text": "Sometimes, while working with Python, we can have a problem in which we need to perform interconversion of data. In this article we discuss converting String list to Nested Character list split by comma. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 512,
"s": 296,
"text": "Method #1 : Using list comprehension + split()The combination of above functionalities can be used to perform this task. In this, we iterate through list using list comprehension and can perform split using split()."
},
{
"code": "# Python3 code to demonstrate working of# Convert String List to Nested Character List# using split() + list comprehension # initialize list test_list = [\"a, b, c\", \"gfg, is, best\", \"1, 2, 3\"] # printing original list print(\"The original list : \" + str(test_list)) # Convert String List to Nested Character List# using split() + list comprehensionres = [char.split(', ') for char in test_list] # printing resultprint(\"List after performing conversion : \" + str(res))",
"e": 983,
"s": 512,
"text": null
},
{
"code": null,
"e": 1135,
"s": 983,
"text": "The original list : [‘a, b, c’, ‘gfg, is, best’, ‘1, 2, 3’]List after performing conversion : [[‘a’, ‘b’, ‘c’], [‘gfg’, ‘is’, ‘best’], [‘1’, ‘2’, ‘3’]]"
},
{
"code": null,
"e": 1398,
"s": 1137,
"text": "Method #2 : Using map() + split() + lambdaThe combination of above functions can be used to perform this task. In this, we perform the task of iteration using map() and lambda function is used to apply the logic of split using split() to all the list elements."
},
{
"code": "# Python3 code to demonstrate working of# Convert String List to Nested Character List# using map() + split() + lambda # initialize list test_list = [\"a, b, c\", \"gfg, is, best\", \"1, 2, 3\"] # printing original list print(\"The original list : \" + str(test_list)) # Convert String List to Nested Character List# using map() + split() + lambdares = list(map(lambda ele: ele.split(', '), test_list)) # printing resultprint(\"List after performing conversion : \" + str(res))",
"e": 1870,
"s": 1398,
"text": null
},
{
"code": null,
"e": 2022,
"s": 1870,
"text": "The original list : [‘a, b, c’, ‘gfg, is, best’, ‘1, 2, 3’]List after performing conversion : [[‘a’, ‘b’, ‘c’], [‘gfg’, ‘is’, ‘best’], [‘1’, ‘2’, ‘3’]]"
},
{
"code": null,
"e": 2043,
"s": 2022,
"text": "Python list-programs"
},
{
"code": null,
"e": 2050,
"s": 2043,
"text": "Python"
},
{
"code": null,
"e": 2066,
"s": 2050,
"text": "Python Programs"
}
] |
Str() and StrComp() Function in MS Access
|
31 Aug, 2020
1. Str() Function :In MS Access, the Str() function return a number in the string format. In this function, we can pass any number the function will return that in the string format.
Syntax :
Str(number)
Example –
SELECT Str(100) AS ConvertToString;
Output –
Example –
SELECT Str(421) AS ConvertToString;
Output –
2. StrComp() Function :In MS Access, The StrComp() function compare two strings . It will take two parameter string1, string2 as the parameter. If both strings will be same then it will return 0, and if the first string is greater than second then it will return 1 if string1<string2 then it returns -1 and if string1 or string2 is null then it will return null.
Syntax :
StrComp(string1, string2)
Example –
SELECT StrComp("geeksforgeeks", "gfg") AS CompString;
Output –
Example –
SELECT StrComp("gfg", "geeksforgeeks") AS CompString;
Output :
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Aug, 2020"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "1. Str() Function :In MS Access, the Str() function return a number in the string format. In this function, we can pass any number the function will return that in the string format."
},
{
"code": null,
"e": 220,
"s": 211,
"text": "Syntax :"
},
{
"code": null,
"e": 234,
"s": 220,
"text": " Str(number) "
},
{
"code": null,
"e": 244,
"s": 234,
"text": "Example –"
},
{
"code": null,
"e": 280,
"s": 244,
"text": "SELECT Str(100) AS ConvertToString;"
},
{
"code": null,
"e": 289,
"s": 280,
"text": "Output –"
},
{
"code": null,
"e": 299,
"s": 289,
"text": "Example –"
},
{
"code": null,
"e": 335,
"s": 299,
"text": "SELECT Str(421) AS ConvertToString;"
},
{
"code": null,
"e": 344,
"s": 335,
"text": "Output –"
},
{
"code": null,
"e": 707,
"s": 344,
"text": "2. StrComp() Function :In MS Access, The StrComp() function compare two strings . It will take two parameter string1, string2 as the parameter. If both strings will be same then it will return 0, and if the first string is greater than second then it will return 1 if string1<string2 then it returns -1 and if string1 or string2 is null then it will return null."
},
{
"code": null,
"e": 716,
"s": 707,
"text": "Syntax :"
},
{
"code": null,
"e": 743,
"s": 716,
"text": "StrComp(string1, string2) "
},
{
"code": null,
"e": 753,
"s": 743,
"text": "Example –"
},
{
"code": null,
"e": 807,
"s": 753,
"text": "SELECT StrComp(\"geeksforgeeks\", \"gfg\") AS CompString;"
},
{
"code": null,
"e": 816,
"s": 807,
"text": "Output –"
},
{
"code": null,
"e": 826,
"s": 816,
"text": "Example –"
},
{
"code": null,
"e": 880,
"s": 826,
"text": "SELECT StrComp(\"gfg\", \"geeksforgeeks\") AS CompString;"
},
{
"code": null,
"e": 889,
"s": 880,
"text": "Output :"
},
{
"code": null,
"e": 898,
"s": 889,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 902,
"s": 898,
"text": "SQL"
},
{
"code": null,
"e": 906,
"s": 902,
"text": "SQL"
}
] |
Java String indexOf()
|
07 Sep, 2021
There are four variants of indexOf() method. This article depicts about all of them, as follows: 1.int indexOf() : This method returns the index within this string of the first occurrence of the specified character or -1, if the character does not occur.
Syntax:
int indexOf(char ch )
Parameters:
ch : a character.
Java
// Java code to demonstrate the working// of String indexOf()public class Index1 {public static void main(String args[]) { // Initialising String String gfg = new String("Welcome to geeksforgeeks"); System.out.print("Found g first at position : "); // Initial index of 'g' will print // prints 11 System.out.println(gfg.indexOf('g')); }}
Found g first at position : 11
2. int indexOf(char ch, int strt ) : This method returns the index within this string of the first occurrence of the specified character, starting the search at the specified index or -1, if the character does not occur.
Syntax:
int indexOf(char ch, int strt)
Parameters:
ch :a character.
strt : the index to start the search from.
Java
// Java code to demonstrate the working// of String indexOf(char ch, int strt)public class Index2 {public static void main(String args[]) { // Initialising String String gfg = new String("Welcome to geeksforgeeks"); System.out.print("Found g after 13th index at position : "); // 2nd index of 'g' will print // prints 19 System.out.println(gfg.indexOf('g', 13)); }}
Found g after 13th index at position : 19
3.int indexOf(String str) : This method returns the index within this string of the first occurrence of the specified substring. If it does not occur as a substring, -1 is returned.
Syntax:
int indexOf(String str)
Parameters:
str : a string.
Java
// Java code to demonstrate the working// of String indexOf(String str)public class Index3 {public static void main(String args[]) { // Initialising string String Str = new String("Welcome to geeksforgeeks"); // Initialising search string String subst = new String("geeks"); // print the index of initial character // of Substring // prints 11 System.out.print("Found geeks starting at position : "); System.out.print(Str.indexOf(subst)); }}
Found geeks starting at position : 11
4. int indexOf(String str, int strt) : This method returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If it does not occur, -1 is returned.
Syntax:
int indexOf(String str, int strt)
Parameters:
strt: the index to start the search from.
str : a string.
Java
// Java code to demonstrate the working// of String indexOf(String str, int strt)public class Index4 {public static void main(String args[]) { // Initialising string String Str = new String("Welcome to geeksforgeeks"); // Initialising search string String subst = new String("geeks"); // print the index of initial character // of Substring after 14th position // prints 19 System.out.print("Found geeks(after 14th index) starting at position : "); System.out.print(Str.indexOf(subst, 14)); }}
Found geeks(after 14th index) starting at position : 19
Some related applications:
Finding out if a given character (maybe anything upper or lower case) is a vowel or consonant. Implementation is given below:
JAVA
class Vowels{ // function to check if the passed // character is a vowel public static boolean vowel(char c) { return "aeiouAEIOU".indexOf(c)>=0; } // Driver program public static void main(String[] args) { boolean isVowel = vowel('a'); // Printing the output if(isVowel) System.out.println("Vowel"); else System.out.println("Consonant"); }} // This code is contributed by debjitdbb
Vowel
This article is contributed by Astha Tyagi. 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.
rohit_sinha
rajeev0719singh
kapoorsagar226
Java-Functions
Java-lang package
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 308,
"s": 52,
"text": "There are four variants of indexOf() method. This article depicts about all of them, as follows: 1.int indexOf() : This method returns the index within this string of the first occurrence of the specified character or -1, if the character does not occur. "
},
{
"code": null,
"e": 368,
"s": 308,
"text": "Syntax:\nint indexOf(char ch )\nParameters:\nch : a character."
},
{
"code": null,
"e": 373,
"s": 368,
"text": "Java"
},
{
"code": "// Java code to demonstrate the working// of String indexOf()public class Index1 {public static void main(String args[]) { // Initialising String String gfg = new String(\"Welcome to geeksforgeeks\"); System.out.print(\"Found g first at position : \"); // Initial index of 'g' will print // prints 11 System.out.println(gfg.indexOf('g')); }}",
"e": 762,
"s": 373,
"text": null
},
{
"code": null,
"e": 793,
"s": 762,
"text": "Found g first at position : 11"
},
{
"code": null,
"e": 1015,
"s": 793,
"text": "2. int indexOf(char ch, int strt ) : This method returns the index within this string of the first occurrence of the specified character, starting the search at the specified index or -1, if the character does not occur. "
},
{
"code": null,
"e": 1126,
"s": 1015,
"text": "Syntax:\nint indexOf(char ch, int strt)\nParameters:\nch :a character.\nstrt : the index to start the search from."
},
{
"code": null,
"e": 1131,
"s": 1126,
"text": "Java"
},
{
"code": "// Java code to demonstrate the working// of String indexOf(char ch, int strt)public class Index2 {public static void main(String args[]) { // Initialising String String gfg = new String(\"Welcome to geeksforgeeks\"); System.out.print(\"Found g after 13th index at position : \"); // 2nd index of 'g' will print // prints 19 System.out.println(gfg.indexOf('g', 13)); }}",
"e": 1548,
"s": 1131,
"text": null
},
{
"code": null,
"e": 1590,
"s": 1548,
"text": "Found g after 13th index at position : 19"
},
{
"code": null,
"e": 1773,
"s": 1590,
"text": "3.int indexOf(String str) : This method returns the index within this string of the first occurrence of the specified substring. If it does not occur as a substring, -1 is returned. "
},
{
"code": null,
"e": 1833,
"s": 1773,
"text": "Syntax:\nint indexOf(String str)\nParameters:\nstr : a string."
},
{
"code": null,
"e": 1838,
"s": 1833,
"text": "Java"
},
{
"code": "// Java code to demonstrate the working// of String indexOf(String str)public class Index3 {public static void main(String args[]) { // Initialising string String Str = new String(\"Welcome to geeksforgeeks\"); // Initialising search string String subst = new String(\"geeks\"); // print the index of initial character // of Substring // prints 11 System.out.print(\"Found geeks starting at position : \"); System.out.print(Str.indexOf(subst)); }}",
"e": 2352,
"s": 1838,
"text": null
},
{
"code": null,
"e": 2390,
"s": 2352,
"text": "Found geeks starting at position : 11"
},
{
"code": null,
"e": 2603,
"s": 2390,
"text": "4. int indexOf(String str, int strt) : This method returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If it does not occur, -1 is returned. "
},
{
"code": null,
"e": 2717,
"s": 2603,
"text": "Syntax:\nint indexOf(String str, int strt)\nParameters:\nstrt: the index to start the search from.\nstr : a string.\n "
},
{
"code": null,
"e": 2722,
"s": 2717,
"text": "Java"
},
{
"code": "// Java code to demonstrate the working// of String indexOf(String str, int strt)public class Index4 {public static void main(String args[]) { // Initialising string String Str = new String(\"Welcome to geeksforgeeks\"); // Initialising search string String subst = new String(\"geeks\"); // print the index of initial character // of Substring after 14th position // prints 19 System.out.print(\"Found geeks(after 14th index) starting at position : \"); System.out.print(Str.indexOf(subst, 14)); }}",
"e": 3288,
"s": 2722,
"text": null
},
{
"code": null,
"e": 3344,
"s": 3288,
"text": "Found geeks(after 14th index) starting at position : 19"
},
{
"code": null,
"e": 3372,
"s": 3344,
"text": "Some related applications: "
},
{
"code": null,
"e": 3500,
"s": 3372,
"text": "Finding out if a given character (maybe anything upper or lower case) is a vowel or consonant. Implementation is given below: "
},
{
"code": null,
"e": 3505,
"s": 3500,
"text": "JAVA"
},
{
"code": "class Vowels{ // function to check if the passed // character is a vowel public static boolean vowel(char c) { return \"aeiouAEIOU\".indexOf(c)>=0; } // Driver program public static void main(String[] args) { boolean isVowel = vowel('a'); // Printing the output if(isVowel) System.out.println(\"Vowel\"); else System.out.println(\"Consonant\"); }} // This code is contributed by debjitdbb",
"e": 4011,
"s": 3505,
"text": null
},
{
"code": null,
"e": 4017,
"s": 4011,
"text": "Vowel"
},
{
"code": null,
"e": 4438,
"s": 4017,
"text": "This article is contributed by Astha Tyagi. 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": 4450,
"s": 4438,
"text": "rohit_sinha"
},
{
"code": null,
"e": 4466,
"s": 4450,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 4481,
"s": 4466,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 4496,
"s": 4481,
"text": "Java-Functions"
},
{
"code": null,
"e": 4514,
"s": 4496,
"text": "Java-lang package"
},
{
"code": null,
"e": 4527,
"s": 4514,
"text": "Java-Strings"
},
{
"code": null,
"e": 4532,
"s": 4527,
"text": "Java"
},
{
"code": null,
"e": 4545,
"s": 4532,
"text": "Java-Strings"
},
{
"code": null,
"e": 4550,
"s": 4545,
"text": "Java"
}
] |
How to receive JSON POST with PHP ?
|
06 Dec, 2021
In this article, we will see how to retrieve the JSON POST with PHP, & will also see their implementation through the examples. First, we will look for the below 3 features:
php://input: This is a read-only stream that allows us to read raw data from the request body. It returns all the raw data after the HTTP headers of the request, regardless of the content type.
file_get_contents() function: This function in PHP is used to read a file into a string.
json_decode() function: This function takes a JSON string and converts it into a PHP variable that may be an array or an object.
It is known that all of the post data can be received in a PHP script using the $_POST[] global variable. But this fails in the case when we want to receive JSON string as post data. To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
Handling JSON POST requests:
// Takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json);
Example 1: This example uses the json_decode() function that is used to decode a JSON string.
PHP
<?php $json = '["geeks", "for", "geeks"]'; $data = json_decode($json); echo $data[0];?>
geeks
Example 2: This example uses the json_decode() function that is used to decode a JSON string.
PHP
<?php $json = '{ "title": "PHP", "site": "GeeksforGeeks" }'; $data = json_decode($json); echo $data->title; echo "\n"; echo $data->site;?>
PHP
GeeksforGeeks
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
bhaskargeeksforgeeks
JSON
Picked
PHP
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 202,
"s": 28,
"text": "In this article, we will see how to retrieve the JSON POST with PHP, & will also see their implementation through the examples. First, we will look for the below 3 features:"
},
{
"code": null,
"e": 396,
"s": 202,
"text": "php://input: This is a read-only stream that allows us to read raw data from the request body. It returns all the raw data after the HTTP headers of the request, regardless of the content type."
},
{
"code": null,
"e": 485,
"s": 396,
"text": "file_get_contents() function: This function in PHP is used to read a file into a string."
},
{
"code": null,
"e": 614,
"s": 485,
"text": "json_decode() function: This function takes a JSON string and converts it into a PHP variable that may be an array or an object."
},
{
"code": null,
"e": 1035,
"s": 614,
"text": "It is known that all of the post data can be received in a PHP script using the $_POST[] global variable. But this fails in the case when we want to receive JSON string as post data. To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string."
},
{
"code": null,
"e": 1064,
"s": 1035,
"text": "Handling JSON POST requests:"
},
{
"code": null,
"e": 1203,
"s": 1064,
"text": "// Takes raw data from the request\n$json = file_get_contents('php://input');\n\n// Converts it into a PHP object\n$data = json_decode($json);"
},
{
"code": null,
"e": 1297,
"s": 1203,
"text": "Example 1: This example uses the json_decode() function that is used to decode a JSON string."
},
{
"code": null,
"e": 1301,
"s": 1297,
"text": "PHP"
},
{
"code": "<?php $json = '[\"geeks\", \"for\", \"geeks\"]'; $data = json_decode($json); echo $data[0];?>",
"e": 1392,
"s": 1301,
"text": null
},
{
"code": null,
"e": 1398,
"s": 1392,
"text": "geeks"
},
{
"code": null,
"e": 1494,
"s": 1400,
"text": "Example 2: This example uses the json_decode() function that is used to decode a JSON string."
},
{
"code": null,
"e": 1498,
"s": 1494,
"text": "PHP"
},
{
"code": "<?php $json = '{ \"title\": \"PHP\", \"site\": \"GeeksforGeeks\" }'; $data = json_decode($json); echo $data->title; echo \"\\n\"; echo $data->site;?>",
"e": 1653,
"s": 1498,
"text": null
},
{
"code": null,
"e": 1671,
"s": 1653,
"text": "PHP\nGeeksforGeeks"
},
{
"code": null,
"e": 1842,
"s": 1673,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 1863,
"s": 1842,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 1868,
"s": 1863,
"text": "JSON"
},
{
"code": null,
"e": 1875,
"s": 1868,
"text": "Picked"
},
{
"code": null,
"e": 1879,
"s": 1875,
"text": "PHP"
},
{
"code": null,
"e": 1883,
"s": 1879,
"text": "PHP"
}
] |
HTTP headers | Keep-Alive
|
27 Feb, 2020
The Keep-Alive header is a general-type header. This header is used to hint at how the connection may be used to set a timeout and a maximum amount of requests. It can also be used to allow a single TCP connection to remain open for multiple HTTP requests/responses (default HTTP connection closed after each request). It is also known as a persistent connection. Enabling keep-alive totally depends on what server you are using and what access you have.
Syntax:
Keep-Alive: parameters
Directives: This header accepts a single directive as mentioned above and described below:
Parameters: This directive holds two comma-separated parameters timeout and max. The timeout parameter holds the minimum amount of time which is the time(in seconds) of connection has to be kept open. The ax parameter holds an integer number define how the number of requests can be sent to this connection before closing the connection.
Example: In this example connection header has to set on Keep-Alive.
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Encoding: gzip
Content-Type: text/html; charset=utf-8
Date: Thu, 17 Feb 2020 18:23:13 GMT
Keep-Alive: timeout=5, max=1000
Last-Modified: Mon, 17 Feb 2020 04:32:39 GMT
Server: Apache
To check this Keep-Alive in action go to Inspect Element -> Network check the header for Keep-ALive like below.
Supported Browsers: The browsers compatible with HTTP header Keep-Alive are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
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 ?
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
Roadmap to Learn JavaScript For Beginners
REST API (Introduction)
How to float three div side by side using CSS?
Difference Between PUT and PATCH Request
ReactJS | Router
Axios in React: A Guide for Beginners
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 483,
"s": 28,
"text": "The Keep-Alive header is a general-type header. This header is used to hint at how the connection may be used to set a timeout and a maximum amount of requests. It can also be used to allow a single TCP connection to remain open for multiple HTTP requests/responses (default HTTP connection closed after each request). It is also known as a persistent connection. Enabling keep-alive totally depends on what server you are using and what access you have."
},
{
"code": null,
"e": 491,
"s": 483,
"text": "Syntax:"
},
{
"code": null,
"e": 514,
"s": 491,
"text": "Keep-Alive: parameters"
},
{
"code": null,
"e": 605,
"s": 514,
"text": "Directives: This header accepts a single directive as mentioned above and described below:"
},
{
"code": null,
"e": 943,
"s": 605,
"text": "Parameters: This directive holds two comma-separated parameters timeout and max. The timeout parameter holds the minimum amount of time which is the time(in seconds) of connection has to be kept open. The ax parameter holds an integer number define how the number of requests can be sent to this connection before closing the connection."
},
{
"code": null,
"e": 1012,
"s": 943,
"text": "Example: In this example connection header has to set on Keep-Alive."
},
{
"code": null,
"e": 1241,
"s": 1012,
"text": "HTTP/1.1 200 OK\nConnection: Keep-Alive\nContent-Encoding: gzip\nContent-Type: text/html; charset=utf-8\nDate: Thu, 17 Feb 2020 18:23:13 GMT\nKeep-Alive: timeout=5, max=1000\nLast-Modified: Mon, 17 Feb 2020 04:32:39 GMT\nServer: Apache"
},
{
"code": null,
"e": 1353,
"s": 1241,
"text": "To check this Keep-Alive in action go to Inspect Element -> Network check the header for Keep-ALive like below."
},
{
"code": null,
"e": 1443,
"s": 1353,
"text": "Supported Browsers: The browsers compatible with HTTP header Keep-Alive are listed below:"
},
{
"code": null,
"e": 1457,
"s": 1443,
"text": "Google Chrome"
},
{
"code": null,
"e": 1475,
"s": 1457,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1483,
"s": 1475,
"text": "Firefox"
},
{
"code": null,
"e": 1490,
"s": 1483,
"text": "Safari"
},
{
"code": null,
"e": 1496,
"s": 1490,
"text": "Opera"
},
{
"code": null,
"e": 1509,
"s": 1496,
"text": "HTTP-headers"
},
{
"code": null,
"e": 1516,
"s": 1509,
"text": "Picked"
},
{
"code": null,
"e": 1533,
"s": 1516,
"text": "Web Technologies"
},
{
"code": null,
"e": 1631,
"s": 1533,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1692,
"s": 1631,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1735,
"s": 1692,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1775,
"s": 1735,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1847,
"s": 1775,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1889,
"s": 1847,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1913,
"s": 1889,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1960,
"s": 1913,
"text": "How to float three div side by side using CSS?"
},
{
"code": null,
"e": 2001,
"s": 1960,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2018,
"s": 2001,
"text": "ReactJS | Router"
}
] |
Intersection of two arrays JavaScript
|
We have two arrays of Numbers, and we are required to write a function, say intersection() that
computes their intersection and returns an array that contains the intersecting elements in any
order. Each element in the result should appear as many times as it shows in both arrays.
For example − If,
Input: arr1 = [1,2,3,1], arr2 = [1,3,1]
Output: [1,3,1]
Had the arrays been sorted, we could have used the two pointer approach with initially both
pointing to 0 the start of the respective array and we could have proceeded with increasing the
corresponding pointer and that would have been O(m+n) complex w.r.t. time where m and n are
the sizes of array.
But since we have unsorted arrays there is no logic in sorting the arrays and then using this
approach, we will check every value of first against the second and construct an intersection
array. This would cost us O(n^2) time.
And the code for doing this will be −
const arr1 = [1, 2, 43, 5, 3, 7, 7,8, 4, 2];
const arr2 = [1, 1, 6, 6, 2, 78, 7, 2, 3, 7, 23, 5, 3];
const intersection = (arr1, arr2) => {
const res = [];
const { length: len1 } = arr1;
const { length: len2 } = arr2;
const smaller = (len1 < len2 ? arr1 : arr2).slice();
const bigger = (len1 >= len2 ? arr1 : arr2).slice();
for(let i = 0; i < smaller.length; i++){
if(bigger.indexOf(smaller[i]) !== -1){
res.push(smaller[i]);
bigger.splice(bigger.indexOf(smaller[i]), 1, undefined);
}
};
return res;
};
console.log(intersection(arr1 ,arr2));
The output in the console will be −
[1, 2, 5, 3, 7, 7, 2]
|
[
{
"code": null,
"e": 1344,
"s": 1062,
"text": "We have two arrays of Numbers, and we are required to write a function, say intersection() that\ncomputes their intersection and returns an array that contains the intersecting elements in any\norder. Each element in the result should appear as many times as it shows in both arrays."
},
{
"code": null,
"e": 1362,
"s": 1344,
"text": "For example − If,"
},
{
"code": null,
"e": 1418,
"s": 1362,
"text": "Input: arr1 = [1,2,3,1], arr2 = [1,3,1]\nOutput: [1,3,1]"
},
{
"code": null,
"e": 1718,
"s": 1418,
"text": "Had the arrays been sorted, we could have used the two pointer approach with initially both\npointing to 0 the start of the respective array and we could have proceeded with increasing the\ncorresponding pointer and that would have been O(m+n) complex w.r.t. time where m and n are\nthe sizes of array."
},
{
"code": null,
"e": 1945,
"s": 1718,
"text": "But since we have unsorted arrays there is no logic in sorting the arrays and then using this\napproach, we will check every value of first against the second and construct an intersection\narray. This would cost us O(n^2) time."
},
{
"code": null,
"e": 1983,
"s": 1945,
"text": "And the code for doing this will be −"
},
{
"code": null,
"e": 2579,
"s": 1983,
"text": "const arr1 = [1, 2, 43, 5, 3, 7, 7,8, 4, 2];\nconst arr2 = [1, 1, 6, 6, 2, 78, 7, 2, 3, 7, 23, 5, 3];\nconst intersection = (arr1, arr2) => {\n const res = [];\n const { length: len1 } = arr1;\n const { length: len2 } = arr2;\n const smaller = (len1 < len2 ? arr1 : arr2).slice();\n const bigger = (len1 >= len2 ? arr1 : arr2).slice();\n for(let i = 0; i < smaller.length; i++){\n if(bigger.indexOf(smaller[i]) !== -1){\n res.push(smaller[i]);\n bigger.splice(bigger.indexOf(smaller[i]), 1, undefined);\n }\n };\n return res;\n};\nconsole.log(intersection(arr1 ,arr2));"
},
{
"code": null,
"e": 2615,
"s": 2579,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 2637,
"s": 2615,
"text": "[1, 2, 5, 3, 7, 7, 2]"
}
] |
Embedded Systems - Quick Guide
|
A system is an arrangement in which all its unit assemble work together according to a set of rules. It can also be defined as a way of working, organizing or doing one or many tasks according to a fixed plan. For example, a watch is a time displaying system. Its components follow a set of rules to show time. If one of its parts fails, the watch will stop working. So we can say, in a system, all its subcomponents depend on each other.
As its name suggests, Embedded means something that is attached to another thing. An embedded system can be thought of as a computer hardware system having software embedded in it. An embedded system can be an independent system or it can be a part of a large system. An embedded system is a microcontroller or microprocessor based system which is designed to perform a specific task. For example, a fire alarm is an embedded system; it will sense only smoke.
An embedded system has three components −
It has hardware.
It has hardware.
It has application software.
It has application software.
It has Real Time Operating system (RTOS) that supervises the application software and provide mechanism to let the processor run a process as per scheduling by following a plan to control the latencies. RTOS defines the way the system works. It sets the rules during the execution of application program. A small scale embedded system may not have RTOS.
It has Real Time Operating system (RTOS) that supervises the application software and provide mechanism to let the processor run a process as per scheduling by following a plan to control the latencies. RTOS defines the way the system works. It sets the rules during the execution of application program. A small scale embedded system may not have RTOS.
So we can define an embedded system as a Microcontroller based, software driven, reliable, real-time control system.
Single-functioned − An embedded system usually performs a specialized operation and does the same repeatedly. For example: A pager always functions as a pager.
Single-functioned − An embedded system usually performs a specialized operation and does the same repeatedly. For example: A pager always functions as a pager.
Tightly constrained − All computing systems have constraints on design metrics, but those on an embedded system can be especially tight. Design metrics is a measure of an implementation's features such as its cost, size, power, and performance. It must be of a size to fit on a single chip, must perform fast enough to process data in real time and consume minimum power to extend battery life.
Tightly constrained − All computing systems have constraints on design metrics, but those on an embedded system can be especially tight. Design metrics is a measure of an implementation's features such as its cost, size, power, and performance. It must be of a size to fit on a single chip, must perform fast enough to process data in real time and consume minimum power to extend battery life.
Reactive and Real time − Many embedded systems must continually react to changes in the system's environment and must compute certain results in real time without any delay. Consider an example of a car cruise controller; it continually monitors and reacts to speed and brake sensors. It must compute acceleration or de-accelerations repeatedly within a limited time; a delayed computation can result in failure to control of the car.
Reactive and Real time − Many embedded systems must continually react to changes in the system's environment and must compute certain results in real time without any delay. Consider an example of a car cruise controller; it continually monitors and reacts to speed and brake sensors. It must compute acceleration or de-accelerations repeatedly within a limited time; a delayed computation can result in failure to control of the car.
Microprocessors based − It must be microprocessor or microcontroller based.
Microprocessors based − It must be microprocessor or microcontroller based.
Memory − It must have a memory, as its software usually embeds in ROM. It does not need any secondary memories in the computer.
Memory − It must have a memory, as its software usually embeds in ROM. It does not need any secondary memories in the computer.
Connected − It must have connected peripherals to connect input and output devices.
Connected − It must have connected peripherals to connect input and output devices.
HW-SW systems − Software is used for more features and flexibility. Hardware is used for performance and security.
HW-SW systems − Software is used for more features and flexibility. Hardware is used for performance and security.
Easily Customizable
Low power consumption
Low cost
Enhanced performance
High development effort
Larger time to market
The following illustration shows the basic structure of an embedded system −
Sensor − It measures the physical quantity and converts it to an electrical signal which can be read by an observer or by any electronic instrument like an A2D converter. A sensor stores the measured quantity to the memory.
Sensor − It measures the physical quantity and converts it to an electrical signal which can be read by an observer or by any electronic instrument like an A2D converter. A sensor stores the measured quantity to the memory.
A-D Converter − An analog-to-digital converter converts the analog signal sent by the sensor into a digital signal.
A-D Converter − An analog-to-digital converter converts the analog signal sent by the sensor into a digital signal.
Processor & ASICs − Processors process the data to measure the output and store it to the memory.
Processor & ASICs − Processors process the data to measure the output and store it to the memory.
D-A Converter − A digital-to-analog converter converts the digital data fed by the processor to analog data
D-A Converter − A digital-to-analog converter converts the digital data fed by the processor to analog data
Actuator − An actuator compares the output given by the D-A Converter to the actual (expected) output stored in it and stores the approved output.
Actuator − An actuator compares the output given by the D-A Converter to the actual (expected) output stored in it and stores the approved output.
Processor is the heart of an embedded system. It is the basic unit that takes inputs and produces an output after processing the data. For an embedded system designer, it is necessary to have the knowledge of both microprocessors and microcontrollers.
A processor has two essential units −
Program Flow Control Unit (CU)
Execution Unit (EU)
The CU includes a fetch unit for fetching instructions from the memory. The EU has circuits that implement the instructions pertaining to data transfer operation and data conversion from one form to another.
The EU includes the Arithmetic and Logical Unit (ALU) and also the circuits that execute instructions for a program control task such as interrupt, or jump to another set of instructions.
A processor runs the cycles of fetch and executes the instructions in the same sequence as they are fetched from memory.
Processors can be of the following categories −
General Purpose Processor (GPP)
Microprocessor
Microcontroller
Embedded Processor
Digital Signal Processor
Media Processor
General Purpose Processor (GPP)
Microprocessor
Microcontroller
Embedded Processor
Digital Signal Processor
Media Processor
Application Specific System Processor (ASSP)
Application Specific System Processor (ASSP)
Application Specific Instruction Processors (ASIPs)
Application Specific Instruction Processors (ASIPs)
GPP core(s) or ASIP core(s) on either an Application Specific Integrated Circuit (ASIC) or a Very Large Scale Integration (VLSI) circuit.
GPP core(s) or ASIP core(s) on either an Application Specific Integrated Circuit (ASIC) or a Very Large Scale Integration (VLSI) circuit.
A microprocessor is a single VLSI chip having a CPU. In addition, it may also have other units such as coaches, floating point processing arithmetic unit, and pipelining units that help in faster processing of instructions.
Earlier generation microprocessors’ fetch-and-execute cycle was guided by a clock frequency of order of ~1 MHz. Processors now operate at a clock frequency of 2GHz
A microcontroller is a single-chip VLSI unit (also called microcomputer) which, although having limited computational capabilities, possesses enhanced input/output capability and a number of on-chip functional units.
Microcontrollers are particularly used in embedded systems for real-time control applications with on-chip program memory and devices.
Let us now take a look at the most notable differences between a microprocessor and a microcontroller.
The 8051 microcontrollers work with 8-bit data bus. So they can support external data memory up to 64K and external program memory of 64k at best. Collectively, 8051 microcontrollers can address 128k of external memory.
When data and code lie in different memory blocks, then the architecture is referred as Harvard architecture. In case data and code lie in the same memory block, then the architecture is referred as Von Neumann architecture.
The Von Neumann architecture was first proposed by a computer scientist John von Neumann. In this architecture, one data path or bus exists for both instruction and data. As a result, the CPU does one operation at a time. It either fetches an instruction from memory, or performs read/write operation on data. So an instruction fetch and a data operation cannot occur simultaneously, sharing a common bus.
Von-Neumann architecture supports simple hardware. It allows the use of a single, sequential memory. Today's processing speeds vastly outpace memory access times, and we employ a very fast but small amount of memory (cache) local to the processor.
The Harvard architecture offers separate storage and signal buses for instructions and data. This architecture has data storage entirely contained within the CPU, and there is no access to the instruction storage as data. Computers have separate memory areas for program instructions and data using internal data buses, allowing simultaneous access to both instructions and data.
Programs needed to be loaded by an operator; the processor could not boot itself. In a Harvard architecture, there is no need to make the two memories share properties.
The following points distinguish the Von Neumann Architecture from the Harvard Architecture.
CISC is a Complex Instruction Set Computer. It is a computer that can address a large number of instructions.
In the early 1980s, computer designers recommended that computers should use fewer instructions with simple constructs so that they can be executed much faster within the CPU without having to use memory. Such computers are classified as Reduced Instruction Set Computer or RISC.
The following points differentiate a CISC from a RISC −
A compiler is a computer program (or a set of programs) that transforms the source code written in a programming language (the source language) into another computer language (normally binary format). The most common reason for conversion is to create an executable program. The name "compiler" is primarily used for programs that translate the source code from a highlevel programming language to a low-level language (e.g., assembly language or machine code).
If the compiled program can run on a computer having different CPU or operating system than the computer on which the compiler compiled the program, then that compiler is known as a cross-compiler.
A program that can translate a program from a low-level language to a high-level language is called a decompiler.
A program that translates programs written in different high-level languages is normally called a language translator, source to source translator, or language converter.
A compiler is likely to perform the following operations −
Preprocessing
Parsing
Semantic Analysis (Syntax-directed translation)
Code generation
Code optimization
An assembler is a program that takes basic computer instructions (called as assembly language) and converts them into a pattern of bits that the computer's processor can use to perform its basic operations. An assembler creates object code by translating assembly instruction mnemonics into opcodes, resolving symbolic names to memory locations. Assembly language uses a mnemonic to represent each low-level machine operation (opcode).
Debugging is a methodical process to find and reduce the number of bugs in a computer program or a piece of electronic hardware, so that it works as expected. Debugging is difficult when subsystems are tightly coupled, because a small change in one subsystem can create bugs in another. The debugging tools used in embedded systems differ greatly in terms of their development time and debugging features. We will discuss here the following debugging tools −
Simulators
Microcontroller starter kits
Emulator
Code is tested for the MCU / system by simulating it on the host computer used for code development. Simulators try to model the behavior of the complete microcontroller in software.
A simulator performs the following functions −
Defines the processor or processing device family as well as its various versions for the target system.
Defines the processor or processing device family as well as its various versions for the target system.
Monitors the detailed information of a source code part with labels and symbolic arguments as the execution goes on for each single step.
Monitors the detailed information of a source code part with labels and symbolic arguments as the execution goes on for each single step.
Provides the status of RAM and simulated ports of the target system for each single step execution.
Provides the status of RAM and simulated ports of the target system for each single step execution.
Monitors system response and determines throughput.
Monitors system response and determines throughput.
Provides trace of the output of contents of program counter versus the processor registers.
Provides trace of the output of contents of program counter versus the processor registers.
Provides the detailed meaning of the present command.
Provides the detailed meaning of the present command.
Monitors the detailed information of the simulator commands as these are entered from the keyboard or selected from the menu.
Monitors the detailed information of the simulator commands as these are entered from the keyboard or selected from the menu.
Supports the conditions (up to 8 or 16 or 32 conditions) and unconditional breakpoints.
Supports the conditions (up to 8 or 16 or 32 conditions) and unconditional breakpoints.
Provides breakpoints and the trace which are together the important testing and debugging tool.
Provides breakpoints and the trace which are together the important testing and debugging tool.
Facilitates synchronizing the internal peripherals and delays.
Facilitates synchronizing the internal peripherals and delays.
A microcontroller starter kit consists of −
Hardware board (Evaluation board)
In-system programmer
Some software tools like compiler, assembler, linker, etc.
Sometimes, an IDE and code size limited evaluation version of a compiler.
A big advantage of these kits over simulators is that they work in real-time and thus allow for easy input/output functionality verification. Starter kits, however, are completely sufficient and the cheapest option to develop simple microcontroller projects.
An emulator is a hardware kit or a software program or can be both which emulates the functions of one computer system (the guest) in another computer system (the host), different from the first one, so that the emulated behavior closely resembles the behavior of the real system (the guest).
Emulation refers to the ability of a computer program in an electronic device to emulate (imitate) another program or device. Emulation focuses on recreating an original computer environment. Emulators have the ability to maintain a closer connection to the authenticity of the digital object. An emulator helps the user to work on any kind of application or operating system on a platform in a similar way as the software runs as in its original environment.
Embedded systems communicate with the outside world via their peripherals, such as following &mins;
Serial Communication Interfaces (SCI) like RS-232, RS-422, RS-485, etc.
Synchronous Serial Communication Interface like I2C, SPI, SSC, and ESSI
Universal Serial Bus (USB)
Multi Media Cards (SD Cards, Compact Flash, etc.)
Networks like Ethernet, LonWorks, etc.
Fieldbuses like CAN-Bus, LIN-Bus, PROFIBUS, etc.
imers like PLL(s), Capture/Compare and Time Processing Units.
Discrete IO aka General Purpose Input/Output (GPIO)
Analog to Digital/Digital to Analog (ADC/DAC)
Debugging like JTAG, ISP, ICSP, BDM Port, BITP, and DP9 ports
While choosing a microcontroller, make sure it meets the task at hand and that it is cost effective. We must see whether an 8-bit, 16-bit or 32-bit microcontroller can best handle the computing needs of a task. In addition, the following points should be kept in mind while choosing a microcontroller −
Speed − What is the highest speed the microcontroller can support?
Speed − What is the highest speed the microcontroller can support?
Packaging − Is it 40-pin DIP (Dual-inline-package) or QFP (Quad flat package)? This is important in terms of space, assembling, and prototyping the end-product.
Packaging − Is it 40-pin DIP (Dual-inline-package) or QFP (Quad flat package)? This is important in terms of space, assembling, and prototyping the end-product.
Power Consumption − This is an important criteria for battery-powered products.
Power Consumption − This is an important criteria for battery-powered products.
Amount of RAM and ROM on the chip.
Amount of RAM and ROM on the chip.
Count of I/O pins and Timers on the chip.
Count of I/O pins and Timers on the chip.
Cost per Unit − This is important in terms of final cost of the product in which the microcontroller is to be used.
Cost per Unit − This is important in terms of final cost of the product in which the microcontroller is to be used.
Further, make sure you have tools such as compilers, debuggers, and assemblers, available with the microcontroller. The most important of all, you should purchase a microcontroller from a reliable source.
The first microprocessor 4004 was invented by Intel Corporation. 8085 and 8086 microprocessors were also invented by Intel. In 1981, Intel introduced an 8-bit microcontroller called the 8051. It was referred as system on a chip because it had 128 bytes of RAM, 4K byte of on-chip ROM, two timers, one serial port, and 4 ports (8-bit wide), all on a single chip. When it became widely popular, Intel allowed other manufacturers to make and market different flavors of 8051 with its code compatible with 8051. It means that if you write your program for one flavor of 8051, it will run on other flavors too, regardless of the manufacturer. This has led to several versions with different speeds and amounts of on-chip RAM.
8052 microcontroller − 8052 has all the standard features of the 8051 microcontroller as well as an extra 128 bytes of RAM and an extra timer. It also has 8K bytes of on-chip program ROM instead of 4K bytes.
8052 microcontroller − 8052 has all the standard features of the 8051 microcontroller as well as an extra 128 bytes of RAM and an extra timer. It also has 8K bytes of on-chip program ROM instead of 4K bytes.
8031 microcontroller − It is another member of the 8051 family. This chip is often referred to as a ROM-less 8051, since it has 0K byte of on-chip ROM. You must add external ROM to it in order to use it, which contains the program to be fetched and executed. This program can be as large as 64K bytes. But in the process of adding external ROM to the 8031, it lost 2 ports out of 4 ports. To solve this problem, we can add an external I/O to the 8031
8031 microcontroller − It is another member of the 8051 family. This chip is often referred to as a ROM-less 8051, since it has 0K byte of on-chip ROM. You must add external ROM to it in order to use it, which contains the program to be fetched and executed. This program can be as large as 64K bytes. But in the process of adding external ROM to the 8031, it lost 2 ports out of 4 ports. To solve this problem, we can add an external I/O to the 8031
The following table compares the features available in 8051, 8052, and 8031.
An 8051 microcontroller comes bundled with the following features −
4KB bytes on-chip program memory (ROM)
128 bytes on-chip data memory (RAM)
Four register banks
128 user defined software flags
8-bit bidirectional data bus
16-bit unidirectional address bus
32 general purpose registers each of 8-bit
16 bit Timers (usually 2, but may have more or less)
Three internal and two external Interrupts
Four 8-bit ports,(short model have two 8-bit ports)
16-bit program counter and data pointer
8051 may also have a number of special features such as UARTs, ADC, Op-amp, etc.
The following illustration shows the block diagram of an 8051 microcontroller −
In 8051, I/O operations are done using four ports and 40 pins. The following pin diagram shows the details of the 40 pins. I/O operation port reserves 32 pins where each port has 8 pins. The other 8 pins are designated as Vcc, GND, XTAL1, XTAL2, RST, EA (bar), ALE/PROG (bar), and PSEN (bar).
It is a 40 Pin PDIP (Plastic Dual Inline Package)
Note − In a DIP package, you can recognize the first pin and the last pin by the cut at the middle of the IC. The first pin is on the left of this cut mark and the last pin (i.e. the 40th pin in this case) is to the right of the cut mark.
The four ports P0, P1, P2, and P3, each use 8 pins, making them 8-bit ports. Upon RESET, all the ports are configured as inputs, ready to be used as input ports. When the first 0 is written to a port, it becomes an output. To reconfigure it as an input, a 1 must be sent to a port.
It has 8 pins (32 to 39). It can be used for input or output. Unlike P1, P2, and P3 ports, we normally connect P0 to 10K-ohm pull-up resistors to use it as an input or output port being an open drain.
It is also designated as AD0-AD7, allowing it to be used as both address and data. In case of 8031 (i.e. ROMless Chip), when we need to access the external ROM, then P0 will be used for both Address and Data Bus. ALE (Pin no 31) indicates if P0 has address or data. When ALE = 0, it provides data D0-D7, but when ALE = 1, it has address A0-A7. In case no external memory connection is available, P0 must be connected externally to a 10K-ohm pull-up resistor.
MOV A,#0FFH ;(comments: A=FFH(Hexadecimal i.e. A=1111 1111)
MOV P0,A ;(Port0 have 1's on every pin so that it works as Input)
It is an 8-bit port (pin 1 through 8) and can be used either as input or output. It doesn't require pull-up resistors because they are already connected internally. Upon reset, Port 1 is configured as an input port. The following code can be used to send alternating values of 55H and AAH to Port 1.
;Toggle all bits of continuously
MOV A,#55
BACK:
MOV P2,A
ACALL DELAY
CPL A ;complement(invert) reg. A
SJMP BACK
If Port 1 is configured to be used as an output port, then to use it as an input port again, program it by writing 1 to all of its bits as in the following code.
;Toggle all bits of continuously
MOV A ,#0FFH ;A = FF hex
MOV P1,A ;Make P1 an input port
MOV A,P1 ;get data from P1
MOV R7,A ;save it in Reg R7
ACALL DELAY ;wait
MOV A,P1 ;get another data from P1
MOV R6,A ;save it in R6
ACALL DELAY ;wait
MOV A,P1 ;get another data from P1
MOV R5,A ;save it in R5
Port 2 occupies a total of 8 pins (pins 21 through 28) and can be used for both input and output operations. Just as P1 (Port 1), P2 also doesn't require external Pull-up resistors because they are already connected internally. It must be used along with P0 to provide the 16-bit address for the external memory. So it is also designated as (A0–A7), as shown in the pin diagram. When the 8051 is connected to an external memory, it provides path for upper 8-bits of 16-bits address, and it cannot be used as I/O. Upon reset, Port 2 is configured as an input port. The following code can be used to send alternating values of 55H and AAH to port 2.
;Toggle all bits of continuously
MOV A,#55
BACK:
MOV P2,A
ACALL DELAY
CPL A ; complement(invert) reg. A
SJMP BACK
If Port 2 is configured to be used as an output port, then to use it as an input port again, program it by writing 1 to all of its bits as in the following code.
;Get a byte from P2 and send it to P1
MOV A,#0FFH ;A = FF hex
MOV P2,A ;make P2 an input port
BACK:
MOV A,P2 ;get data from P2
MOV P1,A ;send it to Port 1
SJMP BACK ;keep doing that
It is also of 8 bits and can be used as Input/Output. This port provides some extremely important signals. P3.0 and P3.1 are RxD (Receiver) and TxD (Transmitter) respectively and are collectively used for Serial Communication. P3.2 and P3.3 pins are used for external interrupts. P3.4 and P3.5 are used for timers T0 and T1 respectively. P3.6 and P3.7 are Write (WR) and Read (RD) pins. These are active low pins, means they will be active when 0 is given to them and these are used to provide Read and Write operations to External ROM in 8031 based systems.
Dual role of Port 0 − Port 0 is also designated as AD0–AD7, as it can be used for both data and address handling. While connecting an 8051 to external memory, Port 0 can provide both address and data. The 8051 microcontroller then multiplexes the input as address or data in order to save pins.
Dual role of Port 0 − Port 0 is also designated as AD0–AD7, as it can be used for both data and address handling. While connecting an 8051 to external memory, Port 0 can provide both address and data. The 8051 microcontroller then multiplexes the input as address or data in order to save pins.
Dual role of Port 2 − Besides working as I/O, Port P2 is also used to provide 16-bit address bus for external memory along with Port 0. Port P2 is also designated as (A8– A15), while Port 0 provides the lower 8-bits via A0–A7. In other words, we can say that when an 8051 is connected to an external memory (ROM) which can be maximum up to 64KB and this is possible by 16 bit address bus because we know 216 = 64KB. Port2 is used for the upper 8-bit of the 16 bits address, and it cannot be used for I/O and this is the way any Program code of external ROM is addressed.
Dual role of Port 2 − Besides working as I/O, Port P2 is also used to provide 16-bit address bus for external memory along with Port 0. Port P2 is also designated as (A8– A15), while Port 0 provides the lower 8-bits via A0–A7. In other words, we can say that when an 8051 is connected to an external memory (ROM) which can be maximum up to 64KB and this is possible by 16 bit address bus because we know 216 = 64KB. Port2 is used for the upper 8-bit of the 16 bits address, and it cannot be used for I/O and this is the way any Program code of external ROM is addressed.
Vcc − Pin 40 provides supply to the Chip and it is +5 V.
Vcc − Pin 40 provides supply to the Chip and it is +5 V.
Gnd − Pin 20 provides ground for the Reference.
Gnd − Pin 20 provides ground for the Reference.
XTAL1, XTAL2 (Pin no 18 & Pin no 19) − 8051 has on-chip oscillator but requires external clock to run it. A quartz crystal is connected between the XTAL1 & XTAL2 pin of the chip. This crystal also needs two capacitors of 30pF for generating a signal of desired frequency. One side of each capacitor is connected to ground. 8051 IC is available in various speeds and it all depends on this Quartz crystal, for example, a 20 MHz microcontroller requires a crystal with a frequency no more than 20 MHz.
XTAL1, XTAL2 (Pin no 18 & Pin no 19) − 8051 has on-chip oscillator but requires external clock to run it. A quartz crystal is connected between the XTAL1 & XTAL2 pin of the chip. This crystal also needs two capacitors of 30pF for generating a signal of desired frequency. One side of each capacitor is connected to ground. 8051 IC is available in various speeds and it all depends on this Quartz crystal, for example, a 20 MHz microcontroller requires a crystal with a frequency no more than 20 MHz.
RST (Pin No. 9) − It is an Input pin and active High pin. Upon applying a high pulse on this pin, that is 1, the microcontroller will reset and terminate all activities. This process is known as Power-On Reset. Activating a power-on reset will cause all values in the register to be lost. It will set a program counter to all 0's. To ensure a valid input of Reset, the high pulse must be high for a minimum of two machine cycles before it is allowed to go low, which depends on the capacitor value and the rate at which it charges. (Machine Cycle is the minimum amount of frequency a single instruction requires in execution).
RST (Pin No. 9) − It is an Input pin and active High pin. Upon applying a high pulse on this pin, that is 1, the microcontroller will reset and terminate all activities. This process is known as Power-On Reset. Activating a power-on reset will cause all values in the register to be lost. It will set a program counter to all 0's. To ensure a valid input of Reset, the high pulse must be high for a minimum of two machine cycles before it is allowed to go low, which depends on the capacitor value and the rate at which it charges. (Machine Cycle is the minimum amount of frequency a single instruction requires in execution).
EA or External Access (Pin No. 31) − It is an input pin. This pin is an active low pin; upon applying a low pulse, it gets activated. In case of microcontroller (8051/52) having on-chip ROM, the EA (bar) pin is connected to Vcc. But in an 8031 microcontroller which does not have an on-chip ROM, the code is stored in an external ROM and then fetched by the microcontroller. In this case, we must connect the (pin no 31) EA to Gnd to indicate that the program code is stored externally.
EA or External Access (Pin No. 31) − It is an input pin. This pin is an active low pin; upon applying a low pulse, it gets activated. In case of microcontroller (8051/52) having on-chip ROM, the EA (bar) pin is connected to Vcc. But in an 8031 microcontroller which does not have an on-chip ROM, the code is stored in an external ROM and then fetched by the microcontroller. In this case, we must connect the (pin no 31) EA to Gnd to indicate that the program code is stored externally.
PSEN or Program store Enable (Pin No 29) − This is also an active low pin, i.e., it gets activated after applying a low pulse. It is an output pin and used along with the EA pin in 8031 based (i.e. ROMLESS) Systems to allow storage of program code in external ROM.
PSEN or Program store Enable (Pin No 29) − This is also an active low pin, i.e., it gets activated after applying a low pulse. It is an output pin and used along with the EA pin in 8031 based (i.e. ROMLESS) Systems to allow storage of program code in external ROM.
ALE or (Address Latch Enable) − This is an Output Pin and is active high. It is especially used for 8031 IC to connect it to the external memory. It can be used while deciding whether P0 pins will be used as Address bus or Data bus. When ALE = 1, then the P0 pins work as Data bus and when ALE = 0, then the P0 pins act as Address bus.
ALE or (Address Latch Enable) − This is an Output Pin and is active high. It is especially used for 8031 IC to connect it to the external memory. It can be used while deciding whether P0 pins will be used as Address bus or Data bus. When ALE = 1, then the P0 pins work as Data bus and when ALE = 0, then the P0 pins act as Address bus.
It is a most widely used feature of 8051 while writing code for 8051. Sometimes we need to access only 1 or 2 bits of the port instead of the entire 8-bits. 8051 provides the capability to access individual bits of the ports.
While accessing a port in a single-bit manner, we use the syntax "SETB X. Y" where X is the port number (0 to 3), and Y is a bit number (0 to 7) for data bits D0-D7 where D0 is the LSB and D7 is the MSB. For example, "SETB P1.5" sets high bit 5 of port 1.
The following code shows how we can toggle the bit P1.2 continuously.
AGAIN:
SETB P1.2
ACALL DELAY
CLR P1.2
ACALL DELAY
SJMP AGAIN
The Program Counter is a 16- or 32-bit register which contains the address of the next instruction to be executed. The PC automatically increments to the next sequential memory location every time an instruction is fetched. Branch, jump, and interrupt operations load the Program Counter with an address other than the next sequential location.
Activating a power-on reset will cause all values in the register to be lost. It means the value of the PC (program counter) is 0 upon reset, forcing the CPU to fetch the first opcode from the ROM memory location 0000. It means we must place the first byte of upcode in ROM location 0000 because that is where the CPU expects to find the first instruction
The significance of the reset vector is that it points the processor to the memory address which contains the firmware's first instruction. Without the Reset Vector, the processor would not know where to begin execution. Upon reset, the processor loads the Program Counter (PC) with the reset vector value from a predefined memory location. On CPU08 architecture, this is at location $FFFE:$FFFF.
When the reset vector is not necessary, developers normally take it for granted and don’t program into the final image. As a result, the processor doesn't start up on the final product. It is a common mistake that takes place during the debug phase.
Stack is implemented in RAM and a CPU register is used to access it called SP (Stack Pointer) register. SP register is an 8-bit register and can address memory addresses of range 00h to FFh. Initially, the SP register contains value 07 to point to location 08 as the first location being used for the stack by the 8051.
When the content of a CPU register is stored in a stack, it is called a PUSH operation. When the content of a stack is stored in a CPU register, it is called a POP operation. In other words, a register is pushed onto the stack to save it and popped off the stack to retrieve it.
An infinite loop or an endless loop can be identified as a sequence of instructions in a computer program that executes endlessly in a loop, because of the following reasons −
loop with no terminating condition.
loop with a terminating condition that can never be met.
loop with a terminating condition that causes the loop to start over.
Such infinite loops normally caused older operating systems to become unresponsive, as an infinite loop consumes all the available processor time. I/O operations waiting for user inputs are also called "infinite loops". One possible cause of a computer "freezing" is an infinite loop; other causes include deadlock and access violations.
Embedded systems, unlike a PC, never "exit" an application. They idle through an Infinite Loop waiting for an event to take place in the form of an interrupt, or a pre-scheduled task. In order to save power, some processors enter special sleep or wait modes instead of idling through an Infinite Loop, but they will come out of this mode upon either a timer or an External Interrupt.
Interrupts are mostly hardware mechanisms that instruct the program that an event has occurred. They may occur at any time, and are therefore asynchronous to the program flow. They require special handling by the processor, and are ultimately handled by a corresponding Interrupt Service Routine (ISR). Interrupts need to be handled quickly. If you take too much time servicing an interrupt, then you may miss another interrupt.
Although numbers are always displayed in the same way, they are not stored in the same way in memory. Big-Endian machines store the most significant byte of data in the lowest memory address. A Big-Endian machine stores 0x12345678 as −
ADD+0: 0x12
ADD+1: 0x34
ADD+2: 0x56
ADD+3: 0x78
Little-Endian machines, on the other hand, store the least significant byte of data in the lowest memory address. A Little-Endian machine stores 0x12345678 as −
ADD+0: 0x78
ADD+1: 0x56
ADD+2: 0x34
ADD+3: 0x12
Assembly languages were developed to provide mnemonics or symbols for the machine level code instructions. Assembly language programs consist of mnemonics, thus they should be translated into machine code. A program that is responsible for this conversion is known as assembler. Assembly language is often termed as a low-level language because it directly works with the internal structure of the CPU. To program in assembly language, a programmer must know all the registers of the CPU.
Different programming languages such as C, C++, Java and various other languages are called high-level languages because they do not deal with the internal details of a CPU. In contrast, an assembler is used to translate an assembly language program into machine code (sometimes also called object code or opcode). Similarly, a compiler translates a high-level language into machine code. For example, to write a program in C language, one must use a C compiler to translate the program into machine language.
An assembly language program is a series of statements, which are either assembly language instructions such as ADD and MOV, or statements called directives.
An instruction tells the CPU what to do, while a directive (also called pseudo-instructions) gives instruction to the assembler. For example, ADD and MOV instructions are commands which the CPU runs, while ORG and END are assembler directives. The assembler places the opcode to the memory location 0 when the ORG directive is used, while END indicates to the end of the source code. A program language instruction consists of the following four fields −
[ label: ] mnemonics [ operands ] [;comment ]
A square bracket ( [ ] ) indicates that the field is optional.
The label field allows the program to refer to a line of code by name. The label fields cannot exceed a certain number of characters.
The label field allows the program to refer to a line of code by name. The label fields cannot exceed a certain number of characters.
The mnemonics and operands fields together perform the real work of the program and accomplish the tasks. Statements like ADD A , C & MOV C, #68 where ADD and MOV are the mnemonics, which produce opcodes ; "A, C" and "C, #68" are operands. These two fields could contain directives. Directives do not generate machine code and are used only by the assembler, whereas instructions are translated into machine code for the CPU to execute.
The mnemonics and operands fields together perform the real work of the program and accomplish the tasks. Statements like ADD A , C & MOV C, #68 where ADD and MOV are the mnemonics, which produce opcodes ; "A, C" and "C, #68" are operands. These two fields could contain directives. Directives do not generate machine code and are used only by the assembler, whereas instructions are translated into machine code for the CPU to execute.
1.0000 ORG 0H ;start (origin) at location 0
2 0000 7D25 MOV R5,#25H ;load 25H into R5
3.0002 7F34 MOV R7,#34H ;load 34H into R7
4.0004 7400 MOV A,#0 ;load 0 into A
5.0006 2D ADD A,R5 ;add contents of R5 to A
6.0007 2F ADD A,R7 ;add contents of R7 to A
7.0008 2412 ADD A,#12H ;add to A value 12 H
8.000A 80FE HERE: SJMP HERE ;stay in this loop
9.000C END ;end of asm source file
The comment field begins with a semicolon which is a comment indicator.
The comment field begins with a semicolon which is a comment indicator.
Notice the Label "HERE" in the program. Any label which refers to an instruction should be followed by a colon.
Notice the Label "HERE" in the program. Any label which refers to an instruction should be followed by a colon.
Here we will discuss about the basic form of an assembly language. The steps to create, assemble, and run an assembly language program are as follows −
First, we use an editor to type in a program similar to the above program. Editors like MS-DOS EDIT program that comes with all Microsoft operating systems can be used to create or edit a program. The Editor must be able to produce an ASCII file. The "asm" extension for the source file is used by an assembler in the next step.
First, we use an editor to type in a program similar to the above program. Editors like MS-DOS EDIT program that comes with all Microsoft operating systems can be used to create or edit a program. The Editor must be able to produce an ASCII file. The "asm" extension for the source file is used by an assembler in the next step.
The "asm" source file contains the program code created in Step 1. It is fed to an 8051 assembler. The assembler then converts the assembly language instructions into machine code instructions and produces an .obj file (object file) and a .lst file (list file). It is also called as a source file, that's why some assemblers require that this file have the "src" extensions. The "lst" file is optional. It is very useful to the program because it lists all the opcodes and addresses as well as errors that the assemblers detected.
The "asm" source file contains the program code created in Step 1. It is fed to an 8051 assembler. The assembler then converts the assembly language instructions into machine code instructions and produces an .obj file (object file) and a .lst file (list file). It is also called as a source file, that's why some assemblers require that this file have the "src" extensions. The "lst" file is optional. It is very useful to the program because it lists all the opcodes and addresses as well as errors that the assemblers detected.
Assemblers require a third step called linking. The link program takes one or more object files and produces an absolute object file with the extension "abs".
Assemblers require a third step called linking. The link program takes one or more object files and produces an absolute object file with the extension "abs".
Next, the "abs" file is fed to a program called "OH" (object to hex converter), which creates a file with the extension "hex" that is ready to burn in to the ROM.
Next, the "abs" file is fed to a program called "OH" (object to hex converter), which creates a file with the extension "hex" that is ready to burn in to the ROM.
The 8051 microcontroller contains a single data type of 8-bits, and each register is also of 8-bits size. The programmer has to break down data larger than 8-bits (00 to FFH, or to 255 in decimal) so that it can be processed by the CPU.
The DB directive is the most widely used data directive in the assembler. It is used to define the 8-bit data. It can also be used to define decimal, binary, hex, or ASCII formats data. For decimal, the "D" after the decimal number is optional, but it is required for "B" (binary) and "Hl" (hexadecimal).
To indicate ASCII, simply place the characters in quotation marks ('like this'). The assembler generates ASCII code for the numbers/characters automatically. The DB directive is the only directive that can be used to define ASCII strings larger than two characters; therefore, it should be used for all the ASCII data definitions. Some examples of DB are given below −
ORG 500H
DATA1: DB 28 ;DECIMAL (1C in hex)
DATA2: DB 00110101B ;BINARY (35 in hex)
DATA3: DB 39H ;HEX
ORG 510H
DATA4: DB "2591" ;ASCII NUMBERS
ORG 520H
DATA6: DA "MY NAME IS Michael" ;ASCII CHARACTERS
Either single or double quotes can be used around ASCII strings. DB is also used to allocate memory in byte-sized chunks.
Some of the directives of 8051 are as follows −
ORG (origin) − The origin directive is used to indicate the beginning of the address. It takes the numbers in hexa or decimal format. If H is provided after the number, the number is treated as hexa, otherwise decimal. The assembler converts the decimal number to hexa.
ORG (origin) − The origin directive is used to indicate the beginning of the address. It takes the numbers in hexa or decimal format. If H is provided after the number, the number is treated as hexa, otherwise decimal. The assembler converts the decimal number to hexa.
EQU (equate) − It is used to define a constant without occupying a memory location. EQU associates a constant value with a data label so that the label appears in the program, its constant value will be substituted for the label. While executing the instruction "MOV R3, #COUNT", the register R3 will be loaded with the value 25 (notice the # sign). The advantage of using EQU is that the programmer can change it once and the assembler will change all of its occurrences; the programmer does not have to search the entire program.
EQU (equate) − It is used to define a constant without occupying a memory location. EQU associates a constant value with a data label so that the label appears in the program, its constant value will be substituted for the label. While executing the instruction "MOV R3, #COUNT", the register R3 will be loaded with the value 25 (notice the # sign). The advantage of using EQU is that the programmer can change it once and the assembler will change all of its occurrences; the programmer does not have to search the entire program.
END directive − It indicates the end of the source (asm) file. The END directive is the last line of the program; anything after the END directive is ignored by the assembler.
END directive − It indicates the end of the source (asm) file. The END directive is the last line of the program; anything after the END directive is ignored by the assembler.
All the labels in assembly language must follow the rules given below −
Each label name must be unique. The names used for labels in assembly language programming consist of alphabetic letters in both uppercase and lowercase, number 0 through 9, and special characters such as question mark (?), period (.), at the rate @, underscore (_), and dollar($).
Each label name must be unique. The names used for labels in assembly language programming consist of alphabetic letters in both uppercase and lowercase, number 0 through 9, and special characters such as question mark (?), period (.), at the rate @, underscore (_), and dollar($).
The first character should be in alphabetical character; it cannot be a number.
The first character should be in alphabetical character; it cannot be a number.
Reserved words cannot be used as a label in the program. For example, ADD and MOV words are the reserved words, since they are instruction mnemonics.
Reserved words cannot be used as a label in the program. For example, ADD and MOV words are the reserved words, since they are instruction mnemonics.
Registers are used in the CPU to store information on temporarily basis which could be data to be processed, or an address pointing to the data which is to be fetched. In 8051, there is one data type is of 8-bits, from the MSB (most significant bit) D7 to the LSB (least significant bit) D0. With 8-bit data type, any data type larger than 8-bits must be broken into 8-bit chunks before it is processed.
The most widely used registers of the 8051 are A (accumulator), B, R0-R7, DPTR (data pointer), and PC (program counter). All these registers are of 8-bits, except DPTR and PC.
We will discuss the following types of storage registers here −
Accumulator
R register
B register
Data Pointer (DPTR)
Program Counter (PC)
Stack Pointer (SP)
The accumulator, register A, is used for all arithmetic and logic operations. If the accumulator is not present, then every result of each calculation (addition, multiplication, shift, etc.) is to be stored into the main memory. Access to main memory is slower than access to a register like the accumulator because the technology used for the large main memory is slower (but cheaper) than that used for a register.
The "R" registers are a set of eight registers, namely, R0, R1 to R7. These registers function as auxiliary or temporary storage registers in many operations. Consider an example of the sum of 10 and 20. Store a variable 10 in an accumulator and another variable 20 in, say, register R4. To process the addition operation, execute the following command −
ADD A,R4
After executing this instruction, the accumulator will contain the value 30. Thus "R" registers are very important auxiliary or helper registers. The Accumulator alone would not be very useful if it were not for these "R" registers. The "R" registers are meant for temporarily storage of values.
Let us take another example. We will add the values in R1 and R2 together and then subtract the values of R3 and R4 from the result.
MOV A,R3 ;Move the value of R3 into the accumulator
ADD A,R4 ;Add the value of R4
MOV R5,A ;Store the resulting value temporarily in R5
MOV A,R1 ;Move the value of R1 into the accumulator
ADD A,R2 ;Add the value of R2
SUBB A,R5 ;Subtract the value of R5 (which now contains R3 + R4)
As you can see, we used R5 to temporarily hold the sum of R3 and R4. Of course, this is not the most efficient way to calculate (R1 + R2) – (R3 + R4), but it does illustrate the use of the "R" registers as a way to store values temporarily.
The "B" register is very similar to the Accumulator in the sense that it may hold an 8-bit (1-byte) value. The "B" register is used only by two 8051 instructions: MUL AB and DIV AB. To quickly and easily multiply or divide A by another number, you may store the other number in "B" and make use of these two instructions. Apart from using MUL and DIV instructions, the "B" register is often used as yet another temporary storage register, much like a ninth R register.
The Data Pointer (DPTR) is the 8051’s only user-accessible 16-bit (2-byte) register. The Accumulator, R0–R7 registers and B register are 1-byte value registers. DPTR is meant for pointing to data. It is used by the 8051 to access external memory using the address indicated by DPTR. DPTR is the only 16-bit register available and is often used to store 2-byte values.
The Program Counter (PC) is a 2-byte address which tells the 8051 where the next instruction to execute can be found in the memory. PC starts at 0000h when the 8051 initializes and is incremented every time after an instruction is executed. PC is not always incremented by 1. Some instructions may require 2 or 3 bytes; in such cases, the PC will be incremented by 2 or 3.
Branch, jump, and interrupt operations load the Program Counter with an address other than the next sequential location. Activating a power-on reset will cause all values in the register to be lost. It means the value of the PC is 0 upon reset, forcing the CPU to fetch the first opcode from the ROM location 0000. It means we must place the first byte of upcode in ROM location 0000 because that is where the CPU expects to find the first instruction.
The Stack Pointer, like all registers except DPTR and PC, may hold an 8-bit (1-byte) value. The Stack Pointer tells the location from where the next value is to be removed from the stack. When a value is pushed onto the stack, the value of SP is incremented and then the value is stored at the resulting memory location. When a value is popped off the stack, the value is returned from the memory location indicated by SP, and then the value of SP is decremented.
This order of operation is important. SP will be initialized to 07h when the 8051 is initialized. If a value is pushed onto the stack at the same time, the value will be stored in the internal RAM address 08h because the 8051 will first increment the value of SP (from 07h to 08h) and then will store the pushed value at that memory address (08h). SP is modified directly by the 8051 by six instructions: PUSH, POP, ACALL, LCALL, RET, and RETI.
Some family members of 8051 have only 4K bytes of on-chip ROM (e.g. 8751, AT8951); some have 8K ROM like AT89C52, and there are some family members with 32K bytes and 64K bytes of on-chip ROM such as Dallas Semiconductor. The point to remember is that no member of the 8051 family can access more than 64K bytes of opcode since the program counter in 8051 is a 16-bit register (0000 to FFFF address).
The first location of the program ROM inside the 8051 has the address of 0000H, whereas the last location can be different depending on the size of the ROM on the chip. Among the 8051 family members, AT8951 has $k bytes of on-chip ROM having a memory address of 0000 (first location) to 0FFFH (last location).
The program status word (PSW) register is an 8-bit register, also known as flag register. It is of 8-bit wide but only 6-bit of it is used. The two unused bits are user-defined flags. Four of the flags are called conditional flags, which means that they indicate a condition which results after an instruction is executed. These four are CY (Carry), AC (auxiliary carry), P (parity), and OV (overflow). The bits RS0 and RS1 are used to change the bank registers. The following figure shows the program status word register.
The PSW Register contains that status bits that reflect the current status of the CPU.
We can select the corresponding Register Bank bit using RS0 and RS1 bits.
CY, the carry flag − This carry flag is set (1) whenever there is a carry out from the D7 bit. It is affected after an 8-bit addition or subtraction operation. It can also be reset to 1 or 0 directly by an instruction such as "SETB C" and "CLR C" where "SETB" stands for set bit carry and "CLR" stands for clear carry.
CY, the carry flag − This carry flag is set (1) whenever there is a carry out from the D7 bit. It is affected after an 8-bit addition or subtraction operation. It can also be reset to 1 or 0 directly by an instruction such as "SETB C" and "CLR C" where "SETB" stands for set bit carry and "CLR" stands for clear carry.
AC, auxiliary carry flag − If there is a carry from D3 and D4 during an ADD or SUB operation, the AC bit is set; otherwise, it is cleared. It is used for the instruction to perform binary coded decimal arithmetic.
AC, auxiliary carry flag − If there is a carry from D3 and D4 during an ADD or SUB operation, the AC bit is set; otherwise, it is cleared. It is used for the instruction to perform binary coded decimal arithmetic.
P, the parity flag − The parity flag represents the number of 1's in the accumulator register only. If the A register contains odd number of 1's, then P = 1; and for even number of 1's, P = 0.
P, the parity flag − The parity flag represents the number of 1's in the accumulator register only. If the A register contains odd number of 1's, then P = 1; and for even number of 1's, P = 0.
OV, the overflow flag − This flag is set whenever the result of a signed number operation is too large causing the high-order bit to overflow into the sign bit. It is used only to detect errors in signed arithmetic operations.
OV, the overflow flag − This flag is set whenever the result of a signed number operation is too large causing the high-order bit to overflow into the sign bit. It is used only to detect errors in signed arithmetic operations.
Show the status of CY, AC, and P flags after the addition of 9CH and 64H in the following instruction.
MOV A, #9CH
ADD A, # 64H
Solution: 9C 10011100
+64 01100100
100 00000000
CY = 1 since there is a carry beyond D7 bit
AC = 0 since there is a carry from D3 to D4
P = 0 because the accumulator has even number of 1's
The 8051 microcontroller has a total of 128 bytes of RAM. We will discuss about the allocation of these 128 bytes of RAM and examine their usage as stack and register.
The 128 bytes of RAM inside the 8051 are assigned the address 00 to 7FH. They can be accessed directly as memory locations and are divided into three different groups as follows −
32 bytes from 00H to 1FH locations are set aside for register banks and the stack.
32 bytes from 00H to 1FH locations are set aside for register banks and the stack.
16 bytes from 20H to 2FH locations are set aside for bit-addressable read/write memory.
16 bytes from 20H to 2FH locations are set aside for bit-addressable read/write memory.
80 bytes from 30H to 7FH locations are used for read and write storage; it is called as scratch pad. These 80 locations RAM are widely used for the purpose of storing data and parameters by 8051 programmers.
80 bytes from 30H to 7FH locations are used for read and write storage; it is called as scratch pad. These 80 locations RAM are widely used for the purpose of storing data and parameters by 8051 programmers.
A total of 32 bytes of RAM are set aside for the register banks and the stack. These 32 bytes are divided into four register banks in which each bank has 8 registers, R0–R7. RAM locations from 0 to 7 are set aside for bank 0 of R0–R7 where R0 is RAM location 0, R1 is RAM location 1, R2 is location 2, and so on, until the memory location 7, which belongs to R7 of bank 0.
The second bank of registers R0–R7 starts at RAM location 08 and goes to locations OFH. The third bank of R0–R7 starts at memory location 10H and goes to location to 17H. Finally, RAM locations 18H to 1FH are set aside for the fourth bank of R0–R7.
If RAM locations 00–1F are set aside for the four registers banks, which register bank of R0–R7 do we have access to when the 8051 is powered up? The answer is register bank 0; that is, RAM locations from 0 to 7 are accessed with the names R0 to R7 when programming the 8051. Because it is much easier to refer these RAM locations by names such as R0 to R7, rather than by their memory locations.
Register bank 0 is the default when the 8051 is powered up. We can switch to the other banks using PSW register. D4 and D3 bits of the PSW are used to select the desired register bank, since they can be accessed by the bit addressable instructions SETB and CLR. For example, "SETB PSW.3" will set PSW.3 = 1 and select the bank register 1.
The stack is a section of a RAM used by the CPU to store information such as data or memory address on temporary basis. The CPU needs this storage area considering limited number of registers.
As the stack is a section of a RAM, there are registers inside the CPU to point to it. The register used to access the stack is known as the stack pointer register. The stack pointer in the 8051 is 8-bits wide, and it can take a value of 00 to FFH. When the 8051 is initialized, the SP register contains the value 07H. This means that the RAM location 08 is the first location used for the stack. The storing operation of a CPU register in the stack is known as a PUSH, and getting the contents from the stack back into a CPU register is called a POP.
In the 8051, the stack pointer (SP) points to the last used location of the stack. When data is pushed onto the stack, the stack pointer (SP) is incremented by 1. When PUSH is executed, the contents of the register are saved on the stack and SP is incremented by 1. To push the registers onto the stack, we must use their RAM addresses. For example, the instruction "PUSH 1" pushes register R1 onto the stack.
Popping the contents of the stack back into a given register is the opposite to the process of pushing. With every pop operation, the top byte of the stack is copied to the register specified by the instruction and the stack pointer is decremented once.
The flow of program proceeds in a sequential manner, from one instruction to the next instruction, unless a control transfer instruction is executed. The various types of control transfer instruction in assembly language include conditional or unconditional jumps and call instructions.
Repeating a sequence of instructions a certain number of times is called a loop. An instruction DJNZ reg, label is used to perform a Loop operation. In this instruction, a register is decremented by 1; if it is not zero, then 8051 jumps to the target address referred to by the label.
The register is loaded with the counter for the number of repetitions prior to the start of the loop. In this instruction, both the registers decrement and the decision to jump are combined into a single instruction. The registers can be any of R0–R7. The counter can also be a RAM location.
Multiply 25 by 10 using the technique of repeated addition.
Solution − Multiplication can be achieved by adding the multiplicand repeatedly, as many times as the multiplier. For example,
25 * 10 = 250(FAH)
25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 = 250
MOV A,#0 ;A = 0,clean ACC
MOV R2,#10 ; the multiplier is replaced in R2
Add A,#25 ;add the multiplicand to the ACC
AGAIN:DJNZ R2,
AGAIN:repeat until R2 = 0 (10 times)
MOV R5 , A ;save A in R5 ;R5 (FAH)
Drawback in 8051 − Looping action with the instruction DJNZ Reg label is limited to 256 iterations only. If a conditional jump is not taken, then the instruction following the jump is executed.
When we use a loop inside another loop, it is called a nested loop. Two registers are used to hold the count when the maximum count is limited to 256. So we use this method to repeat the action more times than 256.
Example
Write a program to −
Load the accumulator with the value 55H.
Complement the ACC 700 times.
Solution − Since 700 is greater than 255 (the maximum capacity of any register), two registers are used to hold the count. The following code shows how to use two registers, R2 and R3, for the count.
MOV A,#55H ;A = 55H
NEXT: MOV R3,#10 ;R3 the outer loop counter
AGAIN:MOV R2,#70 ;R2 the inner loop counter
CPL A ;complement
The following table lists the conditional jumps used in 8051 −
JZ (jump if A = 0) − In this instruction, the content of the accumulator is checked. If it is zero, then the 8051 jumps to the target address. JZ instruction can be used only for the accumulator, it does not apply to any other register.
JZ (jump if A = 0) − In this instruction, the content of the accumulator is checked. If it is zero, then the 8051 jumps to the target address. JZ instruction can be used only for the accumulator, it does not apply to any other register.
JNZ (jump if A is not equal to 0) − In this instruction, the content of the accumulator is checked to be non-zero. If it is not zero, then the 8051 jumps to the target address.
JNZ (jump if A is not equal to 0) − In this instruction, the content of the accumulator is checked to be non-zero. If it is not zero, then the 8051 jumps to the target address.
JNC (Jump if no carry, jumps if CY = 0) − The Carry flag bit in the flag (or PSW) register is used to make the decision whether to jump or not "JNC label". The CPU looks at the carry flag to see if it is raised (CY = 1). If it is not raised, then the CPU starts to fetch and execute instructions from the address of the label. If CY = 1, it will not jump but will execute the next instruction below JNC.
JNC (Jump if no carry, jumps if CY = 0) − The Carry flag bit in the flag (or PSW) register is used to make the decision whether to jump or not "JNC label". The CPU looks at the carry flag to see if it is raised (CY = 1). If it is not raised, then the CPU starts to fetch and execute instructions from the address of the label. If CY = 1, it will not jump but will execute the next instruction below JNC.
JC (Jump if carry, jumps if CY = 1) − If CY = 1, it jumps to the target address.
JC (Jump if carry, jumps if CY = 1) − If CY = 1, it jumps to the target address.
JB (jump if bit is high)
JB (jump if bit is high)
JNB (jump if bit is low)
JNB (jump if bit is low)
Note − It must be noted that all conditional jumps are short jumps, i.e., the address of the target must be within –128 to +127 bytes of the contents of the program counter.
There are two unconditional jumps in 8051 −
LJMP (long jump) − LJMP is 3-byte instruction in which the first byte represents opcode, and the second and third bytes represent the 16-bit address of the target location. The 2-byte target address is to allow a jump to any memory location from 0000 to FFFFH.
LJMP (long jump) − LJMP is 3-byte instruction in which the first byte represents opcode, and the second and third bytes represent the 16-bit address of the target location. The 2-byte target address is to allow a jump to any memory location from 0000 to FFFFH.
SJMP (short jump) − It is a 2-byte instruction where the first byte is the opcode and the second byte is the relative address of the target location. The relative address ranges from 00H to FFH which is divided into forward and backward jumps; that is, within –128 to +127 bytes of memory relative to the address of the current PC (program counter). In case of forward jump, the target address can be within a space of 127 bytes from the current PC. In case of backward jump, the target address can be within –128 bytes from the current PC.
SJMP (short jump) − It is a 2-byte instruction where the first byte is the opcode and the second byte is the relative address of the target location. The relative address ranges from 00H to FFH which is divided into forward and backward jumps; that is, within –128 to +127 bytes of memory relative to the address of the current PC (program counter). In case of forward jump, the target address can be within a space of 127 bytes from the current PC. In case of backward jump, the target address can be within –128 bytes from the current PC.
All conditional jumps (JNC, JZ, and DJNZ) are short jumps because they are 2-byte instructions. In these instructions, the first byte represents opcode and the second byte represents the relative address. The target address is always relative to the value of the program counter. To calculate the target address, the second byte is added to the PC of the instruction immediately below the jump. Take a look at the program given below −
Line PC Op-code Mnemonic Operand
1 0000 ORG 0000
2 0000 7800 MOV R0,#003
3 0002 7455 MOV A,#55H0
4 0004 6003 JZ NEXT
5 0006 08 INC R0
6 0007 04 AGAIN: INC A
7 0008 04 INC A
8 0009 2477 NEXT: ADD A, #77h
9 000B 5005 JNC OVER
10 000D E4 CLR A
11 000E F8 MOV R0, A
12 000F F9 MOV R1, A
13 0010 FA MOV R2, A
14 0011 FB MOV R3, A
15 0012 2B OVER: ADD A, R3
16 0013 50F2 JNC AGAIN
17 0015 80FE HERE: SJMP HERE
18 0017 END
In case of a forward jump, the displacement value is a positive number between 0 to 127 (00 to 7F in hex). However, for a backward jump, the displacement is a negative value of 0 to –128.
CALL is used to call a subroutine or method. Subroutines are used to perform operations or tasks that need to be performed frequently. This makes a program more structured and saves memory space. There are two instructions − LCALL and ACALL.
LCALL is a 3-byte instruction where the first byte represents the opcode and the second and third bytes are used to provide the address of the target subroutine. LCALL can be used to call subroutines which are available within the 64K-byte address space of the 8051.
To make a successful return to the point after execution of the called subroutine, the CPU saves the address of the instruction immediately below the LCALL on the stack. Thus, when a subroutine is called, the control is transferred to that subroutine, and the processor saves the PC (program counter) on the stack and begins to fetch instructions from the new location. The instruction RET (return) transfers the control back to the caller after finishing execution of the subroutine. Every subroutine uses RET as the last instruction.
ACALL is a 2-byte instruction, in contrast to LCALL which is 3 bytes. The target address of the subroutine must be within 2K bytes because only 11 bits of the 2 bytes are used for address. The difference between the ACALL and LCALL is that the target address for LCALL can be anywhere within the 64K-bytes address space of the 8051, while the target address of CALL is within a 2K-byte range.
An addressing mode refers to how you are addressing a given memory location. There are five different ways or five addressing modes to execute this instruction which are as follows −
Immediate addressing mode
Direct addressing mode
Register direct addressing mode
Register indirect addressing mode
Indexed addressing mode
Let's begin with an example.
MOV A, #6AH
In general, we can write,
MOV A, #data
It is termed as immediate because 8-bit data is transferred immediately to the accumulator (destination operand).
The following illustration describes the above instruction and its execution. The opcode 74H is saved at 0202 address. The data 6AH is saved at 0203 address in the program memory. After reading the opcode 74H, the data at the next program memory address is transferred to accumulator A (E0H is the address of accumulator). Since the instruction is of 2-bytes and is executed in one cycle, the program counter will be incremented by 2 and will point to 0204 of the program memory.
Note − The '#' symbol before 6AH indicates that the operand is a data (8 bit). In the absence of '#', the hexadecimal number would be taken as an address.
This is another way of addressing an operand. Here, the address of the data (source data) is given as an operand. Let’s take an example.
MOV A, 04H
The register bank#0 (4th register) has the address 04H. When the MOV instruction is executed, the data stored in register 04H is moved to the accumulator. As the register 04H holds the data 1FH, 1FH is moved to the accumulator.
Note − We have not used '#' in direct addressing mode, unlike immediate mode. If we had used '#', the data value 04H would have been transferred to the accumulator instead of 1FH.
Now, take a look at the following illustration. It shows how the instruction gets executed.
As shown in the above illustration, this is a 2-byte instruction which requires 1 cycle to complete. The PC will be incremented by 2 and will point to 0204. The opcode for the instruction MOV A, address is E5H. When the instruction at 0202 is executed (E5H), the accumulator is made active and ready to receive data. Then the PC goes to the next address as 0203 and looks up the address of the location of 04H where the source data (to be transferred to accumulator) is located. At 04H, the control finds the data 1F and transfers it to the accumulator and hence the execution is completed.
In this addressing mode, we use the register name directly (as source operand). Let us try to understand with the help of an example.
MOV A, R4
At a time, the registers can take values from R0 to R7. There are 32 such registers. In order to use 32 registers with just 8 variables to address registers, register banks are used. There are 4 register banks named from 0 to 3. Each bank comprises of 8 registers named from R0 to R7.
At a time, a single register bank can be selected. Selection of a register bank is made possible through a Special Function Register (SFR) named Processor Status Word (PSW). PSW is an 8-bit SFR where each bit can be programmed as required. Bits are designated from PSW.0 to PSW.7. PSW.3 and PSW.4 are used to select register banks.
Now, take a look at the following illustration to get a clear understanding of how it works.
Opcode EC is used for MOV A, R4. The opcode is stored at the address 0202 and when it is executed, the control goes directly to R4 of the respected register bank (that is selected in PSW). If register bank #0 is selected, then the data from R4 of register bank #0 will be moved to the accumulator. Here 2F is stored at 04H. 04H represents the address of R4 of register bank #0.
Data (2F) movement is highlighted in bold. 2F is getting transferred to the accumulator from data memory location 0C H and is shown as dotted line. 0CH is the address location of Register 4 (R4) of register bank #1. The instruction above is 1 byte and requires 1 cycle for complete execution. What it means is, you can save program memory by using register direct addressing mode.
In this addressing mode, the address of the data is stored in the register as operand.
MOV A, @R0
Here the value inside R0 is considered as an address, which holds the data to be transferred to the accumulator. Example: If R0 has the value 20H, and data 2FH is stored at the address 20H, then the value 2FH will get transferred to the accumulator after executing this instruction. See the following illustration.
So the opcode for MOV A, @R0 is E6H. Assuming that the register bank #0 is selected, the R0 of register bank #0 holds the data 20H. Program control moves to 20H where it locates the data 2FH and it transfers 2FH to the accumulator. This is a 1-byte instruction and the program counter increments by 1 and moves to 0203 of the program memory.
Note − Only R0 and R1 are allowed to form a register indirect addressing instruction. In other words, the programmer can create an instruction either using @R0 or @R1. All register banks are allowed.
We will take two examples to understand the concept of indexed addressing mode. Take a look at the following instructions −
MOVC A, @A+DPTR
and
MOVC A, @A+PC
where DPTR is the data pointer and PC is the program counter (both are 16-bit registers). Consider the first example.
MOVC A, @A+DPTR
The source operand is @A+DPTR. It contains the source data from this location. Here we are adding the contents of DPTR with the current content of the accumulator. This addition will give a new address which is the address of the source data. The data pointed by this address is then transferred to the accumulator.
The opcode is 93H. DPTR has the value 01FE, where 01 is located in DPH (higher 8 bits) and FE is located in DPL (lower 8 bits). Accumulator has the value 02H. Then a 16-bit addition is performed and 01FE H+02H results in 0200 H. Data at the location 0200H will get transferred to the accumulator. The previous value inside the accumulator (02H) will be replaced with the new data from 0200H. The new data in the accumulator is highlighted in the illustration.
This is a 1-byte instruction with 2 cycles needed for execution and the execution time required for this instruction is high compared to previous instructions (which were all 1 cycle each).
The other example MOVC A, @A+PC works the same way as the above example. Instead of adding DPTR with the accumulator, here the data inside the program counter (PC) is added with the accumulator to obtain the target address.
A Special Function Register (or Special Purpose Register, or simply Special Register) is a register within a microprocessor that controls or monitors the various functions of a microprocessor. As the special registers are closely tied to some special function or status of the processor, they might not be directly writable by normal instructions (like add, move, etc.). Instead, some special registers in some processor architectures require special instructions to modify them.
In the 8051, register A, B, DPTR, and PSW are a part of the group of registers commonly referred to as SFR (special function registers). An SFR can be accessed by its name or by its address.
The following table shows a list of SFRs and their addresses.
Consider the following two points about the SFR addresses.
A special function register can have an address between 80H to FFH. These addresses are above 80H, as the addresses from 00 to 7FH are the addresses of RAM memory inside the 8051.
A special function register can have an address between 80H to FFH. These addresses are above 80H, as the addresses from 00 to 7FH are the addresses of RAM memory inside the 8051.
Not all the address space of 80 to FF are used by the SFR. Unused locations, 80H to FFH, are reserved and must not be used by the 8051 programmer.
Not all the address space of 80 to FF are used by the SFR. Unused locations, 80H to FFH, are reserved and must not be used by the 8051 programmer.
In the following example, the SFR registers’ names are replaced with their addresses.
We can select the corresponding Register Bank bit using RS0 and RS1 bits.
The Program Status Word (PSW) contains status bits to reflect the current state of the CPU. The 8051 variants provide one special function register, PSW, with this status information. The 8251 provides two additional status flags, Z and N, which are available in a second special function register called PSW1.
A timer is a specialized type of clock which is used to measure time intervals. A timer that counts from zero upwards for measuring time elapsed is often called a stopwatch. It is a device that counts down from a specified time interval and used to generate a time delay, for example, an hourglass is a timer.
A counter is a device that stores (and sometimes displays) the number of times a particular event or process occurred, with respect to a clock signal. It is used to count the events happening outside the microcontroller. In electronics, counters can be implemented quite easily using register-type circuits such as a flip-flop.
The points that differentiate a timer from a counter are as follows −
The 8051 has two timers, Timer 0 and Timer 1. They can be used as timers or as event counters. Both Timer 0 and Timer 1 are 16-bit wide. Since the 8051 follows an 8-bit architecture, each 16 bit is accessed as two separate registers of low-byte and high-byte.
The 16-bit register of Timer 0 is accessed as low- and high-byte. The low-byte register is called TL0 (Timer 0 low byte) and the high-byte register is called TH0 (Timer 0 high byte). These registers can be accessed like any other register. For example, the instruction MOV TL0, #4H moves the value into the low-byte of Timer #0.
The 16-bit register of Timer 1 is accessed as low- and high-byte. The low-byte register is called TL1 (Timer 1 low byte) and the high-byte register is called TH1 (Timer 1 high byte). These registers can be accessed like any other register. For example, the instruction MOV TL1, #4H moves the value into the low-byte of Timer 1.
Both Timer 0 and Timer 1 use the same register to set the various timer operation modes. It is an 8-bit register in which the lower 4 bits are set aside for Timer 0 and the upper four bits for Timers. In each case, the lower 2 bits are used to set the timer mode in advance and the upper 2 bits are used to specify the location.
Gate − When set, the timer only runs while INT(0,1) is high.
C/T − Counter/Timer select bit.
M1 − Mode bit 1.
M0 − Mode bit 0.
Every timer has a means of starting and stopping. Some timers do this by software, some by hardware, and some have both software and hardware controls. 8051 timers have both software and hardware controls. The start and stop of a timer is controlled by software using the instruction SETB TR1 and CLR TR1 for timer 1, and SETB TR0 and CLR TR0 for timer 0.
The SETB instruction is used to start it and it is stopped by the CLR instruction. These instructions start and stop the timers as long as GATE = 0 in the TMOD register. Timers can be started and stopped by an external source by making GATE = 1 in the TMOD register.
This bit in the TMOD register is used to decide whether a timer is used as a delay generator or an event manager. If C/T = 0, it is used as a timer for timer delay generation. The clock source to create the time delay is the crystal frequency of the 8051. If C/T = 0, the crystal frequency attached to the 8051 also decides the speed at which the 8051 timer ticks at a regular interval.
Timer frequency is always 1/12th of the frequency of the crystal attached to the 8051. Although various 8051 based systems have an XTAL frequency of 10 MHz to 40 MHz, we normally work with the XTAL frequency of 11.0592 MHz. It is because the baud rate for serial communication of the 8051.XTAL = 11.0592 allows the 8051 system to communicate with the PC with no errors.
Both Timer 1 and Timer 0 in Mode 0 operate as 8-bit counters (with a divide-by-32 prescaler). Timer register is configured as a 13-bit register consisting of all the 8 bits of TH1 and the lower 5 bits of TL1. The upper 3 bits of TL1 are indeterminate and should be ignored. Setting the run flag (TR1) does not clear the register. The timer interrupt flag TF1 is set when the count rolls over from all 1s to all 0s. Mode 0 operation is the same for Timer 0 as it is for Timer 1.
Timer mode "1" is a 16-bit timer and is a commonly used mode. It functions in the same way as 13-bit mode except that all 16 bits are used. TLx is incremented starting from 0 to a maximum 255. Once the value 255 is reached, TLx resets to 0 and then THx is incremented by 1. As being a full 16-bit timer, the timer may contain up to 65536 distinct values and it will overflow back to 0 after 65,536 machine cycles.
Both the timer registers are configured as 8-bit counters (TL1 and TL0) with automatic reload. Overflow from TL1 (TL0) sets TF1 (TF0) and also reloads TL1 (TL0) with the contents of Th1 (TH0), which is preset by software. The reload leaves TH1 (TH0) unchanged.
The benefit of auto-reload mode is that you can have the timer to always contain a value from 200 to 255. If you use mode 0 or 1, you would have to check in the code to see the overflow and, in that case, reset the timer to 200. In this case, precious instructions check the value and/or get reloaded. In mode 2, the microcontroller takes care of this. Once you have configured a timer in mode 2, you don't have to worry about checking to see if the timer has overflowed, nor do you have to worry about resetting the value because the microcontroller hardware will do it all for you. The auto-reload mode is used for establishing a common baud rate.
Timer mode "3" is known as split-timer mode. When Timer 0 is placed in mode 3, it becomes two separate 8-bit timers. Timer 0 is TL0 and Timer 1 is TH0. Both the timers count from 0 to 255 and in case of overflow, reset back to 0. All the bits that are of Timer 1 will now be tied to TH0.
When Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be set in modes 0, 1 or 2, but it cannot be started/stopped as the bits that do that are now linked to TH0. The real timer 1 will be incremented with every machine cycle.
Decide the timer mode. Consider a 16-bit timer that runs continuously, and is independent of any external pins.
Initialize the TMOD SFR. Use the lowest 4 bits of TMOD and consider Timer 0. Keep the two bits, GATE 0 and C/T 0, as 0, since we want the timer to be independent of the external pins. As 16-bit mode is timer mode 1, clear T0M1 and set T0M0. Effectively, the only bit to turn on is bit 0 of TMOD. Now execute the following instruction −
MOV TMOD,#01h
Now, Timer 0 is in 16-bit timer mode, but the timer is not running. To start the timer in running mode, set the TR0 bit by executing the following instruction −
SETB TR0
Now, Timer 0 will immediately start counting, being incremented once every machine cycle.
A 16-bit timer can be read in two ways. Either read the actual value of the timer as a 16-bit number, or you detect when the timer has overflowed.
When a timer overflows from its highest value to 0, the microcontroller automatically sets the TFx bit in the TCON register. So instead of checking the exact value of the timer, the TFx bit can be checked. If TF0 is set, then Timer 0 has overflowed; if TF1 is set, then Timer 1 has overflowed.
An interrupt is a signal to the processor emitted by hardware or software indicating an event that needs immediate attention. Whenever an interrupt occurs, the controller completes the execution of the current instruction and starts the execution of an Interrupt Service Routine (ISR) or Interrupt Handler. ISR tells the processor or controller what to do when the interrupt occurs. The interrupts can be either hardware interrupts or software interrupts.
A hardware interrupt is an electronic alerting signal sent to the processor from an external device, like a disk controller or an external peripheral. For example, when we press a key on the keyboard or move the mouse, they trigger hardware interrupts which cause the processor to read the keystroke or mouse position.
A software interrupt is caused either by an exceptional condition or a special instruction in the instruction set which causes an interrupt when it is executed by the processor. For example, if the processor's arithmetic logic unit runs a command to divide a number by zero, to cause a divide-by-zero exception, thus causing the computer to abandon the calculation or display an error message. Software interrupt instructions work similar to subroutine calls.
The state of continuous monitoring is known as polling. The microcontroller keeps checking the status of other devices; and while doing so, it does no other operation and consumes all its processing time for monitoring. This problem can be addressed by using interrupts.
In the interrupt method, the controller responds only when an interruption occurs. Thus, the controller is not required to regularly monitor the status (flags, signals etc.) of interfaced and inbuilt devices.
Here is an analogy that differentiates an interrupt from polling −
For every interrupt, there must be an interrupt service routine (ISR), or interrupt handler. When an interrupt occurs, the microcontroller runs the interrupt service routine. For every interrupt, there is a fixed location in memory that holds the address of its interrupt service routine, ISR. The table of memory locations set aside to hold the addresses of ISRs is called as the Interrupt Vector Table.
There are six interrupts including RESET in 8051.
When the reset pin is activated, the 8051 jumps to the address location 0000. This is power-up reset.
When the reset pin is activated, the 8051 jumps to the address location 0000. This is power-up reset.
Two interrupts are set aside for the timers: one for timer 0 and one for timer 1. Memory locations are 000BH and 001BH respectively in the interrupt vector table.
Two interrupts are set aside for the timers: one for timer 0 and one for timer 1. Memory locations are 000BH and 001BH respectively in the interrupt vector table.
Two interrupts are set aside for hardware external interrupts. Pin no. 12 and Pin no. 13 in Port 3 are for the external hardware interrupts INT0 and INT1, respectively. Memory locations are 0003H and 0013H respectively in the interrupt vector table.
Two interrupts are set aside for hardware external interrupts. Pin no. 12 and Pin no. 13 in Port 3 are for the external hardware interrupts INT0 and INT1, respectively. Memory locations are 0003H and 0013H respectively in the interrupt vector table.
Serial communication has a single interrupt that belongs to both receive and transmit. Memory location 0023H belongs to this interrupt.
Serial communication has a single interrupt that belongs to both receive and transmit. Memory location 0023H belongs to this interrupt.
When an interrupt gets active, the microcontroller goes through the following steps −
The microcontroller closes the currently executing instruction and saves the address of the next instruction (PC) on the stack.
The microcontroller closes the currently executing instruction and saves the address of the next instruction (PC) on the stack.
It also saves the current status of all the interrupts internally (i.e., not on the stack).
It also saves the current status of all the interrupts internally (i.e., not on the stack).
It jumps to the memory location of the interrupt vector table that holds the address of the interrupts service routine.
It jumps to the memory location of the interrupt vector table that holds the address of the interrupts service routine.
The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it. It starts to execute the interrupt service subroutine, which is RETI (return from interrupt).
The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it. It starts to execute the interrupt service subroutine, which is RETI (return from interrupt).
Upon executing the RETI instruction, the microcontroller returns to the location where it was interrupted. First, it gets the program counter (PC) address from the stack by popping the top bytes of the stack into the PC. Then, it start to execute from that address.
Upon executing the RETI instruction, the microcontroller returns to the location where it was interrupted. First, it gets the program counter (PC) address from the stack by popping the top bytes of the stack into the PC. Then, it start to execute from that address.
Interrupt modules are of two types − level-triggered or edge-triggered.
Upon Reset, all the interrupts are disabled even if they are activated. The interrupts must be enabled using software in order for the microcontroller to respond to those interrupts.
IE (interrupt enable) register is responsible for enabling and disabling the interrupt. IE is a bitaddressable register.
EA − Global enable/disable.
EA − Global enable/disable.
- − Undefined.
- − Undefined.
ET2 − Enable Timer 2 interrupt.
ET2 − Enable Timer 2 interrupt.
ES − Enable Serial port interrupt.
ES − Enable Serial port interrupt.
ET1 − Enable Timer 1 interrupt.
ET1 − Enable Timer 1 interrupt.
EX1 − Enable External 1 interrupt.
EX1 − Enable External 1 interrupt.
ET0 − Enable Timer 0 interrupt.
ET0 − Enable Timer 0 interrupt.
EX0 − Enable External 0 interrupt.
EX0 − Enable External 0 interrupt.
To enable an interrupt, we take the following steps −
Bit D7 of the IE register (EA) must be high to allow the rest of register to take effect.
Bit D7 of the IE register (EA) must be high to allow the rest of register to take effect.
If EA = 1, interrupts will be enabled and will be responded to, if their corresponding bits in IE are high. If EA = 0, no interrupts will respond, even if their associated pins in the IE register are high.
If EA = 1, interrupts will be enabled and will be responded to, if their corresponding bits in IE are high. If EA = 0, no interrupts will respond, even if their associated pins in the IE register are high.
We can alter the interrupt priority by assigning the higher priority to any one of the interrupts. This is accomplished by programming a register called IP (interrupt priority).
The following figure shows the bits of IP register. Upon reset, the IP register contains all 0's. To give a higher priority to any of the interrupts, we make the corresponding bit in the IP register high.
What happens if the 8051 is executing an ISR that belongs to an interrupt and another one gets active? In such cases, a high-priority interrupt can interrupt a low-priority interrupt. This is known as interrupt inside interrupt. In 8051, a low-priority interrupt can be interrupted by a high-priority interrupt, but not by any another low-priority interrupt.
There are times when we need to test an ISR by way of simulation. This can be done with the simple instructions to set the interrupt high and thereby cause the 8051 to jump to the interrupt vector table. For example, set the IE bit as 1 for timer 1. An instruction SETB TF1 will interrupt the 8051 in whatever it is doing and force it to jump to the interrupt vector table.
65 Lectures
6.5 hours
Amit Rana
36 Lectures
4.5 hours
Amit Rana
33 Lectures
3 hours
Ashraf Said
23 Lectures
2 hours
Smart Logic Academy
66 Lectures
5.5 hours
NerdyElectronics
49 Lectures
8.5 hours
Rahul Shrivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2322,
"s": 1883,
"text": "A system is an arrangement in which all its unit assemble work together according to a set of rules. It can also be defined as a way of working, organizing or doing one or many tasks according to a fixed plan. For example, a watch is a time displaying system. Its components follow a set of rules to show time. If one of its parts fails, the watch will stop working. So we can say, in a system, all its subcomponents depend on each other."
},
{
"code": null,
"e": 2782,
"s": 2322,
"text": "As its name suggests, Embedded means something that is attached to another thing. An embedded system can be thought of as a computer hardware system having software embedded in it. An embedded system can be an independent system or it can be a part of a large system. An embedded system is a microcontroller or microprocessor based system which is designed to perform a specific task. For example, a fire alarm is an embedded system; it will sense only smoke."
},
{
"code": null,
"e": 2824,
"s": 2782,
"text": "An embedded system has three components −"
},
{
"code": null,
"e": 2841,
"s": 2824,
"text": "It has hardware."
},
{
"code": null,
"e": 2858,
"s": 2841,
"text": "It has hardware."
},
{
"code": null,
"e": 2887,
"s": 2858,
"text": "It has application software."
},
{
"code": null,
"e": 2916,
"s": 2887,
"text": "It has application software."
},
{
"code": null,
"e": 3270,
"s": 2916,
"text": "It has Real Time Operating system (RTOS) that supervises the application software and provide mechanism to let the processor run a process as per scheduling by following a plan to control the latencies. RTOS defines the way the system works. It sets the rules during the execution of application program. A small scale embedded system may not have RTOS."
},
{
"code": null,
"e": 3624,
"s": 3270,
"text": "It has Real Time Operating system (RTOS) that supervises the application software and provide mechanism to let the processor run a process as per scheduling by following a plan to control the latencies. RTOS defines the way the system works. It sets the rules during the execution of application program. A small scale embedded system may not have RTOS."
},
{
"code": null,
"e": 3741,
"s": 3624,
"text": "So we can define an embedded system as a Microcontroller based, software driven, reliable, real-time control system."
},
{
"code": null,
"e": 3901,
"s": 3741,
"text": "Single-functioned − An embedded system usually performs a specialized operation and does the same repeatedly. For example: A pager always functions as a pager."
},
{
"code": null,
"e": 4061,
"s": 3901,
"text": "Single-functioned − An embedded system usually performs a specialized operation and does the same repeatedly. For example: A pager always functions as a pager."
},
{
"code": null,
"e": 4456,
"s": 4061,
"text": "Tightly constrained − All computing systems have constraints on design metrics, but those on an embedded system can be especially tight. Design metrics is a measure of an implementation's features such as its cost, size, power, and performance. It must be of a size to fit on a single chip, must perform fast enough to process data in real time and consume minimum power to extend battery life."
},
{
"code": null,
"e": 4851,
"s": 4456,
"text": "Tightly constrained − All computing systems have constraints on design metrics, but those on an embedded system can be especially tight. Design metrics is a measure of an implementation's features such as its cost, size, power, and performance. It must be of a size to fit on a single chip, must perform fast enough to process data in real time and consume minimum power to extend battery life."
},
{
"code": null,
"e": 5286,
"s": 4851,
"text": "Reactive and Real time − Many embedded systems must continually react to changes in the system's environment and must compute certain results in real time without any delay. Consider an example of a car cruise controller; it continually monitors and reacts to speed and brake sensors. It must compute acceleration or de-accelerations repeatedly within a limited time; a delayed computation can result in failure to control of the car."
},
{
"code": null,
"e": 5721,
"s": 5286,
"text": "Reactive and Real time − Many embedded systems must continually react to changes in the system's environment and must compute certain results in real time without any delay. Consider an example of a car cruise controller; it continually monitors and reacts to speed and brake sensors. It must compute acceleration or de-accelerations repeatedly within a limited time; a delayed computation can result in failure to control of the car."
},
{
"code": null,
"e": 5797,
"s": 5721,
"text": "Microprocessors based − It must be microprocessor or microcontroller based."
},
{
"code": null,
"e": 5873,
"s": 5797,
"text": "Microprocessors based − It must be microprocessor or microcontroller based."
},
{
"code": null,
"e": 6001,
"s": 5873,
"text": "Memory − It must have a memory, as its software usually embeds in ROM. It does not need any secondary memories in the computer."
},
{
"code": null,
"e": 6129,
"s": 6001,
"text": "Memory − It must have a memory, as its software usually embeds in ROM. It does not need any secondary memories in the computer."
},
{
"code": null,
"e": 6213,
"s": 6129,
"text": "Connected − It must have connected peripherals to connect input and output devices."
},
{
"code": null,
"e": 6297,
"s": 6213,
"text": "Connected − It must have connected peripherals to connect input and output devices."
},
{
"code": null,
"e": 6412,
"s": 6297,
"text": "HW-SW systems − Software is used for more features and flexibility. Hardware is used for performance and security."
},
{
"code": null,
"e": 6527,
"s": 6412,
"text": "HW-SW systems − Software is used for more features and flexibility. Hardware is used for performance and security."
},
{
"code": null,
"e": 6547,
"s": 6527,
"text": "Easily Customizable"
},
{
"code": null,
"e": 6569,
"s": 6547,
"text": "Low power consumption"
},
{
"code": null,
"e": 6578,
"s": 6569,
"text": "Low cost"
},
{
"code": null,
"e": 6599,
"s": 6578,
"text": "Enhanced performance"
},
{
"code": null,
"e": 6623,
"s": 6599,
"text": "High development effort"
},
{
"code": null,
"e": 6645,
"s": 6623,
"text": "Larger time to market"
},
{
"code": null,
"e": 6722,
"s": 6645,
"text": "The following illustration shows the basic structure of an embedded system −"
},
{
"code": null,
"e": 6946,
"s": 6722,
"text": "Sensor − It measures the physical quantity and converts it to an electrical signal which can be read by an observer or by any electronic instrument like an A2D converter. A sensor stores the measured quantity to the memory."
},
{
"code": null,
"e": 7170,
"s": 6946,
"text": "Sensor − It measures the physical quantity and converts it to an electrical signal which can be read by an observer or by any electronic instrument like an A2D converter. A sensor stores the measured quantity to the memory."
},
{
"code": null,
"e": 7286,
"s": 7170,
"text": "A-D Converter − An analog-to-digital converter converts the analog signal sent by the sensor into a digital signal."
},
{
"code": null,
"e": 7402,
"s": 7286,
"text": "A-D Converter − An analog-to-digital converter converts the analog signal sent by the sensor into a digital signal."
},
{
"code": null,
"e": 7500,
"s": 7402,
"text": "Processor & ASICs − Processors process the data to measure the output and store it to the memory."
},
{
"code": null,
"e": 7598,
"s": 7500,
"text": "Processor & ASICs − Processors process the data to measure the output and store it to the memory."
},
{
"code": null,
"e": 7706,
"s": 7598,
"text": "D-A Converter − A digital-to-analog converter converts the digital data fed by the processor to analog data"
},
{
"code": null,
"e": 7814,
"s": 7706,
"text": "D-A Converter − A digital-to-analog converter converts the digital data fed by the processor to analog data"
},
{
"code": null,
"e": 7962,
"s": 7814,
"text": "Actuator − An actuator compares the output given by the D-A Converter to the actual (expected) output stored in it and stores the approved output. "
},
{
"code": null,
"e": 8110,
"s": 7962,
"text": "Actuator − An actuator compares the output given by the D-A Converter to the actual (expected) output stored in it and stores the approved output. "
},
{
"code": null,
"e": 8362,
"s": 8110,
"text": "Processor is the heart of an embedded system. It is the basic unit that takes inputs and produces an output after processing the data. For an embedded system designer, it is necessary to have the knowledge of both microprocessors and microcontrollers."
},
{
"code": null,
"e": 8400,
"s": 8362,
"text": "A processor has two essential units −"
},
{
"code": null,
"e": 8431,
"s": 8400,
"text": "Program Flow Control Unit (CU)"
},
{
"code": null,
"e": 8451,
"s": 8431,
"text": "Execution Unit (EU)"
},
{
"code": null,
"e": 8659,
"s": 8451,
"text": "The CU includes a fetch unit for fetching instructions from the memory. The EU has circuits that implement the instructions pertaining to data transfer operation and data conversion from one form to another."
},
{
"code": null,
"e": 8847,
"s": 8659,
"text": "The EU includes the Arithmetic and Logical Unit (ALU) and also the circuits that execute instructions for a program control task such as interrupt, or jump to another set of instructions."
},
{
"code": null,
"e": 8968,
"s": 8847,
"text": "A processor runs the cycles of fetch and executes the instructions in the same sequence as they are fetched from memory."
},
{
"code": null,
"e": 9016,
"s": 8968,
"text": "Processors can be of the following categories −"
},
{
"code": null,
"e": 9142,
"s": 9016,
"text": "General Purpose Processor (GPP)\n\nMicroprocessor\nMicrocontroller\nEmbedded Processor\nDigital Signal Processor\nMedia Processor\n\n"
},
{
"code": null,
"e": 9174,
"s": 9142,
"text": "General Purpose Processor (GPP)"
},
{
"code": null,
"e": 9189,
"s": 9174,
"text": "Microprocessor"
},
{
"code": null,
"e": 9205,
"s": 9189,
"text": "Microcontroller"
},
{
"code": null,
"e": 9224,
"s": 9205,
"text": "Embedded Processor"
},
{
"code": null,
"e": 9249,
"s": 9224,
"text": "Digital Signal Processor"
},
{
"code": null,
"e": 9265,
"s": 9249,
"text": "Media Processor"
},
{
"code": null,
"e": 9310,
"s": 9265,
"text": "Application Specific System Processor (ASSP)"
},
{
"code": null,
"e": 9355,
"s": 9310,
"text": "Application Specific System Processor (ASSP)"
},
{
"code": null,
"e": 9407,
"s": 9355,
"text": "Application Specific Instruction Processors (ASIPs)"
},
{
"code": null,
"e": 9459,
"s": 9407,
"text": "Application Specific Instruction Processors (ASIPs)"
},
{
"code": null,
"e": 9597,
"s": 9459,
"text": "GPP core(s) or ASIP core(s) on either an Application Specific Integrated Circuit (ASIC) or a Very Large Scale Integration (VLSI) circuit."
},
{
"code": null,
"e": 9735,
"s": 9597,
"text": "GPP core(s) or ASIP core(s) on either an Application Specific Integrated Circuit (ASIC) or a Very Large Scale Integration (VLSI) circuit."
},
{
"code": null,
"e": 9959,
"s": 9735,
"text": "A microprocessor is a single VLSI chip having a CPU. In addition, it may also have other units such as coaches, floating point processing arithmetic unit, and pipelining units that help in faster processing of instructions."
},
{
"code": null,
"e": 10123,
"s": 9959,
"text": "Earlier generation microprocessors’ fetch-and-execute cycle was guided by a clock frequency of order of ~1 MHz. Processors now operate at a clock frequency of 2GHz"
},
{
"code": null,
"e": 10340,
"s": 10123,
"text": "A microcontroller is a single-chip VLSI unit (also called microcomputer) which, although having limited computational capabilities, possesses enhanced input/output capability and a number of on-chip functional units."
},
{
"code": null,
"e": 10475,
"s": 10340,
"text": "Microcontrollers are particularly used in embedded systems for real-time control applications with on-chip program memory and devices."
},
{
"code": null,
"e": 10578,
"s": 10475,
"text": "Let us now take a look at the most notable differences between a microprocessor and a microcontroller."
},
{
"code": null,
"e": 10798,
"s": 10578,
"text": "The 8051 microcontrollers work with 8-bit data bus. So they can support external data memory up to 64K and external program memory of 64k at best. Collectively, 8051 microcontrollers can address 128k of external memory."
},
{
"code": null,
"e": 11023,
"s": 10798,
"text": "When data and code lie in different memory blocks, then the architecture is referred as Harvard architecture. In case data and code lie in the same memory block, then the architecture is referred as Von Neumann architecture."
},
{
"code": null,
"e": 11429,
"s": 11023,
"text": "The Von Neumann architecture was first proposed by a computer scientist John von Neumann. In this architecture, one data path or bus exists for both instruction and data. As a result, the CPU does one operation at a time. It either fetches an instruction from memory, or performs read/write operation on data. So an instruction fetch and a data operation cannot occur simultaneously, sharing a common bus."
},
{
"code": null,
"e": 11677,
"s": 11429,
"text": "Von-Neumann architecture supports simple hardware. It allows the use of a single, sequential memory. Today's processing speeds vastly outpace memory access times, and we employ a very fast but small amount of memory (cache) local to the processor."
},
{
"code": null,
"e": 12057,
"s": 11677,
"text": "The Harvard architecture offers separate storage and signal buses for instructions and data. This architecture has data storage entirely contained within the CPU, and there is no access to the instruction storage as data. Computers have separate memory areas for program instructions and data using internal data buses, allowing simultaneous access to both instructions and data."
},
{
"code": null,
"e": 12226,
"s": 12057,
"text": "Programs needed to be loaded by an operator; the processor could not boot itself. In a Harvard architecture, there is no need to make the two memories share properties."
},
{
"code": null,
"e": 12319,
"s": 12226,
"text": "The following points distinguish the Von Neumann Architecture from the Harvard Architecture."
},
{
"code": null,
"e": 12429,
"s": 12319,
"text": "CISC is a Complex Instruction Set Computer. It is a computer that can address a large number of instructions."
},
{
"code": null,
"e": 12709,
"s": 12429,
"text": "In the early 1980s, computer designers recommended that computers should use fewer instructions with simple constructs so that they can be executed much faster within the CPU without having to use memory. Such computers are classified as Reduced Instruction Set Computer or RISC."
},
{
"code": null,
"e": 12765,
"s": 12709,
"text": "The following points differentiate a CISC from a RISC −"
},
{
"code": null,
"e": 13227,
"s": 12765,
"text": "A compiler is a computer program (or a set of programs) that transforms the source code written in a programming language (the source language) into another computer language (normally binary format). The most common reason for conversion is to create an executable program. The name \"compiler\" is primarily used for programs that translate the source code from a highlevel programming language to a low-level language (e.g., assembly language or machine code)."
},
{
"code": null,
"e": 13425,
"s": 13227,
"text": "If the compiled program can run on a computer having different CPU or operating system than the computer on which the compiler compiled the program, then that compiler is known as a cross-compiler."
},
{
"code": null,
"e": 13539,
"s": 13425,
"text": "A program that can translate a program from a low-level language to a high-level language is called a decompiler."
},
{
"code": null,
"e": 13710,
"s": 13539,
"text": "A program that translates programs written in different high-level languages is normally called a language translator, source to source translator, or language converter."
},
{
"code": null,
"e": 13769,
"s": 13710,
"text": "A compiler is likely to perform the following operations −"
},
{
"code": null,
"e": 13783,
"s": 13769,
"text": "Preprocessing"
},
{
"code": null,
"e": 13791,
"s": 13783,
"text": "Parsing"
},
{
"code": null,
"e": 13839,
"s": 13791,
"text": "Semantic Analysis (Syntax-directed translation)"
},
{
"code": null,
"e": 13855,
"s": 13839,
"text": "Code generation"
},
{
"code": null,
"e": 13873,
"s": 13855,
"text": "Code optimization"
},
{
"code": null,
"e": 14309,
"s": 13873,
"text": "An assembler is a program that takes basic computer instructions (called as assembly language) and converts them into a pattern of bits that the computer's processor can use to perform its basic operations. An assembler creates object code by translating assembly instruction mnemonics into opcodes, resolving symbolic names to memory locations. Assembly language uses a mnemonic to represent each low-level machine operation (opcode)."
},
{
"code": null,
"e": 14768,
"s": 14309,
"text": "Debugging is a methodical process to find and reduce the number of bugs in a computer program or a piece of electronic hardware, so that it works as expected. Debugging is difficult when subsystems are tightly coupled, because a small change in one subsystem can create bugs in another. The debugging tools used in embedded systems differ greatly in terms of their development time and debugging features. We will discuss here the following debugging tools −"
},
{
"code": null,
"e": 14779,
"s": 14768,
"text": "Simulators"
},
{
"code": null,
"e": 14808,
"s": 14779,
"text": "Microcontroller starter kits"
},
{
"code": null,
"e": 14817,
"s": 14808,
"text": "Emulator"
},
{
"code": null,
"e": 15000,
"s": 14817,
"text": "Code is tested for the MCU / system by simulating it on the host computer used for code development. Simulators try to model the behavior of the complete microcontroller in software."
},
{
"code": null,
"e": 15047,
"s": 15000,
"text": "A simulator performs the following functions −"
},
{
"code": null,
"e": 15152,
"s": 15047,
"text": "Defines the processor or processing device family as well as its various versions for the target system."
},
{
"code": null,
"e": 15257,
"s": 15152,
"text": "Defines the processor or processing device family as well as its various versions for the target system."
},
{
"code": null,
"e": 15395,
"s": 15257,
"text": "Monitors the detailed information of a source code part with labels and symbolic arguments as the execution goes on for each single step."
},
{
"code": null,
"e": 15533,
"s": 15395,
"text": "Monitors the detailed information of a source code part with labels and symbolic arguments as the execution goes on for each single step."
},
{
"code": null,
"e": 15633,
"s": 15533,
"text": "Provides the status of RAM and simulated ports of the target system for each single step execution."
},
{
"code": null,
"e": 15733,
"s": 15633,
"text": "Provides the status of RAM and simulated ports of the target system for each single step execution."
},
{
"code": null,
"e": 15785,
"s": 15733,
"text": "Monitors system response and determines throughput."
},
{
"code": null,
"e": 15837,
"s": 15785,
"text": "Monitors system response and determines throughput."
},
{
"code": null,
"e": 15929,
"s": 15837,
"text": "Provides trace of the output of contents of program counter versus the processor registers."
},
{
"code": null,
"e": 16021,
"s": 15929,
"text": "Provides trace of the output of contents of program counter versus the processor registers."
},
{
"code": null,
"e": 16075,
"s": 16021,
"text": "Provides the detailed meaning of the present command."
},
{
"code": null,
"e": 16129,
"s": 16075,
"text": "Provides the detailed meaning of the present command."
},
{
"code": null,
"e": 16255,
"s": 16129,
"text": "Monitors the detailed information of the simulator commands as these are entered from the keyboard or selected from the menu."
},
{
"code": null,
"e": 16381,
"s": 16255,
"text": "Monitors the detailed information of the simulator commands as these are entered from the keyboard or selected from the menu."
},
{
"code": null,
"e": 16469,
"s": 16381,
"text": "Supports the conditions (up to 8 or 16 or 32 conditions) and unconditional breakpoints."
},
{
"code": null,
"e": 16557,
"s": 16469,
"text": "Supports the conditions (up to 8 or 16 or 32 conditions) and unconditional breakpoints."
},
{
"code": null,
"e": 16653,
"s": 16557,
"text": "Provides breakpoints and the trace which are together the important testing and debugging tool."
},
{
"code": null,
"e": 16749,
"s": 16653,
"text": "Provides breakpoints and the trace which are together the important testing and debugging tool."
},
{
"code": null,
"e": 16812,
"s": 16749,
"text": "Facilitates synchronizing the internal peripherals and delays."
},
{
"code": null,
"e": 16875,
"s": 16812,
"text": "Facilitates synchronizing the internal peripherals and delays."
},
{
"code": null,
"e": 16919,
"s": 16875,
"text": "A microcontroller starter kit consists of −"
},
{
"code": null,
"e": 16953,
"s": 16919,
"text": "Hardware board (Evaluation board)"
},
{
"code": null,
"e": 16974,
"s": 16953,
"text": "In-system programmer"
},
{
"code": null,
"e": 17033,
"s": 16974,
"text": "Some software tools like compiler, assembler, linker, etc."
},
{
"code": null,
"e": 17107,
"s": 17033,
"text": "Sometimes, an IDE and code size limited evaluation version of a compiler."
},
{
"code": null,
"e": 17366,
"s": 17107,
"text": "A big advantage of these kits over simulators is that they work in real-time and thus allow for easy input/output functionality verification. Starter kits, however, are completely sufficient and the cheapest option to develop simple microcontroller projects."
},
{
"code": null,
"e": 17659,
"s": 17366,
"text": "An emulator is a hardware kit or a software program or can be both which emulates the functions of one computer system (the guest) in another computer system (the host), different from the first one, so that the emulated behavior closely resembles the behavior of the real system (the guest)."
},
{
"code": null,
"e": 18119,
"s": 17659,
"text": "Emulation refers to the ability of a computer program in an electronic device to emulate (imitate) another program or device. Emulation focuses on recreating an original computer environment. Emulators have the ability to maintain a closer connection to the authenticity of the digital object. An emulator helps the user to work on any kind of application or operating system on a platform in a similar way as the software runs as in its original environment."
},
{
"code": null,
"e": 18219,
"s": 18119,
"text": "Embedded systems communicate with the outside world via their peripherals, such as following &mins;"
},
{
"code": null,
"e": 18291,
"s": 18219,
"text": "Serial Communication Interfaces (SCI) like RS-232, RS-422, RS-485, etc."
},
{
"code": null,
"e": 18363,
"s": 18291,
"text": "Synchronous Serial Communication Interface like I2C, SPI, SSC, and ESSI"
},
{
"code": null,
"e": 18390,
"s": 18363,
"text": "Universal Serial Bus (USB)"
},
{
"code": null,
"e": 18440,
"s": 18390,
"text": "Multi Media Cards (SD Cards, Compact Flash, etc.)"
},
{
"code": null,
"e": 18479,
"s": 18440,
"text": "Networks like Ethernet, LonWorks, etc."
},
{
"code": null,
"e": 18528,
"s": 18479,
"text": "Fieldbuses like CAN-Bus, LIN-Bus, PROFIBUS, etc."
},
{
"code": null,
"e": 18590,
"s": 18528,
"text": "imers like PLL(s), Capture/Compare and Time Processing Units."
},
{
"code": null,
"e": 18642,
"s": 18590,
"text": "Discrete IO aka General Purpose Input/Output (GPIO)"
},
{
"code": null,
"e": 18688,
"s": 18642,
"text": "Analog to Digital/Digital to Analog (ADC/DAC)"
},
{
"code": null,
"e": 18750,
"s": 18688,
"text": "Debugging like JTAG, ISP, ICSP, BDM Port, BITP, and DP9 ports"
},
{
"code": null,
"e": 19053,
"s": 18750,
"text": "While choosing a microcontroller, make sure it meets the task at hand and that it is cost effective. We must see whether an 8-bit, 16-bit or 32-bit microcontroller can best handle the computing needs of a task. In addition, the following points should be kept in mind while choosing a microcontroller −"
},
{
"code": null,
"e": 19120,
"s": 19053,
"text": "Speed − What is the highest speed the microcontroller can support?"
},
{
"code": null,
"e": 19187,
"s": 19120,
"text": "Speed − What is the highest speed the microcontroller can support?"
},
{
"code": null,
"e": 19348,
"s": 19187,
"text": "Packaging − Is it 40-pin DIP (Dual-inline-package) or QFP (Quad flat package)? This is important in terms of space, assembling, and prototyping the end-product."
},
{
"code": null,
"e": 19509,
"s": 19348,
"text": "Packaging − Is it 40-pin DIP (Dual-inline-package) or QFP (Quad flat package)? This is important in terms of space, assembling, and prototyping the end-product."
},
{
"code": null,
"e": 19589,
"s": 19509,
"text": "Power Consumption − This is an important criteria for battery-powered products."
},
{
"code": null,
"e": 19669,
"s": 19589,
"text": "Power Consumption − This is an important criteria for battery-powered products."
},
{
"code": null,
"e": 19704,
"s": 19669,
"text": "Amount of RAM and ROM on the chip."
},
{
"code": null,
"e": 19739,
"s": 19704,
"text": "Amount of RAM and ROM on the chip."
},
{
"code": null,
"e": 19781,
"s": 19739,
"text": "Count of I/O pins and Timers on the chip."
},
{
"code": null,
"e": 19823,
"s": 19781,
"text": "Count of I/O pins and Timers on the chip."
},
{
"code": null,
"e": 19939,
"s": 19823,
"text": "Cost per Unit − This is important in terms of final cost of the product in which the microcontroller is to be used."
},
{
"code": null,
"e": 20055,
"s": 19939,
"text": "Cost per Unit − This is important in terms of final cost of the product in which the microcontroller is to be used."
},
{
"code": null,
"e": 20260,
"s": 20055,
"text": "Further, make sure you have tools such as compilers, debuggers, and assemblers, available with the microcontroller. The most important of all, you should purchase a microcontroller from a reliable source."
},
{
"code": null,
"e": 20981,
"s": 20260,
"text": "The first microprocessor 4004 was invented by Intel Corporation. 8085 and 8086 microprocessors were also invented by Intel. In 1981, Intel introduced an 8-bit microcontroller called the 8051. It was referred as system on a chip because it had 128 bytes of RAM, 4K byte of on-chip ROM, two timers, one serial port, and 4 ports (8-bit wide), all on a single chip. When it became widely popular, Intel allowed other manufacturers to make and market different flavors of 8051 with its code compatible with 8051. It means that if you write your program for one flavor of 8051, it will run on other flavors too, regardless of the manufacturer. This has led to several versions with different speeds and amounts of on-chip RAM."
},
{
"code": null,
"e": 21189,
"s": 20981,
"text": "8052 microcontroller − 8052 has all the standard features of the 8051 microcontroller as well as an extra 128 bytes of RAM and an extra timer. It also has 8K bytes of on-chip program ROM instead of 4K bytes."
},
{
"code": null,
"e": 21397,
"s": 21189,
"text": "8052 microcontroller − 8052 has all the standard features of the 8051 microcontroller as well as an extra 128 bytes of RAM and an extra timer. It also has 8K bytes of on-chip program ROM instead of 4K bytes."
},
{
"code": null,
"e": 21848,
"s": 21397,
"text": "8031 microcontroller − It is another member of the 8051 family. This chip is often referred to as a ROM-less 8051, since it has 0K byte of on-chip ROM. You must add external ROM to it in order to use it, which contains the program to be fetched and executed. This program can be as large as 64K bytes. But in the process of adding external ROM to the 8031, it lost 2 ports out of 4 ports. To solve this problem, we can add an external I/O to the 8031"
},
{
"code": null,
"e": 22299,
"s": 21848,
"text": "8031 microcontroller − It is another member of the 8051 family. This chip is often referred to as a ROM-less 8051, since it has 0K byte of on-chip ROM. You must add external ROM to it in order to use it, which contains the program to be fetched and executed. This program can be as large as 64K bytes. But in the process of adding external ROM to the 8031, it lost 2 ports out of 4 ports. To solve this problem, we can add an external I/O to the 8031"
},
{
"code": null,
"e": 22376,
"s": 22299,
"text": "The following table compares the features available in 8051, 8052, and 8031."
},
{
"code": null,
"e": 22444,
"s": 22376,
"text": "An 8051 microcontroller comes bundled with the following features −"
},
{
"code": null,
"e": 22483,
"s": 22444,
"text": "4KB bytes on-chip program memory (ROM)"
},
{
"code": null,
"e": 22519,
"s": 22483,
"text": "128 bytes on-chip data memory (RAM)"
},
{
"code": null,
"e": 22539,
"s": 22519,
"text": "Four register banks"
},
{
"code": null,
"e": 22571,
"s": 22539,
"text": "128 user defined software flags"
},
{
"code": null,
"e": 22600,
"s": 22571,
"text": "8-bit bidirectional data bus"
},
{
"code": null,
"e": 22634,
"s": 22600,
"text": "16-bit unidirectional address bus"
},
{
"code": null,
"e": 22677,
"s": 22634,
"text": "32 general purpose registers each of 8-bit"
},
{
"code": null,
"e": 22730,
"s": 22677,
"text": "16 bit Timers (usually 2, but may have more or less)"
},
{
"code": null,
"e": 22773,
"s": 22730,
"text": "Three internal and two external Interrupts"
},
{
"code": null,
"e": 22825,
"s": 22773,
"text": "Four 8-bit ports,(short model have two 8-bit ports)"
},
{
"code": null,
"e": 22865,
"s": 22825,
"text": "16-bit program counter and data pointer"
},
{
"code": null,
"e": 22946,
"s": 22865,
"text": "8051 may also have a number of special features such as UARTs, ADC, Op-amp, etc."
},
{
"code": null,
"e": 23026,
"s": 22946,
"text": "The following illustration shows the block diagram of an 8051 microcontroller −"
},
{
"code": null,
"e": 23319,
"s": 23026,
"text": "In 8051, I/O operations are done using four ports and 40 pins. The following pin diagram shows the details of the 40 pins. I/O operation port reserves 32 pins where each port has 8 pins. The other 8 pins are designated as Vcc, GND, XTAL1, XTAL2, RST, EA (bar), ALE/PROG (bar), and PSEN (bar)."
},
{
"code": null,
"e": 23369,
"s": 23319,
"text": "It is a 40 Pin PDIP (Plastic Dual Inline Package)"
},
{
"code": null,
"e": 23608,
"s": 23369,
"text": "Note − In a DIP package, you can recognize the first pin and the last pin by the cut at the middle of the IC. The first pin is on the left of this cut mark and the last pin (i.e. the 40th pin in this case) is to the right of the cut mark."
},
{
"code": null,
"e": 23890,
"s": 23608,
"text": "The four ports P0, P1, P2, and P3, each use 8 pins, making them 8-bit ports. Upon RESET, all the ports are configured as inputs, ready to be used as input ports. When the first 0 is written to a port, it becomes an output. To reconfigure it as an input, a 1 must be sent to a port."
},
{
"code": null,
"e": 24091,
"s": 23890,
"text": "It has 8 pins (32 to 39). It can be used for input or output. Unlike P1, P2, and P3 ports, we normally connect P0 to 10K-ohm pull-up resistors to use it as an input or output port being an open drain."
},
{
"code": null,
"e": 24550,
"s": 24091,
"text": "It is also designated as AD0-AD7, allowing it to be used as both address and data. In case of 8031 (i.e. ROMless Chip), when we need to access the external ROM, then P0 will be used for both Address and Data Bus. ALE (Pin no 31) indicates if P0 has address or data. When ALE = 0, it provides data D0-D7, but when ALE = 1, it has address A0-A7. In case no external memory connection is available, P0 must be connected externally to a 10K-ohm pull-up resistor."
},
{
"code": null,
"e": 24686,
"s": 24550,
"text": "MOV A,#0FFH ;(comments: A=FFH(Hexadecimal i.e. A=1111 1111) \n\nMOV P0,A ;(Port0 have 1's on every pin so that it works as Input)\n"
},
{
"code": null,
"e": 24986,
"s": 24686,
"text": "It is an 8-bit port (pin 1 through 8) and can be used either as input or output. It doesn't require pull-up resistors because they are already connected internally. Upon reset, Port 1 is configured as an input port. The following code can be used to send alternating values of 55H and AAH to Port 1."
},
{
"code": null,
"e": 25132,
"s": 24986,
"text": ";Toggle all bits of continuously \nMOV A,#55 \nBACK: \n\nMOV P2,A \nACALL DELAY \nCPL A ;complement(invert) reg. A \nSJMP BACK\n"
},
{
"code": null,
"e": 25294,
"s": 25132,
"text": "If Port 1 is configured to be used as an output port, then to use it as an input port again, program it by writing 1 to all of its bits as in the following code."
},
{
"code": null,
"e": 25727,
"s": 25294,
"text": ";Toggle all bits of continuously \n\nMOV A ,#0FFH ;A = FF hex \nMOV P1,A ;Make P1 an input port \nMOV A,P1 ;get data from P1 \nMOV R7,A ;save it in Reg R7 \nACALL DELAY ;wait \n\nMOV A,P1 ;get another data from P1 \nMOV R6,A ;save it in R6 \nACALL DELAY ;wait \n\nMOV A,P1 ;get another data from P1 \nMOV R5,A ;save it in R5\n"
},
{
"code": null,
"e": 26375,
"s": 25727,
"text": "Port 2 occupies a total of 8 pins (pins 21 through 28) and can be used for both input and output operations. Just as P1 (Port 1), P2 also doesn't require external Pull-up resistors because they are already connected internally. It must be used along with P0 to provide the 16-bit address for the external memory. So it is also designated as (A0–A7), as shown in the pin diagram. When the 8051 is connected to an external memory, it provides path for upper 8-bits of 16-bits address, and it cannot be used as I/O. Upon reset, Port 2 is configured as an input port. The following code can be used to send alternating values of 55H and AAH to port 2."
},
{
"code": null,
"e": 26521,
"s": 26375,
"text": ";Toggle all bits of continuously \nMOV A,#55 \nBACK: \nMOV P2,A \nACALL DELAY \nCPL A ; complement(invert) reg. A \nSJMP BACK\n"
},
{
"code": null,
"e": 26683,
"s": 26521,
"text": "If Port 2 is configured to be used as an output port, then to use it as an input port again, program it by writing 1 to all of its bits as in the following code."
},
{
"code": null,
"e": 26912,
"s": 26683,
"text": ";Get a byte from P2 and send it to P1 \nMOV A,#0FFH ;A = FF hex \nMOV P2,A ;make P2 an input port \nBACK: \nMOV A,P2 ;get data from P2 \nMOV P1,A ;send it to Port 1\nSJMP BACK ;keep doing that\n"
},
{
"code": null,
"e": 27471,
"s": 26912,
"text": "It is also of 8 bits and can be used as Input/Output. This port provides some extremely important signals. P3.0 and P3.1 are RxD (Receiver) and TxD (Transmitter) respectively and are collectively used for Serial Communication. P3.2 and P3.3 pins are used for external interrupts. P3.4 and P3.5 are used for timers T0 and T1 respectively. P3.6 and P3.7 are Write (WR) and Read (RD) pins. These are active low pins, means they will be active when 0 is given to them and these are used to provide Read and Write operations to External ROM in 8031 based systems."
},
{
"code": null,
"e": 27766,
"s": 27471,
"text": "Dual role of Port 0 − Port 0 is also designated as AD0–AD7, as it can be used for both data and address handling. While connecting an 8051 to external memory, Port 0 can provide both address and data. The 8051 microcontroller then multiplexes the input as address or data in order to save pins."
},
{
"code": null,
"e": 28061,
"s": 27766,
"text": "Dual role of Port 0 − Port 0 is also designated as AD0–AD7, as it can be used for both data and address handling. While connecting an 8051 to external memory, Port 0 can provide both address and data. The 8051 microcontroller then multiplexes the input as address or data in order to save pins."
},
{
"code": null,
"e": 28632,
"s": 28061,
"text": "Dual role of Port 2 − Besides working as I/O, Port P2 is also used to provide 16-bit address bus for external memory along with Port 0. Port P2 is also designated as (A8– A15), while Port 0 provides the lower 8-bits via A0–A7. In other words, we can say that when an 8051 is connected to an external memory (ROM) which can be maximum up to 64KB and this is possible by 16 bit address bus because we know 216 = 64KB. Port2 is used for the upper 8-bit of the 16 bits address, and it cannot be used for I/O and this is the way any Program code of external ROM is addressed."
},
{
"code": null,
"e": 29203,
"s": 28632,
"text": "Dual role of Port 2 − Besides working as I/O, Port P2 is also used to provide 16-bit address bus for external memory along with Port 0. Port P2 is also designated as (A8– A15), while Port 0 provides the lower 8-bits via A0–A7. In other words, we can say that when an 8051 is connected to an external memory (ROM) which can be maximum up to 64KB and this is possible by 16 bit address bus because we know 216 = 64KB. Port2 is used for the upper 8-bit of the 16 bits address, and it cannot be used for I/O and this is the way any Program code of external ROM is addressed."
},
{
"code": null,
"e": 29260,
"s": 29203,
"text": "Vcc − Pin 40 provides supply to the Chip and it is +5 V."
},
{
"code": null,
"e": 29317,
"s": 29260,
"text": "Vcc − Pin 40 provides supply to the Chip and it is +5 V."
},
{
"code": null,
"e": 29365,
"s": 29317,
"text": "Gnd − Pin 20 provides ground for the Reference."
},
{
"code": null,
"e": 29413,
"s": 29365,
"text": "Gnd − Pin 20 provides ground for the Reference."
},
{
"code": null,
"e": 29913,
"s": 29413,
"text": "XTAL1, XTAL2 (Pin no 18 & Pin no 19) − 8051 has on-chip oscillator but requires external clock to run it. A quartz crystal is connected between the XTAL1 & XTAL2 pin of the chip. This crystal also needs two capacitors of 30pF for generating a signal of desired frequency. One side of each capacitor is connected to ground. 8051 IC is available in various speeds and it all depends on this Quartz crystal, for example, a 20 MHz microcontroller requires a crystal with a frequency no more than 20 MHz."
},
{
"code": null,
"e": 30413,
"s": 29913,
"text": "XTAL1, XTAL2 (Pin no 18 & Pin no 19) − 8051 has on-chip oscillator but requires external clock to run it. A quartz crystal is connected between the XTAL1 & XTAL2 pin of the chip. This crystal also needs two capacitors of 30pF for generating a signal of desired frequency. One side of each capacitor is connected to ground. 8051 IC is available in various speeds and it all depends on this Quartz crystal, for example, a 20 MHz microcontroller requires a crystal with a frequency no more than 20 MHz."
},
{
"code": null,
"e": 31040,
"s": 30413,
"text": "RST (Pin No. 9) − It is an Input pin and active High pin. Upon applying a high pulse on this pin, that is 1, the microcontroller will reset and terminate all activities. This process is known as Power-On Reset. Activating a power-on reset will cause all values in the register to be lost. It will set a program counter to all 0's. To ensure a valid input of Reset, the high pulse must be high for a minimum of two machine cycles before it is allowed to go low, which depends on the capacitor value and the rate at which it charges. (Machine Cycle is the minimum amount of frequency a single instruction requires in execution)."
},
{
"code": null,
"e": 31667,
"s": 31040,
"text": "RST (Pin No. 9) − It is an Input pin and active High pin. Upon applying a high pulse on this pin, that is 1, the microcontroller will reset and terminate all activities. This process is known as Power-On Reset. Activating a power-on reset will cause all values in the register to be lost. It will set a program counter to all 0's. To ensure a valid input of Reset, the high pulse must be high for a minimum of two machine cycles before it is allowed to go low, which depends on the capacitor value and the rate at which it charges. (Machine Cycle is the minimum amount of frequency a single instruction requires in execution)."
},
{
"code": null,
"e": 32154,
"s": 31667,
"text": "EA or External Access (Pin No. 31) − It is an input pin. This pin is an active low pin; upon applying a low pulse, it gets activated. In case of microcontroller (8051/52) having on-chip ROM, the EA (bar) pin is connected to Vcc. But in an 8031 microcontroller which does not have an on-chip ROM, the code is stored in an external ROM and then fetched by the microcontroller. In this case, we must connect the (pin no 31) EA to Gnd to indicate that the program code is stored externally."
},
{
"code": null,
"e": 32641,
"s": 32154,
"text": "EA or External Access (Pin No. 31) − It is an input pin. This pin is an active low pin; upon applying a low pulse, it gets activated. In case of microcontroller (8051/52) having on-chip ROM, the EA (bar) pin is connected to Vcc. But in an 8031 microcontroller which does not have an on-chip ROM, the code is stored in an external ROM and then fetched by the microcontroller. In this case, we must connect the (pin no 31) EA to Gnd to indicate that the program code is stored externally."
},
{
"code": null,
"e": 32906,
"s": 32641,
"text": "PSEN or Program store Enable (Pin No 29) − This is also an active low pin, i.e., it gets activated after applying a low pulse. It is an output pin and used along with the EA pin in 8031 based (i.e. ROMLESS) Systems to allow storage of program code in external ROM."
},
{
"code": null,
"e": 33171,
"s": 32906,
"text": "PSEN or Program store Enable (Pin No 29) − This is also an active low pin, i.e., it gets activated after applying a low pulse. It is an output pin and used along with the EA pin in 8031 based (i.e. ROMLESS) Systems to allow storage of program code in external ROM."
},
{
"code": null,
"e": 33507,
"s": 33171,
"text": "ALE or (Address Latch Enable) − This is an Output Pin and is active high. It is especially used for 8031 IC to connect it to the external memory. It can be used while deciding whether P0 pins will be used as Address bus or Data bus. When ALE = 1, then the P0 pins work as Data bus and when ALE = 0, then the P0 pins act as Address bus."
},
{
"code": null,
"e": 33843,
"s": 33507,
"text": "ALE or (Address Latch Enable) − This is an Output Pin and is active high. It is especially used for 8031 IC to connect it to the external memory. It can be used while deciding whether P0 pins will be used as Address bus or Data bus. When ALE = 1, then the P0 pins work as Data bus and when ALE = 0, then the P0 pins act as Address bus."
},
{
"code": null,
"e": 34069,
"s": 33843,
"text": "It is a most widely used feature of 8051 while writing code for 8051. Sometimes we need to access only 1 or 2 bits of the port instead of the entire 8-bits. 8051 provides the capability to access individual bits of the ports."
},
{
"code": null,
"e": 34325,
"s": 34069,
"text": "While accessing a port in a single-bit manner, we use the syntax \"SETB X. Y\" where X is the port number (0 to 3), and Y is a bit number (0 to 7) for data bits D0-D7 where D0 is the LSB and D7 is the MSB. For example, \"SETB P1.5\" sets high bit 5 of port 1."
},
{
"code": null,
"e": 34395,
"s": 34325,
"text": "The following code shows how we can toggle the bit P1.2 continuously."
},
{
"code": null,
"e": 34483,
"s": 34395,
"text": "AGAIN: \nSETB P1.2\nACALL DELAY \nCLR P1.2 \nACALL DELAY \nSJMP AGAIN\n"
},
{
"code": null,
"e": 34828,
"s": 34483,
"text": "The Program Counter is a 16- or 32-bit register which contains the address of the next instruction to be executed. The PC automatically increments to the next sequential memory location every time an instruction is fetched. Branch, jump, and interrupt operations load the Program Counter with an address other than the next sequential location."
},
{
"code": null,
"e": 35184,
"s": 34828,
"text": "Activating a power-on reset will cause all values in the register to be lost. It means the value of the PC (program counter) is 0 upon reset, forcing the CPU to fetch the first opcode from the ROM memory location 0000. It means we must place the first byte of upcode in ROM location 0000 because that is where the CPU expects to find the first instruction"
},
{
"code": null,
"e": 35581,
"s": 35184,
"text": "The significance of the reset vector is that it points the processor to the memory address which contains the firmware's first instruction. Without the Reset Vector, the processor would not know where to begin execution. Upon reset, the processor loads the Program Counter (PC) with the reset vector value from a predefined memory location. On CPU08 architecture, this is at location $FFFE:$FFFF."
},
{
"code": null,
"e": 35831,
"s": 35581,
"text": "When the reset vector is not necessary, developers normally take it for granted and don’t program into the final image. As a result, the processor doesn't start up on the final product. It is a common mistake that takes place during the debug phase."
},
{
"code": null,
"e": 36151,
"s": 35831,
"text": "Stack is implemented in RAM and a CPU register is used to access it called SP (Stack Pointer) register. SP register is an 8-bit register and can address memory addresses of range 00h to FFh. Initially, the SP register contains value 07 to point to location 08 as the first location being used for the stack by the 8051."
},
{
"code": null,
"e": 36430,
"s": 36151,
"text": "When the content of a CPU register is stored in a stack, it is called a PUSH operation. When the content of a stack is stored in a CPU register, it is called a POP operation. In other words, a register is pushed onto the stack to save it and popped off the stack to retrieve it."
},
{
"code": null,
"e": 36606,
"s": 36430,
"text": "An infinite loop or an endless loop can be identified as a sequence of instructions in a computer program that executes endlessly in a loop, because of the following reasons −"
},
{
"code": null,
"e": 36642,
"s": 36606,
"text": "loop with no terminating condition."
},
{
"code": null,
"e": 36699,
"s": 36642,
"text": "loop with a terminating condition that can never be met."
},
{
"code": null,
"e": 36769,
"s": 36699,
"text": "loop with a terminating condition that causes the loop to start over."
},
{
"code": null,
"e": 37107,
"s": 36769,
"text": "Such infinite loops normally caused older operating systems to become unresponsive, as an infinite loop consumes all the available processor time. I/O operations waiting for user inputs are also called \"infinite loops\". One possible cause of a computer \"freezing\" is an infinite loop; other causes include deadlock and access violations."
},
{
"code": null,
"e": 37491,
"s": 37107,
"text": "Embedded systems, unlike a PC, never \"exit\" an application. They idle through an Infinite Loop waiting for an event to take place in the form of an interrupt, or a pre-scheduled task. In order to save power, some processors enter special sleep or wait modes instead of idling through an Infinite Loop, but they will come out of this mode upon either a timer or an External Interrupt."
},
{
"code": null,
"e": 37920,
"s": 37491,
"text": "Interrupts are mostly hardware mechanisms that instruct the program that an event has occurred. They may occur at any time, and are therefore asynchronous to the program flow. They require special handling by the processor, and are ultimately handled by a corresponding Interrupt Service Routine (ISR). Interrupts need to be handled quickly. If you take too much time servicing an interrupt, then you may miss another interrupt."
},
{
"code": null,
"e": 38156,
"s": 37920,
"text": "Although numbers are always displayed in the same way, they are not stored in the same way in memory. Big-Endian machines store the most significant byte of data in the lowest memory address. A Big-Endian machine stores 0x12345678 as −"
},
{
"code": null,
"e": 38208,
"s": 38156,
"text": "ADD+0: 0x12 \nADD+1: 0x34 \nADD+2: 0x56 \nADD+3: 0x78\n"
},
{
"code": null,
"e": 38369,
"s": 38208,
"text": "Little-Endian machines, on the other hand, store the least significant byte of data in the lowest memory address. A Little-Endian machine stores 0x12345678 as −"
},
{
"code": null,
"e": 38421,
"s": 38369,
"text": "ADD+0: 0x78 \nADD+1: 0x56 \nADD+2: 0x34 \nADD+3: 0x12\n"
},
{
"code": null,
"e": 38910,
"s": 38421,
"text": "Assembly languages were developed to provide mnemonics or symbols for the machine level code instructions. Assembly language programs consist of mnemonics, thus they should be translated into machine code. A program that is responsible for this conversion is known as assembler. Assembly language is often termed as a low-level language because it directly works with the internal structure of the CPU. To program in assembly language, a programmer must know all the registers of the CPU."
},
{
"code": null,
"e": 39420,
"s": 38910,
"text": "Different programming languages such as C, C++, Java and various other languages are called high-level languages because they do not deal with the internal details of a CPU. In contrast, an assembler is used to translate an assembly language program into machine code (sometimes also called object code or opcode). Similarly, a compiler translates a high-level language into machine code. For example, to write a program in C language, one must use a C compiler to translate the program into machine language."
},
{
"code": null,
"e": 39578,
"s": 39420,
"text": "An assembly language program is a series of statements, which are either assembly language instructions such as ADD and MOV, or statements called directives."
},
{
"code": null,
"e": 40033,
"s": 39578,
"text": "An instruction tells the CPU what to do, while a directive (also called pseudo-instructions) gives instruction to the assembler. For example, ADD and MOV instructions are commands which the CPU runs, while ORG and END are assembler directives. The assembler places the opcode to the memory location 0 when the ORG directive is used, while END indicates to the end of the source code. A program language instruction consists of the following four fields −"
},
{
"code": null,
"e": 40086,
"s": 40033,
"text": "[ label: ] mnemonics [ operands ] [;comment ] \n"
},
{
"code": null,
"e": 40149,
"s": 40086,
"text": "A square bracket ( [ ] ) indicates that the field is optional."
},
{
"code": null,
"e": 40283,
"s": 40149,
"text": "The label field allows the program to refer to a line of code by name. The label fields cannot exceed a certain number of characters."
},
{
"code": null,
"e": 40417,
"s": 40283,
"text": "The label field allows the program to refer to a line of code by name. The label fields cannot exceed a certain number of characters."
},
{
"code": null,
"e": 40854,
"s": 40417,
"text": "The mnemonics and operands fields together perform the real work of the program and accomplish the tasks. Statements like ADD A , C & MOV C, #68 where ADD and MOV are the mnemonics, which produce opcodes ; \"A, C\" and \"C, #68\" are operands. These two fields could contain directives. Directives do not generate machine code and are used only by the assembler, whereas instructions are translated into machine code for the CPU to execute."
},
{
"code": null,
"e": 41291,
"s": 40854,
"text": "The mnemonics and operands fields together perform the real work of the program and accomplish the tasks. Statements like ADD A , C & MOV C, #68 where ADD and MOV are the mnemonics, which produce opcodes ; \"A, C\" and \"C, #68\" are operands. These two fields could contain directives. Directives do not generate machine code and are used only by the assembler, whereas instructions are translated into machine code for the CPU to execute."
},
{
"code": null,
"e": 41801,
"s": 41291,
"text": "1.0000 ORG 0H ;start (origin) at location 0 \n2 0000 7D25 MOV R5,#25H ;load 25H into R5 \n3.0002 7F34 MOV R7,#34H ;load 34H into R7 \n4.0004 7400 MOV A,#0 ;load 0 into A \n5.0006 2D ADD A,R5 ;add contents of R5 to A \n6.0007 2F ADD A,R7 ;add contents of R7 to A\n7.0008 2412 ADD A,#12H ;add to A value 12 H \n8.000A 80FE HERE: SJMP HERE ;stay in this loop \n9.000C END ;end of asm source file\n"
},
{
"code": null,
"e": 41873,
"s": 41801,
"text": "The comment field begins with a semicolon which is a comment indicator."
},
{
"code": null,
"e": 41945,
"s": 41873,
"text": "The comment field begins with a semicolon which is a comment indicator."
},
{
"code": null,
"e": 42057,
"s": 41945,
"text": "Notice the Label \"HERE\" in the program. Any label which refers to an instruction should be followed by a colon."
},
{
"code": null,
"e": 42169,
"s": 42057,
"text": "Notice the Label \"HERE\" in the program. Any label which refers to an instruction should be followed by a colon."
},
{
"code": null,
"e": 42321,
"s": 42169,
"text": "Here we will discuss about the basic form of an assembly language. The steps to create, assemble, and run an assembly language program are as follows −"
},
{
"code": null,
"e": 42650,
"s": 42321,
"text": "First, we use an editor to type in a program similar to the above program. Editors like MS-DOS EDIT program that comes with all Microsoft operating systems can be used to create or edit a program. The Editor must be able to produce an ASCII file. The \"asm\" extension for the source file is used by an assembler in the next step."
},
{
"code": null,
"e": 42979,
"s": 42650,
"text": "First, we use an editor to type in a program similar to the above program. Editors like MS-DOS EDIT program that comes with all Microsoft operating systems can be used to create or edit a program. The Editor must be able to produce an ASCII file. The \"asm\" extension for the source file is used by an assembler in the next step."
},
{
"code": null,
"e": 43510,
"s": 42979,
"text": "The \"asm\" source file contains the program code created in Step 1. It is fed to an 8051 assembler. The assembler then converts the assembly language instructions into machine code instructions and produces an .obj file (object file) and a .lst file (list file). It is also called as a source file, that's why some assemblers require that this file have the \"src\" extensions. The \"lst\" file is optional. It is very useful to the program because it lists all the opcodes and addresses as well as errors that the assemblers detected."
},
{
"code": null,
"e": 44041,
"s": 43510,
"text": "The \"asm\" source file contains the program code created in Step 1. It is fed to an 8051 assembler. The assembler then converts the assembly language instructions into machine code instructions and produces an .obj file (object file) and a .lst file (list file). It is also called as a source file, that's why some assemblers require that this file have the \"src\" extensions. The \"lst\" file is optional. It is very useful to the program because it lists all the opcodes and addresses as well as errors that the assemblers detected."
},
{
"code": null,
"e": 44200,
"s": 44041,
"text": "Assemblers require a third step called linking. The link program takes one or more object files and produces an absolute object file with the extension \"abs\"."
},
{
"code": null,
"e": 44359,
"s": 44200,
"text": "Assemblers require a third step called linking. The link program takes one or more object files and produces an absolute object file with the extension \"abs\"."
},
{
"code": null,
"e": 44522,
"s": 44359,
"text": "Next, the \"abs\" file is fed to a program called \"OH\" (object to hex converter), which creates a file with the extension \"hex\" that is ready to burn in to the ROM."
},
{
"code": null,
"e": 44685,
"s": 44522,
"text": "Next, the \"abs\" file is fed to a program called \"OH\" (object to hex converter), which creates a file with the extension \"hex\" that is ready to burn in to the ROM."
},
{
"code": null,
"e": 44922,
"s": 44685,
"text": "The 8051 microcontroller contains a single data type of 8-bits, and each register is also of 8-bits size. The programmer has to break down data larger than 8-bits (00 to FFH, or to 255 in decimal) so that it can be processed by the CPU."
},
{
"code": null,
"e": 45227,
"s": 44922,
"text": "The DB directive is the most widely used data directive in the assembler. It is used to define the 8-bit data. It can also be used to define decimal, binary, hex, or ASCII formats data. For decimal, the \"D\" after the decimal number is optional, but it is required for \"B\" (binary) and \"Hl\" (hexadecimal)."
},
{
"code": null,
"e": 45596,
"s": 45227,
"text": "To indicate ASCII, simply place the characters in quotation marks ('like this'). The assembler generates ASCII code for the numbers/characters automatically. The DB directive is the only directive that can be used to define ASCII strings larger than two characters; therefore, it should be used for all the ASCII data definitions. Some examples of DB are given below −"
},
{
"code": null,
"e": 45944,
"s": 45596,
"text": " ORG 500H \nDATA1: DB 28 ;DECIMAL (1C in hex) \nDATA2: DB 00110101B ;BINARY (35 in hex) \nDATA3: DB 39H ;HEX \n ORG 510H \nDATA4: DB \"2591\" ;ASCII NUMBERS \n ORG 520H \nDATA6: DA \"MY NAME IS Michael\" ;ASCII CHARACTERS \n"
},
{
"code": null,
"e": 46066,
"s": 45944,
"text": "Either single or double quotes can be used around ASCII strings. DB is also used to allocate memory in byte-sized chunks."
},
{
"code": null,
"e": 46114,
"s": 46066,
"text": "Some of the directives of 8051 are as follows −"
},
{
"code": null,
"e": 46384,
"s": 46114,
"text": "ORG (origin) − The origin directive is used to indicate the beginning of the address. It takes the numbers in hexa or decimal format. If H is provided after the number, the number is treated as hexa, otherwise decimal. The assembler converts the decimal number to hexa."
},
{
"code": null,
"e": 46654,
"s": 46384,
"text": "ORG (origin) − The origin directive is used to indicate the beginning of the address. It takes the numbers in hexa or decimal format. If H is provided after the number, the number is treated as hexa, otherwise decimal. The assembler converts the decimal number to hexa."
},
{
"code": null,
"e": 47186,
"s": 46654,
"text": "EQU (equate) − It is used to define a constant without occupying a memory location. EQU associates a constant value with a data label so that the label appears in the program, its constant value will be substituted for the label. While executing the instruction \"MOV R3, #COUNT\", the register R3 will be loaded with the value 25 (notice the # sign). The advantage of using EQU is that the programmer can change it once and the assembler will change all of its occurrences; the programmer does not have to search the entire program."
},
{
"code": null,
"e": 47718,
"s": 47186,
"text": "EQU (equate) − It is used to define a constant without occupying a memory location. EQU associates a constant value with a data label so that the label appears in the program, its constant value will be substituted for the label. While executing the instruction \"MOV R3, #COUNT\", the register R3 will be loaded with the value 25 (notice the # sign). The advantage of using EQU is that the programmer can change it once and the assembler will change all of its occurrences; the programmer does not have to search the entire program."
},
{
"code": null,
"e": 47894,
"s": 47718,
"text": "END directive − It indicates the end of the source (asm) file. The END directive is the last line of the program; anything after the END directive is ignored by the assembler."
},
{
"code": null,
"e": 48070,
"s": 47894,
"text": "END directive − It indicates the end of the source (asm) file. The END directive is the last line of the program; anything after the END directive is ignored by the assembler."
},
{
"code": null,
"e": 48142,
"s": 48070,
"text": "All the labels in assembly language must follow the rules given below −"
},
{
"code": null,
"e": 48424,
"s": 48142,
"text": "Each label name must be unique. The names used for labels in assembly language programming consist of alphabetic letters in both uppercase and lowercase, number 0 through 9, and special characters such as question mark (?), period (.), at the rate @, underscore (_), and dollar($)."
},
{
"code": null,
"e": 48706,
"s": 48424,
"text": "Each label name must be unique. The names used for labels in assembly language programming consist of alphabetic letters in both uppercase and lowercase, number 0 through 9, and special characters such as question mark (?), period (.), at the rate @, underscore (_), and dollar($)."
},
{
"code": null,
"e": 48786,
"s": 48706,
"text": "The first character should be in alphabetical character; it cannot be a number."
},
{
"code": null,
"e": 48866,
"s": 48786,
"text": "The first character should be in alphabetical character; it cannot be a number."
},
{
"code": null,
"e": 49016,
"s": 48866,
"text": "Reserved words cannot be used as a label in the program. For example, ADD and MOV words are the reserved words, since they are instruction mnemonics."
},
{
"code": null,
"e": 49166,
"s": 49016,
"text": "Reserved words cannot be used as a label in the program. For example, ADD and MOV words are the reserved words, since they are instruction mnemonics."
},
{
"code": null,
"e": 49570,
"s": 49166,
"text": "Registers are used in the CPU to store information on temporarily basis which could be data to be processed, or an address pointing to the data which is to be fetched. In 8051, there is one data type is of 8-bits, from the MSB (most significant bit) D7 to the LSB (least significant bit) D0. With 8-bit data type, any data type larger than 8-bits must be broken into 8-bit chunks before it is processed."
},
{
"code": null,
"e": 49746,
"s": 49570,
"text": "The most widely used registers of the 8051 are A (accumulator), B, R0-R7, DPTR (data pointer), and PC (program counter). All these registers are of 8-bits, except DPTR and PC."
},
{
"code": null,
"e": 49810,
"s": 49746,
"text": "We will discuss the following types of storage registers here −"
},
{
"code": null,
"e": 49822,
"s": 49810,
"text": "Accumulator"
},
{
"code": null,
"e": 49833,
"s": 49822,
"text": "R register"
},
{
"code": null,
"e": 49844,
"s": 49833,
"text": "B register"
},
{
"code": null,
"e": 49864,
"s": 49844,
"text": "Data Pointer (DPTR)"
},
{
"code": null,
"e": 49885,
"s": 49864,
"text": "Program Counter (PC)"
},
{
"code": null,
"e": 49904,
"s": 49885,
"text": "Stack Pointer (SP)"
},
{
"code": null,
"e": 50321,
"s": 49904,
"text": "The accumulator, register A, is used for all arithmetic and logic operations. If the accumulator is not present, then every result of each calculation (addition, multiplication, shift, etc.) is to be stored into the main memory. Access to main memory is slower than access to a register like the accumulator because the technology used for the large main memory is slower (but cheaper) than that used for a register."
},
{
"code": null,
"e": 50676,
"s": 50321,
"text": "The \"R\" registers are a set of eight registers, namely, R0, R1 to R7. These registers function as auxiliary or temporary storage registers in many operations. Consider an example of the sum of 10 and 20. Store a variable 10 in an accumulator and another variable 20 in, say, register R4. To process the addition operation, execute the following command −"
},
{
"code": null,
"e": 50686,
"s": 50676,
"text": "ADD A,R4\n"
},
{
"code": null,
"e": 50982,
"s": 50686,
"text": "After executing this instruction, the accumulator will contain the value 30. Thus \"R\" registers are very important auxiliary or helper registers. The Accumulator alone would not be very useful if it were not for these \"R\" registers. The \"R\" registers are meant for temporarily storage of values."
},
{
"code": null,
"e": 51115,
"s": 50982,
"text": "Let us take another example. We will add the values in R1 and R2 together and then subtract the values of R3 and R4 from the result."
},
{
"code": null,
"e": 51415,
"s": 51115,
"text": "MOV A,R3 ;Move the value of R3 into the accumulator \nADD A,R4 ;Add the value of R4 \nMOV R5,A ;Store the resulting value temporarily in R5 \nMOV A,R1 ;Move the value of R1 into the accumulator \nADD A,R2 ;Add the value of R2 \nSUBB A,R5 ;Subtract the value of R5 (which now contains R3 + R4)\n"
},
{
"code": null,
"e": 51656,
"s": 51415,
"text": "As you can see, we used R5 to temporarily hold the sum of R3 and R4. Of course, this is not the most efficient way to calculate (R1 + R2) – (R3 + R4), but it does illustrate the use of the \"R\" registers as a way to store values temporarily."
},
{
"code": null,
"e": 52125,
"s": 51656,
"text": "The \"B\" register is very similar to the Accumulator in the sense that it may hold an 8-bit (1-byte) value. The \"B\" register is used only by two 8051 instructions: MUL AB and DIV AB. To quickly and easily multiply or divide A by another number, you may store the other number in \"B\" and make use of these two instructions. Apart from using MUL and DIV instructions, the \"B\" register is often used as yet another temporary storage register, much like a ninth R register."
},
{
"code": null,
"e": 52493,
"s": 52125,
"text": "The Data Pointer (DPTR) is the 8051’s only user-accessible 16-bit (2-byte) register. The Accumulator, R0–R7 registers and B register are 1-byte value registers. DPTR is meant for pointing to data. It is used by the 8051 to access external memory using the address indicated by DPTR. DPTR is the only 16-bit register available and is often used to store 2-byte values."
},
{
"code": null,
"e": 52866,
"s": 52493,
"text": "The Program Counter (PC) is a 2-byte address which tells the 8051 where the next instruction to execute can be found in the memory. PC starts at 0000h when the 8051 initializes and is incremented every time after an instruction is executed. PC is not always incremented by 1. Some instructions may require 2 or 3 bytes; in such cases, the PC will be incremented by 2 or 3."
},
{
"code": null,
"e": 53319,
"s": 52866,
"text": "Branch, jump, and interrupt operations load the Program Counter with an address other than the next sequential location. Activating a power-on reset will cause all values in the register to be lost. It means the value of the PC is 0 upon reset, forcing the CPU to fetch the first opcode from the ROM location 0000. It means we must place the first byte of upcode in ROM location 0000 because that is where the CPU expects to find the first instruction."
},
{
"code": null,
"e": 53783,
"s": 53319,
"text": "The Stack Pointer, like all registers except DPTR and PC, may hold an 8-bit (1-byte) value. The Stack Pointer tells the location from where the next value is to be removed from the stack. When a value is pushed onto the stack, the value of SP is incremented and then the value is stored at the resulting memory location. When a value is popped off the stack, the value is returned from the memory location indicated by SP, and then the value of SP is decremented."
},
{
"code": null,
"e": 54228,
"s": 53783,
"text": "This order of operation is important. SP will be initialized to 07h when the 8051 is initialized. If a value is pushed onto the stack at the same time, the value will be stored in the internal RAM address 08h because the 8051 will first increment the value of SP (from 07h to 08h) and then will store the pushed value at that memory address (08h). SP is modified directly by the 8051 by six instructions: PUSH, POP, ACALL, LCALL, RET, and RETI."
},
{
"code": null,
"e": 54629,
"s": 54228,
"text": "Some family members of 8051 have only 4K bytes of on-chip ROM (e.g. 8751, AT8951); some have 8K ROM like AT89C52, and there are some family members with 32K bytes and 64K bytes of on-chip ROM such as Dallas Semiconductor. The point to remember is that no member of the 8051 family can access more than 64K bytes of opcode since the program counter in 8051 is a 16-bit register (0000 to FFFF address)."
},
{
"code": null,
"e": 54939,
"s": 54629,
"text": "The first location of the program ROM inside the 8051 has the address of 0000H, whereas the last location can be different depending on the size of the ROM on the chip. Among the 8051 family members, AT8951 has $k bytes of on-chip ROM having a memory address of 0000 (first location) to 0FFFH (last location)."
},
{
"code": null,
"e": 55463,
"s": 54939,
"text": "The program status word (PSW) register is an 8-bit register, also known as flag register. It is of 8-bit wide but only 6-bit of it is used. The two unused bits are user-defined flags. Four of the flags are called conditional flags, which means that they indicate a condition which results after an instruction is executed. These four are CY (Carry), AC (auxiliary carry), P (parity), and OV (overflow). The bits RS0 and RS1 are used to change the bank registers. The following figure shows the program status word register."
},
{
"code": null,
"e": 55550,
"s": 55463,
"text": "The PSW Register contains that status bits that reflect the current status of the CPU."
},
{
"code": null,
"e": 55624,
"s": 55550,
"text": "We can select the corresponding Register Bank bit using RS0 and RS1 bits."
},
{
"code": null,
"e": 55943,
"s": 55624,
"text": "CY, the carry flag − This carry flag is set (1) whenever there is a carry out from the D7 bit. It is affected after an 8-bit addition or subtraction operation. It can also be reset to 1 or 0 directly by an instruction such as \"SETB C\" and \"CLR C\" where \"SETB\" stands for set bit carry and \"CLR\" stands for clear carry."
},
{
"code": null,
"e": 56262,
"s": 55943,
"text": "CY, the carry flag − This carry flag is set (1) whenever there is a carry out from the D7 bit. It is affected after an 8-bit addition or subtraction operation. It can also be reset to 1 or 0 directly by an instruction such as \"SETB C\" and \"CLR C\" where \"SETB\" stands for set bit carry and \"CLR\" stands for clear carry."
},
{
"code": null,
"e": 56476,
"s": 56262,
"text": "AC, auxiliary carry flag − If there is a carry from D3 and D4 during an ADD or SUB operation, the AC bit is set; otherwise, it is cleared. It is used for the instruction to perform binary coded decimal arithmetic."
},
{
"code": null,
"e": 56690,
"s": 56476,
"text": "AC, auxiliary carry flag − If there is a carry from D3 and D4 during an ADD or SUB operation, the AC bit is set; otherwise, it is cleared. It is used for the instruction to perform binary coded decimal arithmetic."
},
{
"code": null,
"e": 56883,
"s": 56690,
"text": "P, the parity flag − The parity flag represents the number of 1's in the accumulator register only. If the A register contains odd number of 1's, then P = 1; and for even number of 1's, P = 0."
},
{
"code": null,
"e": 57076,
"s": 56883,
"text": "P, the parity flag − The parity flag represents the number of 1's in the accumulator register only. If the A register contains odd number of 1's, then P = 1; and for even number of 1's, P = 0."
},
{
"code": null,
"e": 57303,
"s": 57076,
"text": "OV, the overflow flag − This flag is set whenever the result of a signed number operation is too large causing the high-order bit to overflow into the sign bit. It is used only to detect errors in signed arithmetic operations."
},
{
"code": null,
"e": 57530,
"s": 57303,
"text": "OV, the overflow flag − This flag is set whenever the result of a signed number operation is too large causing the high-order bit to overflow into the sign bit. It is used only to detect errors in signed arithmetic operations."
},
{
"code": null,
"e": 57633,
"s": 57530,
"text": "Show the status of CY, AC, and P flags after the addition of 9CH and 64H in the following instruction."
},
{
"code": null,
"e": 57645,
"s": 57633,
"text": "MOV A, #9CH"
},
{
"code": null,
"e": 57658,
"s": 57645,
"text": "ADD A, # 64H"
},
{
"code": null,
"e": 57888,
"s": 57658,
"text": "Solution: 9C 10011100 \n +64 01100100 \n 100 00000000 \n\t\t\t \nCY = 1 since there is a carry beyond D7 bit \nAC = 0 since there is a carry from D3 to D4 \nP = 0 because the accumulator has even number of 1's \n"
},
{
"code": null,
"e": 58056,
"s": 57888,
"text": "The 8051 microcontroller has a total of 128 bytes of RAM. We will discuss about the allocation of these 128 bytes of RAM and examine their usage as stack and register."
},
{
"code": null,
"e": 58236,
"s": 58056,
"text": "The 128 bytes of RAM inside the 8051 are assigned the address 00 to 7FH. They can be accessed directly as memory locations and are divided into three different groups as follows −"
},
{
"code": null,
"e": 58319,
"s": 58236,
"text": "32 bytes from 00H to 1FH locations are set aside for register banks and the stack."
},
{
"code": null,
"e": 58402,
"s": 58319,
"text": "32 bytes from 00H to 1FH locations are set aside for register banks and the stack."
},
{
"code": null,
"e": 58490,
"s": 58402,
"text": "16 bytes from 20H to 2FH locations are set aside for bit-addressable read/write memory."
},
{
"code": null,
"e": 58578,
"s": 58490,
"text": "16 bytes from 20H to 2FH locations are set aside for bit-addressable read/write memory."
},
{
"code": null,
"e": 58786,
"s": 58578,
"text": "80 bytes from 30H to 7FH locations are used for read and write storage; it is called as scratch pad. These 80 locations RAM are widely used for the purpose of storing data and parameters by 8051 programmers."
},
{
"code": null,
"e": 58994,
"s": 58786,
"text": "80 bytes from 30H to 7FH locations are used for read and write storage; it is called as scratch pad. These 80 locations RAM are widely used for the purpose of storing data and parameters by 8051 programmers."
},
{
"code": null,
"e": 59367,
"s": 58994,
"text": "A total of 32 bytes of RAM are set aside for the register banks and the stack. These 32 bytes are divided into four register banks in which each bank has 8 registers, R0–R7. RAM locations from 0 to 7 are set aside for bank 0 of R0–R7 where R0 is RAM location 0, R1 is RAM location 1, R2 is location 2, and so on, until the memory location 7, which belongs to R7 of bank 0."
},
{
"code": null,
"e": 59616,
"s": 59367,
"text": "The second bank of registers R0–R7 starts at RAM location 08 and goes to locations OFH. The third bank of R0–R7 starts at memory location 10H and goes to location to 17H. Finally, RAM locations 18H to 1FH are set aside for the fourth bank of R0–R7."
},
{
"code": null,
"e": 60013,
"s": 59616,
"text": "If RAM locations 00–1F are set aside for the four registers banks, which register bank of R0–R7 do we have access to when the 8051 is powered up? The answer is register bank 0; that is, RAM locations from 0 to 7 are accessed with the names R0 to R7 when programming the 8051. Because it is much easier to refer these RAM locations by names such as R0 to R7, rather than by their memory locations."
},
{
"code": null,
"e": 60352,
"s": 60013,
"text": "Register bank 0 is the default when the 8051 is powered up. We can switch to the other banks using PSW register. D4 and D3 bits of the PSW are used to select the desired register bank, since they can be accessed by the bit addressable instructions SETB and CLR. For example, \"SETB PSW.3\" will set PSW.3 = 1 and select the bank register 1."
},
{
"code": null,
"e": 60545,
"s": 60352,
"text": "The stack is a section of a RAM used by the CPU to store information such as data or memory address on temporary basis. The CPU needs this storage area considering limited number of registers."
},
{
"code": null,
"e": 61097,
"s": 60545,
"text": "As the stack is a section of a RAM, there are registers inside the CPU to point to it. The register used to access the stack is known as the stack pointer register. The stack pointer in the 8051 is 8-bits wide, and it can take a value of 00 to FFH. When the 8051 is initialized, the SP register contains the value 07H. This means that the RAM location 08 is the first location used for the stack. The storing operation of a CPU register in the stack is known as a PUSH, and getting the contents from the stack back into a CPU register is called a POP."
},
{
"code": null,
"e": 61507,
"s": 61097,
"text": "In the 8051, the stack pointer (SP) points to the last used location of the stack. When data is pushed onto the stack, the stack pointer (SP) is incremented by 1. When PUSH is executed, the contents of the register are saved on the stack and SP is incremented by 1. To push the registers onto the stack, we must use their RAM addresses. For example, the instruction \"PUSH 1\" pushes register R1 onto the stack."
},
{
"code": null,
"e": 61761,
"s": 61507,
"text": "Popping the contents of the stack back into a given register is the opposite to the process of pushing. With every pop operation, the top byte of the stack is copied to the register specified by the instruction and the stack pointer is decremented once."
},
{
"code": null,
"e": 62048,
"s": 61761,
"text": "The flow of program proceeds in a sequential manner, from one instruction to the next instruction, unless a control transfer instruction is executed. The various types of control transfer instruction in assembly language include conditional or unconditional jumps and call instructions."
},
{
"code": null,
"e": 62333,
"s": 62048,
"text": "Repeating a sequence of instructions a certain number of times is called a loop. An instruction DJNZ reg, label is used to perform a Loop operation. In this instruction, a register is decremented by 1; if it is not zero, then 8051 jumps to the target address referred to by the label."
},
{
"code": null,
"e": 62625,
"s": 62333,
"text": "The register is loaded with the counter for the number of repetitions prior to the start of the loop. In this instruction, both the registers decrement and the decision to jump are combined into a single instruction. The registers can be any of R0–R7. The counter can also be a RAM location."
},
{
"code": null,
"e": 62685,
"s": 62625,
"text": "Multiply 25 by 10 using the technique of repeated addition."
},
{
"code": null,
"e": 62812,
"s": 62685,
"text": "Solution − Multiplication can be achieved by adding the multiplicand repeatedly, as many times as the multiplier. For example,"
},
{
"code": null,
"e": 62831,
"s": 62812,
"text": "25 * 10 = 250(FAH)"
},
{
"code": null,
"e": 62885,
"s": 62831,
"text": "25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 + 25 = 250"
},
{
"code": null,
"e": 63152,
"s": 62885,
"text": " MOV A,#0 ;A = 0,clean ACC \n MOV R2,#10 ; the multiplier is replaced in R2 \n Add A,#25 ;add the multiplicand to the ACC \n\t\nAGAIN:DJNZ R2, \nAGAIN:repeat until R2 = 0 (10 times) \n\n MOV R5 , A ;save A in R5 ;R5 (FAH)\n"
},
{
"code": null,
"e": 63346,
"s": 63152,
"text": "Drawback in 8051 − Looping action with the instruction DJNZ Reg label is limited to 256 iterations only. If a conditional jump is not taken, then the instruction following the jump is executed."
},
{
"code": null,
"e": 63561,
"s": 63346,
"text": "When we use a loop inside another loop, it is called a nested loop. Two registers are used to hold the count when the maximum count is limited to 256. So we use this method to repeat the action more times than 256."
},
{
"code": null,
"e": 63569,
"s": 63561,
"text": "Example"
},
{
"code": null,
"e": 63590,
"s": 63569,
"text": "Write a program to −"
},
{
"code": null,
"e": 63631,
"s": 63590,
"text": "Load the accumulator with the value 55H."
},
{
"code": null,
"e": 63661,
"s": 63631,
"text": "Complement the ACC 700 times."
},
{
"code": null,
"e": 63861,
"s": 63661,
"text": "Solution − Since 700 is greater than 255 (the maximum capacity of any register), two registers are used to hold the count. The following code shows how to use two registers, R2 and R3, for the count."
},
{
"code": null,
"e": 64042,
"s": 63861,
"text": " MOV A,#55H ;A = 55H \n\t\nNEXT: MOV R3,#10 ;R3 the outer loop counter \nAGAIN:MOV R2,#70 ;R2 the inner loop counter \n\n CPL A ;complement"
},
{
"code": null,
"e": 64105,
"s": 64042,
"text": "The following table lists the conditional jumps used in 8051 −"
},
{
"code": null,
"e": 64342,
"s": 64105,
"text": "JZ (jump if A = 0) − In this instruction, the content of the accumulator is checked. If it is zero, then the 8051 jumps to the target address. JZ instruction can be used only for the accumulator, it does not apply to any other register."
},
{
"code": null,
"e": 64579,
"s": 64342,
"text": "JZ (jump if A = 0) − In this instruction, the content of the accumulator is checked. If it is zero, then the 8051 jumps to the target address. JZ instruction can be used only for the accumulator, it does not apply to any other register."
},
{
"code": null,
"e": 64756,
"s": 64579,
"text": "JNZ (jump if A is not equal to 0) − In this instruction, the content of the accumulator is checked to be non-zero. If it is not zero, then the 8051 jumps to the target address."
},
{
"code": null,
"e": 64933,
"s": 64756,
"text": "JNZ (jump if A is not equal to 0) − In this instruction, the content of the accumulator is checked to be non-zero. If it is not zero, then the 8051 jumps to the target address."
},
{
"code": null,
"e": 65337,
"s": 64933,
"text": "JNC (Jump if no carry, jumps if CY = 0) − The Carry flag bit in the flag (or PSW) register is used to make the decision whether to jump or not \"JNC label\". The CPU looks at the carry flag to see if it is raised (CY = 1). If it is not raised, then the CPU starts to fetch and execute instructions from the address of the label. If CY = 1, it will not jump but will execute the next instruction below JNC."
},
{
"code": null,
"e": 65741,
"s": 65337,
"text": "JNC (Jump if no carry, jumps if CY = 0) − The Carry flag bit in the flag (or PSW) register is used to make the decision whether to jump or not \"JNC label\". The CPU looks at the carry flag to see if it is raised (CY = 1). If it is not raised, then the CPU starts to fetch and execute instructions from the address of the label. If CY = 1, it will not jump but will execute the next instruction below JNC."
},
{
"code": null,
"e": 65822,
"s": 65741,
"text": "JC (Jump if carry, jumps if CY = 1) − If CY = 1, it jumps to the target address."
},
{
"code": null,
"e": 65903,
"s": 65822,
"text": "JC (Jump if carry, jumps if CY = 1) − If CY = 1, it jumps to the target address."
},
{
"code": null,
"e": 65928,
"s": 65903,
"text": "JB (jump if bit is high)"
},
{
"code": null,
"e": 65953,
"s": 65928,
"text": "JB (jump if bit is high)"
},
{
"code": null,
"e": 65978,
"s": 65953,
"text": "JNB (jump if bit is low)"
},
{
"code": null,
"e": 66003,
"s": 65978,
"text": "JNB (jump if bit is low)"
},
{
"code": null,
"e": 66177,
"s": 66003,
"text": "Note − It must be noted that all conditional jumps are short jumps, i.e., the address of the target must be within –128 to +127 bytes of the contents of the program counter."
},
{
"code": null,
"e": 66221,
"s": 66177,
"text": "There are two unconditional jumps in 8051 −"
},
{
"code": null,
"e": 66482,
"s": 66221,
"text": "LJMP (long jump) − LJMP is 3-byte instruction in which the first byte represents opcode, and the second and third bytes represent the 16-bit address of the target location. The 2-byte target address is to allow a jump to any memory location from 0000 to FFFFH."
},
{
"code": null,
"e": 66743,
"s": 66482,
"text": "LJMP (long jump) − LJMP is 3-byte instruction in which the first byte represents opcode, and the second and third bytes represent the 16-bit address of the target location. The 2-byte target address is to allow a jump to any memory location from 0000 to FFFFH."
},
{
"code": null,
"e": 67284,
"s": 66743,
"text": "SJMP (short jump) − It is a 2-byte instruction where the first byte is the opcode and the second byte is the relative address of the target location. The relative address ranges from 00H to FFH which is divided into forward and backward jumps; that is, within –128 to +127 bytes of memory relative to the address of the current PC (program counter). In case of forward jump, the target address can be within a space of 127 bytes from the current PC. In case of backward jump, the target address can be within –128 bytes from the current PC."
},
{
"code": null,
"e": 67825,
"s": 67284,
"text": "SJMP (short jump) − It is a 2-byte instruction where the first byte is the opcode and the second byte is the relative address of the target location. The relative address ranges from 00H to FFH which is divided into forward and backward jumps; that is, within –128 to +127 bytes of memory relative to the address of the current PC (program counter). In case of forward jump, the target address can be within a space of 127 bytes from the current PC. In case of backward jump, the target address can be within –128 bytes from the current PC."
},
{
"code": null,
"e": 68261,
"s": 67825,
"text": "All conditional jumps (JNC, JZ, and DJNZ) are short jumps because they are 2-byte instructions. In these instructions, the first byte represents opcode and the second byte represents the relative address. The target address is always relative to the value of the program counter. To calculate the target address, the second byte is added to the PC of the instruction immediately below the jump. Take a look at the program given below −"
},
{
"code": null,
"e": 69050,
"s": 68261,
"text": "Line PC Op-code Mnemonic Operand \n1 0000 ORG 0000 \n2 0000 7800 MOV R0,#003 \n3 0002 7455 MOV A,#55H0 \n4 0004 6003 JZ NEXT \n5 0006 08 INC R0 \n6 0007 04 AGAIN: INC A \n7 0008 04 INC A \n8 0009 2477 NEXT: ADD A, #77h \n9 000B 5005 JNC OVER \n10 000D E4 CLR A\n11 000E F8 MOV R0, A \n12 000F F9 MOV R1, A \n13 0010 FA MOV R2, A \n14 0011 FB MOV R3, A \n15 0012 2B OVER: ADD A, R3 \n16 0013 50F2 JNC AGAIN \n17 0015 80FE HERE: SJMP HERE \n18 0017 END\n"
},
{
"code": null,
"e": 69238,
"s": 69050,
"text": "In case of a forward jump, the displacement value is a positive number between 0 to 127 (00 to 7F in hex). However, for a backward jump, the displacement is a negative value of 0 to –128."
},
{
"code": null,
"e": 69480,
"s": 69238,
"text": "CALL is used to call a subroutine or method. Subroutines are used to perform operations or tasks that need to be performed frequently. This makes a program more structured and saves memory space. There are two instructions − LCALL and ACALL."
},
{
"code": null,
"e": 69747,
"s": 69480,
"text": "LCALL is a 3-byte instruction where the first byte represents the opcode and the second and third bytes are used to provide the address of the target subroutine. LCALL can be used to call subroutines which are available within the 64K-byte address space of the 8051."
},
{
"code": null,
"e": 70283,
"s": 69747,
"text": "To make a successful return to the point after execution of the called subroutine, the CPU saves the address of the instruction immediately below the LCALL on the stack. Thus, when a subroutine is called, the control is transferred to that subroutine, and the processor saves the PC (program counter) on the stack and begins to fetch instructions from the new location. The instruction RET (return) transfers the control back to the caller after finishing execution of the subroutine. Every subroutine uses RET as the last instruction."
},
{
"code": null,
"e": 70676,
"s": 70283,
"text": "ACALL is a 2-byte instruction, in contrast to LCALL which is 3 bytes. The target address of the subroutine must be within 2K bytes because only 11 bits of the 2 bytes are used for address. The difference between the ACALL and LCALL is that the target address for LCALL can be anywhere within the 64K-bytes address space of the 8051, while the target address of CALL is within a 2K-byte range."
},
{
"code": null,
"e": 70859,
"s": 70676,
"text": "An addressing mode refers to how you are addressing a given memory location. There are five different ways or five addressing modes to execute this instruction which are as follows −"
},
{
"code": null,
"e": 70885,
"s": 70859,
"text": "Immediate addressing mode"
},
{
"code": null,
"e": 70908,
"s": 70885,
"text": "Direct addressing mode"
},
{
"code": null,
"e": 70940,
"s": 70908,
"text": "Register direct addressing mode"
},
{
"code": null,
"e": 70974,
"s": 70940,
"text": "Register indirect addressing mode"
},
{
"code": null,
"e": 70998,
"s": 70974,
"text": "Indexed addressing mode"
},
{
"code": null,
"e": 71027,
"s": 70998,
"text": "Let's begin with an example."
},
{
"code": null,
"e": 71041,
"s": 71027,
"text": "MOV A, #6AH \n"
},
{
"code": null,
"e": 71067,
"s": 71041,
"text": "In general, we can write,"
},
{
"code": null,
"e": 71081,
"s": 71067,
"text": "MOV A, #data\n"
},
{
"code": null,
"e": 71195,
"s": 71081,
"text": "It is termed as immediate because 8-bit data is transferred immediately to the accumulator (destination operand)."
},
{
"code": null,
"e": 71675,
"s": 71195,
"text": "The following illustration describes the above instruction and its execution. The opcode 74H is saved at 0202 address. The data 6AH is saved at 0203 address in the program memory. After reading the opcode 74H, the data at the next program memory address is transferred to accumulator A (E0H is the address of accumulator). Since the instruction is of 2-bytes and is executed in one cycle, the program counter will be incremented by 2 and will point to 0204 of the program memory."
},
{
"code": null,
"e": 71830,
"s": 71675,
"text": "Note − The '#' symbol before 6AH indicates that the operand is a data (8 bit). In the absence of '#', the hexadecimal number would be taken as an address."
},
{
"code": null,
"e": 71967,
"s": 71830,
"text": "This is another way of addressing an operand. Here, the address of the data (source data) is given as an operand. Let’s take an example."
},
{
"code": null,
"e": 71980,
"s": 71967,
"text": "MOV A, 04H \n"
},
{
"code": null,
"e": 72208,
"s": 71980,
"text": "The register bank#0 (4th register) has the address 04H. When the MOV instruction is executed, the data stored in register 04H is moved to the accumulator. As the register 04H holds the data 1FH, 1FH is moved to the accumulator."
},
{
"code": null,
"e": 72388,
"s": 72208,
"text": "Note − We have not used '#' in direct addressing mode, unlike immediate mode. If we had used '#', the data value 04H would have been transferred to the accumulator instead of 1FH."
},
{
"code": null,
"e": 72480,
"s": 72388,
"text": "Now, take a look at the following illustration. It shows how the instruction gets executed."
},
{
"code": null,
"e": 73071,
"s": 72480,
"text": "As shown in the above illustration, this is a 2-byte instruction which requires 1 cycle to complete. The PC will be incremented by 2 and will point to 0204. The opcode for the instruction MOV A, address is E5H. When the instruction at 0202 is executed (E5H), the accumulator is made active and ready to receive data. Then the PC goes to the next address as 0203 and looks up the address of the location of 04H where the source data (to be transferred to accumulator) is located. At 04H, the control finds the data 1F and transfers it to the accumulator and hence the execution is completed."
},
{
"code": null,
"e": 73205,
"s": 73071,
"text": "In this addressing mode, we use the register name directly (as source operand). Let us try to understand with the help of an example."
},
{
"code": null,
"e": 73217,
"s": 73205,
"text": "MOV A, R4 \n"
},
{
"code": null,
"e": 73502,
"s": 73217,
"text": "At a time, the registers can take values from R0 to R7. There are 32 such registers. In order to use 32 registers with just 8 variables to address registers, register banks are used. There are 4 register banks named from 0 to 3. Each bank comprises of 8 registers named from R0 to R7."
},
{
"code": null,
"e": 73834,
"s": 73502,
"text": "At a time, a single register bank can be selected. Selection of a register bank is made possible through a Special Function Register (SFR) named Processor Status Word (PSW). PSW is an 8-bit SFR where each bit can be programmed as required. Bits are designated from PSW.0 to PSW.7. PSW.3 and PSW.4 are used to select register banks."
},
{
"code": null,
"e": 73927,
"s": 73834,
"text": "Now, take a look at the following illustration to get a clear understanding of how it works."
},
{
"code": null,
"e": 74305,
"s": 73927,
"text": "Opcode EC is used for MOV A, R4. The opcode is stored at the address 0202 and when it is executed, the control goes directly to R4 of the respected register bank (that is selected in PSW). If register bank #0 is selected, then the data from R4 of register bank #0 will be moved to the accumulator. Here 2F is stored at 04H. 04H represents the address of R4 of register bank #0."
},
{
"code": null,
"e": 74686,
"s": 74305,
"text": "Data (2F) movement is highlighted in bold. 2F is getting transferred to the accumulator from data memory location 0C H and is shown as dotted line. 0CH is the address location of Register 4 (R4) of register bank #1. The instruction above is 1 byte and requires 1 cycle for complete execution. What it means is, you can save program memory by using register direct addressing mode."
},
{
"code": null,
"e": 74773,
"s": 74686,
"text": "In this addressing mode, the address of the data is stored in the register as operand."
},
{
"code": null,
"e": 74786,
"s": 74773,
"text": "MOV A, @R0 \n"
},
{
"code": null,
"e": 75101,
"s": 74786,
"text": "Here the value inside R0 is considered as an address, which holds the data to be transferred to the accumulator. Example: If R0 has the value 20H, and data 2FH is stored at the address 20H, then the value 2FH will get transferred to the accumulator after executing this instruction. See the following illustration."
},
{
"code": null,
"e": 75443,
"s": 75101,
"text": "So the opcode for MOV A, @R0 is E6H. Assuming that the register bank #0 is selected, the R0 of register bank #0 holds the data 20H. Program control moves to 20H where it locates the data 2FH and it transfers 2FH to the accumulator. This is a 1-byte instruction and the program counter increments by 1 and moves to 0203 of the program memory."
},
{
"code": null,
"e": 75643,
"s": 75443,
"text": "Note − Only R0 and R1 are allowed to form a register indirect addressing instruction. In other words, the programmer can create an instruction either using @R0 or @R1. All register banks are allowed."
},
{
"code": null,
"e": 75767,
"s": 75643,
"text": "We will take two examples to understand the concept of indexed addressing mode. Take a look at the following instructions −"
},
{
"code": null,
"e": 75783,
"s": 75767,
"text": "MOVC A, @A+DPTR"
},
{
"code": null,
"e": 75787,
"s": 75783,
"text": "and"
},
{
"code": null,
"e": 75801,
"s": 75787,
"text": "MOVC A, @A+PC"
},
{
"code": null,
"e": 75919,
"s": 75801,
"text": "where DPTR is the data pointer and PC is the program counter (both are 16-bit registers). Consider the first example."
},
{
"code": null,
"e": 75936,
"s": 75919,
"text": "MOVC A, @A+DPTR\n"
},
{
"code": null,
"e": 76252,
"s": 75936,
"text": "The source operand is @A+DPTR. It contains the source data from this location. Here we are adding the contents of DPTR with the current content of the accumulator. This addition will give a new address which is the address of the source data. The data pointed by this address is then transferred to the accumulator."
},
{
"code": null,
"e": 76712,
"s": 76252,
"text": "The opcode is 93H. DPTR has the value 01FE, where 01 is located in DPH (higher 8 bits) and FE is located in DPL (lower 8 bits). Accumulator has the value 02H. Then a 16-bit addition is performed and 01FE H+02H results in 0200 H. Data at the location 0200H will get transferred to the accumulator. The previous value inside the accumulator (02H) will be replaced with the new data from 0200H. The new data in the accumulator is highlighted in the illustration."
},
{
"code": null,
"e": 76902,
"s": 76712,
"text": "This is a 1-byte instruction with 2 cycles needed for execution and the execution time required for this instruction is high compared to previous instructions (which were all 1 cycle each)."
},
{
"code": null,
"e": 77126,
"s": 76902,
"text": "The other example MOVC A, @A+PC works the same way as the above example. Instead of adding DPTR with the accumulator, here the data inside the program counter (PC) is added with the accumulator to obtain the target address."
},
{
"code": null,
"e": 77606,
"s": 77126,
"text": "A Special Function Register (or Special Purpose Register, or simply Special Register) is a register within a microprocessor that controls or monitors the various functions of a microprocessor. As the special registers are closely tied to some special function or status of the processor, they might not be directly writable by normal instructions (like add, move, etc.). Instead, some special registers in some processor architectures require special instructions to modify them."
},
{
"code": null,
"e": 77797,
"s": 77606,
"text": "In the 8051, register A, B, DPTR, and PSW are a part of the group of registers commonly referred to as SFR (special function registers). An SFR can be accessed by its name or by its address."
},
{
"code": null,
"e": 77859,
"s": 77797,
"text": "The following table shows a list of SFRs and their addresses."
},
{
"code": null,
"e": 77918,
"s": 77859,
"text": "Consider the following two points about the SFR addresses."
},
{
"code": null,
"e": 78098,
"s": 77918,
"text": "A special function register can have an address between 80H to FFH. These addresses are above 80H, as the addresses from 00 to 7FH are the addresses of RAM memory inside the 8051."
},
{
"code": null,
"e": 78278,
"s": 78098,
"text": "A special function register can have an address between 80H to FFH. These addresses are above 80H, as the addresses from 00 to 7FH are the addresses of RAM memory inside the 8051."
},
{
"code": null,
"e": 78425,
"s": 78278,
"text": "Not all the address space of 80 to FF are used by the SFR. Unused locations, 80H to FFH, are reserved and must not be used by the 8051 programmer."
},
{
"code": null,
"e": 78572,
"s": 78425,
"text": "Not all the address space of 80 to FF are used by the SFR. Unused locations, 80H to FFH, are reserved and must not be used by the 8051 programmer."
},
{
"code": null,
"e": 78658,
"s": 78572,
"text": "In the following example, the SFR registers’ names are replaced with their addresses."
},
{
"code": null,
"e": 78732,
"s": 78658,
"text": "We can select the corresponding Register Bank bit using RS0 and RS1 bits."
},
{
"code": null,
"e": 79043,
"s": 78732,
"text": "The Program Status Word (PSW) contains status bits to reflect the current state of the CPU. The 8051 variants provide one special function register, PSW, with this status information. The 8251 provides two additional status flags, Z and N, which are available in a second special function register called PSW1."
},
{
"code": null,
"e": 79353,
"s": 79043,
"text": "A timer is a specialized type of clock which is used to measure time intervals. A timer that counts from zero upwards for measuring time elapsed is often called a stopwatch. It is a device that counts down from a specified time interval and used to generate a time delay, for example, an hourglass is a timer."
},
{
"code": null,
"e": 79681,
"s": 79353,
"text": "A counter is a device that stores (and sometimes displays) the number of times a particular event or process occurred, with respect to a clock signal. It is used to count the events happening outside the microcontroller. In electronics, counters can be implemented quite easily using register-type circuits such as a flip-flop."
},
{
"code": null,
"e": 79751,
"s": 79681,
"text": "The points that differentiate a timer from a counter are as follows −"
},
{
"code": null,
"e": 80011,
"s": 79751,
"text": "The 8051 has two timers, Timer 0 and Timer 1. They can be used as timers or as event counters. Both Timer 0 and Timer 1 are 16-bit wide. Since the 8051 follows an 8-bit architecture, each 16 bit is accessed as two separate registers of low-byte and high-byte."
},
{
"code": null,
"e": 80340,
"s": 80011,
"text": "The 16-bit register of Timer 0 is accessed as low- and high-byte. The low-byte register is called TL0 (Timer 0 low byte) and the high-byte register is called TH0 (Timer 0 high byte). These registers can be accessed like any other register. For example, the instruction MOV TL0, #4H moves the value into the low-byte of Timer #0."
},
{
"code": null,
"e": 80668,
"s": 80340,
"text": "The 16-bit register of Timer 1 is accessed as low- and high-byte. The low-byte register is called TL1 (Timer 1 low byte) and the high-byte register is called TH1 (Timer 1 high byte). These registers can be accessed like any other register. For example, the instruction MOV TL1, #4H moves the value into the low-byte of Timer 1."
},
{
"code": null,
"e": 80997,
"s": 80668,
"text": "Both Timer 0 and Timer 1 use the same register to set the various timer operation modes. It is an 8-bit register in which the lower 4 bits are set aside for Timer 0 and the upper four bits for Timers. In each case, the lower 2 bits are used to set the timer mode in advance and the upper 2 bits are used to specify the location."
},
{
"code": null,
"e": 81058,
"s": 80997,
"text": "Gate − When set, the timer only runs while INT(0,1) is high."
},
{
"code": null,
"e": 81090,
"s": 81058,
"text": "C/T − Counter/Timer select bit."
},
{
"code": null,
"e": 81107,
"s": 81090,
"text": "M1 − Mode bit 1."
},
{
"code": null,
"e": 81124,
"s": 81107,
"text": "M0 − Mode bit 0."
},
{
"code": null,
"e": 81480,
"s": 81124,
"text": "Every timer has a means of starting and stopping. Some timers do this by software, some by hardware, and some have both software and hardware controls. 8051 timers have both software and hardware controls. The start and stop of a timer is controlled by software using the instruction SETB TR1 and CLR TR1 for timer 1, and SETB TR0 and CLR TR0 for timer 0."
},
{
"code": null,
"e": 81747,
"s": 81480,
"text": "The SETB instruction is used to start it and it is stopped by the CLR instruction. These instructions start and stop the timers as long as GATE = 0 in the TMOD register. Timers can be started and stopped by an external source by making GATE = 1 in the TMOD register."
},
{
"code": null,
"e": 82134,
"s": 81747,
"text": "This bit in the TMOD register is used to decide whether a timer is used as a delay generator or an event manager. If C/T = 0, it is used as a timer for timer delay generation. The clock source to create the time delay is the crystal frequency of the 8051. If C/T = 0, the crystal frequency attached to the 8051 also decides the speed at which the 8051 timer ticks at a regular interval."
},
{
"code": null,
"e": 82504,
"s": 82134,
"text": "Timer frequency is always 1/12th of the frequency of the crystal attached to the 8051. Although various 8051 based systems have an XTAL frequency of 10 MHz to 40 MHz, we normally work with the XTAL frequency of 11.0592 MHz. It is because the baud rate for serial communication of the 8051.XTAL = 11.0592 allows the 8051 system to communicate with the PC with no errors."
},
{
"code": null,
"e": 82982,
"s": 82504,
"text": "Both Timer 1 and Timer 0 in Mode 0 operate as 8-bit counters (with a divide-by-32 prescaler). Timer register is configured as a 13-bit register consisting of all the 8 bits of TH1 and the lower 5 bits of TL1. The upper 3 bits of TL1 are indeterminate and should be ignored. Setting the run flag (TR1) does not clear the register. The timer interrupt flag TF1 is set when the count rolls over from all 1s to all 0s. Mode 0 operation is the same for Timer 0 as it is for Timer 1."
},
{
"code": null,
"e": 83396,
"s": 82982,
"text": "Timer mode \"1\" is a 16-bit timer and is a commonly used mode. It functions in the same way as 13-bit mode except that all 16 bits are used. TLx is incremented starting from 0 to a maximum 255. Once the value 255 is reached, TLx resets to 0 and then THx is incremented by 1. As being a full 16-bit timer, the timer may contain up to 65536 distinct values and it will overflow back to 0 after 65,536 machine cycles."
},
{
"code": null,
"e": 83657,
"s": 83396,
"text": "Both the timer registers are configured as 8-bit counters (TL1 and TL0) with automatic reload. Overflow from TL1 (TL0) sets TF1 (TF0) and also reloads TL1 (TL0) with the contents of Th1 (TH0), which is preset by software. The reload leaves TH1 (TH0) unchanged."
},
{
"code": null,
"e": 84307,
"s": 83657,
"text": "The benefit of auto-reload mode is that you can have the timer to always contain a value from 200 to 255. If you use mode 0 or 1, you would have to check in the code to see the overflow and, in that case, reset the timer to 200. In this case, precious instructions check the value and/or get reloaded. In mode 2, the microcontroller takes care of this. Once you have configured a timer in mode 2, you don't have to worry about checking to see if the timer has overflowed, nor do you have to worry about resetting the value because the microcontroller hardware will do it all for you. The auto-reload mode is used for establishing a common baud rate."
},
{
"code": null,
"e": 84595,
"s": 84307,
"text": "Timer mode \"3\" is known as split-timer mode. When Timer 0 is placed in mode 3, it becomes two separate 8-bit timers. Timer 0 is TL0 and Timer 1 is TH0. Both the timers count from 0 to 255 and in case of overflow, reset back to 0. All the bits that are of Timer 1 will now be tied to TH0."
},
{
"code": null,
"e": 84837,
"s": 84595,
"text": "When Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be set in modes 0, 1 or 2, but it cannot be started/stopped as the bits that do that are now linked to TH0. The real timer 1 will be incremented with every machine cycle."
},
{
"code": null,
"e": 84949,
"s": 84837,
"text": "Decide the timer mode. Consider a 16-bit timer that runs continuously, and is independent of any external pins."
},
{
"code": null,
"e": 85285,
"s": 84949,
"text": "Initialize the TMOD SFR. Use the lowest 4 bits of TMOD and consider Timer 0. Keep the two bits, GATE 0 and C/T 0, as 0, since we want the timer to be independent of the external pins. As 16-bit mode is timer mode 1, clear T0M1 and set T0M0. Effectively, the only bit to turn on is bit 0 of TMOD. Now execute the following instruction −"
},
{
"code": null,
"e": 85300,
"s": 85285,
"text": "MOV TMOD,#01h\n"
},
{
"code": null,
"e": 85461,
"s": 85300,
"text": "Now, Timer 0 is in 16-bit timer mode, but the timer is not running. To start the timer in running mode, set the TR0 bit by executing the following instruction −"
},
{
"code": null,
"e": 85471,
"s": 85461,
"text": "SETB TR0\n"
},
{
"code": null,
"e": 85561,
"s": 85471,
"text": "Now, Timer 0 will immediately start counting, being incremented once every machine cycle."
},
{
"code": null,
"e": 85708,
"s": 85561,
"text": "A 16-bit timer can be read in two ways. Either read the actual value of the timer as a 16-bit number, or you detect when the timer has overflowed."
},
{
"code": null,
"e": 86002,
"s": 85708,
"text": "When a timer overflows from its highest value to 0, the microcontroller automatically sets the TFx bit in the TCON register. So instead of checking the exact value of the timer, the TFx bit can be checked. If TF0 is set, then Timer 0 has overflowed; if TF1 is set, then Timer 1 has overflowed."
},
{
"code": null,
"e": 86458,
"s": 86002,
"text": "An interrupt is a signal to the processor emitted by hardware or software indicating an event that needs immediate attention. Whenever an interrupt occurs, the controller completes the execution of the current instruction and starts the execution of an Interrupt Service Routine (ISR) or Interrupt Handler. ISR tells the processor or controller what to do when the interrupt occurs. The interrupts can be either hardware interrupts or software interrupts."
},
{
"code": null,
"e": 86777,
"s": 86458,
"text": "A hardware interrupt is an electronic alerting signal sent to the processor from an external device, like a disk controller or an external peripheral. For example, when we press a key on the keyboard or move the mouse, they trigger hardware interrupts which cause the processor to read the keystroke or mouse position."
},
{
"code": null,
"e": 87237,
"s": 86777,
"text": "A software interrupt is caused either by an exceptional condition or a special instruction in the instruction set which causes an interrupt when it is executed by the processor. For example, if the processor's arithmetic logic unit runs a command to divide a number by zero, to cause a divide-by-zero exception, thus causing the computer to abandon the calculation or display an error message. Software interrupt instructions work similar to subroutine calls."
},
{
"code": null,
"e": 87508,
"s": 87237,
"text": "The state of continuous monitoring is known as polling. The microcontroller keeps checking the status of other devices; and while doing so, it does no other operation and consumes all its processing time for monitoring. This problem can be addressed by using interrupts."
},
{
"code": null,
"e": 87717,
"s": 87508,
"text": "In the interrupt method, the controller responds only when an interruption occurs. Thus, the controller is not required to regularly monitor the status (flags, signals etc.) of interfaced and inbuilt devices."
},
{
"code": null,
"e": 87784,
"s": 87717,
"text": "Here is an analogy that differentiates an interrupt from polling −"
},
{
"code": null,
"e": 88189,
"s": 87784,
"text": "For every interrupt, there must be an interrupt service routine (ISR), or interrupt handler. When an interrupt occurs, the microcontroller runs the interrupt service routine. For every interrupt, there is a fixed location in memory that holds the address of its interrupt service routine, ISR. The table of memory locations set aside to hold the addresses of ISRs is called as the Interrupt Vector Table."
},
{
"code": null,
"e": 88239,
"s": 88189,
"text": "There are six interrupts including RESET in 8051."
},
{
"code": null,
"e": 88341,
"s": 88239,
"text": "When the reset pin is activated, the 8051 jumps to the address location 0000. This is power-up reset."
},
{
"code": null,
"e": 88443,
"s": 88341,
"text": "When the reset pin is activated, the 8051 jumps to the address location 0000. This is power-up reset."
},
{
"code": null,
"e": 88606,
"s": 88443,
"text": "Two interrupts are set aside for the timers: one for timer 0 and one for timer 1. Memory locations are 000BH and 001BH respectively in the interrupt vector table."
},
{
"code": null,
"e": 88769,
"s": 88606,
"text": "Two interrupts are set aside for the timers: one for timer 0 and one for timer 1. Memory locations are 000BH and 001BH respectively in the interrupt vector table."
},
{
"code": null,
"e": 89019,
"s": 88769,
"text": "Two interrupts are set aside for hardware external interrupts. Pin no. 12 and Pin no. 13 in Port 3 are for the external hardware interrupts INT0 and INT1, respectively. Memory locations are 0003H and 0013H respectively in the interrupt vector table."
},
{
"code": null,
"e": 89269,
"s": 89019,
"text": "Two interrupts are set aside for hardware external interrupts. Pin no. 12 and Pin no. 13 in Port 3 are for the external hardware interrupts INT0 and INT1, respectively. Memory locations are 0003H and 0013H respectively in the interrupt vector table."
},
{
"code": null,
"e": 89405,
"s": 89269,
"text": "Serial communication has a single interrupt that belongs to both receive and transmit. Memory location 0023H belongs to this interrupt."
},
{
"code": null,
"e": 89541,
"s": 89405,
"text": "Serial communication has a single interrupt that belongs to both receive and transmit. Memory location 0023H belongs to this interrupt."
},
{
"code": null,
"e": 89627,
"s": 89541,
"text": "When an interrupt gets active, the microcontroller goes through the following steps −"
},
{
"code": null,
"e": 89755,
"s": 89627,
"text": "The microcontroller closes the currently executing instruction and saves the address of the next instruction (PC) on the stack."
},
{
"code": null,
"e": 89883,
"s": 89755,
"text": "The microcontroller closes the currently executing instruction and saves the address of the next instruction (PC) on the stack."
},
{
"code": null,
"e": 89975,
"s": 89883,
"text": "It also saves the current status of all the interrupts internally (i.e., not on the stack)."
},
{
"code": null,
"e": 90067,
"s": 89975,
"text": "It also saves the current status of all the interrupts internally (i.e., not on the stack)."
},
{
"code": null,
"e": 90187,
"s": 90067,
"text": "It jumps to the memory location of the interrupt vector table that holds the address of the interrupts service routine."
},
{
"code": null,
"e": 90307,
"s": 90187,
"text": "It jumps to the memory location of the interrupt vector table that holds the address of the interrupts service routine."
},
{
"code": null,
"e": 90498,
"s": 90307,
"text": "The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it. It starts to execute the interrupt service subroutine, which is RETI (return from interrupt)."
},
{
"code": null,
"e": 90689,
"s": 90498,
"text": "The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it. It starts to execute the interrupt service subroutine, which is RETI (return from interrupt)."
},
{
"code": null,
"e": 90955,
"s": 90689,
"text": "Upon executing the RETI instruction, the microcontroller returns to the location where it was interrupted. First, it gets the program counter (PC) address from the stack by popping the top bytes of the stack into the PC. Then, it start to execute from that address."
},
{
"code": null,
"e": 91221,
"s": 90955,
"text": "Upon executing the RETI instruction, the microcontroller returns to the location where it was interrupted. First, it gets the program counter (PC) address from the stack by popping the top bytes of the stack into the PC. Then, it start to execute from that address."
},
{
"code": null,
"e": 91293,
"s": 91221,
"text": "Interrupt modules are of two types − level-triggered or edge-triggered."
},
{
"code": null,
"e": 91476,
"s": 91293,
"text": "Upon Reset, all the interrupts are disabled even if they are activated. The interrupts must be enabled using software in order for the microcontroller to respond to those interrupts."
},
{
"code": null,
"e": 91597,
"s": 91476,
"text": "IE (interrupt enable) register is responsible for enabling and disabling the interrupt. IE is a bitaddressable register."
},
{
"code": null,
"e": 91625,
"s": 91597,
"text": "EA − Global enable/disable."
},
{
"code": null,
"e": 91653,
"s": 91625,
"text": "EA − Global enable/disable."
},
{
"code": null,
"e": 91668,
"s": 91653,
"text": "- − Undefined."
},
{
"code": null,
"e": 91683,
"s": 91668,
"text": "- − Undefined."
},
{
"code": null,
"e": 91715,
"s": 91683,
"text": "ET2 − Enable Timer 2 interrupt."
},
{
"code": null,
"e": 91747,
"s": 91715,
"text": "ET2 − Enable Timer 2 interrupt."
},
{
"code": null,
"e": 91782,
"s": 91747,
"text": "ES − Enable Serial port interrupt."
},
{
"code": null,
"e": 91817,
"s": 91782,
"text": "ES − Enable Serial port interrupt."
},
{
"code": null,
"e": 91849,
"s": 91817,
"text": "ET1 − Enable Timer 1 interrupt."
},
{
"code": null,
"e": 91881,
"s": 91849,
"text": "ET1 − Enable Timer 1 interrupt."
},
{
"code": null,
"e": 91916,
"s": 91881,
"text": "EX1 − Enable External 1 interrupt."
},
{
"code": null,
"e": 91951,
"s": 91916,
"text": "EX1 − Enable External 1 interrupt."
},
{
"code": null,
"e": 91983,
"s": 91951,
"text": "ET0 − Enable Timer 0 interrupt."
},
{
"code": null,
"e": 92015,
"s": 91983,
"text": "ET0 − Enable Timer 0 interrupt."
},
{
"code": null,
"e": 92050,
"s": 92015,
"text": "EX0 − Enable External 0 interrupt."
},
{
"code": null,
"e": 92085,
"s": 92050,
"text": "EX0 − Enable External 0 interrupt."
},
{
"code": null,
"e": 92139,
"s": 92085,
"text": "To enable an interrupt, we take the following steps −"
},
{
"code": null,
"e": 92229,
"s": 92139,
"text": "Bit D7 of the IE register (EA) must be high to allow the rest of register to take effect."
},
{
"code": null,
"e": 92319,
"s": 92229,
"text": "Bit D7 of the IE register (EA) must be high to allow the rest of register to take effect."
},
{
"code": null,
"e": 92525,
"s": 92319,
"text": "If EA = 1, interrupts will be enabled and will be responded to, if their corresponding bits in IE are high. If EA = 0, no interrupts will respond, even if their associated pins in the IE register are high."
},
{
"code": null,
"e": 92731,
"s": 92525,
"text": "If EA = 1, interrupts will be enabled and will be responded to, if their corresponding bits in IE are high. If EA = 0, no interrupts will respond, even if their associated pins in the IE register are high."
},
{
"code": null,
"e": 92909,
"s": 92731,
"text": "We can alter the interrupt priority by assigning the higher priority to any one of the interrupts. This is accomplished by programming a register called IP (interrupt priority)."
},
{
"code": null,
"e": 93114,
"s": 92909,
"text": "The following figure shows the bits of IP register. Upon reset, the IP register contains all 0's. To give a higher priority to any of the interrupts, we make the corresponding bit in the IP register high."
},
{
"code": null,
"e": 93473,
"s": 93114,
"text": "What happens if the 8051 is executing an ISR that belongs to an interrupt and another one gets active? In such cases, a high-priority interrupt can interrupt a low-priority interrupt. This is known as interrupt inside interrupt. In 8051, a low-priority interrupt can be interrupted by a high-priority interrupt, but not by any another low-priority interrupt."
},
{
"code": null,
"e": 93847,
"s": 93473,
"text": "There are times when we need to test an ISR by way of simulation. This can be done with the simple instructions to set the interrupt high and thereby cause the 8051 to jump to the interrupt vector table. For example, set the IE bit as 1 for timer 1. An instruction SETB TF1 will interrupt the 8051 in whatever it is doing and force it to jump to the interrupt vector table."
},
{
"code": null,
"e": 93882,
"s": 93847,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 93893,
"s": 93882,
"text": " Amit Rana"
},
{
"code": null,
"e": 93928,
"s": 93893,
"text": "\n 36 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 93939,
"s": 93928,
"text": " Amit Rana"
},
{
"code": null,
"e": 93972,
"s": 93939,
"text": "\n 33 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 93985,
"s": 93972,
"text": " Ashraf Said"
},
{
"code": null,
"e": 94018,
"s": 93985,
"text": "\n 23 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 94039,
"s": 94018,
"text": " Smart Logic Academy"
},
{
"code": null,
"e": 94074,
"s": 94039,
"text": "\n 66 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 94092,
"s": 94074,
"text": " NerdyElectronics"
},
{
"code": null,
"e": 94127,
"s": 94092,
"text": "\n 49 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 94146,
"s": 94127,
"text": " Rahul Shrivastava"
},
{
"code": null,
"e": 94153,
"s": 94146,
"text": " Print"
},
{
"code": null,
"e": 94164,
"s": 94153,
"text": " Add Notes"
}
] |
How to write a C program to find the roots of a quadratic equation?
|
Applying the software development method to solve any problem in C Language
Find roots of a quadratic equation, ax2+bx+c.
There will be 2 roots for given quadratic equation.
Input − a,b,c values
Output − r1, r2 values
r1=−b+b2−4ac2a
r2=−b−b2−4ac2a
Start
Read a, b, c values
Compute d = b2 4ac
if d > 0 thenr1 = b+ sqrt (d)/(2*a)r2 = b sqrt(d)/(2*a)
r1 = b+ sqrt (d)/(2*a)
r2 = b sqrt(d)/(2*a)
Otherwise if d = 0 thencompute r1 = -b/2a, r2=-b/2aprint r1,r2 values
compute r1 = -b/2a, r2=-b/2a
print r1,r2 values
Otherwise if d < 0 then print roots are imaginary
Stop
# include<stdio.h>
# include<conio.h>
# include<math.h>
main (){
float a,b,c,r1,r2,d;
printf (“enter the values of a b c”);
scanf (“ %f %f %f”, &a, &b, &c);
d= b*b – 4*a*c;
if (d>0){
r1 = -b+sqrt (d) / (2*a);
r2 = -b-sqrt (d) / (2*a);
printf (“The real roots = %f %f”, r1, r2);
}
else if (d= =0){
r1 = -b/(2*a);
r2 = -b/(2*a);
printf (“roots are equal =%f %f”, r1, r2);
}
else
printf(“Roots are imaginary”);
getch ();
}
Case 1: enter the values of a b c: 1 4 3
r1 = -1
r2 = -3
Case 2: enter the values of a b c: 1 2 1
r1 = -1
r2 = -1
Case 3: enter the values of a b c: 1 1 4
Roots are imaginary
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "Applying the software development method to solve any problem in C Language"
},
{
"code": null,
"e": 1184,
"s": 1138,
"text": "Find roots of a quadratic equation, ax2+bx+c."
},
{
"code": null,
"e": 1236,
"s": 1184,
"text": "There will be 2 roots for given quadratic equation."
},
{
"code": null,
"e": 1257,
"s": 1236,
"text": "Input − a,b,c values"
},
{
"code": null,
"e": 1280,
"s": 1257,
"text": "Output − r1, r2 values"
},
{
"code": null,
"e": 1295,
"s": 1280,
"text": "r1=−b+b2−4ac2a"
},
{
"code": null,
"e": 1310,
"s": 1295,
"text": "r2=−b−b2−4ac2a"
},
{
"code": null,
"e": 1316,
"s": 1310,
"text": "Start"
},
{
"code": null,
"e": 1336,
"s": 1316,
"text": "Read a, b, c values"
},
{
"code": null,
"e": 1355,
"s": 1336,
"text": "Compute d = b2 4ac"
},
{
"code": null,
"e": 1411,
"s": 1355,
"text": "if d > 0 thenr1 = b+ sqrt (d)/(2*a)r2 = b sqrt(d)/(2*a)"
},
{
"code": null,
"e": 1434,
"s": 1411,
"text": "r1 = b+ sqrt (d)/(2*a)"
},
{
"code": null,
"e": 1455,
"s": 1434,
"text": "r2 = b sqrt(d)/(2*a)"
},
{
"code": null,
"e": 1525,
"s": 1455,
"text": "Otherwise if d = 0 thencompute r1 = -b/2a, r2=-b/2aprint r1,r2 values"
},
{
"code": null,
"e": 1554,
"s": 1525,
"text": "compute r1 = -b/2a, r2=-b/2a"
},
{
"code": null,
"e": 1573,
"s": 1554,
"text": "print r1,r2 values"
},
{
"code": null,
"e": 1623,
"s": 1573,
"text": "Otherwise if d < 0 then print roots are imaginary"
},
{
"code": null,
"e": 1628,
"s": 1623,
"text": "Stop"
},
{
"code": null,
"e": 2120,
"s": 1628,
"text": "# include<stdio.h>\n# include<conio.h>\n# include<math.h>\nmain (){\n float a,b,c,r1,r2,d;\n printf (“enter the values of a b c”);\n scanf (“ %f %f %f”, &a, &b, &c);\n d= b*b – 4*a*c;\n if (d>0){\n r1 = -b+sqrt (d) / (2*a);\n r2 = -b-sqrt (d) / (2*a);\n printf (“The real roots = %f %f”, r1, r2);\n }\n else if (d= =0){\n r1 = -b/(2*a);\n r2 = -b/(2*a);\n printf (“roots are equal =%f %f”, r1, r2);\n }\n else\n printf(“Roots are imaginary”);\n getch ();\n}"
},
{
"code": null,
"e": 2307,
"s": 2120,
"text": "Case 1: enter the values of a b c: 1 4 3\n r1 = -1\n r2 = -3\nCase 2: enter the values of a b c: 1 2 1\n r1 = -1\n r2 = -1\nCase 3: enter the values of a b c: 1 1 4\nRoots are imaginary"
}
] |
Appending CSV files. Power BI, R, Power Shell or CMD | by Peter Hui | Towards Data Science
|
Have you ever had to combine multiple CSV files? I’m sure it’s a task every data analyst or data scientist must do at some point, and a strange task really. Why are they separated in the first place? Isn’t it better to connect to the source? Sometimes the best solution may not always be possible.
If you find yourself opening Excel, copying files and juggling 10 different workbooks, then this article is for you. I’ll show you different ways of appending files. Not only will you save time, but it will save you from errors as well. Trust me, I used to do this before I discovered Power BI and R.
If you don’t have to do this and you are well acquainted with Power BI and R, then I’m sure you will find some interesting scripts with command line and Power Shell.
Let’s get started.
I have 6 files from the image here and they have 29 columns in each file.
These are all located in one folder. The end result I am trying to get is a bigger file that combines all 6 into one. The number here doesn’t matter, it can be 6 or 100. The process is still the same :)
Why are we combining these? Reasons varies. Sometimes it’s easier to work with a big table for a simple analysis. Sometimes it maybe because of a data type issue and files cannot be loaded. In whatever case, there are different tools to append these files.
With Power BI can simply go to Power BI and use the connect to the folder to connect it all.
Here you go — all the files in Power Query for you to combine and load.
Sometimes Power BI may find a data error and won’t be able to load these files. Here is an article on some of the errors and how to fix them.
Power BI won’t be able to load all these files because of a column error. Sometimes one single cell may have letters but instead Power BI has categorized that column as numeric. This will cause and error.
As a quick tip, delete the “change types” step when loading files. It seems to cause errors more than it is useful. If I remove this step, you can see that Power BI is able to load it all.
PRO: No code, just clicks. Simple navigation and GUI. Allows you to do other type of analysis by table and functions using Table functions and custom functions.
CON: Slow, may not work and require trouble shooting if there are data type errors. Frustrating if you have a large amount of files and discovering a type error after waiting.
Here I can use the package call VROOM, get all the file names in the folder and combine it all.
In R Studio type in
library(vroom)setwd("Your folder directory")Files = dir_ls(glob = "*.csv")Files_Combined = vroom(Files)
The script here says to set your working directory, using dir_ls, filter for anything that ends with “.csv” and save it into a variable call files. Then vroom() reads the “Files” and assigns it to the end variable call Files_Combined.
Here — it didn’t exactly work for me because one of the file has 150 columns.
To correct this, you can use map instead. If you are not familiar with R, map applies a function over the variable provided. In this case it is the Files — which contains the names of the CSV files we want to load. The function here would be vroom() which is the load function.
library(vroom)setwd("Your folder directory")Files = dir_ls(glob = "*csv")Files_Combined = map(Files, ~vroom(.x))
Here all the files will be loaded but in list format. You can then choose the files you want by sub setting. You can use Files_Combined[1:3] or refer to the actual file itself using names Files_Combined[“your_file_name”].
PRO:Very fast! Also really like the sound of it :) Able to load all the files in a list format in 5 seconds.
CON: Assumes you have same number of column headers. I have to do some tweaking to see which file has extra columns before running vroom. Cannot bind rows if one column in data frame one is numeric and the other one is character.
Here is the script to combine these files into a CSV document. You can type in “PowerShell ISE” in the start up menu and PowerShell will be loaded.
A blue screen will appear — don’t worry it’s not the blue screen of death. :)
Here you can type in.
cd "Your folder directory"Get-ChildItem -Filter *csv | Get-Content | Add-Content "Combined.csv"
Get-ChildItem will list all the files that are in that folder. If you wish, you can even use -Recurse and it will list all the files in the relevant sub-folders as well. Get-Content takes the content of each of the CSVs and Add-Content will add the content into a new file call “combined.csv”.
Nifty :)
PRO: Reliable. Doesn’t throw type errors. It just does what you tell it to do.
CON: It’s great, no issues. Happy to see that it didn’t throw any errors! Can be both a good and bad thing, the extra column didn’t get appended into the new file.
This one is my favorite. Simply type in CMD in your start up menu and a black screen will appear. Don’t worry it’s just the command prompt.
cd "your folder directory"copy *csv combined.csv
This simple line will copy all the CSV files in the folder you have created into a new file call “combined.csv”.
Here it says to copy everything that ends with “csv” and put them into a document call “combined.csv”.
The great thing about this is you can add in grep to filter for values you want before combining.
grep "your_item" *csv >> item.csv
Here you “grep” your item from all the CSV files in that folder and export it into a new file call “item.csv”
I do like this one :)
Image you have to search for one single item, let’s say an account number in 200 files? grep with CMD is your friend.
PRO: Very fast and no issues. Copied everything in 3 seconds.
CON: A bit cryptic if you don’t know what you are reading.
There are different tools available to append CSVs.
The major headache, at least for me, is dealing with type issues. Both PowerShell and CMD can by pass all that and provide you with a table for analysis.
If you are just looking to append files, do some filtering and work on a combined document, use PowerShell or CMD. You can use Power BI or R to do the analysis after without worrying about the data format issues. I haven’t tried CSVKIT yet, but when I do, I’ll sure let you know.
Someone once asked me, “Why do you bother writing? You make <5 dollars an article anyways”. It’s a good question. The truth is, I learned a lot from others. I think it’s important to share knowledge. No one got to where they are today without another’s help. We all rely on each other, both directly and indirectly.
Thanks! Stay safe and good luck to your data journey :)
|
[
{
"code": null,
"e": 470,
"s": 172,
"text": "Have you ever had to combine multiple CSV files? I’m sure it’s a task every data analyst or data scientist must do at some point, and a strange task really. Why are they separated in the first place? Isn’t it better to connect to the source? Sometimes the best solution may not always be possible."
},
{
"code": null,
"e": 771,
"s": 470,
"text": "If you find yourself opening Excel, copying files and juggling 10 different workbooks, then this article is for you. I’ll show you different ways of appending files. Not only will you save time, but it will save you from errors as well. Trust me, I used to do this before I discovered Power BI and R."
},
{
"code": null,
"e": 937,
"s": 771,
"text": "If you don’t have to do this and you are well acquainted with Power BI and R, then I’m sure you will find some interesting scripts with command line and Power Shell."
},
{
"code": null,
"e": 956,
"s": 937,
"text": "Let’s get started."
},
{
"code": null,
"e": 1030,
"s": 956,
"text": "I have 6 files from the image here and they have 29 columns in each file."
},
{
"code": null,
"e": 1233,
"s": 1030,
"text": "These are all located in one folder. The end result I am trying to get is a bigger file that combines all 6 into one. The number here doesn’t matter, it can be 6 or 100. The process is still the same :)"
},
{
"code": null,
"e": 1490,
"s": 1233,
"text": "Why are we combining these? Reasons varies. Sometimes it’s easier to work with a big table for a simple analysis. Sometimes it maybe because of a data type issue and files cannot be loaded. In whatever case, there are different tools to append these files."
},
{
"code": null,
"e": 1583,
"s": 1490,
"text": "With Power BI can simply go to Power BI and use the connect to the folder to connect it all."
},
{
"code": null,
"e": 1655,
"s": 1583,
"text": "Here you go — all the files in Power Query for you to combine and load."
},
{
"code": null,
"e": 1797,
"s": 1655,
"text": "Sometimes Power BI may find a data error and won’t be able to load these files. Here is an article on some of the errors and how to fix them."
},
{
"code": null,
"e": 2002,
"s": 1797,
"text": "Power BI won’t be able to load all these files because of a column error. Sometimes one single cell may have letters but instead Power BI has categorized that column as numeric. This will cause and error."
},
{
"code": null,
"e": 2191,
"s": 2002,
"text": "As a quick tip, delete the “change types” step when loading files. It seems to cause errors more than it is useful. If I remove this step, you can see that Power BI is able to load it all."
},
{
"code": null,
"e": 2352,
"s": 2191,
"text": "PRO: No code, just clicks. Simple navigation and GUI. Allows you to do other type of analysis by table and functions using Table functions and custom functions."
},
{
"code": null,
"e": 2528,
"s": 2352,
"text": "CON: Slow, may not work and require trouble shooting if there are data type errors. Frustrating if you have a large amount of files and discovering a type error after waiting."
},
{
"code": null,
"e": 2624,
"s": 2528,
"text": "Here I can use the package call VROOM, get all the file names in the folder and combine it all."
},
{
"code": null,
"e": 2644,
"s": 2624,
"text": "In R Studio type in"
},
{
"code": null,
"e": 2748,
"s": 2644,
"text": "library(vroom)setwd(\"Your folder directory\")Files = dir_ls(glob = \"*.csv\")Files_Combined = vroom(Files)"
},
{
"code": null,
"e": 2983,
"s": 2748,
"text": "The script here says to set your working directory, using dir_ls, filter for anything that ends with “.csv” and save it into a variable call files. Then vroom() reads the “Files” and assigns it to the end variable call Files_Combined."
},
{
"code": null,
"e": 3061,
"s": 2983,
"text": "Here — it didn’t exactly work for me because one of the file has 150 columns."
},
{
"code": null,
"e": 3339,
"s": 3061,
"text": "To correct this, you can use map instead. If you are not familiar with R, map applies a function over the variable provided. In this case it is the Files — which contains the names of the CSV files we want to load. The function here would be vroom() which is the load function."
},
{
"code": null,
"e": 3452,
"s": 3339,
"text": "library(vroom)setwd(\"Your folder directory\")Files = dir_ls(glob = \"*csv\")Files_Combined = map(Files, ~vroom(.x))"
},
{
"code": null,
"e": 3674,
"s": 3452,
"text": "Here all the files will be loaded but in list format. You can then choose the files you want by sub setting. You can use Files_Combined[1:3] or refer to the actual file itself using names Files_Combined[“your_file_name”]."
},
{
"code": null,
"e": 3783,
"s": 3674,
"text": "PRO:Very fast! Also really like the sound of it :) Able to load all the files in a list format in 5 seconds."
},
{
"code": null,
"e": 4013,
"s": 3783,
"text": "CON: Assumes you have same number of column headers. I have to do some tweaking to see which file has extra columns before running vroom. Cannot bind rows if one column in data frame one is numeric and the other one is character."
},
{
"code": null,
"e": 4161,
"s": 4013,
"text": "Here is the script to combine these files into a CSV document. You can type in “PowerShell ISE” in the start up menu and PowerShell will be loaded."
},
{
"code": null,
"e": 4239,
"s": 4161,
"text": "A blue screen will appear — don’t worry it’s not the blue screen of death. :)"
},
{
"code": null,
"e": 4261,
"s": 4239,
"text": "Here you can type in."
},
{
"code": null,
"e": 4357,
"s": 4261,
"text": "cd \"Your folder directory\"Get-ChildItem -Filter *csv | Get-Content | Add-Content \"Combined.csv\""
},
{
"code": null,
"e": 4651,
"s": 4357,
"text": "Get-ChildItem will list all the files that are in that folder. If you wish, you can even use -Recurse and it will list all the files in the relevant sub-folders as well. Get-Content takes the content of each of the CSVs and Add-Content will add the content into a new file call “combined.csv”."
},
{
"code": null,
"e": 4660,
"s": 4651,
"text": "Nifty :)"
},
{
"code": null,
"e": 4739,
"s": 4660,
"text": "PRO: Reliable. Doesn’t throw type errors. It just does what you tell it to do."
},
{
"code": null,
"e": 4903,
"s": 4739,
"text": "CON: It’s great, no issues. Happy to see that it didn’t throw any errors! Can be both a good and bad thing, the extra column didn’t get appended into the new file."
},
{
"code": null,
"e": 5043,
"s": 4903,
"text": "This one is my favorite. Simply type in CMD in your start up menu and a black screen will appear. Don’t worry it’s just the command prompt."
},
{
"code": null,
"e": 5092,
"s": 5043,
"text": "cd \"your folder directory\"copy *csv combined.csv"
},
{
"code": null,
"e": 5205,
"s": 5092,
"text": "This simple line will copy all the CSV files in the folder you have created into a new file call “combined.csv”."
},
{
"code": null,
"e": 5308,
"s": 5205,
"text": "Here it says to copy everything that ends with “csv” and put them into a document call “combined.csv”."
},
{
"code": null,
"e": 5406,
"s": 5308,
"text": "The great thing about this is you can add in grep to filter for values you want before combining."
},
{
"code": null,
"e": 5440,
"s": 5406,
"text": "grep \"your_item\" *csv >> item.csv"
},
{
"code": null,
"e": 5550,
"s": 5440,
"text": "Here you “grep” your item from all the CSV files in that folder and export it into a new file call “item.csv”"
},
{
"code": null,
"e": 5572,
"s": 5550,
"text": "I do like this one :)"
},
{
"code": null,
"e": 5690,
"s": 5572,
"text": "Image you have to search for one single item, let’s say an account number in 200 files? grep with CMD is your friend."
},
{
"code": null,
"e": 5752,
"s": 5690,
"text": "PRO: Very fast and no issues. Copied everything in 3 seconds."
},
{
"code": null,
"e": 5811,
"s": 5752,
"text": "CON: A bit cryptic if you don’t know what you are reading."
},
{
"code": null,
"e": 5863,
"s": 5811,
"text": "There are different tools available to append CSVs."
},
{
"code": null,
"e": 6017,
"s": 5863,
"text": "The major headache, at least for me, is dealing with type issues. Both PowerShell and CMD can by pass all that and provide you with a table for analysis."
},
{
"code": null,
"e": 6297,
"s": 6017,
"text": "If you are just looking to append files, do some filtering and work on a combined document, use PowerShell or CMD. You can use Power BI or R to do the analysis after without worrying about the data format issues. I haven’t tried CSVKIT yet, but when I do, I’ll sure let you know."
},
{
"code": null,
"e": 6613,
"s": 6297,
"text": "Someone once asked me, “Why do you bother writing? You make <5 dollars an article anyways”. It’s a good question. The truth is, I learned a lot from others. I think it’s important to share knowledge. No one got to where they are today without another’s help. We all rely on each other, both directly and indirectly."
}
] |
Find maximum level sum in Binary Tree - GeeksforGeeks
|
11 May, 2021
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it.
Examples:
Input : 4
/ \
2 -5
/ \ /\
-1 3 -2 6
Output: 6
Explanation :
Sum of all nodes of 0'th level is 4
Sum of all nodes of 1'th level is -3
Sum of all nodes of 0'th level is 6
Hence maximum sum is 6
Input : 1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
Output : 17
This problem is a variation of the maximum width problem. The idea is to do a level order traversal of the tree. While doing traversal, process nodes of different levels separately. For every level being processed, compute the sum of nodes in the level and keep track of the maximum sum.
Below is the implementation of the above idea:
C++
Java
Python3
C#
Javascript
// A queue based C++ program to find maximum sum// of a level in Binary Tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node *left, *right;}; // Function to find the maximum sum of a level in tree// using level order traversalint maxLevelSum(struct Node* root){ // Base case if (root == NULL) return 0; // Initialize result int result = root->data; // Do Level order traversal keeping track of number // of nodes at every level. queue<Node*> q; q.push(root); while (!q.empty()) { // Get the size of queue when the level order // traversal for one level finishes int count = q.size(); // Iterate for all the nodes in the queue currently int sum = 0; while (count--) { // Dequeue an node from queue Node* temp = q.front(); q.pop(); // Add this node's value to current sum. sum = sum + temp->data; // Enqueue left and right children of // dequeued node if (temp->left != NULL) q.push(temp->left); if (temp->right != NULL) q.push(temp->right); } // Update the maximum node count value result = max(sum, result); } return result;} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); /* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ cout << "Maximum level sum is " << maxLevelSum(root) << endl; return 0;}
// A queue based Java program to find maximum// sum of a level in Binary Treeimport java.util.LinkedList;import java.util.Queue; class GFG{ // A binary tree node has data, pointer// to left child and a pointer to right// childstatic class Node{ int data; Node left, right; public Node(int data) { this.data = data; this.left = this.right = null; }}; // Function to find the maximum// sum of a level in tree// using level order traversalstatic int maxLevelSum(Node root){ // Base case if (root == null) return 0; // Initialize result int result = root.data; // Do Level order traversal keeping // track of number of nodes at every // level. Queue<Node> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { // Get the size of queue when the // level order traversal for one // level finishes int count = q.size(); // Iterate for all the nodes // in the queue currently int sum = 0; while (count-- > 0) { // Dequeue an node from queue Node temp = q.poll(); // Add this node's value // to current sum. sum = sum + temp.data; // Enqueue left and right children // of dequeued node if (temp.left != null) q.add(temp.left); if (temp.right != null) q.add(temp.right); } // Update the maximum node // count value result = Math.max(sum, result); } return result;} // Driver codepublic static void main(String[] args){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(8); root.right.right.left = new Node(6); root.right.right.right = new Node(7); /* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ System.out.println("Maximum level sum is " + maxLevelSum(root));}} // This code is contributed by sanjeev2552
# A queue based Python3 program to find# maximum sum of a level in Binary Treefrom collections import deque # A binary tree node has data, pointer# to left child and a pointer to right# childclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # Function to find the maximum sum# of a level in tree# using level order traversaldef maxLevelSum(root): # Base case if (root == None): return 0 # Initialize result result = root.data # Do Level order traversal keeping # track of number # of nodes at every level. q = deque() q.append(root) while (len(q) > 0): # Get the size of queue when the # level order traversal for one # level finishes count = len(q) # Iterate for all the nodes in # the queue currently sum = 0 while (count > 0): # Dequeue an node from queue temp = q.popleft() # Add this node's value to current sum. sum = sum + temp.data # Enqueue left and right children of # dequeued node if (temp.left != None): q.append(temp.left) if (temp.right != None): q.append(temp.right) count -= 1 # Update the maximum node count value result = max(sum, result) return result # Driver codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(8) root.right.right.left = Node(6) root.right.right.right = Node(7) # Constructed Binary tree is: # 1 # / \ # 2 3 # / \ \ # 4 5 8 # / \ # 6 7 print("Maximum level sum is", maxLevelSum(root)) # This code is contributed by mohit kumar 29
// A queue based C# program to find maximum// sum of a level in Binary Treeusing System;using System.Collections.Generic;class GFG{ // A binary tree node has data, pointer // to left child and a pointer to right // child public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; this.left = this.right = null; } }; // Function to find the maximum // sum of a level in tree // using level order traversal static int maxLevelSum(Node root) { // Base case if (root == null) return 0; // Initialize result int result = root.data; // Do Level order traversal keeping // track of number of nodes at every // level. Queue<Node> q = new Queue<Node>(); q.Enqueue(root); while (q.Count != 0) { // Get the size of queue when the // level order traversal for one // level finishes int count = q.Count; // Iterate for all the nodes // in the queue currently int sum = 0; while (count --> 0) { // Dequeue an node from queue Node temp = q.Dequeue(); // Add this node's value // to current sum. sum = sum + temp.data; // Enqueue left and right children // of dequeued node if (temp.left != null) q.Enqueue(temp.left); if (temp.right != null) q.Enqueue(temp.right); } // Update the maximum node // count value result = Math.Max(sum, result); } return result; } // Driver code public static void Main(String[] args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(8); root.right.right.left = new Node(6); root.right.right.right = new Node(7); /* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ Console.WriteLine("Maximum level sum is " + maxLevelSum(root)); }} // This code is contributed by gauravrajput1
<script>// A queue based Javascript program to find maximum// sum of a level in Binary Tree // A binary tree node has data, pointer// to left child and a pointer to right// child class Node { constructor(data) { this.data = data; this.left = this.right = null; } } // Function to find the maximum// sum of a level in tree// using level order traversal function maxLevelSum(root){ // Base case if (root == null) return 0; // Initialize result let result = root.data; // Do Level order traversal keeping // track of number of nodes at every // level. let q = []; q.push(root); while (q.length!=0) { // Get the size of queue when the // level order traversal for one // level finishes let count = q.length; // Iterate for all the nodes // in the queue currently let sum = 0; while (count-- > 0) { // Dequeue an node from queue let temp = q.shift(); // Add this node's value // to current sum. sum = sum + temp.data; // Enqueue left and right children // of dequeued node if (temp.left != null) q.push(temp.left); if (temp.right != null) q.push(temp.right); } // Update the maximum node // count value result = Math.max(sum, result); } return result;} // Driver codelet root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.right = new Node(8);root.right.right.left = new Node(6);root.right.right.right = new Node(7); /* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ document.write("Maximum level sum is " + maxLevelSum(root)); // This code is contributed by unknown2108</script>
Maximum level sum is 17
Complexity Analysis:
Time Complexity: O(N) where N is the total number of nodes in the tree.In level order traversal, every node of the tree is processed once, and hence the complexity due to the level order traversal is O(N) if there are total N nodes in the tree. Also, while processing every node, we are maintaining the sum at each level, however, this does not affect the overall time complexity. Therefore, the time complexity is O(N).
Auxiliary Space: O(w) where w is the maximum width of the tree.In level order traversal, a queue is maintained whose maximum size at any moment can go up to the maximum width of the binary tree.
YouTubeGeeksforGeeks502K subscribersFind maximum level sum in Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:10•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oiStyIvqwCg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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.
muskan_garg
sanjeev2552
mohit kumar 29
GauravRajput1
unknown2108
Amazon
tree-level-order
Queue
Tree
Amazon
Queue
Tree
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)
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
|
[
{
"code": null,
"e": 25170,
"s": 25142,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 25275,
"s": 25170,
"text": "Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it."
},
{
"code": null,
"e": 25286,
"s": 25275,
"text": "Examples: "
},
{
"code": null,
"e": 25754,
"s": 25286,
"text": "Input : 4\n / \\\n 2 -5\n / \\ /\\\n -1 3 -2 6\nOutput: 6\nExplanation :\nSum of all nodes of 0'th level is 4\nSum of all nodes of 1'th level is -3\nSum of all nodes of 0'th level is 6\nHence maximum sum is 6\n\nInput : 1\n / \\\n 2 3\n / \\ \\\n 4 5 8\n / \\\n 6 7 \nOutput : 17"
},
{
"code": null,
"e": 26042,
"s": 25754,
"text": "This problem is a variation of the maximum width problem. The idea is to do a level order traversal of the tree. While doing traversal, process nodes of different levels separately. For every level being processed, compute the sum of nodes in the level and keep track of the maximum sum."
},
{
"code": null,
"e": 26089,
"s": 26042,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 26093,
"s": 26089,
"text": "C++"
},
{
"code": null,
"e": 26098,
"s": 26093,
"text": "Java"
},
{
"code": null,
"e": 26106,
"s": 26098,
"text": "Python3"
},
{
"code": null,
"e": 26109,
"s": 26106,
"text": "C#"
},
{
"code": null,
"e": 26120,
"s": 26109,
"text": "Javascript"
},
{
"code": "// A queue based C++ program to find maximum sum// of a level in Binary Tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; struct Node *left, *right;}; // Function to find the maximum sum of a level in tree// using level order traversalint maxLevelSum(struct Node* root){ // Base case if (root == NULL) return 0; // Initialize result int result = root->data; // Do Level order traversal keeping track of number // of nodes at every level. queue<Node*> q; q.push(root); while (!q.empty()) { // Get the size of queue when the level order // traversal for one level finishes int count = q.size(); // Iterate for all the nodes in the queue currently int sum = 0; while (count--) { // Dequeue an node from queue Node* temp = q.front(); q.pop(); // Add this node's value to current sum. sum = sum + temp->data; // Enqueue left and right children of // dequeued node if (temp->left != NULL) q.push(temp->left); if (temp->right != NULL) q.push(temp->right); } // Update the maximum node count value result = max(sum, result); } return result;} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); /* Constructed Binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ cout << \"Maximum level sum is \" << maxLevelSum(root) << endl; return 0;}",
"e": 28357,
"s": 26120,
"text": null
},
{
"code": "// A queue based Java program to find maximum// sum of a level in Binary Treeimport java.util.LinkedList;import java.util.Queue; class GFG{ // A binary tree node has data, pointer// to left child and a pointer to right// childstatic class Node{ int data; Node left, right; public Node(int data) { this.data = data; this.left = this.right = null; }}; // Function to find the maximum// sum of a level in tree// using level order traversalstatic int maxLevelSum(Node root){ // Base case if (root == null) return 0; // Initialize result int result = root.data; // Do Level order traversal keeping // track of number of nodes at every // level. Queue<Node> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { // Get the size of queue when the // level order traversal for one // level finishes int count = q.size(); // Iterate for all the nodes // in the queue currently int sum = 0; while (count-- > 0) { // Dequeue an node from queue Node temp = q.poll(); // Add this node's value // to current sum. sum = sum + temp.data; // Enqueue left and right children // of dequeued node if (temp.left != null) q.add(temp.left); if (temp.right != null) q.add(temp.right); } // Update the maximum node // count value result = Math.max(sum, result); } return result;} // Driver codepublic static void main(String[] args){ Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(8); root.right.right.left = new Node(6); root.right.right.right = new Node(7); /* Constructed Binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ System.out.println(\"Maximum level sum is \" + maxLevelSum(root));}} // This code is contributed by sanjeev2552",
"e": 30607,
"s": 28357,
"text": null
},
{
"code": "# A queue based Python3 program to find# maximum sum of a level in Binary Treefrom collections import deque # A binary tree node has data, pointer# to left child and a pointer to right# childclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # Function to find the maximum sum# of a level in tree# using level order traversaldef maxLevelSum(root): # Base case if (root == None): return 0 # Initialize result result = root.data # Do Level order traversal keeping # track of number # of nodes at every level. q = deque() q.append(root) while (len(q) > 0): # Get the size of queue when the # level order traversal for one # level finishes count = len(q) # Iterate for all the nodes in # the queue currently sum = 0 while (count > 0): # Dequeue an node from queue temp = q.popleft() # Add this node's value to current sum. sum = sum + temp.data # Enqueue left and right children of # dequeued node if (temp.left != None): q.append(temp.left) if (temp.right != None): q.append(temp.right) count -= 1 # Update the maximum node count value result = max(sum, result) return result # Driver codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(8) root.right.right.left = Node(6) root.right.right.right = Node(7) # Constructed Binary tree is: # 1 # / \\ # 2 3 # / \\ \\ # 4 5 8 # / \\ # 6 7 print(\"Maximum level sum is\", maxLevelSum(root)) # This code is contributed by mohit kumar 29",
"e": 32632,
"s": 30607,
"text": null
},
{
"code": "// A queue based C# program to find maximum// sum of a level in Binary Treeusing System;using System.Collections.Generic;class GFG{ // A binary tree node has data, pointer // to left child and a pointer to right // child public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; this.left = this.right = null; } }; // Function to find the maximum // sum of a level in tree // using level order traversal static int maxLevelSum(Node root) { // Base case if (root == null) return 0; // Initialize result int result = root.data; // Do Level order traversal keeping // track of number of nodes at every // level. Queue<Node> q = new Queue<Node>(); q.Enqueue(root); while (q.Count != 0) { // Get the size of queue when the // level order traversal for one // level finishes int count = q.Count; // Iterate for all the nodes // in the queue currently int sum = 0; while (count --> 0) { // Dequeue an node from queue Node temp = q.Dequeue(); // Add this node's value // to current sum. sum = sum + temp.data; // Enqueue left and right children // of dequeued node if (temp.left != null) q.Enqueue(temp.left); if (temp.right != null) q.Enqueue(temp.right); } // Update the maximum node // count value result = Math.Max(sum, result); } return result; } // Driver code public static void Main(String[] args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.right = new Node(8); root.right.right.left = new Node(6); root.right.right.right = new Node(7); /* Constructed Binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ Console.WriteLine(\"Maximum level sum is \" + maxLevelSum(root)); }} // This code is contributed by gauravrajput1",
"e": 34859,
"s": 32632,
"text": null
},
{
"code": "<script>// A queue based Javascript program to find maximum// sum of a level in Binary Tree // A binary tree node has data, pointer// to left child and a pointer to right// child class Node { constructor(data) { this.data = data; this.left = this.right = null; } } // Function to find the maximum// sum of a level in tree// using level order traversal function maxLevelSum(root){ // Base case if (root == null) return 0; // Initialize result let result = root.data; // Do Level order traversal keeping // track of number of nodes at every // level. let q = []; q.push(root); while (q.length!=0) { // Get the size of queue when the // level order traversal for one // level finishes let count = q.length; // Iterate for all the nodes // in the queue currently let sum = 0; while (count-- > 0) { // Dequeue an node from queue let temp = q.shift(); // Add this node's value // to current sum. sum = sum + temp.data; // Enqueue left and right children // of dequeued node if (temp.left != null) q.push(temp.left); if (temp.right != null) q.push(temp.right); } // Update the maximum node // count value result = Math.max(sum, result); } return result;} // Driver codelet root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.right = new Node(8);root.right.right.left = new Node(6);root.right.right.right = new Node(7); /* Constructed Binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ document.write(\"Maximum level sum is \" + maxLevelSum(root)); // This code is contributed by unknown2108</script>",
"e": 36971,
"s": 34859,
"text": null
},
{
"code": null,
"e": 36995,
"s": 36971,
"text": "Maximum level sum is 17"
},
{
"code": null,
"e": 37016,
"s": 36995,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 37437,
"s": 37016,
"text": "Time Complexity: O(N) where N is the total number of nodes in the tree.In level order traversal, every node of the tree is processed once, and hence the complexity due to the level order traversal is O(N) if there are total N nodes in the tree. Also, while processing every node, we are maintaining the sum at each level, however, this does not affect the overall time complexity. Therefore, the time complexity is O(N)."
},
{
"code": null,
"e": 37632,
"s": 37437,
"text": "Auxiliary Space: O(w) where w is the maximum width of the tree.In level order traversal, a queue is maintained whose maximum size at any moment can go up to the maximum width of the binary tree."
},
{
"code": null,
"e": 38468,
"s": 37632,
"text": "YouTubeGeeksforGeeks502K subscribersFind maximum level sum in Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:10•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=oiStyIvqwCg\" 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": 38902,
"s": 38468,
"text": "This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 38914,
"s": 38902,
"text": "muskan_garg"
},
{
"code": null,
"e": 38926,
"s": 38914,
"text": "sanjeev2552"
},
{
"code": null,
"e": 38941,
"s": 38926,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 38955,
"s": 38941,
"text": "GauravRajput1"
},
{
"code": null,
"e": 38967,
"s": 38955,
"text": "unknown2108"
},
{
"code": null,
"e": 38974,
"s": 38967,
"text": "Amazon"
},
{
"code": null,
"e": 38991,
"s": 38974,
"text": "tree-level-order"
},
{
"code": null,
"e": 38997,
"s": 38991,
"text": "Queue"
},
{
"code": null,
"e": 39002,
"s": 38997,
"text": "Tree"
},
{
"code": null,
"e": 39009,
"s": 39002,
"text": "Amazon"
},
{
"code": null,
"e": 39015,
"s": 39009,
"text": "Queue"
},
{
"code": null,
"e": 39020,
"s": 39015,
"text": "Tree"
},
{
"code": null,
"e": 39118,
"s": 39020,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39172,
"s": 39118,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 39210,
"s": 39172,
"text": "Priority Queue | Set 1 (Introduction)"
},
{
"code": null,
"e": 39235,
"s": 39210,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 39270,
"s": 39235,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 39333,
"s": 39270,
"text": "Circular Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 39383,
"s": 39333,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 39418,
"s": 39383,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 39447,
"s": 39418,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 39488,
"s": 39447,
"text": "Inorder Tree Traversal without Recursion"
}
] |
C# - Reflection
|
Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace.
The System.Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values, and objects to the application.
Reflection has the following applications −
It allows view attribute information at runtime.
It allows view attribute information at runtime.
It allows examining various types in an assembly and instantiate these types.
It allows examining various types in an assembly and instantiate these types.
It allows late binding to methods and properties
It allows late binding to methods and properties
It allows creating new types at runtime and then performs some tasks using those types.
It allows creating new types at runtime and then performs some tasks using those types.
We have mentioned in the preceding chapter that using reflection you can view the attribute information.
The MemberInfo object of the System.Reflection class needs to be initialized for discovering the attributes associated with a class. To do this, you define an object of the target class, as −
System.Reflection.MemberInfo info = typeof(MyClass);
The following program demonstrates this −
using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute {
public readonly string Url;
public string Topic // Topic is a named parameter {
get {
return topic;
}
set {
topic = value;
}
}
public HelpAttribute(string url) // url is a positional parameter {
this.Url = url;
}
private string topic;
}
[HelpAttribute("Information on the class MyClass")]
class MyClass {
}
namespace AttributeAppl {
class Program {
static void Main(string[] args) {
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++) {
System.Console.WriteLine(attributes[i]);
}
Console.ReadKey();
}
}
}
When it is compiled and run, it displays the name of the custom attributes attached to the class MyClass −
HelpAttribute
In this example, we use the DeBugInfo attribute created in the previous chapter and use reflection to read metadata in the Rectangle class.
using System;
using System.Reflection;
namespace BugFixApplication {
//a custom attribute BugFix to be assigned to a class and its members
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class DeBugInfo : System.Attribute {
private int bugNo;
private string developer;
private string lastReview;
public string message;
public DeBugInfo(int bg, string dev, string d) {
this.bugNo = bg;
this.developer = dev;
this.lastReview = d;
}
public int BugNo {
get {
return bugNo;
}
}
public string Developer {
get {
return developer;
}
}
public string LastReview {
get {
return lastReview;
}
}
public string Message {
get {
return message;
}
set {
message = value;
}
}
}
[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
[DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
class Rectangle {
//member variables
protected double length;
protected double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
[DeBugInfo(55, "Zara Ali", "19/10/2012", Message = "Return type mismatch")]
public double GetArea() {
return length * width;
}
[DeBugInfo(56, "Zara Ali", "19/10/2012")]
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle(4.5, 7.5);
r.Display();
Type type = typeof(Rectangle);
//iterating through the attribtues of the Rectangle class
foreach (Object attributes in type.GetCustomAttributes(false)) {
DeBugInfo dbi = (DeBugInfo)attributes;
if (null != dbi) {
Console.WriteLine("Bug no: {0}", dbi.BugNo);
Console.WriteLine("Developer: {0}", dbi.Developer);
Console.WriteLine("Last Reviewed: {0}", dbi.LastReview);
Console.WriteLine("Remarks: {0}", dbi.Message);
}
}
//iterating through the method attribtues
foreach (MethodInfo m in type.GetMethods()) {
foreach (Attribute a in m.GetCustomAttributes(true)) {
DeBugInfo dbi = (DeBugInfo)a;
if (null != dbi) {
Console.WriteLine("Bug no: {0}, for Method: {1}", dbi.BugNo, m.Name);
Console.WriteLine("Developer: {0}", dbi.Developer);
Console.WriteLine("Last Reviewed: {0}", dbi.LastReview);
Console.WriteLine("Remarks: {0}", dbi.Message);
}
}
}
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Length: 4.5
Width: 7.5
Area: 33.75
Bug No: 49
Developer: Nuha Ali
Last Reviewed: 10/10/2012
Remarks: Unused variable
Bug No: 45
Developer: Zara Ali
Last Reviewed: 12/8/2012
Remarks: Return type mismatch
Bug No: 55, for Method: GetArea
Developer: Zara Ali
Last Reviewed: 19/10/2012
Remarks: Return type mismatch
Bug No: 56, for Method: Display
Developer: Zara Ali
Last Reviewed: 19/10/2012
Remarks:
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2447,
"s": 2270,
"text": "Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace."
},
{
"code": null,
"e": 2625,
"s": 2447,
"text": "The System.Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values, and objects to the application."
},
{
"code": null,
"e": 2669,
"s": 2625,
"text": "Reflection has the following applications −"
},
{
"code": null,
"e": 2718,
"s": 2669,
"text": "It allows view attribute information at runtime."
},
{
"code": null,
"e": 2767,
"s": 2718,
"text": "It allows view attribute information at runtime."
},
{
"code": null,
"e": 2845,
"s": 2767,
"text": "It allows examining various types in an assembly and instantiate these types."
},
{
"code": null,
"e": 2923,
"s": 2845,
"text": "It allows examining various types in an assembly and instantiate these types."
},
{
"code": null,
"e": 2972,
"s": 2923,
"text": "It allows late binding to methods and properties"
},
{
"code": null,
"e": 3021,
"s": 2972,
"text": "It allows late binding to methods and properties"
},
{
"code": null,
"e": 3109,
"s": 3021,
"text": "It allows creating new types at runtime and then performs some tasks using those types."
},
{
"code": null,
"e": 3197,
"s": 3109,
"text": "It allows creating new types at runtime and then performs some tasks using those types."
},
{
"code": null,
"e": 3302,
"s": 3197,
"text": "We have mentioned in the preceding chapter that using reflection you can view the attribute information."
},
{
"code": null,
"e": 3494,
"s": 3302,
"text": "The MemberInfo object of the System.Reflection class needs to be initialized for discovering the attributes associated with a class. To do this, you define an object of the target class, as −"
},
{
"code": null,
"e": 3547,
"s": 3494,
"text": "System.Reflection.MemberInfo info = typeof(MyClass);"
},
{
"code": null,
"e": 3589,
"s": 3547,
"text": "The following program demonstrates this −"
},
{
"code": null,
"e": 4457,
"s": 3589,
"text": "using System;\n\n[AttributeUsage(AttributeTargets.All)]\npublic class HelpAttribute : System.Attribute {\n public readonly string Url;\n \n public string Topic // Topic is a named parameter {\n get {\n return topic;\n }\n set {\n topic = value;\n }\n }\n public HelpAttribute(string url) // url is a positional parameter {\n this.Url = url;\n }\n private string topic;\n}\n\n[HelpAttribute(\"Information on the class MyClass\")]\nclass MyClass {\n\n}\n\nnamespace AttributeAppl {\n class Program {\n static void Main(string[] args) {\n System.Reflection.MemberInfo info = typeof(MyClass);\n object[] attributes = info.GetCustomAttributes(true);\n \n for (int i = 0; i < attributes.Length; i++) {\n System.Console.WriteLine(attributes[i]);\n }\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 4564,
"s": 4457,
"text": "When it is compiled and run, it displays the name of the custom attributes attached to the class MyClass −"
},
{
"code": null,
"e": 4579,
"s": 4564,
"text": "HelpAttribute\n"
},
{
"code": null,
"e": 4719,
"s": 4579,
"text": "In this example, we use the DeBugInfo attribute created in the previous chapter and use reflection to read metadata in the Rectangle class."
},
{
"code": null,
"e": 8003,
"s": 4719,
"text": "using System;\nusing System.Reflection;\n\nnamespace BugFixApplication {\n //a custom attribute BugFix to be assigned to a class and its members\n [AttributeUsage(\n AttributeTargets.Class |\n AttributeTargets.Constructor |\n AttributeTargets.Field |\n AttributeTargets.Method |\n AttributeTargets.Property,\n AllowMultiple = true)]\n\n public class DeBugInfo : System.Attribute {\n private int bugNo;\n private string developer;\n private string lastReview;\n public string message;\n \n public DeBugInfo(int bg, string dev, string d) {\n this.bugNo = bg;\n this.developer = dev;\n this.lastReview = d;\n }\n public int BugNo {\n get {\n return bugNo;\n }\n }\n public string Developer {\n get {\n return developer;\n }\n }\n public string LastReview {\n get {\n return lastReview;\n }\n }\n public string Message {\n get {\n return message;\n }\n set {\n message = value;\n }\n }\n }\n [DeBugInfo(45, \"Zara Ali\", \"12/8/2012\", Message = \"Return type mismatch\")]\n [DeBugInfo(49, \"Nuha Ali\", \"10/10/2012\", Message = \"Unused variable\")]\n \n class Rectangle {\n //member variables\n protected double length;\n protected double width;\n \n public Rectangle(double l, double w) {\n length = l;\n width = w;\n }\n [DeBugInfo(55, \"Zara Ali\", \"19/10/2012\", Message = \"Return type mismatch\")]\n public double GetArea() {\n return length * width;\n }\n [DeBugInfo(56, \"Zara Ali\", \"19/10/2012\")]\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n }//end class Rectangle\n \n class ExecuteRectangle {\n static void Main(string[] args) {\n Rectangle r = new Rectangle(4.5, 7.5);\n r.Display();\n Type type = typeof(Rectangle);\n \n //iterating through the attribtues of the Rectangle class\n foreach (Object attributes in type.GetCustomAttributes(false)) {\n DeBugInfo dbi = (DeBugInfo)attributes;\n \n if (null != dbi) {\n Console.WriteLine(\"Bug no: {0}\", dbi.BugNo);\n Console.WriteLine(\"Developer: {0}\", dbi.Developer);\n Console.WriteLine(\"Last Reviewed: {0}\", dbi.LastReview);\n Console.WriteLine(\"Remarks: {0}\", dbi.Message);\n }\n }\n \n //iterating through the method attribtues\n foreach (MethodInfo m in type.GetMethods()) {\n \n foreach (Attribute a in m.GetCustomAttributes(true)) {\n DeBugInfo dbi = (DeBugInfo)a;\n \n if (null != dbi) {\n Console.WriteLine(\"Bug no: {0}, for Method: {1}\", dbi.BugNo, m.Name);\n Console.WriteLine(\"Developer: {0}\", dbi.Developer);\n Console.WriteLine(\"Last Reviewed: {0}\", dbi.LastReview);\n Console.WriteLine(\"Remarks: {0}\", dbi.Message);\n }\n }\n }\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 8084,
"s": 8003,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 8484,
"s": 8084,
"text": "Length: 4.5\nWidth: 7.5\nArea: 33.75\nBug No: 49\nDeveloper: Nuha Ali\nLast Reviewed: 10/10/2012\nRemarks: Unused variable\nBug No: 45\nDeveloper: Zara Ali\nLast Reviewed: 12/8/2012\nRemarks: Return type mismatch\nBug No: 55, for Method: GetArea\nDeveloper: Zara Ali\nLast Reviewed: 19/10/2012\nRemarks: Return type mismatch\nBug No: 56, for Method: Display\nDeveloper: Zara Ali\nLast Reviewed: 19/10/2012\nRemarks: \n"
},
{
"code": null,
"e": 8521,
"s": 8484,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 8534,
"s": 8521,
"text": " Raja Biswas"
},
{
"code": null,
"e": 8568,
"s": 8534,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 8586,
"s": 8568,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 8619,
"s": 8586,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8633,
"s": 8619,
"text": " Peter Jepson"
},
{
"code": null,
"e": 8670,
"s": 8633,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 8685,
"s": 8670,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 8720,
"s": 8685,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 8735,
"s": 8720,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 8770,
"s": 8735,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8782,
"s": 8770,
"text": " Eric Frick"
},
{
"code": null,
"e": 8789,
"s": 8782,
"text": " Print"
},
{
"code": null,
"e": 8800,
"s": 8789,
"text": " Add Notes"
}
] |
Angular CLI - ng help Command
|
This chapter explains the syntax and options of ng help command along with an example.
An example for ng help command is given below −
ng help [options]
ng help command lists the available commands with their short descriptions.
Options are optional parameters.
An example for ng help command is given below −
\>Node ng help
Available Commands:
add Adds support for an external library to your project.
analytics Configures the gathering of Angular CLI usage metrics. See
https://v
8.angular.io/cli/usage-analytics-gathering.
build (b) Compiles an Angular app into an output directory named dist/ at the
given output path. Must be executed from within a workspace directory.
deploy Invokes the deploy builder for a specified project or for the default
project in the workspace.
config Retrieves or sets Angular configuration values in the angular.json
file
for the workspace.
doc (d) Opens the official Angular documentation (angular.io) in a browser,
an
d searches for a given keyword.
e2e (e) Builds and serves an Angular app, then runs end-to-end tests using
Pro
tractor.
generate (g) Generates and/or modifies files based on a schematic.
help Lists available commands and their short descriptions.
lint (l) Runs linting tools on Angular app code in a given project folder.
new (n) Creates a new workspace and an initial Angular app.
run Runs an Architect target with an optional custom builder configuration
defined in your project.
serve (s) Builds and serves your app, rebuilding on file changes.
test (t) Runs unit tests in a project.
update Updates your application and its dependencies. See
https://update.angular.io/
version (v) Outputs Angular CLI version.
xi18n (i18n-extract) Extracts i18n messages from source code.
For more detailed help run "ng [command name] --help"
In case of individual commands, use the --help or -h option with the command. First move to an angular project created using ng new command and then run the command. The chapter which explains the ng new command is available at https://www.tutorialspoint.com/angular_cli/angular_cli_ng_new.htm.
An example is given below −
\>Node\>TutorialsPoint> ng serve --help
Builds and serves your app, rebuilding on file changes.
usage: ng serve <project> [options]
arguments:
project
The name of the project to build. Can be an application or a library.
options:
--allowed-hosts
Whitelist of hosts that are allowed to access the dev server.
--aot
Build using Ahead of Time compilation.
--base-href
Base url for the application being built.
--browser-target
Target to serve.
--build-event-log
**EXPERIMENTAL** Output file path for Build Event Protocol events
--common-chunk
Use a separate bundle containing code used across multiple bundles.
--configuration (-c)
A named build target, as specified in the "configurations" section of angular.json.
Each named target is accompanied by a configuration of option defaults for t hat target.
Setting this explicitly overrides the "--prod" flag
--deploy-url
URL where files will be deployed.
--disable-host-check
Don't verify connected clients are part of allowed hosts.
--eval-source-map
Output in-file eval sourcemaps.
--help
Shows a help message for this command in the console.
--hmr
Enable hot module replacement.
--hmr-warning
Show a warning when the --hmr option is enabled.
--host
Host to listen on.
--live-reload
Whether to reload the page on change, using live-reload.
--open (-o)
Opens the url in default browser.
--optimization
Enables optimization of the build output.
--poll
Enable and define the file watching poll time period in milliseconds.
--port
Port to listen on.
--prod
Shorthand for "--configuration=production".
When true, sets the build configuration to the production target.
By default, the production target is set up in the workspace
configuration such that all builds make use of bundling, limited tree-shaking, and also
limited
dead code elimination.
--progress
Log progress to the console while building.
--proxy-config
Proxy configuration file.
--public-host
The URL that the browser client (or live-reload client, if enabled)
should u
see to connect to the development server. Use for a complex dev server setup,
such as one with reverse proxies.
--serve-path
The pathname where the app will be served.
--serve-path-default-warning
Show a warning when deploy-url/base-href use unsupported serve path
values.
--source-map
Output sourcemaps.
--ssl
Serve using HTTPS.
--ssl-cert
SSL certificate to use for serving HTTPS.
--ssl-key
SSL key to use for serving HTTPS.
--vendor-chunk
Use a separate bundle containing only vendor libraries.
--vendor-source-map
Resolve vendor packages sourcemaps.
--verbose
Adds more details to output logging.
--watch
Rebuild on change.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2162,
"s": 2075,
"text": "This chapter explains the syntax and options of ng help command along with an example."
},
{
"code": null,
"e": 2210,
"s": 2162,
"text": "An example for ng help command is given below −"
},
{
"code": null,
"e": 2229,
"s": 2210,
"text": "ng help [options]\n"
},
{
"code": null,
"e": 2305,
"s": 2229,
"text": "ng help command lists the available commands with their short descriptions."
},
{
"code": null,
"e": 2338,
"s": 2305,
"text": "Options are optional parameters."
},
{
"code": null,
"e": 2386,
"s": 2338,
"text": "An example for ng help command is given below −"
},
{
"code": null,
"e": 3918,
"s": 2386,
"text": "\\>Node ng help\nAvailable Commands:\n add Adds support for an external library to your project.\n analytics Configures the gathering of Angular CLI usage metrics. See\nhttps://v\n8.angular.io/cli/usage-analytics-gathering.\n build (b) Compiles an Angular app into an output directory named dist/ at the\ngiven output path. Must be executed from within a workspace directory.\n deploy Invokes the deploy builder for a specified project or for the default\nproject in the workspace.\n config Retrieves or sets Angular configuration values in the angular.json\nfile\n for the workspace.\n doc (d) Opens the official Angular documentation (angular.io) in a browser,\nan\nd searches for a given keyword.\n e2e (e) Builds and serves an Angular app, then runs end-to-end tests using\nPro\ntractor.\n generate (g) Generates and/or modifies files based on a schematic.\n help Lists available commands and their short descriptions.\n lint (l) Runs linting tools on Angular app code in a given project folder.\n new (n) Creates a new workspace and an initial Angular app.\n run Runs an Architect target with an optional custom builder configuration\ndefined in your project.\n serve (s) Builds and serves your app, rebuilding on file changes.\n test (t) Runs unit tests in a project.\n update Updates your application and its dependencies. See\nhttps://update.angular.io/\n version (v) Outputs Angular CLI version.\n xi18n (i18n-extract) Extracts i18n messages from source code.\nFor more detailed help run \"ng [command name] --help\"\n"
},
{
"code": null,
"e": 4213,
"s": 3918,
"text": "In case of individual commands, use the --help or -h option with the command. First move to an angular project created using ng new command and then run the command. The chapter which explains the ng new command is available at https://www.tutorialspoint.com/angular_cli/angular_cli_ng_new.htm."
},
{
"code": null,
"e": 4241,
"s": 4213,
"text": "An example is given below −"
},
{
"code": null,
"e": 7175,
"s": 4241,
"text": "\\>Node\\>TutorialsPoint> ng serve --help\nBuilds and serves your app, rebuilding on file changes.\nusage: ng serve <project> [options]\narguments:\n project\n The name of the project to build. Can be an application or a library.\noptions:\n --allowed-hosts\n Whitelist of hosts that are allowed to access the dev server.\n --aot\n Build using Ahead of Time compilation.\n --base-href\n Base url for the application being built.\n --browser-target\n Target to serve.\n --build-event-log\n **EXPERIMENTAL** Output file path for Build Event Protocol events\n --common-chunk\n Use a separate bundle containing code used across multiple bundles.\n --configuration (-c)\n A named build target, as specified in the \"configurations\" section of angular.json.\n Each named target is accompanied by a configuration of option defaults for t hat target.\n Setting this explicitly overrides the \"--prod\" flag\n --deploy-url\n URL where files will be deployed.\n --disable-host-check\n Don't verify connected clients are part of allowed hosts.\n --eval-source-map\n Output in-file eval sourcemaps.\n --help\n Shows a help message for this command in the console.\n --hmr\n Enable hot module replacement.\n --hmr-warning\n Show a warning when the --hmr option is enabled.\n --host\n Host to listen on.\n --live-reload\n Whether to reload the page on change, using live-reload.\n --open (-o)\n Opens the url in default browser.\n --optimization\n Enables optimization of the build output.\n --poll\n Enable and define the file watching poll time period in milliseconds.\n --port\n Port to listen on.\n --prod\n Shorthand for \"--configuration=production\".\n When true, sets the build configuration to the production target.\n By default, the production target is set up in the workspace\nconfiguration such that all builds make use of bundling, limited tree-shaking, and also\nlimited\n dead code elimination.\n --progress\n Log progress to the console while building.\n --proxy-config\n Proxy configuration file.\n --public-host\n The URL that the browser client (or live-reload client, if enabled)\nshould u\nsee to connect to the development server. Use for a complex dev server setup,\nsuch as one with reverse proxies.\n --serve-path\n The pathname where the app will be served.\n --serve-path-default-warning\n Show a warning when deploy-url/base-href use unsupported serve path\nvalues.\n --source-map\n Output sourcemaps.\n --ssl\n Serve using HTTPS.\n --ssl-cert\n SSL certificate to use for serving HTTPS.\n --ssl-key\n SSL key to use for serving HTTPS.\n --vendor-chunk\n Use a separate bundle containing only vendor libraries.\n --vendor-source-map\n Resolve vendor packages sourcemaps.\n --verbose\n Adds more details to output logging.\n --watch\n Rebuild on change.\n"
},
{
"code": null,
"e": 7210,
"s": 7175,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7224,
"s": 7210,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7259,
"s": 7224,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7273,
"s": 7259,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7308,
"s": 7273,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7328,
"s": 7308,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7363,
"s": 7328,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7380,
"s": 7363,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7413,
"s": 7380,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7425,
"s": 7413,
"text": " Senol Atac"
},
{
"code": null,
"e": 7460,
"s": 7425,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7472,
"s": 7460,
"text": " Senol Atac"
},
{
"code": null,
"e": 7479,
"s": 7472,
"text": " Print"
},
{
"code": null,
"e": 7490,
"s": 7479,
"text": " Add Notes"
}
] |
Python PostgreSQL - Join
|
When you have divided the data in two tables you can fetch combined records from these two tables using Joins.
Assume we have created a table with name CRICKETERS and inserted 5 records into it as shown below −
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int,
Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
postgres=# insert into CRICKETERS values (
'Shikhar', 'Dhawan', 33, 'Delhi', 'India'
);
postgres=# insert into CRICKETERS values (
'Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'
);
postgres=# insert into CRICKETERS values (
'Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'
);
postgres=# insert into CRICKETERS values (
'Virat', 'Kohli', 30, 'Delhi', 'India'
);
postgres=# insert into CRICKETERS values (
'Rohit', 'Sharma', 32, 'Nagpur', 'India'
);
And, if we have created another table with name OdiStats and inserted 5 records into it as −
postgres=# CREATE TABLE ODIStats (
First_Name VARCHAR(255), Matches INT, Runs INT, AVG FLOAT,
Centuries INT, HalfCenturies INT
);
postgres=# insert into OdiStats values ('Shikhar', 133, 5518, 44.5, 17, 27);
postgres=# insert into OdiStats values ('Jonathan', 68, 2819, 51.25, 4, 22);
postgres=# insert into OdiStats values ('Kumara', 404, 14234, 41.99, 25, 93);
postgres=# insert into OdiStats values ('Virat', 239, 11520, 60.31, 43, 54);
postgres=# insert into OdiStats values ('Rohit', 218, 8686, 48.53, 24, 42);
Following statement retrieves data combining the values in these two tables −
postgres=# SELECT
Cricketers.First_Name, Cricketers.Last_Name, Cricketers.Country,
OdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies
from Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name;
first_name | last_name | country | matches | runs | centuries | halfcenturies
------------+------------+-------------+---------+-------+-----------+---------------
Shikhar | Dhawan | India | 133 | 5518 | 17 | 27
Jonathan | Trott | SouthAfrica | 68 | 2819 | 4 | 22
Kumara | Sangakkara | Srilanka | 404 | 14234 | 25 | 93
Virat | Kohli | India | 239 | 11520 | 43 | 54
Rohit | Sharma | India | 218 | 8686 | 24 | 42
(5 rows)
postgres=#
When you have divided the data in two tables you can fetch combined records from these two tables using Joins.
Following python program demonstrates the usage of the JOIN clause −
import psycopg2
#establishing the connection
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Setting auto commit false
conn.autocommit = True
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Retrieving single row
sql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID'''
#Executing the query
cursor.execute(sql)
#Fetching 1st row from the table
result = cursor.fetchall();
print(result)
#Commit your changes in the database
conn.commit()
#Closing the connection
conn.close()
[('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, 'Krishna@mymail.com', 'Hyderabad'),
('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102, 'Raja@mymail.com', 'Vishakhapatnam'),
('Sharukh', 'Sheik', 25, 'M', 8300.0, 103, 103, 'Krishna@mymail.com ', 'Pune'),
('Sarmista', 'Sharma', 26, 'F', 10000.0, 104, 104, 'Raja@mymail.com', 'Mumbai')]
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3316,
"s": 3205,
"text": "When you have divided the data in two tables you can fetch combined records from these two tables using Joins."
},
{
"code": null,
"e": 3416,
"s": 3316,
"text": "Assume we have created a table with name CRICKETERS and inserted 5 records into it as shown below −"
},
{
"code": null,
"e": 4038,
"s": 3416,
"text": "postgres=# CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, \n Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\npostgres=# insert into CRICKETERS values (\n 'Shikhar', 'Dhawan', 33, 'Delhi', 'India'\n);\npostgres=# insert into CRICKETERS values (\n 'Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'\n);\npostgres=# insert into CRICKETERS values (\n 'Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'\n);\npostgres=# insert into CRICKETERS values (\n 'Virat', 'Kohli', 30, 'Delhi', 'India'\n);\npostgres=# insert into CRICKETERS values (\n 'Rohit', 'Sharma', 32, 'Nagpur', 'India'\n);"
},
{
"code": null,
"e": 4131,
"s": 4038,
"text": "And, if we have created another table with name OdiStats and inserted 5 records into it as −"
},
{
"code": null,
"e": 4653,
"s": 4131,
"text": "postgres=# CREATE TABLE ODIStats (\n First_Name VARCHAR(255), Matches INT, Runs INT, AVG FLOAT, \n Centuries INT, HalfCenturies INT\n);\npostgres=# insert into OdiStats values ('Shikhar', 133, 5518, 44.5, 17, 27);\npostgres=# insert into OdiStats values ('Jonathan', 68, 2819, 51.25, 4, 22);\npostgres=# insert into OdiStats values ('Kumara', 404, 14234, 41.99, 25, 93);\npostgres=# insert into OdiStats values ('Virat', 239, 11520, 60.31, 43, 54);\npostgres=# insert into OdiStats values ('Rohit', 218, 8686, 48.53, 24, 42);"
},
{
"code": null,
"e": 4731,
"s": 4653,
"text": "Following statement retrieves data combining the values in these two tables −"
},
{
"code": null,
"e": 5536,
"s": 4731,
"text": "postgres=# SELECT\nCricketers.First_Name, Cricketers.Last_Name, Cricketers.Country,\nOdiStats.matches, OdiStats.runs, OdiStats.centuries, OdiStats.halfcenturies\nfrom Cricketers INNER JOIN OdiStats ON Cricketers.First_Name = OdiStats.First_Name;\nfirst_name | last_name | country | matches | runs | centuries | halfcenturies\n------------+------------+-------------+---------+-------+-----------+---------------\nShikhar | Dhawan | India | 133 | 5518 | 17 | 27\nJonathan | Trott | SouthAfrica | 68 | 2819 | 4 | 22\nKumara | Sangakkara | Srilanka | 404 | 14234 | 25 | 93\nVirat | Kohli | India | 239 | 11520 | 43 | 54\nRohit | Sharma | India | 218 | 8686 | 24 | 42\n(5 rows)\npostgres=#\n"
},
{
"code": null,
"e": 5647,
"s": 5536,
"text": "When you have divided the data in two tables you can fetch combined records from these two tables using Joins."
},
{
"code": null,
"e": 5716,
"s": 5647,
"text": "Following python program demonstrates the usage of the JOIN clause −"
},
{
"code": null,
"e": 6313,
"s": 5716,
"text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Retrieving single row\nsql = '''SELECT * from EMP INNER JOIN CONTACT ON EMP.CONTACT = CONTACT.ID'''\n\n#Executing the query\ncursor.execute(sql)\n\n#Fetching 1st row from the table\nresult = cursor.fetchall();\nprint(result)\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()"
},
{
"code": null,
"e": 6665,
"s": 6313,
"text": "[('Ramya', 'Rama priya', 27, 'F', 9000.0, 101, 101, 'Krishna@mymail.com', 'Hyderabad'), \n ('Vinay', 'Battacharya', 20, 'M', 6000.0, 102, 102, 'Raja@mymail.com', 'Vishakhapatnam'), \n ('Sharukh', 'Sheik', 25, 'M', 8300.0, 103, 103, 'Krishna@mymail.com ', 'Pune'), \n ('Sarmista', 'Sharma', 26, 'F', 10000.0, 104, 104, 'Raja@mymail.com', 'Mumbai')]\n"
},
{
"code": null,
"e": 6702,
"s": 6665,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6718,
"s": 6702,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6751,
"s": 6718,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6770,
"s": 6751,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6805,
"s": 6770,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 6827,
"s": 6805,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 6861,
"s": 6827,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6889,
"s": 6861,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6924,
"s": 6889,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6938,
"s": 6924,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6971,
"s": 6938,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6988,
"s": 6971,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6995,
"s": 6988,
"text": " Print"
},
{
"code": null,
"e": 7006,
"s": 6995,
"text": " Add Notes"
}
] |
How to set the environmental variable LD_LIBRARY_PATH in Linux?
|
There are plenty of ways in which we can set an environment variable in Linux and then make use of it later. Some ways provide us access to that variable in a particular window, in other cases, we can get access to those variables in every terminal window and in a permanent manner.
Let’s explore setting a new environment variable on an Ubuntu machine and then we can talk about setting the LD_LIBRARY_PATH.
In order to set a new environment variable, follow the commands shown below in sequence.
Open your bash-profile with the command shown below −
vi ~/.bashrc
Make use of the export linux utility command and insert the paste the command shown below in your bash-profile.
export GOPATH=/root/go_projects
Exit the bash-profile and then source the profile with the command shown below.
source ~/.bashrc
Open a new terminal to check that the environment variable you set is available to you.
echo $GOPATH
Output should look something like below −
/root/go_projects
If you don’t get any output, then make sure you followed the steps mentioned above correctly.
In case of LD_LIBRARY_PATH, we can follow the same steps as mentioned above, the command to change inside the bash-profile would look something like this −
export LD_LIBRARY_PATH = /path/to/your/library
And then you can source the file and make use of it.
Though it is recommended that you shouldn’t change the LD_LIBRARY_PATH as the other libraries and their dependencies might get broken, so it's better to append the path you want to the already existing LD_LIBRARY_PATH with the command shown below −
export LD_LIBRARY_PATH=$LD_LIBRARY_PAT:H/path/to/your/library
Now if you do echo $LD_LIBRARY_PATH
/usr/local/bin:/path/to/your/directory
|
[
{
"code": null,
"e": 1345,
"s": 1062,
"text": "There are plenty of ways in which we can set an environment variable in Linux and then make use of it later. Some ways provide us access to that variable in a particular window, in other cases, we can get access to those variables in every terminal window and in a permanent manner."
},
{
"code": null,
"e": 1471,
"s": 1345,
"text": "Let’s explore setting a new environment variable on an Ubuntu machine and then we can talk about setting the LD_LIBRARY_PATH."
},
{
"code": null,
"e": 1560,
"s": 1471,
"text": "In order to set a new environment variable, follow the commands shown below in sequence."
},
{
"code": null,
"e": 1614,
"s": 1560,
"text": "Open your bash-profile with the command shown below −"
},
{
"code": null,
"e": 1627,
"s": 1614,
"text": "vi ~/.bashrc"
},
{
"code": null,
"e": 1739,
"s": 1627,
"text": "Make use of the export linux utility command and insert the paste the command shown below in your bash-profile."
},
{
"code": null,
"e": 1771,
"s": 1739,
"text": "export GOPATH=/root/go_projects"
},
{
"code": null,
"e": 1851,
"s": 1771,
"text": "Exit the bash-profile and then source the profile with the command shown below."
},
{
"code": null,
"e": 1868,
"s": 1851,
"text": "source ~/.bashrc"
},
{
"code": null,
"e": 1956,
"s": 1868,
"text": "Open a new terminal to check that the environment variable you set is available to you."
},
{
"code": null,
"e": 1969,
"s": 1956,
"text": "echo $GOPATH"
},
{
"code": null,
"e": 2011,
"s": 1969,
"text": "Output should look something like below −"
},
{
"code": null,
"e": 2029,
"s": 2011,
"text": "/root/go_projects"
},
{
"code": null,
"e": 2123,
"s": 2029,
"text": "If you don’t get any output, then make sure you followed the steps mentioned above correctly."
},
{
"code": null,
"e": 2279,
"s": 2123,
"text": "In case of LD_LIBRARY_PATH, we can follow the same steps as mentioned above, the command to change inside the bash-profile would look something like this −"
},
{
"code": null,
"e": 2326,
"s": 2279,
"text": "export LD_LIBRARY_PATH = /path/to/your/library"
},
{
"code": null,
"e": 2379,
"s": 2326,
"text": "And then you can source the file and make use of it."
},
{
"code": null,
"e": 2628,
"s": 2379,
"text": "Though it is recommended that you shouldn’t change the LD_LIBRARY_PATH as the other libraries and their dependencies might get broken, so it's better to append the path you want to the already existing LD_LIBRARY_PATH with the command shown below −"
},
{
"code": null,
"e": 2690,
"s": 2628,
"text": "export LD_LIBRARY_PATH=$LD_LIBRARY_PAT:H/path/to/your/library"
},
{
"code": null,
"e": 2726,
"s": 2690,
"text": "Now if you do echo $LD_LIBRARY_PATH"
},
{
"code": null,
"e": 2766,
"s": 2726,
"text": "/usr/local/bin:/path/to/your/directory\n"
}
] |
C# difference in milliseconds between two DateTime
|
Let’s say the following are two DateTime objects for our dates.
DateTime date1 = new DateTime(2018, 8, 11, 08, 15, 20);
DateTime date2 = new DateTime(2018, 8, 11, 11, 14, 25);
Find the difference between both these dates using TimeSpan.
TimeSpan ts = date2 - date1;
Now to get the Milliseconds, use the following property −
ts.TotalMilliseconds
Let us see the complete code.
Live Demo
using System;
using System.Linq;
public class Demo {
public static void Main() {
DateTime date1 = new DateTime(2018, 8, 11, 08, 15, 20);
DateTime date2 = new DateTime(2018, 8, 11, 11, 14, 25);
TimeSpan ts = date2 - date1;
Console.WriteLine("No. of Seconds (Difference) = {0}", ts.TotalMilliseconds);
}
}
No. of Seconds (Difference) = 10745000
|
[
{
"code": null,
"e": 1126,
"s": 1062,
"text": "Let’s say the following are two DateTime objects for our dates."
},
{
"code": null,
"e": 1238,
"s": 1126,
"text": "DateTime date1 = new DateTime(2018, 8, 11, 08, 15, 20);\nDateTime date2 = new DateTime(2018, 8, 11, 11, 14, 25);"
},
{
"code": null,
"e": 1299,
"s": 1238,
"text": "Find the difference between both these dates using TimeSpan."
},
{
"code": null,
"e": 1328,
"s": 1299,
"text": "TimeSpan ts = date2 - date1;"
},
{
"code": null,
"e": 1386,
"s": 1328,
"text": "Now to get the Milliseconds, use the following property −"
},
{
"code": null,
"e": 1407,
"s": 1386,
"text": "ts.TotalMilliseconds"
},
{
"code": null,
"e": 1437,
"s": 1407,
"text": "Let us see the complete code."
},
{
"code": null,
"e": 1448,
"s": 1437,
"text": " Live Demo"
},
{
"code": null,
"e": 1782,
"s": 1448,
"text": "using System;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n DateTime date1 = new DateTime(2018, 8, 11, 08, 15, 20);\n DateTime date2 = new DateTime(2018, 8, 11, 11, 14, 25);\n TimeSpan ts = date2 - date1;\n Console.WriteLine(\"No. of Seconds (Difference) = {0}\", ts.TotalMilliseconds);\n }\n}"
},
{
"code": null,
"e": 1821,
"s": 1782,
"text": "No. of Seconds (Difference) = 10745000"
}
] |
How to count child element using jQuery ? - GeeksforGeeks
|
27 Apr, 2020
It is very simple to count the number of child elements in the HTML file using jQuery. For example: If you have a parent element consisting of many children elements then you can use .length or.children().length method as given below.
Syntax:
var len=$("#parentID").length;
or
var count = $("#parentId").children().length;
Example 1:
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Count child elements using Jquery</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""></head> <body> <div id="parentID"> <p>Red</p> <p>White</p> <p>Green</p> <p>Black</p> <p>Blue</p> <p>Orange</p> </div> <script src="https://code.jquery.com/jquery-3.5.0.min.js"integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"> </script> <script> // Here we count the child element in parentID var count = $("#parentID p").length; document.writeln(count); </script></body> </html>
Output:
Example 2:
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Count child elements using jQuery.</title> <script src= "https://code.jquery.com/jquery-3.4.1.js"> </script></head> <body> <div id="parentId"> <ul> <li>1 child</li> <li>2 child</li> <li>3 child</li> <li>4 child</li> <li>5 child</li> </ul> </div> <script> var count = $("#parentId ul").children().length; document.writeln(count); </script></body> </html>
Output:
jQuery-Misc
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
How to get the ID of the clicked button using JavaScript / jQuery ?
jQuery | children() with Examples
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": 24292,
"s": 24264,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 24527,
"s": 24292,
"text": "It is very simple to count the number of child elements in the HTML file using jQuery. For example: If you have a parent element consisting of many children elements then you can use .length or.children().length method as given below."
},
{
"code": null,
"e": 24535,
"s": 24527,
"text": "Syntax:"
},
{
"code": null,
"e": 24567,
"s": 24535,
"text": "var len=$(\"#parentID\").length;\n"
},
{
"code": null,
"e": 24570,
"s": 24567,
"text": "or"
},
{
"code": null,
"e": 24616,
"s": 24570,
"text": "var count = $(\"#parentId\").children().length;"
},
{
"code": null,
"e": 24627,
"s": 24616,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <title>Count child elements using Jquery</title> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"\"></head> <body> <div id=\"parentID\"> <p>Red</p> <p>White</p> <p>Green</p> <p>Black</p> <p>Blue</p> <p>Orange</p> </div> <script src=\"https://code.jquery.com/jquery-3.5.0.min.js\"integrity=\"sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=\" crossorigin=\"anonymous\"> </script> <script> // Here we count the child element in parentID var count = $(\"#parentID p\").length; document.writeln(count); </script></body> </html>",
"e": 25439,
"s": 24627,
"text": null
},
{
"code": null,
"e": 25447,
"s": 25439,
"text": "Output:"
},
{
"code": null,
"e": 25458,
"s": 25447,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width\"> <title>Count child elements using jQuery.</title> <script src= \"https://code.jquery.com/jquery-3.4.1.js\"> </script></head> <body> <div id=\"parentId\"> <ul> <li>1 child</li> <li>2 child</li> <li>3 child</li> <li>4 child</li> <li>5 child</li> </ul> </div> <script> var count = $(\"#parentId ul\").children().length; document.writeln(count); </script></body> </html>",
"e": 26000,
"s": 25458,
"text": null
},
{
"code": null,
"e": 26008,
"s": 26000,
"text": "Output:"
},
{
"code": null,
"e": 26020,
"s": 26008,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 26027,
"s": 26020,
"text": "Picked"
},
{
"code": null,
"e": 26034,
"s": 26027,
"text": "JQuery"
},
{
"code": null,
"e": 26051,
"s": 26034,
"text": "Web Technologies"
},
{
"code": null,
"e": 26078,
"s": 26051,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 26176,
"s": 26078,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26185,
"s": 26176,
"text": "Comments"
},
{
"code": null,
"e": 26198,
"s": 26185,
"text": "Old Comments"
},
{
"code": null,
"e": 26227,
"s": 26198,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 26283,
"s": 26227,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 26337,
"s": 26283,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 26405,
"s": 26337,
"text": "How to get the ID of the clicked button using JavaScript / jQuery ?"
},
{
"code": null,
"e": 26439,
"s": 26405,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 26495,
"s": 26439,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26528,
"s": 26495,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26590,
"s": 26528,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26633,
"s": 26590,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Java Cryptography - Decrypting Data
|
You can decrypt the encrypted data using the Cipher class of the javax.crypto package. Follow the steps given below to decrypt given data using Java.
The KeyPairGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyPairGenerator object that generates keys.
Create KeyPairGenerator object using the getInstance() method as shown below.
//Creating KeyPair generator object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
The KeyPairGenerator class provides a method named initialize() this method is used to initialize the key pair generator. This method accepts an integer value representing the key size.
Initialize the KeyPairGenerator object created in the previous step using the initialize() method as shown below.
//Initializing the KeyPairGenerator
keyPairGen.initialize(2048);
You can generate the KeyPair using the generateKeyPair() method of the KeyPairGenerator class. Generate the key pair using this method as shown below.
//Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();
You can get the public key from the generated KeyPair object using the getPublic() method as shown below.
//Getting the public key from the key pair
PublicKey publicKey = pair.getPublic();
The getInstance() method of Cipher class accepts a String variable representing the required transformation and returns a Cipher object that implements the given transformation.
Create the Cipher object using the getInstance() method as shown below.
//Creating a Cipher object
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
The init() method of the Cipher class accepts two parameters
An integer parameter representing the operation mode (encrypt/decrypt)
Key object representing the public key
Initialize the Cypher object using the init() method as shown below.
//Initializing a Cipher object
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
The update() method of the Cipher class accepts a byte array representing the data to be encrypted and updates the current object with the data given.
Update the initialized Cipher object by passing the data to the update() method in the form of byte array as shown below.
//Adding data to the cipher
byte[] input = "Welcome to Tutorialspoint".getBytes();
cipher.update(input);
The doFinal() method of the Cipher class completes the encryption operation. Therefore, finish the encryption using this method as shown below.
//Encrypting the data
byte[] cipherText = cipher.doFinal();
To decrypt the cypher encrypted in the previous steps you need to initialize it for decryption.
Therefore, initialize the cipher object by passing the parameters Cipher.DECRYPT_MODE and PrivateKey object as shown below.
//Initializing the same cipher for decryption
cipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());
Finally, Decrypt the encrypted text using the doFinal() method as shown below.
//Decrypting the text
byte[] decipheredText = cipher.doFinal(cipherText);
Following Java program accepts text from user, encrypts it using RSA algorithm and, prints the cipher of the given text, decrypts the cipher and prints the decrypted text again.
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import javax.crypto.Cipher;
public class CipherDecrypt {
public static void main(String args[]) throws Exception{
//Creating a Signature object
Signature sign = Signature.getInstance("SHA256withRSA");
//Creating KeyPair generator object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
//Initializing the key pair generator
keyPairGen.initialize(2048);
//Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();
//Getting the public key from the key pair
PublicKey publicKey = pair.getPublic();
//Creating a Cipher object
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//Initializing a Cipher object
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
//Add data to the cipher
byte[] input = "Welcome to Tutorialspoint".getBytes();
cipher.update(input);
//encrypting the data
byte[] cipherText = cipher.doFinal();
System.out.println( new String(cipherText, "UTF8"));
//Initializing the same cipher for decryption
cipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());
//Decrypting the text
byte[] decipheredText = cipher.doFinal(cipherText);
System.out.println(new String(decipheredText));
}
}
The above program generates the following output −
Encrypted Text:
]/[?F3?D?p
v?w?!?H???^?A??????P?u??FA?
?
???_?? ???_jMH-??>??OP?'?j?_?n`
?_??'`????o??_GL??g???g_f?????f|???LT?|?Vz_TDu#??\?<b,,?$C2???Bq?#?lDB`??g,^??K?_?v???`}
?;LX?a?_5e???#???_?6?/B&B_???^?__Ap^#_?q?IEh????_?,??*??]~_?_?D?
_y???lp??a?P_U{
Decrypted Text:
Welcome to Tutorialspoint
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2203,
"s": 2053,
"text": "You can decrypt the encrypted data using the Cipher class of the javax.crypto package. Follow the steps given below to decrypt given data using Java."
},
{
"code": null,
"e": 2402,
"s": 2203,
"text": "The KeyPairGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyPairGenerator object that generates keys."
},
{
"code": null,
"e": 2480,
"s": 2402,
"text": "Create KeyPairGenerator object using the getInstance() method as shown below."
},
{
"code": null,
"e": 2584,
"s": 2480,
"text": "//Creating KeyPair generator object\nKeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(\"DSA\");\n"
},
{
"code": null,
"e": 2770,
"s": 2584,
"text": "The KeyPairGenerator class provides a method named initialize() this method is used to initialize the key pair generator. This method accepts an integer value representing the key size."
},
{
"code": null,
"e": 2884,
"s": 2770,
"text": "Initialize the KeyPairGenerator object created in the previous step using the initialize() method as shown below."
},
{
"code": null,
"e": 2950,
"s": 2884,
"text": "//Initializing the KeyPairGenerator\nkeyPairGen.initialize(2048);\n"
},
{
"code": null,
"e": 3101,
"s": 2950,
"text": "You can generate the KeyPair using the generateKeyPair() method of the KeyPairGenerator class. Generate the key pair using this method as shown below."
},
{
"code": null,
"e": 3175,
"s": 3101,
"text": "//Generate the pair of keys\nKeyPair pair = keyPairGen.generateKeyPair();\n"
},
{
"code": null,
"e": 3281,
"s": 3175,
"text": "You can get the public key from the generated KeyPair object using the getPublic() method as shown below."
},
{
"code": null,
"e": 3365,
"s": 3281,
"text": "//Getting the public key from the key pair\nPublicKey publicKey = pair.getPublic();\n"
},
{
"code": null,
"e": 3543,
"s": 3365,
"text": "The getInstance() method of Cipher class accepts a String variable representing the required transformation and returns a Cipher object that implements the given transformation."
},
{
"code": null,
"e": 3615,
"s": 3543,
"text": "Create the Cipher object using the getInstance() method as shown below."
},
{
"code": null,
"e": 3703,
"s": 3615,
"text": "//Creating a Cipher object\nCipher cipher = Cipher.getInstance(\"RSA/ECB/PKCS1Padding\");\n"
},
{
"code": null,
"e": 3764,
"s": 3703,
"text": "The init() method of the Cipher class accepts two parameters"
},
{
"code": null,
"e": 3835,
"s": 3764,
"text": "An integer parameter representing the operation mode (encrypt/decrypt)"
},
{
"code": null,
"e": 3874,
"s": 3835,
"text": "Key object representing the public key"
},
{
"code": null,
"e": 3943,
"s": 3874,
"text": "Initialize the Cypher object using the init() method as shown below."
},
{
"code": null,
"e": 4020,
"s": 3943,
"text": "//Initializing a Cipher object\ncipher.init(Cipher.ENCRYPT_MODE, publicKey);\n"
},
{
"code": null,
"e": 4171,
"s": 4020,
"text": "The update() method of the Cipher class accepts a byte array representing the data to be encrypted and updates the current object with the data given."
},
{
"code": null,
"e": 4293,
"s": 4171,
"text": "Update the initialized Cipher object by passing the data to the update() method in the form of byte array as shown below."
},
{
"code": null,
"e": 4402,
"s": 4293,
"text": "//Adding data to the cipher\nbyte[] input = \"Welcome to Tutorialspoint\".getBytes();\t \ncipher.update(input);\n"
},
{
"code": null,
"e": 4546,
"s": 4402,
"text": "The doFinal() method of the Cipher class completes the encryption operation. Therefore, finish the encryption using this method as shown below."
},
{
"code": null,
"e": 4607,
"s": 4546,
"text": "//Encrypting the data\nbyte[] cipherText = cipher.doFinal();\n"
},
{
"code": null,
"e": 4703,
"s": 4607,
"text": "To decrypt the cypher encrypted in the previous steps you need to initialize it for decryption."
},
{
"code": null,
"e": 4827,
"s": 4703,
"text": "Therefore, initialize the cipher object by passing the parameters Cipher.DECRYPT_MODE and PrivateKey object as shown below."
},
{
"code": null,
"e": 4927,
"s": 4827,
"text": "//Initializing the same cipher for decryption\ncipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());\n"
},
{
"code": null,
"e": 5006,
"s": 4927,
"text": "Finally, Decrypt the encrypted text using the doFinal() method as shown below."
},
{
"code": null,
"e": 5081,
"s": 5006,
"text": "//Decrypting the text\nbyte[] decipheredText = cipher.doFinal(cipherText);\n"
},
{
"code": null,
"e": 5259,
"s": 5081,
"text": "Following Java program accepts text from user, encrypts it using RSA algorithm and, prints the cipher of the given text, decrypts the cipher and prints the decrypted text again."
},
{
"code": null,
"e": 6702,
"s": 5259,
"text": "import java.security.KeyPair;\nimport java.security.KeyPairGenerator;\nimport java.security.Signature;\n\nimport javax.crypto.Cipher;\n\npublic class CipherDecrypt {\n public static void main(String args[]) throws Exception{\n\t //Creating a Signature object\n Signature sign = Signature.getInstance(\"SHA256withRSA\");\n \n //Creating KeyPair generator object\n KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(\"RSA\");\n \n //Initializing the key pair generator\n keyPairGen.initialize(2048);\n \n //Generate the pair of keys\n KeyPair pair = keyPairGen.generateKeyPair(); \n \n //Getting the public key from the key pair\n PublicKey publicKey = pair.getPublic(); \n\n //Creating a Cipher object\n Cipher cipher = Cipher.getInstance(\"RSA/ECB/PKCS1Padding\");\n\n //Initializing a Cipher object\n cipher.init(Cipher.ENCRYPT_MODE, publicKey);\n\t \n //Add data to the cipher\n byte[] input = \"Welcome to Tutorialspoint\".getBytes();\t \n cipher.update(input);\n\t \n //encrypting the data\n byte[] cipherText = cipher.doFinal();\t \n System.out.println( new String(cipherText, \"UTF8\"));\n\n //Initializing the same cipher for decryption\n cipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());\n \n //Decrypting the text\n byte[] decipheredText = cipher.doFinal(cipherText);\n System.out.println(new String(decipheredText));\n }\n}"
},
{
"code": null,
"e": 6753,
"s": 6702,
"text": "The above program generates the following output −"
},
{
"code": null,
"e": 7056,
"s": 6753,
"text": "Encrypted Text:\n]/[?F3?D?p\nv?w?!?H???^?A??????P?u??FA?\n?\n???_?? ???_jMH-??>??OP?'?j?_?n`\n?_??'`????o??_GL??g???g_f?????f|???LT?|?Vz_TDu#??\\?<b,,?$C2???Bq?#?lDB`??g,^??K?_?v???`}\n?;LX?a?_5e???#???_?6?/B&B_???^?__Ap^#_?q?IEh????_?,??*??]~_?_?D?\n_y???lp??a?P_U{\n\nDecrypted Text:\nWelcome to Tutorialspoint\n"
},
{
"code": null,
"e": 7089,
"s": 7056,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7105,
"s": 7089,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7138,
"s": 7105,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7154,
"s": 7138,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7189,
"s": 7154,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7203,
"s": 7189,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7237,
"s": 7203,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7251,
"s": 7237,
"text": " Tushar Kale"
},
{
"code": null,
"e": 7288,
"s": 7251,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7303,
"s": 7288,
"text": " Monica Mittal"
},
{
"code": null,
"e": 7336,
"s": 7303,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7355,
"s": 7336,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7362,
"s": 7355,
"text": " Print"
},
{
"code": null,
"e": 7373,
"s": 7362,
"text": " Add Notes"
}
] |
C# DateTime Max Value
|
To set the max value for a Date, use the DateTime property MaxValue.
DateTime max = DateTime.MaxValue;
Now, display the value of max to get the maximum value of a date as shown below.
Live Demo
using System;
using System.Linq;
public class Demo {
public static void Main() {
DateTime max = DateTime.MaxValue;
Console.WriteLine(max);
}
}
12/31/9999 11:59:59 PM
|
[
{
"code": null,
"e": 1131,
"s": 1062,
"text": "To set the max value for a Date, use the DateTime property MaxValue."
},
{
"code": null,
"e": 1165,
"s": 1131,
"text": "DateTime max = DateTime.MaxValue;"
},
{
"code": null,
"e": 1246,
"s": 1165,
"text": "Now, display the value of max to get the maximum value of a date as shown below."
},
{
"code": null,
"e": 1257,
"s": 1246,
"text": " Live Demo"
},
{
"code": null,
"e": 1418,
"s": 1257,
"text": "using System;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n DateTime max = DateTime.MaxValue;\n Console.WriteLine(max);\n }\n}"
},
{
"code": null,
"e": 1441,
"s": 1418,
"text": "12/31/9999 11:59:59 PM"
}
] |
Create SubReports
|
Subreports are one of the nice features of the JasperReports. This feature allows incorporating a report within another report, that is, one report can be a subreport of another. Subreports help us keep report designs simple, as we can create many simple reports and encapsulate them into a master report. Subreports are compiled and filled just like normal reports. Any report template can be used as a subreport when incorporated into another report template, without anything changed inside (of the report template).
Subreports are like normal report templates. They are in fact net.sf.jasperreports.engine.JasperReport objects, which are obtained after compiling a net.sf.jasperreports.engine.design.JasperDesign object.
A <subreport> element is used when introducing subreports into master reports. Here is the list of sub-elements in the <subreport> JRXML element.
<reportElement>
<reportElement>
<parametersMapExpression> − This is used to pass a map containing report parameters to the subreport. The map is usually obtained from a parameter in the master report, or by using the built-in REPORTS_PARAMETERS_MAP parameter to pass the parent report's parameters to the subreport. This expression should always return a java.util.Map object in which the keys are the parameter
names.
<parametersMapExpression> − This is used to pass a map containing report parameters to the subreport. The map is usually obtained from a parameter in the master report, or by using the built-in REPORTS_PARAMETERS_MAP parameter to pass the parent report's parameters to the subreport. This expression should always return a java.util.Map object in which the keys are the parameter
names.
<subreportParameter> − This element is used to pass parameters to the subreport. It has an attribute name, which is mandatory.
<subreportParameter> − This element is used to pass parameters to the subreport. It has an attribute name, which is mandatory.
<connectionExpression > − This is used to pass a java.sql.Connection to the subreport. It is used only when the subreport template needs a database connection during report filling phase.
<connectionExpression > − This is used to pass a java.sql.Connection to the subreport. It is used only when the subreport template needs a database connection during report filling phase.
<dataSourceExpression> − This is used to pass a datasource to the subreport. This datasource is usually obtained from a parameter in the master report or by using the built-in REPORT_DATA_SOURCE parameter to pass the parent report's datasource to the subreport.
<dataSourceExpression> − This is used to pass a datasource to the subreport. This datasource is usually obtained from a parameter in the master report or by using the built-in REPORT_DATA_SOURCE parameter to pass the parent report's datasource to the subreport.
The elements (connectionExpression and dataSourceExpression) cannot be present at the same time in a <subreport> element declaration. This is because we cannot supply both a data source and a connection to the subreport. We must decide on one of them and stick to it.
The elements (connectionExpression and dataSourceExpression) cannot be present at the same time in a <subreport> element declaration. This is because we cannot supply both a data source and a connection to the subreport. We must decide on one of them and stick to it.
<returnValue> − This is used to assign the value of one of the subreport's variables to one of the master report's variables. This sub element has attributes as follows −
subreportVariable − This attribute specifies the name of the subreport variable whose value is to be returned.
toVariable − This attribute specifies the name of the parent report variable whose value is to be copied/incremented with the value from the subreport.
calculation − This attribute can take values : Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance. Default value for attribute calculation is "Nothing".
incrementerFactoryClass − This attribute specifies the factory class for creating the incrementer instance.
<returnValue> − This is used to assign the value of one of the subreport's variables to one of the master report's variables. This sub element has attributes as follows −
subreportVariable − This attribute specifies the name of the subreport variable whose value is to be returned.
subreportVariable − This attribute specifies the name of the subreport variable whose value is to be returned.
toVariable − This attribute specifies the name of the parent report variable whose value is to be copied/incremented with the value from the subreport.
toVariable − This attribute specifies the name of the parent report variable whose value is to be copied/incremented with the value from the subreport.
calculation − This attribute can take values : Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance. Default value for attribute calculation is "Nothing".
calculation − This attribute can take values : Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance. Default value for attribute calculation is "Nothing".
incrementerFactoryClass − This attribute specifies the factory class for creating the incrementer instance.
incrementerFactoryClass − This attribute specifies the factory class for creating the incrementer instance.
<subreportExpression> − This indicates where to find the compiled report template for the subreport. This element has a class attribute. The class attribute can take any of these values:java.lang.String, java.io.File, java.net.URL, java.io.InputStream, net.sf.jasperreports.engine.JasperReport. Default value is java.lang.String.
<subreportExpression> − This indicates where to find the compiled report template for the subreport. This element has a class attribute. The class attribute can take any of these values:java.lang.String, java.io.File, java.net.URL, java.io.InputStream, net.sf.jasperreports.engine.JasperReport. Default value is java.lang.String.
isUsingCache − This is an attribute of the <subreport> element. This is a Boolean, when set to true, the reporting engine will try to recognize previously loaded subreport template objects, using their specified source. This caching functionality is available only for subreport elements that have expressions returning java.lang.String objects as the subreport template source, representing file names, URLs, or classpath resources.
isUsingCache − This is an attribute of the <subreport> element. This is a Boolean, when set to true, the reporting engine will try to recognize previously loaded subreport template objects, using their specified source. This caching functionality is available only for subreport elements that have expressions returning java.lang.String objects as the subreport template source, representing file names, URLs, or classpath resources.
Let take up a simple example to demonstrate creation of subreports using JRDataSource. Let's first write two new report templates, one being subreport and the other Master report. The contents of the subreport (address_report_template.jrxml) template is as given below. Save it to C:\tools\jasperreports-5.0.1\test directory.
<?xml version = "1.0" encoding = "UTF-8"?>
<jasperReport
xmlns = "http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name = "address_report_template" pageWidth = "175" pageHeight = "842"
columnWidth = "175" leftMargin = "0" rightMargin = "0"
topMargin = "0" bottomMargin = "0">
<field name = "city" class = "java.lang.String"/>
<field name = "street" class = "java.lang.String"/>
<background>
<band splitType = "Stretch"/>
</background>
<title>
<band height = "20" splitType = "Stretch">
<staticText>
<reportElement x = "0" y = "0" width = "100" height = "20"/>
<textElement>
<font size = "14" isBold = "true"/>
</textElement>
<text><![CDATA[Addresses]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band height = "12" splitType = "Stretch"/>
</pageHeader>
<columnHeader>
<band height = "12" splitType = "Stretch"/>
</columnHeader>
<detail>
<band height = "27" splitType = "Stretch">
<textField>
<reportElement x = "0" y = "0" width = "120" height = "20"/>
<textElement>
<font size = "12" isBold = "true"/>
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$F{city}+" Address:"]]>
</textFieldExpression>
</textField>
<textField isStretchWithOverflow = "true">
<reportElement x = "120" y = "0" width = "435" height = "20"/>
<textElement>
<font size = "12"/>
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$F{street}]]>
</textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band height = "8" splitType = "Stretch"/>
</columnFooter>
<pageFooter>
<band height = "11" splitType = "Stretch"/>
</pageFooter>
<summary>
<band height = "9" splitType = "Stretch"/>
</summary>
</jasperReport>
As we use a data source, we need to write a corresponding POJO file SubReportBean.java as shown below. Save it to directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint −
package com.tutorialspoint;
public class SubReportBean {
private String city;
private String street;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
Here, we have declared two fields 'city' and 'street' and respective getter and setter methods are defined.
Now, let's update our existing DataBean file. We will add a new field subReportBeanList, which is a java.util.List. This field will hold the list of SubReportBean objects. The contents of the file DataBean are as below. Save it to directory C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint.
package com.tutorialspoint;
import java.util.List;
public class DataBean {
private String name;
private String country;
private List<SubReportBean> subReportBeanList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public List<SubReportBean> getSubReportBeanList() {
return subReportBeanList;
}
public void setSubReportBeanList(List<SubReportBean> subReportBeanList) {
this.subReportBeanList = subReportBeanList;
}
}
Let's now update the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java. The contents of this file are as −
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DataBeanList {
public ArrayList<DataBean> getDataBeanList() {
// Create sub report data
SubReportBean subBean1 = new SubReportBean();
subBean1.setCity("Mumbai");
subBean1.setStreet("M.G.Road");
SubReportBean subBean2 = new SubReportBean();
subBean2.setCity("New York");
subBean2.setStreet("Park Street");
SubReportBean subBean3 = new SubReportBean();
subBean3.setCity("San Fransisco");
subBean3.setStreet("King Street");
ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();
// Create master report data
dataBeanList.add(produce("Manisha", "India",
Arrays.asList(subBean1)));
dataBeanList.add(produce("Dennis Ritchie", "USA",
Arrays.asList(subBean2)));
dataBeanList.add(produce("V.Anand", "India",
Arrays.asList(subBean1)));
dataBeanList.add(produce("Shrinath", "California",
Arrays.asList(subBean3)));
return dataBeanList;
}
/*
* This method returns a DataBean object,
* with name, country and sub report
* bean data set in it.
*/
private DataBean produce(String name, String country,
List<SubReportBean> subBean) {
DataBean dataBean = new DataBean();
dataBean.setName(name);
dataBean.setCountry(country);
dataBean.setSubReportBeanList(subBean);
return dataBean;
}
}
In the method produce() in the above file, we are setting the list of SubReportBean.
Now, let's write a new master report template (jasper_report_template.jrxml). Save this file to directory C:\tools\jasperreports-5.0.1\test. The contents for this file are as below −
<?xml version = "1.0" encoding = "UTF-8"?>
<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name = "jasper_report_template" language = "groovy" pageWidth = "595"
pageHeight = "842" columnWidth ="555" leftMargin = "20" rightMargin = "20"
topMargin = "20" bottomMargin = "20">
<parameter name = "SUBREPORT_DIR" class = "java.lang.String" isForPrompting = "false">
<defaultValueExpression>
<![CDATA["C:\\tools\\jasperreports-5.0.1\\test\\"]]>
</defaultValueExpression>
</parameter>
<field name = "country" class = "java.lang.String"/>
<field name = "name" class = "java.lang.String"/>
<field name = "subReportBeanList" class = "java.util.List"/>
<background>
<band splitType = "Stretch"/>
</background>
<title>
<band height = "35" splitType = "Stretch">
<staticText>
<reportElement x = "0" y = "0" width = "204" height = "34"/>
<textElement>
<font size = "26" isBold = "true"/>
</textElement>
<text><![CDATA[Contact Report]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band height = "17" splitType = "Stretch"/>
</pageHeader>
<columnHeader>
<band height = "21" splitType = "Stretch"/>
</columnHeader>
<detail>
<band height = "112" splitType = "Stretch">
<staticText>
<reportElement x = "0" y = "0" width = "100" height = "20"/>
<textElement>
<font size = "12" isBold = "true"/>
</textElement>
<text><![CDATA[Name:]]></text>
</staticText>
<staticText>
<reportElement x = "0" y = "20" width = "100" height = "20"/>
<textElement>
<font size = "12" isBold = "true"/>
</textElement>
<text><![CDATA[Country:]]></text>
</staticText>
<textField>
<reportElement x = "104" y = "0" width = "277" height = "20"/>
<textElement>
<font size = "12"/>
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$F{name}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x = "104" y = "20" width = "277" height = "20"/>
<textElement>
<font size = "12"/>
</textElement>
<textFieldExpression class = "java.lang.String">
<![CDATA[$F{country}]]>
</textFieldExpression>
</textField>
<subreport>
<reportElement positionType = "Float" x = "335" y = "25" width = "175"
height = "20" isRemoveLineWhenBlank = "true" backcolor = "#99ccff"/>
<dataSourceExpression>
new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource
($F{subReportBeanList})
</dataSourceExpression>
<subreportExpression class = "java.lang.String">
<![CDATA[$P{SUBREPORT_DIR} + "address_report_template.jasper"]]>
</subreportExpression>
</subreport>
<line>
<reportElement x = "0" y = "50" width = "550" height = "1"/>
</line>
</band>
</detail>
<columnFooter>
<band height = "19" splitType = "Stretch"/>
</columnFooter>
<pageFooter>
<band height = "18" splitType = "Stretch"/>
</pageFooter>
<summary>
<band height = "14" splitType = "Stretch"/>
</summary>
</jasperReport>
In the above template, we have defined a new parameter "SUBREPORT_DIR," which defines the path of the subreport. We have defined a field subReportBeanList of type java.util.List, which corresponds to property in the file DataBean. The element <subreport> has sub-element <dataSourceExpression>. We have put the list subReportBeanList in an instance of JRBeanCollectionDataSource. In the sub-element <subreportExpression/>, we have given the subreport name (AddressReport.jasper).
Now, let's write a new class CreateReport to compile and execute our report template. The contents of file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\CreateReport.java are as given below −
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
public class CreateReport {
public static void main(String[] args) {
String masterReportFileName = "C://tools/jasperreports-5.0.1/test"
+ "/jasper_report_template.jrxml";
String subReportFileName = "C://tools/jasperreports-5.0.1/test"
+ "/AddressReport.jrxml";
String destFileName = "C://tools/jasperreports-5.0.1/test"
+ "/jasper_report_template.JRprint";
DataBeanList DataBeanList = new DataBeanList();
ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();
JRBeanCollectionDataSource beanColDataSource = new
JRBeanCollectionDataSource(dataList);
try {
/* Compile the master and sub report */
JasperReport jasperMasterReport = JasperCompileManager
.compileReport(masterReportFileName);
JasperReport jasperSubReport = JasperCompileManager
.compileReport(subReportFileName);
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("subreportParameter", jasperSubReport);
JasperFillManager.fillReportToFile(jasperMasterReport,
destFileName, parameters, beanColDataSource);
} catch (JRException e) {
e.printStackTrace();
}
System.out.println("Done filling!!! ...");
}
}
Here, we see that we are compiling both the master and sub report templates and passing the master report (.jasper) file for the report filling.
Now, all our files are ready, let's compile and execute them using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below.
The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "viewFillReport" basedir = ".">
<import file = "baseBuild.xml" />
<target name = "viewFillReport" depends = "compile,compilereportdesing,run"
description = "Launches the report viewer to preview the
report stored in the .JRprint file.">
<java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true">
<arg value = "-F${file.name}.JRprint" />
<classpath refid = "classpath" />
</java>
</target>
<target name = "compilereportdesing" description = "Compiles the JXML file and
produces the .jasper file.">
<taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask">
<classpath refid = "classpath" />
</taskdef>
<jrc destdir = ".">
<src>
<fileset dir = ".">
<include name = "*.jrxml" />
</fileset>
</src>
<classpath refid = "classpath" />
</jrc>
</target>
</project>
Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.CreateReport (viewFullReport is the default target) as follows −
Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml
clean-sample:
[delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes
compile:
[mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes
[javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28:
warning: 'includeantruntime' was not set, defaulting to
[javac] Compiling 7 source files to C:\tools\jasperreports-5.0.1\test\classes
compilereportdesing:
[jrc] Compiling 1 report design files.
[jrc] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
[jrc] log4j:WARN Please initialize the log4j system properly.
[jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig
for more info.
[jrc] File : C:\tools\jasperreports-5.0.1\test\
jasper_report_template.jrxml ... OK.
run:
[echo] Runnin class : com.tutorialspoint.CreateReport
[java] Compiling Report Design ...
[java] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
[java] log4j:WARN Please initialize the log4j system properly.
[java] Done filling!!! ...
viewFillReport:
[java] log4j:WARN No appenders could be found for logger
(net.sf.jasperreports.extensions.ExtensionsEnvironment).
[java] log4j:WARN Please initialize the log4j system properly.
BUILD SUCCESSFUL
Total time: 72 minutes 13 seconds
As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −
Here, we can see that the attributes Name, Country, and Address are displayed.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2774,
"s": 2254,
"text": "Subreports are one of the nice features of the JasperReports. This feature allows incorporating a report within another report, that is, one report can be a subreport of another. Subreports help us keep report designs simple, as we can create many simple reports and encapsulate them into a master report. Subreports are compiled and filled just like normal reports. Any report template can be used as a subreport when incorporated into another report template, without anything changed inside (of the report template)."
},
{
"code": null,
"e": 2979,
"s": 2774,
"text": "Subreports are like normal report templates. They are in fact net.sf.jasperreports.engine.JasperReport objects, which are obtained after compiling a net.sf.jasperreports.engine.design.JasperDesign object."
},
{
"code": null,
"e": 3125,
"s": 2979,
"text": "A <subreport> element is used when introducing subreports into master reports. Here is the list of sub-elements in the <subreport> JRXML element."
},
{
"code": null,
"e": 3141,
"s": 3125,
"text": "<reportElement>"
},
{
"code": null,
"e": 3157,
"s": 3141,
"text": "<reportElement>"
},
{
"code": null,
"e": 3544,
"s": 3157,
"text": "<parametersMapExpression> − This is used to pass a map containing report parameters to the subreport. The map is usually obtained from a parameter in the master report, or by using the built-in REPORTS_PARAMETERS_MAP parameter to pass the parent report's parameters to the subreport. This expression should always return a java.util.Map object in which the keys are the parameter\nnames."
},
{
"code": null,
"e": 3931,
"s": 3544,
"text": "<parametersMapExpression> − This is used to pass a map containing report parameters to the subreport. The map is usually obtained from a parameter in the master report, or by using the built-in REPORTS_PARAMETERS_MAP parameter to pass the parent report's parameters to the subreport. This expression should always return a java.util.Map object in which the keys are the parameter\nnames."
},
{
"code": null,
"e": 4058,
"s": 3931,
"text": "<subreportParameter> − This element is used to pass parameters to the subreport. It has an attribute name, which is mandatory."
},
{
"code": null,
"e": 4185,
"s": 4058,
"text": "<subreportParameter> − This element is used to pass parameters to the subreport. It has an attribute name, which is mandatory."
},
{
"code": null,
"e": 4373,
"s": 4185,
"text": "<connectionExpression > − This is used to pass a java.sql.Connection to the subreport. It is used only when the subreport template needs a database connection during report filling phase."
},
{
"code": null,
"e": 4561,
"s": 4373,
"text": "<connectionExpression > − This is used to pass a java.sql.Connection to the subreport. It is used only when the subreport template needs a database connection during report filling phase."
},
{
"code": null,
"e": 4823,
"s": 4561,
"text": "<dataSourceExpression> − This is used to pass a datasource to the subreport. This datasource is usually obtained from a parameter in the master report or by using the built-in REPORT_DATA_SOURCE parameter to pass the parent report's datasource to the subreport."
},
{
"code": null,
"e": 5085,
"s": 4823,
"text": "<dataSourceExpression> − This is used to pass a datasource to the subreport. This datasource is usually obtained from a parameter in the master report or by using the built-in REPORT_DATA_SOURCE parameter to pass the parent report's datasource to the subreport."
},
{
"code": null,
"e": 5353,
"s": 5085,
"text": "The elements (connectionExpression and dataSourceExpression) cannot be present at the same time in a <subreport> element declaration. This is because we cannot supply both a data source and a connection to the subreport. We must decide on one of them and stick to it."
},
{
"code": null,
"e": 5621,
"s": 5353,
"text": "The elements (connectionExpression and dataSourceExpression) cannot be present at the same time in a <subreport> element declaration. This is because we cannot supply both a data source and a connection to the subreport. We must decide on one of them and stick to it."
},
{
"code": null,
"e": 6358,
"s": 5621,
"text": "<returnValue> − This is used to assign the value of one of the subreport's variables to one of the master report's variables. This sub element has attributes as follows −\n\nsubreportVariable − This attribute specifies the name of the subreport variable whose value is to be returned.\ntoVariable − This attribute specifies the name of the parent report variable whose value is to be copied/incremented with the value from the subreport.\ncalculation − This attribute can take values : Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance. Default value for attribute calculation is \"Nothing\".\nincrementerFactoryClass − This attribute specifies the factory class for creating the incrementer instance.\n\n"
},
{
"code": null,
"e": 6529,
"s": 6358,
"text": "<returnValue> − This is used to assign the value of one of the subreport's variables to one of the master report's variables. This sub element has attributes as follows −"
},
{
"code": null,
"e": 6640,
"s": 6529,
"text": "subreportVariable − This attribute specifies the name of the subreport variable whose value is to be returned."
},
{
"code": null,
"e": 6751,
"s": 6640,
"text": "subreportVariable − This attribute specifies the name of the subreport variable whose value is to be returned."
},
{
"code": null,
"e": 6903,
"s": 6751,
"text": "toVariable − This attribute specifies the name of the parent report variable whose value is to be copied/incremented with the value from the subreport."
},
{
"code": null,
"e": 7055,
"s": 6903,
"text": "toVariable − This attribute specifies the name of the parent report variable whose value is to be copied/incremented with the value from the subreport."
},
{
"code": null,
"e": 7247,
"s": 7055,
"text": "calculation − This attribute can take values : Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance. Default value for attribute calculation is \"Nothing\"."
},
{
"code": null,
"e": 7439,
"s": 7247,
"text": "calculation − This attribute can take values : Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance. Default value for attribute calculation is \"Nothing\"."
},
{
"code": null,
"e": 7547,
"s": 7439,
"text": "incrementerFactoryClass − This attribute specifies the factory class for creating the incrementer instance."
},
{
"code": null,
"e": 7655,
"s": 7547,
"text": "incrementerFactoryClass − This attribute specifies the factory class for creating the incrementer instance."
},
{
"code": null,
"e": 7985,
"s": 7655,
"text": "<subreportExpression> − This indicates where to find the compiled report template for the subreport. This element has a class attribute. The class attribute can take any of these values:java.lang.String, java.io.File, java.net.URL, java.io.InputStream, net.sf.jasperreports.engine.JasperReport. Default value is java.lang.String."
},
{
"code": null,
"e": 8315,
"s": 7985,
"text": "<subreportExpression> − This indicates where to find the compiled report template for the subreport. This element has a class attribute. The class attribute can take any of these values:java.lang.String, java.io.File, java.net.URL, java.io.InputStream, net.sf.jasperreports.engine.JasperReport. Default value is java.lang.String."
},
{
"code": null,
"e": 8749,
"s": 8315,
"text": "isUsingCache − This is an attribute of the <subreport> element. This is a Boolean, when set to true, the reporting engine will try to recognize previously loaded subreport template objects, using their specified source. This caching functionality is available only for subreport elements that have expressions returning java.lang.String objects as the subreport template source, representing file names, URLs, or classpath resources."
},
{
"code": null,
"e": 9183,
"s": 8749,
"text": "isUsingCache − This is an attribute of the <subreport> element. This is a Boolean, when set to true, the reporting engine will try to recognize previously loaded subreport template objects, using their specified source. This caching functionality is available only for subreport elements that have expressions returning java.lang.String objects as the subreport template source, representing file names, URLs, or classpath resources."
},
{
"code": null,
"e": 9509,
"s": 9183,
"text": "Let take up a simple example to demonstrate creation of subreports using JRDataSource. Let's first write two new report templates, one being subreport and the other Master report. The contents of the subreport (address_report_template.jrxml) template is as given below. Save it to C:\\tools\\jasperreports-5.0.1\\test directory."
},
{
"code": null,
"e": 11932,
"s": 9509,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<jasperReport\n xmlns = \"http://jasperreports.sourceforge.net/jasperreports\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\"\n name = \"address_report_template\" pageWidth = \"175\" pageHeight = \"842\" \n columnWidth = \"175\" leftMargin = \"0\" rightMargin = \"0\" \n topMargin = \"0\" bottomMargin = \"0\">\n\n <field name = \"city\" class = \"java.lang.String\"/>\n <field name = \"street\" class = \"java.lang.String\"/>\n \n <background>\n <band splitType = \"Stretch\"/>\n </background>\n \n <title>\n <band height = \"20\" splitType = \"Stretch\">\n \n <staticText>\n <reportElement x = \"0\" y = \"0\" width = \"100\" height = \"20\"/>\n \n <textElement>\n <font size = \"14\" isBold = \"true\"/>\n </textElement>\n\t\t\t\t\n <text><![CDATA[Addresses]]></text>\n </staticText>\n \n </band>\n </title>\n \n <pageHeader>\n <band height = \"12\" splitType = \"Stretch\"/>\n </pageHeader>\n \n <columnHeader>\n <band height = \"12\" splitType = \"Stretch\"/>\n </columnHeader>\n \n <detail>\n <band height = \"27\" splitType = \"Stretch\">\n \n <textField>\n <reportElement x = \"0\" y = \"0\" width = \"120\" height = \"20\"/>\n \n <textElement>\n <font size = \"12\" isBold = \"true\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{city}+\" Address:\"]]>\n </textFieldExpression>\n </textField>\n \n <textField isStretchWithOverflow = \"true\">\n <reportElement x = \"120\" y = \"0\" width = \"435\" height = \"20\"/>\n \n <textElement>\n <font size = \"12\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{street}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </detail>\n \n <columnFooter>\n <band height = \"8\" splitType = \"Stretch\"/>\n </columnFooter>\n \n <pageFooter>\n <band height = \"11\" splitType = \"Stretch\"/>\n </pageFooter>\n \n <summary>\n <band height = \"9\" splitType = \"Stretch\"/>\n </summary>\n\n</jasperReport>"
},
{
"code": null,
"e": 12117,
"s": 11932,
"text": "As we use a data source, we need to write a corresponding POJO file SubReportBean.java as shown below. Save it to directory C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint −"
},
{
"code": null,
"e": 12483,
"s": 12117,
"text": "package com.tutorialspoint;\n\npublic class SubReportBean {\n private String city;\n private String street;\n\n public String getCity() {\n return city;\n }\n\n public void setCity(String city) {\n this.city = city;\n }\n\n public String getStreet() {\n return street;\n }\n\n public void setStreet(String street) {\n this.street = street;\n }\n}"
},
{
"code": null,
"e": 12591,
"s": 12483,
"text": "Here, we have declared two fields 'city' and 'street' and respective getter and setter methods are defined."
},
{
"code": null,
"e": 12890,
"s": 12591,
"text": "Now, let's update our existing DataBean file. We will add a new field subReportBeanList, which is a java.util.List. This field will hold the list of SubReportBean objects. The contents of the file DataBean are as below. Save it to directory C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint."
},
{
"code": null,
"e": 13558,
"s": 12890,
"text": "package com.tutorialspoint;\n\nimport java.util.List;\n\npublic class DataBean {\n private String name;\n private String country;\n private List<SubReportBean> subReportBeanList;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n\n public List<SubReportBean> getSubReportBeanList() {\n return subReportBeanList;\n }\n\n public void setSubReportBeanList(List<SubReportBean> subReportBeanList) {\n this.subReportBeanList = subReportBeanList;\n }\n}"
},
{
"code": null,
"e": 13695,
"s": 13558,
"text": "Let's now update the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBeanList.java. The contents of this file are as −"
},
{
"code": null,
"e": 15202,
"s": 13695,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class DataBeanList {\n public ArrayList<DataBean> getDataBeanList() {\n\n // Create sub report data\n SubReportBean subBean1 = new SubReportBean();\n subBean1.setCity(\"Mumbai\");\n subBean1.setStreet(\"M.G.Road\");\n SubReportBean subBean2 = new SubReportBean();\n subBean2.setCity(\"New York\");\n subBean2.setStreet(\"Park Street\");\n SubReportBean subBean3 = new SubReportBean();\n subBean3.setCity(\"San Fransisco\");\n subBean3.setStreet(\"King Street\");\n\n ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();\n\n // Create master report data\n dataBeanList.add(produce(\"Manisha\", \"India\",\n Arrays.asList(subBean1)));\n dataBeanList.add(produce(\"Dennis Ritchie\", \"USA\",\n Arrays.asList(subBean2)));\n dataBeanList.add(produce(\"V.Anand\", \"India\",\n Arrays.asList(subBean1)));\n dataBeanList.add(produce(\"Shrinath\", \"California\",\n Arrays.asList(subBean3)));\n\n return dataBeanList;\n }\n\n /*\n * This method returns a DataBean object,\n * with name, country and sub report\n * bean data set in it.\n */\n private DataBean produce(String name, String country,\n List<SubReportBean> subBean) {\n DataBean dataBean = new DataBean();\n\n dataBean.setName(name);\n dataBean.setCountry(country);\n dataBean.setSubReportBeanList(subBean);\n\n return dataBean;\n }\n}"
},
{
"code": null,
"e": 15287,
"s": 15202,
"text": "In the method produce() in the above file, we are setting the list of SubReportBean."
},
{
"code": null,
"e": 15471,
"s": 15287,
"text": "Now, let's write a new master report template (jasper_report_template.jrxml). Save this file to directory C:\\tools\\jasperreports-5.0.1\\test. The contents for this file are as below − "
},
{
"code": null,
"e": 19476,
"s": 15471,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\"\n name = \"jasper_report_template\" language = \"groovy\" pageWidth = \"595\"\n pageHeight = \"842\" columnWidth =\"555\" leftMargin = \"20\" rightMargin = \"20\"\n topMargin = \"20\" bottomMargin = \"20\">\n\n <parameter name = \"SUBREPORT_DIR\" class = \"java.lang.String\" isForPrompting = \"false\">\n <defaultValueExpression>\n <![CDATA[\"C:\\\\tools\\\\jasperreports-5.0.1\\\\test\\\\\"]]>\n </defaultValueExpression>\n </parameter>\n \n <field name = \"country\" class = \"java.lang.String\"/>\n <field name = \"name\" class = \"java.lang.String\"/>\n <field name = \"subReportBeanList\" class = \"java.util.List\"/>\n \n <background>\n <band splitType = \"Stretch\"/>\n </background>\n \n <title>\n <band height = \"35\" splitType = \"Stretch\">\n \n <staticText>\n <reportElement x = \"0\" y = \"0\" width = \"204\" height = \"34\"/>\n \n <textElement>\n <font size = \"26\" isBold = \"true\"/>\n </textElement>\n\t\t\t\t\n <text><![CDATA[Contact Report]]></text>\n </staticText>\n \n </band>\n </title>\n \n <pageHeader>\n <band height = \"17\" splitType = \"Stretch\"/>\n </pageHeader>\n \n <columnHeader>\n <band height = \"21\" splitType = \"Stretch\"/>\n </columnHeader>\n \n <detail>\n <band height = \"112\" splitType = \"Stretch\">\n \n <staticText>\n <reportElement x = \"0\" y = \"0\" width = \"100\" height = \"20\"/>\n \n <textElement>\n <font size = \"12\" isBold = \"true\"/>\n </textElement>\n\t\t\t\t\n <text><![CDATA[Name:]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"20\" width = \"100\" height = \"20\"/>\n \n <textElement>\n <font size = \"12\" isBold = \"true\"/>\n </textElement>\n\t\t\t\t\n <text><![CDATA[Country:]]></text>\n </staticText>\n \n <textField>\n <reportElement x = \"104\" y = \"0\" width = \"277\" height = \"20\"/>\n \n <textElement>\n <font size = \"12\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{name}]]>\n </textFieldExpression>\n </textField>\n \n <textField>\n <reportElement x = \"104\" y = \"20\" width = \"277\" height = \"20\"/>\n \n <textElement>\n <font size = \"12\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{country}]]>\n </textFieldExpression>\n </textField>\n \n <subreport>\n <reportElement positionType = \"Float\" x = \"335\" y = \"25\" width = \"175\"\n height = \"20\" isRemoveLineWhenBlank = \"true\" backcolor = \"#99ccff\"/>\n\n <dataSourceExpression>\n new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource\n ($F{subReportBeanList})\n </dataSourceExpression>\n \n <subreportExpression class = \"java.lang.String\">\n <![CDATA[$P{SUBREPORT_DIR} + \"address_report_template.jasper\"]]>\n </subreportExpression>\n </subreport>\n \n <line>\n <reportElement x = \"0\" y = \"50\" width = \"550\" height = \"1\"/>\n </line>\n \n </band>\n </detail>\n \n <columnFooter>\n <band height = \"19\" splitType = \"Stretch\"/>\n </columnFooter>\n \n <pageFooter>\n <band height = \"18\" splitType = \"Stretch\"/>\n </pageFooter>\n \n <summary>\n <band height = \"14\" splitType = \"Stretch\"/>\n </summary>\n\n</jasperReport>"
},
{
"code": null,
"e": 19958,
"s": 19476,
"text": "In the above template, we have defined a new parameter \"SUBREPORT_DIR,\" which defines the path of the subreport. We have defined a field subReportBeanList of type java.util.List, which corresponds to property in the file DataBean. The element <subreport> has sub-element <dataSourceExpression>. We have put the list subReportBeanList in an instance of JRBeanCollectionDataSource. In the sub-element <subreportExpression/>, we have given the subreport name (AddressReport.jasper)."
},
{
"code": null,
"e": 20161,
"s": 19958,
"text": "Now, let's write a new class CreateReport to compile and execute our report template. The contents of file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\CreateReport.java are as given below −"
},
{
"code": null,
"e": 21855,
"s": 20161,
"text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JasperCompileManager;\nimport net.sf.jasperreports.engine.JasperFillManager;\nimport net.sf.jasperreports.engine.JasperReport;\nimport net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;\n\npublic class CreateReport {\n\n public static void main(String[] args) {\n String masterReportFileName = \"C://tools/jasperreports-5.0.1/test\"\n + \"/jasper_report_template.jrxml\";\n String subReportFileName = \"C://tools/jasperreports-5.0.1/test\"\n + \"/AddressReport.jrxml\";\n String destFileName = \"C://tools/jasperreports-5.0.1/test\"\n + \"/jasper_report_template.JRprint\";\n\t\t\t\n DataBeanList DataBeanList = new DataBeanList();\n ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();\n JRBeanCollectionDataSource beanColDataSource = new \n JRBeanCollectionDataSource(dataList);\n\n try {\n /* Compile the master and sub report */\n JasperReport jasperMasterReport = JasperCompileManager\n .compileReport(masterReportFileName);\n JasperReport jasperSubReport = JasperCompileManager\n .compileReport(subReportFileName);\n\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"subreportParameter\", jasperSubReport);\n JasperFillManager.fillReportToFile(jasperMasterReport, \n destFileName, parameters, beanColDataSource);\n\n } catch (JRException e) {\n\n e.printStackTrace();\n }\n System.out.println(\"Done filling!!! ...\");\n }\n}"
},
{
"code": null,
"e": 22000,
"s": 21855,
"text": "Here, we see that we are compiling both the master and sub report templates and passing the master report (.jasper) file for the report filling."
},
{
"code": null,
"e": 22211,
"s": 22000,
"text": "Now, all our files are ready, let's compile and execute them using our regular ANT build process. The contents of the file build.xml (saved under directory C:\\tools\\jasperreports-5.0.1\\test) are as given below."
},
{
"code": null,
"e": 22352,
"s": 22211,
"text": "The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml."
},
{
"code": null,
"e": 23427,
"s": 22352,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"viewFillReport\" basedir = \".\">\n <import file = \"baseBuild.xml\" />\n \n <target name = \"viewFillReport\" depends = \"compile,compilereportdesing,run\"\n description = \"Launches the report viewer to preview the \n report stored in the .JRprint file.\">\n \n <java classname = \"net.sf.jasperreports.view.JasperViewer\" fork = \"true\">\n <arg value = \"-F${file.name}.JRprint\" />\n <classpath refid = \"classpath\" />\n </java>\n </target>\n \n <target name = \"compilereportdesing\" description = \"Compiles the JXML file and\n produces the .jasper file.\">\n \n <taskdef name = \"jrc\" classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n\t\t\n </target>\n\n</project>"
},
{
"code": null,
"e": 23645,
"s": 23427,
"text": "Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.CreateReport (viewFullReport is the default target) as follows −"
},
{
"code": null,
"e": 25084,
"s": 23645,
"text": "Buildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\nclean-sample:\n [delete] Deleting directory C:\\tools\\jasperreports-5.0.1\\test\\classes\n\ncompile:\n [mkdir] Created dir: C:\\tools\\jasperreports-5.0.1\\test\\classes\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:28: \n warning: 'includeantruntime' was not set, defaulting to\n [javac] Compiling 7 source files to C:\\tools\\jasperreports-5.0.1\\test\\classes\n\ncompilereportdesing:\n [jrc] Compiling 1 report design files.\n [jrc] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [jrc] log4j:WARN Please initialize the log4j system properly.\n [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig \n for more info.\n [jrc] File : C:\\tools\\jasperreports-5.0.1\\test\\\n jasper_report_template.jrxml ... OK.\n\nrun:\n [echo] Runnin class : com.tutorialspoint.CreateReport\n [java] Compiling Report Design ...\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [java] log4j:WARN Please initialize the log4j system properly.\n [java] Done filling!!! ...\n\nviewFillReport:\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nBUILD SUCCESSFUL\nTotal time: 72 minutes 13 seconds\n"
},
{
"code": null,
"e": 25186,
"s": 25084,
"text": "As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −"
},
{
"code": null,
"e": 25265,
"s": 25186,
"text": "Here, we can see that the attributes Name, Country, and Address are displayed."
},
{
"code": null,
"e": 25272,
"s": 25265,
"text": " Print"
},
{
"code": null,
"e": 25283,
"s": 25272,
"text": " Add Notes"
}
] |
Python Pandas - How to select rows from a DataFrame by integer location
|
To select rows by integer location, use the iloc() function. Mention the index number of the row you want to select.
Create a DataFrame −
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],index=['x', 'y', 'z'],columns=['a', 'b'])
Select rows with integer location using iloc() −
dataFrame.iloc[1]
Following is the code −
import pandas as pd
# Create DataFrame
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],index=['x', 'y', 'z'],columns=['a', 'b'])
# DataFrame
print"DataFrame...\n",dataFrame
# select rows with loc
print"\nSelect rows by passing label..."
print(dataFrame.loc['z'])
# select rows with integer location using iloc
print"\nSelect rows by passing integer location..."
print(dataFrame.iloc[1])
This will produce the following output −
DataFrame...
a b
x 10 15
y 20 25
z 30 35
Select rows by passing label...
a 30
b 35
Name: z, dtype: int64
Select rows by passing integer location...
a 20
b 25
Name: y, dtype: int64
|
[
{
"code": null,
"e": 1179,
"s": 1062,
"text": "To select rows by integer location, use the iloc() function. Mention the index number of the row you want to select."
},
{
"code": null,
"e": 1200,
"s": 1179,
"text": "Create a DataFrame −"
},
{
"code": null,
"e": 1298,
"s": 1200,
"text": "dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],index=['x', 'y', 'z'],columns=['a', 'b'])"
},
{
"code": null,
"e": 1347,
"s": 1298,
"text": "Select rows with integer location using iloc() −"
},
{
"code": null,
"e": 1366,
"s": 1347,
"text": "dataFrame.iloc[1]\n"
},
{
"code": null,
"e": 1390,
"s": 1366,
"text": "Following is the code −"
},
{
"code": null,
"e": 1791,
"s": 1390,
"text": "import pandas as pd\n\n# Create DataFrame\ndataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],index=['x', 'y', 'z'],columns=['a', 'b'])\n\n# DataFrame\nprint\"DataFrame...\\n\",dataFrame\n\n# select rows with loc\nprint\"\\nSelect rows by passing label...\"\nprint(dataFrame.loc['z'])\n\n# select rows with integer location using iloc\nprint\"\\nSelect rows by passing integer location...\"\nprint(dataFrame.iloc[1])\n\n"
},
{
"code": null,
"e": 1832,
"s": 1791,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2042,
"s": 1832,
"text": "DataFrame...\n a b\nx 10 15\ny 20 25\nz 30 35\n\nSelect rows by passing label...\na 30\nb 35\nName: z, dtype: int64\n\nSelect rows by passing integer location...\na 20\nb 25\nName: y, dtype: int64"
}
] |
Retrieving Cookies in Python - GeeksforGeeks
|
16 Jul, 2020
Retrieving cookies in Python can be done by the use of the Requests library. Requests library is one of the integral part of Python for making HTTP requests to a specified URL. The below codes show different approaches to do show:
1. By requesting a session:
# import the requests libraryimport requests # initialize a sessionsession = requests.Session() # send a get request to the serverresponse = session.get('http://google.com') # print the response dictionaryprint(session.cookies.get_dict())
Output:
{‘1P_JAR’: ‘2020-04-30-07’, ‘NID’: ‘203=GIlzlNytcSGjMtV-ML49xgKQax4NACMgFZi56sbQ3tSd9uDqL7EWZ6KC_gUqPsKkk-XsDIlca8ElKqhjsHGgWrPRwbbPBFXxcGL_G5Jd0gzdQYhCo-QALsZm4zItqIeImlBBTp_TDOgRQIW0d2hSNerxmQkljluhIA3QGLgNLnM’}
2.By requesting cookies list from the server:
import requests r = requests.get('http://google.com') for c in r.cookies: print(c.name +"==>>", c.value)
Output:
1P_JAR==>> 2020-04-30-07
NID==>> 203=YvFCKkIeHS4SvpTVv8jw6MIGEU54IlN8V_1aQZrXmOU7Zdj74qZdW69E3A38KSP-GrE5xLmR40ozrHTFxkXm4-iaTm4DbhU4cwmvOWHEs1OZELI8H8KQLmBLCxccxCuHT07QQ2mqc-ppBYXhcHtOC7idVc9RWD2kmNPDMR-YMl4
Python-projects
python-utility
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
Factory method design pattern in Java
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 24132,
"s": 23901,
"text": "Retrieving cookies in Python can be done by the use of the Requests library. Requests library is one of the integral part of Python for making HTTP requests to a specified URL. The below codes show different approaches to do show:"
},
{
"code": null,
"e": 24160,
"s": 24132,
"text": "1. By requesting a session:"
},
{
"code": "# import the requests libraryimport requests # initialize a sessionsession = requests.Session() # send a get request to the serverresponse = session.get('http://google.com') # print the response dictionaryprint(session.cookies.get_dict())",
"e": 24402,
"s": 24160,
"text": null
},
{
"code": null,
"e": 24410,
"s": 24402,
"text": "Output:"
},
{
"code": null,
"e": 24624,
"s": 24410,
"text": "{‘1P_JAR’: ‘2020-04-30-07’, ‘NID’: ‘203=GIlzlNytcSGjMtV-ML49xgKQax4NACMgFZi56sbQ3tSd9uDqL7EWZ6KC_gUqPsKkk-XsDIlca8ElKqhjsHGgWrPRwbbPBFXxcGL_G5Jd0gzdQYhCo-QALsZm4zItqIeImlBBTp_TDOgRQIW0d2hSNerxmQkljluhIA3QGLgNLnM’}"
},
{
"code": null,
"e": 24670,
"s": 24624,
"text": "2.By requesting cookies list from the server:"
},
{
"code": "import requests r = requests.get('http://google.com') for c in r.cookies: print(c.name +\"==>>\", c.value)",
"e": 24780,
"s": 24670,
"text": null
},
{
"code": null,
"e": 24788,
"s": 24780,
"text": "Output:"
},
{
"code": null,
"e": 24813,
"s": 24788,
"text": "1P_JAR==>> 2020-04-30-07"
},
{
"code": null,
"e": 24997,
"s": 24813,
"text": "NID==>> 203=YvFCKkIeHS4SvpTVv8jw6MIGEU54IlN8V_1aQZrXmOU7Zdj74qZdW69E3A38KSP-GrE5xLmR40ozrHTFxkXm4-iaTm4DbhU4cwmvOWHEs1OZELI8H8KQLmBLCxccxCuHT07QQ2mqc-ppBYXhcHtOC7idVc9RWD2kmNPDMR-YMl4"
},
{
"code": null,
"e": 25013,
"s": 24997,
"text": "Python-projects"
},
{
"code": null,
"e": 25028,
"s": 25013,
"text": "python-utility"
},
{
"code": null,
"e": 25035,
"s": 25028,
"text": "Python"
},
{
"code": null,
"e": 25051,
"s": 25035,
"text": "Write From Home"
},
{
"code": null,
"e": 25149,
"s": 25051,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25158,
"s": 25149,
"text": "Comments"
},
{
"code": null,
"e": 25171,
"s": 25158,
"text": "Old Comments"
},
{
"code": null,
"e": 25203,
"s": 25171,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25259,
"s": 25203,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25301,
"s": 25259,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25343,
"s": 25301,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25379,
"s": 25343,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 25415,
"s": 25379,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 25431,
"s": 25415,
"text": "Python infinity"
},
{
"code": null,
"e": 25492,
"s": 25431,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 25528,
"s": 25492,
"text": "Matplotlib.pyplot.title() in Python"
}
] |
Tryit Editor v3.7
|
HTML file paths
Tryit: absolute url
|
[
{
"code": null,
"e": 26,
"s": 10,
"text": "HTML file paths"
}
] |
Find count of Almost Prime numbers from 1 to N - GeeksforGeeks
|
21 May, 2021
Given a number N. Find number of almost primes from 1 to . A number is called almost if it has exactly two distinct prime factors. Note: The numbers can have any number of non-prime factors but should have exactly two prime factors.Examples:
Input : N = 10
Output : 2
Explanation : 6, 10 are such numbers.
Input : N = 21
Output : 8
An efficient solution is to find prime numbers using Sieve of Eratosthenes. And find distinct prime factors count for numbers less than N.Please Refer: Almost Prime NumbersBelow is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to count almost prime numbers// from 1 to n#include <bits/stdc++.h>using namespace std;#define N 100005 // Create a boolean array "prime[0..n]" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.bool prime[N]; void SieveOfEratosthenes(){ memset(prime, true, sizeof(prime)); prime[1] = false; for (int p = 2; p * p < N; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i < N; i += p) prime[i] = false; } }} // Function to count almost prime numbers// from 1 to nint almostPrimes(int n){ // to store required answer int ans = 0; // 6 is first almost prime number for (int i = 6; i <= n; i++) { // to count prime factors int c = 0; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { // if it is perfect square if (j * j == i) { if (prime[j]) c++; } else { if (prime[j]) c++; if (prime[i / j]) c++; } } } // if I is almost prime number if (c == 2) ans++; } return ans;} // Driver codeint main(){ SieveOfEratosthenes(); int n = 21; cout << almostPrimes(n); return 0;}
// Java program to count almost prime numbers// from 1 to n import java.io.*; class GFG { static int N = 100005; // Create a boolean array "prime[0..n]" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.static boolean prime[] = new boolean[N];static void SieveOfEratosthenes(){ for(int i=0;i<N;i++) prime[i] =true; prime[1] = false; for (int p = 2; p * p < N; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i < N; i += p) prime[i] = false; } }} // Function to count almost prime numbers// from 1 to nstatic int almostPrimes(int n){ // to store required answer int ans = 0; // 6 is first almost prime number for (int i = 6; i <= n; i++) { // to count prime factors int c = 0; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { // if it is perfect square if (j * j == i) { if (prime[j]) c++; } else { if (prime[j]) c++; if (prime[i / j]) c++; } } } // if I is almost prime number if (c == 2) ans++; } return ans;} // Driver code public static void main (String[] args) { SieveOfEratosthenes(); int n = 21; System.out.println( almostPrimes(n)); }}//This code is contributed by inder_verma..
# Python 3 program to count almost# prime numbers# from 1 to n # from math import everythingfrom math import * N = 100005 # Create a boolean array "prime[0..n]"# and initialize all entries it as true.# A value in prime[i] will# finally be false if i is Not a prime, else true.prime = [True] * N def SieveOfEratosthenes() : prime[1] = False for p in range(2, int(sqrt(N))) : # If prime[p] is not changed, then # it is a prime if prime[p] == True : # Update all multiples of p for i in range(2*p, N, p) : prime[i] = False # Function to count almost prime numbers# from 1 to ndef almostPrimes(n) : # to store required answer ans = 0 # 6 is first almost prime number for i in range(6, n + 1) : # to count prime factors c = 0 for j in range(2, int(sqrt(i)) + 1) : # if it is perfect square if i % j == 0 : if j * j == i : if prime[j] : c += 1 else : if prime[j] : c += 1 if prime[i // j] : c += 1 # if I is almost prime number if c == 2 : ans += 1 return ans # Driver Codeif __name__ == "__main__" : SieveOfEratosthenes() n = 21 print(almostPrimes(n)) # This code is contributed by ANKITRAI1
// C# program to count almost// prime numbers from 1 to nusing System; class GFG{ static int N = 100005; // Create a boolean array "prime[0..n]"// and initialize all entries it as// true. A value in prime[i] will finally// be false if i is Not a prime, else true.static bool []prime = new bool[N];static void SieveOfEratosthenes(){ for(int i = 0; i < N; i++) prime[i] = true; prime[1] = false; for (int p = 2; p * p < N; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i < N; i += p) prime[i] = false; } }} // Function to count almost// prime numbers from 1 to nstatic int almostPrimes(int n){ // to store required answer int ans = 0; // 6 is first almost prime number for (int i = 6; i <= n; i++) { // to count prime factors int c = 0; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { // if it is perfect square if (j * j == i) { if (prime[j]) c++; } else { if (prime[j]) c++; if (prime[i / j]) c++; } } } // if I is almost prime number if (c == 2) ans++; } return ans;} // Driver codepublic static void Main (){ SieveOfEratosthenes(); int n = 21; Console.WriteLine( almostPrimes(n));}} // This code is contributed// by inder_verma
<?php// PHP program to count almost prime// numbers from 1 to n $N = 100005; // Create a boolean array "prime[0..n]"// and initialize all entries it as true.// A value in prime[i] will// finally be false if i is Not a prime, else true.$prime = array_fill(0, $N, true); function SieveOfEratosthenes(){ global $N, $prime; $prime[1] = false; for($p = 2; $p < (int)(sqrt($N)); $p++) { // If prime[p] is not changed, then // it is a prime if ($prime[$p] == true) // Update all multiples of p for($i = 2 * $p; $i < $N; $i += $p) $prime[$i] = false; }} // Function to count almost prime// numbers from 1 to nfunction almostPrimes($n){ global $prime; // to store required answer $ans = 0; // 6 is first almost prime number for($i = 6; $i < $n + 1; $i++) { // to count prime factors $c = 0; for($j = 2; $i >= $j * $j; $j++) { // if it is perfect square if ($i % $j == 0) { if ($j * $j == $i) { if ($prime[$j]) $c += 1; } else { if ($prime[$j]) $c += 1; if ($prime[($i / $j)]) $c += 1; } } } // if I is almost prime number if ($c == 2) $ans += 1; } return $ans;} // Driver CodeSieveOfEratosthenes();$n = 21; print(almostPrimes($n)); // This code is contributed by mits?>
<script>// Javascript program to count almost prime// numbers from 1 to n let N = 100005; // Create a boolean array "prime[0..n]"// and initialize all entries it as true.// A value in prime[i] will// finally be false if i is Not a prime, else true.let prime = new Array(N).fill(true); function SieveOfEratosthenes(){ prime[1] = false; for(let p = 2; p < Math.floor(Math.sqrt(N)); p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) // Update all multiples of p for(let i = 2 * p; i < N; i += p) prime[i] = false; }} // Function to count almost prime// numbers from 1 to nfunction almostPrimes(n){ // to store required answer let ans = 0; // 6 is first almost prime number for(let i = 6; i < n + 1; i++) { // to count prime factors let c = 0; for(let j = 2; i >= j * j; j++) { // if it is perfect square if (i % j == 0) { if (j * j == i) { if (prime[j]) c += 1; } else { if (prime[j]) c += 1; if (prime[(i / j)]) c += 1; } } } // if I is almost prime number if (c == 2) ans += 1; } return ans;} // Driver CodeSieveOfEratosthenes();let n = 21; document.write(almostPrimes(n)); // This code is contributed by _saurabh_jaiswal</script>
8
ankthon
inderDuMCA
Mithun Kumar
_saurabh_jaiswal
Prime Number
prime-factor
sieve
Mathematical
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
The Knight's tour problem | Backtracking-1
Find all factors of a natural number | Set 1
Program for factorial of a number
Operators in C / C++
Minimum number of jumps to reach end
Find minimum number of coins that make a given value
|
[
{
"code": null,
"e": 24249,
"s": 24221,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 24493,
"s": 24249,
"text": "Given a number N. Find number of almost primes from 1 to . A number is called almost if it has exactly two distinct prime factors. Note: The numbers can have any number of non-prime factors but should have exactly two prime factors.Examples: "
},
{
"code": null,
"e": 24584,
"s": 24493,
"text": "Input : N = 10\nOutput : 2\nExplanation : 6, 10 are such numbers.\n\nInput : N = 21\nOutput : 8"
},
{
"code": null,
"e": 24811,
"s": 24586,
"text": "An efficient solution is to find prime numbers using Sieve of Eratosthenes. And find distinct prime factors count for numbers less than N.Please Refer: Almost Prime NumbersBelow is the implementation of the above approach: "
},
{
"code": null,
"e": 24815,
"s": 24811,
"text": "C++"
},
{
"code": null,
"e": 24820,
"s": 24815,
"text": "Java"
},
{
"code": null,
"e": 24829,
"s": 24820,
"text": "Python 3"
},
{
"code": null,
"e": 24832,
"s": 24829,
"text": "C#"
},
{
"code": null,
"e": 24836,
"s": 24832,
"text": "PHP"
},
{
"code": null,
"e": 24847,
"s": 24836,
"text": "Javascript"
},
{
"code": "// CPP program to count almost prime numbers// from 1 to n#include <bits/stdc++.h>using namespace std;#define N 100005 // Create a boolean array \"prime[0..n]\" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.bool prime[N]; void SieveOfEratosthenes(){ memset(prime, true, sizeof(prime)); prime[1] = false; for (int p = 2; p * p < N; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i < N; i += p) prime[i] = false; } }} // Function to count almost prime numbers// from 1 to nint almostPrimes(int n){ // to store required answer int ans = 0; // 6 is first almost prime number for (int i = 6; i <= n; i++) { // to count prime factors int c = 0; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { // if it is perfect square if (j * j == i) { if (prime[j]) c++; } else { if (prime[j]) c++; if (prime[i / j]) c++; } } } // if I is almost prime number if (c == 2) ans++; } return ans;} // Driver codeint main(){ SieveOfEratosthenes(); int n = 21; cout << almostPrimes(n); return 0;}",
"e": 26354,
"s": 24847,
"text": null
},
{
"code": "// Java program to count almost prime numbers// from 1 to n import java.io.*; class GFG { static int N = 100005; // Create a boolean array \"prime[0..n]\" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.static boolean prime[] = new boolean[N];static void SieveOfEratosthenes(){ for(int i=0;i<N;i++) prime[i] =true; prime[1] = false; for (int p = 2; p * p < N; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i < N; i += p) prime[i] = false; } }} // Function to count almost prime numbers// from 1 to nstatic int almostPrimes(int n){ // to store required answer int ans = 0; // 6 is first almost prime number for (int i = 6; i <= n; i++) { // to count prime factors int c = 0; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { // if it is perfect square if (j * j == i) { if (prime[j]) c++; } else { if (prime[j]) c++; if (prime[i / j]) c++; } } } // if I is almost prime number if (c == 2) ans++; } return ans;} // Driver code public static void main (String[] args) { SieveOfEratosthenes(); int n = 21; System.out.println( almostPrimes(n)); }}//This code is contributed by inder_verma..",
"e": 27984,
"s": 26354,
"text": null
},
{
"code": "# Python 3 program to count almost# prime numbers# from 1 to n # from math import everythingfrom math import * N = 100005 # Create a boolean array \"prime[0..n]\"# and initialize all entries it as true.# A value in prime[i] will# finally be false if i is Not a prime, else true.prime = [True] * N def SieveOfEratosthenes() : prime[1] = False for p in range(2, int(sqrt(N))) : # If prime[p] is not changed, then # it is a prime if prime[p] == True : # Update all multiples of p for i in range(2*p, N, p) : prime[i] = False # Function to count almost prime numbers# from 1 to ndef almostPrimes(n) : # to store required answer ans = 0 # 6 is first almost prime number for i in range(6, n + 1) : # to count prime factors c = 0 for j in range(2, int(sqrt(i)) + 1) : # if it is perfect square if i % j == 0 : if j * j == i : if prime[j] : c += 1 else : if prime[j] : c += 1 if prime[i // j] : c += 1 # if I is almost prime number if c == 2 : ans += 1 return ans # Driver Codeif __name__ == \"__main__\" : SieveOfEratosthenes() n = 21 print(almostPrimes(n)) # This code is contributed by ANKITRAI1",
"e": 29410,
"s": 27984,
"text": null
},
{
"code": "// C# program to count almost// prime numbers from 1 to nusing System; class GFG{ static int N = 100005; // Create a boolean array \"prime[0..n]\"// and initialize all entries it as// true. A value in prime[i] will finally// be false if i is Not a prime, else true.static bool []prime = new bool[N];static void SieveOfEratosthenes(){ for(int i = 0; i < N; i++) prime[i] = true; prime[1] = false; for (int p = 2; p * p < N; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i < N; i += p) prime[i] = false; } }} // Function to count almost// prime numbers from 1 to nstatic int almostPrimes(int n){ // to store required answer int ans = 0; // 6 is first almost prime number for (int i = 6; i <= n; i++) { // to count prime factors int c = 0; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { // if it is perfect square if (j * j == i) { if (prime[j]) c++; } else { if (prime[j]) c++; if (prime[i / j]) c++; } } } // if I is almost prime number if (c == 2) ans++; } return ans;} // Driver codepublic static void Main (){ SieveOfEratosthenes(); int n = 21; Console.WriteLine( almostPrimes(n));}} // This code is contributed// by inder_verma",
"e": 31084,
"s": 29410,
"text": null
},
{
"code": "<?php// PHP program to count almost prime// numbers from 1 to n $N = 100005; // Create a boolean array \"prime[0..n]\"// and initialize all entries it as true.// A value in prime[i] will// finally be false if i is Not a prime, else true.$prime = array_fill(0, $N, true); function SieveOfEratosthenes(){ global $N, $prime; $prime[1] = false; for($p = 2; $p < (int)(sqrt($N)); $p++) { // If prime[p] is not changed, then // it is a prime if ($prime[$p] == true) // Update all multiples of p for($i = 2 * $p; $i < $N; $i += $p) $prime[$i] = false; }} // Function to count almost prime// numbers from 1 to nfunction almostPrimes($n){ global $prime; // to store required answer $ans = 0; // 6 is first almost prime number for($i = 6; $i < $n + 1; $i++) { // to count prime factors $c = 0; for($j = 2; $i >= $j * $j; $j++) { // if it is perfect square if ($i % $j == 0) { if ($j * $j == $i) { if ($prime[$j]) $c += 1; } else { if ($prime[$j]) $c += 1; if ($prime[($i / $j)]) $c += 1; } } } // if I is almost prime number if ($c == 2) $ans += 1; } return $ans;} // Driver CodeSieveOfEratosthenes();$n = 21; print(almostPrimes($n)); // This code is contributed by mits?>",
"e": 32693,
"s": 31084,
"text": null
},
{
"code": "<script>// Javascript program to count almost prime// numbers from 1 to n let N = 100005; // Create a boolean array \"prime[0..n]\"// and initialize all entries it as true.// A value in prime[i] will// finally be false if i is Not a prime, else true.let prime = new Array(N).fill(true); function SieveOfEratosthenes(){ prime[1] = false; for(let p = 2; p < Math.floor(Math.sqrt(N)); p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) // Update all multiples of p for(let i = 2 * p; i < N; i += p) prime[i] = false; }} // Function to count almost prime// numbers from 1 to nfunction almostPrimes(n){ // to store required answer let ans = 0; // 6 is first almost prime number for(let i = 6; i < n + 1; i++) { // to count prime factors let c = 0; for(let j = 2; i >= j * j; j++) { // if it is perfect square if (i % j == 0) { if (j * j == i) { if (prime[j]) c += 1; } else { if (prime[j]) c += 1; if (prime[(i / j)]) c += 1; } } } // if I is almost prime number if (c == 2) ans += 1; } return ans;} // Driver CodeSieveOfEratosthenes();let n = 21; document.write(almostPrimes(n)); // This code is contributed by _saurabh_jaiswal</script>",
"e": 34295,
"s": 32693,
"text": null
},
{
"code": null,
"e": 34297,
"s": 34295,
"text": "8"
},
{
"code": null,
"e": 34307,
"s": 34299,
"text": "ankthon"
},
{
"code": null,
"e": 34318,
"s": 34307,
"text": "inderDuMCA"
},
{
"code": null,
"e": 34331,
"s": 34318,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 34348,
"s": 34331,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 34361,
"s": 34348,
"text": "Prime Number"
},
{
"code": null,
"e": 34374,
"s": 34361,
"text": "prime-factor"
},
{
"code": null,
"e": 34380,
"s": 34374,
"text": "sieve"
},
{
"code": null,
"e": 34393,
"s": 34380,
"text": "Mathematical"
},
{
"code": null,
"e": 34406,
"s": 34393,
"text": "Mathematical"
},
{
"code": null,
"e": 34419,
"s": 34406,
"text": "Prime Number"
},
{
"code": null,
"e": 34425,
"s": 34419,
"text": "sieve"
},
{
"code": null,
"e": 34523,
"s": 34425,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34532,
"s": 34523,
"text": "Comments"
},
{
"code": null,
"e": 34545,
"s": 34532,
"text": "Old Comments"
},
{
"code": null,
"e": 34569,
"s": 34545,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 34612,
"s": 34569,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 34626,
"s": 34612,
"text": "Prime Numbers"
},
{
"code": null,
"e": 34675,
"s": 34626,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34718,
"s": 34675,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 34763,
"s": 34718,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 34797,
"s": 34763,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 34818,
"s": 34797,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 34855,
"s": 34818,
"text": "Minimum number of jumps to reach end"
}
] |
Java Program to concatenate a String and Integers
|
To concatenate a String and some integer values, you need to use the + operator.
Let’s say the following is the string.
String str = "Demo Text";
Now, we will concatenate integer values.
String res = str + 1 + 2 + 3 + 4 + 5;
The following is the final example.
Live Demo
public class Demo {
public static void main(String[] args) {
String str = "Demo Text";
System.out.println("String = "+str);
String res = str + 1 + 2 + 3 + 4 + 5;
System.out.println(res);
}
}
String = Demo Text
Demo Text12345
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "To concatenate a String and some integer values, you need to use the + operator."
},
{
"code": null,
"e": 1182,
"s": 1143,
"text": "Let’s say the following is the string."
},
{
"code": null,
"e": 1209,
"s": 1182,
"text": "String str = \"Demo Text\";\n"
},
{
"code": null,
"e": 1250,
"s": 1209,
"text": "Now, we will concatenate integer values."
},
{
"code": null,
"e": 1289,
"s": 1250,
"text": "String res = str + 1 + 2 + 3 + 4 + 5;\n"
},
{
"code": null,
"e": 1325,
"s": 1289,
"text": "The following is the final example."
},
{
"code": null,
"e": 1336,
"s": 1325,
"text": " Live Demo"
},
{
"code": null,
"e": 1557,
"s": 1336,
"text": "public class Demo {\n public static void main(String[] args) {\n String str = \"Demo Text\";\n System.out.println(\"String = \"+str);\n String res = str + 1 + 2 + 3 + 4 + 5;\n System.out.println(res);\n }\n}"
},
{
"code": null,
"e": 1592,
"s": 1557,
"text": "String = Demo Text\nDemo Text12345\n"
}
] |
AIML - Introduction
|
AIML stands for Artificial Intelligence Markup Language. AIML was developed by the Alicebot free software community and Dr. Richard S. Wallace during 1995-2000. AIML is used to create or customize Alicebot which is a chat-box application based on A.L.I.C.E. (Artificial Linguistic Internet Computer Entity) free software.
Following are the important tags which are commonly used in AIML documents.
<aiml>
Defines the beginning and end of a AIML document.
<category>
Defines the unit of knowledge in Alicebot's knowledge base.
<pattern>
Defines the pattern to match what a user may input to an Alicebot.
<template>
Defines the response of an Alicebot to user's input.
We'll discuss each of these tags in AIML Basic tags chapter.
Following are some of the other widely used aiml tags. We'll be discussing each tag in details in coming chapters.
<star>
Used to match wild card * character(s) in the <pattern> Tag.
<srai>
Multipurpose tag, used to call/match the other categories.
<random>
Used <random> to get random responses.
<li>
Used to represent multiple responses.
<set>
Used to set value in an AIML variable.
<get>
Used to get value stored in an AIML variable.
<that>
Used in AIML to respond based on the context.
<topic>
Used in AIML to store a context so that later conversation can be done based on that context.
<think>
Used in AIML to store a variable without notifying the user.
<condition>
Similar to switch statements in programming language. It helps ALICE to respond to matching input.
AIML vocabulary uses words, space and two special characters * and _ as wild cards. AIML interpreter gives preference to pattern having _ than pattern having *. AIML tags are XML compliant and patterns are case-insensitive.
<aiml version = "1.0.1" encoding = "UTF-8"?>
<category>
<pattern> HELLO ALICE </pattern>
<template>
Hello User!
</template>
</category>
</aiml>
Following are the important points to be considered −
<aiml> tag signifies start of the AIML document.
<aiml> tag signifies start of the AIML document.
<category> tag defines the knowledge unit.
<category> tag defines the knowledge unit.
<pattern> tag defines the pattern user is going to type.
<pattern> tag defines the pattern user is going to type.
<template> tag defines the response to the user if user types Hello Alice.
<template> tag defines the response to the user if user types Hello Alice.
User: Hello Alice
Bot: Hello User
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2133,
"s": 1811,
"text": "AIML stands for Artificial Intelligence Markup Language. AIML was developed by the Alicebot free software community and Dr. Richard S. Wallace during 1995-2000. AIML is used to create or customize Alicebot which is a chat-box application based on A.L.I.C.E. (Artificial Linguistic Internet Computer Entity) free software."
},
{
"code": null,
"e": 2209,
"s": 2133,
"text": "Following are the important tags which are commonly used in AIML documents."
},
{
"code": null,
"e": 2216,
"s": 2209,
"text": "<aiml>"
},
{
"code": null,
"e": 2267,
"s": 2216,
"text": "Defines the beginning and end of a AIML document."
},
{
"code": null,
"e": 2278,
"s": 2267,
"text": "<category>"
},
{
"code": null,
"e": 2338,
"s": 2278,
"text": "Defines the unit of knowledge in Alicebot's knowledge base."
},
{
"code": null,
"e": 2348,
"s": 2338,
"text": "<pattern>"
},
{
"code": null,
"e": 2415,
"s": 2348,
"text": "Defines the pattern to match what a user may input to an Alicebot."
},
{
"code": null,
"e": 2426,
"s": 2415,
"text": "<template>"
},
{
"code": null,
"e": 2479,
"s": 2426,
"text": "Defines the response of an Alicebot to user's input."
},
{
"code": null,
"e": 2540,
"s": 2479,
"text": "We'll discuss each of these tags in AIML Basic tags chapter."
},
{
"code": null,
"e": 2655,
"s": 2540,
"text": "Following are some of the other widely used aiml tags. We'll be discussing each tag in details in coming chapters."
},
{
"code": null,
"e": 2662,
"s": 2655,
"text": "<star>"
},
{
"code": null,
"e": 2723,
"s": 2662,
"text": "Used to match wild card * character(s) in the <pattern> Tag."
},
{
"code": null,
"e": 2730,
"s": 2723,
"text": "<srai>"
},
{
"code": null,
"e": 2789,
"s": 2730,
"text": "Multipurpose tag, used to call/match the other categories."
},
{
"code": null,
"e": 2798,
"s": 2789,
"text": "<random>"
},
{
"code": null,
"e": 2837,
"s": 2798,
"text": "Used <random> to get random responses."
},
{
"code": null,
"e": 2842,
"s": 2837,
"text": "<li>"
},
{
"code": null,
"e": 2880,
"s": 2842,
"text": "Used to represent multiple responses."
},
{
"code": null,
"e": 2886,
"s": 2880,
"text": "<set>"
},
{
"code": null,
"e": 2925,
"s": 2886,
"text": "Used to set value in an AIML variable."
},
{
"code": null,
"e": 2931,
"s": 2925,
"text": "<get>"
},
{
"code": null,
"e": 2977,
"s": 2931,
"text": "Used to get value stored in an AIML variable."
},
{
"code": null,
"e": 2984,
"s": 2977,
"text": "<that>"
},
{
"code": null,
"e": 3030,
"s": 2984,
"text": "Used in AIML to respond based on the context."
},
{
"code": null,
"e": 3038,
"s": 3030,
"text": "<topic>"
},
{
"code": null,
"e": 3132,
"s": 3038,
"text": "Used in AIML to store a context so that later conversation can be done based on that context."
},
{
"code": null,
"e": 3140,
"s": 3132,
"text": "<think>"
},
{
"code": null,
"e": 3201,
"s": 3140,
"text": "Used in AIML to store a variable without notifying the user."
},
{
"code": null,
"e": 3213,
"s": 3201,
"text": "<condition>"
},
{
"code": null,
"e": 3312,
"s": 3213,
"text": "Similar to switch statements in programming language. It helps ALICE to respond to matching input."
},
{
"code": null,
"e": 3536,
"s": 3312,
"text": "AIML vocabulary uses words, space and two special characters * and _ as wild cards. AIML interpreter gives preference to pattern having _ than pattern having *. AIML tags are XML compliant and patterns are case-insensitive."
},
{
"code": null,
"e": 3727,
"s": 3536,
"text": "<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n <category>\n <pattern> HELLO ALICE </pattern>\n \n <template>\n Hello User!\n </template>\n \n </category>\n</aiml>"
},
{
"code": null,
"e": 3781,
"s": 3727,
"text": "Following are the important points to be considered −"
},
{
"code": null,
"e": 3830,
"s": 3781,
"text": "<aiml> tag signifies start of the AIML document."
},
{
"code": null,
"e": 3879,
"s": 3830,
"text": "<aiml> tag signifies start of the AIML document."
},
{
"code": null,
"e": 3922,
"s": 3879,
"text": "<category> tag defines the knowledge unit."
},
{
"code": null,
"e": 3965,
"s": 3922,
"text": "<category> tag defines the knowledge unit."
},
{
"code": null,
"e": 4022,
"s": 3965,
"text": "<pattern> tag defines the pattern user is going to type."
},
{
"code": null,
"e": 4079,
"s": 4022,
"text": "<pattern> tag defines the pattern user is going to type."
},
{
"code": null,
"e": 4154,
"s": 4079,
"text": "<template> tag defines the response to the user if user types Hello Alice."
},
{
"code": null,
"e": 4229,
"s": 4154,
"text": "<template> tag defines the response to the user if user types Hello Alice."
},
{
"code": null,
"e": 4264,
"s": 4229,
"text": "User: Hello Alice\nBot: Hello User\n"
},
{
"code": null,
"e": 4271,
"s": 4264,
"text": " Print"
},
{
"code": null,
"e": 4282,
"s": 4271,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.