title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Azure Synapse Analytics & Power BI | by Yousry Mohamed | Towards Data Science | Quoting Microsoft’s Synapse product page
Azure Synapse Analytics is a limitless analytics service that brings together data integration, enterprise data warehousing and big data analytics. It gives you the freedom to query data on your terms, using either serverless or dedicated resources at scale.
I quite agree with the bit related to freedom. Synapse has all the tools you need for different workloads or requirements. If you need a plain data warehouse, then use dedicated or serverless SQL pools. If you want Spark, then Spark pools are available with friendly notebook experience like Databricks (downside is that latest Spark versions are not there yet). Data factory is also integrated with Synapse workspace so there is no need to jump here and there among different tools. Source control is also baked into the same recipe if you want to have more control on code artefacts and CI/CD process.
Still, one cannot evaluate the usefulness of a certain tool or application without taking it first to a test drive.
The problem I wanted to solve is to improve Power BI dataset refresh speed and simplify some M queries used to pull the data needed. The source data is a group of parquet files hosted on Azure Data Lake Gen2. Power BI has provided an M function to parse Parquet data like all the classic connectors used to read CSV, Excel, etc. Unfortunately, the overall experience with such method is less than optimal. Dataset refresh is usually slow for non-trivial data loads because parsing is done using Power BI premium capacity which is not the best tool to load/filter large amounts of data from parquet files. Also, the M query used to pull the data is a bit complicated and more importantly not very easy to read.
Azure Synapse serverless SQL pool can define external tables or views over data lake folders containing CSV or Parquet files. Once those tables or views are defined, we can switch the parquet connector in Power BI with a SQL database connector and try to craft the loading query to use query folding. So , any filters or projections done using M will be translated into plain T-SQL statements that will be executed by Synapse itself not Power BI. If Synapse is smart enough to do partition pruning or predicate pushdown like Spark, then it would be a great win. Dataset refresh will hopefully be faster and cost incurred will be minimal. By the way, pricing for serverless SQL pool depends on the size of data read to serve the query.
Let’s get some Power BI datasets cooked.
A synapse analytics workspace is needed. It comes with a built-in serverless SQL pool and you can choose to connect to an existing data lake or create a new one linked with the workspace. I will use NYC yellow taxi trips dataset. It is a very famous dataset, well documented and used by many Synapse samples already. The dataset is hosted in East US Azure region so for data locality purposes, it is recommended to have Synapse workspace & Power BI service located in the same region. In my case, I copied years 2015/2016/2017 to my Synapse workspace as it is not hosted in same region.
Assuming reporting requirements are:
Year is 2015
Vendor ID is 1
3 years of data including 2015 is loaded into data lake for testing partition pruning with Synapse later but for testing Power BI out of the box data lake plus parquet connection, we can simply point to the folder hosting 2015 only.
Tip: Azure storage explorer can be used to also explore/copy data from public blob containers.
Provide the URL of the public blob container which is https://azureopendatastorage.blob.core.windows.net/nyctlc. Once, connected you can browse the data and even copy some folders to your own data lake folders. You will need to grab the data inside nyctlc/yellow folder.
Alright, let’s first try reading this data using the parquet connector provided by Power BI. M query looks a bit complex due to the need to enumerate files from data lake, parquet parsing and applying the vendor Id filter. Most of the below stuff is created by the wizard to load data from data lake. A certain container folder will be selected first and then all parquet files in this root folder will have their contents expanded using an M function and all contents are concatenated.
To minimise the time needed to populate the file locally and publish to powerbi.com, I used a small trick.
Rename the 2015 folder by appending some characters to the end of it
Create a new 2015 folder with same naming pattern
Copy over one month of data from the real 2015 folder
Apply changes on the local report and then publish it to powerbi.com
Drop the folder with single month of data then restore 2015 renamed folder to have the right name
Next, we will see how much time needed to refresh this dataset on powerbi.com. This refresh was done against 2015 folder data with 12 months included.
Data refresh for NYC trips of 2015 for vendor Id 1 took 43 minutes. This dataset has a single table with ~70M records which is not too much but slow to refresh. Part of that time is to build the underlying tabular database of the dataset, but 43 minutes is somehow too much.
Next, let’s see if using a different approach like using Synapse serverless SQL pool could make a difference.
Synapse workspace comes with a built-in serverless SQL pool. We need to prepare a SQL abstraction layer pointing to trips data on data lake.
First, we need to create a database using UTF8 collation. Without UTF8 collation, there will be lots of warnings when reading from parquet files. See this article for details. Open Synapse Studio then create a new empty SQL script file to run the following snippet.
CREATE DATABASE NycTaxiTrips COLLATE Latin1_General_100_BIN2_UTF8;
Then an external data source is required specially if we need to add some authentication details. In our case, I am using pass-through authentication so no need to add such details.
CREATE EXTERNAL DATA SOURCE NycTripsDataSourceWITH (LOCATION='https://[DATA-LAKE-ACCOUNT].dfs.core.windows.net/')
Create a view pointing to the folder containing the 3 years of NYC taxi trips.
CREATE VIEW Trips ASSELECT *, T.filepath(1) AS year, T.filepath(2) AS monthFROMOPENROWSET(BULK '/root/nyctlc/puYear=*/puMonth=*/*.parquet',DATA_SOURCE = 'NycTripsDataSource',FORMAT='PARQUET')AS T;
If you want to try the above two snippets, then update them to use your own data lake account name and right relative path to trips parquet files.
You can see that we have pulled year and month columns from file paths using synapse filepath function.
To verify the view works as expected, read the first 10 records. If you scroll right, you will see the additional year and month columns sourced from partition structure.
Data lake has data for 3 years. If we want to read data for 2015, Synapse should be able to read year 2015 folder only to pick the required data. Let’s verify if this assumption is valid or not.
Run this query first.
SELECT year, COUNT(*) AS count FROM TripsGROUP BY year
The result should look like this which means the view has access to 3 years of data.
Switch to the messages tab to see query statistics involving the amount of data read to run this query.
Synapse needs to read 53MB to run this query. By the way, Synapse does not have to read whole contents of parquet files to come up with record counts. Parquet is a columnar file format and, in our case or in the case of projection of a few columns, Synapse can just read the column(s) needed to satisfy the query.
Let’s apply a year filter to same query.
Synapse scanned 18MB of data this time which is roughly 1/3 of the 53MB data read for the query scanning all years.
Another similar pattern is that reading smaller number of columns will require less data to be read than reading larger number of columns. This can be handy in case we do not need to load all columns.
Great! This means we can have a view defined over all years and if we want to pull a certain year(s), partition pruning will kick in to read the required data only which makes queries run faster plus your Azure bill will not skyrocket.
Now clone the Power BI report you have and drop the existing Trips table. Then replace it with a connection to a SQL server database and select the Trips view. SQL server connection can be grabbed from Synapse workspace home page as it has serverless SQL pool server name. Use your Azure credentials to authenticate.
On the year column, use the dropdown arrow to apply a basic text filter to pull year 2015 only and similarly on the vendorID column filter for the value of 1. Drop the year and month columns.
Right click the last applied step and click View Native Query which should be enabled meaning query folding is there. You will see the applied filters appearing in the WHERE clause and the SELECT statement has a projection such that year & month columns are not included. If you need a few columns only, projection will make things much faster as well.
M query used to pull the data looks much cleaner and readable.
Query Folding Tip
If you need to filter a certain column using a parameter containing a CSV string of the filter values (something like multiple product Ids), you can go for a combination of Table.SelectRows and List.Contains . Unfortunately, that will directly break query folding. You would need to materialise parameter values as a standalone query producing a list of values and then point List.Contains to that query.
Now moment of the truth. Push this report to powerbi.com using the same trick used before, fill the credentials of Synapse connection and trigger a dataset refresh.
It is about 23 minutes now which is about half the time needed for data lake & parquet connector. Actually, if you have filters such that filtered data is a small subset of full raw data, the gain will be much more obvious.
What about the amount of data used to perform this refresh?
The following query gets size of data processed by serverless SQL pool. The difference between the daily value after data refresh and before data refresh would give a good indicator on the size of data used to do the refresh which can be used to assess cost needed to use Synapse specially if the refresh is periodically scheduled.
SELECT * FROM sys.dm_external_data_processed
Well, decreasing the time needed to refresh the dataset by half is a good progress but more can be done on Synapse as well as Power BI sides. Here is Dax Studio VertiPaq Analyzer Metrics which provides some hints on low hanging fruits for optimising this dataset.
Cardinality of pick up and drop off times is very large (~25M). We can consider using a date column for pick up, two time columns for pick up and drop off and maybe another column for duration in case a trip crosses a day boundary.
All columns with monetary amounts should be switched from decimal to fixed decimal (money).
Redefine Synapse view to select needed columns only from Parquet (in case we don’t need all columns) plus explicitly specify each column data type in the CREATE VIEW statement. This might help with string columns.
For spatial columns (latitude & longitude), we can round them to 4 decimal places for example if it is fine to report location with an error in the range of 11 metres. This would reduce the cardinality and size of final dataset. | [
{
"code": null,
"e": 88,
"s": 47,
"text": "Quoting Microsoft’s Synapse product page"
},
{
"code": null,
"e": 347,
"s": 88,
"text": "Azure Synapse Analytics is a limitless analytics service that brings together data integration, enterprise data warehousing and big data analytics. It gives you the freedom to query data on your terms, using either serverless or dedicated resources at scale."
},
{
"code": null,
"e": 951,
"s": 347,
"text": "I quite agree with the bit related to freedom. Synapse has all the tools you need for different workloads or requirements. If you need a plain data warehouse, then use dedicated or serverless SQL pools. If you want Spark, then Spark pools are available with friendly notebook experience like Databricks (downside is that latest Spark versions are not there yet). Data factory is also integrated with Synapse workspace so there is no need to jump here and there among different tools. Source control is also baked into the same recipe if you want to have more control on code artefacts and CI/CD process."
},
{
"code": null,
"e": 1067,
"s": 951,
"text": "Still, one cannot evaluate the usefulness of a certain tool or application without taking it first to a test drive."
},
{
"code": null,
"e": 1777,
"s": 1067,
"text": "The problem I wanted to solve is to improve Power BI dataset refresh speed and simplify some M queries used to pull the data needed. The source data is a group of parquet files hosted on Azure Data Lake Gen2. Power BI has provided an M function to parse Parquet data like all the classic connectors used to read CSV, Excel, etc. Unfortunately, the overall experience with such method is less than optimal. Dataset refresh is usually slow for non-trivial data loads because parsing is done using Power BI premium capacity which is not the best tool to load/filter large amounts of data from parquet files. Also, the M query used to pull the data is a bit complicated and more importantly not very easy to read."
},
{
"code": null,
"e": 2512,
"s": 1777,
"text": "Azure Synapse serverless SQL pool can define external tables or views over data lake folders containing CSV or Parquet files. Once those tables or views are defined, we can switch the parquet connector in Power BI with a SQL database connector and try to craft the loading query to use query folding. So , any filters or projections done using M will be translated into plain T-SQL statements that will be executed by Synapse itself not Power BI. If Synapse is smart enough to do partition pruning or predicate pushdown like Spark, then it would be a great win. Dataset refresh will hopefully be faster and cost incurred will be minimal. By the way, pricing for serverless SQL pool depends on the size of data read to serve the query."
},
{
"code": null,
"e": 2553,
"s": 2512,
"text": "Let’s get some Power BI datasets cooked."
},
{
"code": null,
"e": 3140,
"s": 2553,
"text": "A synapse analytics workspace is needed. It comes with a built-in serverless SQL pool and you can choose to connect to an existing data lake or create a new one linked with the workspace. I will use NYC yellow taxi trips dataset. It is a very famous dataset, well documented and used by many Synapse samples already. The dataset is hosted in East US Azure region so for data locality purposes, it is recommended to have Synapse workspace & Power BI service located in the same region. In my case, I copied years 2015/2016/2017 to my Synapse workspace as it is not hosted in same region."
},
{
"code": null,
"e": 3177,
"s": 3140,
"text": "Assuming reporting requirements are:"
},
{
"code": null,
"e": 3190,
"s": 3177,
"text": "Year is 2015"
},
{
"code": null,
"e": 3205,
"s": 3190,
"text": "Vendor ID is 1"
},
{
"code": null,
"e": 3438,
"s": 3205,
"text": "3 years of data including 2015 is loaded into data lake for testing partition pruning with Synapse later but for testing Power BI out of the box data lake plus parquet connection, we can simply point to the folder hosting 2015 only."
},
{
"code": null,
"e": 3533,
"s": 3438,
"text": "Tip: Azure storage explorer can be used to also explore/copy data from public blob containers."
},
{
"code": null,
"e": 3804,
"s": 3533,
"text": "Provide the URL of the public blob container which is https://azureopendatastorage.blob.core.windows.net/nyctlc. Once, connected you can browse the data and even copy some folders to your own data lake folders. You will need to grab the data inside nyctlc/yellow folder."
},
{
"code": null,
"e": 4291,
"s": 3804,
"text": "Alright, let’s first try reading this data using the parquet connector provided by Power BI. M query looks a bit complex due to the need to enumerate files from data lake, parquet parsing and applying the vendor Id filter. Most of the below stuff is created by the wizard to load data from data lake. A certain container folder will be selected first and then all parquet files in this root folder will have their contents expanded using an M function and all contents are concatenated."
},
{
"code": null,
"e": 4398,
"s": 4291,
"text": "To minimise the time needed to populate the file locally and publish to powerbi.com, I used a small trick."
},
{
"code": null,
"e": 4467,
"s": 4398,
"text": "Rename the 2015 folder by appending some characters to the end of it"
},
{
"code": null,
"e": 4517,
"s": 4467,
"text": "Create a new 2015 folder with same naming pattern"
},
{
"code": null,
"e": 4571,
"s": 4517,
"text": "Copy over one month of data from the real 2015 folder"
},
{
"code": null,
"e": 4640,
"s": 4571,
"text": "Apply changes on the local report and then publish it to powerbi.com"
},
{
"code": null,
"e": 4738,
"s": 4640,
"text": "Drop the folder with single month of data then restore 2015 renamed folder to have the right name"
},
{
"code": null,
"e": 4889,
"s": 4738,
"text": "Next, we will see how much time needed to refresh this dataset on powerbi.com. This refresh was done against 2015 folder data with 12 months included."
},
{
"code": null,
"e": 5164,
"s": 4889,
"text": "Data refresh for NYC trips of 2015 for vendor Id 1 took 43 minutes. This dataset has a single table with ~70M records which is not too much but slow to refresh. Part of that time is to build the underlying tabular database of the dataset, but 43 minutes is somehow too much."
},
{
"code": null,
"e": 5274,
"s": 5164,
"text": "Next, let’s see if using a different approach like using Synapse serverless SQL pool could make a difference."
},
{
"code": null,
"e": 5415,
"s": 5274,
"text": "Synapse workspace comes with a built-in serverless SQL pool. We need to prepare a SQL abstraction layer pointing to trips data on data lake."
},
{
"code": null,
"e": 5681,
"s": 5415,
"text": "First, we need to create a database using UTF8 collation. Without UTF8 collation, there will be lots of warnings when reading from parquet files. See this article for details. Open Synapse Studio then create a new empty SQL script file to run the following snippet."
},
{
"code": null,
"e": 5748,
"s": 5681,
"text": "CREATE DATABASE NycTaxiTrips COLLATE Latin1_General_100_BIN2_UTF8;"
},
{
"code": null,
"e": 5930,
"s": 5748,
"text": "Then an external data source is required specially if we need to add some authentication details. In our case, I am using pass-through authentication so no need to add such details."
},
{
"code": null,
"e": 6044,
"s": 5930,
"text": "CREATE EXTERNAL DATA SOURCE NycTripsDataSourceWITH (LOCATION='https://[DATA-LAKE-ACCOUNT].dfs.core.windows.net/')"
},
{
"code": null,
"e": 6123,
"s": 6044,
"text": "Create a view pointing to the folder containing the 3 years of NYC taxi trips."
},
{
"code": null,
"e": 6320,
"s": 6123,
"text": "CREATE VIEW Trips ASSELECT *, T.filepath(1) AS year, T.filepath(2) AS monthFROMOPENROWSET(BULK '/root/nyctlc/puYear=*/puMonth=*/*.parquet',DATA_SOURCE = 'NycTripsDataSource',FORMAT='PARQUET')AS T;"
},
{
"code": null,
"e": 6467,
"s": 6320,
"text": "If you want to try the above two snippets, then update them to use your own data lake account name and right relative path to trips parquet files."
},
{
"code": null,
"e": 6571,
"s": 6467,
"text": "You can see that we have pulled year and month columns from file paths using synapse filepath function."
},
{
"code": null,
"e": 6742,
"s": 6571,
"text": "To verify the view works as expected, read the first 10 records. If you scroll right, you will see the additional year and month columns sourced from partition structure."
},
{
"code": null,
"e": 6937,
"s": 6742,
"text": "Data lake has data for 3 years. If we want to read data for 2015, Synapse should be able to read year 2015 folder only to pick the required data. Let’s verify if this assumption is valid or not."
},
{
"code": null,
"e": 6959,
"s": 6937,
"text": "Run this query first."
},
{
"code": null,
"e": 7014,
"s": 6959,
"text": "SELECT year, COUNT(*) AS count FROM TripsGROUP BY year"
},
{
"code": null,
"e": 7099,
"s": 7014,
"text": "The result should look like this which means the view has access to 3 years of data."
},
{
"code": null,
"e": 7203,
"s": 7099,
"text": "Switch to the messages tab to see query statistics involving the amount of data read to run this query."
},
{
"code": null,
"e": 7517,
"s": 7203,
"text": "Synapse needs to read 53MB to run this query. By the way, Synapse does not have to read whole contents of parquet files to come up with record counts. Parquet is a columnar file format and, in our case or in the case of projection of a few columns, Synapse can just read the column(s) needed to satisfy the query."
},
{
"code": null,
"e": 7558,
"s": 7517,
"text": "Let’s apply a year filter to same query."
},
{
"code": null,
"e": 7674,
"s": 7558,
"text": "Synapse scanned 18MB of data this time which is roughly 1/3 of the 53MB data read for the query scanning all years."
},
{
"code": null,
"e": 7875,
"s": 7674,
"text": "Another similar pattern is that reading smaller number of columns will require less data to be read than reading larger number of columns. This can be handy in case we do not need to load all columns."
},
{
"code": null,
"e": 8111,
"s": 7875,
"text": "Great! This means we can have a view defined over all years and if we want to pull a certain year(s), partition pruning will kick in to read the required data only which makes queries run faster plus your Azure bill will not skyrocket."
},
{
"code": null,
"e": 8428,
"s": 8111,
"text": "Now clone the Power BI report you have and drop the existing Trips table. Then replace it with a connection to a SQL server database and select the Trips view. SQL server connection can be grabbed from Synapse workspace home page as it has serverless SQL pool server name. Use your Azure credentials to authenticate."
},
{
"code": null,
"e": 8620,
"s": 8428,
"text": "On the year column, use the dropdown arrow to apply a basic text filter to pull year 2015 only and similarly on the vendorID column filter for the value of 1. Drop the year and month columns."
},
{
"code": null,
"e": 8973,
"s": 8620,
"text": "Right click the last applied step and click View Native Query which should be enabled meaning query folding is there. You will see the applied filters appearing in the WHERE clause and the SELECT statement has a projection such that year & month columns are not included. If you need a few columns only, projection will make things much faster as well."
},
{
"code": null,
"e": 9036,
"s": 8973,
"text": "M query used to pull the data looks much cleaner and readable."
},
{
"code": null,
"e": 9054,
"s": 9036,
"text": "Query Folding Tip"
},
{
"code": null,
"e": 9459,
"s": 9054,
"text": "If you need to filter a certain column using a parameter containing a CSV string of the filter values (something like multiple product Ids), you can go for a combination of Table.SelectRows and List.Contains . Unfortunately, that will directly break query folding. You would need to materialise parameter values as a standalone query producing a list of values and then point List.Contains to that query."
},
{
"code": null,
"e": 9624,
"s": 9459,
"text": "Now moment of the truth. Push this report to powerbi.com using the same trick used before, fill the credentials of Synapse connection and trigger a dataset refresh."
},
{
"code": null,
"e": 9848,
"s": 9624,
"text": "It is about 23 minutes now which is about half the time needed for data lake & parquet connector. Actually, if you have filters such that filtered data is a small subset of full raw data, the gain will be much more obvious."
},
{
"code": null,
"e": 9908,
"s": 9848,
"text": "What about the amount of data used to perform this refresh?"
},
{
"code": null,
"e": 10240,
"s": 9908,
"text": "The following query gets size of data processed by serverless SQL pool. The difference between the daily value after data refresh and before data refresh would give a good indicator on the size of data used to do the refresh which can be used to assess cost needed to use Synapse specially if the refresh is periodically scheduled."
},
{
"code": null,
"e": 10285,
"s": 10240,
"text": "SELECT * FROM sys.dm_external_data_processed"
},
{
"code": null,
"e": 10549,
"s": 10285,
"text": "Well, decreasing the time needed to refresh the dataset by half is a good progress but more can be done on Synapse as well as Power BI sides. Here is Dax Studio VertiPaq Analyzer Metrics which provides some hints on low hanging fruits for optimising this dataset."
},
{
"code": null,
"e": 10781,
"s": 10549,
"text": "Cardinality of pick up and drop off times is very large (~25M). We can consider using a date column for pick up, two time columns for pick up and drop off and maybe another column for duration in case a trip crosses a day boundary."
},
{
"code": null,
"e": 10873,
"s": 10781,
"text": "All columns with monetary amounts should be switched from decimal to fixed decimal (money)."
},
{
"code": null,
"e": 11087,
"s": 10873,
"text": "Redefine Synapse view to select needed columns only from Parquet (in case we don’t need all columns) plus explicitly specify each column data type in the CREATE VIEW statement. This might help with string columns."
}
]
|
Math.Min() Method in C# | The Math.Min() method in C# is used to return the larger of two specified numbers. This method works for both the numbers being Double, Decimal, Int16, Int32, etc.
Following is the syntax −
public static ulong Min (ulong val1, ulong val2);
public static uint Min (uint val1, uint val2);
public static ushort Min (ushort val1, ushort val2);
public static float Min (float val1, float val2);
public static byte Min (byte val1, byte val2);
public static long Min (long val1, long val2);
Let us now see an example to implement Math.Min() method −
using System;
public class Demo {
public static void Main(){
byte val1 = 10, val2 = 15;
decimal val3 = 1000M, val4 = 1500M;
double val5 = 15.896745, val6 = 25.676843;
short val7 = 20, val8 = 30;
Console.WriteLine("Minimum Value from two byte values = "+Math.Min(val1, val2));
Console.WriteLine("Minimum Value from two decimal values = "+Math.Min(val3, val4));
Console.WriteLine("Minimum Value from two double values = "+Math.Min(val5, val6));
Console.WriteLine("Minimum Value from two short values = "+Math.Min(val7, val8));
}
}
This will produce the following output −
Minimum Value from two byte values = 10
Minimum Value from two decimal values = 1000
Minimum Value from two double values = 15.896745
Minimum Value from two short values = 20
Let us see another example to implement Math.Min() method −
using System;
public class Demo {
public static void Main(){
int val1 = 10, val2 = 15;
float val3 = 12.8f, val4 = 25.6f;
Console.WriteLine("Minimum Value from two int values = "+Math.Min(val1, val2));
Console.WriteLine("Minimum Value from two float values = "+Math.Min(val3, val4));
}
}
This will produce the following output &minuns;
Minimum Value from two int values = 10
Minimum Value from two float values = 12.8 | [
{
"code": null,
"e": 1226,
"s": 1062,
"text": "The Math.Min() method in C# is used to return the larger of two specified numbers. This method works for both the numbers being Double, Decimal, Int16, Int32, etc."
},
{
"code": null,
"e": 1252,
"s": 1226,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1546,
"s": 1252,
"text": "public static ulong Min (ulong val1, ulong val2);\npublic static uint Min (uint val1, uint val2);\npublic static ushort Min (ushort val1, ushort val2);\npublic static float Min (float val1, float val2);\npublic static byte Min (byte val1, byte val2);\npublic static long Min (long val1, long val2);"
},
{
"code": null,
"e": 1605,
"s": 1546,
"text": "Let us now see an example to implement Math.Min() method −"
},
{
"code": null,
"e": 2188,
"s": 1605,
"text": "using System;\npublic class Demo {\n public static void Main(){\n byte val1 = 10, val2 = 15;\n decimal val3 = 1000M, val4 = 1500M;\n double val5 = 15.896745, val6 = 25.676843;\n short val7 = 20, val8 = 30;\n Console.WriteLine(\"Minimum Value from two byte values = \"+Math.Min(val1, val2));\n Console.WriteLine(\"Minimum Value from two decimal values = \"+Math.Min(val3, val4));\n Console.WriteLine(\"Minimum Value from two double values = \"+Math.Min(val5, val6));\n Console.WriteLine(\"Minimum Value from two short values = \"+Math.Min(val7, val8));\n }\n}"
},
{
"code": null,
"e": 2229,
"s": 2188,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2404,
"s": 2229,
"text": "Minimum Value from two byte values = 10\nMinimum Value from two decimal values = 1000\nMinimum Value from two double values = 15.896745\nMinimum Value from two short values = 20"
},
{
"code": null,
"e": 2464,
"s": 2404,
"text": "Let us see another example to implement Math.Min() method −"
},
{
"code": null,
"e": 2781,
"s": 2464,
"text": "using System;\npublic class Demo {\n public static void Main(){\n int val1 = 10, val2 = 15;\n float val3 = 12.8f, val4 = 25.6f;\n Console.WriteLine(\"Minimum Value from two int values = \"+Math.Min(val1, val2));\n Console.WriteLine(\"Minimum Value from two float values = \"+Math.Min(val3, val4));\n }\n}"
},
{
"code": null,
"e": 2829,
"s": 2781,
"text": "This will produce the following output &minuns;"
},
{
"code": null,
"e": 2911,
"s": 2829,
"text": "Minimum Value from two int values = 10\nMinimum Value from two float values = 12.8"
}
]
|
Print all possible ways to convert one string into another string | Edit-Distance - GeeksforGeeks | 23 Apr, 2021
Prerequisite: Dynamic Programming | Set 5 (Edit Distance) Given two strings str1 and str2, the task is to print the all possible ways to convert ‘str1’ into ‘str2’. Below are the operations that can be performed on “str1”:
InsertRemoveReplace
Insert
Remove
Replace
All of the above operations are of equal cost. The task is to print all the various ways to convert ‘str1’ into ‘str2’ using the minimum number of edits (operations) required, where a “way” comprises of the series of all such operations required. Examples:
Input: str1 = “abcdef”, str2 = “axcdfdh” Output: Method 1: Add h Change f to d Change e to f Change b to xMethod 2: Change f to h Add d Change e to f Change b to xMethod 3: Change f to h Change e to d Add f Change b to x
Approach for printing one possible way:
The approach for finding the minimum number of edits has been discussed in this post. To print one possible way, iterate from the bottom right corner of the DP matrix formed using Min-Edit Distance method. Check if the character pertaining to that element in both strings is equal or not. If it is, it means it needs no edit, and DP[i][j] was copied from DP[i-1][j-1].
If str1[i-1] == str2[j-1], proceed diagonally.
Note that since the DP matrix contains one extra row and column at 0 indices, String indexes will be decreased by one. i.e. DP[i][j] corresponds to i-1 index of str1 and j-1 index of str2.Now, if the characters were not equal, that means this matrix element DP[i][j] was obtained from the minimum of DP[i-1][j-1], DP[i][j-1] and DP[i-1][j], plus 1. Hence, check from where this element was from.
1. If DP[i][j] == DP[i-1][j-1] + 1
It means the character was replaced from str1[i] to str2[j]. Proceed diagonally.
2. If DP[i][j] == DP[i][j-1] + 1
It means the character was Added from str2[j]. Proceed left.
3. If DP[i][j] == DP[i-1][j] + 1
It means the character str1[i] was deleted. Proceed up.
Once the end i.e., (i==0 or j==0 ) of either string is reached, converting of one string to other is done. We will have printed all the set of operations required. Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program to print one possible// way of converting a string to another#include <bits/stdc++.h>using namespace std; int DP[100][100]; // Function to print the stepsvoid printChanges(string s1, string s2, int dp[][100]){ int i = s1.length(); int j = s2.length(); // check till the end while (i and j) { // if characters are same if (s1[i - 1] == s2[j - 1]) { i--; j--; } // Replace else if (dp[i][j] == dp[i - 1][j - 1] + 1) { cout << "change " << s1[i - 1] << " to " << s2[j - 1] << endl; i--; j--; } // Delete the character else if (dp[i][j] == dp[i - 1][j] + 1) { cout << "Delete " << s1[i - 1] << endl; i--; } // Add the character else if (dp[i][j] == dp[i][j - 1] + 1) { cout << "Add " << s2[j - 1] << endl; j--; } }} // Function to compute the DP matrixvoid editDP(string s1, string s2){ int l1 = s1.length(); int l2 = s2.length(); DP[l1 + 1][l2 + 1]; // initialize by the maximum edits possible for (int i = 0; i <= l1; i++) DP[i][0] = i; for (int j = 0; j <= l2; j++) DP[0][j] = j; // Compute the DP matrix for (int i = 1; i <= l1; i++) { for (int j = 1; j <= l2; j++) { // if the characters are same // no changes required if (s1[i - 1] == s2[j - 1]) DP[i][j] = DP[i - 1][j - 1]; else // minimum of three operations possible DP[i][j] = min(min(DP[i - 1][j - 1], DP[i - 1][j]), DP[i][j - 1]) + 1; } } // print the steps printChanges(s1, s2, DP);}// Driver Codeint main(){ string s1 = "abcdef"; string s2 = "axcdfdh"; // calculate the DP matrix editDP(s1, s2); return 0;} // This code is contributed by// sanjeev2552
// Java program to print one possible// way of converting a string to anotherimport java.util.*; public class Edit_Distance { static int dp[][]; // Function to print the steps static void printChanges(String s1, String s2) { int i = s1.length(); int j = s2.length(); // check till the end while (i != 0 && j != 0) { // if characters are same if (s1.charAt(i - 1) == s2.charAt(j - 1)) { i--; j--; } // Replace else if (dp[i][j] == dp[i - 1][j - 1] + 1) { System.out.println("change " + s1.charAt(i - 1) + " to " + s2.charAt(j - 1)); i--; j--; } // Delete the character else if (dp[i][j] == dp[i - 1][j] + 1) { System.out.println("Delete " + s1.charAt(i - 1)); i--; } // Add the character else if (dp[i][j] == dp[i][j - 1] + 1) { System.out.println("Add " + s2.charAt(j - 1)); j--; } } } // Function to compute the DP matrix static void editDP(String s1, String s2) { int l1 = s1.length(); int l2 = s2.length(); int[][] DP = new int[l1 + 1][l2 + 1]; // initialize by the maximum edits possible for (int i = 0; i <= l1; i++) DP[i][0] = i; for (int j = 0; j <= l2; j++) DP[0][j] = j; // Compute the DP matrix for (int i = 1; i <= l1; i++) { for (int j = 1; j <= l2; j++) { // if the characters are same // no changes required if (s1.charAt(i - 1) == s2.charAt(j - 1)) DP[i][j] = DP[i - 1][j - 1]; else { // minimum of three operations possible DP[i][j] = min(DP[i - 1][j - 1], DP[i - 1][j], DP[i][j - 1]) + 1; } } } // initialize to global array dp = DP; } // Function to find the minimum of three static int min(int a, int b, int c) { int z = Math.min(a, b); return Math.min(z, c); } // Driver Code public static void main(String[] args) throws Exception { String s1 = "abcdef"; String s2 = "axcdfdh"; // calculate the DP matrix editDP(s1, s2); // print the steps printChanges(s1, s2); }}
# Python3 program to print one possible# way of converting a string to another # Function to print the stepsdef printChanges(s1, s2, dp): i = len(s1) j = len(s2) # Check till the end while(i > 0 and j > 0): # If characters are same if s1[i - 1] == s2[j - 1]: i -= 1 j -= 1 # Replace elif dp[i][j] == dp[i - 1][j - 1] + 1: print("change", s1[i - 1], "to", s2[j - 1]) j -= 1 i -= 1 # Delete elif dp[i][j] == dp[i - 1][j] + 1: print("Delete", s1[i - 1]) i -= 1 # Add elif dp[i][j] == dp[i][j - 1] + 1: print("Add", s2[j - 1]) j -= 1 # Function to compute the DP matrixdef editDP(s1, s2): len1 = len(s1) len2 = len(s2) dp = [[0 for i in range(len2 + 1)] for j in range(len1 + 1)] # Initialize by the maximum edits possible for i in range(len1 + 1): dp[i][0] = i for j in range(len2 + 1): dp[0][j] = j # Compute the DP Matrix for i in range(1, len1 + 1): for j in range(1, len2 + 1): # If the characters are same # no changes required if s2[j - 1] == s1[i - 1]: dp[i][j] = dp[i - 1][j - 1] # Minimum of three operations possible else: dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j - 1], dp[i - 1][j]) # Print the steps printChanges(s1, s2, dp) # Driver Codes1 = "abcdef"s2 = "axcdfdh" # Compute the DP MatrixeditDP(s1, s2) # This code is contributed by Pranav S
// C# program to print one possible// way of converting a string to anotherusing System; public class Edit_Distance{ static int [,]dp; // Function to print the steps static void printChanges(String s1, String s2) { int i = s1.Length; int j = s2.Length; // check till the end while (i != 0 && j != 0) { // if characters are same if (s1[i - 1] == s2[j - 1]) { i--; j--; } // Replace else if (dp[i, j] == dp[i - 1, j - 1] + 1) { Console.WriteLine("change " + s1[i - 1] + " to " + s2[j - 1]); i--; j--; } // Delete the character else if (dp[i, j] == dp[i - 1, j] + 1) { Console.WriteLine("Delete " + s1[i - 1]); i--; } // Add the character else if (dp[i, j] == dp[i, j - 1] + 1) { Console.WriteLine("Add " + s2[j - 1]); j--; } } } // Function to compute the DP matrix static void editDP(String s1, String s2) { int l1 = s1.Length; int l2 = s2.Length; int[,] DP = new int[l1 + 1, l2 + 1]; // initialize by the maximum edits possible for (int i = 0; i <= l1; i++) DP[i, 0] = i; for (int j = 0; j <= l2; j++) DP[0, j] = j; // Compute the DP matrix for (int i = 1; i <= l1; i++) { for (int j = 1; j <= l2; j++) { // if the characters are same // no changes required if (s1[i - 1] == s2[j - 1]) DP[i, j] = DP[i - 1, j - 1]; else { // minimu of three operations possible DP[i, j] = min(DP[i - 1, j - 1], DP[i - 1, j], DP[i, j - 1]) + 1; } } } // initialize to global array dp = DP; } // Function to find the minimum of three static int min(int a, int b, int c) { int z = Math.Min(a, b); return Math.Min(z, c); } // Driver Code public static void Main(String[] args) { String s1 = "abcdef"; String s2 = "axcdfdh"; // calculate the DP matrix editDP(s1, s2); // print the steps printChanges(s1, s2); }} // This code is contributed by PrinciRaj1992
change f to h
change e to d
Add f
change b to x
Approach to print all possible ways:
Create a collection of strings that will store the operations required. This collection can be a vector of strings in C++ or a List of strings in Java. Add operations just like printing them before to this collection. Then create a collection of these collections which will store the multiple methods (sets of string operations). Else-if was used earlier to check from where we derived the DP[i][j] from. Now, check all If’s to see if there were more than 1 ways you could obtain the element. If there was, we create a new collection from before, remove the last operation, add this new operation and initiate another instance of this function with this new list. In this manner, add new lists whenever there was a new method to change str1 to str2, getting a new method every time.On reaching the end of either string, add this list to the collection of lists, thus completing the set of all possible operations, and add them. Below is the implementation of the above approach:
Java
// Java program to print all the possible// steps to change a string to anotherimport java.util.ArrayList; public class Edit_Distance { static int dp[][]; // create List of lists that will store all sets of operations static ArrayList<ArrayList<String> > arrs = new ArrayList<ArrayList<String> >(); // Function to print all ways static void printAllChanges(String s1, String s2, ArrayList<String> changes) { int i = s1.length(); int j = s2.length(); // Iterate till end while (true) { if (i == 0 || j == 0) { // Add this list to our List of lists. arrs.add(changes); break; } // If same if (s1.charAt(i - 1) == s2.charAt(j - 1)) { i--; j--; } else { boolean if1 = false, if2 = false; // Replace if (dp[i][j] == dp[i - 1][j - 1] + 1) { // Add this step changes.add("Change " + s1.charAt(i - 1) + " to " + s2.charAt(j - 1)); i--; j--; // note whether this 'if' was true. if1 = true; } // Delete if (dp[i][j] == dp[i - 1][j] + 1) { if (if1 == false) { changes.add("Delete " + s1.charAt(i - 1)); i--; } else { // If the previous method was true, // create a new list as a copy of previous. ArrayList<String> changes2 = new ArrayList<String>(); changes2.addAll(changes); // Remove last operation changes2.remove(changes.size() - 1); // Add this new operation changes2.add("Delete " + s1.charAt(i)); // initiate new new instance of this // function with remaining substrings printAllChanges(s1.substring(0, i), s2.substring(0, j + 1), changes2); } if2 = true; } // Add character step if (dp[i][j] == dp[i][j - 1] + 1) { if (if1 == false && if2 == false) { changes.add("Add " + s2.charAt(j - 1)); j--; } else { // Add steps ArrayList<String> changes2 = new ArrayList<String>(); changes2.addAll(changes); changes2.remove(changes.size() - 1); changes2.add("Add " + s2.charAt(j)); // Recursively call for the next steps printAllChanges(s1.substring(0, i + 1), s2.substring(0, j), changes2); } } } } } // Function to compute the DP matrix static void editDP(String s1, String s2) { int l1 = s1.length(); int l2 = s2.length(); int[][] DP = new int[l1 + 1][l2 + 1]; // initialize by the maximum edits possible for (int i = 0; i <= l1; i++) DP[i][0] = i; for (int j = 0; j <= l2; j++) DP[0][j] = j; // Compute the DP matrix for (int i = 1; i <= l1; i++) { for (int j = 1; j <= l2; j++) { // if the characters are same // no changes required if (s1.charAt(i - 1) == s2.charAt(j - 1)) DP[i][j] = DP[i - 1][j - 1]; else { // minimum of three operations possible DP[i][j] = min(DP[i - 1][j - 1], DP[i - 1][j], DP[i][j - 1]) + 1; } } } // initialize to global array dp = DP; } // Function to find the minimum of three static int min(int a, int b, int c) { int z = Math.min(a, b); return Math.min(z, c); } static void printWays(String s1, String s2, ArrayList<String> changes) { // Function to print all the ways printAllChanges(s1, s2, new ArrayList<String>()); int i = 1; // print all the possible ways for (ArrayList<String> ar : arrs) { System.out.println("\nMethod " + i++ + " : \n"); for (String s : ar) { System.out.println(s); } } } // Driver Code public static void main(String[] args) throws Exception { String s1 = "abcdef"; String s2 = "axcdfdh"; // calculate the DP matrix editDP(s1, s2); // Function to print all ways printWays(s1, s2, new ArrayList<String>()); }}
Method 1 :
Add h
Change f to d
Change e to f
Change b to x
Method 2 :
Change f to h
Add d
Change e to f
Change b to x
Method 3 :
Change f to h
Change e to d
Add f
Change b to x
sanjeev2552
princiraj1992
pranav1503
sweetyty
arorakashish0911
Algorithms-Recursion
Java-ArrayList
Java-Strings
Dynamic Programming
Java-Strings
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Matrix Chain Multiplication | DP-8
Longest Palindromic Substring | Set 1
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Sieve of Eratosthenes
Overlapping Subproblems Property in Dynamic Programming | DP-1
Cutting a Rod | DP-13
Longest Common Substring | DP-29 | [
{
"code": null,
"e": 24431,
"s": 24403,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 24656,
"s": 24431,
"text": "Prerequisite: Dynamic Programming | Set 5 (Edit Distance) Given two strings str1 and str2, the task is to print the all possible ways to convert ‘str1’ into ‘str2’. Below are the operations that can be performed on “str1”: "
},
{
"code": null,
"e": 24676,
"s": 24656,
"text": "InsertRemoveReplace"
},
{
"code": null,
"e": 24683,
"s": 24676,
"text": "Insert"
},
{
"code": null,
"e": 24690,
"s": 24683,
"text": "Remove"
},
{
"code": null,
"e": 24698,
"s": 24690,
"text": "Replace"
},
{
"code": null,
"e": 24957,
"s": 24698,
"text": "All of the above operations are of equal cost. The task is to print all the various ways to convert ‘str1’ into ‘str2’ using the minimum number of edits (operations) required, where a “way” comprises of the series of all such operations required. Examples: "
},
{
"code": null,
"e": 25180,
"s": 24957,
"text": "Input: str1 = “abcdef”, str2 = “axcdfdh” Output: Method 1: Add h Change f to d Change e to f Change b to xMethod 2: Change f to h Add d Change e to f Change b to xMethod 3: Change f to h Change e to d Add f Change b to x "
},
{
"code": null,
"e": 25222,
"s": 25182,
"text": "Approach for printing one possible way:"
},
{
"code": null,
"e": 25593,
"s": 25222,
"text": "The approach for finding the minimum number of edits has been discussed in this post. To print one possible way, iterate from the bottom right corner of the DP matrix formed using Min-Edit Distance method. Check if the character pertaining to that element in both strings is equal or not. If it is, it means it needs no edit, and DP[i][j] was copied from DP[i-1][j-1]. "
},
{
"code": null,
"e": 25641,
"s": 25593,
"text": "If str1[i-1] == str2[j-1], proceed diagonally. "
},
{
"code": null,
"e": 26039,
"s": 25641,
"text": "Note that since the DP matrix contains one extra row and column at 0 indices, String indexes will be decreased by one. i.e. DP[i][j] corresponds to i-1 index of str1 and j-1 index of str2.Now, if the characters were not equal, that means this matrix element DP[i][j] was obtained from the minimum of DP[i-1][j-1], DP[i][j-1] and DP[i-1][j], plus 1. Hence, check from where this element was from. "
},
{
"code": null,
"e": 26363,
"s": 26039,
"text": "1. If DP[i][j] == DP[i-1][j-1] + 1 \n It means the character was replaced from str1[i] to str2[j]. Proceed diagonally.\n2. If DP[i][j] == DP[i][j-1] + 1\n It means the character was Added from str2[j]. Proceed left.\n3. If DP[i][j] == DP[i-1][j] + 1\n It means the character str1[i] was deleted. Proceed up."
},
{
"code": null,
"e": 26580,
"s": 26363,
"text": "Once the end i.e., (i==0 or j==0 ) of either string is reached, converting of one string to other is done. We will have printed all the set of operations required. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26584,
"s": 26580,
"text": "C++"
},
{
"code": null,
"e": 26589,
"s": 26584,
"text": "Java"
},
{
"code": null,
"e": 26597,
"s": 26589,
"text": "Python3"
},
{
"code": null,
"e": 26600,
"s": 26597,
"text": "C#"
},
{
"code": "// C++ program to print one possible// way of converting a string to another#include <bits/stdc++.h>using namespace std; int DP[100][100]; // Function to print the stepsvoid printChanges(string s1, string s2, int dp[][100]){ int i = s1.length(); int j = s2.length(); // check till the end while (i and j) { // if characters are same if (s1[i - 1] == s2[j - 1]) { i--; j--; } // Replace else if (dp[i][j] == dp[i - 1][j - 1] + 1) { cout << \"change \" << s1[i - 1] << \" to \" << s2[j - 1] << endl; i--; j--; } // Delete the character else if (dp[i][j] == dp[i - 1][j] + 1) { cout << \"Delete \" << s1[i - 1] << endl; i--; } // Add the character else if (dp[i][j] == dp[i][j - 1] + 1) { cout << \"Add \" << s2[j - 1] << endl; j--; } }} // Function to compute the DP matrixvoid editDP(string s1, string s2){ int l1 = s1.length(); int l2 = s2.length(); DP[l1 + 1][l2 + 1]; // initialize by the maximum edits possible for (int i = 0; i <= l1; i++) DP[i][0] = i; for (int j = 0; j <= l2; j++) DP[0][j] = j; // Compute the DP matrix for (int i = 1; i <= l1; i++) { for (int j = 1; j <= l2; j++) { // if the characters are same // no changes required if (s1[i - 1] == s2[j - 1]) DP[i][j] = DP[i - 1][j - 1]; else // minimum of three operations possible DP[i][j] = min(min(DP[i - 1][j - 1], DP[i - 1][j]), DP[i][j - 1]) + 1; } } // print the steps printChanges(s1, s2, DP);}// Driver Codeint main(){ string s1 = \"abcdef\"; string s2 = \"axcdfdh\"; // calculate the DP matrix editDP(s1, s2); return 0;} // This code is contributed by// sanjeev2552",
"e": 28649,
"s": 26600,
"text": null
},
{
"code": "// Java program to print one possible// way of converting a string to anotherimport java.util.*; public class Edit_Distance { static int dp[][]; // Function to print the steps static void printChanges(String s1, String s2) { int i = s1.length(); int j = s2.length(); // check till the end while (i != 0 && j != 0) { // if characters are same if (s1.charAt(i - 1) == s2.charAt(j - 1)) { i--; j--; } // Replace else if (dp[i][j] == dp[i - 1][j - 1] + 1) { System.out.println(\"change \" + s1.charAt(i - 1) + \" to \" + s2.charAt(j - 1)); i--; j--; } // Delete the character else if (dp[i][j] == dp[i - 1][j] + 1) { System.out.println(\"Delete \" + s1.charAt(i - 1)); i--; } // Add the character else if (dp[i][j] == dp[i][j - 1] + 1) { System.out.println(\"Add \" + s2.charAt(j - 1)); j--; } } } // Function to compute the DP matrix static void editDP(String s1, String s2) { int l1 = s1.length(); int l2 = s2.length(); int[][] DP = new int[l1 + 1][l2 + 1]; // initialize by the maximum edits possible for (int i = 0; i <= l1; i++) DP[i][0] = i; for (int j = 0; j <= l2; j++) DP[0][j] = j; // Compute the DP matrix for (int i = 1; i <= l1; i++) { for (int j = 1; j <= l2; j++) { // if the characters are same // no changes required if (s1.charAt(i - 1) == s2.charAt(j - 1)) DP[i][j] = DP[i - 1][j - 1]; else { // minimum of three operations possible DP[i][j] = min(DP[i - 1][j - 1], DP[i - 1][j], DP[i][j - 1]) + 1; } } } // initialize to global array dp = DP; } // Function to find the minimum of three static int min(int a, int b, int c) { int z = Math.min(a, b); return Math.min(z, c); } // Driver Code public static void main(String[] args) throws Exception { String s1 = \"abcdef\"; String s2 = \"axcdfdh\"; // calculate the DP matrix editDP(s1, s2); // print the steps printChanges(s1, s2); }}",
"e": 31177,
"s": 28649,
"text": null
},
{
"code": "# Python3 program to print one possible# way of converting a string to another # Function to print the stepsdef printChanges(s1, s2, dp): i = len(s1) j = len(s2) # Check till the end while(i > 0 and j > 0): # If characters are same if s1[i - 1] == s2[j - 1]: i -= 1 j -= 1 # Replace elif dp[i][j] == dp[i - 1][j - 1] + 1: print(\"change\", s1[i - 1], \"to\", s2[j - 1]) j -= 1 i -= 1 # Delete elif dp[i][j] == dp[i - 1][j] + 1: print(\"Delete\", s1[i - 1]) i -= 1 # Add elif dp[i][j] == dp[i][j - 1] + 1: print(\"Add\", s2[j - 1]) j -= 1 # Function to compute the DP matrixdef editDP(s1, s2): len1 = len(s1) len2 = len(s2) dp = [[0 for i in range(len2 + 1)] for j in range(len1 + 1)] # Initialize by the maximum edits possible for i in range(len1 + 1): dp[i][0] = i for j in range(len2 + 1): dp[0][j] = j # Compute the DP Matrix for i in range(1, len1 + 1): for j in range(1, len2 + 1): # If the characters are same # no changes required if s2[j - 1] == s1[i - 1]: dp[i][j] = dp[i - 1][j - 1] # Minimum of three operations possible else: dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j - 1], dp[i - 1][j]) # Print the steps printChanges(s1, s2, dp) # Driver Codes1 = \"abcdef\"s2 = \"axcdfdh\" # Compute the DP MatrixeditDP(s1, s2) # This code is contributed by Pranav S",
"e": 32987,
"s": 31177,
"text": null
},
{
"code": "// C# program to print one possible// way of converting a string to anotherusing System; public class Edit_Distance{ static int [,]dp; // Function to print the steps static void printChanges(String s1, String s2) { int i = s1.Length; int j = s2.Length; // check till the end while (i != 0 && j != 0) { // if characters are same if (s1[i - 1] == s2[j - 1]) { i--; j--; } // Replace else if (dp[i, j] == dp[i - 1, j - 1] + 1) { Console.WriteLine(\"change \" + s1[i - 1] + \" to \" + s2[j - 1]); i--; j--; } // Delete the character else if (dp[i, j] == dp[i - 1, j] + 1) { Console.WriteLine(\"Delete \" + s1[i - 1]); i--; } // Add the character else if (dp[i, j] == dp[i, j - 1] + 1) { Console.WriteLine(\"Add \" + s2[j - 1]); j--; } } } // Function to compute the DP matrix static void editDP(String s1, String s2) { int l1 = s1.Length; int l2 = s2.Length; int[,] DP = new int[l1 + 1, l2 + 1]; // initialize by the maximum edits possible for (int i = 0; i <= l1; i++) DP[i, 0] = i; for (int j = 0; j <= l2; j++) DP[0, j] = j; // Compute the DP matrix for (int i = 1; i <= l1; i++) { for (int j = 1; j <= l2; j++) { // if the characters are same // no changes required if (s1[i - 1] == s2[j - 1]) DP[i, j] = DP[i - 1, j - 1]; else { // minimu of three operations possible DP[i, j] = min(DP[i - 1, j - 1], DP[i - 1, j], DP[i, j - 1]) + 1; } } } // initialize to global array dp = DP; } // Function to find the minimum of three static int min(int a, int b, int c) { int z = Math.Min(a, b); return Math.Min(z, c); } // Driver Code public static void Main(String[] args) { String s1 = \"abcdef\"; String s2 = \"axcdfdh\"; // calculate the DP matrix editDP(s1, s2); // print the steps printChanges(s1, s2); }} // This code is contributed by PrinciRaj1992",
"e": 35542,
"s": 32987,
"text": null
},
{
"code": null,
"e": 35590,
"s": 35542,
"text": "change f to h\nchange e to d\nAdd f\nchange b to x"
},
{
"code": null,
"e": 35629,
"s": 35592,
"text": "Approach to print all possible ways:"
},
{
"code": null,
"e": 36611,
"s": 35629,
"text": "Create a collection of strings that will store the operations required. This collection can be a vector of strings in C++ or a List of strings in Java. Add operations just like printing them before to this collection. Then create a collection of these collections which will store the multiple methods (sets of string operations). Else-if was used earlier to check from where we derived the DP[i][j] from. Now, check all If’s to see if there were more than 1 ways you could obtain the element. If there was, we create a new collection from before, remove the last operation, add this new operation and initiate another instance of this function with this new list. In this manner, add new lists whenever there was a new method to change str1 to str2, getting a new method every time.On reaching the end of either string, add this list to the collection of lists, thus completing the set of all possible operations, and add them. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 36616,
"s": 36611,
"text": "Java"
},
{
"code": "// Java program to print all the possible// steps to change a string to anotherimport java.util.ArrayList; public class Edit_Distance { static int dp[][]; // create List of lists that will store all sets of operations static ArrayList<ArrayList<String> > arrs = new ArrayList<ArrayList<String> >(); // Function to print all ways static void printAllChanges(String s1, String s2, ArrayList<String> changes) { int i = s1.length(); int j = s2.length(); // Iterate till end while (true) { if (i == 0 || j == 0) { // Add this list to our List of lists. arrs.add(changes); break; } // If same if (s1.charAt(i - 1) == s2.charAt(j - 1)) { i--; j--; } else { boolean if1 = false, if2 = false; // Replace if (dp[i][j] == dp[i - 1][j - 1] + 1) { // Add this step changes.add(\"Change \" + s1.charAt(i - 1) + \" to \" + s2.charAt(j - 1)); i--; j--; // note whether this 'if' was true. if1 = true; } // Delete if (dp[i][j] == dp[i - 1][j] + 1) { if (if1 == false) { changes.add(\"Delete \" + s1.charAt(i - 1)); i--; } else { // If the previous method was true, // create a new list as a copy of previous. ArrayList<String> changes2 = new ArrayList<String>(); changes2.addAll(changes); // Remove last operation changes2.remove(changes.size() - 1); // Add this new operation changes2.add(\"Delete \" + s1.charAt(i)); // initiate new new instance of this // function with remaining substrings printAllChanges(s1.substring(0, i), s2.substring(0, j + 1), changes2); } if2 = true; } // Add character step if (dp[i][j] == dp[i][j - 1] + 1) { if (if1 == false && if2 == false) { changes.add(\"Add \" + s2.charAt(j - 1)); j--; } else { // Add steps ArrayList<String> changes2 = new ArrayList<String>(); changes2.addAll(changes); changes2.remove(changes.size() - 1); changes2.add(\"Add \" + s2.charAt(j)); // Recursively call for the next steps printAllChanges(s1.substring(0, i + 1), s2.substring(0, j), changes2); } } } } } // Function to compute the DP matrix static void editDP(String s1, String s2) { int l1 = s1.length(); int l2 = s2.length(); int[][] DP = new int[l1 + 1][l2 + 1]; // initialize by the maximum edits possible for (int i = 0; i <= l1; i++) DP[i][0] = i; for (int j = 0; j <= l2; j++) DP[0][j] = j; // Compute the DP matrix for (int i = 1; i <= l1; i++) { for (int j = 1; j <= l2; j++) { // if the characters are same // no changes required if (s1.charAt(i - 1) == s2.charAt(j - 1)) DP[i][j] = DP[i - 1][j - 1]; else { // minimum of three operations possible DP[i][j] = min(DP[i - 1][j - 1], DP[i - 1][j], DP[i][j - 1]) + 1; } } } // initialize to global array dp = DP; } // Function to find the minimum of three static int min(int a, int b, int c) { int z = Math.min(a, b); return Math.min(z, c); } static void printWays(String s1, String s2, ArrayList<String> changes) { // Function to print all the ways printAllChanges(s1, s2, new ArrayList<String>()); int i = 1; // print all the possible ways for (ArrayList<String> ar : arrs) { System.out.println(\"\\nMethod \" + i++ + \" : \\n\"); for (String s : ar) { System.out.println(s); } } } // Driver Code public static void main(String[] args) throws Exception { String s1 = \"abcdef\"; String s2 = \"axcdfdh\"; // calculate the DP matrix editDP(s1, s2); // Function to print all ways printWays(s1, s2, new ArrayList<String>()); }}",
"e": 41758,
"s": 36616,
"text": null
},
{
"code": null,
"e": 41943,
"s": 41758,
"text": "Method 1 : \n\nAdd h\nChange f to d\nChange e to f\nChange b to x\n\nMethod 2 : \n\nChange f to h\nAdd d\nChange e to f\nChange b to x\n\nMethod 3 : \n\nChange f to h\nChange e to d\nAdd f\nChange b to x"
},
{
"code": null,
"e": 41957,
"s": 41945,
"text": "sanjeev2552"
},
{
"code": null,
"e": 41971,
"s": 41957,
"text": "princiraj1992"
},
{
"code": null,
"e": 41982,
"s": 41971,
"text": "pranav1503"
},
{
"code": null,
"e": 41991,
"s": 41982,
"text": "sweetyty"
},
{
"code": null,
"e": 42008,
"s": 41991,
"text": "arorakashish0911"
},
{
"code": null,
"e": 42029,
"s": 42008,
"text": "Algorithms-Recursion"
},
{
"code": null,
"e": 42044,
"s": 42029,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 42057,
"s": 42044,
"text": "Java-Strings"
},
{
"code": null,
"e": 42077,
"s": 42057,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 42090,
"s": 42077,
"text": "Java-Strings"
},
{
"code": null,
"e": 42110,
"s": 42090,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 42208,
"s": 42110,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42217,
"s": 42208,
"text": "Comments"
},
{
"code": null,
"e": 42230,
"s": 42217,
"text": "Old Comments"
},
{
"code": null,
"e": 42261,
"s": 42230,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 42294,
"s": 42261,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 42321,
"s": 42294,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 42356,
"s": 42321,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 42394,
"s": 42356,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 42462,
"s": 42394,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 42484,
"s": 42462,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 42547,
"s": 42484,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
},
{
"code": null,
"e": 42569,
"s": 42547,
"text": "Cutting a Rod | DP-13"
}
]
|
Understanding and Implementing LeNet-5 CNN Architecture (Deep Learning) | by Richmond Alake | Towards Data Science | Learn the basics of AI and Deep Learning with TensorFlow and Keras in this Live Training Session hosted by Me.
LeNet was introduced in the research paper “Gradient-Based Learning Applied To Document Recognition” in the year 1998 by Yann LeCun, Leon Bottou, Yoshua Bengio, and Patrick Haffner. Many of the listed authors of the paper have gone on to provide several significant academic contributions to the field of deep learning.
This article will introduce the LeNet-5 CNN architecture as described in the original paper, along with the implementation of the architecture using TensorFlow 2.0.
This article will then conclude with the utilization of the implemented LeNet-5 CNN for the classification of images from the MNIST dataset.
Understanding of components within a convolutional neural network
Key definitions of terms commonly used in deep learning and machine learning
Understanding of LeNet-5 as presented in the original research paper
Implementation of a neural network using TensorFlow and Keras
The content in this article is written for Deep learning and Machine Learning students of all levels.
For those who are eager to get coding, scroll down to the ‘LeNet-5 TensorFlow Implementation’ section.
Convolutional Neural Networks is the standard form of neural network architecture for solving tasks associated with images. Solutions for tasks such as object detection, face detection, pose estimation and more all have CNN architecture variants.
A few characteristics of the CNN architecture makes them more favourable in several computer vision tasks. I have written previous articles that dive into each characteristic.
Local Receptive Fields
Sub-Sampling
Weight Sharing
LeNet-5 CNN architecture is made up of 7 layers. The layer composition consists of 3 convolutional layers, 2 subsampling layers and 2 fully connected layers.
The diagram above shows a depiction of the LeNet-5 architecture, as illustrated in the original paper.
The first layer is the input layer — this is generally not considered a layer of the network as nothing is learnt in this layer. The input layer is built to take in 32x32, and these are the dimensions of images that are passed into the next layer. Those who are familiar with the MNIST dataset will be aware that the MNIST dataset images have the dimensions 28x28. To get the MNIST images dimension to the meet the requirements of the input layer, the 28x28 images are padded.
The grayscale images used in the research paper had their pixel values normalized from 0 to 255, to values between -0.1 and 1.175. The reason for normalization is to ensure that the batch of images have a mean of 0 and a standard deviation of 1, the benefits of this is seen in the reduction in the amount of training time. In the image classification with LeNet-5 example below, we’ll be normalizing the pixel values of the images to take on values between 0 to 1.
The LeNet-5 architecture utilizes two significant types of layer construct: convolutional layers and subsampling layers.
Convolutional layers
Sub-sampling layers
Within the research paper and the image below, convolutional layers are identified with the ‘Cx’, and subsampling layers are identified with ‘Sx’, where ‘x’ is the sequential position of the layer within the architecture. ‘Fx’ is used to identify fully connected layers. This method of layer identification can be seen in the image above.
The official first layer convolutional layer C1 produces as output 6 feature maps, and has a kernel size of 5x5. The kernel/filter is the name given to the window that contains the weight values that are utilized during the convolution of the weight values with the input values. 5x5 is also indicative of the local receptive field size each unit or neuron within a convolutional layer. The dimensions of the six feature maps the first convolution layer produces are 28x28.
A subsampling layer ‘S2’ follows the ‘C1’ layer’. The ‘S2’ layer halves the dimension of the feature maps it receives from the previous layer; this is known commonly as downsampling.
The ‘S2’ layer also produces 6 feature maps, each one corresponding to the feature maps passed as input from the previous layer. This link contains more information on subsampling layers.
More information on the rest of the LeNet-5 layers is covered in the implementation section.
Below is a table that summarises the key features of each layer:
We begin implementation by importing the libraries we will be utilizing:
TensorFlow: An open-source platform for the implementation, training, and deployment of machine learning models.
Keras: An open-source library used for the implementation of neural network architectures that run on both CPUs and GPUs.
Numpy: A library for numerical computation with n-dimensional arrays.
import tensorflow as tffrom tensorflow import kerasimport numpy as np
Next, we load the MNIST dataset using the Keras library. The Keras library has a suite of datasets readily available for use with easy accessibility.
We are also required to partition the dataset into testing, validation and training. Here are some quick descriptions of each partition category.
Training Dataset: This is the group of our dataset used to train the neural network directly. Training data refers to the dataset partition exposed to the neural network during training.
Validation Dataset: This group of the dataset is utilized during training to assess the performance of the network at various iterations.
Test Dataset: This partition of the dataset evaluates the performance of our network after the completion of the training phase.
It is also required that the pixel intensity of the images within the dataset are normalized from the value range 0–255 to 0–1.
(train_x, train_y), (test_x, test_y) = keras.datasets.mnist.load_data()train_x = train_x / 255.0test_x = test_x / 255.0train_x = tf.expand_dims(train_x, 3)test_x = tf.expand_dims(test_x, 3)val_x = train_x[:5000]val_y = train_y[:5000]
In the code snippet above, we expand the dimensions of the training and dataset. The reason we do this is that during the training and evaluation phases, the network expects the images to be presented within batches; the extra dimension is representative of the numbers of images in a batch.
Keras provides tools required to implement the classification model. Keras presents a Sequential API for stacking layers of the neural network on top of each other.
lenet_5_model = keras.models.Sequential([ keras.layers.Conv2D(6, kernel_size=5, strides=1, activation='tanh', input_shape=train_x[0].shape, padding='same'), #C1 keras.layers.AveragePooling2D(), #S2 keras.layers.Conv2D(16, kernel_size=5, strides=1, activation='tanh', padding='valid'), #C3 keras.layers.AveragePooling2D(), #S4 keras.layers.Conv2D(120, kernel_size=5, strides=1, activation='tanh', padding='valid'), #C5 keras.layers.Flatten(), #Flatten keras.layers.Dense(84, activation='tanh'), #F6 keras.layers.Dense(10, activation='softmax') #Output layer])
We first assign the variable’lenet_5_model'to an instance of the tf.keras.Sequential class constructor.
Within the class constructor, we then proceed to define the layers within our model.
The C1 layer is defined by the linekeras.layers.Conv2D(6, kernel_size=5, strides=1, activation='tanh', input_shape=train_x[0].shape, padding='same'). We are using the tf.keras.layers.Conv2D class to construct the convolutional layers within the network. We pass a couple of arguments which are described here.
Activation Function: A mathematical operation that transforms the result or signals of neurons into a normalized output. An activation function is a component of a neural network that introduces non-linearity within the network. The inclusion of the activation function enables the neural network to have greater representational power and solve complex functions.
The rest of the convolutional layers follow the same layer definition as C1 with some different values entered for the arguments.
In the original paper where the LeNet-5 architecture was introduced, subsampling layers were utilized. Within the subsampling layer the average of the pixel values that fall within the 2x2 pooling window was taken, after that, the value is multiplied with a coefficient value. A bias is added to the final result, and all this is done before the values are passed through the activation function.
But in our implemented LeNet-5 neural network, we’re utilizing the tf.keras.layers.AveragePooling2D constructor. We don’ t pass any arguments into the constructor as some default values for the required arguments are initialized when the constructor is called. Remember that the pooling layer role within the network is to downsample the feature maps as they move through the network.
There are two more types of layers within the network, the flatten layer and the dense layers.
The flatten layer is created with the class constructor tf.keras.layers.Flatten.
The purpose of this layer is to transform its input to a 1-dimensional array that can be fed into the subsequent dense layers.
The dense layers have a specified number of units or neurons within each layer, F6 has 84, while the output layer has ten units.
The last dense layer has ten units that correspond to the number of classes that are within the MNIST dataset. The activation function for the output layer is a softmax activation function.
Softmax: An activation function that is utilized to derive the probability distribution of a set of numbers within an input vector. The output of a softmax activation function is a vector in which its set of values represents the probability of an occurrence of a class/event. The values within the vector all add up to 1.
Now we can compile and build the model.
lenet_5_model.compile(optimizer=’adam’, loss=keras.losses.sparse_categorical_crossentropy, metrics=[‘accuracy’])
Keras provides the ‘compile’ method through the model object we have instantiated earlier. The compile function enables the actual building of the model we have implemented behind the scene with some additional characteristics such as the loss function, optimizer, and metrics.
To train the network, we utilize a loss function that calculates the difference between the predicted values provided by the network and actual values of the training data.
The loss values accompanied by an optimization algorithm(Adam) facilitates the number of changes made to the weights within the network. Supporting factors such as momentum and learning rate schedule, provide the ideal environment to enable the network training to converge, herby getting the loss values as close to zero as possible.
During training, we’ll also validate our model after every epoch with the valuation dataset partition created earlier
lenet_5_model.fit(train_x, train_y, epochs=5, validation_data=(val_x, val_y))
After training, you will notice that your model achieves a validation accuracy of over 90%. But for a more explicit verification of the performance of the model on an unseen dataset, we will evaluate the trained model on the test dataset partition created earlier.
lenet_5_model.evaluate(test_x, test_y)>> [0.04592850968674757, 0.9859]
After training my model, I was able to achieve 98% accuracy on the test dataset, which is quite useful for such a simple network.
Here’s GitHub link for the code presented in this article:
github.com.
To connect with me or find more content similar to this article, do the following:
Subscribe to my YouTube channel for video contents coming soon hereFollow me on MediumConnect and reach me on LinkedIn
Subscribe to my YouTube channel for video contents coming soon here
Follow me on Medium
Connect and reach me on LinkedIn | [
{
"code": null,
"e": 283,
"s": 172,
"text": "Learn the basics of AI and Deep Learning with TensorFlow and Keras in this Live Training Session hosted by Me."
},
{
"code": null,
"e": 603,
"s": 283,
"text": "LeNet was introduced in the research paper “Gradient-Based Learning Applied To Document Recognition” in the year 1998 by Yann LeCun, Leon Bottou, Yoshua Bengio, and Patrick Haffner. Many of the listed authors of the paper have gone on to provide several significant academic contributions to the field of deep learning."
},
{
"code": null,
"e": 768,
"s": 603,
"text": "This article will introduce the LeNet-5 CNN architecture as described in the original paper, along with the implementation of the architecture using TensorFlow 2.0."
},
{
"code": null,
"e": 909,
"s": 768,
"text": "This article will then conclude with the utilization of the implemented LeNet-5 CNN for the classification of images from the MNIST dataset."
},
{
"code": null,
"e": 975,
"s": 909,
"text": "Understanding of components within a convolutional neural network"
},
{
"code": null,
"e": 1052,
"s": 975,
"text": "Key definitions of terms commonly used in deep learning and machine learning"
},
{
"code": null,
"e": 1121,
"s": 1052,
"text": "Understanding of LeNet-5 as presented in the original research paper"
},
{
"code": null,
"e": 1183,
"s": 1121,
"text": "Implementation of a neural network using TensorFlow and Keras"
},
{
"code": null,
"e": 1285,
"s": 1183,
"text": "The content in this article is written for Deep learning and Machine Learning students of all levels."
},
{
"code": null,
"e": 1388,
"s": 1285,
"text": "For those who are eager to get coding, scroll down to the ‘LeNet-5 TensorFlow Implementation’ section."
},
{
"code": null,
"e": 1635,
"s": 1388,
"text": "Convolutional Neural Networks is the standard form of neural network architecture for solving tasks associated with images. Solutions for tasks such as object detection, face detection, pose estimation and more all have CNN architecture variants."
},
{
"code": null,
"e": 1811,
"s": 1635,
"text": "A few characteristics of the CNN architecture makes them more favourable in several computer vision tasks. I have written previous articles that dive into each characteristic."
},
{
"code": null,
"e": 1834,
"s": 1811,
"text": "Local Receptive Fields"
},
{
"code": null,
"e": 1847,
"s": 1834,
"text": "Sub-Sampling"
},
{
"code": null,
"e": 1862,
"s": 1847,
"text": "Weight Sharing"
},
{
"code": null,
"e": 2020,
"s": 1862,
"text": "LeNet-5 CNN architecture is made up of 7 layers. The layer composition consists of 3 convolutional layers, 2 subsampling layers and 2 fully connected layers."
},
{
"code": null,
"e": 2123,
"s": 2020,
"text": "The diagram above shows a depiction of the LeNet-5 architecture, as illustrated in the original paper."
},
{
"code": null,
"e": 2600,
"s": 2123,
"text": "The first layer is the input layer — this is generally not considered a layer of the network as nothing is learnt in this layer. The input layer is built to take in 32x32, and these are the dimensions of images that are passed into the next layer. Those who are familiar with the MNIST dataset will be aware that the MNIST dataset images have the dimensions 28x28. To get the MNIST images dimension to the meet the requirements of the input layer, the 28x28 images are padded."
},
{
"code": null,
"e": 3066,
"s": 2600,
"text": "The grayscale images used in the research paper had their pixel values normalized from 0 to 255, to values between -0.1 and 1.175. The reason for normalization is to ensure that the batch of images have a mean of 0 and a standard deviation of 1, the benefits of this is seen in the reduction in the amount of training time. In the image classification with LeNet-5 example below, we’ll be normalizing the pixel values of the images to take on values between 0 to 1."
},
{
"code": null,
"e": 3187,
"s": 3066,
"text": "The LeNet-5 architecture utilizes two significant types of layer construct: convolutional layers and subsampling layers."
},
{
"code": null,
"e": 3208,
"s": 3187,
"text": "Convolutional layers"
},
{
"code": null,
"e": 3228,
"s": 3208,
"text": "Sub-sampling layers"
},
{
"code": null,
"e": 3567,
"s": 3228,
"text": "Within the research paper and the image below, convolutional layers are identified with the ‘Cx’, and subsampling layers are identified with ‘Sx’, where ‘x’ is the sequential position of the layer within the architecture. ‘Fx’ is used to identify fully connected layers. This method of layer identification can be seen in the image above."
},
{
"code": null,
"e": 4041,
"s": 3567,
"text": "The official first layer convolutional layer C1 produces as output 6 feature maps, and has a kernel size of 5x5. The kernel/filter is the name given to the window that contains the weight values that are utilized during the convolution of the weight values with the input values. 5x5 is also indicative of the local receptive field size each unit or neuron within a convolutional layer. The dimensions of the six feature maps the first convolution layer produces are 28x28."
},
{
"code": null,
"e": 4224,
"s": 4041,
"text": "A subsampling layer ‘S2’ follows the ‘C1’ layer’. The ‘S2’ layer halves the dimension of the feature maps it receives from the previous layer; this is known commonly as downsampling."
},
{
"code": null,
"e": 4412,
"s": 4224,
"text": "The ‘S2’ layer also produces 6 feature maps, each one corresponding to the feature maps passed as input from the previous layer. This link contains more information on subsampling layers."
},
{
"code": null,
"e": 4505,
"s": 4412,
"text": "More information on the rest of the LeNet-5 layers is covered in the implementation section."
},
{
"code": null,
"e": 4570,
"s": 4505,
"text": "Below is a table that summarises the key features of each layer:"
},
{
"code": null,
"e": 4643,
"s": 4570,
"text": "We begin implementation by importing the libraries we will be utilizing:"
},
{
"code": null,
"e": 4756,
"s": 4643,
"text": "TensorFlow: An open-source platform for the implementation, training, and deployment of machine learning models."
},
{
"code": null,
"e": 4878,
"s": 4756,
"text": "Keras: An open-source library used for the implementation of neural network architectures that run on both CPUs and GPUs."
},
{
"code": null,
"e": 4948,
"s": 4878,
"text": "Numpy: A library for numerical computation with n-dimensional arrays."
},
{
"code": null,
"e": 5018,
"s": 4948,
"text": "import tensorflow as tffrom tensorflow import kerasimport numpy as np"
},
{
"code": null,
"e": 5168,
"s": 5018,
"text": "Next, we load the MNIST dataset using the Keras library. The Keras library has a suite of datasets readily available for use with easy accessibility."
},
{
"code": null,
"e": 5314,
"s": 5168,
"text": "We are also required to partition the dataset into testing, validation and training. Here are some quick descriptions of each partition category."
},
{
"code": null,
"e": 5501,
"s": 5314,
"text": "Training Dataset: This is the group of our dataset used to train the neural network directly. Training data refers to the dataset partition exposed to the neural network during training."
},
{
"code": null,
"e": 5639,
"s": 5501,
"text": "Validation Dataset: This group of the dataset is utilized during training to assess the performance of the network at various iterations."
},
{
"code": null,
"e": 5768,
"s": 5639,
"text": "Test Dataset: This partition of the dataset evaluates the performance of our network after the completion of the training phase."
},
{
"code": null,
"e": 5896,
"s": 5768,
"text": "It is also required that the pixel intensity of the images within the dataset are normalized from the value range 0–255 to 0–1."
},
{
"code": null,
"e": 6130,
"s": 5896,
"text": "(train_x, train_y), (test_x, test_y) = keras.datasets.mnist.load_data()train_x = train_x / 255.0test_x = test_x / 255.0train_x = tf.expand_dims(train_x, 3)test_x = tf.expand_dims(test_x, 3)val_x = train_x[:5000]val_y = train_y[:5000]"
},
{
"code": null,
"e": 6422,
"s": 6130,
"text": "In the code snippet above, we expand the dimensions of the training and dataset. The reason we do this is that during the training and evaluation phases, the network expects the images to be presented within batches; the extra dimension is representative of the numbers of images in a batch."
},
{
"code": null,
"e": 6587,
"s": 6422,
"text": "Keras provides tools required to implement the classification model. Keras presents a Sequential API for stacking layers of the neural network on top of each other."
},
{
"code": null,
"e": 7175,
"s": 6587,
"text": "lenet_5_model = keras.models.Sequential([ keras.layers.Conv2D(6, kernel_size=5, strides=1, activation='tanh', input_shape=train_x[0].shape, padding='same'), #C1 keras.layers.AveragePooling2D(), #S2 keras.layers.Conv2D(16, kernel_size=5, strides=1, activation='tanh', padding='valid'), #C3 keras.layers.AveragePooling2D(), #S4 keras.layers.Conv2D(120, kernel_size=5, strides=1, activation='tanh', padding='valid'), #C5 keras.layers.Flatten(), #Flatten keras.layers.Dense(84, activation='tanh'), #F6 keras.layers.Dense(10, activation='softmax') #Output layer])"
},
{
"code": null,
"e": 7279,
"s": 7175,
"text": "We first assign the variable’lenet_5_model'to an instance of the tf.keras.Sequential class constructor."
},
{
"code": null,
"e": 7364,
"s": 7279,
"text": "Within the class constructor, we then proceed to define the layers within our model."
},
{
"code": null,
"e": 7674,
"s": 7364,
"text": "The C1 layer is defined by the linekeras.layers.Conv2D(6, kernel_size=5, strides=1, activation='tanh', input_shape=train_x[0].shape, padding='same'). We are using the tf.keras.layers.Conv2D class to construct the convolutional layers within the network. We pass a couple of arguments which are described here."
},
{
"code": null,
"e": 8039,
"s": 7674,
"text": "Activation Function: A mathematical operation that transforms the result or signals of neurons into a normalized output. An activation function is a component of a neural network that introduces non-linearity within the network. The inclusion of the activation function enables the neural network to have greater representational power and solve complex functions."
},
{
"code": null,
"e": 8169,
"s": 8039,
"text": "The rest of the convolutional layers follow the same layer definition as C1 with some different values entered for the arguments."
},
{
"code": null,
"e": 8566,
"s": 8169,
"text": "In the original paper where the LeNet-5 architecture was introduced, subsampling layers were utilized. Within the subsampling layer the average of the pixel values that fall within the 2x2 pooling window was taken, after that, the value is multiplied with a coefficient value. A bias is added to the final result, and all this is done before the values are passed through the activation function."
},
{
"code": null,
"e": 8951,
"s": 8566,
"text": "But in our implemented LeNet-5 neural network, we’re utilizing the tf.keras.layers.AveragePooling2D constructor. We don’ t pass any arguments into the constructor as some default values for the required arguments are initialized when the constructor is called. Remember that the pooling layer role within the network is to downsample the feature maps as they move through the network."
},
{
"code": null,
"e": 9046,
"s": 8951,
"text": "There are two more types of layers within the network, the flatten layer and the dense layers."
},
{
"code": null,
"e": 9127,
"s": 9046,
"text": "The flatten layer is created with the class constructor tf.keras.layers.Flatten."
},
{
"code": null,
"e": 9254,
"s": 9127,
"text": "The purpose of this layer is to transform its input to a 1-dimensional array that can be fed into the subsequent dense layers."
},
{
"code": null,
"e": 9383,
"s": 9254,
"text": "The dense layers have a specified number of units or neurons within each layer, F6 has 84, while the output layer has ten units."
},
{
"code": null,
"e": 9573,
"s": 9383,
"text": "The last dense layer has ten units that correspond to the number of classes that are within the MNIST dataset. The activation function for the output layer is a softmax activation function."
},
{
"code": null,
"e": 9896,
"s": 9573,
"text": "Softmax: An activation function that is utilized to derive the probability distribution of a set of numbers within an input vector. The output of a softmax activation function is a vector in which its set of values represents the probability of an occurrence of a class/event. The values within the vector all add up to 1."
},
{
"code": null,
"e": 9936,
"s": 9896,
"text": "Now we can compile and build the model."
},
{
"code": null,
"e": 10049,
"s": 9936,
"text": "lenet_5_model.compile(optimizer=’adam’, loss=keras.losses.sparse_categorical_crossentropy, metrics=[‘accuracy’])"
},
{
"code": null,
"e": 10327,
"s": 10049,
"text": "Keras provides the ‘compile’ method through the model object we have instantiated earlier. The compile function enables the actual building of the model we have implemented behind the scene with some additional characteristics such as the loss function, optimizer, and metrics."
},
{
"code": null,
"e": 10500,
"s": 10327,
"text": "To train the network, we utilize a loss function that calculates the difference between the predicted values provided by the network and actual values of the training data."
},
{
"code": null,
"e": 10835,
"s": 10500,
"text": "The loss values accompanied by an optimization algorithm(Adam) facilitates the number of changes made to the weights within the network. Supporting factors such as momentum and learning rate schedule, provide the ideal environment to enable the network training to converge, herby getting the loss values as close to zero as possible."
},
{
"code": null,
"e": 10953,
"s": 10835,
"text": "During training, we’ll also validate our model after every epoch with the valuation dataset partition created earlier"
},
{
"code": null,
"e": 11031,
"s": 10953,
"text": "lenet_5_model.fit(train_x, train_y, epochs=5, validation_data=(val_x, val_y))"
},
{
"code": null,
"e": 11296,
"s": 11031,
"text": "After training, you will notice that your model achieves a validation accuracy of over 90%. But for a more explicit verification of the performance of the model on an unseen dataset, we will evaluate the trained model on the test dataset partition created earlier."
},
{
"code": null,
"e": 11367,
"s": 11296,
"text": "lenet_5_model.evaluate(test_x, test_y)>> [0.04592850968674757, 0.9859]"
},
{
"code": null,
"e": 11497,
"s": 11367,
"text": "After training my model, I was able to achieve 98% accuracy on the test dataset, which is quite useful for such a simple network."
},
{
"code": null,
"e": 11556,
"s": 11497,
"text": "Here’s GitHub link for the code presented in this article:"
},
{
"code": null,
"e": 11568,
"s": 11556,
"text": "github.com."
},
{
"code": null,
"e": 11651,
"s": 11568,
"text": "To connect with me or find more content similar to this article, do the following:"
},
{
"code": null,
"e": 11770,
"s": 11651,
"text": "Subscribe to my YouTube channel for video contents coming soon hereFollow me on MediumConnect and reach me on LinkedIn"
},
{
"code": null,
"e": 11838,
"s": 11770,
"text": "Subscribe to my YouTube channel for video contents coming soon here"
},
{
"code": null,
"e": 11858,
"s": 11838,
"text": "Follow me on Medium"
}
]
|
The Easiest Way to Pull Stock Data into your Python Program: yfinance | by Kevin Tang | Towards Data Science | I’ve been working on a fun stock ticker project recently and I came across something I’ve never thought about before: what’s the best way to pull current and historical stock market price data into my Python program?
It turns out that for me, the best option was yfinance — a Python library that gives you current and historical stock market price data from Yahoo Finance, and so much more. The cool thing is that it is entirely free, doesn’t require an API key, and allows for a relatively high throughput of 2,000 requests per hour. And the cooler thing is that you (yes you right there!) can get stock data into your Python program so easily and it’s as simple as these few steps I’ll show you below.
I’m using Python 3.8 but anything above Python 3.4 should be supported. You can be running on Linux, Mac, or Windows. (If you’re on Windows, I’d recommend you check out WSL2, how to get started, and everything it can do — if you do use WSL2, be sure to follow the Linux commands)
To start, we want to create our Python virtual environment named envand activate it.
For Linux/Mac Terminal
python3 -m venv envsource env/bin/activate
For Windows PowerShell
python3 -m venv env.\env\Scripts\Activate.ps1
Now that we’ve got our Python virtual environment setup and activated, let’s install yfinance into this virtual environment so we can use it. The next command is the same for whichever platform you’re on.
pip install yfinance
Now yfinance is installed and we’re ready to write some Python code!
Let’s try out some of yfinance’s most basic, but likely most commonly used features.
I was working on a stock ticker so I wanted the current current price of a stock. Let’s get the current price of a stock and the previous close price of a stock— in this Python example, we’ll use TSLA.
import yfinance as yfstock_info = yf.Ticker('TSLA').info# stock_info.keys() for other properties you can exploremarket_price = stock_info['regularMarketPrice']previous_close_price = stock_info['regularMarketPreviousClose']print('market price ', market_price)print('previous close price ', previous_close_price)
Okay, so if we are running this during the hours the stock market is open, the price information does change and update in real time. How fast are updates? Prices change as fast as Yahoo Finance updates price, which is plenty fast enough for my purposes. It’s probably not fast enough for something like a high frequency trading bot, but Python might not be the best for that anyways.
Next let’s look at some historical data. If we want to plot it, we’ll have to install some additional Python libraries to help us out — matplotlib to plot and pendulum to do some easy time conversions for us.
pip install matplotlib pendulum
Now let’s look at TSLA’s past 2 years of stock price with an interval of every 1 month. You can see these numbers are flexible and can be changed to fit your use case.
import yfinance as yfimport pendulumimport matplotlib.pyplot as pltprice_history = yf.Ticker('TSLA').history(period='2y', # valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max interval='1wk', # valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo actions=False)time_series = list(price_history['Open'])dt_list = [pendulum.parse(str(dt)).float_timestamp for dt in list(price_history.index)]plt.style.use('dark_background')plt.plot(dt_list, time_series, linewidth=2)
I hope you find the yfinance library as hassle-free to set up and incorporate into your project as I did! There is a lot to explore and more information and examples can be found at https://pypi.org/project/yfinance/.
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. | [
{
"code": null,
"e": 389,
"s": 172,
"text": "I’ve been working on a fun stock ticker project recently and I came across something I’ve never thought about before: what’s the best way to pull current and historical stock market price data into my Python program?"
},
{
"code": null,
"e": 876,
"s": 389,
"text": "It turns out that for me, the best option was yfinance — a Python library that gives you current and historical stock market price data from Yahoo Finance, and so much more. The cool thing is that it is entirely free, doesn’t require an API key, and allows for a relatively high throughput of 2,000 requests per hour. And the cooler thing is that you (yes you right there!) can get stock data into your Python program so easily and it’s as simple as these few steps I’ll show you below."
},
{
"code": null,
"e": 1156,
"s": 876,
"text": "I’m using Python 3.8 but anything above Python 3.4 should be supported. You can be running on Linux, Mac, or Windows. (If you’re on Windows, I’d recommend you check out WSL2, how to get started, and everything it can do — if you do use WSL2, be sure to follow the Linux commands)"
},
{
"code": null,
"e": 1241,
"s": 1156,
"text": "To start, we want to create our Python virtual environment named envand activate it."
},
{
"code": null,
"e": 1264,
"s": 1241,
"text": "For Linux/Mac Terminal"
},
{
"code": null,
"e": 1307,
"s": 1264,
"text": "python3 -m venv envsource env/bin/activate"
},
{
"code": null,
"e": 1330,
"s": 1307,
"text": "For Windows PowerShell"
},
{
"code": null,
"e": 1376,
"s": 1330,
"text": "python3 -m venv env.\\env\\Scripts\\Activate.ps1"
},
{
"code": null,
"e": 1581,
"s": 1376,
"text": "Now that we’ve got our Python virtual environment setup and activated, let’s install yfinance into this virtual environment so we can use it. The next command is the same for whichever platform you’re on."
},
{
"code": null,
"e": 1602,
"s": 1581,
"text": "pip install yfinance"
},
{
"code": null,
"e": 1671,
"s": 1602,
"text": "Now yfinance is installed and we’re ready to write some Python code!"
},
{
"code": null,
"e": 1756,
"s": 1671,
"text": "Let’s try out some of yfinance’s most basic, but likely most commonly used features."
},
{
"code": null,
"e": 1958,
"s": 1756,
"text": "I was working on a stock ticker so I wanted the current current price of a stock. Let’s get the current price of a stock and the previous close price of a stock— in this Python example, we’ll use TSLA."
},
{
"code": null,
"e": 2269,
"s": 1958,
"text": "import yfinance as yfstock_info = yf.Ticker('TSLA').info# stock_info.keys() for other properties you can exploremarket_price = stock_info['regularMarketPrice']previous_close_price = stock_info['regularMarketPreviousClose']print('market price ', market_price)print('previous close price ', previous_close_price)"
},
{
"code": null,
"e": 2654,
"s": 2269,
"text": "Okay, so if we are running this during the hours the stock market is open, the price information does change and update in real time. How fast are updates? Prices change as fast as Yahoo Finance updates price, which is plenty fast enough for my purposes. It’s probably not fast enough for something like a high frequency trading bot, but Python might not be the best for that anyways."
},
{
"code": null,
"e": 2863,
"s": 2654,
"text": "Next let’s look at some historical data. If we want to plot it, we’ll have to install some additional Python libraries to help us out — matplotlib to plot and pendulum to do some easy time conversions for us."
},
{
"code": null,
"e": 2895,
"s": 2863,
"text": "pip install matplotlib pendulum"
},
{
"code": null,
"e": 3063,
"s": 2895,
"text": "Now let’s look at TSLA’s past 2 years of stock price with an interval of every 1 month. You can see these numbers are flexible and can be changed to fit your use case."
},
{
"code": null,
"e": 3608,
"s": 3063,
"text": "import yfinance as yfimport pendulumimport matplotlib.pyplot as pltprice_history = yf.Ticker('TSLA').history(period='2y', # valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max interval='1wk', # valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo actions=False)time_series = list(price_history['Open'])dt_list = [pendulum.parse(str(dt)).float_timestamp for dt in list(price_history.index)]plt.style.use('dark_background')plt.plot(dt_list, time_series, linewidth=2)"
},
{
"code": null,
"e": 3826,
"s": 3608,
"text": "I hope you find the yfinance library as hassle-free to set up and incorporate into your project as I did! There is a lot to explore and more information and examples can be found at https://pypi.org/project/yfinance/."
}
]
|
QlikView - Joins | Joins in QlikView are used to combine data from two data sets into one. Joins in QlikView mean the same as in joins in SQL. Only the column and row values that match the join conditions are shown in the output. In case you are completely new to joins, you may like
to first learn about them here.
Let us consider the following two CSV data files, which are used as input for further illustrations.
Product List:
ProductID,ProductCategory
1,Outdoor Recreation
2,Clothing
3,Costumes & Accessories
4,Athletics
5,Personal Care
6,Hobbies & Creative Arts
ProductSales:
ProductID,ProductCategory,SaleAmount
4,Athletics,1212
5,Personal Care,5211
6,Hobbies & Creative Arts,1021
7,Display Board,2177
8,Game,1145
9,soap,1012
10,Beverages & Tobacco,2514
We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. Then we edit the commands in the script to create an inner join between the tables.
Inner join fetches only those rows, which are present in both the tables. In this case, the
rows available in both Product List and Product Sales table are fetched. We create a Table Box using the menu Layout → New Sheet Objects → Table Box where we choose all the three fields - ProductID, ProductCategory and SaleAmount to be displayed.
Left join involves fetching all the rows from the table in the left and the matching rows from the table in the right.
Sales:
LOAD ProductID,
ProductCategory,
SaleAmount
FROM
[C:\Qlikview\data\product_lists.csv]
(txt, codepage is 1252, embedded labels, delimiter is ',', msq);
LEFT JOIN(Sales)
LOAD ProductID,
ProductCategory
FROM
[C:\Qlikview\data\Productsales.csv]
(txt, codepage is 1252, embedded labels, delimiter is ',', msq);
We create a Table Box using the menu Layout → New Sheet Objects → Table
Box, where we choose all the three fields − ProductID, ProductCategory and SaleAmount to be displayed.
Right join involves fetching all the rows from the table in the right and the matching rows from the table in the left.
Sales:
LOAD ProductID,
ProductCategory,
SaleAmount
FROM
[C:\Qlikview\data\product_lists.csv]
(txt, codepage is 1252, embedded labels, delimiter is ',', msq);
RIGHT JOIN(Sales)
LOAD ProductID,
ProductCategory
FROM
[C:\Qlikview\data\Productsales.csv]
(txt, codepage is 1252, embedded labels, delimiter is ',', msq);
We create a Table Box using the menu Layout → New Sheet Objects → Table Box, where we choose all the three fields - ProductID, ProductCategory and SaleAmount to be displayed.
Outer join involves fetching all the rows from the table in the right as well as from the table in the left.
Sales:
LOAD ProductID,
ProductCategory,
SaleAmount
FROM
[C:\Qlikview\data\product_lists.csv]
(txt, codepage is 1252, embedded labels, delimiter is ',', msq);
OUTER JOIN(Sales)
LOAD ProductID,
ProductCategory
FROM
[C:\Qlikview\data\Productsales.csv]
(txt, codepage is 1252, embedded labels, delimiter is ',', msq);
We create a Table Box using the menu Layout → New Sheet Objects → Table Box where we choose all the three fields - ProductID, ProductCategory and SaleAmount to be displayed.
70 Lectures
5 hours
Arthur Fong
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3217,
"s": 2920,
"text": "Joins in QlikView are used to combine data from two data sets into one. Joins in QlikView mean the same as in joins in SQL. Only the column and row values that match the join conditions are shown in the output. In case you are completely new to joins, you may like\nto first learn about them here."
},
{
"code": null,
"e": 3318,
"s": 3217,
"text": "Let us consider the following two CSV data files, which are used as input for further illustrations."
},
{
"code": null,
"e": 3664,
"s": 3318,
"text": "Product List:\nProductID,ProductCategory\n1,Outdoor Recreation\n2,Clothing\n3,Costumes & Accessories\n4,Athletics\n5,Personal Care\n6,Hobbies & Creative Arts\n\nProductSales:\nProductID,ProductCategory,SaleAmount\n4,Athletics,1212\n5,Personal Care,5211\n6,Hobbies & Creative Arts,1021\n7,Display Board,2177\n8,Game,1145\n9,soap,1012\n10,Beverages & Tobacco,2514\n"
},
{
"code": null,
"e": 3903,
"s": 3664,
"text": "We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. Then we edit the commands in the script to create an inner join between the tables."
},
{
"code": null,
"e": 4242,
"s": 3903,
"text": "Inner join fetches only those rows, which are present in both the tables. In this case, the\nrows available in both Product List and Product Sales table are fetched. We create a Table Box using the menu Layout → New Sheet Objects → Table Box where we choose all the three fields - ProductID, ProductCategory and SaleAmount to be displayed."
},
{
"code": null,
"e": 4361,
"s": 4242,
"text": "Left join involves fetching all the rows from the table in the left and the matching rows from the table in the right."
},
{
"code": null,
"e": 4694,
"s": 4361,
"text": "Sales:\nLOAD ProductID, \n ProductCategory, \n SaleAmount\nFROM\n[C:\\Qlikview\\data\\product_lists.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nLEFT JOIN(Sales)\n\nLOAD ProductID, \n ProductCategory\nFROM\n[C:\\Qlikview\\data\\Productsales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);"
},
{
"code": null,
"e": 4869,
"s": 4694,
"text": "We create a Table Box using the menu Layout → New Sheet Objects → Table\nBox, where we choose all the three fields − ProductID, ProductCategory and SaleAmount to be displayed."
},
{
"code": null,
"e": 4989,
"s": 4869,
"text": "Right join involves fetching all the rows from the table in the right and the matching rows from the table in the left."
},
{
"code": null,
"e": 5323,
"s": 4989,
"text": "Sales:\nLOAD ProductID, \n ProductCategory, \n SaleAmount\nFROM\n[C:\\Qlikview\\data\\product_lists.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nRIGHT JOIN(Sales)\n\nLOAD ProductID, \n ProductCategory\nFROM\n[C:\\Qlikview\\data\\Productsales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);"
},
{
"code": null,
"e": 5498,
"s": 5323,
"text": "We create a Table Box using the menu Layout → New Sheet Objects → Table Box, where we choose all the three fields - ProductID, ProductCategory and SaleAmount to be displayed."
},
{
"code": null,
"e": 5607,
"s": 5498,
"text": "Outer join involves fetching all the rows from the table in the right as well as from the table in the left."
},
{
"code": null,
"e": 5941,
"s": 5607,
"text": "Sales:\nLOAD ProductID, \n ProductCategory, \n SaleAmount\nFROM\n[C:\\Qlikview\\data\\product_lists.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);\n\nOUTER JOIN(Sales)\n\nLOAD ProductID, \n ProductCategory\nFROM\n[C:\\Qlikview\\data\\Productsales.csv]\n(txt, codepage is 1252, embedded labels, delimiter is ',', msq);"
},
{
"code": null,
"e": 6115,
"s": 5941,
"text": "We create a Table Box using the menu Layout → New Sheet Objects → Table Box where we choose all the three fields - ProductID, ProductCategory and SaleAmount to be displayed."
},
{
"code": null,
"e": 6148,
"s": 6115,
"text": "\n 70 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6161,
"s": 6148,
"text": " Arthur Fong"
},
{
"code": null,
"e": 6168,
"s": 6161,
"text": " Print"
},
{
"code": null,
"e": 6179,
"s": 6168,
"text": " Add Notes"
}
]
|
Implementing Random Forest in R. A Practical Application of Random... | by Joe Tran | Towards Data Science | In order to understand RF, we need to first understand about decision trees. Rajesh S. Brid wrote a detailed article about decision trees. We will not go too much in details about the definition of decision trees since that is not the purpose of this article. I just want to quickly summarise a few points. A decision tree is series of Yes/No questions. For each level of the tree, if your answer is Yes, you fall into a category, otherwise, you will fall into another category. You will answer this series of Yes/No questions until you reach the final category. You will be classified into that group.
Trees work well with the data we use to train, but they are not performing well when it comes to new data samples. Fortunately, we have Random Forest, which is a combination of many decision trees with flexibility, hence resulting in an improvement in accuracy.
Here I will not go too much into details about RF because there are various sources outside we can get to understand what is the mathematics behind it. Here is one of them.
This article is more about practical application of RF in classifying cancer patients, so I will jump straight into the coding part. Now let’s open Rstudio and get our hands dirty :)
First of all, we need to load the following packages. If you cannot load them, chances are you have not installed them yet. So please do so first before loading the following packages.
library(ggplot2)library(corrplot)library(reshape2)library(ggthemes)library(dplyr)library(randomForest)Wisconsin = read.table(url(paste0("https://archive.ics.uci.edu/ml/machine-learning-databases/","breast-cancer-wisconsin/wdbc.data")),header=FALSE,sep=",",nrows=570)
I read the data directly from the web link and name the dataset as Wisconsin. Let’s inspect the data a little bit
head(Wisconsin)
V1 is the ID so it is not relevant in our analysis here. V2 is the classification result, with ‘M’ standing for ‘Malignant’ and ‘B’ standing for ‘Benign’. The rest is just the variables of information about the cancer diagnosis.
Now I would like to change M and B to TRUE and FALSE for easier interpretation.
Wisconsin$V2 <- Wisconsin$V2 == “M”
Pre-processing data
First, we shuffle the data and split it into train and test. We decide a 70–30 split for this.
set.seed(2019)test_size = floor(0.3 * nrow(Wisconsin))samp = sample(nrow(Wisconsin), test_size,replace = FALSE)y_train = Wisconsin[-samp,2]x_train = Wisconsin[-samp,-c(1,2)] #since the first column is just IDy_test= Wisconsin[samp,2]x_test = Wisconsin[samp,-c(1,2)] #since the first column is just ID#convert labels to categoricaly_train = factor(y_train)y_test = factor(y_test)
We should note that RF only works when the response variable is a factor. Just now when we convert ‘M’ and ‘B’ into TRUE and FALSE, the type of this variable is logical. Hence we need to convert it into factor by using factor() function.
Now let’s combine x and y to form training and test set.
#Create training set and testing settrain = cbind(y_train,x_train)test = cbind(y_test,x_test)
The training set will be used to train the RF model and the test set will be used to test the performance of the model. Now let’s give the name to our response variable. Here I named it as ‘label’
colnames(train)[1] = ‘label’colnames(test)[1] = ‘label’
It now looks like this
Fit a Random Forest model
Now everything is ready. We can start fitting the model. This step is easy.
The ‘randomForest()’ function in the package fits a random forest model to the data. Besides including the dataset and specifying the formula and labels, some key parameters of this function includes:
1. ntree: Number of trees to grow. The default value is 500.
2. mtry: Number of randomly selected variables for each split. In this example we use the square root of p (p denotes the number of predictors). Note that for regression analysis the general rule is to use mtry = p/3 and is also the default value of this parameter for regression.
3. importance: If True, the model will calculate the feature importance for further analysis. (default = False)
4. proximity: If True, the model will contain a N*N matrix which represents the proximity measure.
5. maxnodes: The maximum number of terminal nodes the trees can have.
6. na.action: A function to specify how the missing data should be treated.
Since there are 30 independent variables, we set mtry to be square root of 30 and then fit the model
mtry = sqrt(30)model_1 = randomForest(label~., data = train, importance = TRUE)
That is it. Simple isn’t it? Now we already have a RF model
print(model_1)
The Out-of-bag OOB error estimate rate is 3%, which is very good, i.e. 97% accuracy. If we look at the Confusion Matrix, we can see that classification error is quite low. This shows that our RF model is performing well in classifying the train set.
Let’s test the model with our test set.
pred_1 = predict(model_1, x_test)table(y_test, pred_1)accuracy_m1 = mean(y_test == pred_1)
Looks like our model is performing well on the test set too, with the accuracy of 95%.
Variable Importance
varImpPlot(model_1)
Another way for us to visualise the plot is to use ggplot package. Do note that the code below is to visualize the ‘Mean Decrease Accuracy’. To get the ‘Mean Decrease Gini’, simply change the line in bold below to ‘MeanDecreaseAccuracy’ (no spacing).
importance = importance(model_1)varImportance = data.frame(Variables = row.names(importance), Importance =round(importance[, “MeanDecreaseAccuracy”],2))rankImportance=varImportance%>%mutate(Rank=paste(‘#’,dense_rank(desc(Importance))))ggplot(rankImportance,aes(x=reorder(Variables,Importance), y=Importance,fill=Importance))+ geom_bar(stat=’identity’) + geom_text(aes(x = Variables, y = 0.5, label = Rank), hjust=0, vjust=0.55, size = 4, colour = ‘white’) + labs(x = ‘Variables’) + coord_flip() + theme_classic()
The result is similar to the plot we obtained earlier. The result shows that variables V25, V30, V26 and V23 are the most important.
Using Mean Decrease Gini, we get V25, V23, and V26 as the most important variables.
This article shows how to implement a simple Random Forest model in solving classification problems. I did not go too deep into how to tune the parameters in order to optimize the model because with such a high accuracy in classification, I think that a simple model would be enough. HOWEVER, in real life, there are other much more complicated classification problems that require us to tune the parameters to obtain the best model, which I will write a separate article on next time. But it is important to remember to ALWAYS start with a simple model and then from there build up the model to get a better prediction.
Thank you for your time. I hope this article helps you guys, especially those who have never tried implementing RF in R before, gain a better idea of how to do it. Let me know if you have any comments or questions.
Have a great day and happy programming :) | [
{
"code": null,
"e": 775,
"s": 172,
"text": "In order to understand RF, we need to first understand about decision trees. Rajesh S. Brid wrote a detailed article about decision trees. We will not go too much in details about the definition of decision trees since that is not the purpose of this article. I just want to quickly summarise a few points. A decision tree is series of Yes/No questions. For each level of the tree, if your answer is Yes, you fall into a category, otherwise, you will fall into another category. You will answer this series of Yes/No questions until you reach the final category. You will be classified into that group."
},
{
"code": null,
"e": 1037,
"s": 775,
"text": "Trees work well with the data we use to train, but they are not performing well when it comes to new data samples. Fortunately, we have Random Forest, which is a combination of many decision trees with flexibility, hence resulting in an improvement in accuracy."
},
{
"code": null,
"e": 1210,
"s": 1037,
"text": "Here I will not go too much into details about RF because there are various sources outside we can get to understand what is the mathematics behind it. Here is one of them."
},
{
"code": null,
"e": 1393,
"s": 1210,
"text": "This article is more about practical application of RF in classifying cancer patients, so I will jump straight into the coding part. Now let’s open Rstudio and get our hands dirty :)"
},
{
"code": null,
"e": 1578,
"s": 1393,
"text": "First of all, we need to load the following packages. If you cannot load them, chances are you have not installed them yet. So please do so first before loading the following packages."
},
{
"code": null,
"e": 1845,
"s": 1578,
"text": "library(ggplot2)library(corrplot)library(reshape2)library(ggthemes)library(dplyr)library(randomForest)Wisconsin = read.table(url(paste0(\"https://archive.ics.uci.edu/ml/machine-learning-databases/\",\"breast-cancer-wisconsin/wdbc.data\")),header=FALSE,sep=\",\",nrows=570)"
},
{
"code": null,
"e": 1959,
"s": 1845,
"text": "I read the data directly from the web link and name the dataset as Wisconsin. Let’s inspect the data a little bit"
},
{
"code": null,
"e": 1975,
"s": 1959,
"text": "head(Wisconsin)"
},
{
"code": null,
"e": 2204,
"s": 1975,
"text": "V1 is the ID so it is not relevant in our analysis here. V2 is the classification result, with ‘M’ standing for ‘Malignant’ and ‘B’ standing for ‘Benign’. The rest is just the variables of information about the cancer diagnosis."
},
{
"code": null,
"e": 2284,
"s": 2204,
"text": "Now I would like to change M and B to TRUE and FALSE for easier interpretation."
},
{
"code": null,
"e": 2320,
"s": 2284,
"text": "Wisconsin$V2 <- Wisconsin$V2 == “M”"
},
{
"code": null,
"e": 2340,
"s": 2320,
"text": "Pre-processing data"
},
{
"code": null,
"e": 2435,
"s": 2340,
"text": "First, we shuffle the data and split it into train and test. We decide a 70–30 split for this."
},
{
"code": null,
"e": 2814,
"s": 2435,
"text": "set.seed(2019)test_size = floor(0.3 * nrow(Wisconsin))samp = sample(nrow(Wisconsin), test_size,replace = FALSE)y_train = Wisconsin[-samp,2]x_train = Wisconsin[-samp,-c(1,2)] #since the first column is just IDy_test= Wisconsin[samp,2]x_test = Wisconsin[samp,-c(1,2)] #since the first column is just ID#convert labels to categoricaly_train = factor(y_train)y_test = factor(y_test)"
},
{
"code": null,
"e": 3052,
"s": 2814,
"text": "We should note that RF only works when the response variable is a factor. Just now when we convert ‘M’ and ‘B’ into TRUE and FALSE, the type of this variable is logical. Hence we need to convert it into factor by using factor() function."
},
{
"code": null,
"e": 3109,
"s": 3052,
"text": "Now let’s combine x and y to form training and test set."
},
{
"code": null,
"e": 3203,
"s": 3109,
"text": "#Create training set and testing settrain = cbind(y_train,x_train)test = cbind(y_test,x_test)"
},
{
"code": null,
"e": 3400,
"s": 3203,
"text": "The training set will be used to train the RF model and the test set will be used to test the performance of the model. Now let’s give the name to our response variable. Here I named it as ‘label’"
},
{
"code": null,
"e": 3456,
"s": 3400,
"text": "colnames(train)[1] = ‘label’colnames(test)[1] = ‘label’"
},
{
"code": null,
"e": 3479,
"s": 3456,
"text": "It now looks like this"
},
{
"code": null,
"e": 3505,
"s": 3479,
"text": "Fit a Random Forest model"
},
{
"code": null,
"e": 3581,
"s": 3505,
"text": "Now everything is ready. We can start fitting the model. This step is easy."
},
{
"code": null,
"e": 3782,
"s": 3581,
"text": "The ‘randomForest()’ function in the package fits a random forest model to the data. Besides including the dataset and specifying the formula and labels, some key parameters of this function includes:"
},
{
"code": null,
"e": 3843,
"s": 3782,
"text": "1. ntree: Number of trees to grow. The default value is 500."
},
{
"code": null,
"e": 4124,
"s": 3843,
"text": "2. mtry: Number of randomly selected variables for each split. In this example we use the square root of p (p denotes the number of predictors). Note that for regression analysis the general rule is to use mtry = p/3 and is also the default value of this parameter for regression."
},
{
"code": null,
"e": 4236,
"s": 4124,
"text": "3. importance: If True, the model will calculate the feature importance for further analysis. (default = False)"
},
{
"code": null,
"e": 4335,
"s": 4236,
"text": "4. proximity: If True, the model will contain a N*N matrix which represents the proximity measure."
},
{
"code": null,
"e": 4405,
"s": 4335,
"text": "5. maxnodes: The maximum number of terminal nodes the trees can have."
},
{
"code": null,
"e": 4481,
"s": 4405,
"text": "6. na.action: A function to specify how the missing data should be treated."
},
{
"code": null,
"e": 4582,
"s": 4481,
"text": "Since there are 30 independent variables, we set mtry to be square root of 30 and then fit the model"
},
{
"code": null,
"e": 4662,
"s": 4582,
"text": "mtry = sqrt(30)model_1 = randomForest(label~., data = train, importance = TRUE)"
},
{
"code": null,
"e": 4722,
"s": 4662,
"text": "That is it. Simple isn’t it? Now we already have a RF model"
},
{
"code": null,
"e": 4737,
"s": 4722,
"text": "print(model_1)"
},
{
"code": null,
"e": 4987,
"s": 4737,
"text": "The Out-of-bag OOB error estimate rate is 3%, which is very good, i.e. 97% accuracy. If we look at the Confusion Matrix, we can see that classification error is quite low. This shows that our RF model is performing well in classifying the train set."
},
{
"code": null,
"e": 5027,
"s": 4987,
"text": "Let’s test the model with our test set."
},
{
"code": null,
"e": 5118,
"s": 5027,
"text": "pred_1 = predict(model_1, x_test)table(y_test, pred_1)accuracy_m1 = mean(y_test == pred_1)"
},
{
"code": null,
"e": 5205,
"s": 5118,
"text": "Looks like our model is performing well on the test set too, with the accuracy of 95%."
},
{
"code": null,
"e": 5225,
"s": 5205,
"text": "Variable Importance"
},
{
"code": null,
"e": 5245,
"s": 5225,
"text": "varImpPlot(model_1)"
},
{
"code": null,
"e": 5496,
"s": 5245,
"text": "Another way for us to visualise the plot is to use ggplot package. Do note that the code below is to visualize the ‘Mean Decrease Accuracy’. To get the ‘Mean Decrease Gini’, simply change the line in bold below to ‘MeanDecreaseAccuracy’ (no spacing)."
},
{
"code": null,
"e": 6012,
"s": 5496,
"text": "importance = importance(model_1)varImportance = data.frame(Variables = row.names(importance), Importance =round(importance[, “MeanDecreaseAccuracy”],2))rankImportance=varImportance%>%mutate(Rank=paste(‘#’,dense_rank(desc(Importance))))ggplot(rankImportance,aes(x=reorder(Variables,Importance), y=Importance,fill=Importance))+ geom_bar(stat=’identity’) + geom_text(aes(x = Variables, y = 0.5, label = Rank), hjust=0, vjust=0.55, size = 4, colour = ‘white’) + labs(x = ‘Variables’) + coord_flip() + theme_classic()"
},
{
"code": null,
"e": 6145,
"s": 6012,
"text": "The result is similar to the plot we obtained earlier. The result shows that variables V25, V30, V26 and V23 are the most important."
},
{
"code": null,
"e": 6229,
"s": 6145,
"text": "Using Mean Decrease Gini, we get V25, V23, and V26 as the most important variables."
},
{
"code": null,
"e": 6850,
"s": 6229,
"text": "This article shows how to implement a simple Random Forest model in solving classification problems. I did not go too deep into how to tune the parameters in order to optimize the model because with such a high accuracy in classification, I think that a simple model would be enough. HOWEVER, in real life, there are other much more complicated classification problems that require us to tune the parameters to obtain the best model, which I will write a separate article on next time. But it is important to remember to ALWAYS start with a simple model and then from there build up the model to get a better prediction."
},
{
"code": null,
"e": 7065,
"s": 6850,
"text": "Thank you for your time. I hope this article helps you guys, especially those who have never tried implementing RF in R before, gain a better idea of how to do it. Let me know if you have any comments or questions."
}
]
|
Non maximum suppression (NMS) in python | Towards Data Science | Have you ever used an object detection algorithm? If yes, then chances are high that you have already used the Non-maximum suppression algorithm. Maybe it was part of a deep learning model you used and you haven’t even noticed. Because even very sophisticated algorithms face the problem they recognize the same object multiple times.
Today, I want to show you how the Non-maximum suppression algorithm works and provide a python implementation.
I will start out by showing you, that bounding boxes are rectangle that surround a detected object in an image. Then I will introduce the code for Non-maximum suppression. This algorithm removes the redundant bounding boxes one by one. It does so by removing boxes with an overlap greater than a threshold which we set manually.
We use bounding boxes to mark the part of an image where an object of interest has been recognized.
In this example, the object to recognize was the big diamond in the ace of diamonds.
Bounding Boxes are always upright rectangles. We therefore only need to store the top left and the bottom right corner of all bounding boxes.
When using object detection methods it happens often, that the same object get’s detected multiple times in slightly different areas.
Most of the time, we want to detect an object only once. To achieve this, we remove the redundant bounding boxes by applying non-maximum suppression.
I present you now the fully functional code to perform non-maximum suppression, so that you have an overview. But don’t worry, I will walk you through the code.
The Non-maximum suppression (NMS) function takes in an array of boxes and overlap treshold with a default value of 0.4.
The array of boxes must be organized so that every row contains a different bounding box.
The overlap treshold determines the overlap in area two bounding boxes are allowed to have. If they overlap more, then one of the two will be discarded. An overlap treshold of 0.4 would mean, that two boxes are allowed to share 40% of their area.
The area of a rectangle is calculated by multiplying it’s width by it’s height. We add one to x2−x1 and y2−y1, because the bounding box has a pixel on the start as well as on the end coordinate.
We then create indices for all the boxes. Later, we will drop out one index after another until we have only indices corresponding to non-overlapping boxes.
In the loop, we iterate over all boxes. For each box, we check, if it’s overlap with any other box is greater than the treshold. If so, we drop out the index of that box from our indices list.
We have to create indices, that contain contain the indices of the boxes, but without the index of the box[i].
To calculate the overlap we first calculate the coordinates of the intersection boxes. This code is vectorized to make it faster and therefore we calculate the intersection of the box[i] with every other box.
It might be a little bit confusing but the zero point is in the top left corner. Therefore we get the coordinates of the intersection box by selecting the minimum of x1 and y1 of two boxes and the maximum of x2 and y2 of the same boxes.
Then we calculate the width and the height of the intersection boxes. We take the maximum of 0 and our calculated widths and heights, because negative widths and heights would mess up the calculation of the overlap.
The overlap is then simply the area of the intersection boxes divided by the are of the bounding box. In our case all bounding boxes have the same size, but the algorithm also works with difference in sizes.
We then exclude the index i from our remaining indices, if the overlap of box[i] with any other box is greater than the treshold.
We then return the boxes with the indices that have not been dropped out. Pixel coordinates have to be integers, so we convert them just to be safe.
You might ask yourself how I got those bounding boxes in the first place. I used a simple technique called template matching. You only need 1 image where you want to detect an object and 1 template, which is the object you want to search for.
Our image will be the ace of diamonds.
Our template will be the diamond in the middle of the image.
Note that the template must have roughly the same orientation and size (in pixels) as the object we want to detect in the image.
If you want to use my images, you can download them in the sources section.
We are going to need the opencv. If you don’t have it yet, you can install in the terminal.
pip install opencv-python
And we import it under the name cv2.
import cv2
To perform template matching and generate bounding boxes from it, we can use the following function.
The cv2.matchTemplate function return us the correlation of different parts of the image with the template.
We then select the parts of the image, where the correlation is above the treshold.
We also need a function to draw the bounding boxes onto the image.
We can use Non-maximum suppression to remove redundant bounding boxes. They are redundant in the sense that they mark the same object multiple times. The NMS algorithm calculates the overlap between triangles by making use of the area of the intersection triangle. If the overlap of a bounding box with any other bounding box is above the threshold, it will get removed.
Linkedinhttps://www.linkedin.com/in/vincent-m%C3%BCller-6b3542214/Facebookhttps://www.facebook.com/profile.php?id=100072095823739Twitterhttps://twitter.com/Vincent02770108Mediumhttps://medium.com/@Vincent.MuellerBecome medium member and support mehttps://medium.com/@Vincent.Mueller/membership
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
pyimagesearch “(Faster) Non-Maximum Suppression in Python”
LearnOpenCV ”Non Maximum Suppression: Theory and Implementation in PyTorch”
All images are provided by author. You are free to reuse them for any purpose, even commercially. | [
{
"code": null,
"e": 507,
"s": 172,
"text": "Have you ever used an object detection algorithm? If yes, then chances are high that you have already used the Non-maximum suppression algorithm. Maybe it was part of a deep learning model you used and you haven’t even noticed. Because even very sophisticated algorithms face the problem they recognize the same object multiple times."
},
{
"code": null,
"e": 618,
"s": 507,
"text": "Today, I want to show you how the Non-maximum suppression algorithm works and provide a python implementation."
},
{
"code": null,
"e": 947,
"s": 618,
"text": "I will start out by showing you, that bounding boxes are rectangle that surround a detected object in an image. Then I will introduce the code for Non-maximum suppression. This algorithm removes the redundant bounding boxes one by one. It does so by removing boxes with an overlap greater than a threshold which we set manually."
},
{
"code": null,
"e": 1047,
"s": 947,
"text": "We use bounding boxes to mark the part of an image where an object of interest has been recognized."
},
{
"code": null,
"e": 1132,
"s": 1047,
"text": "In this example, the object to recognize was the big diamond in the ace of diamonds."
},
{
"code": null,
"e": 1274,
"s": 1132,
"text": "Bounding Boxes are always upright rectangles. We therefore only need to store the top left and the bottom right corner of all bounding boxes."
},
{
"code": null,
"e": 1408,
"s": 1274,
"text": "When using object detection methods it happens often, that the same object get’s detected multiple times in slightly different areas."
},
{
"code": null,
"e": 1558,
"s": 1408,
"text": "Most of the time, we want to detect an object only once. To achieve this, we remove the redundant bounding boxes by applying non-maximum suppression."
},
{
"code": null,
"e": 1719,
"s": 1558,
"text": "I present you now the fully functional code to perform non-maximum suppression, so that you have an overview. But don’t worry, I will walk you through the code."
},
{
"code": null,
"e": 1839,
"s": 1719,
"text": "The Non-maximum suppression (NMS) function takes in an array of boxes and overlap treshold with a default value of 0.4."
},
{
"code": null,
"e": 1929,
"s": 1839,
"text": "The array of boxes must be organized so that every row contains a different bounding box."
},
{
"code": null,
"e": 2176,
"s": 1929,
"text": "The overlap treshold determines the overlap in area two bounding boxes are allowed to have. If they overlap more, then one of the two will be discarded. An overlap treshold of 0.4 would mean, that two boxes are allowed to share 40% of their area."
},
{
"code": null,
"e": 2371,
"s": 2176,
"text": "The area of a rectangle is calculated by multiplying it’s width by it’s height. We add one to x2−x1 and y2−y1, because the bounding box has a pixel on the start as well as on the end coordinate."
},
{
"code": null,
"e": 2528,
"s": 2371,
"text": "We then create indices for all the boxes. Later, we will drop out one index after another until we have only indices corresponding to non-overlapping boxes."
},
{
"code": null,
"e": 2721,
"s": 2528,
"text": "In the loop, we iterate over all boxes. For each box, we check, if it’s overlap with any other box is greater than the treshold. If so, we drop out the index of that box from our indices list."
},
{
"code": null,
"e": 2832,
"s": 2721,
"text": "We have to create indices, that contain contain the indices of the boxes, but without the index of the box[i]."
},
{
"code": null,
"e": 3041,
"s": 2832,
"text": "To calculate the overlap we first calculate the coordinates of the intersection boxes. This code is vectorized to make it faster and therefore we calculate the intersection of the box[i] with every other box."
},
{
"code": null,
"e": 3278,
"s": 3041,
"text": "It might be a little bit confusing but the zero point is in the top left corner. Therefore we get the coordinates of the intersection box by selecting the minimum of x1 and y1 of two boxes and the maximum of x2 and y2 of the same boxes."
},
{
"code": null,
"e": 3494,
"s": 3278,
"text": "Then we calculate the width and the height of the intersection boxes. We take the maximum of 0 and our calculated widths and heights, because negative widths and heights would mess up the calculation of the overlap."
},
{
"code": null,
"e": 3702,
"s": 3494,
"text": "The overlap is then simply the area of the intersection boxes divided by the are of the bounding box. In our case all bounding boxes have the same size, but the algorithm also works with difference in sizes."
},
{
"code": null,
"e": 3832,
"s": 3702,
"text": "We then exclude the index i from our remaining indices, if the overlap of box[i] with any other box is greater than the treshold."
},
{
"code": null,
"e": 3981,
"s": 3832,
"text": "We then return the boxes with the indices that have not been dropped out. Pixel coordinates have to be integers, so we convert them just to be safe."
},
{
"code": null,
"e": 4224,
"s": 3981,
"text": "You might ask yourself how I got those bounding boxes in the first place. I used a simple technique called template matching. You only need 1 image where you want to detect an object and 1 template, which is the object you want to search for."
},
{
"code": null,
"e": 4263,
"s": 4224,
"text": "Our image will be the ace of diamonds."
},
{
"code": null,
"e": 4324,
"s": 4263,
"text": "Our template will be the diamond in the middle of the image."
},
{
"code": null,
"e": 4453,
"s": 4324,
"text": "Note that the template must have roughly the same orientation and size (in pixels) as the object we want to detect in the image."
},
{
"code": null,
"e": 4529,
"s": 4453,
"text": "If you want to use my images, you can download them in the sources section."
},
{
"code": null,
"e": 4621,
"s": 4529,
"text": "We are going to need the opencv. If you don’t have it yet, you can install in the terminal."
},
{
"code": null,
"e": 4647,
"s": 4621,
"text": "pip install opencv-python"
},
{
"code": null,
"e": 4684,
"s": 4647,
"text": "And we import it under the name cv2."
},
{
"code": null,
"e": 4695,
"s": 4684,
"text": "import cv2"
},
{
"code": null,
"e": 4796,
"s": 4695,
"text": "To perform template matching and generate bounding boxes from it, we can use the following function."
},
{
"code": null,
"e": 4904,
"s": 4796,
"text": "The cv2.matchTemplate function return us the correlation of different parts of the image with the template."
},
{
"code": null,
"e": 4988,
"s": 4904,
"text": "We then select the parts of the image, where the correlation is above the treshold."
},
{
"code": null,
"e": 5055,
"s": 4988,
"text": "We also need a function to draw the bounding boxes onto the image."
},
{
"code": null,
"e": 5426,
"s": 5055,
"text": "We can use Non-maximum suppression to remove redundant bounding boxes. They are redundant in the sense that they mark the same object multiple times. The NMS algorithm calculates the overlap between triangles by making use of the area of the intersection triangle. If the overlap of a bounding box with any other bounding box is above the threshold, it will get removed."
},
{
"code": null,
"e": 5720,
"s": 5426,
"text": "Linkedinhttps://www.linkedin.com/in/vincent-m%C3%BCller-6b3542214/Facebookhttps://www.facebook.com/profile.php?id=100072095823739Twitterhttps://twitter.com/Vincent02770108Mediumhttps://medium.com/@Vincent.MuellerBecome medium member and support mehttps://medium.com/@Vincent.Mueller/membership"
},
{
"code": null,
"e": 5743,
"s": 5720,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5766,
"s": 5743,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5789,
"s": 5766,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5812,
"s": 5789,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5835,
"s": 5812,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5858,
"s": 5835,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5917,
"s": 5858,
"text": "pyimagesearch “(Faster) Non-Maximum Suppression in Python”"
},
{
"code": null,
"e": 5993,
"s": 5917,
"text": "LearnOpenCV ”Non Maximum Suppression: Theory and Implementation in PyTorch”"
}
]
|
Image Augmentation with skimage — Python | by Mathanraj Sharma | Towards Data Science | Hey buddies, recently I was working on an image classification problem. But unfortunately, there were not enough samples in one of class. I searched the internet and learned about a technique called image augmentation. Here I have shared my understanding of this technique and shared some codes using skimage. You can find the jupyter notebook at the bottom.
Image augmentation is a technique used to artificially increase the size of your image dataset. It can be achieved by applying random transformations to your image.
We know Deep learning models are able to generalize well when they are able to see more data. Data augmentation can create variations of existing images which helps to generalize well.
But you need to be careful too. We can use Augmented Images for training but not for testing. So before applying any augmentation split your data into train and testing set. Expand your training data with Image Augmentation.
Image augmentation can be applied mainly on two domains of Image
Position AugmentationColor Augmentation
Position Augmentation
Color Augmentation
Positon augmentation is simple where we apply different transformations on pixel positions.
Scaling, rotation, cropping, flipping, padding, zoom, translation, shearing, and other affine transformations are examples for the Position Augmentation. Let us try applying some of these transformations.
import numpy as npfrom skimage.io import imread, imsaveimport matplotlib.pyplot as pltfrom skimage import transformfrom skimage.transform import rotate, AffineTransformfrom skimage.util import random_noisefrom skimage.filters import gaussianfrom scipy import ndimage# load Imageimg = imread('./butterfly.jpg') / 255# plot original Imageplt.imshow(img)plt.show()
# image rotation using skimage.transformation.rotaterotate30 = rotate(img, angle=30)rotate45 = rotate(img, angle=45)rotate60 = rotate(img, angle=60)rotate90 = rotate(img, angle=90)fig = plt.figure(tight_layout='auto', figsize=(10, 7))fig.add_subplot(221)plt.title('Rotate 30')plt.imshow(rotate30)fig.add_subplot(222)plt.title('Rotate 45')plt.imshow(rotate45)fig.add_subplot(223)plt.title('Rotate 60')plt.imshow(rotate60)fig.add_subplot(224)plt.title('Rotate 90')plt.imshow(rotate90)plt.show()
# image shearing using sklearn.transform.AffineTransform# try out with differnt values of shear tf = AffineTransform(shear=-0.5)sheared = transform.warp(img, tf, order=1, preserve_range=True, mode='wrap')sheared_fig = plot_side_by_side(img, sheared, 'Original', 'Sheared')
# Image rescaling with sklearn.transform.rescalerescaled = transform.rescale(img, 1.1)rescaled_fig = plot_side_by_side(img, rescaled, 'Original', 'Rescaled')plt.show()print('Original Shape: ',img.shape)print('Rescaled Shape: ',rescaled.shape)Output: Original Shape: (684, 1024, 3)Rescaled Shape: (752, 1126, 3)
# flip up-down using np.flipudup_down = np.flipud(img)fig_updown = plot_side_by_side(img, up_down, 'Original', 'Up-Down')plt.show()
# flip up-down using np.flipudleft_right = np.fliplr(img)fig_lr = plot_side_by_side(img, left_right, 'Original', 'Up-Right')plt.show()
What is Color Augmentation?
Color augmentation is a technique where we play with the intensity value of pixels.
We reproduce different images by tweaking brightness, contrast, saturation, and also we can add random noise to the image.
# Apply Random Noise to image using skimage.utils.random_noisenoised = random_noise(img, var=0.1**2)fig_noised = plot_side_by_side(img, noised, 'Original', 'Noised')plt.show()
# Increasing the brighness of the Image# Note: Here we add 100/255 since we scaled Intensity values of Image when loading (by dividing it 255)highB = img + (100/255)fig_highB = plot_side_by_side(img, highB, 'Original', 'highB')plt.show()
# Increasing the contrast of the Image# Note: Here we add 100/255 since we scaled Intensity values of Image when loading (by dividing it 255)highC = img * 1.5fig_highB = plot_side_by_side(img, highC, 'Original', 'highC')plt.show()
Did you notice one thing, we have already created 11 different images from 1 image. Note we can still play with parameters and create a lot more.
When training neural networks we can add random transformations to the ImageLoader. There are other advanced techniques like using GAN for data augmentation, let us see that in another article. I hope now you understand what is image augmentation.
You can find the notebook at https://github.com/Mathanraj-Sharma/sample-for-medium-article/blob/master/image-augmentation-skimage/image-augmentation.ipynb | [
{
"code": null,
"e": 530,
"s": 171,
"text": "Hey buddies, recently I was working on an image classification problem. But unfortunately, there were not enough samples in one of class. I searched the internet and learned about a technique called image augmentation. Here I have shared my understanding of this technique and shared some codes using skimage. You can find the jupyter notebook at the bottom."
},
{
"code": null,
"e": 695,
"s": 530,
"text": "Image augmentation is a technique used to artificially increase the size of your image dataset. It can be achieved by applying random transformations to your image."
},
{
"code": null,
"e": 880,
"s": 695,
"text": "We know Deep learning models are able to generalize well when they are able to see more data. Data augmentation can create variations of existing images which helps to generalize well."
},
{
"code": null,
"e": 1105,
"s": 880,
"text": "But you need to be careful too. We can use Augmented Images for training but not for testing. So before applying any augmentation split your data into train and testing set. Expand your training data with Image Augmentation."
},
{
"code": null,
"e": 1170,
"s": 1105,
"text": "Image augmentation can be applied mainly on two domains of Image"
},
{
"code": null,
"e": 1210,
"s": 1170,
"text": "Position AugmentationColor Augmentation"
},
{
"code": null,
"e": 1232,
"s": 1210,
"text": "Position Augmentation"
},
{
"code": null,
"e": 1251,
"s": 1232,
"text": "Color Augmentation"
},
{
"code": null,
"e": 1343,
"s": 1251,
"text": "Positon augmentation is simple where we apply different transformations on pixel positions."
},
{
"code": null,
"e": 1548,
"s": 1343,
"text": "Scaling, rotation, cropping, flipping, padding, zoom, translation, shearing, and other affine transformations are examples for the Position Augmentation. Let us try applying some of these transformations."
},
{
"code": null,
"e": 1910,
"s": 1548,
"text": "import numpy as npfrom skimage.io import imread, imsaveimport matplotlib.pyplot as pltfrom skimage import transformfrom skimage.transform import rotate, AffineTransformfrom skimage.util import random_noisefrom skimage.filters import gaussianfrom scipy import ndimage# load Imageimg = imread('./butterfly.jpg') / 255# plot original Imageplt.imshow(img)plt.show()"
},
{
"code": null,
"e": 2403,
"s": 1910,
"text": "# image rotation using skimage.transformation.rotaterotate30 = rotate(img, angle=30)rotate45 = rotate(img, angle=45)rotate60 = rotate(img, angle=60)rotate90 = rotate(img, angle=90)fig = plt.figure(tight_layout='auto', figsize=(10, 7))fig.add_subplot(221)plt.title('Rotate 30')plt.imshow(rotate30)fig.add_subplot(222)plt.title('Rotate 45')plt.imshow(rotate45)fig.add_subplot(223)plt.title('Rotate 60')plt.imshow(rotate60)fig.add_subplot(224)plt.title('Rotate 90')plt.imshow(rotate90)plt.show()"
},
{
"code": null,
"e": 2676,
"s": 2403,
"text": "# image shearing using sklearn.transform.AffineTransform# try out with differnt values of shear tf = AffineTransform(shear=-0.5)sheared = transform.warp(img, tf, order=1, preserve_range=True, mode='wrap')sheared_fig = plot_side_by_side(img, sheared, 'Original', 'Sheared')"
},
{
"code": null,
"e": 2989,
"s": 2676,
"text": "# Image rescaling with sklearn.transform.rescalerescaled = transform.rescale(img, 1.1)rescaled_fig = plot_side_by_side(img, rescaled, 'Original', 'Rescaled')plt.show()print('Original Shape: ',img.shape)print('Rescaled Shape: ',rescaled.shape)Output: Original Shape: (684, 1024, 3)Rescaled Shape: (752, 1126, 3)"
},
{
"code": null,
"e": 3121,
"s": 2989,
"text": "# flip up-down using np.flipudup_down = np.flipud(img)fig_updown = plot_side_by_side(img, up_down, 'Original', 'Up-Down')plt.show()"
},
{
"code": null,
"e": 3256,
"s": 3121,
"text": "# flip up-down using np.flipudleft_right = np.fliplr(img)fig_lr = plot_side_by_side(img, left_right, 'Original', 'Up-Right')plt.show()"
},
{
"code": null,
"e": 3284,
"s": 3256,
"text": "What is Color Augmentation?"
},
{
"code": null,
"e": 3368,
"s": 3284,
"text": "Color augmentation is a technique where we play with the intensity value of pixels."
},
{
"code": null,
"e": 3491,
"s": 3368,
"text": "We reproduce different images by tweaking brightness, contrast, saturation, and also we can add random noise to the image."
},
{
"code": null,
"e": 3667,
"s": 3491,
"text": "# Apply Random Noise to image using skimage.utils.random_noisenoised = random_noise(img, var=0.1**2)fig_noised = plot_side_by_side(img, noised, 'Original', 'Noised')plt.show()"
},
{
"code": null,
"e": 3905,
"s": 3667,
"text": "# Increasing the brighness of the Image# Note: Here we add 100/255 since we scaled Intensity values of Image when loading (by dividing it 255)highB = img + (100/255)fig_highB = plot_side_by_side(img, highB, 'Original', 'highB')plt.show()"
},
{
"code": null,
"e": 4136,
"s": 3905,
"text": "# Increasing the contrast of the Image# Note: Here we add 100/255 since we scaled Intensity values of Image when loading (by dividing it 255)highC = img * 1.5fig_highB = plot_side_by_side(img, highC, 'Original', 'highC')plt.show()"
},
{
"code": null,
"e": 4282,
"s": 4136,
"text": "Did you notice one thing, we have already created 11 different images from 1 image. Note we can still play with parameters and create a lot more."
},
{
"code": null,
"e": 4530,
"s": 4282,
"text": "When training neural networks we can add random transformations to the ImageLoader. There are other advanced techniques like using GAN for data augmentation, let us see that in another article. I hope now you understand what is image augmentation."
}
]
|
What happens when we use COMMIT in MySQL stored procedure and one of the transaction, under START transaction, fails? | Suppose one of the queries fails or generates errors and another query (s) properly executed the MySQL still commit the changes of the properly executed query(s). It can be understood from the following example in which we are using the table ‘employee.tbl’ having the following data −
mysql> Select * from employee.tbl;
+----+---------+
| Id | Name |
+----+---------+
| 1 | Mohan |
| 2 | Gaurav |
| 3 | Sohan |
| 4 | Saurabh |
| 5 | Yash |
+----+---------+
5 rows in set (0.00 sec)
mysql> Delimiter //
mysql> Create Procedure st_transaction_commit_save()
-> BEGIN
-> START TRANSACTION;
-> INSERT INTO employee.tbl (name) values ('Rahul');
-> UPDATE employee.tbl set name = 'Gurdas' WHERE id = 10;
-> COMMIT;
-> END //
Query OK, 0 rows affected (0.00 sec)
Now, when we invoke this procedure, we know that the UPDATE query will produce an error because we do not have id =10 on our table. But as the first query will execute successfully hence the COMMIT will save changes into the table.
mysql> Delimiter ;
mysql> Call st_transaction_commit_save()//
Query OK, 0 rows affected (0.07 sec)
mysql> Select * from employee.tbl;
+----+---------+
| Id | Name |
+----+---------+
| 1 | Mohan |
| 2 | Gaurav |
| 3 | Sohan |
| 4 | Saurabh |
| 5 | Yash |
| 6 | Rahul |
+----+---------+
6 rows in set (0.00 sec) | [
{
"code": null,
"e": 1348,
"s": 1062,
"text": "Suppose one of the queries fails or generates errors and another query (s) properly executed the MySQL still commit the changes of the properly executed query(s). It can be understood from the following example in which we are using the table ‘employee.tbl’ having the following data −"
},
{
"code": null,
"e": 1860,
"s": 1348,
"text": "mysql> Select * from employee.tbl;\n+----+---------+\n| Id | Name |\n+----+---------+\n| 1 | Mohan |\n| 2 | Gaurav |\n| 3 | Sohan |\n| 4 | Saurabh |\n| 5 | Yash |\n+----+---------+\n5 rows in set (0.00 sec)\n\nmysql> Delimiter //\n\nmysql> Create Procedure st_transaction_commit_save()\n -> BEGIN\n -> START TRANSACTION;\n -> INSERT INTO employee.tbl (name) values ('Rahul');\n -> UPDATE employee.tbl set name = 'Gurdas' WHERE id = 10;\n -> COMMIT;\n -> END //\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 2092,
"s": 1860,
"text": "Now, when we invoke this procedure, we know that the UPDATE query will produce an error because we do not have id =10 on our table. But as the first query will execute successfully hence the COMMIT will save changes into the table."
},
{
"code": null,
"e": 2422,
"s": 2092,
"text": "mysql> Delimiter ;\nmysql> Call st_transaction_commit_save()//\nQuery OK, 0 rows affected (0.07 sec)\n\nmysql> Select * from employee.tbl;\n+----+---------+\n| Id | Name |\n+----+---------+\n| 1 | Mohan |\n| 2 | Gaurav |\n| 3 | Sohan |\n| 4 | Saurabh |\n| 5 | Yash |\n| 6 | Rahul |\n+----+---------+\n6 rows in set (0.00 sec)"
}
]
|
C program to calculate power of a given number | Take two integers from the user for base and exponent and calculate the power as explained below.
Consider the following for writing a C program.
Suppose base =3
Exponent = 4
Power=3*3*3*3
Follow the algorithm given below −
Step 1: Declare int and long variables.
Step 2: Enter base value through console.
Step 3: Enter exponent value through console.
Step 4: While loop.
Exponent !=0
i. Value *=base
ii. –exponent
Step 5: Print the result.
The following program explains how to calculate power of given number in C language.
#include<stdio.h>
int main(){
int base, exponent;
long value = 1;
printf("Enter a base value:\n ");
scanf("%d", &base);
printf("Enter an exponent value: ");
scanf("%d", &exponent);
while (exponent != 0){
value *= base;
--exponent;
}
printf("result = %ld", value);
return 0;
}
When the above program is executed, it produces the following result −
Run 1:
Enter a base value:
5
Enter an exponent value: 4
result = 625
Run 2:
Enter a base value:
8
Enter an exponent value: 3
result = 512
If we want to find the power of real numbers, we can use pow function which is a predefined function present in math.h.
#include<math.h>
#include<stdio.h>
int main() {
double base, exponent, value;
printf("Enter a base value: ");
scanf("%lf", &base);
printf("Enter an exponent value: ");
scanf("%lf", &exponent);
// calculates the power
value = pow(base, exponent);
printf("%.1lf^%.1lf = %.2lf", base, exponent, value);
return 0;
}
When the above program is executed, it produces the following result −
Enter a base value: 3.4
Enter an exponent value: 2.3
3.4^2.3 = 16.69 | [
{
"code": null,
"e": 1160,
"s": 1062,
"text": "Take two integers from the user for base and exponent and calculate the power as explained below."
},
{
"code": null,
"e": 1208,
"s": 1160,
"text": "Consider the following for writing a C program."
},
{
"code": null,
"e": 1224,
"s": 1208,
"text": "Suppose base =3"
},
{
"code": null,
"e": 1237,
"s": 1224,
"text": "Exponent = 4"
},
{
"code": null,
"e": 1251,
"s": 1237,
"text": "Power=3*3*3*3"
},
{
"code": null,
"e": 1286,
"s": 1251,
"text": "Follow the algorithm given below −"
},
{
"code": null,
"e": 1509,
"s": 1286,
"text": "Step 1: Declare int and long variables.\nStep 2: Enter base value through console.\nStep 3: Enter exponent value through console.\nStep 4: While loop.\nExponent !=0\n i. Value *=base\n ii. –exponent\nStep 5: Print the result."
},
{
"code": null,
"e": 1594,
"s": 1509,
"text": "The following program explains how to calculate power of given number in C language."
},
{
"code": null,
"e": 1912,
"s": 1594,
"text": "#include<stdio.h>\nint main(){\n int base, exponent;\n long value = 1;\n printf(\"Enter a base value:\\n \");\n scanf(\"%d\", &base);\n printf(\"Enter an exponent value: \");\n scanf(\"%d\", &exponent);\n while (exponent != 0){\n value *= base;\n --exponent;\n }\n printf(\"result = %ld\", value);\n return 0;\n}"
},
{
"code": null,
"e": 1983,
"s": 1912,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2121,
"s": 1983,
"text": "Run 1:\nEnter a base value:\n5\nEnter an exponent value: 4\nresult = 625\nRun 2:\nEnter a base value:\n8\nEnter an exponent value: 3\nresult = 512"
},
{
"code": null,
"e": 2241,
"s": 2121,
"text": "If we want to find the power of real numbers, we can use pow function which is a predefined function present in math.h."
},
{
"code": null,
"e": 2580,
"s": 2241,
"text": "#include<math.h>\n#include<stdio.h>\nint main() {\n double base, exponent, value;\n printf(\"Enter a base value: \");\n scanf(\"%lf\", &base);\n printf(\"Enter an exponent value: \");\n scanf(\"%lf\", &exponent);\n // calculates the power\n value = pow(base, exponent);\n printf(\"%.1lf^%.1lf = %.2lf\", base, exponent, value);\n return 0;\n}"
},
{
"code": null,
"e": 2651,
"s": 2580,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2720,
"s": 2651,
"text": "Enter a base value: 3.4\nEnter an exponent value: 2.3\n3.4^2.3 = 16.69"
}
]
|
Inserting data in table in SAP HANA | Like other database, you can insert rows in column based table in SAP HANA using Insert statement. Insert statement can be written in SQL editor in HANA.
To open SQL editor, you can select HANA system and click on SQL sign at top.
Below SQL statements can be used to insert the data −
INSERT INTO TEST.PROD_DESC VALUES (11,’E’,’Table’);
INSERT INTO TEST.PROD_DESC VALUES (11,’D’,’Chair’);
INSERT INTO TEST.PROD_DESC VALUES (14,’E’,’32 LED’);
INSERT INTO TEST.PROD_DESC VALUES (14,’D’,’32 inch LCD’);
INSERT INTO SAP_STUDENT.PRODUCT_DESC VALUES (25,’E’,’Comp Table’);
INSERT INTO SAP_STUDENT.PRODUCT_DESC VALUES (25,’E’,’Mixer’); | [
{
"code": null,
"e": 1216,
"s": 1062,
"text": "Like other database, you can insert rows in column based table in SAP HANA using Insert statement. Insert statement can be written in SQL editor in HANA."
},
{
"code": null,
"e": 1293,
"s": 1216,
"text": "To open SQL editor, you can select HANA system and click on SQL sign at top."
},
{
"code": null,
"e": 1347,
"s": 1293,
"text": "Below SQL statements can be used to insert the data −"
},
{
"code": null,
"e": 1691,
"s": 1347,
"text": "INSERT INTO TEST.PROD_DESC VALUES (11,’E’,’Table’);\nINSERT INTO TEST.PROD_DESC VALUES (11,’D’,’Chair’);\nINSERT INTO TEST.PROD_DESC VALUES (14,’E’,’32 LED’);\nINSERT INTO TEST.PROD_DESC VALUES (14,’D’,’32 inch LCD’);\nINSERT INTO SAP_STUDENT.PRODUCT_DESC VALUES (25,’E’,’Comp Table’);\nINSERT INTO SAP_STUDENT.PRODUCT_DESC VALUES (25,’E’,’Mixer’);"
}
]
|
Ruby - LDAP Tutorial | Ruby/LDAP is an extension library for Ruby. It provides the interface to some LDAP libraries like OpenLDAP, UMich LDAP, Netscape SDK, ActiveDirectory.
The common API for application development is described in RFC1823 and is supported by Ruby/LDAP.
You can download and install a complete Ruby/LDAP package from SOURCEFORGE.NET.
Before installing Ruby/LDAP, make sure you have the following components −
Ruby 1.8.x (at least 1.8.2 if you want to use ldap/control).
OpenLDAP, Netscape SDK, Windows 2003 or Windows XP.
Now, you can use standard Ruby Installation method. Before starting, if you'd like to see the available options for extconf.rb, run it with '--help' option.
$ ruby extconf.rb [--with-openldap1|--with-openldap2| \
--with-netscape|--with-wldap32]
$ make
$ make install
NOTE − If you're building the software on Windows, you may need to use nmake instead of make.
This is a two-step process −
Following is the syntax to create a connection to a LDAP directory.
LDAP::Conn.new(host = 'localhost', port = LDAP_PORT)
host − This is the host ID running LDAP directory. We will take it as localhost.
host − This is the host ID running LDAP directory. We will take it as localhost.
port − This is the port being used for LDAP service. Standard LDAP ports are 636 and 389. Make sure which port is being used at your server otherwise you can use LDAP::LDAP_PORT.
port − This is the port being used for LDAP service. Standard LDAP ports are 636 and 389. Make sure which port is being used at your server otherwise you can use LDAP::LDAP_PORT.
This call returns a new LDAP::Conn connection to the server, host, on port port.
This is where we usually specify the username and password we will use for the rest of the session.
Following is the syntax to bind an LDAP connection, using the DN, dn, the credential, pwd, and the bind method, method −
conn.bind(dn = nil, password = nil, method = LDAP::LDAP_AUTH_SIMPLE)do
....
end
You can use the same method without a code block. In this case, you would need to unbind the connection explicitly as follows −
conn.bind(dn = nil, password = nil, method = LDAP::LDAP_AUTH_SIMPLE)
....
conn.unbind
If a code block is given, self is yielded to the block.
We can now perform search, add, modify or delete operations inside the block of the bind method (between bind and unbind), provided we have the proper permissions.
Example
Assuming we are working on a local server, let's put things together with appropriate host, domain, user id and password, etc.
#/usr/bin/ruby -w
require 'ldap'
$HOST = 'localhost'
$PORT = LDAP::LDAP_PORT
$SSLPORT = LDAP::LDAPS_PORT
conn = LDAP::Conn.new($HOST, $PORT)
conn.bind('cn = root, dc = localhost, dc = localdomain','secret')
....
conn.unbind
Adding an LDPA entry is a two step process −
We need LDAP::Mod object pass to conn.add method to create an entry. Here is a simple syntax to create LDAP::Mod object −
Mod.new(mod_type, attr, vals)
mod_type − One or more option LDAP_MOD_ADD, LDAP_MOD_REPLACE or LDAP_MOD_DELETE.
mod_type − One or more option LDAP_MOD_ADD, LDAP_MOD_REPLACE or LDAP_MOD_DELETE.
attr − should be the name of the attribute on which to operate.
attr − should be the name of the attribute on which to operate.
vals − is an array of values pertaining to attr. If vals contains binary data, mod_type should be logically OR'ed (|) with LDAP_MOD_BVALUES.
vals − is an array of values pertaining to attr. If vals contains binary data, mod_type should be logically OR'ed (|) with LDAP_MOD_BVALUES.
This call returns LDAP::Mod object, which can be passed to methods in the LDAP::Conn class, such as Conn#add, Conn#add_ext, Conn#modify and Conn#modify_ext.
Once we are ready with LDAP::Mod object, we can call conn.add method to create an entry. Here is a syntax to call this method −
conn.add(dn, attrs)
This method adds an entry with the DN, dn, and the attributes, attrs. Here, attrs should be either an array of LDAP::Mod objects or a hash of attribute/value array pairs.
Example
Here is a complete example, which will create two directory entries −
#/usr/bin/ruby -w
require 'ldap'
$HOST = 'localhost'
$PORT = LDAP::LDAP_PORT
$SSLPORT = LDAP::LDAPS_PORT
conn = LDAP::Conn.new($HOST, $PORT)
conn.bind('cn = root, dc = localhost, dc = localdomain','secret')
conn.perror("bind")
entry1 = [
LDAP.mod(LDAP::LDAP_MOD_ADD,'objectclass',['top','domain']),
LDAP.mod(LDAP::LDAP_MOD_ADD,'o',['TTSKY.NET']),
LDAP.mod(LDAP::LDAP_MOD_ADD,'dc',['localhost']),
]
entry2 = [
LDAP.mod(LDAP::LDAP_MOD_ADD,'objectclass',['top','person']),
LDAP.mod(LDAP::LDAP_MOD_ADD, 'cn', ['Zara Ali']),
LDAP.mod(LDAP::LDAP_MOD_ADD | LDAP::LDAP_MOD_BVALUES, 'sn',
['ttate','ALI', "zero\000zero"]),
]
begin
conn.add("dc = localhost, dc = localdomain", entry1)
conn.add("cn = Zara Ali, dc = localhost, dc = localdomain", entry2)
rescue LDAP::ResultError
conn.perror("add")
exit
end
conn.perror("add")
conn.unbind
Modifying an entry is similar to adding one. Just call the modify method instead of add with the attributes to modify. Here is a simple syntax of modify method.
conn.modify(dn, mods)
This method modifies an entry with the DN, dn, and the attributes, mods. Here, mods should be either an array of LDAP::Mod objects or a hash of attribute/value array pairs.
To modify the surname of the entry, which we added in the previous section, we would write −
#/usr/bin/ruby -w
require 'ldap'
$HOST = 'localhost'
$PORT = LDAP::LDAP_PORT
$SSLPORT = LDAP::LDAPS_PORT
conn = LDAP::Conn.new($HOST, $PORT)
conn.bind('cn = root, dc = localhost, dc = localdomain','secret')
conn.perror("bind")
entry1 = [
LDAP.mod(LDAP::LDAP_MOD_REPLACE, 'sn', ['Mohtashim']),
]
begin
conn.modify("cn = Zara Ali, dc = localhost, dc = localdomain", entry1)
rescue LDAP::ResultError
conn.perror("modify")
exit
end
conn.perror("modify")
conn.unbind
To delete an entry, call the delete method with the distinguished name as parameter. Here is a simple syntax of delete method.
conn.delete(dn)
This method deletes an entry with the DN, dn.
To delete Zara Mohtashim entry, which we added in the previous section, we would write −
#/usr/bin/ruby -w
require 'ldap'
$HOST = 'localhost'
$PORT = LDAP::LDAP_PORT
$SSLPORT = LDAP::LDAPS_PORT
conn = LDAP::Conn.new($HOST, $PORT)
conn.bind('cn = root, dc = localhost, dc = localdomain','secret')
conn.perror("bind")
begin
conn.delete("cn = Zara-Mohtashim, dc = localhost, dc = localdomain")
rescue LDAP::ResultError
conn.perror("delete")
exit
end
conn.perror("delete")
conn.unbind
It's not possible to modify the distinguished name of an entry with the modify method. Instead, use the modrdn method. Here is simple syntax of modrdn method −
conn.modrdn(dn, new_rdn, delete_old_rdn)
This method modifies the RDN of the entry with DN, dn, giving it the new RDN, new_rdn. If delete_old_rdn is true, the old RDN value will be deleted from the entry.
Suppose we have the following entry −
dn: cn = Zara Ali,dc = localhost,dc = localdomain
cn: Zara Ali
sn: Ali
objectclass: person
Then, we can modify its distinguished name with the following code −
#/usr/bin/ruby -w
require 'ldap'
$HOST = 'localhost'
$PORT = LDAP::LDAP_PORT
$SSLPORT = LDAP::LDAPS_PORT
conn = LDAP::Conn.new($HOST, $PORT)
conn.bind('cn = root, dc = localhost, dc = localdomain','secret')
conn.perror("bind")
begin
conn.modrdn("cn = Zara Ali, dc = localhost, dc = localdomain", "cn = Zara Mohtashim", true)
rescue LDAP::ResultError
conn.perror("modrdn")
exit
end
conn.perror("modrdn")
conn.unbind
To perform a search on a LDAP directory, use the search method with one of the three different search modes −
LDAP_SCOPE_BASEM − Search only the base node.
LDAP_SCOPE_BASEM − Search only the base node.
LDAP_SCOPE_ONELEVEL − Search all children of the base node.
LDAP_SCOPE_ONELEVEL − Search all children of the base node.
LDAP_SCOPE_SUBTREE − Search the whole subtree including the base node.
LDAP_SCOPE_SUBTREE − Search the whole subtree including the base node.
Here, we are going to search the whole subtree of entry dc = localhost, dc = localdomain for person objects −
#/usr/bin/ruby -w
require 'ldap'
$HOST = 'localhost'
$PORT = LDAP::LDAP_PORT
$SSLPORT = LDAP::LDAPS_PORT
base = 'dc = localhost,dc = localdomain'
scope = LDAP::LDAP_SCOPE_SUBTREE
filter = '(objectclass = person)'
attrs = ['sn', 'cn']
conn = LDAP::Conn.new($HOST, $PORT)
conn.bind('cn = root, dc = localhost, dc = localdomain','secret')
conn.perror("bind")
begin
conn.search(base, scope, filter, attrs) { |entry|
# print distinguished name
p entry.dn
# print all attribute names
p entry.attrs
# print values of attribute 'sn'
p entry.vals('sn')
# print entry as Hash
p entry.to_hash
}
rescue LDAP::ResultError
conn.perror("search")
exit
end
conn.perror("search")
conn.unbind
This invokes the given code block for each matching entry where the LDAP entry is represented by an instance of the LDAP::Entry class. With the last parameter of search, you can specify the attributes in which you are interested, omitting all others. If you pass nil here, all attributes are returned same as "SELECT *" in relational databases.
The dn method (alias for get_dn) of the LDAP::Entry class returns the distinguished name of the entry, and with the to_hash method, you can get a hash representation of its attributes (including the distinguished name). To get a list of an entry's attributes, use the attrs method (alias for get_attributes). Also, to get the list of one specific attribute's values, use the vals method (alias for get_values).
Ruby/LDAP defines two different exception classes −
In case of an error, the new, bind or unbind methods raise an LDAP::Error exception.
In case of an error, the new, bind or unbind methods raise an LDAP::Error exception.
In case of add, modify, delete or searching an LDAP directory raise an LDAP::ResultError.
In case of add, modify, delete or searching an LDAP directory raise an LDAP::ResultError.
For complete details on LDAP methods, please refer to the standard documentation for LDAP Documentation.
46 Lectures
9.5 hours
Eduonix Learning Solutions
97 Lectures
7.5 hours
Skillbakerystudios
227 Lectures
40 hours
YouAccel
19 Lectures
10 hours
Programming Line
51 Lectures
5 hours
Stone River ELearning
39 Lectures
4.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2445,
"s": 2294,
"text": "Ruby/LDAP is an extension library for Ruby. It provides the interface to some LDAP libraries like OpenLDAP, UMich LDAP, Netscape SDK, ActiveDirectory."
},
{
"code": null,
"e": 2543,
"s": 2445,
"text": "The common API for application development is described in RFC1823 and is supported by Ruby/LDAP."
},
{
"code": null,
"e": 2623,
"s": 2543,
"text": "You can download and install a complete Ruby/LDAP package from SOURCEFORGE.NET."
},
{
"code": null,
"e": 2698,
"s": 2623,
"text": "Before installing Ruby/LDAP, make sure you have the following components −"
},
{
"code": null,
"e": 2759,
"s": 2698,
"text": "Ruby 1.8.x (at least 1.8.2 if you want to use ldap/control)."
},
{
"code": null,
"e": 2811,
"s": 2759,
"text": "OpenLDAP, Netscape SDK, Windows 2003 or Windows XP."
},
{
"code": null,
"e": 2968,
"s": 2811,
"text": "Now, you can use standard Ruby Installation method. Before starting, if you'd like to see the available options for extconf.rb, run it with '--help' option."
},
{
"code": null,
"e": 3098,
"s": 2968,
"text": "$ ruby extconf.rb [--with-openldap1|--with-openldap2| \\\n --with-netscape|--with-wldap32]\n$ make\n$ make install\n"
},
{
"code": null,
"e": 3192,
"s": 3098,
"text": "NOTE − If you're building the software on Windows, you may need to use nmake instead of make."
},
{
"code": null,
"e": 3221,
"s": 3192,
"text": "This is a two-step process −"
},
{
"code": null,
"e": 3289,
"s": 3221,
"text": "Following is the syntax to create a connection to a LDAP directory."
},
{
"code": null,
"e": 3343,
"s": 3289,
"text": "LDAP::Conn.new(host = 'localhost', port = LDAP_PORT)\n"
},
{
"code": null,
"e": 3424,
"s": 3343,
"text": "host − This is the host ID running LDAP directory. We will take it as localhost."
},
{
"code": null,
"e": 3505,
"s": 3424,
"text": "host − This is the host ID running LDAP directory. We will take it as localhost."
},
{
"code": null,
"e": 3684,
"s": 3505,
"text": "port − This is the port being used for LDAP service. Standard LDAP ports are 636 and 389. Make sure which port is being used at your server otherwise you can use LDAP::LDAP_PORT."
},
{
"code": null,
"e": 3863,
"s": 3684,
"text": "port − This is the port being used for LDAP service. Standard LDAP ports are 636 and 389. Make sure which port is being used at your server otherwise you can use LDAP::LDAP_PORT."
},
{
"code": null,
"e": 3944,
"s": 3863,
"text": "This call returns a new LDAP::Conn connection to the server, host, on port port."
},
{
"code": null,
"e": 4044,
"s": 3944,
"text": "This is where we usually specify the username and password we will use for the rest of the session."
},
{
"code": null,
"e": 4165,
"s": 4044,
"text": "Following is the syntax to bind an LDAP connection, using the DN, dn, the credential, pwd, and the bind method, method −"
},
{
"code": null,
"e": 4246,
"s": 4165,
"text": "conn.bind(dn = nil, password = nil, method = LDAP::LDAP_AUTH_SIMPLE)do\n....\nend\n"
},
{
"code": null,
"e": 4374,
"s": 4246,
"text": "You can use the same method without a code block. In this case, you would need to unbind the connection explicitly as follows −"
},
{
"code": null,
"e": 4461,
"s": 4374,
"text": "conn.bind(dn = nil, password = nil, method = LDAP::LDAP_AUTH_SIMPLE)\n....\nconn.unbind\n"
},
{
"code": null,
"e": 4517,
"s": 4461,
"text": "If a code block is given, self is yielded to the block."
},
{
"code": null,
"e": 4681,
"s": 4517,
"text": "We can now perform search, add, modify or delete operations inside the block of the bind method (between bind and unbind), provided we have the proper permissions."
},
{
"code": null,
"e": 4689,
"s": 4681,
"text": "Example"
},
{
"code": null,
"e": 4816,
"s": 4689,
"text": "Assuming we are working on a local server, let's put things together with appropriate host, domain, user id and password, etc."
},
{
"code": null,
"e": 5049,
"s": 4816,
"text": "#/usr/bin/ruby -w\n\nrequire 'ldap'\n\n$HOST = 'localhost'\n$PORT = LDAP::LDAP_PORT\n$SSLPORT = LDAP::LDAPS_PORT\n\nconn = LDAP::Conn.new($HOST, $PORT)\nconn.bind('cn = root, dc = localhost, dc = localdomain','secret')\n....\nconn.unbind"
},
{
"code": null,
"e": 5094,
"s": 5049,
"text": "Adding an LDPA entry is a two step process −"
},
{
"code": null,
"e": 5216,
"s": 5094,
"text": "We need LDAP::Mod object pass to conn.add method to create an entry. Here is a simple syntax to create LDAP::Mod object −"
},
{
"code": null,
"e": 5247,
"s": 5216,
"text": "Mod.new(mod_type, attr, vals)\n"
},
{
"code": null,
"e": 5328,
"s": 5247,
"text": "mod_type − One or more option LDAP_MOD_ADD, LDAP_MOD_REPLACE or LDAP_MOD_DELETE."
},
{
"code": null,
"e": 5409,
"s": 5328,
"text": "mod_type − One or more option LDAP_MOD_ADD, LDAP_MOD_REPLACE or LDAP_MOD_DELETE."
},
{
"code": null,
"e": 5473,
"s": 5409,
"text": "attr − should be the name of the attribute on which to operate."
},
{
"code": null,
"e": 5537,
"s": 5473,
"text": "attr − should be the name of the attribute on which to operate."
},
{
"code": null,
"e": 5678,
"s": 5537,
"text": "vals − is an array of values pertaining to attr. If vals contains binary data, mod_type should be logically OR'ed (|) with LDAP_MOD_BVALUES."
},
{
"code": null,
"e": 5819,
"s": 5678,
"text": "vals − is an array of values pertaining to attr. If vals contains binary data, mod_type should be logically OR'ed (|) with LDAP_MOD_BVALUES."
},
{
"code": null,
"e": 5976,
"s": 5819,
"text": "This call returns LDAP::Mod object, which can be passed to methods in the LDAP::Conn class, such as Conn#add, Conn#add_ext, Conn#modify and Conn#modify_ext."
},
{
"code": null,
"e": 6104,
"s": 5976,
"text": "Once we are ready with LDAP::Mod object, we can call conn.add method to create an entry. Here is a syntax to call this method −"
},
{
"code": null,
"e": 6125,
"s": 6104,
"text": "conn.add(dn, attrs)\n"
},
{
"code": null,
"e": 6296,
"s": 6125,
"text": "This method adds an entry with the DN, dn, and the attributes, attrs. Here, attrs should be either an array of LDAP::Mod objects or a hash of attribute/value array pairs."
},
{
"code": null,
"e": 6304,
"s": 6296,
"text": "Example"
},
{
"code": null,
"e": 6374,
"s": 6304,
"text": "Here is a complete example, which will create two directory entries −"
},
{
"code": null,
"e": 7266,
"s": 6374,
"text": "#/usr/bin/ruby -w\n\nrequire 'ldap'\n\n$HOST = 'localhost'\n$PORT = LDAP::LDAP_PORT\n$SSLPORT = LDAP::LDAPS_PORT\n\nconn = LDAP::Conn.new($HOST, $PORT)\nconn.bind('cn = root, dc = localhost, dc = localdomain','secret')\n\nconn.perror(\"bind\")\nentry1 = [\n LDAP.mod(LDAP::LDAP_MOD_ADD,'objectclass',['top','domain']),\n LDAP.mod(LDAP::LDAP_MOD_ADD,'o',['TTSKY.NET']),\n LDAP.mod(LDAP::LDAP_MOD_ADD,'dc',['localhost']),\n]\n\nentry2 = [\n LDAP.mod(LDAP::LDAP_MOD_ADD,'objectclass',['top','person']),\n LDAP.mod(LDAP::LDAP_MOD_ADD, 'cn', ['Zara Ali']),\n LDAP.mod(LDAP::LDAP_MOD_ADD | LDAP::LDAP_MOD_BVALUES, 'sn', \n ['ttate','ALI', \"zero\\000zero\"]),\n]\n\nbegin\n conn.add(\"dc = localhost, dc = localdomain\", entry1)\n conn.add(\"cn = Zara Ali, dc = localhost, dc = localdomain\", entry2)\nrescue LDAP::ResultError\n conn.perror(\"add\")\n exit\nend\nconn.perror(\"add\")\nconn.unbind"
},
{
"code": null,
"e": 7427,
"s": 7266,
"text": "Modifying an entry is similar to adding one. Just call the modify method instead of add with the attributes to modify. Here is a simple syntax of modify method."
},
{
"code": null,
"e": 7450,
"s": 7427,
"text": "conn.modify(dn, mods)\n"
},
{
"code": null,
"e": 7623,
"s": 7450,
"text": "This method modifies an entry with the DN, dn, and the attributes, mods. Here, mods should be either an array of LDAP::Mod objects or a hash of attribute/value array pairs."
},
{
"code": null,
"e": 7716,
"s": 7623,
"text": "To modify the surname of the entry, which we added in the previous section, we would write −"
},
{
"code": null,
"e": 8201,
"s": 7716,
"text": "#/usr/bin/ruby -w\n\nrequire 'ldap'\n\n$HOST = 'localhost'\n$PORT = LDAP::LDAP_PORT\n$SSLPORT = LDAP::LDAPS_PORT\n\nconn = LDAP::Conn.new($HOST, $PORT)\nconn.bind('cn = root, dc = localhost, dc = localdomain','secret')\n\nconn.perror(\"bind\")\nentry1 = [\n LDAP.mod(LDAP::LDAP_MOD_REPLACE, 'sn', ['Mohtashim']),\n]\n\nbegin\n conn.modify(\"cn = Zara Ali, dc = localhost, dc = localdomain\", entry1)\nrescue LDAP::ResultError\n conn.perror(\"modify\")\n exit\nend\nconn.perror(\"modify\")\nconn.unbind"
},
{
"code": null,
"e": 8328,
"s": 8201,
"text": "To delete an entry, call the delete method with the distinguished name as parameter. Here is a simple syntax of delete method."
},
{
"code": null,
"e": 8345,
"s": 8328,
"text": "conn.delete(dn)\n"
},
{
"code": null,
"e": 8391,
"s": 8345,
"text": "This method deletes an entry with the DN, dn."
},
{
"code": null,
"e": 8480,
"s": 8391,
"text": "To delete Zara Mohtashim entry, which we added in the previous section, we would write −"
},
{
"code": null,
"e": 8891,
"s": 8480,
"text": "#/usr/bin/ruby -w\n\nrequire 'ldap'\n\n$HOST = 'localhost'\n$PORT = LDAP::LDAP_PORT\n$SSLPORT = LDAP::LDAPS_PORT\n\nconn = LDAP::Conn.new($HOST, $PORT)\nconn.bind('cn = root, dc = localhost, dc = localdomain','secret')\n\nconn.perror(\"bind\")\nbegin\n conn.delete(\"cn = Zara-Mohtashim, dc = localhost, dc = localdomain\")\nrescue LDAP::ResultError\n conn.perror(\"delete\")\n exit\nend\nconn.perror(\"delete\")\nconn.unbind"
},
{
"code": null,
"e": 9051,
"s": 8891,
"text": "It's not possible to modify the distinguished name of an entry with the modify method. Instead, use the modrdn method. Here is simple syntax of modrdn method −"
},
{
"code": null,
"e": 9093,
"s": 9051,
"text": "conn.modrdn(dn, new_rdn, delete_old_rdn)\n"
},
{
"code": null,
"e": 9257,
"s": 9093,
"text": "This method modifies the RDN of the entry with DN, dn, giving it the new RDN, new_rdn. If delete_old_rdn is true, the old RDN value will be deleted from the entry."
},
{
"code": null,
"e": 9295,
"s": 9257,
"text": "Suppose we have the following entry −"
},
{
"code": null,
"e": 9386,
"s": 9295,
"text": "dn: cn = Zara Ali,dc = localhost,dc = localdomain\ncn: Zara Ali\nsn: Ali\nobjectclass: person"
},
{
"code": null,
"e": 9455,
"s": 9386,
"text": "Then, we can modify its distinguished name with the following code −"
},
{
"code": null,
"e": 9889,
"s": 9455,
"text": "#/usr/bin/ruby -w\n\nrequire 'ldap'\n\n$HOST = 'localhost'\n$PORT = LDAP::LDAP_PORT\n$SSLPORT = LDAP::LDAPS_PORT\n\nconn = LDAP::Conn.new($HOST, $PORT)\nconn.bind('cn = root, dc = localhost, dc = localdomain','secret')\n\nconn.perror(\"bind\")\nbegin\n conn.modrdn(\"cn = Zara Ali, dc = localhost, dc = localdomain\", \"cn = Zara Mohtashim\", true)\nrescue LDAP::ResultError\n conn.perror(\"modrdn\")\n exit\nend\nconn.perror(\"modrdn\")\nconn.unbind"
},
{
"code": null,
"e": 9999,
"s": 9889,
"text": "To perform a search on a LDAP directory, use the search method with one of the three different search modes −"
},
{
"code": null,
"e": 10045,
"s": 9999,
"text": "LDAP_SCOPE_BASEM − Search only the base node."
},
{
"code": null,
"e": 10091,
"s": 10045,
"text": "LDAP_SCOPE_BASEM − Search only the base node."
},
{
"code": null,
"e": 10151,
"s": 10091,
"text": "LDAP_SCOPE_ONELEVEL − Search all children of the base node."
},
{
"code": null,
"e": 10211,
"s": 10151,
"text": "LDAP_SCOPE_ONELEVEL − Search all children of the base node."
},
{
"code": null,
"e": 10282,
"s": 10211,
"text": "LDAP_SCOPE_SUBTREE − Search the whole subtree including the base node."
},
{
"code": null,
"e": 10353,
"s": 10282,
"text": "LDAP_SCOPE_SUBTREE − Search the whole subtree including the base node."
},
{
"code": null,
"e": 10463,
"s": 10353,
"text": "Here, we are going to search the whole subtree of entry dc = localhost, dc = localdomain for person objects −"
},
{
"code": null,
"e": 11208,
"s": 10463,
"text": "#/usr/bin/ruby -w\n\nrequire 'ldap'\n\n$HOST = 'localhost'\n$PORT = LDAP::LDAP_PORT\n$SSLPORT = LDAP::LDAPS_PORT\n\nbase = 'dc = localhost,dc = localdomain'\nscope = LDAP::LDAP_SCOPE_SUBTREE\nfilter = '(objectclass = person)'\nattrs = ['sn', 'cn']\n\nconn = LDAP::Conn.new($HOST, $PORT)\nconn.bind('cn = root, dc = localhost, dc = localdomain','secret')\n\nconn.perror(\"bind\")\nbegin\n conn.search(base, scope, filter, attrs) { |entry|\n # print distinguished name\n p entry.dn\n # print all attribute names\n p entry.attrs\n # print values of attribute 'sn'\n p entry.vals('sn')\n # print entry as Hash\n p entry.to_hash\n }\nrescue LDAP::ResultError\n conn.perror(\"search\")\n exit\nend\nconn.perror(\"search\")\nconn.unbind"
},
{
"code": null,
"e": 11553,
"s": 11208,
"text": "This invokes the given code block for each matching entry where the LDAP entry is represented by an instance of the LDAP::Entry class. With the last parameter of search, you can specify the attributes in which you are interested, omitting all others. If you pass nil here, all attributes are returned same as \"SELECT *\" in relational databases."
},
{
"code": null,
"e": 11964,
"s": 11553,
"text": "The dn method (alias for get_dn) of the LDAP::Entry class returns the distinguished name of the entry, and with the to_hash method, you can get a hash representation of its attributes (including the distinguished name). To get a list of an entry's attributes, use the attrs method (alias for get_attributes). Also, to get the list of one specific attribute's values, use the vals method (alias for get_values)."
},
{
"code": null,
"e": 12016,
"s": 11964,
"text": "Ruby/LDAP defines two different exception classes −"
},
{
"code": null,
"e": 12101,
"s": 12016,
"text": "In case of an error, the new, bind or unbind methods raise an LDAP::Error exception."
},
{
"code": null,
"e": 12186,
"s": 12101,
"text": "In case of an error, the new, bind or unbind methods raise an LDAP::Error exception."
},
{
"code": null,
"e": 12276,
"s": 12186,
"text": "In case of add, modify, delete or searching an LDAP directory raise an LDAP::ResultError."
},
{
"code": null,
"e": 12366,
"s": 12276,
"text": "In case of add, modify, delete or searching an LDAP directory raise an LDAP::ResultError."
},
{
"code": null,
"e": 12471,
"s": 12366,
"text": "For complete details on LDAP methods, please refer to the standard documentation for LDAP Documentation."
},
{
"code": null,
"e": 12506,
"s": 12471,
"text": "\n 46 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 12534,
"s": 12506,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 12569,
"s": 12534,
"text": "\n 97 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 12589,
"s": 12569,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 12624,
"s": 12589,
"text": "\n 227 Lectures \n 40 hours \n"
},
{
"code": null,
"e": 12634,
"s": 12624,
"text": " YouAccel"
},
{
"code": null,
"e": 12668,
"s": 12634,
"text": "\n 19 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 12686,
"s": 12668,
"text": " Programming Line"
},
{
"code": null,
"e": 12719,
"s": 12686,
"text": "\n 51 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 12742,
"s": 12719,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 12777,
"s": 12742,
"text": "\n 39 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12800,
"s": 12777,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 12807,
"s": 12800,
"text": " Print"
},
{
"code": null,
"e": 12818,
"s": 12807,
"text": " Add Notes"
}
]
|
ArrayDeque peekFirst() Method in Java - GeeksforGeeks | 10 Dec, 2018
The java.util.ArrayDeque.peekFirst() method in Java is used to retrieve or fetch the first element of the deque. The element retrieved does not get deleted or removed from the Queue instead the method just returns it. If no element is present in the deque or it is empty, then Null is returned.
Syntax:
Array_Deque.peekFirst()
Parameters: The method does not take any parameter.
Return Value: The method returns the first element of the Deque.
Below programs illustrate the Java.util.ArrayDeque.peekFirst() method:Program 1:
// Java code to illustrate peekFirst()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add("Welcome"); de_que.add("To"); de_que.add("Geeks"); de_que.add("4"); de_que.add("Geeks"); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Displaying the first element System.out.println("The first element is: " + de_que.peekFirst()); // Displaying the ArrayDeque after operation System.out.println("Final ArrayDeque: " + de_que); }}
Initial ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
The first element is: Welcome
Final ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
Program 2:
// Java code to illustrate peekFirst()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println("Initial ArrayDeque: " + de_que); // Displaying the first element System.out.println("The first element is: " + de_que.peekFirst()); // Displaying the ArrayDeque after operation System.out.println("Final ArrayDeque: " + de_que); }}
Initial ArrayDeque: [10, 15, 30, 20, 5]
The first element is: 10
Final ArrayDeque: [10, 15, 30, 20, 5]
Program 3: For an empty deque:
// Java code to illustrate peekFirst()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque ArrayDeque<Integer> de_que = new ArrayDeque<Integer>(); // Displaying the ArrayDeque System.out.println("ArrayDeque: " + de_que); // Displaying the first element System.out.println("The first element is: " + de_que.peekFirst()); }}
ArrayDeque: []
The first element is: null
Java - util package
Java-ArrayDeque
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
Reverse a string in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java | [
{
"code": null,
"e": 25397,
"s": 25369,
"text": "\n10 Dec, 2018"
},
{
"code": null,
"e": 25692,
"s": 25397,
"text": "The java.util.ArrayDeque.peekFirst() method in Java is used to retrieve or fetch the first element of the deque. The element retrieved does not get deleted or removed from the Queue instead the method just returns it. If no element is present in the deque or it is empty, then Null is returned."
},
{
"code": null,
"e": 25700,
"s": 25692,
"text": "Syntax:"
},
{
"code": null,
"e": 25724,
"s": 25700,
"text": "Array_Deque.peekFirst()"
},
{
"code": null,
"e": 25776,
"s": 25724,
"text": "Parameters: The method does not take any parameter."
},
{
"code": null,
"e": 25841,
"s": 25776,
"text": "Return Value: The method returns the first element of the Deque."
},
{
"code": null,
"e": 25922,
"s": 25841,
"text": "Below programs illustrate the Java.util.ArrayDeque.peekFirst() method:Program 1:"
},
{
"code": "// Java code to illustrate peekFirst()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<String> de_que = new ArrayDeque<String>(); // Use add() method to add elements into the Deque de_que.add(\"Welcome\"); de_que.add(\"To\"); de_que.add(\"Geeks\"); de_que.add(\"4\"); de_que.add(\"Geeks\"); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Displaying the first element System.out.println(\"The first element is: \" + de_que.peekFirst()); // Displaying the ArrayDeque after operation System.out.println(\"Final ArrayDeque: \" + de_que); }}",
"e": 26722,
"s": 25922,
"text": null
},
{
"code": null,
"e": 26853,
"s": 26722,
"text": "Initial ArrayDeque: [Welcome, To, Geeks, 4, Geeks]\nThe first element is: Welcome\nFinal ArrayDeque: [Welcome, To, Geeks, 4, Geeks]\n"
},
{
"code": null,
"e": 26864,
"s": 26853,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate peekFirst()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque Deque<Integer> de_que = new ArrayDeque<Integer>(); // Use add() method to add elements into the Deque de_que.add(10); de_que.add(15); de_que.add(30); de_que.add(20); de_que.add(5); // Displaying the ArrayDeque System.out.println(\"Initial ArrayDeque: \" + de_que); // Displaying the first element System.out.println(\"The first element is: \" + de_que.peekFirst()); // Displaying the ArrayDeque after operation System.out.println(\"Final ArrayDeque: \" + de_que); }}",
"e": 27645,
"s": 26864,
"text": null
},
{
"code": null,
"e": 27749,
"s": 27645,
"text": "Initial ArrayDeque: [10, 15, 30, 20, 5]\nThe first element is: 10\nFinal ArrayDeque: [10, 15, 30, 20, 5]\n"
},
{
"code": null,
"e": 27780,
"s": 27749,
"text": "Program 3: For an empty deque:"
},
{
"code": "// Java code to illustrate peekFirst()import java.util.*; public class ArrayDequeDemo { public static void main(String args[]) { // Creating an empty ArrayDeque ArrayDeque<Integer> de_que = new ArrayDeque<Integer>(); // Displaying the ArrayDeque System.out.println(\"ArrayDeque: \" + de_que); // Displaying the first element System.out.println(\"The first element is: \" + de_que.peekFirst()); }}",
"e": 28266,
"s": 27780,
"text": null
},
{
"code": null,
"e": 28309,
"s": 28266,
"text": "ArrayDeque: []\nThe first element is: null\n"
},
{
"code": null,
"e": 28329,
"s": 28309,
"text": "Java - util package"
},
{
"code": null,
"e": 28345,
"s": 28329,
"text": "Java-ArrayDeque"
},
{
"code": null,
"e": 28362,
"s": 28345,
"text": "Java-Collections"
},
{
"code": null,
"e": 28377,
"s": 28362,
"text": "Java-Functions"
},
{
"code": null,
"e": 28382,
"s": 28377,
"text": "Java"
},
{
"code": null,
"e": 28387,
"s": 28382,
"text": "Java"
},
{
"code": null,
"e": 28404,
"s": 28387,
"text": "Java-Collections"
},
{
"code": null,
"e": 28502,
"s": 28404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28517,
"s": 28502,
"text": "Arrays in Java"
},
{
"code": null,
"e": 28561,
"s": 28517,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 28583,
"s": 28561,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 28634,
"s": 28583,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28670,
"s": 28634,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 28695,
"s": 28670,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 28725,
"s": 28695,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28744,
"s": 28725,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28759,
"s": 28744,
"text": "Stream In Java"
}
]
|
Largest right circular cone that can be inscribed within a sphere - GeeksforGeeks | 17 Mar, 2021
Given sphere of radius . The task is to find the radius of base and height of the largest right circular cone that can be inscribed within it.Examples:
Input : R = 10
Output : r = 9.42809, h = 13.3333
Input : R = 25
Output : r = 23.5702, h = 33.3333
Approach:Let the radius of the cone = r height of the cone = hFrom the diagram it is clear that: x = √(R^2 – r^2) and h=x+R Now using these values we get,
To maximize the volume of the cone(V): V = (πr2h)/3From the diagram, V = (πr2R)/3 + πr2√(R2 – r2)/3Taking first derivative of V with respect to r we get, Now, setting dV/dr = 0 we get, Squaring both sides and solving we get, since, h = R + √(R2 – r2)Now calculating the second derivative we get
*** QuickLaTeX cannot compile formula:
*** Error message:
Error: Nothing to show, formula is empty
Thus r=(2R√2)/3 is point of maxima So, h = 4R/3
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find the biggest cone// that can be inscribed within a sphere#include <bits/stdc++.h>using namespace std; // Function to find the radius of the conefloat coner(float R){ // radius cannot be negative if (R < 0) return -1; // radius of the cone float r = (2 * sqrt(2) * R) / 3; return r;} // Function to find the height of the conefloat coneh(float R){ // side cannot be negative if (R < 0) return -1; // height of the cone float h = (4 * R) / 3; return h;} // Driver codeint main(){ float R = 10; cout << "r = " << coner(R) << ", " << "h = " << coneh(R) << endl; return 0;}
// Java Program to find the biggest cone// that can be inscribed within a sphereimport java.util.*;import java.lang.*; class GFG{// Function to find the radius// of the conestatic float coner(float R){ // radius cannot be negative if (R < 0) return -1; // radius of the cone float r = (float)(2 * Math.sqrt(2) * R) / 3; return r;} // Function to find the// height of the conestatic float coneh(float R){ // side cannot be negative if (R < 0) return -1; // height of the cone float h = (4 * R) / 3; return h;} // Driver codepublic static void main(String args[]){ float R = 10; System.out.println("r = " + coner(R) + ", " + "h = " + coneh(R));}} // This code is contributed// by Akanksha Rai
# Python 3 Program to find the biggest cone# that can be inscribed within a sphereimport math # Function to find the radius# of the conedef coner(R): # radius cannot be negative if (R < 0): return -1; # radius of the cone r = (2 * math.sqrt(2) * R) / 3 return float(r) # Function to find the height# of the conedef coneh(R): # side cannot be negative if (R < 0): return -1; # height of the cone h = (4 * R) / 3 return float(h) # Driver codeR = 10print("r = " , coner(R) , ", ", "h = " , coneh(R)) # This code is contributed# by 29AjayKumar
// C# Program to find the biggest cone// that can be inscribed within a sphereusing System; class GFG{// Function to find the radius// of the conestatic float coner(float R){ // radius cannot be negative if (R < 0) return -1; // radius of the cone float r = (float)(2 * Math.Sqrt(2) * R) / 3; return r;} // Function to find the// height of the conestatic float coneh(float R){ // side cannot be negative if (R < 0) return -1; // height of the cone float h = (4 * R) / 3; return h;} // Driver codepublic static void Main(){ float R = 10; Console.WriteLine("r = " + coner(R) + ", " + "h = " + coneh(R));}} // This code is contributed// by Akanksha Rai
<?php// PHP Program to find the biggest// cone that can be inscribed// within a sphere // Function to find the radius// of the conefunction coner($R){ // radius cannot be negative if ($R < 0) return -1; // radius of the cone $r = (2 * sqrt(2) * $R) / 3; return $r;} // Function to find the height// of the conefunction coneh($R){ // side cannot be negative if ($R < 0) return -1; // height of the cone $h = (4 * $R) / 3; return $h;} // Driver code$R = 10; echo ("r = ");echo coner($R);echo (", ");echo ("h = ");echo (coneh($R)); // This code is contributed// by Shivi_Aggarwal?>
<script>// javascript Program to find the biggest cone// that can be inscribed within a sphere // Function to find the radius// of the conefunction coner(R){ // radius cannot be negative if (R < 0) return -1; // radius of the cone var r = (2 * Math.sqrt(2) * R) / 3; return r;} // Function to find the// height of the conefunction coneh(R){ // side cannot be negative if (R < 0) return -1; // height of the cone var h = (4 * R) / 3; return h;} // Driver codevar R = 10;document.write("r = " + coner(R).toFixed(5) + ", " + "h = " + coneh(R).toFixed(5)); // This code is contributed by 29AjayKumar</script>
r = 9.42809, h = 13.3333
Shivi_Aggarwal
Akanksha_Rai
29AjayKumar
mohitg593
circle
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Haversine formula to find distance between two points on a sphere
Program to find slope of a line
Equation of circle when three points on the circle are given
Program to find line passing through 2 Points
Maximum Manhattan distance between a distinct pair from N coordinates
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26561,
"s": 26533,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 26715,
"s": 26561,
"text": "Given sphere of radius . The task is to find the radius of base and height of the largest right circular cone that can be inscribed within it.Examples: "
},
{
"code": null,
"e": 26814,
"s": 26715,
"text": "Input : R = 10\nOutput : r = 9.42809, h = 13.3333\n\nInput : R = 25\nOutput : r = 23.5702, h = 33.3333"
},
{
"code": null,
"e": 26975,
"s": 26818,
"text": "Approach:Let the radius of the cone = r height of the cone = hFrom the diagram it is clear that: x = √(R^2 – r^2) and h=x+R Now using these values we get, "
},
{
"code": null,
"e": 27271,
"s": 26975,
"text": "To maximize the volume of the cone(V): V = (πr2h)/3From the diagram, V = (πr2R)/3 + πr2√(R2 – r2)/3Taking first derivative of V with respect to r we get, Now, setting dV/dr = 0 we get, Squaring both sides and solving we get, since, h = R + √(R2 – r2)Now calculating the second derivative we get "
},
{
"code": null,
"e": 27374,
"s": 27271,
"text": "*** QuickLaTeX cannot compile formula:\n \n\n*** Error message:\nError: Nothing to show, formula is empty\n"
},
{
"code": null,
"e": 27424,
"s": 27374,
"text": "Thus r=(2R√2)/3 is point of maxima So, h = 4R/3 "
},
{
"code": null,
"e": 27477,
"s": 27424,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27481,
"s": 27477,
"text": "C++"
},
{
"code": null,
"e": 27486,
"s": 27481,
"text": "Java"
},
{
"code": null,
"e": 27494,
"s": 27486,
"text": "Python3"
},
{
"code": null,
"e": 27497,
"s": 27494,
"text": "C#"
},
{
"code": null,
"e": 27501,
"s": 27497,
"text": "PHP"
},
{
"code": null,
"e": 27512,
"s": 27501,
"text": "Javascript"
},
{
"code": "// C++ Program to find the biggest cone// that can be inscribed within a sphere#include <bits/stdc++.h>using namespace std; // Function to find the radius of the conefloat coner(float R){ // radius cannot be negative if (R < 0) return -1; // radius of the cone float r = (2 * sqrt(2) * R) / 3; return r;} // Function to find the height of the conefloat coneh(float R){ // side cannot be negative if (R < 0) return -1; // height of the cone float h = (4 * R) / 3; return h;} // Driver codeint main(){ float R = 10; cout << \"r = \" << coner(R) << \", \" << \"h = \" << coneh(R) << endl; return 0;}",
"e": 28170,
"s": 27512,
"text": null
},
{
"code": "// Java Program to find the biggest cone// that can be inscribed within a sphereimport java.util.*;import java.lang.*; class GFG{// Function to find the radius// of the conestatic float coner(float R){ // radius cannot be negative if (R < 0) return -1; // radius of the cone float r = (float)(2 * Math.sqrt(2) * R) / 3; return r;} // Function to find the// height of the conestatic float coneh(float R){ // side cannot be negative if (R < 0) return -1; // height of the cone float h = (4 * R) / 3; return h;} // Driver codepublic static void main(String args[]){ float R = 10; System.out.println(\"r = \" + coner(R) + \", \" + \"h = \" + coneh(R));}} // This code is contributed// by Akanksha Rai",
"e": 28948,
"s": 28170,
"text": null
},
{
"code": "# Python 3 Program to find the biggest cone# that can be inscribed within a sphereimport math # Function to find the radius# of the conedef coner(R): # radius cannot be negative if (R < 0): return -1; # radius of the cone r = (2 * math.sqrt(2) * R) / 3 return float(r) # Function to find the height# of the conedef coneh(R): # side cannot be negative if (R < 0): return -1; # height of the cone h = (4 * R) / 3 return float(h) # Driver codeR = 10print(\"r = \" , coner(R) , \", \", \"h = \" , coneh(R)) # This code is contributed# by 29AjayKumar",
"e": 29553,
"s": 28948,
"text": null
},
{
"code": "// C# Program to find the biggest cone// that can be inscribed within a sphereusing System; class GFG{// Function to find the radius// of the conestatic float coner(float R){ // radius cannot be negative if (R < 0) return -1; // radius of the cone float r = (float)(2 * Math.Sqrt(2) * R) / 3; return r;} // Function to find the// height of the conestatic float coneh(float R){ // side cannot be negative if (R < 0) return -1; // height of the cone float h = (4 * R) / 3; return h;} // Driver codepublic static void Main(){ float R = 10; Console.WriteLine(\"r = \" + coner(R) + \", \" + \"h = \" + coneh(R));}} // This code is contributed// by Akanksha Rai",
"e": 30292,
"s": 29553,
"text": null
},
{
"code": "<?php// PHP Program to find the biggest// cone that can be inscribed// within a sphere // Function to find the radius// of the conefunction coner($R){ // radius cannot be negative if ($R < 0) return -1; // radius of the cone $r = (2 * sqrt(2) * $R) / 3; return $r;} // Function to find the height// of the conefunction coneh($R){ // side cannot be negative if ($R < 0) return -1; // height of the cone $h = (4 * $R) / 3; return $h;} // Driver code$R = 10; echo (\"r = \");echo coner($R);echo (\", \");echo (\"h = \");echo (coneh($R)); // This code is contributed// by Shivi_Aggarwal?>",
"e": 30919,
"s": 30292,
"text": null
},
{
"code": "<script>// javascript Program to find the biggest cone// that can be inscribed within a sphere // Function to find the radius// of the conefunction coner(R){ // radius cannot be negative if (R < 0) return -1; // radius of the cone var r = (2 * Math.sqrt(2) * R) / 3; return r;} // Function to find the// height of the conefunction coneh(R){ // side cannot be negative if (R < 0) return -1; // height of the cone var h = (4 * R) / 3; return h;} // Driver codevar R = 10;document.write(\"r = \" + coner(R).toFixed(5) + \", \" + \"h = \" + coneh(R).toFixed(5)); // This code is contributed by 29AjayKumar</script>",
"e": 31601,
"s": 30919,
"text": null
},
{
"code": null,
"e": 31626,
"s": 31601,
"text": "r = 9.42809, h = 13.3333"
},
{
"code": null,
"e": 31643,
"s": 31628,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 31656,
"s": 31643,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31668,
"s": 31656,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31678,
"s": 31668,
"text": "mohitg593"
},
{
"code": null,
"e": 31685,
"s": 31678,
"text": "circle"
},
{
"code": null,
"e": 31695,
"s": 31685,
"text": "Geometric"
},
{
"code": null,
"e": 31708,
"s": 31695,
"text": "Mathematical"
},
{
"code": null,
"e": 31721,
"s": 31708,
"text": "Mathematical"
},
{
"code": null,
"e": 31731,
"s": 31721,
"text": "Geometric"
},
{
"code": null,
"e": 31829,
"s": 31731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31895,
"s": 31829,
"text": "Haversine formula to find distance between two points on a sphere"
},
{
"code": null,
"e": 31927,
"s": 31895,
"text": "Program to find slope of a line"
},
{
"code": null,
"e": 31988,
"s": 31927,
"text": "Equation of circle when three points on the circle are given"
},
{
"code": null,
"e": 32034,
"s": 31988,
"text": "Program to find line passing through 2 Points"
},
{
"code": null,
"e": 32104,
"s": 32034,
"text": "Maximum Manhattan distance between a distinct pair from N coordinates"
},
{
"code": null,
"e": 32134,
"s": 32104,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32194,
"s": 32134,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32209,
"s": 32194,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32252,
"s": 32209,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
Sum of all the multiples of 3 and 7 below N - GeeksforGeeks | 05 Apr, 2021
Given a number N, the task is to find the sum of all the multiples of 3 and 7 below N. Note: A number must not repeat itself in the sum.
Examples:
Input: N = 10 Output: 25 3 + 6 + 7 + 9 = 25
Input: N = 24 Output: 105 3 + 6 + 7 + 9 + 12 + 14 + 15 + 18 + 21 = 105
Approach:
We know that multiples of 3 form an AP as S3 = 3 + 6 + 9 + 12 + 15 + 18 + 21 + ...
And the multiples of 7 form an AP as S7 = 7 + 14 + 21 + 28 + ...
Now, Sum = S3 + S7 i.e. 3 + 6 + 7 + 9 + 12 + 14 + 15 + 18 + 21 + 21 + ...
From the previous step, 21 is repeated twice. In fact, all of the multiples of 21 (or 3*7) will be repeated as they are counted twice, once in the series S3 and again in the series S7. So, the multiples of 21 need to be discarded from the result.
So, the final result will be S3 + S7 – S21
The formula for the sum of an AP series is : n * ( a + l ) / 2 Where n is the number of terms, a is the starting term, and l is the last term.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the sum of all// multiples of 3 and 7 below N #include <bits/stdc++.h>using namespace std; // Function to find sum of AP serieslong long sumAP(long long n, long long d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of 3 and 7 below Nlong long sumMultiples(long long n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 3) + sumAP(n, 7) - sumAP(n, 21);} // Driver codeint main(){ long long n = 24; cout << sumMultiples(n); return 0;}
// Java program to find the sum of all// multiples of 3 and 7 below Nimport java.util.*; class solution{ // Function to find sum of AP seriesstatic long sumAP(long n, long d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of 3 and 7 below Nstatic long sumMultiples(long n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 3) + sumAP(n, 7) - sumAP(n, 21);} // Driver codepublic static void main(String args[]){ long n = 24; System.out.println(sumMultiples(n)); }} //This code is contributed by Surendra_Gangwar
# Python3 program to find the sum of# all multiples of 3 and 7 below N # Function to find sum of AP seriesdef sumAP(n, d): # Number of terms n = int(n / d); return (n) * (1 + n) * (d / 2); # Function to find the sum of all# multiples of 3 and 7 below Ndef sumMultiples(n): # Since, we need the sum of # multiples less than N n -= 1; return int(sumAP(n, 3) + sumAP(n, 7) - sumAP(n, 21)); # Driver coden = 24; print(sumMultiples(n)); # This code is contributed# by mits
// C# program to find the sum of all// multiples of 3 and 7 below Nusing System; class GFG{ // Function to find sum of AP seriesstatic long sumAP(long n, long d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of 3 and 7 below Nstatic long sumMultiples(long n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 3) + sumAP(n, 7) - sumAP(n, 21);} // Driver codestatic public void Main(String []args){ long n = 24; Console.WriteLine(sumMultiples(n));}} // This code is contributed// by Arnab Kundu
<?php// PHP program to find the sum of all// multiples of 3 and 7 below N // Function to find sum of AP seriesfunction sumAP($n, $d){ // Number of terms $n = (int)($n / $d); return ($n) * (1 + $n) * ($d / 2);} // Function to find the sum of all// multiples of 3 and 7 below Nfunction sumMultiples($n){ // Since, we need the sum of // multiples less than N $n--; return sumAP($n, 3) + sumAP($n, 7) - sumAP($n, 21);} // Driver code$n = 24; echo sumMultiples($n); // This code is contributed// by Akanksha Rai?>
<script> // JavaScript program to find the sum of all// multiples of 3 and 7 below N // Function to find sum of AP seriesfunction sumAP(n, d){ // Number of terms n = parseInt(n / d); return (n) * (1 + n) * (d / 2);} // Function to find the sum of all// multiples of 3 and 7 below Nfunction sumMultiples(n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 3) + sumAP(n, 7) - sumAP(n, 21);} // Driver codelet n = 24; document.write(sumMultiples(n)); // This code is contributed by mohan1240760 </script>
105
SURENDRA_GANGWAR
andrew1234
Akanksha_Rai
Mithun Kumar
pulamolusaimohan
divisibility
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multistage Graph (Shortest Path)
Breadth First Traversal ( BFS ) on a 2D array
Shortest path in a directed graph by Dijkstra’s algorithm
5 Best Books for Competitive Programming
Check whether bitwise AND of a number with any subset of an array is zero or not
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 26333,
"s": 26305,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 26470,
"s": 26333,
"text": "Given a number N, the task is to find the sum of all the multiples of 3 and 7 below N. Note: A number must not repeat itself in the sum."
},
{
"code": null,
"e": 26482,
"s": 26470,
"text": "Examples: "
},
{
"code": null,
"e": 26526,
"s": 26482,
"text": "Input: N = 10 Output: 25 3 + 6 + 7 + 9 = 25"
},
{
"code": null,
"e": 26598,
"s": 26526,
"text": "Input: N = 24 Output: 105 3 + 6 + 7 + 9 + 12 + 14 + 15 + 18 + 21 = 105 "
},
{
"code": null,
"e": 26610,
"s": 26598,
"text": "Approach: "
},
{
"code": null,
"e": 26693,
"s": 26610,
"text": "We know that multiples of 3 form an AP as S3 = 3 + 6 + 9 + 12 + 15 + 18 + 21 + ..."
},
{
"code": null,
"e": 26758,
"s": 26693,
"text": "And the multiples of 7 form an AP as S7 = 7 + 14 + 21 + 28 + ..."
},
{
"code": null,
"e": 26832,
"s": 26758,
"text": "Now, Sum = S3 + S7 i.e. 3 + 6 + 7 + 9 + 12 + 14 + 15 + 18 + 21 + 21 + ..."
},
{
"code": null,
"e": 27079,
"s": 26832,
"text": "From the previous step, 21 is repeated twice. In fact, all of the multiples of 21 (or 3*7) will be repeated as they are counted twice, once in the series S3 and again in the series S7. So, the multiples of 21 need to be discarded from the result."
},
{
"code": null,
"e": 27122,
"s": 27079,
"text": "So, the final result will be S3 + S7 – S21"
},
{
"code": null,
"e": 27267,
"s": 27122,
"text": "The formula for the sum of an AP series is : n * ( a + l ) / 2 Where n is the number of terms, a is the starting term, and l is the last term. "
},
{
"code": null,
"e": 27320,
"s": 27267,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27324,
"s": 27320,
"text": "C++"
},
{
"code": null,
"e": 27329,
"s": 27324,
"text": "Java"
},
{
"code": null,
"e": 27337,
"s": 27329,
"text": "Python3"
},
{
"code": null,
"e": 27340,
"s": 27337,
"text": "C#"
},
{
"code": null,
"e": 27344,
"s": 27340,
"text": "PHP"
},
{
"code": null,
"e": 27355,
"s": 27344,
"text": "Javascript"
},
{
"code": "// C++ program to find the sum of all// multiples of 3 and 7 below N #include <bits/stdc++.h>using namespace std; // Function to find sum of AP serieslong long sumAP(long long n, long long d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of 3 and 7 below Nlong long sumMultiples(long long n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 3) + sumAP(n, 7) - sumAP(n, 21);} // Driver codeint main(){ long long n = 24; cout << sumMultiples(n); return 0;}",
"e": 27931,
"s": 27355,
"text": null
},
{
"code": "// Java program to find the sum of all// multiples of 3 and 7 below Nimport java.util.*; class solution{ // Function to find sum of AP seriesstatic long sumAP(long n, long d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of 3 and 7 below Nstatic long sumMultiples(long n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 3) + sumAP(n, 7) - sumAP(n, 21);} // Driver codepublic static void main(String args[]){ long n = 24; System.out.println(sumMultiples(n)); }} //This code is contributed by Surendra_Gangwar",
"e": 28558,
"s": 27931,
"text": null
},
{
"code": "# Python3 program to find the sum of# all multiples of 3 and 7 below N # Function to find sum of AP seriesdef sumAP(n, d): # Number of terms n = int(n / d); return (n) * (1 + n) * (d / 2); # Function to find the sum of all# multiples of 3 and 7 below Ndef sumMultiples(n): # Since, we need the sum of # multiples less than N n -= 1; return int(sumAP(n, 3) + sumAP(n, 7) - sumAP(n, 21)); # Driver coden = 24; print(sumMultiples(n)); # This code is contributed# by mits",
"e": 29083,
"s": 28558,
"text": null
},
{
"code": "// C# program to find the sum of all// multiples of 3 and 7 below Nusing System; class GFG{ // Function to find sum of AP seriesstatic long sumAP(long n, long d){ // Number of terms n /= d; return (n) * (1 + n) * d / 2;} // Function to find the sum of all// multiples of 3 and 7 below Nstatic long sumMultiples(long n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 3) + sumAP(n, 7) - sumAP(n, 21);} // Driver codestatic public void Main(String []args){ long n = 24; Console.WriteLine(sumMultiples(n));}} // This code is contributed// by Arnab Kundu",
"e": 29716,
"s": 29083,
"text": null
},
{
"code": "<?php// PHP program to find the sum of all// multiples of 3 and 7 below N // Function to find sum of AP seriesfunction sumAP($n, $d){ // Number of terms $n = (int)($n / $d); return ($n) * (1 + $n) * ($d / 2);} // Function to find the sum of all// multiples of 3 and 7 below Nfunction sumMultiples($n){ // Since, we need the sum of // multiples less than N $n--; return sumAP($n, 3) + sumAP($n, 7) - sumAP($n, 21);} // Driver code$n = 24; echo sumMultiples($n); // This code is contributed// by Akanksha Rai?>",
"e": 30258,
"s": 29716,
"text": null
},
{
"code": "<script> // JavaScript program to find the sum of all// multiples of 3 and 7 below N // Function to find sum of AP seriesfunction sumAP(n, d){ // Number of terms n = parseInt(n / d); return (n) * (1 + n) * (d / 2);} // Function to find the sum of all// multiples of 3 and 7 below Nfunction sumMultiples(n){ // Since, we need the sum of // multiples less than N n--; return sumAP(n, 3) + sumAP(n, 7) - sumAP(n, 21);} // Driver codelet n = 24; document.write(sumMultiples(n)); // This code is contributed by mohan1240760 </script>",
"e": 30840,
"s": 30258,
"text": null
},
{
"code": null,
"e": 30844,
"s": 30840,
"text": "105"
},
{
"code": null,
"e": 30863,
"s": 30846,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 30874,
"s": 30863,
"text": "andrew1234"
},
{
"code": null,
"e": 30887,
"s": 30874,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30900,
"s": 30887,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 30917,
"s": 30900,
"text": "pulamolusaimohan"
},
{
"code": null,
"e": 30930,
"s": 30917,
"text": "divisibility"
},
{
"code": null,
"e": 30954,
"s": 30930,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30967,
"s": 30954,
"text": "Mathematical"
},
{
"code": null,
"e": 30980,
"s": 30967,
"text": "Mathematical"
},
{
"code": null,
"e": 31078,
"s": 30980,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31111,
"s": 31078,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 31157,
"s": 31111,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 31215,
"s": 31157,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 31256,
"s": 31215,
"text": "5 Best Books for Competitive Programming"
},
{
"code": null,
"e": 31337,
"s": 31256,
"text": "Check whether bitwise AND of a number with any subset of an array is zero or not"
},
{
"code": null,
"e": 31367,
"s": 31337,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31427,
"s": 31367,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31442,
"s": 31427,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31485,
"s": 31442,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
Class getEnumConstants() method in Java with Examples - GeeksforGeeks | 27 Dec, 2019
The getEnumConstants() method of java.lang.Class class is used to get the Enum constants of this class. The method returns the Enum constants of this class in the form of an array of objects comprising the enum class represented by this class.
Syntax:
public T[] getEnumConstants()
Parameter: This method does not accepts any parameter
Return Value: This method returns the specified Enum constants of this class in the form of an array of Enum objects.
Below programs demonstrate the getEnumConstants() method.
Example 1:
// Java program to demonstrate// getEnumConstants() method import java.util.*; enum A {} public class Test { public Object obj; public static void main(String[] args) { // returns the Class object for this class Class myClass = A.class; System.out.println("Class represented by myClass: " + myClass.toString()); // Get the Enum constants of myClass // using getEnumConstants() method System.out.println( "Enum constants of myClass: " + Arrays.toString( myClass.getEnumConstants())); }}
Class represented by myClass: class A
Enum constants of myClass: []
Example 2:
// Java program to demonstrate// getEnumConstants() method import java.util.*; enum A { RED, GREEN, BLUE;} class Main { private Object obj; public static void main(String[] args) { try { // returns the Class object for this class Class myClass = A.class; System.out.println("Class represented by myClass: " + myClass.toString()); // Get the Enum constants of myClass // using getEnumConstants() method System.out.println( "Enum constants of myClass: " + Arrays.toString( myClass.getEnumConstants())); } catch (Exception e) { System.out.println(e); } }}
Class represented by myClass: class A
Enum constants of myClass: [RED, GREEN, BLUE]
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getEnumConstants–
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 25777,
"s": 25749,
"text": "\n27 Dec, 2019"
},
{
"code": null,
"e": 26021,
"s": 25777,
"text": "The getEnumConstants() method of java.lang.Class class is used to get the Enum constants of this class. The method returns the Enum constants of this class in the form of an array of objects comprising the enum class represented by this class."
},
{
"code": null,
"e": 26029,
"s": 26021,
"text": "Syntax:"
},
{
"code": null,
"e": 26060,
"s": 26029,
"text": "public T[] getEnumConstants()\n"
},
{
"code": null,
"e": 26114,
"s": 26060,
"text": "Parameter: This method does not accepts any parameter"
},
{
"code": null,
"e": 26232,
"s": 26114,
"text": "Return Value: This method returns the specified Enum constants of this class in the form of an array of Enum objects."
},
{
"code": null,
"e": 26290,
"s": 26232,
"text": "Below programs demonstrate the getEnumConstants() method."
},
{
"code": null,
"e": 26301,
"s": 26290,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// getEnumConstants() method import java.util.*; enum A {} public class Test { public Object obj; public static void main(String[] args) { // returns the Class object for this class Class myClass = A.class; System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the Enum constants of myClass // using getEnumConstants() method System.out.println( \"Enum constants of myClass: \" + Arrays.toString( myClass.getEnumConstants())); }}",
"e": 26919,
"s": 26301,
"text": null
},
{
"code": null,
"e": 26988,
"s": 26919,
"text": "Class represented by myClass: class A\nEnum constants of myClass: []\n"
},
{
"code": null,
"e": 26999,
"s": 26988,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// getEnumConstants() method import java.util.*; enum A { RED, GREEN, BLUE;} class Main { private Object obj; public static void main(String[] args) { try { // returns the Class object for this class Class myClass = A.class; System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the Enum constants of myClass // using getEnumConstants() method System.out.println( \"Enum constants of myClass: \" + Arrays.toString( myClass.getEnumConstants())); } catch (Exception e) { System.out.println(e); } }}",
"e": 27774,
"s": 26999,
"text": null
},
{
"code": null,
"e": 27859,
"s": 27774,
"text": "Class represented by myClass: class A\nEnum constants of myClass: [RED, GREEN, BLUE]\n"
},
{
"code": null,
"e": 27951,
"s": 27859,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getEnumConstants–"
},
{
"code": null,
"e": 27966,
"s": 27951,
"text": "Java-Functions"
},
{
"code": null,
"e": 27984,
"s": 27966,
"text": "Java-lang package"
},
{
"code": null,
"e": 28000,
"s": 27984,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 28005,
"s": 28000,
"text": "Java"
},
{
"code": null,
"e": 28010,
"s": 28005,
"text": "Java"
},
{
"code": null,
"e": 28108,
"s": 28010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28159,
"s": 28108,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28189,
"s": 28159,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28208,
"s": 28189,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 28223,
"s": 28208,
"text": "Stream In Java"
},
{
"code": null,
"e": 28254,
"s": 28223,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 28286,
"s": 28254,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28306,
"s": 28286,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 28338,
"s": 28306,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 28362,
"s": 28338,
"text": "Singleton Class in Java"
}
]
|
C# - Param Arrays | At times, while declaring a method, you are not sure of the number of arguments passed as a parameter. C# param arrays (or parameter arrays) come into help at such times.
The following example demonstrates this −
using System;
namespace ArrayApplication {
class ParamArray {
public int AddElements(params int[] arr) {
int sum = 0;
foreach (int i in arr) {
sum += i;
}
return sum;
}
}
class TestClass {
static void Main(string[] args) {
ParamArray app = new ParamArray();
int sum = app.AddElements(512, 720, 250, 567, 889);
Console.WriteLine("The sum is: {0}", sum);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
The sum is: 2938
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": 2441,
"s": 2270,
"text": "At times, while declaring a method, you are not sure of the number of arguments passed as a parameter. C# param arrays (or parameter arrays) come into help at such times."
},
{
"code": null,
"e": 2483,
"s": 2441,
"text": "The following example demonstrates this −"
},
{
"code": null,
"e": 3002,
"s": 2483,
"text": "using System;\n\nnamespace ArrayApplication {\n class ParamArray {\n public int AddElements(params int[] arr) {\n int sum = 0;\n \n foreach (int i in arr) {\n sum += i;\n }\n return sum;\n }\n }\n class TestClass {\n static void Main(string[] args) {\n ParamArray app = new ParamArray();\n int sum = app.AddElements(512, 720, 250, 567, 889);\n \n Console.WriteLine(\"The sum is: {0}\", sum);\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 3083,
"s": 3002,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3101,
"s": 3083,
"text": "The sum is: 2938\n"
},
{
"code": null,
"e": 3138,
"s": 3101,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 3151,
"s": 3138,
"text": " Raja Biswas"
},
{
"code": null,
"e": 3185,
"s": 3151,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3203,
"s": 3185,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 3236,
"s": 3203,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3250,
"s": 3236,
"text": " Peter Jepson"
},
{
"code": null,
"e": 3287,
"s": 3250,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 3302,
"s": 3287,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 3337,
"s": 3302,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 3352,
"s": 3337,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3387,
"s": 3352,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3399,
"s": 3387,
"text": " Eric Frick"
},
{
"code": null,
"e": 3406,
"s": 3399,
"text": " Print"
},
{
"code": null,
"e": 3417,
"s": 3406,
"text": " Add Notes"
}
]
|
CSS | counter-increment Property - GeeksforGeeks | 24 Aug, 2021
The CSS counter-increment Property is used to increment/decrement value of a counter. A CSS counter is a variable that is used to track how many times a variable is used.
Syntax:
counter-increment: none | identifier | initial | inherit;
Default Value: none
Property values:
none: This is the default value and by this no counters will be incremented.Syntax:
counter-increment: none;
Example:
html
<!DOCTYPE html><html> <head> <title>CSS counter-increment Property</title> <style> h1 { color: green; } body { } <!-- The h2::before selector inserts something before the content of each selected element --> h2::before { counter-increment: none; } </style></head> <body> <h1>Welcome to GeeksforGeeks</h1> <h1>Courses: </h1> <h2>Fork Python</h2> <h2>Fork Java</h2> <h2>Fork CPP</h2> <h2>Sudo Gate</h2> </body> </html>
Output:
identifier: The identifier value is used to define which counter is to be incremented. This value also takes a number which defines how much the increment will take place. The default value of this increment value is 1 (if the selector has not been reset, then the default value will be 0). This value also takes the negative values as well.Syntax:
counter-increment: identifier;
Example:
html
<!DOCTYPE html><html> <head> <title>CSS counter-increment Property</title> <style> h1 { color: green; } body { <!-- Set "geek-counter" identifier to 0 --> counter-reset: geek-counter; } <!-- The h2::before selector inserts something before the content of each selected element --> h2::before { <!-- Increment "geek-counter" by 1 --> counter-increment: geek-counter; content: "Course " counter(geek-counter) ": "; } </style></head> <body> <h1>Welcome to GeeksforGeeks</h1> <h1>Courses: </h1> <h2>Fork Python</h2> <h2>Fork Java</h2> <h2>Fork CPP</h2> <h2>Sudo Gate</h2> </body> </html>
Output:
initial: This value sets the property to its default value.Syntax:
counter-increment: initial;
Example:
html
<!DOCTYPE html><html> <head> <style> body { /* Set "my-geek-counter" to 1*/ counter-reset: my-geek-counter 1; } h2::before { /* Sets the initial value which is 1 here for the counter */ counter-increment: initial; content: "Section " counter(my-geek-counter) ". "; } } </style></head> <body> <h1>Welcome to GeeksforGeeks</h1> <h1>Courses: </h1> <h2>Fork Python</h2> <h2>Fork Java</h2> <h2>Fork CPP</h2> <h2>Sudo Gate</h2></body> </html>
Output:
inherit: This value inherits this property from its parent element.Syntax:
counter-increment: inherit;
Example:
html
<!DOCTYPE html><html> <head> <style> body { /* Set "my-geek-counter" to 1*/ counter-reset: my-geek-counter 1; } h2::before { /* Sets the initial value which is 1 here for the counter */ counter-increment: inherit; content: "Section " counter(my-geek-counter) ". "; } } </style></head> <body> <h1>Welcome to GeeksforGeeks</h1> <h1>Courses: </h1> <h2>Fork Python</h2> <h2>Fork Java</h2> <h2>Fork CPP</h2> <h2>Sudo Gate</h2></body> </html>
Output:
Supported Browsers The browsers supported by counter-increment property are listed below:
Google Chrome 2.0
Internet Explore 8.0
Firefox 1.0
Opera 9.2
Apple Safari 3.0
ManasChhabra2
CSS-Properties
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 23616,
"s": 23588,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 23788,
"s": 23616,
"text": "The CSS counter-increment Property is used to increment/decrement value of a counter. A CSS counter is a variable that is used to track how many times a variable is used. "
},
{
"code": null,
"e": 23798,
"s": 23788,
"text": "Syntax: "
},
{
"code": null,
"e": 23856,
"s": 23798,
"text": "counter-increment: none | identifier | initial | inherit;"
},
{
"code": null,
"e": 23878,
"s": 23856,
"text": "Default Value: none "
},
{
"code": null,
"e": 23895,
"s": 23878,
"text": "Property values:"
},
{
"code": null,
"e": 23980,
"s": 23895,
"text": "none: This is the default value and by this no counters will be incremented.Syntax: "
},
{
"code": null,
"e": 24005,
"s": 23980,
"text": "counter-increment: none;"
},
{
"code": null,
"e": 24016,
"s": 24005,
"text": "Example: "
},
{
"code": null,
"e": 24021,
"s": 24016,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS counter-increment Property</title> <style> h1 { color: green; } body { } <!-- The h2::before selector inserts something before the content of each selected element --> h2::before { counter-increment: none; } </style></head> <body> <h1>Welcome to GeeksforGeeks</h1> <h1>Courses: </h1> <h2>Fork Python</h2> <h2>Fork Java</h2> <h2>Fork CPP</h2> <h2>Sudo Gate</h2> </body> </html> ",
"e": 24595,
"s": 24021,
"text": null
},
{
"code": null,
"e": 24605,
"s": 24595,
"text": "Output: "
},
{
"code": null,
"e": 24957,
"s": 24607,
"text": "identifier: The identifier value is used to define which counter is to be incremented. This value also takes a number which defines how much the increment will take place. The default value of this increment value is 1 (if the selector has not been reset, then the default value will be 0). This value also takes the negative values as well.Syntax: "
},
{
"code": null,
"e": 24988,
"s": 24957,
"text": "counter-increment: identifier;"
},
{
"code": null,
"e": 24999,
"s": 24988,
"text": "Example: "
},
{
"code": null,
"e": 25004,
"s": 24999,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS counter-increment Property</title> <style> h1 { color: green; } body { <!-- Set \"geek-counter\" identifier to 0 --> counter-reset: geek-counter; } <!-- The h2::before selector inserts something before the content of each selected element --> h2::before { <!-- Increment \"geek-counter\" by 1 --> counter-increment: geek-counter; content: \"Course \" counter(geek-counter) \": \"; } </style></head> <body> <h1>Welcome to GeeksforGeeks</h1> <h1>Courses: </h1> <h2>Fork Python</h2> <h2>Fork Java</h2> <h2>Fork CPP</h2> <h2>Sudo Gate</h2> </body> </html>",
"e": 25791,
"s": 25004,
"text": null
},
{
"code": null,
"e": 25801,
"s": 25791,
"text": "Output: "
},
{
"code": null,
"e": 25871,
"s": 25803,
"text": "initial: This value sets the property to its default value.Syntax: "
},
{
"code": null,
"e": 25899,
"s": 25871,
"text": "counter-increment: initial;"
},
{
"code": null,
"e": 25910,
"s": 25899,
"text": "Example: "
},
{
"code": null,
"e": 25915,
"s": 25910,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { /* Set \"my-geek-counter\" to 1*/ counter-reset: my-geek-counter 1; } h2::before { /* Sets the initial value which is 1 here for the counter */ counter-increment: initial; content: \"Section \" counter(my-geek-counter) \". \"; } } </style></head> <body> <h1>Welcome to GeeksforGeeks</h1> <h1>Courses: </h1> <h2>Fork Python</h2> <h2>Fork Java</h2> <h2>Fork CPP</h2> <h2>Sudo Gate</h2></body> </html>",
"e": 26481,
"s": 25915,
"text": null
},
{
"code": null,
"e": 26491,
"s": 26481,
"text": "Output: "
},
{
"code": null,
"e": 26569,
"s": 26493,
"text": "inherit: This value inherits this property from its parent element.Syntax: "
},
{
"code": null,
"e": 26597,
"s": 26569,
"text": "counter-increment: inherit;"
},
{
"code": null,
"e": 26608,
"s": 26597,
"text": "Example: "
},
{
"code": null,
"e": 26613,
"s": 26608,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { /* Set \"my-geek-counter\" to 1*/ counter-reset: my-geek-counter 1; } h2::before { /* Sets the initial value which is 1 here for the counter */ counter-increment: inherit; content: \"Section \" counter(my-geek-counter) \". \"; } } </style></head> <body> <h1>Welcome to GeeksforGeeks</h1> <h1>Courses: </h1> <h2>Fork Python</h2> <h2>Fork Java</h2> <h2>Fork CPP</h2> <h2>Sudo Gate</h2></body> </html>",
"e": 27177,
"s": 26613,
"text": null
},
{
"code": null,
"e": 27187,
"s": 27177,
"text": "Output: "
},
{
"code": null,
"e": 27281,
"s": 27189,
"text": "Supported Browsers The browsers supported by counter-increment property are listed below: "
},
{
"code": null,
"e": 27299,
"s": 27281,
"text": "Google Chrome 2.0"
},
{
"code": null,
"e": 27320,
"s": 27299,
"text": "Internet Explore 8.0"
},
{
"code": null,
"e": 27332,
"s": 27320,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 27342,
"s": 27332,
"text": "Opera 9.2"
},
{
"code": null,
"e": 27359,
"s": 27342,
"text": "Apple Safari 3.0"
},
{
"code": null,
"e": 27375,
"s": 27361,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 27390,
"s": 27375,
"text": "CSS-Properties"
},
{
"code": null,
"e": 27397,
"s": 27390,
"text": "Picked"
},
{
"code": null,
"e": 27401,
"s": 27397,
"text": "CSS"
},
{
"code": null,
"e": 27418,
"s": 27401,
"text": "Web Technologies"
},
{
"code": null,
"e": 27516,
"s": 27418,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27578,
"s": 27516,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27628,
"s": 27578,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 27686,
"s": 27628,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 27734,
"s": 27686,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 27784,
"s": 27734,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 27826,
"s": 27784,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27888,
"s": 27826,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27931,
"s": 27888,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27964,
"s": 27931,
"text": "Installation of Node.js on Linux"
}
]
|
JSTL - fn:substringBefore() Function | The fn:substringBefore() function returns the part of a string before a specified substring.
The fn:substringBefore() function has the following syntax −
java.lang.String substringBefore(java.lang.String, java.lang.String)
Following example explains the functionality of the fn:substringBefore() function −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>
<html>
<head>
<title>Using JSTL Functions</title>
</head>
<body>
<c:set var = "string1" value = "This is first String."/>
<c:set var = "string2" value = "${fn:substringBefore(string1, 'first')}" />
<p>Final sub string : ${string2}</p>
</body>
</html>
You will receive the following result −
Final sub string : This is
108 Lectures
11 hours
Chaand Sheikh
517 Lectures
57 hours
Chaand Sheikh
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
44 Lectures
15 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2332,
"s": 2239,
"text": "The fn:substringBefore() function returns the part of a string before a specified substring."
},
{
"code": null,
"e": 2393,
"s": 2332,
"text": "The fn:substringBefore() function has the following syntax −"
},
{
"code": null,
"e": 2463,
"s": 2393,
"text": "java.lang.String substringBefore(java.lang.String, java.lang.String)\n"
},
{
"code": null,
"e": 2547,
"s": 2463,
"text": "Following example explains the functionality of the fn:substringBefore() function −"
},
{
"code": null,
"e": 2980,
"s": 2547,
"text": "<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/functions\" prefix = \"fn\" %>\n\n<html>\n <head>\n <title>Using JSTL Functions</title>\n </head>\n\n <body>\n <c:set var = \"string1\" value = \"This is first String.\"/>\n <c:set var = \"string2\" value = \"${fn:substringBefore(string1, 'first')}\" />\n <p>Final sub string : ${string2}</p>\n </body>\n</html>"
},
{
"code": null,
"e": 3020,
"s": 2980,
"text": "You will receive the following result −"
},
{
"code": null,
"e": 3049,
"s": 3020,
"text": "Final sub string : This is \n"
},
{
"code": null,
"e": 3084,
"s": 3049,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3099,
"s": 3084,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3134,
"s": 3099,
"text": "\n 517 Lectures \n 57 hours \n"
},
{
"code": null,
"e": 3149,
"s": 3134,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3184,
"s": 3149,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3198,
"s": 3184,
"text": " Karthikeya T"
},
{
"code": null,
"e": 3233,
"s": 3198,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3249,
"s": 3233,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3282,
"s": 3249,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3298,
"s": 3282,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3332,
"s": 3298,
"text": "\n 44 Lectures \n 15 hours \n"
},
{
"code": null,
"e": 3340,
"s": 3332,
"text": " Uplatz"
},
{
"code": null,
"e": 3347,
"s": 3340,
"text": " Print"
},
{
"code": null,
"e": 3358,
"s": 3347,
"text": " Add Notes"
}
]
|
Hearing aids for Impaired People using MATLAB - GeeksforGeeks | 24 Feb, 2022
In this article, we are going to discuss how to develop a digital hearing aid using MATLAB.
MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It allows matrix manipulations, plotting of functions, implementation of algorithms and creation of user interfaces. It is both a programming language and a programming environment. It allows the computation of statements in the command window itself.
Step-by-step approach:
We give an input speech signal to the MATLAB model.
Then we add noise to the input speech signal because for this system the input signal is a clean signal, some noise is added in order to simulate a real situation.
Now we use the Wavelet filter to reduce the noise.
We use frequency shaper to correct the loss of hearing certain frequencies.
The amplitude compression is used to improve the gain of the signal.
Flow Diagram based on the above approach:
Here we are using AWGN(additive white gaussian noise) because AWGN is a fundamental model utilized in data hypothesis to emulate the impact of numerous arbitrary cycles that happen in nature. AWGN has a continuous and uniform frequency spectrum over a specified frequency band and has equal power per Hertz of this band.
Algorithm
MATLAB
clc clear close all % disp('recording...');% recObj = audiorecorder;% recordblocking(recObj,5);% disp('recorded');% %% % disp('playing recorded sound...');% play(recObj);% pause(7);%% % y = getaudiodata(recObj);% input= 'Counting-16-44p1-mono-15secs.wav'; disp('input sound') % input = 'audio.wav';% [in,fs] = audioread(input);% [y,fs] = audioread(input); load handle.mat fs=Fs; y = y(:, 1); % info = audioinfo(input); sound(y);pause(10); figure,plot(y);title('input');xlabel('samples');ylabel('amplitude'); y = awgn(y,40);noi = y;figure,plot(y); xlabel('samples');ylabel('amplitude');title('awgn');disp('playing added noise...');sound(y);pause(10) %'Fp,Fst,Ap,Ast' (passband frequency, stopband frequency, passband ripple, stopband attenuation) hlpf = fdesign.lowpass('Fp,Fst,Ap,Ast',3.0e3,3.5e3,0.5,50,fs);D = design(hlpf);freqz(D);x = filter(D,y); disp('playing denoised sound');figure,plot(x);title('denoise');sound(x,fs); xlabel('samples');ylabel('amplitude');pause(10) % freq shaper using band pass T = 1/fs;len = length(x);p = log2(len);p = ceil(p);N = 2^p;f1 = fdesign.bandpass('Fst1,Fp1,Fp2,Fst2,Ast1,Ap,Ast2',2000,3000,4000,5000,60,2,60,2*fs);hd = design(f1,'equiripple');y = filter(hd,x);freqz(hd);y = y*100; disp('playing frequency shaped...');sound(y,fs);pause(10); % amplitude shaper disp('amplitude shaper')out1=fft(y);phase=angle(out1);mag=abs(out1)/N;[magsig,~]=size(mag);threshold=1000;out=zeros(magsig,1); for i=1:magsig/2 if(mag(i)>threshold) mag(i)=threshold;mag(magsig-i)=threshold; end out(i)=mag(i)*exp(j*phase(i)); out(magsig-i)=out(i); end outfinal=real(ifft(out))*10000;disp('playing amplitude shaped...');sound(outfinal,fs);pause(10); load handle.matfigure;subplot(2,1,1);specgram(noi);title('Spectrogram of Original Signal'); subplot(2,1,2);specgram(outfinal);title('Spectrogram of Adjusted Signal');
Output:
clintra
rkbhola5
MATLAB
Advanced Computer Subject
Programming Language
Project
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Principal Component Analysis with Python
Classifying data using Support Vector Machines(SVMs) in Python
Fuzzy Logic | Introduction
Q-Learning in Python
Arrow operator -> in C/C++ with Examples
Modulo Operator (%) in C/C++ with Examples
Structures in C++
Differences between Procedural and Object Oriented Programming
Top 10 Programming Languages to Learn in 2022 | [
{
"code": null,
"e": 24228,
"s": 24200,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 24320,
"s": 24228,
"text": "In this article, we are going to discuss how to develop a digital hearing aid using MATLAB."
},
{
"code": null,
"e": 24681,
"s": 24320,
"text": "MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for technical computing. It allows matrix manipulations, plotting of functions, implementation of algorithms and creation of user interfaces. It is both a programming language and a programming environment. It allows the computation of statements in the command window itself."
},
{
"code": null,
"e": 24704,
"s": 24681,
"text": "Step-by-step approach:"
},
{
"code": null,
"e": 24756,
"s": 24704,
"text": "We give an input speech signal to the MATLAB model."
},
{
"code": null,
"e": 24920,
"s": 24756,
"text": "Then we add noise to the input speech signal because for this system the input signal is a clean signal, some noise is added in order to simulate a real situation."
},
{
"code": null,
"e": 24971,
"s": 24920,
"text": "Now we use the Wavelet filter to reduce the noise."
},
{
"code": null,
"e": 25047,
"s": 24971,
"text": "We use frequency shaper to correct the loss of hearing certain frequencies."
},
{
"code": null,
"e": 25116,
"s": 25047,
"text": "The amplitude compression is used to improve the gain of the signal."
},
{
"code": null,
"e": 25158,
"s": 25116,
"text": "Flow Diagram based on the above approach:"
},
{
"code": null,
"e": 25479,
"s": 25158,
"text": "Here we are using AWGN(additive white gaussian noise) because AWGN is a fundamental model utilized in data hypothesis to emulate the impact of numerous arbitrary cycles that happen in nature. AWGN has a continuous and uniform frequency spectrum over a specified frequency band and has equal power per Hertz of this band."
},
{
"code": null,
"e": 25489,
"s": 25479,
"text": "Algorithm"
},
{
"code": null,
"e": 25496,
"s": 25489,
"text": "MATLAB"
},
{
"code": "clc clear close all % disp('recording...');% recObj = audiorecorder;% recordblocking(recObj,5);% disp('recorded');% %% % disp('playing recorded sound...');% play(recObj);% pause(7);%% % y = getaudiodata(recObj);% input= 'Counting-16-44p1-mono-15secs.wav'; disp('input sound') % input = 'audio.wav';% [in,fs] = audioread(input);% [y,fs] = audioread(input); load handle.mat fs=Fs; y = y(:, 1); % info = audioinfo(input); sound(y);pause(10); figure,plot(y);title('input');xlabel('samples');ylabel('amplitude'); y = awgn(y,40);noi = y;figure,plot(y); xlabel('samples');ylabel('amplitude');title('awgn');disp('playing added noise...');sound(y);pause(10) %'Fp,Fst,Ap,Ast' (passband frequency, stopband frequency, passband ripple, stopband attenuation) hlpf = fdesign.lowpass('Fp,Fst,Ap,Ast',3.0e3,3.5e3,0.5,50,fs);D = design(hlpf);freqz(D);x = filter(D,y); disp('playing denoised sound');figure,plot(x);title('denoise');sound(x,fs); xlabel('samples');ylabel('amplitude');pause(10) % freq shaper using band pass T = 1/fs;len = length(x);p = log2(len);p = ceil(p);N = 2^p;f1 = fdesign.bandpass('Fst1,Fp1,Fp2,Fst2,Ast1,Ap,Ast2',2000,3000,4000,5000,60,2,60,2*fs);hd = design(f1,'equiripple');y = filter(hd,x);freqz(hd);y = y*100; disp('playing frequency shaped...');sound(y,fs);pause(10); % amplitude shaper disp('amplitude shaper')out1=fft(y);phase=angle(out1);mag=abs(out1)/N;[magsig,~]=size(mag);threshold=1000;out=zeros(magsig,1); for i=1:magsig/2 if(mag(i)>threshold) mag(i)=threshold;mag(magsig-i)=threshold; end out(i)=mag(i)*exp(j*phase(i)); out(magsig-i)=out(i); end outfinal=real(ifft(out))*10000;disp('playing amplitude shaped...');sound(outfinal,fs);pause(10); load handle.matfigure;subplot(2,1,1);specgram(noi);title('Spectrogram of Original Signal'); subplot(2,1,2);specgram(outfinal);title('Spectrogram of Adjusted Signal');",
"e": 27343,
"s": 25496,
"text": null
},
{
"code": null,
"e": 27354,
"s": 27346,
"text": "Output:"
},
{
"code": null,
"e": 27366,
"s": 27358,
"text": "clintra"
},
{
"code": null,
"e": 27375,
"s": 27366,
"text": "rkbhola5"
},
{
"code": null,
"e": 27382,
"s": 27375,
"text": "MATLAB"
},
{
"code": null,
"e": 27408,
"s": 27382,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 27429,
"s": 27408,
"text": "Programming Language"
},
{
"code": null,
"e": 27437,
"s": 27429,
"text": "Project"
},
{
"code": null,
"e": 27535,
"s": 27437,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27579,
"s": 27535,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 27620,
"s": 27579,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 27683,
"s": 27620,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 27710,
"s": 27683,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 27731,
"s": 27710,
"text": "Q-Learning in Python"
},
{
"code": null,
"e": 27772,
"s": 27731,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 27815,
"s": 27772,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 27833,
"s": 27815,
"text": "Structures in C++"
},
{
"code": null,
"e": 27896,
"s": 27833,
"text": "Differences between Procedural and Object Oriented Programming"
}
]
|
JavaScript | Object Accessors - GeeksforGeeks | 12 Mar, 2019
There are two keywords which define the accessors functions: a getter and setter for the fullName property. When the property is accessed, the return value from the getter is used. When a value is set, the setter is called and passed the value that was set.
JavaScript Getter (The get Keyword):
Example: This example describes the use of lang() property to get the value of language property.
<!DOCTYPE html><html> <head> <title> JavaScript Getter </title></head> <body style="text-align:center;"> <div style="background-color: green;"> <h1> Welcome to GeeksforGeeks!. </h1> <h2> JavaScript Getters </h2> <p id="GFG"></p> </div> <script> // Create an object: var person = { name: "geeksforgeeks", get lang() { return this.name; } }; // Display data from the object using a getter document.getElementById("GFG").innerHTML = person.name; </script></body> </html>
Output:
JavaScript Setter (The set Keyword):Example: This example describes the use of lang() property to set the value of language property.
<!DOCTYPE html><html> <head> <title> JavaScript Getter </title></head> <body style="text-align:center;"> <div style="background-color: green;"> <h1> Welcome to GeeksforGeeks!. </h1> <h2> JavaScript Getters </h2> <p id="GFG"></p> </div> <script> // Create an object: var person = { name: "geeksforgeeks", set lang(value) { return this.name; } }; // Display data from the object using a getter document.getElementById("GFG").innerHTML = person.name; </script></body> </html>
Output:
Note: Getters and Setters are not supported in Internet Explorer 8.
Reasons to use Getters and Setters:
The syntax for properties and methods are equal.
Used for doing things behind-the-scenes.
They can secure better data quality.
The syntax of this are simpler.
Data Quality: The Getters and Setters are used to securing better data quality.
In the given example below, using the lang property, the lower case value of the language is returned.Example: This example use lang property and it returns the lower case value of the language.
<!DOCTYPE html><html> <head> <title> Data Quality </title></head> <body style="text-align:center;"> <div style="background-color: green;"> <h1>Geeksforgeeks !!</h1> <b> Data Quality : lower case value is returned </b> <p id="GFG"></p> </div> <script> var person = { language : "Geeksforgeeks", get lang() { return this.language.toLowerCase(); } }; // Display data from the object using a getter document.getElementById("GFG").innerHTML = person.lang; </script></body> </html>
Output:
javascript-object
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24909,
"s": 24881,
"text": "\n12 Mar, 2019"
},
{
"code": null,
"e": 25167,
"s": 24909,
"text": "There are two keywords which define the accessors functions: a getter and setter for the fullName property. When the property is accessed, the return value from the getter is used. When a value is set, the setter is called and passed the value that was set."
},
{
"code": null,
"e": 25204,
"s": 25167,
"text": "JavaScript Getter (The get Keyword):"
},
{
"code": null,
"e": 25302,
"s": 25204,
"text": "Example: This example describes the use of lang() property to get the value of language property."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript Getter </title></head> <body style=\"text-align:center;\"> <div style=\"background-color: green;\"> <h1> Welcome to GeeksforGeeks!. </h1> <h2> JavaScript Getters </h2> <p id=\"GFG\"></p> </div> <script> // Create an object: var person = { name: \"geeksforgeeks\", get lang() { return this.name; } }; // Display data from the object using a getter document.getElementById(\"GFG\").innerHTML = person.name; </script></body> </html> ",
"e": 26024,
"s": 25302,
"text": null
},
{
"code": null,
"e": 26032,
"s": 26024,
"text": "Output:"
},
{
"code": null,
"e": 26166,
"s": 26032,
"text": "JavaScript Setter (The set Keyword):Example: This example describes the use of lang() property to set the value of language property."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript Getter </title></head> <body style=\"text-align:center;\"> <div style=\"background-color: green;\"> <h1> Welcome to GeeksforGeeks!. </h1> <h2> JavaScript Getters </h2> <p id=\"GFG\"></p> </div> <script> // Create an object: var person = { name: \"geeksforgeeks\", set lang(value) { return this.name; } }; // Display data from the object using a getter document.getElementById(\"GFG\").innerHTML = person.name; </script></body> </html> ",
"e": 26903,
"s": 26166,
"text": null
},
{
"code": null,
"e": 26911,
"s": 26903,
"text": "Output:"
},
{
"code": null,
"e": 26979,
"s": 26911,
"text": "Note: Getters and Setters are not supported in Internet Explorer 8."
},
{
"code": null,
"e": 27015,
"s": 26979,
"text": "Reasons to use Getters and Setters:"
},
{
"code": null,
"e": 27064,
"s": 27015,
"text": "The syntax for properties and methods are equal."
},
{
"code": null,
"e": 27105,
"s": 27064,
"text": "Used for doing things behind-the-scenes."
},
{
"code": null,
"e": 27142,
"s": 27105,
"text": "They can secure better data quality."
},
{
"code": null,
"e": 27174,
"s": 27142,
"text": "The syntax of this are simpler."
},
{
"code": null,
"e": 27254,
"s": 27174,
"text": "Data Quality: The Getters and Setters are used to securing better data quality."
},
{
"code": null,
"e": 27449,
"s": 27254,
"text": "In the given example below, using the lang property, the lower case value of the language is returned.Example: This example use lang property and it returns the lower case value of the language."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Data Quality </title></head> <body style=\"text-align:center;\"> <div style=\"background-color: green;\"> <h1>Geeksforgeeks !!</h1> <b> Data Quality : lower case value is returned </b> <p id=\"GFG\"></p> </div> <script> var person = { language : \"Geeksforgeeks\", get lang() { return this.language.toLowerCase(); } }; // Display data from the object using a getter document.getElementById(\"GFG\").innerHTML = person.lang; </script></body> </html> ",
"e": 28174,
"s": 27449,
"text": null
},
{
"code": null,
"e": 28182,
"s": 28174,
"text": "Output:"
},
{
"code": null,
"e": 28200,
"s": 28182,
"text": "javascript-object"
},
{
"code": null,
"e": 28207,
"s": 28200,
"text": "Picked"
},
{
"code": null,
"e": 28218,
"s": 28207,
"text": "JavaScript"
},
{
"code": null,
"e": 28235,
"s": 28218,
"text": "Web Technologies"
},
{
"code": null,
"e": 28333,
"s": 28235,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28342,
"s": 28333,
"text": "Comments"
},
{
"code": null,
"e": 28355,
"s": 28342,
"text": "Old Comments"
},
{
"code": null,
"e": 28416,
"s": 28355,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28457,
"s": 28416,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28511,
"s": 28457,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28551,
"s": 28511,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28613,
"s": 28551,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 28669,
"s": 28613,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28702,
"s": 28669,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28764,
"s": 28702,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28807,
"s": 28764,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Lua - Garbage Collection | Lua uses automatic memory management that uses garbage collection based on certain algorithms that is in-built in Lua. As a result of automatic memory management, as a developer −
No need to worry about allocating memory for objects.
No need to free them when no longer needed except for setting it to nil.
Lua uses a garbage collector that runs from time to time to collect dead objects when they are no longer accessible from the Lua program.
All objects including tables, userdata, functions, thread, string and so on are subject to automatic memory management. Lua uses incremental mark and sweep collector that uses two numbers to control its garbage collection cycles namely garbage collector pause and garbage collector step multiplier. These values are in percentage and value of 100 is often equal to 1 internally.
Garbage collector pause is used for controlling how long the garbage collector needs to wait, before; it is called again by the Lua's automatic memory management. Values less than 100 would mean that Lua will not wait for the next cycle. Similarly, higher values of this value would result in the garbage collector being slow and less aggressive in nature. A value of 200, means that the collector waits for the total memory in use to double before starting a new cycle. Hence, depending on the nature and speed of application, there may be a requirement to alter this value to get best performance in Lua applications.
This step multiplier controls the relative speed of garbage collector to that of memory allocation in Lua program. Larger step values will lead to garbage collector to be more aggressive and it also increases the step size of each incremental step of garbage collection. Values less than 100 could often lead to avoid the garbage collector not to complete its cycle and its not generally preferred. The default value is 200, which means the garbage collector runs twice as the speed of memory allocation.
As developers, we do have some control over the automatic memory management in Lua. For this, we have the following methods.
collectgarbage("collect") − Runs one complete cycle of garbage collection.
collectgarbage("collect") − Runs one complete cycle of garbage collection.
collectgarbage("count") − Returns the amount of memory currently used by the program in Kilobytes.
collectgarbage("count") − Returns the amount of memory currently used by the program in Kilobytes.
collectgarbage("restart") − If the garbage collector has been stopped, it restarts it.
collectgarbage("restart") − If the garbage collector has been stopped, it restarts it.
collectgarbage("setpause") − Sets the value given as second parameter divided by 100 to the garbage collector pause variable. Its uses are as discussed a little above.
collectgarbage("setpause") − Sets the value given as second parameter divided by 100 to the garbage collector pause variable. Its uses are as discussed a little above.
collectgarbage("setstepmul") − Sets the value given as second parameter divided by 100 to the garbage step multiplier variable. Its uses are as discussed a little above.
collectgarbage("setstepmul") − Sets the value given as second parameter divided by 100 to the garbage step multiplier variable. Its uses are as discussed a little above.
collectgarbage("step") − Runs one step of garbage collection. The larger the second argument is, the larger this step will be. The collectgarbage will return true if the triggered step was the last step of a garbage-collection cycle.
collectgarbage("step") − Runs one step of garbage collection. The larger the second argument is, the larger this step will be. The collectgarbage will return true if the triggered step was the last step of a garbage-collection cycle.
collectgarbage("stop") − Stops the garbage collector if its running.
collectgarbage("stop") − Stops the garbage collector if its running.
A simple example using the garbage collector example is shown below.
mytable = {"apple", "orange", "banana"}
print(collectgarbage("count"))
mytable = nil
print(collectgarbage("count"))
print(collectgarbage("collect"))
print(collectgarbage("count"))
When we run the above program, we will get the following output. Please note that this result will vary due to the difference in type of operating system and also the automatic memory management feature of Lua.
23.1455078125 149
23.2880859375 295
0
22.37109375 380
You can see in the above program, once garbage collection is done, it reduced the memory used. But, it's not mandatory to call this. Even if we don't call them, it will be executed automatically at a later stage by Lua interpreter after the predefined period.
Obviously, we can change the behavior of the garbage collector using these functions if required. These functions provide a bit of additional capability for the developer to handle complex situations. Depending on the type of memory need for the program, you may or may not use this feature. But it is very useful to know the memory usage in the applications and check it during the programming itself to avoid undesired results after deployment.
12 Lectures
2 hours
Manish Gupta
80 Lectures
3 hours
Sanjeev Mittal
54 Lectures
3.5 hours
Mehmet GOKTEPE
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2283,
"s": 2103,
"text": "Lua uses automatic memory management that uses garbage collection based on certain algorithms that is in-built in Lua. As a result of automatic memory management, as a developer −"
},
{
"code": null,
"e": 2337,
"s": 2283,
"text": "No need to worry about allocating memory for objects."
},
{
"code": null,
"e": 2410,
"s": 2337,
"text": "No need to free them when no longer needed except for setting it to nil."
},
{
"code": null,
"e": 2548,
"s": 2410,
"text": "Lua uses a garbage collector that runs from time to time to collect dead objects when they are no longer accessible from the Lua program."
},
{
"code": null,
"e": 2927,
"s": 2548,
"text": "All objects including tables, userdata, functions, thread, string and so on are subject to automatic memory management. Lua uses incremental mark and sweep collector that uses two numbers to control its garbage collection cycles namely garbage collector pause and garbage collector step multiplier. These values are in percentage and value of 100 is often equal to 1 internally."
},
{
"code": null,
"e": 3547,
"s": 2927,
"text": "Garbage collector pause is used for controlling how long the garbage collector needs to wait, before; it is called again by the Lua's automatic memory management. Values less than 100 would mean that Lua will not wait for the next cycle. Similarly, higher values of this value would result in the garbage collector being slow and less aggressive in nature. A value of 200, means that the collector waits for the total memory in use to double before starting a new cycle. Hence, depending on the nature and speed of application, there may be a requirement to alter this value to get best performance in Lua applications."
},
{
"code": null,
"e": 4052,
"s": 3547,
"text": "This step multiplier controls the relative speed of garbage collector to that of memory allocation in Lua program. Larger step values will lead to garbage collector to be more aggressive and it also increases the step size of each incremental step of garbage collection. Values less than 100 could often lead to avoid the garbage collector not to complete its cycle and its not generally preferred. The default value is 200, which means the garbage collector runs twice as the speed of memory allocation."
},
{
"code": null,
"e": 4177,
"s": 4052,
"text": "As developers, we do have some control over the automatic memory management in Lua. For this, we have the following methods."
},
{
"code": null,
"e": 4252,
"s": 4177,
"text": "collectgarbage(\"collect\") − Runs one complete cycle of garbage collection."
},
{
"code": null,
"e": 4327,
"s": 4252,
"text": "collectgarbage(\"collect\") − Runs one complete cycle of garbage collection."
},
{
"code": null,
"e": 4426,
"s": 4327,
"text": "collectgarbage(\"count\") − Returns the amount of memory currently used by the program in Kilobytes."
},
{
"code": null,
"e": 4525,
"s": 4426,
"text": "collectgarbage(\"count\") − Returns the amount of memory currently used by the program in Kilobytes."
},
{
"code": null,
"e": 4612,
"s": 4525,
"text": "collectgarbage(\"restart\") − If the garbage collector has been stopped, it restarts it."
},
{
"code": null,
"e": 4699,
"s": 4612,
"text": "collectgarbage(\"restart\") − If the garbage collector has been stopped, it restarts it."
},
{
"code": null,
"e": 4867,
"s": 4699,
"text": "collectgarbage(\"setpause\") − Sets the value given as second parameter divided by 100 to the garbage collector pause variable. Its uses are as discussed a little above."
},
{
"code": null,
"e": 5035,
"s": 4867,
"text": "collectgarbage(\"setpause\") − Sets the value given as second parameter divided by 100 to the garbage collector pause variable. Its uses are as discussed a little above."
},
{
"code": null,
"e": 5205,
"s": 5035,
"text": "collectgarbage(\"setstepmul\") − Sets the value given as second parameter divided by 100 to the garbage step multiplier variable. Its uses are as discussed a little above."
},
{
"code": null,
"e": 5375,
"s": 5205,
"text": "collectgarbage(\"setstepmul\") − Sets the value given as second parameter divided by 100 to the garbage step multiplier variable. Its uses are as discussed a little above."
},
{
"code": null,
"e": 5609,
"s": 5375,
"text": "collectgarbage(\"step\") − Runs one step of garbage collection. The larger the second argument is, the larger this step will be. The collectgarbage will return true if the triggered step was the last step of a garbage-collection cycle."
},
{
"code": null,
"e": 5843,
"s": 5609,
"text": "collectgarbage(\"step\") − Runs one step of garbage collection. The larger the second argument is, the larger this step will be. The collectgarbage will return true if the triggered step was the last step of a garbage-collection cycle."
},
{
"code": null,
"e": 5912,
"s": 5843,
"text": "collectgarbage(\"stop\") − Stops the garbage collector if its running."
},
{
"code": null,
"e": 5981,
"s": 5912,
"text": "collectgarbage(\"stop\") − Stops the garbage collector if its running."
},
{
"code": null,
"e": 6050,
"s": 5981,
"text": "A simple example using the garbage collector example is shown below."
},
{
"code": null,
"e": 6235,
"s": 6050,
"text": "mytable = {\"apple\", \"orange\", \"banana\"}\n\nprint(collectgarbage(\"count\"))\n\nmytable = nil\n\nprint(collectgarbage(\"count\"))\n\nprint(collectgarbage(\"collect\"))\n\nprint(collectgarbage(\"count\"))"
},
{
"code": null,
"e": 6446,
"s": 6235,
"text": "When we run the above program, we will get the following output. Please note that this result will vary due to the difference in type of operating system and also the automatic memory management feature of Lua."
},
{
"code": null,
"e": 6509,
"s": 6446,
"text": "23.1455078125 149\n23.2880859375 295\n0\n22.37109375 380\n"
},
{
"code": null,
"e": 6769,
"s": 6509,
"text": "You can see in the above program, once garbage collection is done, it reduced the memory used. But, it's not mandatory to call this. Even if we don't call them, it will be executed automatically at a later stage by Lua interpreter after the predefined period."
},
{
"code": null,
"e": 7216,
"s": 6769,
"text": "Obviously, we can change the behavior of the garbage collector using these functions if required. These functions provide a bit of additional capability for the developer to handle complex situations. Depending on the type of memory need for the program, you may or may not use this feature. But it is very useful to know the memory usage in the applications and check it during the programming itself to avoid undesired results after deployment."
},
{
"code": null,
"e": 7249,
"s": 7216,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7263,
"s": 7249,
"text": " Manish Gupta"
},
{
"code": null,
"e": 7296,
"s": 7263,
"text": "\n 80 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7312,
"s": 7296,
"text": " Sanjeev Mittal"
},
{
"code": null,
"e": 7347,
"s": 7312,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7363,
"s": 7347,
"text": " Mehmet GOKTEPE"
},
{
"code": null,
"e": 7370,
"s": 7363,
"text": " Print"
},
{
"code": null,
"e": 7381,
"s": 7370,
"text": " Add Notes"
}
]
|
Swift - Switch Statement | A switch statement in Swift completes its execution as soon as the first matching case is completed instead of falling through the bottom of subsequent cases like it happens in C and C++ programing languages. Following is a generic syntax of switch statement in C and C++ −
switch(expression) {
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
Here we need to use break statement to come out of a case statement otherwise execution control will fall through the subsequent case statements available below to matching case statement.
Following is a generic syntax of switch statement available in Swift −
switch expression {
case expression1 :
statement(s)
fallthrough /* optional */
case expression2, expression3 :
statement(s)
fallthrough /* optional */
default : /* Optional */
statement(s);
}
If we do not use fallthrough statement, then the program will come out of switch statement after executing the matching case statement. We will take the following two examples to make its functionality clear.
Following is an example of switch statement in Swift programming without using fallthrough −
import Cocoa
var index = 10
switch index {
case 100 :
println( "Value of index is 100")
case 10,15 :
println( "Value of index is either 10 or 15")
case 5 :
println( "Value of index is 5")
default :
println( "default case")
}
When the above code is compiled and executed, it produces the following result −
Value of index is either 10 or 15
Following is an example of switch statement in Swift programming with fallthrough −
import Cocoa
var index = 10
switch index {
case 100 :
println( "Value of index is 100")
fallthrough
case 10,15 :
println( "Value of index is either 10 or 15")
fallthrough
case 5 :
println( "Value of index is 5")
default :
println( "default case")
}
When the above code is compiled and executed, it produces the following result −
Value of index is either 10 or 15
Value of index is 5
38 Lectures
1 hours
Ashish Sharma
13 Lectures
2 hours
Three Millennials
7 Lectures
1 hours
Three Millennials
22 Lectures
1 hours
Frahaan Hussain
12 Lectures
39 mins
Devasena Rajendran
40 Lectures
2.5 hours
Grant Klimaytys
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2527,
"s": 2253,
"text": "A switch statement in Swift completes its execution as soon as the first matching case is completed instead of falling through the bottom of subsequent cases like it happens in C and C++ programing languages. Following is a generic syntax of switch statement in C and C++ −"
},
{
"code": null,
"e": 2812,
"s": 2527,
"text": "switch(expression) {\n case constant-expression :\n statement(s);\n break; /* optional */\n case constant-expression :\n statement(s);\n break; /* optional */\n \n /* you can have any number of case statements */\n default : /* Optional */\n statement(s);\n}\n"
},
{
"code": null,
"e": 3001,
"s": 2812,
"text": "Here we need to use break statement to come out of a case statement otherwise execution control will fall through the subsequent case statements available below to matching case statement."
},
{
"code": null,
"e": 3072,
"s": 3001,
"text": "Following is a generic syntax of switch statement available in Swift −"
},
{
"code": null,
"e": 3309,
"s": 3072,
"text": "switch expression {\n case expression1 :\n statement(s)\n fallthrough /* optional */\n case expression2, expression3 :\n statement(s)\n fallthrough /* optional */\n \n default : /* Optional */\n statement(s);\n}\n"
},
{
"code": null,
"e": 3518,
"s": 3309,
"text": "If we do not use fallthrough statement, then the program will come out of switch statement after executing the matching case statement. We will take the following two examples to make its functionality clear."
},
{
"code": null,
"e": 3611,
"s": 3518,
"text": "Following is an example of switch statement in Swift programming without using fallthrough −"
},
{
"code": null,
"e": 3877,
"s": 3611,
"text": "import Cocoa\n\nvar index = 10\n\nswitch index {\n case 100 :\n println( \"Value of index is 100\")\n case 10,15 :\n println( \"Value of index is either 10 or 15\")\n case 5 :\n println( \"Value of index is 5\")\n default :\n println( \"default case\")\n}"
},
{
"code": null,
"e": 3958,
"s": 3877,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3993,
"s": 3958,
"text": "Value of index is either 10 or 15\n"
},
{
"code": null,
"e": 4077,
"s": 3993,
"text": "Following is an example of switch statement in Swift programming with fallthrough −"
},
{
"code": null,
"e": 4379,
"s": 4077,
"text": "import Cocoa\n\nvar index = 10\n\nswitch index {\n case 100 :\n println( \"Value of index is 100\")\n fallthrough\n case 10,15 :\n println( \"Value of index is either 10 or 15\")\n fallthrough\n case 5 :\n println( \"Value of index is 5\")\n default :\n println( \"default case\")\n}"
},
{
"code": null,
"e": 4460,
"s": 4379,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4515,
"s": 4460,
"text": "Value of index is either 10 or 15\nValue of index is 5\n"
},
{
"code": null,
"e": 4548,
"s": 4515,
"text": "\n 38 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4563,
"s": 4548,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 4596,
"s": 4563,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4615,
"s": 4596,
"text": " Three Millennials"
},
{
"code": null,
"e": 4647,
"s": 4615,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4666,
"s": 4647,
"text": " Three Millennials"
},
{
"code": null,
"e": 4699,
"s": 4666,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4716,
"s": 4699,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4748,
"s": 4716,
"text": "\n 12 Lectures \n 39 mins\n"
},
{
"code": null,
"e": 4768,
"s": 4748,
"text": " Devasena Rajendran"
},
{
"code": null,
"e": 4803,
"s": 4768,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4820,
"s": 4803,
"text": " Grant Klimaytys"
},
{
"code": null,
"e": 4827,
"s": 4820,
"text": " Print"
},
{
"code": null,
"e": 4838,
"s": 4827,
"text": " Add Notes"
}
]
|
Beautiful custom colormaps with Matplotlib | by Kerry Halupka | Towards Data Science | If your Matplotlib chart needs a colormap and you’re not using an inbuilt map, chances are you’re going to have a bad time. I used to dread editing colormaps in Python. Every help thread I looked at showed a different approach, and none of them quite matched my situation. This was always disappointing because colormaps can vastly change the message you’re sending with your data visualisation, and can even go so far as to make your chart un-useable.
Don’t believe me? Check this out.
Each of these visualisations show identical data (estimated population of local government areas in Australia), but with different colormaps. The data is continuous and positive, which is shown by carefully examining the legend for each. However, the colormaps tell a different story, one that’s a bit like the tale of Goldilocks:
The first chart uses a sequential colormap, where the lightness value changes (either increasing or decreasing) monotonically throughout. If the detail in your visualisation is important then sequential probably isn’t your best bet, since it can be difficult to compare areas with similar values.The second chart uses a diverging colormap. With more colours it’s easier to tell the difference between similar values, but it also suggests to the viewer that the data is centred about a normal baseline, like zero. If we were to normalise our data about the mean then this scale would be appropriate, but since we’re just showing a range of positive values it doesn’t work here.The third chart is just right. This is similar to a sequential map since the color changes gradually throughout, with one end that clearly indicates higher values, and one that indicates lower values. However this map includes more colors, which allows the viewer to more easily compare small differences.
The first chart uses a sequential colormap, where the lightness value changes (either increasing or decreasing) monotonically throughout. If the detail in your visualisation is important then sequential probably isn’t your best bet, since it can be difficult to compare areas with similar values.
The second chart uses a diverging colormap. With more colours it’s easier to tell the difference between similar values, but it also suggests to the viewer that the data is centred about a normal baseline, like zero. If we were to normalise our data about the mean then this scale would be appropriate, but since we’re just showing a range of positive values it doesn’t work here.
The third chart is just right. This is similar to a sequential map since the color changes gradually throughout, with one end that clearly indicates higher values, and one that indicates lower values. However this map includes more colors, which allows the viewer to more easily compare small differences.
These are just a few examples of the colormaps you can use, for more details and options, check out this guide from Matplotlib.
Designing and creating a colormap gets even harder if you are attempting to make it fit in with a theme. For example, a visualisation embedded within a dashboard or website with an existing color scheme. It’s worth putting in the extra work for a thoroughly professional end product, and this guide will help you get there.
Let’s create a test image to work with, and turn off the axis ticks to make it look a bit nicer.
Now let’s edit the image, and test out 4 different inbuilt Matplotlib colormaps.
If the Matplotlib default colormaps don’t suit your need, you can always create your own. For this tutorial I’m going to assume you have some colors you’d like to use in a colormap. If not, scroll down to the bottom for some resources to help choose your colors.
If you have a specific set of colors to use based on a brand or website theme, chances are they’ll be in HEX format. So first up let’s define some functions to convert HEX to RGB, and RGB to Decimal (value between 0 and 1 for each of RBG channels).
My HEX colors are shown below, along with their RGB equivalents (the code I used to generate this image is here).
Let’s create a continuous colormap containing all of the colors above. We’ll be using the matplotlib.colors function called LinearSegmentedColormap. This function accepts a dictionary with a red, green and blue entries. Each entry should be a list of x, y0, y1 tuples, forming rows in a table. So, if you want red to increase from 0 to 1 over the bottom half, green to do the same over the middle half, and blue over the top half. Then you would use:
cdict = {'red': [(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)], 'green': [(0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)], 'blue': [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)]}
Confused? I was too. So I wrote some code (below) to wrap this function and make it more manageable. The code below can be used to map between an arbitrary number of hex colors in a list, it uses the functions we defined earlier to convert from hex to decimal.
By providing a list of floats from 0 to 1 we can also map the colors to specific locations on the colorbar, in order to stretch the representations of certain parts of the map.
We can also use this code to create a diverging colormap, which is useful if our data is to be displayed about some midpoint, like zero. If the data is not equally centred about the midpoint, for example if it ranges from -2 to 5, we need to shift the centre of the colormap to the midpoint of our data. The code below shows how to do this by using TwoSlopeNorm to create a norm, which is then used within imshow to scale the data to the [0, 1] range before mapping to colors.
Keep in mind that, while I won’t go in to detail in this post, your choice of colors goes beyond mere aesthetics, there is a whole field dedicated to to understanding the effect of different colors and combinations on human understanding. There is also the consideration of how your colormap would look to people with color blindness. You should consider both of these things when choosing your colors.
If you’re in need of some inspiration in choosing your colors, here are some sources I find helpful.
CoolorsCoolors is a fantastic app with so many features. For the purpose of creating a continuous colorscale I prefer their color gradient generation service, which has tonnes of beautiful color palettes that transition well in to continuous scales, and can be tweaked to suit your needs.
Gregor Aisch’s ChromaChroma is useful for optimizing your color palettes. It can be a little bit buggy, but it helps you take two or more colors and generate a full scale of in-between values. It also helpfully tells you whether your scale is colorblind safe.
W3schools color palettesThis has some nice example color palettes. W3 also provides other free services to choose palettes based on color theory, convert between different color formats (e.g. Hex, RGB etc), and lots of other helpful tools.
Hayk An’s color scale generatorI stumbled across this color scale generator during my last project. It’s a great resource where you can generate random, visually pleasing color scales, and then adjust their properties, including adding a larger range of colors and adjusting things like saturation and lightness.
Checkout my GitHub for the code for this tutorial. | [
{
"code": null,
"e": 625,
"s": 172,
"text": "If your Matplotlib chart needs a colormap and you’re not using an inbuilt map, chances are you’re going to have a bad time. I used to dread editing colormaps in Python. Every help thread I looked at showed a different approach, and none of them quite matched my situation. This was always disappointing because colormaps can vastly change the message you’re sending with your data visualisation, and can even go so far as to make your chart un-useable."
},
{
"code": null,
"e": 659,
"s": 625,
"text": "Don’t believe me? Check this out."
},
{
"code": null,
"e": 990,
"s": 659,
"text": "Each of these visualisations show identical data (estimated population of local government areas in Australia), but with different colormaps. The data is continuous and positive, which is shown by carefully examining the legend for each. However, the colormaps tell a different story, one that’s a bit like the tale of Goldilocks:"
},
{
"code": null,
"e": 1972,
"s": 990,
"text": "The first chart uses a sequential colormap, where the lightness value changes (either increasing or decreasing) monotonically throughout. If the detail in your visualisation is important then sequential probably isn’t your best bet, since it can be difficult to compare areas with similar values.The second chart uses a diverging colormap. With more colours it’s easier to tell the difference between similar values, but it also suggests to the viewer that the data is centred about a normal baseline, like zero. If we were to normalise our data about the mean then this scale would be appropriate, but since we’re just showing a range of positive values it doesn’t work here.The third chart is just right. This is similar to a sequential map since the color changes gradually throughout, with one end that clearly indicates higher values, and one that indicates lower values. However this map includes more colors, which allows the viewer to more easily compare small differences."
},
{
"code": null,
"e": 2269,
"s": 1972,
"text": "The first chart uses a sequential colormap, where the lightness value changes (either increasing or decreasing) monotonically throughout. If the detail in your visualisation is important then sequential probably isn’t your best bet, since it can be difficult to compare areas with similar values."
},
{
"code": null,
"e": 2650,
"s": 2269,
"text": "The second chart uses a diverging colormap. With more colours it’s easier to tell the difference between similar values, but it also suggests to the viewer that the data is centred about a normal baseline, like zero. If we were to normalise our data about the mean then this scale would be appropriate, but since we’re just showing a range of positive values it doesn’t work here."
},
{
"code": null,
"e": 2956,
"s": 2650,
"text": "The third chart is just right. This is similar to a sequential map since the color changes gradually throughout, with one end that clearly indicates higher values, and one that indicates lower values. However this map includes more colors, which allows the viewer to more easily compare small differences."
},
{
"code": null,
"e": 3084,
"s": 2956,
"text": "These are just a few examples of the colormaps you can use, for more details and options, check out this guide from Matplotlib."
},
{
"code": null,
"e": 3408,
"s": 3084,
"text": "Designing and creating a colormap gets even harder if you are attempting to make it fit in with a theme. For example, a visualisation embedded within a dashboard or website with an existing color scheme. It’s worth putting in the extra work for a thoroughly professional end product, and this guide will help you get there."
},
{
"code": null,
"e": 3505,
"s": 3408,
"text": "Let’s create a test image to work with, and turn off the axis ticks to make it look a bit nicer."
},
{
"code": null,
"e": 3586,
"s": 3505,
"text": "Now let’s edit the image, and test out 4 different inbuilt Matplotlib colormaps."
},
{
"code": null,
"e": 3849,
"s": 3586,
"text": "If the Matplotlib default colormaps don’t suit your need, you can always create your own. For this tutorial I’m going to assume you have some colors you’d like to use in a colormap. If not, scroll down to the bottom for some resources to help choose your colors."
},
{
"code": null,
"e": 4098,
"s": 3849,
"text": "If you have a specific set of colors to use based on a brand or website theme, chances are they’ll be in HEX format. So first up let’s define some functions to convert HEX to RGB, and RGB to Decimal (value between 0 and 1 for each of RBG channels)."
},
{
"code": null,
"e": 4212,
"s": 4098,
"text": "My HEX colors are shown below, along with their RGB equivalents (the code I used to generate this image is here)."
},
{
"code": null,
"e": 4663,
"s": 4212,
"text": "Let’s create a continuous colormap containing all of the colors above. We’ll be using the matplotlib.colors function called LinearSegmentedColormap. This function accepts a dictionary with a red, green and blue entries. Each entry should be a list of x, y0, y1 tuples, forming rows in a table. So, if you want red to increase from 0 to 1 over the bottom half, green to do the same over the middle half, and blue over the top half. Then you would use:"
},
{
"code": null,
"e": 5027,
"s": 4663,
"text": "cdict = {'red': [(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)], 'green': [(0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)], 'blue': [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)]}"
},
{
"code": null,
"e": 5288,
"s": 5027,
"text": "Confused? I was too. So I wrote some code (below) to wrap this function and make it more manageable. The code below can be used to map between an arbitrary number of hex colors in a list, it uses the functions we defined earlier to convert from hex to decimal."
},
{
"code": null,
"e": 5465,
"s": 5288,
"text": "By providing a list of floats from 0 to 1 we can also map the colors to specific locations on the colorbar, in order to stretch the representations of certain parts of the map."
},
{
"code": null,
"e": 5942,
"s": 5465,
"text": "We can also use this code to create a diverging colormap, which is useful if our data is to be displayed about some midpoint, like zero. If the data is not equally centred about the midpoint, for example if it ranges from -2 to 5, we need to shift the centre of the colormap to the midpoint of our data. The code below shows how to do this by using TwoSlopeNorm to create a norm, which is then used within imshow to scale the data to the [0, 1] range before mapping to colors."
},
{
"code": null,
"e": 6345,
"s": 5942,
"text": "Keep in mind that, while I won’t go in to detail in this post, your choice of colors goes beyond mere aesthetics, there is a whole field dedicated to to understanding the effect of different colors and combinations on human understanding. There is also the consideration of how your colormap would look to people with color blindness. You should consider both of these things when choosing your colors."
},
{
"code": null,
"e": 6446,
"s": 6345,
"text": "If you’re in need of some inspiration in choosing your colors, here are some sources I find helpful."
},
{
"code": null,
"e": 6735,
"s": 6446,
"text": "CoolorsCoolors is a fantastic app with so many features. For the purpose of creating a continuous colorscale I prefer their color gradient generation service, which has tonnes of beautiful color palettes that transition well in to continuous scales, and can be tweaked to suit your needs."
},
{
"code": null,
"e": 6995,
"s": 6735,
"text": "Gregor Aisch’s ChromaChroma is useful for optimizing your color palettes. It can be a little bit buggy, but it helps you take two or more colors and generate a full scale of in-between values. It also helpfully tells you whether your scale is colorblind safe."
},
{
"code": null,
"e": 7235,
"s": 6995,
"text": "W3schools color palettesThis has some nice example color palettes. W3 also provides other free services to choose palettes based on color theory, convert between different color formats (e.g. Hex, RGB etc), and lots of other helpful tools."
},
{
"code": null,
"e": 7548,
"s": 7235,
"text": "Hayk An’s color scale generatorI stumbled across this color scale generator during my last project. It’s a great resource where you can generate random, visually pleasing color scales, and then adjust their properties, including adding a larger range of colors and adjusting things like saturation and lightness."
}
]
|
Java SAX Library - GeeksforGeeks | 17 Apr, 2019
SAX (Simple API for XML), is the most widely adopted API for XML in Java and is considered the de-facto standard. Although it started as a library exclusive for Java, it is now a well-known API distributed over a variety of programming languages. It is an open source project and has recently switched to SourceForge project infrastructure that makes it easier to track open SAX issues outside of the high-volume xml-dev list. The current latest version as of 01/10/2018 is SAX 2.0. It uses an event-driven serial-access mechanism for accessing XML documents and is frequently used by applets which need to access XML documents because it is the fastest and least memory consuming API available for parsing XML documents. The mechanism SAX uses makes it independent of the elements that came before, i.e. it is state independent.
Setting up DOM (Document Object Model) is easier than setting up SAX and SAX is harder to visualize than DOM because of its parser interpreting XML items based on events invoked. This also means you cannot return to a specific part of the SAX interpretation or rearrange them. And hence, user heavy applications should use DOM instead of SAX.
However, there are many reasons to familiarize yourself with SAX, even if you are using DOM. Below are the various advantages of SAX over DOM:
Same Error Handling: The kind of exceptions generated by SAX and DOM are identical.
Handling Validation Errors: If you want to throw an exception when a validation error occurs, you need to understand SAX error handling mechanisms.
Converting Existing Data: In DOM, you can convert existing data set into XML. But to be able to implement it, you need a basic understanding of SAX.
Why or when to use SAX?
SAX uses an event model structure to convert or parse data to XML by simply modifying an existing application to deliver SAX events as it reads the data.
SAX is fast and efficient, but its event model makes it most useful for state-independent filtering. It calls different methods when an element tag is encountered and when a text is encountered. So, as long as the processing is state-independent (meaning that it does not depend on the elements that have come before), then SAX works fine.
It does not create an internal representation(tree structure) of the XML data like DOM, but instead simply sends the data to the application as it is read and hence consumes less memory.
The SAX API acts like a serial I/O stream and hence, it is highly recommended for simple applications that require XML parsers.
Classes in SAX Library: There are few classes in SAX library that makes the parsing work very easy. These are:
HandlerBase: This class provides default implementations for DocumentHandler, ErrorHandler, DTDHandler, and EntityResolver: parser writers can use this to provide a default implementation when the user does not specify handlers, and application writers can subclass this to simplify handler writing.InputSource This class allows a SAX application to encapsulate information about an input source in a single object, which may include a public identifier, a system identifier, a byte stream (possibly with a specified encoding), and/or a character stream.
HandlerBase: This class provides default implementations for DocumentHandler, ErrorHandler, DTDHandler, and EntityResolver: parser writers can use this to provide a default implementation when the user does not specify handlers, and application writers can subclass this to simplify handler writing.
InputSource This class allows a SAX application to encapsulate information about an input source in a single object, which may include a public identifier, a system identifier, a byte stream (possibly with a specified encoding), and/or a character stream.
Example:
XML file to be parsed:
<?xml version="1.0"?><GFG> <contributor> <firstname>Baibhav</firstname> <lastname>Ojha</lastname> </contributor></GFG>
Java program to parse the file:
// Java Code to describe implementation// of SAX library import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler; public class ReadXMLFile { public static void main(String argv[]) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); DefaultHandler handler = new DefaultHandler() { boolean bfname = false; boolean blname = false; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("firstname")) { bfname = true; } if (qName.equalsIgnoreCase("lastname")) { blname = true; } } public void characters(char ch[], int start, int length) throws SAXException { if (bfname) { System.out.println("First Name : " + new String(ch, start, length)); bfname = false; } if (blname) { System.out.println("Last Name : " + new String(ch, start, length)); blname = false; } } }; saxParser.parse("C:\\gfg.xml", handler); } catch (Exception e) { e.printStackTrace(); } }}
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java
Overriding in Java | [
{
"code": null,
"e": 24818,
"s": 24790,
"text": "\n17 Apr, 2019"
},
{
"code": null,
"e": 25648,
"s": 24818,
"text": "SAX (Simple API for XML), is the most widely adopted API for XML in Java and is considered the de-facto standard. Although it started as a library exclusive for Java, it is now a well-known API distributed over a variety of programming languages. It is an open source project and has recently switched to SourceForge project infrastructure that makes it easier to track open SAX issues outside of the high-volume xml-dev list. The current latest version as of 01/10/2018 is SAX 2.0. It uses an event-driven serial-access mechanism for accessing XML documents and is frequently used by applets which need to access XML documents because it is the fastest and least memory consuming API available for parsing XML documents. The mechanism SAX uses makes it independent of the elements that came before, i.e. it is state independent."
},
{
"code": null,
"e": 25991,
"s": 25648,
"text": "Setting up DOM (Document Object Model) is easier than setting up SAX and SAX is harder to visualize than DOM because of its parser interpreting XML items based on events invoked. This also means you cannot return to a specific part of the SAX interpretation or rearrange them. And hence, user heavy applications should use DOM instead of SAX."
},
{
"code": null,
"e": 26134,
"s": 25991,
"text": "However, there are many reasons to familiarize yourself with SAX, even if you are using DOM. Below are the various advantages of SAX over DOM:"
},
{
"code": null,
"e": 26218,
"s": 26134,
"text": "Same Error Handling: The kind of exceptions generated by SAX and DOM are identical."
},
{
"code": null,
"e": 26366,
"s": 26218,
"text": "Handling Validation Errors: If you want to throw an exception when a validation error occurs, you need to understand SAX error handling mechanisms."
},
{
"code": null,
"e": 26515,
"s": 26366,
"text": "Converting Existing Data: In DOM, you can convert existing data set into XML. But to be able to implement it, you need a basic understanding of SAX."
},
{
"code": null,
"e": 26539,
"s": 26515,
"text": "Why or when to use SAX?"
},
{
"code": null,
"e": 26693,
"s": 26539,
"text": "SAX uses an event model structure to convert or parse data to XML by simply modifying an existing application to deliver SAX events as it reads the data."
},
{
"code": null,
"e": 27033,
"s": 26693,
"text": "SAX is fast and efficient, but its event model makes it most useful for state-independent filtering. It calls different methods when an element tag is encountered and when a text is encountered. So, as long as the processing is state-independent (meaning that it does not depend on the elements that have come before), then SAX works fine."
},
{
"code": null,
"e": 27220,
"s": 27033,
"text": "It does not create an internal representation(tree structure) of the XML data like DOM, but instead simply sends the data to the application as it is read and hence consumes less memory."
},
{
"code": null,
"e": 27348,
"s": 27220,
"text": "The SAX API acts like a serial I/O stream and hence, it is highly recommended for simple applications that require XML parsers."
},
{
"code": null,
"e": 27459,
"s": 27348,
"text": "Classes in SAX Library: There are few classes in SAX library that makes the parsing work very easy. These are:"
},
{
"code": null,
"e": 28014,
"s": 27459,
"text": "HandlerBase: This class provides default implementations for DocumentHandler, ErrorHandler, DTDHandler, and EntityResolver: parser writers can use this to provide a default implementation when the user does not specify handlers, and application writers can subclass this to simplify handler writing.InputSource This class allows a SAX application to encapsulate information about an input source in a single object, which may include a public identifier, a system identifier, a byte stream (possibly with a specified encoding), and/or a character stream."
},
{
"code": null,
"e": 28314,
"s": 28014,
"text": "HandlerBase: This class provides default implementations for DocumentHandler, ErrorHandler, DTDHandler, and EntityResolver: parser writers can use this to provide a default implementation when the user does not specify handlers, and application writers can subclass this to simplify handler writing."
},
{
"code": null,
"e": 28570,
"s": 28314,
"text": "InputSource This class allows a SAX application to encapsulate information about an input source in a single object, which may include a public identifier, a system identifier, a byte stream (possibly with a specified encoding), and/or a character stream."
},
{
"code": null,
"e": 28579,
"s": 28570,
"text": "Example:"
},
{
"code": null,
"e": 28602,
"s": 28579,
"text": "XML file to be parsed:"
},
{
"code": "<?xml version=\"1.0\"?><GFG> <contributor> <firstname>Baibhav</firstname> <lastname>Ojha</lastname> </contributor></GFG>",
"e": 28741,
"s": 28602,
"text": null
},
{
"code": null,
"e": 28773,
"s": 28741,
"text": "Java program to parse the file:"
},
{
"code": "// Java Code to describe implementation// of SAX library import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler; public class ReadXMLFile { public static void main(String argv[]) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); DefaultHandler handler = new DefaultHandler() { boolean bfname = false; boolean blname = false; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase(\"firstname\")) { bfname = true; } if (qName.equalsIgnoreCase(\"lastname\")) { blname = true; } } public void characters(char ch[], int start, int length) throws SAXException { if (bfname) { System.out.println(\"First Name : \" + new String(ch, start, length)); bfname = false; } if (blname) { System.out.println(\"Last Name : \" + new String(ch, start, length)); blname = false; } } }; saxParser.parse(\"C:\\\\gfg.xml\", handler); } catch (Exception e) { e.printStackTrace(); } }}",
"e": 31230,
"s": 28773,
"text": null
},
{
"code": null,
"e": 31242,
"s": 31230,
"text": "java-basics"
},
{
"code": null,
"e": 31247,
"s": 31242,
"text": "Java"
},
{
"code": null,
"e": 31252,
"s": 31247,
"text": "Java"
},
{
"code": null,
"e": 31350,
"s": 31252,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31382,
"s": 31350,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31412,
"s": 31382,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31431,
"s": 31412,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31449,
"s": 31431,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31481,
"s": 31449,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31501,
"s": 31481,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 31516,
"s": 31501,
"text": "Stream In Java"
},
{
"code": null,
"e": 31540,
"s": 31516,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 31552,
"s": 31540,
"text": "Set in Java"
}
]
|
Balanced Binary Tree in Python | In a binary tree, each node contains two children, i.e left child and right child. Let us suppose we have a binary tree and we need to check if the tree is balanced or not. A Binary tree is said to be balanced if the difference of height of left subtree and right subtree is less than or equal to '1'.
Example
Input-1:
Output:
True
Explanation:
The given binary tree is [1,2,3, NULL, NULL, 6, 7]. The height difference of its left subtree and right subtree is equal to '1', thus it is a height Balanced tree.
Input-2:
Output:
False
Explanation:
The given binary tree is [1,2,3,4, NULL, NULL,NULL,5]. The height difference of its left subtree and right subtree is greater than '1', thus it is not a height balanced tree.
The recursive approach to solve this problem is to find the height of the left subtree and the right subtree and then check if (height(leftsubstree) - height(rightsubtree) <= 1) and return True or False accordingly. Then, we will check recursively for each node of the binary tree.
Take input of nodes of a Binary Tree.
Define a function to find the height of the tree.
A Boolean function to check recursively if the height difference of left subtree and right subtree is not more than '1', then return True.
Return the Result.
Live Demo
class treenode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# funtion to find the height of the left subtree and right subtree
class height:
def __init__(self):
self.height = 0
# function to check if the tree is balanced or not
def isBalanced(root):
lh = height()
rh = height()
if root is None:
return True
return (
(abs(lh.height - rh.height) <= 1)
and isBalanced(root.left)
and isBalanced(root.right)
)
root = treenode(1)
root.left = treenode(2)
root.right = treenode(3)
root.left.left = None
root.left.right = None
root.right.left = treenode(6)
root.right.right = treenode(7)
if isBalanced(root):
print("Balanced")
else:
print("Not Balanced")
Running the above code will generate the output as,
Balanced
The given binary tree [1, 2, 3, NULL, NULL, 6, 7]. The height difference of its left subtree and right subtree is equal to '1', thus it is a height Balanced tree. | [
{
"code": null,
"e": 1364,
"s": 1062,
"text": "In a binary tree, each node contains two children, i.e left child and right child. Let us suppose we have a binary tree and we need to check if the tree is balanced or not. A Binary tree is said to be balanced if the difference of height of left subtree and right subtree is less than or equal to '1'."
},
{
"code": null,
"e": 1372,
"s": 1364,
"text": "Example"
},
{
"code": null,
"e": 1382,
"s": 1372,
"text": "Input-1: "
},
{
"code": null,
"e": 1390,
"s": 1382,
"text": "Output:"
},
{
"code": null,
"e": 1395,
"s": 1390,
"text": "True"
},
{
"code": null,
"e": 1408,
"s": 1395,
"text": "Explanation:"
},
{
"code": null,
"e": 1572,
"s": 1408,
"text": "The given binary tree is [1,2,3, NULL, NULL, 6, 7]. The height difference of its left subtree and right subtree is equal to '1', thus it is a height Balanced tree."
},
{
"code": null,
"e": 1582,
"s": 1572,
"text": "Input-2: "
},
{
"code": null,
"e": 1605,
"s": 1597,
"text": "Output:"
},
{
"code": null,
"e": 1611,
"s": 1605,
"text": "False"
},
{
"code": null,
"e": 1624,
"s": 1611,
"text": "Explanation:"
},
{
"code": null,
"e": 1800,
"s": 1624,
"text": "The given binary tree is [1,2,3,4, NULL, NULL,NULL,5]. The height difference of its left subtree and right subtree is greater than '1', thus it is not a height balanced tree. "
},
{
"code": null,
"e": 2082,
"s": 1800,
"text": "The recursive approach to solve this problem is to find the height of the left subtree and the right subtree and then check if (height(leftsubstree) - height(rightsubtree) <= 1) and return True or False accordingly. Then, we will check recursively for each node of the binary tree."
},
{
"code": null,
"e": 2120,
"s": 2082,
"text": "Take input of nodes of a Binary Tree."
},
{
"code": null,
"e": 2170,
"s": 2120,
"text": "Define a function to find the height of the tree."
},
{
"code": null,
"e": 2309,
"s": 2170,
"text": "A Boolean function to check recursively if the height difference of left subtree and right subtree is not more than '1', then return True."
},
{
"code": null,
"e": 2328,
"s": 2309,
"text": "Return the Result."
},
{
"code": null,
"e": 2338,
"s": 2328,
"text": "Live Demo"
},
{
"code": null,
"e": 3082,
"s": 2338,
"text": "class treenode:\n def __init__(self, data):\n self.data = data\n self.left = self.right = None\n# funtion to find the height of the left subtree and right subtree\nclass height:\n def __init__(self):\n self.height = 0\n# function to check if the tree is balanced or not\ndef isBalanced(root):\n lh = height()\n rh = height()\n if root is None:\n return True\n return (\n (abs(lh.height - rh.height) <= 1)\n and isBalanced(root.left)\n and isBalanced(root.right)\n )\nroot = treenode(1)\nroot.left = treenode(2)\nroot.right = treenode(3)\nroot.left.left = None\nroot.left.right = None\nroot.right.left = treenode(6)\nroot.right.right = treenode(7)\nif isBalanced(root):\n print(\"Balanced\")\nelse:\n print(\"Not Balanced\")"
},
{
"code": null,
"e": 3134,
"s": 3082,
"text": "Running the above code will generate the output as,"
},
{
"code": null,
"e": 3143,
"s": 3134,
"text": "Balanced"
},
{
"code": null,
"e": 3306,
"s": 3143,
"text": "The given binary tree [1, 2, 3, NULL, NULL, 6, 7]. The height difference of its left subtree and right subtree is equal to '1', thus it is a height Balanced tree."
}
]
|
Rank function in MySQL? | The rank() function can be used to give a rank for every row within the partition of a result set.
First, let us create a table −
mysql> create table RankDemo
mysql> (
mysql> id int
mysql> );
Query OK, 0 rows affected (0.53 sec)
Inserting records into table.
mysql> insert into RankDemo values(1);
Query OK, 1 row affected (0.19 sec)
mysql> insert into RankDemo values(3);
Query OK, 1 row affected (0.12 sec)
mysql> insert into RankDemo values(3);
Query OK, 1 row affected (0.11 sec)
mysql> insert into RankDemo values(4);
Query OK, 1 row affected (0.12 sec)
mysql> insert into RankDemo values(5);
Query OK, 1 row affected (0.17 sec)
Displaying all records from the table with the help of select statement. The query is as follows −
mysql> select *from RankDemo;
The following is the output.
+------+
| id |
+------+
| 1 |
| 3 |
| 3 |
| 4 |
| 5 |
+------+
5 rows in set (0.00 sec)
Let us now apply the rank() function as I have discussed above.
mysql> SELECT
mysql> id,RANK() OVER (ORDER BY id ) Ranking
mysql> from RankDemo;
The following is the output that displays the rank.
+------+---------+
| id | Ranking |
+------+---------+
| 1 | 1 |
| 3 | 2 |
| 3 | 2 |
| 4 | 4 |
| 5 | 5 |
+------+---------+
5 rows in set (0.04 sec) | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "The rank() function can be used to give a rank for every row within the partition of a result set."
},
{
"code": null,
"e": 1192,
"s": 1161,
"text": "First, let us create a table −"
},
{
"code": null,
"e": 1300,
"s": 1192,
"text": "mysql> create table RankDemo\n mysql> (\n mysql> id int\n mysql> );\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1330,
"s": 1300,
"text": "Inserting records into table."
},
{
"code": null,
"e": 1713,
"s": 1330,
"text": "mysql> insert into RankDemo values(1);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into RankDemo values(3);\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into RankDemo values(3);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into RankDemo values(4);\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into RankDemo values(5);\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1812,
"s": 1713,
"text": "Displaying all records from the table with the help of select statement. The query is as follows −"
},
{
"code": null,
"e": 1842,
"s": 1812,
"text": "mysql> select *from RankDemo;"
},
{
"code": null,
"e": 1871,
"s": 1842,
"text": "The following is the output."
},
{
"code": null,
"e": 1978,
"s": 1871,
"text": "+------+\n| id |\n+------+\n| 1 |\n| 3 |\n| 3 |\n| 4 |\n| 5 |\n+------+\n5 rows in set (0.00 sec)\n"
},
{
"code": null,
"e": 2042,
"s": 1978,
"text": "Let us now apply the rank() function as I have discussed above."
},
{
"code": null,
"e": 2129,
"s": 2042,
"text": "mysql> SELECT\n mysql> id,RANK() OVER (ORDER BY id ) Ranking\n mysql> from RankDemo;"
},
{
"code": null,
"e": 2181,
"s": 2129,
"text": "The following is the output that displays the rank."
},
{
"code": null,
"e": 2378,
"s": 2181,
"text": "+------+---------+\n| id | Ranking |\n+------+---------+\n| 1 | 1 |\n| 3 | 2 |\n| 3 | 2 |\n| 4 | 4 |\n| 5 | 5 |\n+------+---------+\n5 rows in set (0.04 sec)\n"
}
]
|
How to add a new column to an existing table using JDBC API? | You can add a new column to a table using the ALTER TABLE command.
ALTER TABLE table_name ADD column_name datatype;
Assume we have a table named Sales in the database with 5 columns namely ProductName, CustomerName, DispatchDate, DeliveryTime, Price and, Location as shown below:
+-------------+--------------+--------------+--------------+-------+----------------+
| ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location |
+-------------+--------------+--------------+--------------+-------+----------------+
| Key-Board | Raja | 2019-09-01 | 08:51:36 | 7000 | Hyderabad |
| Earphones | Roja | 2019-05-01 | 05:54:28 | 2000 | Vishakhapatnam |
| Mouse | Puja | 2019-03-01 | 04:26:38 | 3000 | Vijayawada |
| Mobile | Vanaja | 2019-03-01 | 04:26:35 | 9000 | Vijayawada |
| Headset | Jalaja | 2019-04-06 | 05:19:16 | 6000 | Vijayawada |
+-------------+--------------+--------------+--------------+-------+----------------+
Following JDBC program establishes connection with MySQL database, and adds a new column named ID to the Sales table and populates it.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class AddingColumn {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to alter the table
String query = "ALTER TABLE Sales ADD ID INT NOT NULL";
//Executing the query
stmt.executeUpdate(query);
System.out.println("Column added......");
//inserting values in to the added column
PreparedStatement pstmt = con.prepareStatement("UPDATE sales SET id = ? where ProductName = ");
pstmt.setInt(1, 1);
pstmt.setString(2,"Key-Board");
pstmt.executeUpdate();
pstmt.setInt(1, 2);
pstmt.setString(2,"Earphones");
pstmt.executeUpdate();
pstmt.setInt(1, 3);
pstmt.setString(2,"Mouse");
pstmt.executeUpdate();
pstmt.setInt(1, 4);
pstmt.setString(2,"Mobile");
pstmt.executeUpdate();
pstmt.setInt(1, 5);
pstmt.setString(2,"Headset");
pstmt.executeUpdate();
System.out.println("Values inserted......");
}
}
Connection established......
Column added......
Values inserted in the added column
Since we have added one column, if you retrieve the contents of the Sales table using the SELECT command you can observe 7 columns, with additional column named id as:
mysql> select * from Sales;
+-------------+--------------+--------------+--------------+-------+----------------+----+
| ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location | ID |
+-------------+--------------+--------------+--------------+-------+----------------+----+
| Key-Board | Raja | 2019-09-01 | 08:51:36 | 7000 | Hyderabad | 1 |
| Earphones | Roja | 2019-05-01 | 05:54:28 | 2000 | Vishakhapatnam | 2 |
| Mouse | Puja | 2019-03-01 | 04:26:38 | 3000 | Vijayawada | 3 |
| Mobile | Vanaja | 2019-03-01 | 04:26:35 | 9000 | Chennai | 4 |
| Headset | Jalaja | 2019-03-01 | 05:19:16 | 6000 | Delhi | 5 |
+-------------+--------------+--------------+--------------+-------+----------------+----+
5 rows in set (0.00 sec) | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "You can add a new column to a table using the ALTER TABLE command."
},
{
"code": null,
"e": 1178,
"s": 1129,
"text": "ALTER TABLE table_name ADD column_name datatype;"
},
{
"code": null,
"e": 1342,
"s": 1178,
"text": "Assume we have a table named Sales in the database with 5 columns namely ProductName, CustomerName, DispatchDate, DeliveryTime, Price and, Location as shown below:"
},
{
"code": null,
"e": 2116,
"s": 1342,
"text": "+-------------+--------------+--------------+--------------+-------+----------------+\n| ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location |\n+-------------+--------------+--------------+--------------+-------+----------------+\n| Key-Board | Raja | 2019-09-01 | 08:51:36 | 7000 | Hyderabad |\n| Earphones | Roja | 2019-05-01 | 05:54:28 | 2000 | Vishakhapatnam |\n| Mouse | Puja | 2019-03-01 | 04:26:38 | 3000 | Vijayawada |\n| Mobile | Vanaja | 2019-03-01 | 04:26:35 | 9000 | Vijayawada |\n| Headset | Jalaja | 2019-04-06 | 05:19:16 | 6000 | Vijayawada |\n+-------------+--------------+--------------+--------------+-------+----------------+"
},
{
"code": null,
"e": 2251,
"s": 2116,
"text": "Following JDBC program establishes connection with MySQL database, and adds a new column named ID to the Sales table and populates it."
},
{
"code": null,
"e": 3772,
"s": 2251,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class AddingColumn {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to alter the table\n String query = \"ALTER TABLE Sales ADD ID INT NOT NULL\";\n //Executing the query\n stmt.executeUpdate(query);\n System.out.println(\"Column added......\");\n //inserting values in to the added column\n PreparedStatement pstmt = con.prepareStatement(\"UPDATE sales SET id = ? where ProductName = \");\n pstmt.setInt(1, 1);\n pstmt.setString(2,\"Key-Board\");\n pstmt.executeUpdate();\n\n pstmt.setInt(1, 2);\n pstmt.setString(2,\"Earphones\");\n pstmt.executeUpdate();\n\n pstmt.setInt(1, 3);\n pstmt.setString(2,\"Mouse\");\n pstmt.executeUpdate();\n\n pstmt.setInt(1, 4);\n pstmt.setString(2,\"Mobile\");\n pstmt.executeUpdate();\n\n pstmt.setInt(1, 5);\n pstmt.setString(2,\"Headset\");\n pstmt.executeUpdate();\n\n System.out.println(\"Values inserted......\");\n }\n}"
},
{
"code": null,
"e": 3856,
"s": 3772,
"text": "Connection established......\nColumn added......\nValues inserted in the added column"
},
{
"code": null,
"e": 4024,
"s": 3856,
"text": "Since we have added one column, if you retrieve the contents of the Sales table using the SELECT command you can observe 7 columns, with additional column named id as:"
},
{
"code": null,
"e": 4896,
"s": 4024,
"text": "mysql> select * from Sales;\n+-------------+--------------+--------------+--------------+-------+----------------+----+\n| ProductName | CustomerName | DispatchDate | DeliveryTime | Price | Location | ID |\n+-------------+--------------+--------------+--------------+-------+----------------+----+\n| Key-Board | Raja | 2019-09-01 | 08:51:36 | 7000 | Hyderabad | 1 |\n| Earphones | Roja | 2019-05-01 | 05:54:28 | 2000 | Vishakhapatnam | 2 |\n| Mouse | Puja | 2019-03-01 | 04:26:38 | 3000 | Vijayawada | 3 |\n| Mobile | Vanaja | 2019-03-01 | 04:26:35 | 9000 | Chennai | 4 |\n| Headset | Jalaja | 2019-03-01 | 05:19:16 | 6000 | Delhi | 5 |\n+-------------+--------------+--------------+--------------+-------+----------------+----+\n5 rows in set (0.00 sec)"
}
]
|
Playit | #myDIV { background-color:lightblue; transform:scale(1.1);} | []
|
Python - cmath.polar() function - GeeksforGeeks | 28 May, 2020
cMath module contains a number of functions which is used for mathematical operations for complex numbers. The cmath.polar() function is used to convert a complex number to polar coordinates. The value passed in this function can be int, float, and complex numbers.
Syntax: cmath.polar(x)
Parameter:This method accepts the following parameters.
x :This parameter is the number to find polar coordinates of.
Returns:This method returns a tuple value that represent the polar coordinates.
Below examples illustrate the use of above function:
Example #1 :
Python3
# Python code to implement# the polar()function # importing "cmath"# for mathematical operations import cmath # using cmath.polar() method val = cmath.polar(1) print(val)
Output:
(1.0, 0.0)
Example 2:
Python3
# Python code to implement# the polar()function # importing "cmath"# for mathematical operations import cmath # using cmath.polar() method val = cmath.polar(2 + 4j)print(val)
Output:
(4.47213595499958, 1.1071487177940904)
Python Cmath-library
Python math-library-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24317,
"s": 24289,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 24583,
"s": 24317,
"text": "cMath module contains a number of functions which is used for mathematical operations for complex numbers. The cmath.polar() function is used to convert a complex number to polar coordinates. The value passed in this function can be int, float, and complex numbers."
},
{
"code": null,
"e": 24606,
"s": 24583,
"text": "Syntax: cmath.polar(x)"
},
{
"code": null,
"e": 24662,
"s": 24606,
"text": "Parameter:This method accepts the following parameters."
},
{
"code": null,
"e": 24724,
"s": 24662,
"text": "x :This parameter is the number to find polar coordinates of."
},
{
"code": null,
"e": 24804,
"s": 24724,
"text": "Returns:This method returns a tuple value that represent the polar coordinates."
},
{
"code": null,
"e": 24857,
"s": 24804,
"text": "Below examples illustrate the use of above function:"
},
{
"code": null,
"e": 24871,
"s": 24857,
"text": "Example #1 : "
},
{
"code": null,
"e": 24879,
"s": 24871,
"text": "Python3"
},
{
"code": "# Python code to implement# the polar()function # importing \"cmath\"# for mathematical operations import cmath # using cmath.polar() method val = cmath.polar(1) print(val)",
"e": 25062,
"s": 24879,
"text": null
},
{
"code": null,
"e": 25070,
"s": 25062,
"text": "Output:"
},
{
"code": null,
"e": 25081,
"s": 25070,
"text": "(1.0, 0.0)"
},
{
"code": null,
"e": 25092,
"s": 25081,
"text": "Example 2:"
},
{
"code": null,
"e": 25100,
"s": 25092,
"text": "Python3"
},
{
"code": "# Python code to implement# the polar()function # importing \"cmath\"# for mathematical operations import cmath # using cmath.polar() method val = cmath.polar(2 + 4j)print(val)",
"e": 25287,
"s": 25100,
"text": null
},
{
"code": null,
"e": 25295,
"s": 25287,
"text": "Output:"
},
{
"code": null,
"e": 25334,
"s": 25295,
"text": "(4.47213595499958, 1.1071487177940904)"
},
{
"code": null,
"e": 25355,
"s": 25334,
"text": "Python Cmath-library"
},
{
"code": null,
"e": 25385,
"s": 25355,
"text": "Python math-library-functions"
},
{
"code": null,
"e": 25392,
"s": 25385,
"text": "Python"
},
{
"code": null,
"e": 25490,
"s": 25392,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25522,
"s": 25490,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25578,
"s": 25522,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25620,
"s": 25578,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25662,
"s": 25620,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25684,
"s": 25662,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25715,
"s": 25684,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25754,
"s": 25715,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25809,
"s": 25754,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25838,
"s": 25809,
"text": "Create a directory in Python"
}
]
|
arc function in C - GeeksforGeeks | 23 May, 2019
The header file graphics.h contains arc() function which draws an arc with center at (x, y) and given radius. start_angle is the starting point of angle and end_angle is the ending point of the angle. The value of the angle can vary from 0 to 360 degree.
Syntax :
void arc(int x, int y, int start_angle,
int end_angle, int radius);
where,
(x, y) is the center of the arc.
start_angle is the starting angle and
end_angle is the ending angle.
'radius' is the Radius of the arc.
Examples :
Input : x=250, y=250, start_angle = 155, end_angle = 300, radius = 100
Output :
Input : x=250, y=250, start_angle = 0, end_angle = 300, radius = 100;
Output :
Below is the implementation of arc() function :
// C implementation of arc function#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; // location of the arc int x = 250; int y = 250; // starting angle and ending angle // of the arc int start_angle = 155; int end_angle = 300; // radius of the arc int radius = 100; // initgraph initializes the graphics system // by loading a graphics driver from disk initgraph(&gd, &gm, ""); // arc function arc(x, y, start_angle, end_angle, radius); getch(); // closegraph function closes the graphics // mode and deallocates all memory allocated // by graphics system closegraph(); return 0;}
Output:
Kirti_Mangal
c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Arrow operator -> in C/C++ with Examples
Understanding "extern" keyword in C
Storage Classes in C
Smart Pointers in C++ and How to Use Them
Switch Statement in C/C++ | [
{
"code": null,
"e": 24234,
"s": 24206,
"text": "\n23 May, 2019"
},
{
"code": null,
"e": 24489,
"s": 24234,
"text": "The header file graphics.h contains arc() function which draws an arc with center at (x, y) and given radius. start_angle is the starting point of angle and end_angle is the ending point of the angle. The value of the angle can vary from 0 to 360 degree."
},
{
"code": null,
"e": 24498,
"s": 24489,
"text": "Syntax :"
},
{
"code": null,
"e": 24725,
"s": 24498,
"text": "void arc(int x, int y, int start_angle,\n int end_angle, int radius);\n\nwhere,\n(x, y) is the center of the arc.\nstart_angle is the starting angle and \nend_angle is the ending angle.\n'radius' is the Radius of the arc.\n"
},
{
"code": null,
"e": 24736,
"s": 24725,
"text": "Examples :"
},
{
"code": null,
"e": 24899,
"s": 24736,
"text": "Input : x=250, y=250, start_angle = 155, end_angle = 300, radius = 100\nOutput :\n\n\nInput : x=250, y=250, start_angle = 0, end_angle = 300, radius = 100;\nOutput :\n\n"
},
{
"code": null,
"e": 24947,
"s": 24899,
"text": "Below is the implementation of arc() function :"
},
{
"code": "// C implementation of arc function#include <graphics.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; // location of the arc int x = 250; int y = 250; // starting angle and ending angle // of the arc int start_angle = 155; int end_angle = 300; // radius of the arc int radius = 100; // initgraph initializes the graphics system // by loading a graphics driver from disk initgraph(&gd, &gm, \"\"); // arc function arc(x, y, start_angle, end_angle, radius); getch(); // closegraph function closes the graphics // mode and deallocates all memory allocated // by graphics system closegraph(); return 0;}",
"e": 25799,
"s": 24947,
"text": null
},
{
"code": null,
"e": 25807,
"s": 25799,
"text": "Output:"
},
{
"code": null,
"e": 25822,
"s": 25809,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 25833,
"s": 25822,
"text": "c-graphics"
},
{
"code": null,
"e": 25851,
"s": 25833,
"text": "computer-graphics"
},
{
"code": null,
"e": 25862,
"s": 25851,
"text": "C Language"
},
{
"code": null,
"e": 25960,
"s": 25862,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25969,
"s": 25960,
"text": "Comments"
},
{
"code": null,
"e": 25982,
"s": 25969,
"text": "Old Comments"
},
{
"code": null,
"e": 26020,
"s": 25982,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26046,
"s": 26020,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 26066,
"s": 26046,
"text": "Multithreading in C"
},
{
"code": null,
"e": 26088,
"s": 26066,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 26126,
"s": 26088,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 26167,
"s": 26126,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 26203,
"s": 26167,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 26224,
"s": 26203,
"text": "Storage Classes in C"
},
{
"code": null,
"e": 26266,
"s": 26224,
"text": "Smart Pointers in C++ and How to Use Them"
}
]
|
Python List sort() Method | Python list method sort() sorts objects of list, use compare func if given.
Following is the syntax for sort() method −
list.sort([func])
NA
NA
This method does not return any value but it changes from the original list.
The following example shows the usage of sort() method.
#!/usr/bin/python
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.sort();
print "List : ", aList
When we run above program, it produces following result −
List : [123, 'abc', 'xyz', 'xyz', 'zara']
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": 2320,
"s": 2244,
"text": "Python list method sort() sorts objects of list, use compare func if given."
},
{
"code": null,
"e": 2364,
"s": 2320,
"text": "Following is the syntax for sort() method −"
},
{
"code": null,
"e": 2383,
"s": 2364,
"text": "list.sort([func])\n"
},
{
"code": null,
"e": 2386,
"s": 2383,
"text": "NA"
},
{
"code": null,
"e": 2389,
"s": 2386,
"text": "NA"
},
{
"code": null,
"e": 2466,
"s": 2389,
"text": "This method does not return any value but it changes from the original list."
},
{
"code": null,
"e": 2522,
"s": 2466,
"text": "The following example shows the usage of sort() method."
},
{
"code": null,
"e": 2622,
"s": 2522,
"text": "#!/usr/bin/python\n\naList = [123, 'xyz', 'zara', 'abc', 'xyz'];\naList.sort();\nprint \"List : \", aList"
},
{
"code": null,
"e": 2680,
"s": 2622,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 2724,
"s": 2680,
"text": "List : [123, 'abc', 'xyz', 'xyz', 'zara']\n"
},
{
"code": null,
"e": 2761,
"s": 2724,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2777,
"s": 2761,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2810,
"s": 2777,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2829,
"s": 2810,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2864,
"s": 2829,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 2886,
"s": 2864,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 2920,
"s": 2886,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 2948,
"s": 2920,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 2983,
"s": 2948,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 2997,
"s": 2983,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3030,
"s": 2997,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3047,
"s": 3030,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3054,
"s": 3047,
"text": " Print"
},
{
"code": null,
"e": 3065,
"s": 3054,
"text": " Add Notes"
}
]
|
GATE | GATE CS 1997 | Question 40 - GeeksforGeeks | 20 Nov, 2018
Consider a logic circuit shown in figure below. The functions f1,f2 and f (in canonical sum of products form in decimal notation) are :f1(w,x,y,z) = ∑ 8,9,10f2(w,x,y,z) = ∑ 7,8,12,13,14,15f(w,x,y,z) = ∑ 8,9
The Function f3 is
a. ∑9,10
b. ∑9
c. ∑1,8,9
d. ∑8,10,15
(A) a(B) b(C) c(D) dAnswer: (B)Explanation:Quiz of this Question
GATE CS 1997
GATE-GATE CS 1997
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25613,
"s": 25585,
"text": "\n20 Nov, 2018"
},
{
"code": null,
"e": 25821,
"s": 25613,
"text": "Consider a logic circuit shown in figure below. The functions f1,f2 and f (in canonical sum of products form in decimal notation) are :f1(w,x,y,z) = ∑ 8,9,10f2(w,x,y,z) = ∑ 7,8,12,13,14,15f(w,x,y,z) = ∑ 8,9"
},
{
"code": null,
"e": 25840,
"s": 25821,
"text": "The Function f3 is"
},
{
"code": null,
"e": 25877,
"s": 25840,
"text": "a. ∑9,10\nb. ∑9\nc. ∑1,8,9\nd. ∑8,10,15"
},
{
"code": null,
"e": 25942,
"s": 25877,
"text": "(A) a(B) b(C) c(D) dAnswer: (B)Explanation:Quiz of this Question"
},
{
"code": null,
"e": 25955,
"s": 25942,
"text": "GATE CS 1997"
},
{
"code": null,
"e": 25973,
"s": 25955,
"text": "GATE-GATE CS 1997"
},
{
"code": null,
"e": 25978,
"s": 25973,
"text": "GATE"
},
{
"code": null,
"e": 26076,
"s": 25978,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26110,
"s": 26076,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26144,
"s": 26110,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26178,
"s": 26144,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26211,
"s": 26178,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26247,
"s": 26211,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26281,
"s": 26247,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26317,
"s": 26281,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26351,
"s": 26317,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26385,
"s": 26351,
"text": "GATE | GATE-CS-2009 | Question 38"
}
]
|
PyQt5 - Setting background color to lineedit of ComboBox - GeeksforGeeks | 04 May, 2020
In this article we will see how we can set the background color to the line edit part of combo box, line edit part of the combo box is in which text is shown and edit.
In order to add background color to the line edit part of the combo box, do the following –
1. Create a combo box2. Create a line edit widget3. Change background color of the line edit widget4. Add line edit widget to the combo box
Syntax :
# creating line edit widget
line_edit = QLineEdit()
# setting background color to the line edit widget
line_edit.setStyleSheet("QLineEdit"
"{"
"background : lightblue;"
"}")
# adding line edit widget to combo box
self.combo_box.setLineEdit(line_edit)
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 150, 30) # making combo box editable self.combo_box.setEditable(True) # geek list geek_list = ["Sayian", "Super Sayian", "Super Sayian 2", "Super Sayian B"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating line edit widget line_edit = QLineEdit() # setting background color to the line edit widget line_edit.setStyleSheet("QLineEdit" "{" "background : lightblue;" "}") # adding line edit widget to combo box self.combo_box.setLineEdit(line_edit) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python PyQt5-ComboBox-stylesheet
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 26223,
"s": 26195,
"text": "\n04 May, 2020"
},
{
"code": null,
"e": 26391,
"s": 26223,
"text": "In this article we will see how we can set the background color to the line edit part of combo box, line edit part of the combo box is in which text is shown and edit."
},
{
"code": null,
"e": 26483,
"s": 26391,
"text": "In order to add background color to the line edit part of the combo box, do the following –"
},
{
"code": null,
"e": 26623,
"s": 26483,
"text": "1. Create a combo box2. Create a line edit widget3. Change background color of the line edit widget4. Add line edit widget to the combo box"
},
{
"code": null,
"e": 26632,
"s": 26623,
"text": "Syntax :"
},
{
"code": null,
"e": 26983,
"s": 26632,
"text": "# creating line edit widget\nline_edit = QLineEdit()\n \n# setting background color to the line edit widget\nline_edit.setStyleSheet(\"QLineEdit\"\n \"{\"\n \"background : lightblue;\"\n \"}\")\n \n \n# adding line edit widget to combo box\nself.combo_box.setLineEdit(line_edit)\n"
},
{
"code": null,
"e": 27011,
"s": 26983,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 150, 30) # making combo box editable self.combo_box.setEditable(True) # geek list geek_list = [\"Sayian\", \"Super Sayian\", \"Super Sayian 2\", \"Super Sayian B\"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating line edit widget line_edit = QLineEdit() # setting background color to the line edit widget line_edit.setStyleSheet(\"QLineEdit\" \"{\" \"background : lightblue;\" \"}\") # adding line edit widget to combo box self.combo_box.setLineEdit(line_edit) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 28508,
"s": 27011,
"text": null
},
{
"code": null,
"e": 28517,
"s": 28508,
"text": "Output :"
},
{
"code": null,
"e": 28539,
"s": 28517,
"text": "Python PyQt5-ComboBox"
},
{
"code": null,
"e": 28572,
"s": 28539,
"text": "Python PyQt5-ComboBox-stylesheet"
},
{
"code": null,
"e": 28583,
"s": 28572,
"text": "Python-gui"
},
{
"code": null,
"e": 28595,
"s": 28583,
"text": "Python-PyQt"
},
{
"code": null,
"e": 28602,
"s": 28595,
"text": "Python"
},
{
"code": null,
"e": 28700,
"s": 28602,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28718,
"s": 28700,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28753,
"s": 28718,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28785,
"s": 28753,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28807,
"s": 28785,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28849,
"s": 28807,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28879,
"s": 28849,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28905,
"s": 28879,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28934,
"s": 28905,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28978,
"s": 28934,
"text": "Reading and Writing to text files in Python"
}
]
|
Continued Fraction Factorization algorithm - GeeksforGeeks | 02 Sep, 2020
The continued fraction factorization method (CFRAC) is a general-purpose factorization algorithm valid for integers. It calculates factors of a given integer number without considering its unique properties. It has a sub-exponential running time. It was first described in 1931 by D. H. Lehmer and R. E. Powers and later in 1975 were developed into a computer algorithm by Michael A. Morrison and John Brillhart.
(1)
is called a Continued Fraction, where ai and bi are either real or complex values for all i > = 0. When all the values of bi‘s are 1, then it is called a simple continued fraction.
A Simple Continued Fraction can be denoted as:
(2)
where Ck= [a0; a1, a2, ..., an] for k<=n is the k-th convergent of the Simple Continued Fraction.An Infinite Continued Fraction [a0; a1, a2, ..., ak, ...] is defined as a limit of the convergents Ck=[a0; a1, a2, ..., an]
Algorithm:This algorithm uses residues produced in the Continued Fraction of (mn)1/2 for some m to produce a square number.
This algorithm solves the mathematical equation:
(3)
CFRAC algorithm has a time complexity of:
(4)
Example 1:
Input: continued_fraction((10/7))
Output: [1, 2, 3]
Explanation:
(5)
Example 2:
Input: list(continued_fraction_convergents([0, 2, 1, 2]))
Output: [0, 1/2, 1/3, 3/8]
Explanation:
(6)
Example 3:
Input: continued_fraction_reduce([1, 2, 3, 4, 5])
Output: 225/157
Explanation:
(7)
#using sympy modulefrom sympy.ntheory.continued_fraction import continued_fractionfrom sympy import sqrt#calling continued_fraction methodcontinued_fraction(10/7)
Output:
[1, 2, 3]
Code 2: To convert a Continued Fraction into fraction.
#using sympy modulefrom sympy.ntheory.continued_fraction import continued_fraction_reduce #calling continued_fraction_reduce methodcontinued_fraction_reduce([1, 2, 3, 4, 5])
Output:
225/157
Code 3: To get a list of convergents from a Continued fraction.
# using sympy modulefrom sympy.core import Rational, pifrom sympy import Sfrom sympy.ntheory.continued_fraction import continued_fraction_convergents, continued_fraction_iterator # calling continued_fraction_convergents method and # passing it as a parameter to a listlist(continued_fraction_convergents([0, 2, 1, 2]))
Output:
[0, 1/2, 1/3, 3/8]
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 25952,
"s": 25537,
"text": "The continued fraction factorization method (CFRAC) is a general-purpose factorization algorithm valid for integers. It calculates factors of a given integer number without considering its unique properties. It has a sub-exponential running time. It was first described in 1931 by D. H. Lehmer and R. E. Powers and later in 1975 were developed into a computer algorithm by Michael A. Morrison and John Brillhart."
},
{
"code": null,
"e": 25959,
"s": 25952,
"text": "(1) "
},
{
"code": null,
"e": 26140,
"s": 25959,
"text": "is called a Continued Fraction, where ai and bi are either real or complex values for all i > = 0. When all the values of bi‘s are 1, then it is called a simple continued fraction."
},
{
"code": null,
"e": 26187,
"s": 26140,
"text": "A Simple Continued Fraction can be denoted as:"
},
{
"code": null,
"e": 26194,
"s": 26187,
"text": "(2) "
},
{
"code": null,
"e": 26415,
"s": 26194,
"text": "where Ck= [a0; a1, a2, ..., an] for k<=n is the k-th convergent of the Simple Continued Fraction.An Infinite Continued Fraction [a0; a1, a2, ..., ak, ...] is defined as a limit of the convergents Ck=[a0; a1, a2, ..., an]"
},
{
"code": null,
"e": 26540,
"s": 26415,
"text": "Algorithm:This algorithm uses residues produced in the Continued Fraction of (mn)1/2 for some m to produce a square number. "
},
{
"code": null,
"e": 26589,
"s": 26540,
"text": "This algorithm solves the mathematical equation:"
},
{
"code": null,
"e": 26596,
"s": 26589,
"text": "(3) "
},
{
"code": null,
"e": 26638,
"s": 26596,
"text": "CFRAC algorithm has a time complexity of:"
},
{
"code": null,
"e": 26645,
"s": 26638,
"text": "(4) "
},
{
"code": null,
"e": 26656,
"s": 26645,
"text": "Example 1:"
},
{
"code": null,
"e": 26725,
"s": 26656,
"text": " \nInput: continued_fraction((10/7))\nOutput: [1, 2, 3]\n\nExplanation:\n"
},
{
"code": null,
"e": 26732,
"s": 26725,
"text": "(5) "
},
{
"code": null,
"e": 26743,
"s": 26732,
"text": "Example 2:"
},
{
"code": null,
"e": 26843,
"s": 26743,
"text": "Input: list(continued_fraction_convergents([0, 2, 1, 2]))\nOutput: [0, 1/2, 1/3, 3/8]\nExplanation:\n"
},
{
"code": null,
"e": 26850,
"s": 26843,
"text": "(6) "
},
{
"code": null,
"e": 26861,
"s": 26850,
"text": "Example 3:"
},
{
"code": null,
"e": 26944,
"s": 26861,
"text": " \nInput: continued_fraction_reduce([1, 2, 3, 4, 5]) \nOutput: 225/157\nExplanation:\n"
},
{
"code": null,
"e": 26951,
"s": 26944,
"text": "(7) "
},
{
"code": "#using sympy modulefrom sympy.ntheory.continued_fraction import continued_fractionfrom sympy import sqrt#calling continued_fraction methodcontinued_fraction(10/7)",
"e": 27114,
"s": 26951,
"text": null
},
{
"code": null,
"e": 27122,
"s": 27114,
"text": "Output:"
},
{
"code": null,
"e": 27133,
"s": 27122,
"text": "[1, 2, 3]\n"
},
{
"code": null,
"e": 27188,
"s": 27133,
"text": "Code 2: To convert a Continued Fraction into fraction."
},
{
"code": "#using sympy modulefrom sympy.ntheory.continued_fraction import continued_fraction_reduce #calling continued_fraction_reduce methodcontinued_fraction_reduce([1, 2, 3, 4, 5])",
"e": 27364,
"s": 27188,
"text": null
},
{
"code": null,
"e": 27372,
"s": 27364,
"text": "Output:"
},
{
"code": null,
"e": 27381,
"s": 27372,
"text": "225/157\n"
},
{
"code": null,
"e": 27445,
"s": 27381,
"text": "Code 3: To get a list of convergents from a Continued fraction."
},
{
"code": "# using sympy modulefrom sympy.core import Rational, pifrom sympy import Sfrom sympy.ntheory.continued_fraction import continued_fraction_convergents, continued_fraction_iterator # calling continued_fraction_convergents method and # passing it as a parameter to a listlist(continued_fraction_convergents([0, 2, 1, 2]))",
"e": 27769,
"s": 27445,
"text": null
},
{
"code": null,
"e": 27777,
"s": 27769,
"text": "Output:"
},
{
"code": null,
"e": 27797,
"s": 27777,
"text": "[0, 1/2, 1/3, 3/8]\n"
},
{
"code": null,
"e": 27804,
"s": 27797,
"text": "Python"
},
{
"code": null,
"e": 27902,
"s": 27804,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27934,
"s": 27902,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27976,
"s": 27934,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28018,
"s": 27976,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28074,
"s": 28018,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28101,
"s": 28074,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28140,
"s": 28101,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28171,
"s": 28140,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28200,
"s": 28171,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28222,
"s": 28200,
"text": "Defaultdict in Python"
}
]
|
PHP | imagecopymerge() Function - GeeksforGeeks | 23 Aug, 2019
The imagecopymerge() function is an inbuilt function in PHP which is used to copy and merge the image into a single image. This function returns True on success or False on failure.
Syntax:
bool imagecopymerge ( $dst_image, $src_image, $dst_x, $dst_y,
$src_x, $src_y, $src_w, $src_h, $pct )
Parameters: This function accepts nine parameters as mentioned above and described below:
$dst_image: This parameter is used to set destination image link resource.
$src_image: This parameter is used to set source image link resource.
$dst_x: This parameter is used to set x-coordinate of destination point.
$dst_y: This parameter is used to set y-coordinate of destination point.
$src_x: This parameter is used to set x-coordinate of source point.
$src_y: This parameter is used to set x-coordinate of source point.
$src_w: This parameter is used to set source width.
$src_h: This parameter is used to set source height.
$pct: The two images will be merged with the help of $pct variables. The range of pct is 0 to 100. If $pct = 0, then no action is taken and when $pct = 100 then this function behaves similar to imagecopy() function for pallete images, except ignoring the alpha components. It implements alpha transparency for true color images.
Return Value: This function returns True on success or False on failure.
Below programs illustrate the imagecopymerge() function in PHP:
Program 1:Input Source Image:Input Destination Image:
<?php// Create image instances$dest = imagecreatefromgif('https://media.geeksforgeeks.org/wp-content/uploads/animateImages.gif');$src = imagecreatefromgif('https://media.geeksforgeeks.org/wp-content/uploads/slider.gif'); // Copy and mergeimagecopymerge($dest, $src, 10, 10, 0, 0, 500, 200, 75); // Output and free from memoryheader('Content-Type: image/gif');imagegif($dest); imagedestroy($dest);imagedestroy($src);?>
Output:
Program 2:Input Source Image:Input Destination Image:
<?php// Create image instances$dest = imagecreatefrompng('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-9.png');$src = imagecreatefrompng('https://media.geeksforgeeks.org/wp-content/uploads/col1.png'); // Copy and mergeimagecopymerge($dest, $src, 10, 10, 0, 0, 500, 200, 75); // Output and free from memoryheader('Content-Type: image/png');imagegif($dest); imagedestroy($dest);imagedestroy($src);?>
Output:
Related Articles:
PHP | imagecolorclosestalpha() Function
PHP | imagecolorallocatealpha() Function
PHP | imagecolorallocate() Function
Reference: http://php.net/manual/en/function.imagecopymerge.php
Image-Processing
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26281,
"s": 26253,
"text": "\n23 Aug, 2019"
},
{
"code": null,
"e": 26463,
"s": 26281,
"text": "The imagecopymerge() function is an inbuilt function in PHP which is used to copy and merge the image into a single image. This function returns True on success or False on failure."
},
{
"code": null,
"e": 26471,
"s": 26463,
"text": "Syntax:"
},
{
"code": null,
"e": 26573,
"s": 26471,
"text": "bool imagecopymerge ( $dst_image, $src_image, $dst_x, $dst_y, \n$src_x, $src_y, $src_w, $src_h, $pct )"
},
{
"code": null,
"e": 26663,
"s": 26573,
"text": "Parameters: This function accepts nine parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26738,
"s": 26663,
"text": "$dst_image: This parameter is used to set destination image link resource."
},
{
"code": null,
"e": 26808,
"s": 26738,
"text": "$src_image: This parameter is used to set source image link resource."
},
{
"code": null,
"e": 26881,
"s": 26808,
"text": "$dst_x: This parameter is used to set x-coordinate of destination point."
},
{
"code": null,
"e": 26954,
"s": 26881,
"text": "$dst_y: This parameter is used to set y-coordinate of destination point."
},
{
"code": null,
"e": 27022,
"s": 26954,
"text": "$src_x: This parameter is used to set x-coordinate of source point."
},
{
"code": null,
"e": 27090,
"s": 27022,
"text": "$src_y: This parameter is used to set x-coordinate of source point."
},
{
"code": null,
"e": 27142,
"s": 27090,
"text": "$src_w: This parameter is used to set source width."
},
{
"code": null,
"e": 27195,
"s": 27142,
"text": "$src_h: This parameter is used to set source height."
},
{
"code": null,
"e": 27524,
"s": 27195,
"text": "$pct: The two images will be merged with the help of $pct variables. The range of pct is 0 to 100. If $pct = 0, then no action is taken and when $pct = 100 then this function behaves similar to imagecopy() function for pallete images, except ignoring the alpha components. It implements alpha transparency for true color images."
},
{
"code": null,
"e": 27597,
"s": 27524,
"text": "Return Value: This function returns True on success or False on failure."
},
{
"code": null,
"e": 27661,
"s": 27597,
"text": "Below programs illustrate the imagecopymerge() function in PHP:"
},
{
"code": null,
"e": 27715,
"s": 27661,
"text": "Program 1:Input Source Image:Input Destination Image:"
},
{
"code": "<?php// Create image instances$dest = imagecreatefromgif('https://media.geeksforgeeks.org/wp-content/uploads/animateImages.gif');$src = imagecreatefromgif('https://media.geeksforgeeks.org/wp-content/uploads/slider.gif'); // Copy and mergeimagecopymerge($dest, $src, 10, 10, 0, 0, 500, 200, 75); // Output and free from memoryheader('Content-Type: image/gif');imagegif($dest); imagedestroy($dest);imagedestroy($src);?>",
"e": 28136,
"s": 27715,
"text": null
},
{
"code": null,
"e": 28144,
"s": 28136,
"text": "Output:"
},
{
"code": null,
"e": 28198,
"s": 28144,
"text": "Program 2:Input Source Image:Input Destination Image:"
},
{
"code": "<?php// Create image instances$dest = imagecreatefrompng('https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-9.png');$src = imagecreatefrompng('https://media.geeksforgeeks.org/wp-content/uploads/col1.png'); // Copy and mergeimagecopymerge($dest, $src, 10, 10, 0, 0, 500, 200, 75); // Output and free from memoryheader('Content-Type: image/png');imagegif($dest); imagedestroy($dest);imagedestroy($src);?>",
"e": 28619,
"s": 28198,
"text": null
},
{
"code": null,
"e": 28627,
"s": 28619,
"text": "Output:"
},
{
"code": null,
"e": 28645,
"s": 28627,
"text": "Related Articles:"
},
{
"code": null,
"e": 28685,
"s": 28645,
"text": "PHP | imagecolorclosestalpha() Function"
},
{
"code": null,
"e": 28726,
"s": 28685,
"text": "PHP | imagecolorallocatealpha() Function"
},
{
"code": null,
"e": 28762,
"s": 28726,
"text": "PHP | imagecolorallocate() Function"
},
{
"code": null,
"e": 28826,
"s": 28762,
"text": "Reference: http://php.net/manual/en/function.imagecopymerge.php"
},
{
"code": null,
"e": 28843,
"s": 28826,
"text": "Image-Processing"
},
{
"code": null,
"e": 28856,
"s": 28843,
"text": "PHP-function"
},
{
"code": null,
"e": 28860,
"s": 28856,
"text": "PHP"
},
{
"code": null,
"e": 28877,
"s": 28860,
"text": "Web Technologies"
},
{
"code": null,
"e": 28881,
"s": 28877,
"text": "PHP"
},
{
"code": null,
"e": 28979,
"s": 28881,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29029,
"s": 28979,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 29069,
"s": 29029,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 29130,
"s": 29069,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 29180,
"s": 29130,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 29225,
"s": 29180,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 29265,
"s": 29225,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29298,
"s": 29265,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29343,
"s": 29298,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29386,
"s": 29343,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Python | sympy.cos() method - GeeksforGeeks | 19 Jul, 2019
In simpy, cos() method is cosine function. Using the cos(x) method in simpy module, we can compute the cosine of x.
Syntax : sympy.cos(x)
Return : Returns the cosine of x
Code #1:Below is the example using cos() method to find cosine function.
# importing sympy libraryfrom sympy import * # calling cos() method on expressiongeek1 = cos(-1)geek2 = cos(pi / 3) print(geek1)print(geek2)
Output:
cos(1)
1/2
Code #2:
# importing sympy libraryfrom sympy import * # calling cos() method on expressiongeek = cos(2 + 5j)print(geek)
Output:
-30.8822353189167 - 67.4727884405875*I
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25585,
"s": 25557,
"text": "\n19 Jul, 2019"
},
{
"code": null,
"e": 25701,
"s": 25585,
"text": "In simpy, cos() method is cosine function. Using the cos(x) method in simpy module, we can compute the cosine of x."
},
{
"code": null,
"e": 25758,
"s": 25701,
"text": "Syntax : sympy.cos(x)\n\nReturn : Returns the cosine of x "
},
{
"code": null,
"e": 25831,
"s": 25758,
"text": "Code #1:Below is the example using cos() method to find cosine function."
},
{
"code": "# importing sympy libraryfrom sympy import * # calling cos() method on expressiongeek1 = cos(-1)geek2 = cos(pi / 3) print(geek1)print(geek2)",
"e": 25974,
"s": 25831,
"text": null
},
{
"code": null,
"e": 25982,
"s": 25974,
"text": "Output:"
},
{
"code": null,
"e": 25994,
"s": 25982,
"text": "cos(1)\n1/2\n"
},
{
"code": null,
"e": 26004,
"s": 25994,
"text": " Code #2:"
},
{
"code": "# importing sympy libraryfrom sympy import * # calling cos() method on expressiongeek = cos(2 + 5j)print(geek)",
"e": 26118,
"s": 26004,
"text": null
},
{
"code": null,
"e": 26126,
"s": 26118,
"text": "Output:"
},
{
"code": null,
"e": 26165,
"s": 26126,
"text": "-30.8822353189167 - 67.4727884405875*I"
},
{
"code": null,
"e": 26171,
"s": 26165,
"text": "SymPy"
},
{
"code": null,
"e": 26178,
"s": 26171,
"text": "Python"
},
{
"code": null,
"e": 26276,
"s": 26178,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26294,
"s": 26276,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26329,
"s": 26294,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26361,
"s": 26329,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26383,
"s": 26361,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26425,
"s": 26383,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26455,
"s": 26425,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26481,
"s": 26455,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26510,
"s": 26481,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26554,
"s": 26510,
"text": "Reading and Writing to text files in Python"
}
]
|
MongoDB count() Method - db.Collection.count() - GeeksforGeeks | 28 Jan, 2021
The count() method counts the number of documents that match the selection criteria. It returns the number of documents that match the selection criteria. It takes two arguments first one is the selection criteria and the other is optional.
This method is equivalent to db.collection.find().count().
You cannot use this method in transactions.
One a shared cluster, if you use this method without a query predicate, then it will return an inaccurate count if orphaned documents exist or if a chunk migration is in progress. So, to avoid such type of situation use db.collection.aggregate() method
Syntax:
db.Collection_Name.count(
Selection_criteria,
{
limit: <integer>,
skip: <integer>,
hint: <string or document>,
maxTimeMS : <integer>,
readConcern: <string>,
collation: <document>
})
Or if we want to count the number of documents in the collection then use this syntax:
db.Collection_name.count()
Parameters:
The first parameter is a selection criteria. The type of this parameter is a document.
The second parameter is optional.
Optional Parameters:
limit: It is the maximum number of documents to count.
skip: It is the number of documents to skip before counting.
hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error.
maxTimeMs: It is the maximum amount of time to allow the query to run.
readConcern: It is used when you don’t want to use default read concern. To use a read concern level of “majority”, you must specify a nonempty query condition.
collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
Return:
This method returns the number of documents that match to selection criteria.
Examples:
In the following examples, we are working with:
Database: gfg
Collections: student
Document: Four documents contains name and age of the students
Count the number of documents in the given collection:
Here, we count the total number of documents present in the student collection.
db.student.count()
Count the number of documents that match the given collection:
Here, we count the total number of documents in the student collection that matches the given condition, i.e., age is greater than 18.
db.student.count({age:{$gt:18}})
Note: Here, $gt mean greater than
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
Export data from MongoDB
MongoDB - sort() Method
MongoDB - Regex
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB - Update() Method | [
{
"code": null,
"e": 25623,
"s": 25595,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 25865,
"s": 25623,
"text": "The count() method counts the number of documents that match the selection criteria. It returns the number of documents that match the selection criteria. It takes two arguments first one is the selection criteria and the other is optional. "
},
{
"code": null,
"e": 25925,
"s": 25865,
"text": "This method is equivalent to db.collection.find().count(). "
},
{
"code": null,
"e": 25969,
"s": 25925,
"text": "You cannot use this method in transactions."
},
{
"code": null,
"e": 26222,
"s": 25969,
"text": "One a shared cluster, if you use this method without a query predicate, then it will return an inaccurate count if orphaned documents exist or if a chunk migration is in progress. So, to avoid such type of situation use db.collection.aggregate() method"
},
{
"code": null,
"e": 26230,
"s": 26222,
"text": "Syntax:"
},
{
"code": null,
"e": 26256,
"s": 26230,
"text": "db.Collection_Name.count("
},
{
"code": null,
"e": 26276,
"s": 26256,
"text": "Selection_criteria,"
},
{
"code": null,
"e": 26278,
"s": 26276,
"text": "{"
},
{
"code": null,
"e": 26300,
"s": 26278,
"text": " limit: <integer>,"
},
{
"code": null,
"e": 26321,
"s": 26300,
"text": " skip: <integer>,"
},
{
"code": null,
"e": 26353,
"s": 26321,
"text": " hint: <string or document>,"
},
{
"code": null,
"e": 26380,
"s": 26353,
"text": " maxTimeMS : <integer>,"
},
{
"code": null,
"e": 26407,
"s": 26380,
"text": " readConcern: <string>,"
},
{
"code": null,
"e": 26435,
"s": 26407,
"text": " collation: <document> "
},
{
"code": null,
"e": 26438,
"s": 26435,
"text": "})"
},
{
"code": null,
"e": 26525,
"s": 26438,
"text": "Or if we want to count the number of documents in the collection then use this syntax:"
},
{
"code": null,
"e": 26552,
"s": 26525,
"text": "db.Collection_name.count()"
},
{
"code": null,
"e": 26564,
"s": 26552,
"text": "Parameters:"
},
{
"code": null,
"e": 26651,
"s": 26564,
"text": "The first parameter is a selection criteria. The type of this parameter is a document."
},
{
"code": null,
"e": 26685,
"s": 26651,
"text": "The second parameter is optional."
},
{
"code": null,
"e": 26706,
"s": 26685,
"text": "Optional Parameters:"
},
{
"code": null,
"e": 26761,
"s": 26706,
"text": "limit: It is the maximum number of documents to count."
},
{
"code": null,
"e": 26822,
"s": 26761,
"text": "skip: It is the number of documents to skip before counting."
},
{
"code": null,
"e": 27055,
"s": 26822,
"text": "hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error."
},
{
"code": null,
"e": 27126,
"s": 27055,
"text": "maxTimeMs: It is the maximum amount of time to allow the query to run."
},
{
"code": null,
"e": 27287,
"s": 27126,
"text": "readConcern: It is used when you don’t want to use default read concern. To use a read concern level of “majority”, you must specify a nonempty query condition."
},
{
"code": null,
"e": 27515,
"s": 27287,
"text": "collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document."
},
{
"code": null,
"e": 27524,
"s": 27515,
"text": "Return: "
},
{
"code": null,
"e": 27602,
"s": 27524,
"text": "This method returns the number of documents that match to selection criteria."
},
{
"code": null,
"e": 27612,
"s": 27602,
"text": "Examples:"
},
{
"code": null,
"e": 27660,
"s": 27612,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 27674,
"s": 27660,
"text": "Database: gfg"
},
{
"code": null,
"e": 27695,
"s": 27674,
"text": "Collections: student"
},
{
"code": null,
"e": 27758,
"s": 27695,
"text": "Document: Four documents contains name and age of the students"
},
{
"code": null,
"e": 27813,
"s": 27758,
"text": "Count the number of documents in the given collection:"
},
{
"code": null,
"e": 27893,
"s": 27813,
"text": "Here, we count the total number of documents present in the student collection."
},
{
"code": null,
"e": 27912,
"s": 27893,
"text": "db.student.count()"
},
{
"code": null,
"e": 27975,
"s": 27912,
"text": "Count the number of documents that match the given collection:"
},
{
"code": null,
"e": 28110,
"s": 27975,
"text": "Here, we count the total number of documents in the student collection that matches the given condition, i.e., age is greater than 18."
},
{
"code": null,
"e": 28143,
"s": 28110,
"text": "db.student.count({age:{$gt:18}})"
},
{
"code": null,
"e": 28177,
"s": 28143,
"text": "Note: Here, $gt mean greater than"
},
{
"code": null,
"e": 28192,
"s": 28177,
"text": "MongoDB-method"
},
{
"code": null,
"e": 28199,
"s": 28192,
"text": "Picked"
},
{
"code": null,
"e": 28207,
"s": 28199,
"text": "MongoDB"
},
{
"code": null,
"e": 28305,
"s": 28207,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28343,
"s": 28305,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 28368,
"s": 28343,
"text": "MongoDB - limit() Method"
},
{
"code": null,
"e": 28395,
"s": 28368,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 28431,
"s": 28395,
"text": "Create user and add role in MongoDB"
},
{
"code": null,
"e": 28456,
"s": 28431,
"text": "Export data from MongoDB"
},
{
"code": null,
"e": 28480,
"s": 28456,
"text": "MongoDB - sort() Method"
},
{
"code": null,
"e": 28496,
"s": 28480,
"text": "MongoDB - Regex"
},
{
"code": null,
"e": 28551,
"s": 28496,
"text": "MongoDB updateOne() Method - db.Collection.updateOne()"
},
{
"code": null,
"e": 28608,
"s": 28551,
"text": "MongoDB insertMany() Method - db.Collection.insertMany()"
}
]
|
Send mails using a Bash Script - GeeksforGeeks | 16 Feb, 2022
Sending email via the command line can be quite a great feature to have especially on Linux which will allow some users to avoid using the GUI and installing all of the dependencies. We will look into the following article on how to write a BASH (shell) script that can send a custom email to any other email using the SMTP server.
The sender’s email must be a Gmail account. The 2FA should be enabled on this account. You will have to create an app on your Gmail id that will handle the email sending, permissions, and the rest of the stuff for you. It’s quite simple to do that, visit the Google App Password page.
Log in with your credentials from the above linkCreate an App category-> Other give it any name(call it anything you like eg. mailterminal, bashmail)Now copy the password and store it securely somewhere.
Log in with your credentials from the above link
Create an App category-> Other give it any name(call it anything you like eg. mailterminal, bashmail)
Now copy the password and store it securely somewhere.
Google App passwords.
Entering the app type
Entering the add name
Copy the code generated from the app and save it in a secure place, we will need this password later,
Copying the password for the app.
After the Google app is created we can finally move on to the script creation part. We will use cURL to fetch the server and post the email content on the particular route provided by the SMTP server.
We will first input the requirements from the input, these will be sender email, receiver email, google app password, subject, body, and attachments if any. So it’s quite simple to take input in BASH We’ll use the read command along with the -p as an argument to prompt the user with an info message prompt for better understanding.
#!usr/bin/env bash
# Input for sender email
read -p "Enter your email : " sender
# Input for recipient email
read -p "Enter recipient email : " receiver
# Input for google app password
read -p "Enter your Google App password : " gapp
# Input for subject of the mail
read -p "Enter the subject of mail : " sub
So the sender email, receiver email, google app password, and the subject are taken care of but how we will input the body and the attachment. Well, for that we will use the cat command to first input into a file and copy all the content from that file into a variable like this:
# Using cat command to input multiline text to a variable (from file)
echo "Enter the body of mail : "
cat > tempfile.txt
body=$(cat tempfile.txt)
The cat command used with > can redirect the inputs to the file provided after the operator. You have to press CTRL + D to save the multi-line content which you have written and to quit from the cat command. Finally, we store the output of the cat command to a variable. We have used the cat command both ways to write to the file and also for reading from the file. Thus, we have the body variable to work with later.
Now comes the attachment part, we need to provide the positional argument as the file name to specify the attached file.
# set file variable to the 1st positional parameter
file="$1"
# MIME type for multiple type of input file extensions
MIMEType=`file --mime-type "$file" | sed 's/.*: //'`
This will store the name of the file and next, we will also need the type of file. we are extracting the file extension or its type from using the mime fields in the file. We are piping the filename with the set editor and filtering the text after the ‘:’ in the output of the file command. The demonstration of the code is shown below:
adding attachments
So, the filename is stored in the file variable and the filetype is stored in the MIMEType variable. After this, we move on to the cURL command.
The CURL command is one of the most useful and widely popular commands when it comes to its functionality. We will use the command to fetch the SMTP server i.e. smtps://smtp.gmail.com:465. We are basically opening a connection to the Gmail server at a particular port and thereafter we will pass in some arguments and variables to make the body of the email.
We are passing the URL as the SMTP server which is smtps://smtp.gmail.com:465 and we will send the email using the SSL connection as it is secure to send mail via the google server. For that, we will pass –ssl-reqd which will allow using the google account email.
We will start the mail body by adding the mail from the field which will be the sender in our case so we will use –mail-from as the value of the variable sender i.e $sender. We use a \ in a shell script to ignore everything after it in that line and move on to the next line just for better visibility and readability. After the mail sender argument is taken care of, we have the mail recipient argument which takes in the receiver mail address. We will use –mail-rcpt which will be assigned the value of the variable receiver as $receiver.
# cURL command to send requests to SMTP server with arguments of given credentials
curl -s --url 'smtps://smtp.gmail.com:465' --ssl-reqd \
--mail-from $sender \
--mail-rcpt $receiver\
--user $sender:$gapp \
The next bit of information is the user email and the password of the app which we generated before. We have to pass the argument as –user which takes two values separated by : as the email and password, we will simply pass the user email i.e the sender and gapp variables.
Thereafter we pass the argument -T for uploading a file but here we are not uploading any file for content in the mail, we will simply add it manually then the user types in the formatted file for simplifying things for the user.
Inside the argument to the file we are writing the Header information as the sender, To field, subject, and finally the content of the mail i.e the body.
# Creating the structure of mail using previously defined variables
-T <(echo -e "From: ${sender}
To: ${receiver}
Subject:${sub}
${body}")
We also need to pass in the file attachment, we need to handle this independently now but if the user has not specified any file then we need to take care of that we don’t mess up the curl command. We can change the cURL command a bit for the attachment, the header sections remain the same i.e till the password entry of the user. We need to use the –F attribute to have a form for the attachment as well as the body. We will initialize the form with the multipart option that will allow us to embed the body as well as the file in a simple manner. We will then specify what goes in the form, firstly we will include the body as plain text and then add the attachment file into the file option provided and also encode it as per the file type which was initialized into MIMEType as a variable. This ends the part of the form, we now can add the metadata like To, form, and subject to the mail.
For the meta-data, we will simply use the -H as the header to input the To, From, and Subject fields from the variables. Thus we have added an attachment to the mail, the gist for the mail attachment will look like this:
# cURL command for attachment file with extra parameters
curl -s --url 'smtps://smtp.gmail.com:465' --ssl-reqd \
--mail-from $sender \
--mail-rcpt $receiver\
--user $sender:$gapp \
-H "Subject: $sub" -H "From: $sender" -H "To: $receiver" -F \
'=(;type=multipart/mixed' -F "=$body;type=text/plain" -F \
"file=@$file;type=$MIMEType;encoder=base64" -F '=)'
Now to avoid breaking the script when no attachment is passed we need to check for the positional parameter if the value is not assigned, we will simply not add the form and if it exists, we will add the form and change the flow accordingly.
To check for the positional parameters are assigned or not, we can use the -z condition in the if statement. this will check for any NULL or empty value, if the value is empty we will have simple cURL command otherwise, we will include a form in the cURL command.
The full script is shown below:
#!usr/bin/env bash
# User input
read -p "Enter your email : " sender
read -p "Enter recipient email : " receiver
read -p "Enter your Google App password : " gapp
read -p "Enter the subject of mail : " sub
echo "Enter the body of mail : "
cat > tempfile.txt # using cat command for multiline input
body=$(cat tempfile.txt) # storing the content of file in a variable
rm tempfile.txt
# check for provided attachment file as a positional parameter
# -z indicating an empty positional parameter
# attachment doesn't exist condition
if [ -z "$1" ]; then
# curl command for accessing the smtp server
curl -s --url 'smtps://smtp.gmail.com:465' --ssl-reqd \
--mail-from $sender \
--mail-rcpt $receiver\
--user $sender:$gapp \
-T <(echo -e "From: ${sender}
To: ${receiver}
Subject:${sub}
${body}")
# attachment exists condition
else
file="$1" # set file as the 1st positional parameter
# MIME type for multiple type of input file extensions
MIMEType=`file --mime-type "$file" | sed 's/.*: //'`
curl -s --url 'smtps://smtp.gmail.com:465' --ssl-reqd \
--mail-from $sender \
--mail-rcpt $receiver\
--user $sender:$gapp \
-H "Subject: $sub" -H "From: $sender" -H "To: $receiver" -F \
'=(;type=multipart/mixed' -F "=$body;type=text/plain" -F \
"file=@$file;type=$MIMEType;encoder=base64" -F '=)'
fi
Mail sent from the terminal using the script
Mail appeared in the inbox with an attachment
You can attach only one file and mail can only be sent to one recipient in this script. You can extend the functionality by adding multiple recipients as well. We were able to send emails from the terminal on a Gmail account using tools like cURL, sed, BASH programming language, and the SMTP server.
ruhelaa48
sagar0719kumar
singghakshay
rkbhola5
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 25675,
"s": 25647,
"text": "\n16 Feb, 2022"
},
{
"code": null,
"e": 26007,
"s": 25675,
"text": "Sending email via the command line can be quite a great feature to have especially on Linux which will allow some users to avoid using the GUI and installing all of the dependencies. We will look into the following article on how to write a BASH (shell) script that can send a custom email to any other email using the SMTP server."
},
{
"code": null,
"e": 26294,
"s": 26007,
"text": "The sender’s email must be a Gmail account. The 2FA should be enabled on this account. You will have to create an app on your Gmail id that will handle the email sending, permissions, and the rest of the stuff for you. It’s quite simple to do that, visit the Google App Password page. "
},
{
"code": null,
"e": 26499,
"s": 26294,
"text": "Log in with your credentials from the above linkCreate an App category-> Other give it any name(call it anything you like eg. mailterminal, bashmail)Now copy the password and store it securely somewhere."
},
{
"code": null,
"e": 26548,
"s": 26499,
"text": "Log in with your credentials from the above link"
},
{
"code": null,
"e": 26651,
"s": 26548,
"text": "Create an App category-> Other give it any name(call it anything you like eg. mailterminal, bashmail)"
},
{
"code": null,
"e": 26706,
"s": 26651,
"text": "Now copy the password and store it securely somewhere."
},
{
"code": null,
"e": 26728,
"s": 26706,
"text": "Google App passwords."
},
{
"code": null,
"e": 26750,
"s": 26728,
"text": "Entering the app type"
},
{
"code": null,
"e": 26772,
"s": 26750,
"text": "Entering the add name"
},
{
"code": null,
"e": 26874,
"s": 26772,
"text": "Copy the code generated from the app and save it in a secure place, we will need this password later,"
},
{
"code": null,
"e": 26908,
"s": 26874,
"text": "Copying the password for the app."
},
{
"code": null,
"e": 27109,
"s": 26908,
"text": "After the Google app is created we can finally move on to the script creation part. We will use cURL to fetch the server and post the email content on the particular route provided by the SMTP server."
},
{
"code": null,
"e": 27442,
"s": 27109,
"text": "We will first input the requirements from the input, these will be sender email, receiver email, google app password, subject, body, and attachments if any. So it’s quite simple to take input in BASH We’ll use the read command along with the -p as an argument to prompt the user with an info message prompt for better understanding."
},
{
"code": null,
"e": 27756,
"s": 27442,
"text": "#!usr/bin/env bash\n\n# Input for sender email \nread -p \"Enter your email : \" sender\n\n# Input for recipient email\nread -p \"Enter recipient email : \" receiver\n\n# Input for google app password\nread -p \"Enter your Google App password : \" gapp\n\n# Input for subject of the mail\nread -p \"Enter the subject of mail : \" sub"
},
{
"code": null,
"e": 28036,
"s": 27756,
"text": "So the sender email, receiver email, google app password, and the subject are taken care of but how we will input the body and the attachment. Well, for that we will use the cat command to first input into a file and copy all the content from that file into a variable like this:"
},
{
"code": null,
"e": 28184,
"s": 28036,
"text": "# Using cat command to input multiline text to a variable (from file)\n\necho \"Enter the body of mail : \"\ncat > tempfile.txt\nbody=$(cat tempfile.txt)"
},
{
"code": null,
"e": 28604,
"s": 28184,
"text": "The cat command used with > can redirect the inputs to the file provided after the operator. You have to press CTRL + D to save the multi-line content which you have written and to quit from the cat command. Finally, we store the output of the cat command to a variable. We have used the cat command both ways to write to the file and also for reading from the file. Thus, we have the body variable to work with later. "
},
{
"code": null,
"e": 28726,
"s": 28604,
"text": "Now comes the attachment part, we need to provide the positional argument as the file name to specify the attached file. "
},
{
"code": null,
"e": 28897,
"s": 28726,
"text": "# set file variable to the 1st positional parameter\nfile=\"$1\"\n\n# MIME type for multiple type of input file extensions\nMIMEType=`file --mime-type \"$file\" | sed 's/.*: //'`"
},
{
"code": null,
"e": 29235,
"s": 28897,
"text": "This will store the name of the file and next, we will also need the type of file. we are extracting the file extension or its type from using the mime fields in the file. We are piping the filename with the set editor and filtering the text after the ‘:’ in the output of the file command. The demonstration of the code is shown below:"
},
{
"code": null,
"e": 29254,
"s": 29235,
"text": "adding attachments"
},
{
"code": null,
"e": 29399,
"s": 29254,
"text": "So, the filename is stored in the file variable and the filetype is stored in the MIMEType variable. After this, we move on to the cURL command."
},
{
"code": null,
"e": 29759,
"s": 29399,
"text": "The CURL command is one of the most useful and widely popular commands when it comes to its functionality. We will use the command to fetch the SMTP server i.e. smtps://smtp.gmail.com:465. We are basically opening a connection to the Gmail server at a particular port and thereafter we will pass in some arguments and variables to make the body of the email."
},
{
"code": null,
"e": 30024,
"s": 29759,
"text": "We are passing the URL as the SMTP server which is smtps://smtp.gmail.com:465 and we will send the email using the SSL connection as it is secure to send mail via the google server. For that, we will pass –ssl-reqd which will allow using the google account email. "
},
{
"code": null,
"e": 30567,
"s": 30024,
"text": " We will start the mail body by adding the mail from the field which will be the sender in our case so we will use –mail-from as the value of the variable sender i.e $sender. We use a \\ in a shell script to ignore everything after it in that line and move on to the next line just for better visibility and readability. After the mail sender argument is taken care of, we have the mail recipient argument which takes in the receiver mail address. We will use –mail-rcpt which will be assigned the value of the variable receiver as $receiver. "
},
{
"code": null,
"e": 30788,
"s": 30567,
"text": "# cURL command to send requests to SMTP server with arguments of given credentials\n \ncurl -s --url 'smtps://smtp.gmail.com:465' --ssl-reqd \\\n --mail-from $sender \\\n --mail-rcpt $receiver\\\n --user $sender:$gapp \\"
},
{
"code": null,
"e": 31064,
"s": 30788,
"text": "The next bit of information is the user email and the password of the app which we generated before. We have to pass the argument as –user which takes two values separated by : as the email and password, we will simply pass the user email i.e the sender and gapp variables. "
},
{
"code": null,
"e": 31295,
"s": 31064,
"text": "Thereafter we pass the argument -T for uploading a file but here we are not uploading any file for content in the mail, we will simply add it manually then the user types in the formatted file for simplifying things for the user. "
},
{
"code": null,
"e": 31450,
"s": 31295,
"text": "Inside the argument to the file we are writing the Header information as the sender, To field, subject, and finally the content of the mail i.e the body. "
},
{
"code": null,
"e": 31591,
"s": 31450,
"text": "# Creating the structure of mail using previously defined variables\n\n-T <(echo -e \"From: ${sender}\nTo: ${receiver}\nSubject:${sub}\n\n${body}\")"
},
{
"code": null,
"e": 32489,
"s": 31591,
"text": "We also need to pass in the file attachment, we need to handle this independently now but if the user has not specified any file then we need to take care of that we don’t mess up the curl command. We can change the cURL command a bit for the attachment, the header sections remain the same i.e till the password entry of the user. We need to use the –F attribute to have a form for the attachment as well as the body. We will initialize the form with the multipart option that will allow us to embed the body as well as the file in a simple manner. We will then specify what goes in the form, firstly we will include the body as plain text and then add the attachment file into the file option provided and also encode it as per the file type which was initialized into MIMEType as a variable. This ends the part of the form, we now can add the metadata like To, form, and subject to the mail."
},
{
"code": null,
"e": 32710,
"s": 32489,
"text": "For the meta-data, we will simply use the -H as the header to input the To, From, and Subject fields from the variables. Thus we have added an attachment to the mail, the gist for the mail attachment will look like this:"
},
{
"code": null,
"e": 33092,
"s": 32710,
"text": "# cURL command for attachment file with extra parameters\n\ncurl -s --url 'smtps://smtp.gmail.com:465' --ssl-reqd \\\n --mail-from $sender \\\n --mail-rcpt $receiver\\\n --user $sender:$gapp \\\n -H \"Subject: $sub\" -H \"From: $sender\" -H \"To: $receiver\" -F \\\n '=(;type=multipart/mixed' -F \"=$body;type=text/plain\" -F \\\n \"file=@$file;type=$MIMEType;encoder=base64\" -F '=)'"
},
{
"code": null,
"e": 33334,
"s": 33092,
"text": "Now to avoid breaking the script when no attachment is passed we need to check for the positional parameter if the value is not assigned, we will simply not add the form and if it exists, we will add the form and change the flow accordingly."
},
{
"code": null,
"e": 33599,
"s": 33334,
"text": "To check for the positional parameters are assigned or not, we can use the -z condition in the if statement. this will check for any NULL or empty value, if the value is empty we will have simple cURL command otherwise, we will include a form in the cURL command. "
},
{
"code": null,
"e": 33631,
"s": 33599,
"text": "The full script is shown below:"
},
{
"code": null,
"e": 35046,
"s": 33631,
"text": "#!usr/bin/env bash\n\n# User input\nread -p \"Enter your email : \" sender\nread -p \"Enter recipient email : \" receiver\nread -p \"Enter your Google App password : \" gapp\n\nread -p \"Enter the subject of mail : \" sub\n\necho \"Enter the body of mail : \"\ncat > tempfile.txt # using cat command for multiline input\nbody=$(cat tempfile.txt) # storing the content of file in a variable\n\nrm tempfile.txt\n\n\n# check for provided attachment file as a positional parameter\n# -z indicating an empty positional parameter\n# attachment doesn't exist condition\n\nif [ -z \"$1\" ]; then \n\n\n# curl command for accessing the smtp server\n\n curl -s --url 'smtps://smtp.gmail.com:465' --ssl-reqd \\\n --mail-from $sender \\\n --mail-rcpt $receiver\\\n --user $sender:$gapp \\\n -T <(echo -e \"From: ${sender}\nTo: ${receiver}\nSubject:${sub}\n\n ${body}\")\n\n\n# attachment exists condition\nelse\n\n file=\"$1\" # set file as the 1st positional parameter\n \n # MIME type for multiple type of input file extensions\n \n MIMEType=`file --mime-type \"$file\" | sed 's/.*: //'`\n curl -s --url 'smtps://smtp.gmail.com:465' --ssl-reqd \\\n --mail-from $sender \\\n --mail-rcpt $receiver\\\n --user $sender:$gapp \\\n -H \"Subject: $sub\" -H \"From: $sender\" -H \"To: $receiver\" -F \\\n '=(;type=multipart/mixed' -F \"=$body;type=text/plain\" -F \\\n \"file=@$file;type=$MIMEType;encoder=base64\" -F '=)'\n \nfi"
},
{
"code": null,
"e": 35091,
"s": 35046,
"text": "Mail sent from the terminal using the script"
},
{
"code": null,
"e": 35137,
"s": 35091,
"text": "Mail appeared in the inbox with an attachment"
},
{
"code": null,
"e": 35440,
"s": 35137,
"text": "You can attach only one file and mail can only be sent to one recipient in this script. You can extend the functionality by adding multiple recipients as well. We were able to send emails from the terminal on a Gmail account using tools like cURL, sed, BASH programming language, and the SMTP server. "
},
{
"code": null,
"e": 35450,
"s": 35440,
"text": "ruhelaa48"
},
{
"code": null,
"e": 35465,
"s": 35450,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 35478,
"s": 35465,
"text": "singghakshay"
},
{
"code": null,
"e": 35487,
"s": 35478,
"text": "rkbhola5"
},
{
"code": null,
"e": 35498,
"s": 35487,
"text": "Linux-Unix"
},
{
"code": null,
"e": 35596,
"s": 35498,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35631,
"s": 35596,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 35657,
"s": 35631,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 35691,
"s": 35657,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 35720,
"s": 35691,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 35757,
"s": 35720,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 35794,
"s": 35757,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 35836,
"s": 35794,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 35862,
"s": 35836,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 35898,
"s": 35862,
"text": "uniq Command in LINUX with examples"
}
]
|
Implementation of Perceptron Algorithm for NOT Logic Gate - GeeksforGeeks | 08 Jun, 2020
In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function:
For a particular choice of the weight vector and bias parameter , the model predicts output for the corresponding input vector .
NOT logical function truth table is of only 1-bit binary input (0 or 1), i.e, the input vector and the corresponding output –
Now for the corresponding weight vector of the input vector , the associated Perceptron Function can be defined as:
For the implementation, considered weight parameter is and the bias parameter is .
Python Implementation:
# importing Python libraryimport numpy as np # define Unit Step Functiondef unitStep(v): if v >= 0: return 1 else: return 0 # design Perceptron Modeldef perceptronModel(x, w, b): v = np.dot(w, x) + b y = unitStep(v) return y # NOT Logic Function# w = -1, b = 0.5def NOT_logicFunction(x): w = -1 b = 0.5 return perceptronModel(x, w, b) # testing the Perceptron Modeltest1 = np.array(1)test2 = np.array(0) print("NOT({}) = {}".format(1, NOT_logicFunction(test1)))print("NOT({}) = {}".format(0, NOT_logicFunction(test2)))
NOT(1) = 0
NOT(0) = 1
Here, the model predicted output () for each of the test inputs are exactly matched with the NOT logic gate conventional output () according to the truth table.Hence, it is verified that the perceptron algorithm for NOT logic gate is correctly implemented.
Neural Network
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree
Decision Tree Introduction with example
Support Vector Machine Algorithm
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 26839,
"s": 26811,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 27003,
"s": 26839,
"text": "In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function:"
},
{
"code": null,
"e": 27139,
"s": 27008,
"text": "For a particular choice of the weight vector and bias parameter , the model predicts output for the corresponding input vector ."
},
{
"code": null,
"e": 27267,
"s": 27139,
"text": "NOT logical function truth table is of only 1-bit binary input (0 or 1), i.e, the input vector and the corresponding output –"
},
{
"code": null,
"e": 27384,
"s": 27267,
"text": "Now for the corresponding weight vector of the input vector , the associated Perceptron Function can be defined as:"
},
{
"code": null,
"e": 27473,
"s": 27389,
"text": "For the implementation, considered weight parameter is and the bias parameter is ."
},
{
"code": null,
"e": 27496,
"s": 27473,
"text": "Python Implementation:"
},
{
"code": "# importing Python libraryimport numpy as np # define Unit Step Functiondef unitStep(v): if v >= 0: return 1 else: return 0 # design Perceptron Modeldef perceptronModel(x, w, b): v = np.dot(w, x) + b y = unitStep(v) return y # NOT Logic Function# w = -1, b = 0.5def NOT_logicFunction(x): w = -1 b = 0.5 return perceptronModel(x, w, b) # testing the Perceptron Modeltest1 = np.array(1)test2 = np.array(0) print(\"NOT({}) = {}\".format(1, NOT_logicFunction(test1)))print(\"NOT({}) = {}\".format(0, NOT_logicFunction(test2)))",
"e": 28058,
"s": 27496,
"text": null
},
{
"code": null,
"e": 28081,
"s": 28058,
"text": "NOT(1) = 0\nNOT(0) = 1\n"
},
{
"code": null,
"e": 28338,
"s": 28081,
"text": "Here, the model predicted output () for each of the test inputs are exactly matched with the NOT logic gate conventional output () according to the truth table.Hence, it is verified that the perceptron algorithm for NOT logic gate is correctly implemented."
},
{
"code": null,
"e": 28353,
"s": 28338,
"text": "Neural Network"
},
{
"code": null,
"e": 28370,
"s": 28353,
"text": "Machine Learning"
},
{
"code": null,
"e": 28377,
"s": 28370,
"text": "Python"
},
{
"code": null,
"e": 28394,
"s": 28377,
"text": "Machine Learning"
},
{
"code": null,
"e": 28492,
"s": 28394,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28515,
"s": 28492,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 28538,
"s": 28515,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 28552,
"s": 28538,
"text": "Decision Tree"
},
{
"code": null,
"e": 28592,
"s": 28552,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 28625,
"s": 28592,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 28653,
"s": 28625,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28703,
"s": 28653,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28725,
"s": 28703,
"text": "Python map() function"
}
]
|
Difference between List and Dictionary in Python - GeeksforGeeks | 21 Sep, 2021
Lists are just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it a most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation.Example:
Python3
# Python program to demonstrate# Lists # Creating a List with# the use of multiple valuesList = ["Geeks", "For", "Geeks"]print("List containing multiple values: ")print(List[0]) print(List[2]) # Creating a Multi-Dimensional List# (By Nesting a list inside a List)List = [['Geeks', 'For'] , ['Geeks']]print("\nMulti-Dimensional List: ")print(List)
Output:
List containing multiple values:
Geeks
Geeks
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
Dictionary in Python on the other hand is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.Example:
Python3
# Python program to demonstrate# dictionary # Creating a Dictionary # with Integer KeysDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}print("Dictionary with the use of Integer Keys: ")print(Dict) # Creating a Dictionary # with Mixed keysDict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}print("\nDictionary with the use of Mixed Keys: ")print(Dict)
Output:
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
It is more efficient to use a dictionary for lookup of elements because it takes less time to traverse in the dictionary than a list.For example, let’s consider a data set with 5000000 elements in a machine learning model that relies on the speed of retrieval of data. To implement this we have to choose wisely between two data structure i.e. list and dictionary. The dictionary is preferred because of less time and less space storage as dictionaries are implemented in the form of hash tables from python3.6 so it is never a space-time trade-off problem in dictionaries.Example 1:
Python3
# Program to demonstrate# space-time trade-off between# dictionary and list # To calculate the time# differenceimport time # Creating a dictionaryd ={'john':1, 'alex':2} x = time.time() # Accessing elementsprint("Accessing dictionary elements:")for key in d: print(d[key], end=" ") y = time.time()print("\nTime taken by dictionary:", y-x) # Creating a Listc =[1, 2] x = time.time() print("\nAccessing List elements:")for i in c: print(i, end=" ") y = time.time()print("\nTime taken by dictionary:", y-x)
Output:
Accessing dictionary elements:
1 2
Time taken by dictionary: 1.0013580322265625e-05
Accessing List elements:
1 2
Time taken by dictionary: 3.5762786865234375e-06
Example 2:
Python3
# Program to fetch particular# elements of structure import time # Creating dictionary and listdict_name ={"bob":12, "john":11}list_name =[2, 3, 4, 5, 1] # Time taken by dictionaryx = time.time()L = dict_name["bob"]y = time.time()print("Time taken by dictionary:", y-x) # Time taken by listx = time.time()L = list_name[2]y = time.time()print("\nTime taken by list:", y-x)
Output:
Time taken by dictionary: 9.5367431640625e-07
Time taken by list: 4.76837158203125e-07
Note: It took more time for fetching a single element in a list than that of a dictionary because dictionary uses hashtable for implementing the arrangement.
sooda367
adnanirshad158
python-dict
python-list
Python
python-dict
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 25494,
"s": 25466,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 25805,
"s": 25494,
"text": "Lists are just like the arrays, declared in other languages. Lists need not be homogeneous always which makes it a most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation.Example: "
},
{
"code": null,
"e": 25813,
"s": 25805,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# Lists # Creating a List with# the use of multiple valuesList = [\"Geeks\", \"For\", \"Geeks\"]print(\"List containing multiple values: \")print(List[0]) print(List[2]) # Creating a Multi-Dimensional List# (By Nesting a list inside a List)List = [['Geeks', 'For'] , ['Geeks']]print(\"\\nMulti-Dimensional List: \")print(List)",
"e": 26163,
"s": 25813,
"text": null
},
{
"code": null,
"e": 26172,
"s": 26163,
"text": "Output: "
},
{
"code": null,
"e": 26274,
"s": 26172,
"text": "List containing multiple values: \nGeeks\nGeeks\n\nMulti-Dimensional List: \n[['Geeks', 'For'], ['Geeks']]"
},
{
"code": null,
"e": 26683,
"s": 26274,
"text": "Dictionary in Python on the other hand is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.Example: "
},
{
"code": null,
"e": 26691,
"s": 26683,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# dictionary # Creating a Dictionary # with Integer KeysDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}print(\"Dictionary with the use of Integer Keys: \")print(Dict) # Creating a Dictionary # with Mixed keysDict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}print(\"\\nDictionary with the use of Mixed Keys: \")print(Dict)",
"e": 27028,
"s": 26691,
"text": null
},
{
"code": null,
"e": 27037,
"s": 27028,
"text": "Output: "
},
{
"code": null,
"e": 27190,
"s": 27037,
"text": "Dictionary with the use of Integer Keys: \n{1: 'Geeks', 2: 'For', 3: 'Geeks'}\n\nDictionary with the use of Mixed Keys: \n{1: [1, 2, 3, 4], 'Name': 'Geeks'}"
},
{
"code": null,
"e": 27781,
"s": 27196,
"text": "It is more efficient to use a dictionary for lookup of elements because it takes less time to traverse in the dictionary than a list.For example, let’s consider a data set with 5000000 elements in a machine learning model that relies on the speed of retrieval of data. To implement this we have to choose wisely between two data structure i.e. list and dictionary. The dictionary is preferred because of less time and less space storage as dictionaries are implemented in the form of hash tables from python3.6 so it is never a space-time trade-off problem in dictionaries.Example 1: "
},
{
"code": null,
"e": 27789,
"s": 27781,
"text": "Python3"
},
{
"code": "# Program to demonstrate# space-time trade-off between# dictionary and list # To calculate the time# differenceimport time # Creating a dictionaryd ={'john':1, 'alex':2} x = time.time() # Accessing elementsprint(\"Accessing dictionary elements:\")for key in d: print(d[key], end=\" \") y = time.time()print(\"\\nTime taken by dictionary:\", y-x) # Creating a Listc =[1, 2] x = time.time() print(\"\\nAccessing List elements:\")for i in c: print(i, end=\" \") y = time.time()print(\"\\nTime taken by dictionary:\", y-x)",
"e": 28305,
"s": 27789,
"text": null
},
{
"code": null,
"e": 28314,
"s": 28305,
"text": "Output: "
},
{
"code": null,
"e": 28479,
"s": 28314,
"text": "Accessing dictionary elements:\n1 2 \nTime taken by dictionary: 1.0013580322265625e-05\n\nAccessing List elements:\n1 2 \nTime taken by dictionary: 3.5762786865234375e-06"
},
{
"code": null,
"e": 28491,
"s": 28479,
"text": "Example 2: "
},
{
"code": null,
"e": 28499,
"s": 28491,
"text": "Python3"
},
{
"code": "# Program to fetch particular# elements of structure import time # Creating dictionary and listdict_name ={\"bob\":12, \"john\":11}list_name =[2, 3, 4, 5, 1] # Time taken by dictionaryx = time.time()L = dict_name[\"bob\"]y = time.time()print(\"Time taken by dictionary:\", y-x) # Time taken by listx = time.time()L = list_name[2]y = time.time()print(\"\\nTime taken by list:\", y-x)",
"e": 28873,
"s": 28499,
"text": null
},
{
"code": null,
"e": 28882,
"s": 28873,
"text": "Output: "
},
{
"code": null,
"e": 28970,
"s": 28882,
"text": "Time taken by dictionary: 9.5367431640625e-07\n\nTime taken by list: 4.76837158203125e-07"
},
{
"code": null,
"e": 29129,
"s": 28970,
"text": "Note: It took more time for fetching a single element in a list than that of a dictionary because dictionary uses hashtable for implementing the arrangement. "
},
{
"code": null,
"e": 29138,
"s": 29129,
"text": "sooda367"
},
{
"code": null,
"e": 29153,
"s": 29138,
"text": "adnanirshad158"
},
{
"code": null,
"e": 29165,
"s": 29153,
"text": "python-dict"
},
{
"code": null,
"e": 29177,
"s": 29165,
"text": "python-list"
},
{
"code": null,
"e": 29184,
"s": 29177,
"text": "Python"
},
{
"code": null,
"e": 29196,
"s": 29184,
"text": "python-dict"
},
{
"code": null,
"e": 29208,
"s": 29196,
"text": "python-list"
},
{
"code": null,
"e": 29306,
"s": 29208,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29338,
"s": 29306,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29360,
"s": 29338,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29402,
"s": 29360,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29428,
"s": 29402,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29457,
"s": 29428,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29494,
"s": 29457,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29530,
"s": 29494,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 29572,
"s": 29530,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29597,
"s": 29572,
"text": "sum() function in Python"
}
]
|
Powers of 2 to required sum using Bit Masking - GeeksforGeeks | 03 Jun, 2021
Given an integer N, the task is to find the numbers which when added after being raised to the Power of 2 gives the integer N.Examples:
Input: N = 12345 Output: 0, 3, 4, 5, 12, 13 Explanation: 12345 = 2^0 + 2^3 + 2^4 + 2^5 + 2^12 + 2^13Input: N = 10000 Output: 4, 8, 9, 10, 13 Explanation: 10000 = 2^4 + 2^8 + 2^9 + 2^10 + 2^13
Approach:
Since every number can be expressed as sum of powers of 2, the task is to print every i when ith bit is set in the binary representation of N.
Illustration: (29)10 = (11101)2 Thus, in 29, {0, 2, 3, 4} are the indices of the set bits. 20 + 22 + 23 + 24 = 1 + 4 + 8 + 16 = 29
In order to check if ith bit is set, we only need to check:
if( N & (1 << i) ) == 1 Illustration: (29)10 = (11101)2 0th bit: 11101 & 1 = 1 1st bit: 11101 & 10 = 0 2nd bit: 11101 & 100 = 1 3rd bit: 11101 & 1000 = 1 4th bit: 11101 & 10000 = 1
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ Program to split N// into numbers which when// added after being raised// to the power of 2 gives N #include <bits/stdc++.h>using namespace std; // Function to print the numbers// which raised to power of 2// adds up to Nvoid PowerOfTwo(long long N){ for (int i = 0; i < 64; i++) { long long x = 1; // Checking if i-th bit is // set in N or not by // shifting 1 i bits to // the left and performing // AND with N if (N & (x << i)) cout << i << " "; }} // Driver Codeint main(){ long long N = 12345; PowerOfTwo(N); return 0;}
// Java Program to split N// into numbers which when// added after being raised// to the power of 2 gives Nclass GFG{ // Function to print the numbers// which raised to power of 2// adds up to Nstatic void PowerOfTwo(long N){ for (int i = 0; i < 64; i++) { long x = 1; // Checking if i-th bit is // set in N or not by // shifting 1 i bits to // the left and performing // AND with N if ((N & (x << i)) > 0) System.out.print(i + " "); }} // Driver Codepublic static void main(String[] args){ long N = 12345; PowerOfTwo(N);}} // This code is contributed by Amit Katiyar
# Python3 program to split N# into numbers which when# added after being raised# to the power of 2 gives N # Function to print the numbers# which raised to power of 2# adds up to Ndef PowerOfTwo(N): for i in range(0, 64): x = 1 # Checking if i-th bit is # set in N or not by # shifting 1 i bits to # the left and performing # AND with N if (N & (x << i)) > 0: print(i, end = " ") # Driver Codeif __name__ == "__main__": # Given number N = 12345; # Function call PowerOfTwo(N) # This code is contributed by rock_cool
// C# Program to split N// into numbers which when// added after being raised// to the power of 2 gives Nusing System;class GFG{ // Function to print the numbers// which raised to power of 2// adds up to Nstatic void PowerOfTwo(long N){ for (int i = 0; i < 64; i++) { long x = 1; // Checking if i-th bit is // set in N or not by // shifting 1 i bits to // the left and performing // AND with N if ((N & (x << i)) > 0) Console.Write(i + " "); }} // Driver Codepublic static void Main(){ long N = 12345; PowerOfTwo(N);}} // This code is contributed by Nidhi_biet
<script> // Javascript Program to split N// into numbers which when// added after being raised// to the power of 2 gives N // Function to print the numbers// which raised to power of 2// adds up to Nfunction PowerOfTwo(N){ for (var i = 0; i < 64; i++) { var x = 1; // Checking if i-th bit is // set in N or not by // shifting 1 i bits to // the left and performing // AND with N if ((N & (x * Math.pow(2,i))) >0) document.write( i + " "); }} // Driver Codevar N = 12345;PowerOfTwo(N); // This code is contributed by importantly.</script>
0 3 4 5 12 13
Time Complexity: O(log N) Space Complexity: O(1)For an alternative approach, refer to Powers of 2 to required sum
amit143katiyar
nidhi_biet
rock_cool
importantly
Bit Algorithms
maths-power
Bit Magic
Combinatorial
Bit Magic
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Cyclic Redundancy Check and Modulo-2 Division
Binary representation of a given number
Add two numbers without using arithmetic operators
Josephus problem | Set 1 (A O(n) Solution)
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Combinational Sum
Factorial of a large number | [
{
"code": null,
"e": 26515,
"s": 26487,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 26653,
"s": 26515,
"text": "Given an integer N, the task is to find the numbers which when added after being raised to the Power of 2 gives the integer N.Examples: "
},
{
"code": null,
"e": 26847,
"s": 26653,
"text": "Input: N = 12345 Output: 0, 3, 4, 5, 12, 13 Explanation: 12345 = 2^0 + 2^3 + 2^4 + 2^5 + 2^12 + 2^13Input: N = 10000 Output: 4, 8, 9, 10, 13 Explanation: 10000 = 2^4 + 2^8 + 2^9 + 2^10 + 2^13 "
},
{
"code": null,
"e": 26861,
"s": 26849,
"text": "Approach: "
},
{
"code": null,
"e": 27004,
"s": 26861,
"text": "Since every number can be expressed as sum of powers of 2, the task is to print every i when ith bit is set in the binary representation of N."
},
{
"code": null,
"e": 27139,
"s": 27006,
"text": "Illustration: (29)10 = (11101)2 Thus, in 29, {0, 2, 3, 4} are the indices of the set bits. 20 + 22 + 23 + 24 = 1 + 4 + 8 + 16 = 29 "
},
{
"code": null,
"e": 27203,
"s": 27141,
"text": "In order to check if ith bit is set, we only need to check: "
},
{
"code": null,
"e": 27386,
"s": 27203,
"text": "if( N & (1 << i) ) == 1 Illustration: (29)10 = (11101)2 0th bit: 11101 & 1 = 1 1st bit: 11101 & 10 = 0 2nd bit: 11101 & 100 = 1 3rd bit: 11101 & 1000 = 1 4th bit: 11101 & 10000 = 1 "
},
{
"code": null,
"e": 27440,
"s": 27388,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 27444,
"s": 27440,
"text": "C++"
},
{
"code": null,
"e": 27449,
"s": 27444,
"text": "Java"
},
{
"code": null,
"e": 27457,
"s": 27449,
"text": "Python3"
},
{
"code": null,
"e": 27460,
"s": 27457,
"text": "C#"
},
{
"code": null,
"e": 27471,
"s": 27460,
"text": "Javascript"
},
{
"code": "// C++ Program to split N// into numbers which when// added after being raised// to the power of 2 gives N #include <bits/stdc++.h>using namespace std; // Function to print the numbers// which raised to power of 2// adds up to Nvoid PowerOfTwo(long long N){ for (int i = 0; i < 64; i++) { long long x = 1; // Checking if i-th bit is // set in N or not by // shifting 1 i bits to // the left and performing // AND with N if (N & (x << i)) cout << i << \" \"; }} // Driver Codeint main(){ long long N = 12345; PowerOfTwo(N); return 0;}",
"e": 28081,
"s": 27471,
"text": null
},
{
"code": "// Java Program to split N// into numbers which when// added after being raised// to the power of 2 gives Nclass GFG{ // Function to print the numbers// which raised to power of 2// adds up to Nstatic void PowerOfTwo(long N){ for (int i = 0; i < 64; i++) { long x = 1; // Checking if i-th bit is // set in N or not by // shifting 1 i bits to // the left and performing // AND with N if ((N & (x << i)) > 0) System.out.print(i + \" \"); }} // Driver Codepublic static void main(String[] args){ long N = 12345; PowerOfTwo(N);}} // This code is contributed by Amit Katiyar",
"e": 28725,
"s": 28081,
"text": null
},
{
"code": "# Python3 program to split N# into numbers which when# added after being raised# to the power of 2 gives N # Function to print the numbers# which raised to power of 2# adds up to Ndef PowerOfTwo(N): for i in range(0, 64): x = 1 # Checking if i-th bit is # set in N or not by # shifting 1 i bits to # the left and performing # AND with N if (N & (x << i)) > 0: print(i, end = \" \") # Driver Codeif __name__ == \"__main__\": # Given number N = 12345; # Function call PowerOfTwo(N) # This code is contributed by rock_cool",
"e": 29340,
"s": 28725,
"text": null
},
{
"code": "// C# Program to split N// into numbers which when// added after being raised// to the power of 2 gives Nusing System;class GFG{ // Function to print the numbers// which raised to power of 2// adds up to Nstatic void PowerOfTwo(long N){ for (int i = 0; i < 64; i++) { long x = 1; // Checking if i-th bit is // set in N or not by // shifting 1 i bits to // the left and performing // AND with N if ((N & (x << i)) > 0) Console.Write(i + \" \"); }} // Driver Codepublic static void Main(){ long N = 12345; PowerOfTwo(N);}} // This code is contributed by Nidhi_biet",
"e": 29977,
"s": 29340,
"text": null
},
{
"code": "<script> // Javascript Program to split N// into numbers which when// added after being raised// to the power of 2 gives N // Function to print the numbers// which raised to power of 2// adds up to Nfunction PowerOfTwo(N){ for (var i = 0; i < 64; i++) { var x = 1; // Checking if i-th bit is // set in N or not by // shifting 1 i bits to // the left and performing // AND with N if ((N & (x * Math.pow(2,i))) >0) document.write( i + \" \"); }} // Driver Codevar N = 12345;PowerOfTwo(N); // This code is contributed by importantly.</script>",
"e": 30582,
"s": 29977,
"text": null
},
{
"code": null,
"e": 30596,
"s": 30582,
"text": "0 3 4 5 12 13"
},
{
"code": null,
"e": 30713,
"s": 30598,
"text": "Time Complexity: O(log N) Space Complexity: O(1)For an alternative approach, refer to Powers of 2 to required sum "
},
{
"code": null,
"e": 30728,
"s": 30713,
"text": "amit143katiyar"
},
{
"code": null,
"e": 30739,
"s": 30728,
"text": "nidhi_biet"
},
{
"code": null,
"e": 30749,
"s": 30739,
"text": "rock_cool"
},
{
"code": null,
"e": 30761,
"s": 30749,
"text": "importantly"
},
{
"code": null,
"e": 30776,
"s": 30761,
"text": "Bit Algorithms"
},
{
"code": null,
"e": 30788,
"s": 30776,
"text": "maths-power"
},
{
"code": null,
"e": 30798,
"s": 30788,
"text": "Bit Magic"
},
{
"code": null,
"e": 30812,
"s": 30798,
"text": "Combinatorial"
},
{
"code": null,
"e": 30822,
"s": 30812,
"text": "Bit Magic"
},
{
"code": null,
"e": 30836,
"s": 30822,
"text": "Combinatorial"
},
{
"code": null,
"e": 30934,
"s": 30836,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30964,
"s": 30934,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 31010,
"s": 30964,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 31050,
"s": 31010,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 31101,
"s": 31050,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 31144,
"s": 31101,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 31204,
"s": 31144,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31242,
"s": 31204,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 31319,
"s": 31242,
"text": "itertools.combinations() module in Python to print all possible combinations"
},
{
"code": null,
"e": 31337,
"s": 31319,
"text": "Combinational Sum"
}
]
|
Square root of a number using log - GeeksforGeeks | 26 Apr, 2021
For a given number find the square root using log function. Number may be int, float or double.
Examples:
Input : n = 9
Output : 3
Input : n = 2.93
Output : 1.711724
We can find square root of a number using sqrt() method.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to demonstrate finding// square root of a number using sqrt()#include<bits/stdc++.h> int main(void){ double n = 12; printf("%lf ", sqrt(n)); return 0;}
// Java program to demonstrate finding// square root of a number using sqrt() import java.io.*; class GFG { public static void main (String[] args) { double n = 12; System.out.println(Math.sqrt(n)); // This code is contributed by akt_mit }}
# Python3 program to demonstrate finding# square root of a number using sqrt()import math if __name__=='__main__': n = 12 print(math.sqrt(n)) # This code is contributed by# Sanjit_Prasad
// C# program to demonstrate finding// square root of a number using sqrt()using System; class GFG{public static void Main(){ double n = 12; Console.Write(Math.Sqrt(n));}} // This code is contributed// by Akanksha Rai
<?php// PHP program to demonstrate finding// square root of a number using sqrt()$n = 12;echo sqrt($n); // This code is contributed by jit_t?>
<script> // Javascript program to demonstrate finding// square root of a number using sqrt()var n = 12; document.write(Math.sqrt(n).toFixed(6)); // This code is contributed by aashish1995 </script>
Output :
3.464102
We can also find square root using log2() library function:
C++
Java
Python
C#
PHP
Javascript
// C++ program to demonstrate finding// square root of a number using log2()#include<bits/stdc++.h> double squareRoot(double n){ return pow(2, 0.5*log2(n));} int main(void){ double n = 12; printf("%lf ", squareRoot(n)); return 0;}
// Java program to demonstrate finding// square root of a number using log2()import java.io.*; class GFG{static double squareRoot(double n){ return Math.pow(2, 0.5 * (Math.log(n) / Math.log(2)));} // Driver Codepublic static void main (String[] args){ double n = 12; System.out.println(squareRoot(n));}} // This code is contributed by akt_mit
# Python program to demonstrate finding# square root of a number using sqrt()import math # function to return squarerootdef squareRoot(n): return pow(2, 0.5 * math.log2(n)) # Driver program n = 12print(squareRoot(n)) # This code is contributed by# Sanjit_Prasad
// C# program to demonstrate finding// square root of a number using log2()using System; public class GFG{ static double squareRoot(double n){ return Math.Pow(2, 0.5 * (Math.Log(n) /Math.Log(2)));} static public void Main (){ double n = 12; Console.WriteLine(squareRoot(n)); }//This code is contributed by akt_mit }
<?php// PHP program to demonstrate finding// square root of a number using log2()function squareRoot($n){ return pow(2, 0.5 * log($n, 2));} // Driver Code$n = 12;echo squareRoot($n); // This code is contributed by ajit?>
<script> // Javascript program to demonstrate finding // square root of a number using log2() function squareRoot(n) { return Math.pow(2, 0.5 * (Math.log(n) /Math.log(2))); } let n = 12; document.write(squareRoot(n).toFixed(15)); </script>
Output:
3.464101615137755
How does above program work?
let d be our answer for input number n
then n(1/2) = d
apply log2 on both sides
log2(n(1/2)) = log2(d)
log2(d) = 1/2 * log2(n)
d = 2(1/2 * log2(n))
d = pow(2, 0.5*log2(n))
This article is contributed by Tumma Umamaheswararao from Jntuh College of Engineering . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sanjit_Prasad
jit_t
Akanksha_Rai
aashish1995
divyesh072019
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Count ways to reach the n'th stair
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python | [
{
"code": null,
"e": 25961,
"s": 25933,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 26057,
"s": 25961,
"text": "For a given number find the square root using log function. Number may be int, float or double."
},
{
"code": null,
"e": 26068,
"s": 26057,
"text": "Examples: "
},
{
"code": null,
"e": 26131,
"s": 26068,
"text": "Input : n = 9\nOutput : 3\n\nInput : n = 2.93\nOutput : 1.711724"
},
{
"code": null,
"e": 26190,
"s": 26131,
"text": "We can find square root of a number using sqrt() method. "
},
{
"code": null,
"e": 26194,
"s": 26190,
"text": "C++"
},
{
"code": null,
"e": 26199,
"s": 26194,
"text": "Java"
},
{
"code": null,
"e": 26207,
"s": 26199,
"text": "Python3"
},
{
"code": null,
"e": 26210,
"s": 26207,
"text": "C#"
},
{
"code": null,
"e": 26214,
"s": 26210,
"text": "PHP"
},
{
"code": null,
"e": 26225,
"s": 26214,
"text": "Javascript"
},
{
"code": "// C++ program to demonstrate finding// square root of a number using sqrt()#include<bits/stdc++.h> int main(void){ double n = 12; printf(\"%lf \", sqrt(n)); return 0;}",
"e": 26401,
"s": 26225,
"text": null
},
{
"code": "// Java program to demonstrate finding// square root of a number using sqrt() import java.io.*; class GFG { public static void main (String[] args) { double n = 12; System.out.println(Math.sqrt(n)); // This code is contributed by akt_mit }}",
"e": 26655,
"s": 26401,
"text": null
},
{
"code": "# Python3 program to demonstrate finding# square root of a number using sqrt()import math if __name__=='__main__': n = 12 print(math.sqrt(n)) # This code is contributed by# Sanjit_Prasad",
"e": 26848,
"s": 26655,
"text": null
},
{
"code": "// C# program to demonstrate finding// square root of a number using sqrt()using System; class GFG{public static void Main(){ double n = 12; Console.Write(Math.Sqrt(n));}} // This code is contributed// by Akanksha Rai",
"e": 27072,
"s": 26848,
"text": null
},
{
"code": "<?php// PHP program to demonstrate finding// square root of a number using sqrt()$n = 12;echo sqrt($n); // This code is contributed by jit_t?>",
"e": 27215,
"s": 27072,
"text": null
},
{
"code": "<script> // Javascript program to demonstrate finding// square root of a number using sqrt()var n = 12; document.write(Math.sqrt(n).toFixed(6)); // This code is contributed by aashish1995 </script>",
"e": 27413,
"s": 27215,
"text": null
},
{
"code": null,
"e": 27423,
"s": 27413,
"text": "Output : "
},
{
"code": null,
"e": 27433,
"s": 27423,
"text": "3.464102 "
},
{
"code": null,
"e": 27494,
"s": 27433,
"text": "We can also find square root using log2() library function: "
},
{
"code": null,
"e": 27498,
"s": 27494,
"text": "C++"
},
{
"code": null,
"e": 27503,
"s": 27498,
"text": "Java"
},
{
"code": null,
"e": 27510,
"s": 27503,
"text": "Python"
},
{
"code": null,
"e": 27513,
"s": 27510,
"text": "C#"
},
{
"code": null,
"e": 27517,
"s": 27513,
"text": "PHP"
},
{
"code": null,
"e": 27528,
"s": 27517,
"text": "Javascript"
},
{
"code": "// C++ program to demonstrate finding// square root of a number using log2()#include<bits/stdc++.h> double squareRoot(double n){ return pow(2, 0.5*log2(n));} int main(void){ double n = 12; printf(\"%lf \", squareRoot(n)); return 0;}",
"e": 27771,
"s": 27528,
"text": null
},
{
"code": "// Java program to demonstrate finding// square root of a number using log2()import java.io.*; class GFG{static double squareRoot(double n){ return Math.pow(2, 0.5 * (Math.log(n) / Math.log(2)));} // Driver Codepublic static void main (String[] args){ double n = 12; System.out.println(squareRoot(n));}} // This code is contributed by akt_mit",
"e": 28152,
"s": 27771,
"text": null
},
{
"code": "# Python program to demonstrate finding# square root of a number using sqrt()import math # function to return squarerootdef squareRoot(n): return pow(2, 0.5 * math.log2(n)) # Driver program n = 12print(squareRoot(n)) # This code is contributed by# Sanjit_Prasad",
"e": 28418,
"s": 28152,
"text": null
},
{
"code": "// C# program to demonstrate finding// square root of a number using log2()using System; public class GFG{ static double squareRoot(double n){ return Math.Pow(2, 0.5 * (Math.Log(n) /Math.Log(2)));} static public void Main (){ double n = 12; Console.WriteLine(squareRoot(n)); }//This code is contributed by akt_mit }",
"e": 28778,
"s": 28418,
"text": null
},
{
"code": "<?php// PHP program to demonstrate finding// square root of a number using log2()function squareRoot($n){ return pow(2, 0.5 * log($n, 2));} // Driver Code$n = 12;echo squareRoot($n); // This code is contributed by ajit?>",
"e": 29006,
"s": 28778,
"text": null
},
{
"code": "<script> // Javascript program to demonstrate finding // square root of a number using log2() function squareRoot(n) { return Math.pow(2, 0.5 * (Math.log(n) /Math.log(2))); } let n = 12; document.write(squareRoot(n).toFixed(15)); </script>",
"e": 29287,
"s": 29006,
"text": null
},
{
"code": null,
"e": 29296,
"s": 29287,
"text": "Output: "
},
{
"code": null,
"e": 29314,
"s": 29296,
"text": "3.464101615137755"
},
{
"code": null,
"e": 29344,
"s": 29314,
"text": "How does above program work? "
},
{
"code": null,
"e": 29551,
"s": 29344,
"text": " let d be our answer for input number n\n then n(1/2) = d \n apply log2 on both sides\n log2(n(1/2)) = log2(d)\n log2(d) = 1/2 * log2(n)\n d = 2(1/2 * log2(n)) \n d = pow(2, 0.5*log2(n)) "
},
{
"code": null,
"e": 30020,
"s": 29551,
"text": "This article is contributed by Tumma Umamaheswararao from Jntuh College of Engineering . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 30034,
"s": 30020,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 30040,
"s": 30034,
"text": "jit_t"
},
{
"code": null,
"e": 30053,
"s": 30040,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30065,
"s": 30053,
"text": "aashish1995"
},
{
"code": null,
"e": 30079,
"s": 30065,
"text": "divyesh072019"
},
{
"code": null,
"e": 30092,
"s": 30079,
"text": "Mathematical"
},
{
"code": null,
"e": 30105,
"s": 30092,
"text": "Mathematical"
},
{
"code": null,
"e": 30203,
"s": 30105,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30247,
"s": 30203,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 30289,
"s": 30247,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 30320,
"s": 30289,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 30391,
"s": 30320,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 30416,
"s": 30391,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 30448,
"s": 30416,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 30481,
"s": 30448,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30516,
"s": 30481,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 30562,
"s": 30516,
"text": "Merge two sorted arrays with O(1) extra space"
}
]
|
p5.js | saveCanvas() Function - GeeksforGeeks | 18 Mar, 2020
The saveCanvas() function is used to save a p5.Table object to a file. The format of the file saved can be defined as a parameter to the function. It saves a text file with comma-separated-values by default, however, it can be used to save it using-tab separated-values or generate an HTML table from it.
Syntax:
saveCanvas(selectedCanvas, filename, extension)
saveCanvas(filename, extension)
Parameters: This function accepts three parameter as mentioned above and described below.
selectedCanvas: This is a p5.Table object that would be saved to the file.
filename: It specifies the string that is used as the filename of the saved file. It is an optional parameter.
extension: It is a string which denotes the extension of the file to be saved. It is an optional parameter.
Below example illustrates the saveCanvas() function in p5.js:
Example:
function preload() { img = loadImage('sample-image.png');} function setup() { createCanvas(600, 300); textSize(22); background("orange"); text("Click on the button to save the"+ " current canvas to file", 20, 40); image(img, 30, 60); // Create a button for saving the canvas removeBtn = createButton("Save Canvas"); removeBtn.position(30, 200) removeBtn.mousePressed(saveToFile);} function saveToFile() { // Save the current canvas to file as png saveCanvas('mycanvas', 'png')}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/saveCanvas
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26049,
"s": 26021,
"text": "\n18 Mar, 2020"
},
{
"code": null,
"e": 26354,
"s": 26049,
"text": "The saveCanvas() function is used to save a p5.Table object to a file. The format of the file saved can be defined as a parameter to the function. It saves a text file with comma-separated-values by default, however, it can be used to save it using-tab separated-values or generate an HTML table from it."
},
{
"code": null,
"e": 26362,
"s": 26354,
"text": "Syntax:"
},
{
"code": null,
"e": 26410,
"s": 26362,
"text": "saveCanvas(selectedCanvas, filename, extension)"
},
{
"code": null,
"e": 26442,
"s": 26410,
"text": "saveCanvas(filename, extension)"
},
{
"code": null,
"e": 26532,
"s": 26442,
"text": "Parameters: This function accepts three parameter as mentioned above and described below."
},
{
"code": null,
"e": 26607,
"s": 26532,
"text": "selectedCanvas: This is a p5.Table object that would be saved to the file."
},
{
"code": null,
"e": 26718,
"s": 26607,
"text": "filename: It specifies the string that is used as the filename of the saved file. It is an optional parameter."
},
{
"code": null,
"e": 26826,
"s": 26718,
"text": "extension: It is a string which denotes the extension of the file to be saved. It is an optional parameter."
},
{
"code": null,
"e": 26888,
"s": 26826,
"text": "Below example illustrates the saveCanvas() function in p5.js:"
},
{
"code": null,
"e": 26897,
"s": 26888,
"text": "Example:"
},
{
"code": "function preload() { img = loadImage('sample-image.png');} function setup() { createCanvas(600, 300); textSize(22); background(\"orange\"); text(\"Click on the button to save the\"+ \" current canvas to file\", 20, 40); image(img, 30, 60); // Create a button for saving the canvas removeBtn = createButton(\"Save Canvas\"); removeBtn.position(30, 200) removeBtn.mousePressed(saveToFile);} function saveToFile() { // Save the current canvas to file as png saveCanvas('mycanvas', 'png')}",
"e": 27399,
"s": 26897,
"text": null
},
{
"code": null,
"e": 27407,
"s": 27399,
"text": "Output:"
},
{
"code": null,
"e": 27447,
"s": 27407,
"text": "Online editor: https://editor.p5js.org/"
},
{
"code": null,
"e": 27545,
"s": 27447,
"text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/"
},
{
"code": null,
"e": 27599,
"s": 27545,
"text": "Reference: https://p5js.org/reference/#/p5/saveCanvas"
},
{
"code": null,
"e": 27616,
"s": 27599,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 27627,
"s": 27616,
"text": "JavaScript"
},
{
"code": null,
"e": 27644,
"s": 27627,
"text": "Web Technologies"
},
{
"code": null,
"e": 27742,
"s": 27644,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27782,
"s": 27742,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27827,
"s": 27782,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27888,
"s": 27827,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27960,
"s": 27888,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28006,
"s": 27960,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28046,
"s": 28006,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28091,
"s": 28046,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28134,
"s": 28091,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28195,
"s": 28134,
"text": "Difference between var, let and const keywords in JavaScript"
}
]
|
Minimum Bipartite Groups - GeeksforGeeks | 13 Aug, 2021
Given Adjacency List representation of graph of N vertices from 1 to N, the task is to count the minimum bipartite groups of the given graph.
Examples:
Input: N = 5 Below is the given graph with number of nodes is 5:
Output: 3 Explanation: Possible groups satisfying the Bipartite property: [2, 5], [1, 3], [4] Below is the number of bipartite groups can be formed:
Approach: The idea is to find the maximum height of all the Connected Components in the given graph of N nodes to find the minimum bipartite groups. Below are the steps:
For all the non-visited vertex in the given graph, find the height of the current Connected Components starting from the current vertex.Start DFS Traversal to find the height of all the Connected Components.The maximum of the heights calculated for all the Connected Components gives the minimum bipartite groups required.
For all the non-visited vertex in the given graph, find the height of the current Connected Components starting from the current vertex.
Start DFS Traversal to find the height of all the Connected Components.
The maximum of the heights calculated for all the Connected Components gives the minimum bipartite groups required.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std; // Function to find the height sizeof// the current component with vertex sint height(int s, vector<int> adj[], int* visited){ // Visit the current Node visited[s] = 1; int h = 0; // Call DFS recursively to find the // maximum height of current CC for (auto& child : adj[s]) { // If the node is not visited // then the height recursively // for next element if (visited[child] == 0) { h = max(h, 1 + height(child, adj, visited)); } } return h;} // Function to find the minimum Groupsint minimumGroups(vector<int> adj[], int N){ // Initialise with visited array int visited[N + 1] = { 0 }; // To find the minimum groups int groups = INT_MIN; // Traverse all the non visited Node // and calculate the height of the // tree with current node as a head for (int i = 1; i <= N; i++) { // If the current is not visited // therefore, we get another CC if (visited[i] == 0) { int comHeight; comHeight = height(i, adj, visited); groups = max(groups, comHeight); } } // Return the minimum bipartite matching return groups;} // Function that adds the current edges// in the given graphvoid addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // Drivers Codeint main(){ int N = 5; // Adjacency List vector<int> adj[N + 1]; // Adding edges to List addEdge(adj, 1, 2); addEdge(adj, 3, 2); addEdge(adj, 4, 3); cout << minimumGroups(adj, N);}
import java.util.*; class GFG{ // Function to find the height sizeof// the current component with vertex sstatic int height(int s, Vector<Integer> adj[], int []visited){ // Visit the current Node visited[s] = 1; int h = 0; // Call DFS recursively to find the // maximum height of current CC for (int child : adj[s]) { // If the node is not visited // then the height recursively // for next element if (visited[child] == 0) { h = Math.max(h, 1 + height(child, adj, visited)); } } return h;} // Function to find the minimum Groupsstatic int minimumGroups(Vector<Integer> adj[], int N){ // Initialise with visited array int []visited= new int[N + 1]; // To find the minimum groups int groups = Integer.MIN_VALUE; // Traverse all the non visited Node // and calculate the height of the // tree with current node as a head for (int i = 1; i <= N; i++) { // If the current is not visited // therefore, we get another CC if (visited[i] == 0) { int comHeight; comHeight = height(i, adj, visited); groups = Math.max(groups, comHeight); } } // Return the minimum bipartite matching return groups;} // Function that adds the current edges// in the given graphstatic void addEdge(Vector<Integer> adj[], int u, int v){ adj[u].add(v); adj[v].add(u);} // Drivers Codepublic static void main(String[] args){ int N = 5; // Adjacency List Vector<Integer> []adj = new Vector[N + 1]; for (int i = 0 ; i < N + 1; i++) adj[i] = new Vector<Integer>(); // Adding edges to List addEdge(adj, 1, 2); addEdge(adj, 3, 2); addEdge(adj, 4, 3); System.out.print(minimumGroups(adj, N));}} // This code is contributed by 29AjayKumar
import sys # Function to find the height sizeof# the current component with vertex sdef height(s, adj, visited): # Visit the current Node visited[s] = 1 h = 0 # Call DFS recursively to find the # maximum height of current CC for child in adj[s]: # If the node is not visited # then the height recursively # for next element if (visited[child] == 0): h = max(h, 1 + height(child, adj, visited)) return h # Function to find the minimum Groupsdef minimumGroups(adj, N): # Initialise with visited array visited = [0 for i in range(N + 1)] # To find the minimum groups groups = -sys.maxsize # Traverse all the non visited Node # and calculate the height of the # tree with current node as a head for i in range(1, N + 1): # If the current is not visited # therefore, we get another CC if (visited[i] == 0): comHeight = height(i, adj, visited) groups = max(groups, comHeight) # Return the minimum bipartite matching return groups # Function that adds the current edges# in the given graphdef addEdge(adj, u, v): adj[u].append(v) adj[v].append(u) # Driver code if __name__=="__main__": N = 5 # Adjacency List adj = [[] for i in range(N + 1)] # Adding edges to List addEdge(adj, 1, 2) addEdge(adj, 3, 2) addEdge(adj, 4, 3) print(minimumGroups(adj, N)) # This code is contributed by rutvik_56
using System;using System.Collections.Generic; class GFG{ // Function to find the height sizeof// the current component with vertex sstatic int height(int s, List<int> []adj, int []visited){ // Visit the current Node visited[s] = 1; int h = 0; // Call DFS recursively to find the // maximum height of current CC foreach (int child in adj[s]) { // If the node is not visited // then the height recursively // for next element if (visited[child] == 0) { h = Math.Max(h, 1 + height(child, adj, visited)); } } return h;} // Function to find the minimum Groupsstatic int minimumGroups(List<int> []adj, int N){ // Initialise with visited array int []visited= new int[N + 1]; // To find the minimum groups int groups = int.MinValue; // Traverse all the non visited Node // and calculate the height of the // tree with current node as a head for (int i = 1; i <= N; i++) { // If the current is not visited // therefore, we get another CC if (visited[i] == 0) { int comHeight; comHeight = height(i, adj, visited); groups = Math.Max(groups, comHeight); } } // Return the minimum bipartite matching return groups;} // Function that adds the current edges// in the given graphstatic void addEdge(List<int> []adj, int u, int v){ adj[u].Add(v); adj[v].Add(u);} // Drivers Codepublic static void Main(String[] args){ int N = 5; // Adjacency List List<int> []adj = new List<int>[N + 1]; for (int i = 0 ; i < N + 1; i++) adj[i] = new List<int>(); // Adding edges to List addEdge(adj, 1, 2); addEdge(adj, 3, 2); addEdge(adj, 4, 3); Console.Write(minimumGroups(adj, N));}} // This code is contributed by Rajput-Ji
<script> // Function to find the height sizeof// the current component with vertex sfunction height(s, adj, visited){ // Visit the current Node visited[s] = 1; var h = 0; // Call DFS recursively to find the // maximum height of current CC adj[s].forEach(child => { // If the node is not visited // then the height recursively // for next element if (visited[child] == 0) { h = Math.max(h, 1 + height(child, adj, visited)); } }); return h;} // Function to find the minimum Groupsfunction minimumGroups(adj, N){ // Initialise with visited array var visited = Array(N+1).fill(0); // To find the minimum groups var groups = -1000000000; // Traverse all the non visited Node // and calculate the height of the // tree with current node as a head for (var i = 1; i <= N; i++) { // If the current is not visited // therefore, we get another CC if (visited[i] == 0) { var comHeight; comHeight = height(i, adj, visited); groups = Math.max(groups, comHeight); } } // Return the minimum bipartite matching return groups;} // Function that adds the current edges// in the given graphfunction addEdge(adj, u, v){ adj[u].push(v); adj[v].push(u);} // Drivers Codevar N = 5; // Adjacency Listvar adj = Array.from(Array(N+1), ()=>Array()) // Adding edges to ListaddEdge(adj, 1, 2);addEdge(adj, 3, 2);addEdge(adj, 4, 3); document.write( minimumGroups(adj, N)); </script>
3
Time Complexity: O(V+E), where V is the number of vertices and E is the set of edges.Auxiliary Space: O(V).
29AjayKumar
Rajput-Ji
rutvik_56
importantly
adnanirshad158
pankajsharmagfg
connected
DFS
Algorithms
Data Structures
Game Theory
Greedy
Recursion
Tree
Data Structures
Greedy
Recursion
DFS
Game Theory
Tree
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Difference between Algorithm, Pseudocode and Program
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
How to Start Learning DSA?
Implementing a Linked List in Java using Class
Abstract Data Types | [
{
"code": null,
"e": 25943,
"s": 25915,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 26085,
"s": 25943,
"text": "Given Adjacency List representation of graph of N vertices from 1 to N, the task is to count the minimum bipartite groups of the given graph."
},
{
"code": null,
"e": 26096,
"s": 26085,
"text": "Examples: "
},
{
"code": null,
"e": 26163,
"s": 26096,
"text": "Input: N = 5 Below is the given graph with number of nodes is 5: "
},
{
"code": null,
"e": 26314,
"s": 26163,
"text": "Output: 3 Explanation: Possible groups satisfying the Bipartite property: [2, 5], [1, 3], [4] Below is the number of bipartite groups can be formed: "
},
{
"code": null,
"e": 26485,
"s": 26314,
"text": "Approach: The idea is to find the maximum height of all the Connected Components in the given graph of N nodes to find the minimum bipartite groups. Below are the steps: "
},
{
"code": null,
"e": 26808,
"s": 26485,
"text": "For all the non-visited vertex in the given graph, find the height of the current Connected Components starting from the current vertex.Start DFS Traversal to find the height of all the Connected Components.The maximum of the heights calculated for all the Connected Components gives the minimum bipartite groups required."
},
{
"code": null,
"e": 26945,
"s": 26808,
"text": "For all the non-visited vertex in the given graph, find the height of the current Connected Components starting from the current vertex."
},
{
"code": null,
"e": 27017,
"s": 26945,
"text": "Start DFS Traversal to find the height of all the Connected Components."
},
{
"code": null,
"e": 27133,
"s": 27017,
"text": "The maximum of the heights calculated for all the Connected Components gives the minimum bipartite groups required."
},
{
"code": null,
"e": 27185,
"s": 27133,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27189,
"s": 27185,
"text": "C++"
},
{
"code": null,
"e": 27194,
"s": 27189,
"text": "Java"
},
{
"code": null,
"e": 27202,
"s": 27194,
"text": "Python3"
},
{
"code": null,
"e": 27205,
"s": 27202,
"text": "C#"
},
{
"code": null,
"e": 27216,
"s": 27205,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Function to find the height sizeof// the current component with vertex sint height(int s, vector<int> adj[], int* visited){ // Visit the current Node visited[s] = 1; int h = 0; // Call DFS recursively to find the // maximum height of current CC for (auto& child : adj[s]) { // If the node is not visited // then the height recursively // for next element if (visited[child] == 0) { h = max(h, 1 + height(child, adj, visited)); } } return h;} // Function to find the minimum Groupsint minimumGroups(vector<int> adj[], int N){ // Initialise with visited array int visited[N + 1] = { 0 }; // To find the minimum groups int groups = INT_MIN; // Traverse all the non visited Node // and calculate the height of the // tree with current node as a head for (int i = 1; i <= N; i++) { // If the current is not visited // therefore, we get another CC if (visited[i] == 0) { int comHeight; comHeight = height(i, adj, visited); groups = max(groups, comHeight); } } // Return the minimum bipartite matching return groups;} // Function that adds the current edges// in the given graphvoid addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // Drivers Codeint main(){ int N = 5; // Adjacency List vector<int> adj[N + 1]; // Adding edges to List addEdge(adj, 1, 2); addEdge(adj, 3, 2); addEdge(adj, 4, 3); cout << minimumGroups(adj, N);}",
"e": 28867,
"s": 27216,
"text": null
},
{
"code": "import java.util.*; class GFG{ // Function to find the height sizeof// the current component with vertex sstatic int height(int s, Vector<Integer> adj[], int []visited){ // Visit the current Node visited[s] = 1; int h = 0; // Call DFS recursively to find the // maximum height of current CC for (int child : adj[s]) { // If the node is not visited // then the height recursively // for next element if (visited[child] == 0) { h = Math.max(h, 1 + height(child, adj, visited)); } } return h;} // Function to find the minimum Groupsstatic int minimumGroups(Vector<Integer> adj[], int N){ // Initialise with visited array int []visited= new int[N + 1]; // To find the minimum groups int groups = Integer.MIN_VALUE; // Traverse all the non visited Node // and calculate the height of the // tree with current node as a head for (int i = 1; i <= N; i++) { // If the current is not visited // therefore, we get another CC if (visited[i] == 0) { int comHeight; comHeight = height(i, adj, visited); groups = Math.max(groups, comHeight); } } // Return the minimum bipartite matching return groups;} // Function that adds the current edges// in the given graphstatic void addEdge(Vector<Integer> adj[], int u, int v){ adj[u].add(v); adj[v].add(u);} // Drivers Codepublic static void main(String[] args){ int N = 5; // Adjacency List Vector<Integer> []adj = new Vector[N + 1]; for (int i = 0 ; i < N + 1; i++) adj[i] = new Vector<Integer>(); // Adding edges to List addEdge(adj, 1, 2); addEdge(adj, 3, 2); addEdge(adj, 4, 3); System.out.print(minimumGroups(adj, N));}} // This code is contributed by 29AjayKumar",
"e": 30740,
"s": 28867,
"text": null
},
{
"code": "import sys # Function to find the height sizeof# the current component with vertex sdef height(s, adj, visited): # Visit the current Node visited[s] = 1 h = 0 # Call DFS recursively to find the # maximum height of current CC for child in adj[s]: # If the node is not visited # then the height recursively # for next element if (visited[child] == 0): h = max(h, 1 + height(child, adj, visited)) return h # Function to find the minimum Groupsdef minimumGroups(adj, N): # Initialise with visited array visited = [0 for i in range(N + 1)] # To find the minimum groups groups = -sys.maxsize # Traverse all the non visited Node # and calculate the height of the # tree with current node as a head for i in range(1, N + 1): # If the current is not visited # therefore, we get another CC if (visited[i] == 0): comHeight = height(i, adj, visited) groups = max(groups, comHeight) # Return the minimum bipartite matching return groups # Function that adds the current edges# in the given graphdef addEdge(adj, u, v): adj[u].append(v) adj[v].append(u) # Driver code if __name__==\"__main__\": N = 5 # Adjacency List adj = [[] for i in range(N + 1)] # Adding edges to List addEdge(adj, 1, 2) addEdge(adj, 3, 2) addEdge(adj, 4, 3) print(minimumGroups(adj, N)) # This code is contributed by rutvik_56",
"e": 32264,
"s": 30740,
"text": null
},
{
"code": "using System;using System.Collections.Generic; class GFG{ // Function to find the height sizeof// the current component with vertex sstatic int height(int s, List<int> []adj, int []visited){ // Visit the current Node visited[s] = 1; int h = 0; // Call DFS recursively to find the // maximum height of current CC foreach (int child in adj[s]) { // If the node is not visited // then the height recursively // for next element if (visited[child] == 0) { h = Math.Max(h, 1 + height(child, adj, visited)); } } return h;} // Function to find the minimum Groupsstatic int minimumGroups(List<int> []adj, int N){ // Initialise with visited array int []visited= new int[N + 1]; // To find the minimum groups int groups = int.MinValue; // Traverse all the non visited Node // and calculate the height of the // tree with current node as a head for (int i = 1; i <= N; i++) { // If the current is not visited // therefore, we get another CC if (visited[i] == 0) { int comHeight; comHeight = height(i, adj, visited); groups = Math.Max(groups, comHeight); } } // Return the minimum bipartite matching return groups;} // Function that adds the current edges// in the given graphstatic void addEdge(List<int> []adj, int u, int v){ adj[u].Add(v); adj[v].Add(u);} // Drivers Codepublic static void Main(String[] args){ int N = 5; // Adjacency List List<int> []adj = new List<int>[N + 1]; for (int i = 0 ; i < N + 1; i++) adj[i] = new List<int>(); // Adding edges to List addEdge(adj, 1, 2); addEdge(adj, 3, 2); addEdge(adj, 4, 3); Console.Write(minimumGroups(adj, N));}} // This code is contributed by Rajput-Ji",
"e": 34146,
"s": 32264,
"text": null
},
{
"code": "<script> // Function to find the height sizeof// the current component with vertex sfunction height(s, adj, visited){ // Visit the current Node visited[s] = 1; var h = 0; // Call DFS recursively to find the // maximum height of current CC adj[s].forEach(child => { // If the node is not visited // then the height recursively // for next element if (visited[child] == 0) { h = Math.max(h, 1 + height(child, adj, visited)); } }); return h;} // Function to find the minimum Groupsfunction minimumGroups(adj, N){ // Initialise with visited array var visited = Array(N+1).fill(0); // To find the minimum groups var groups = -1000000000; // Traverse all the non visited Node // and calculate the height of the // tree with current node as a head for (var i = 1; i <= N; i++) { // If the current is not visited // therefore, we get another CC if (visited[i] == 0) { var comHeight; comHeight = height(i, adj, visited); groups = Math.max(groups, comHeight); } } // Return the minimum bipartite matching return groups;} // Function that adds the current edges// in the given graphfunction addEdge(adj, u, v){ adj[u].push(v); adj[v].push(u);} // Drivers Codevar N = 5; // Adjacency Listvar adj = Array.from(Array(N+1), ()=>Array()) // Adding edges to ListaddEdge(adj, 1, 2);addEdge(adj, 3, 2);addEdge(adj, 4, 3); document.write( minimumGroups(adj, N)); </script>",
"e": 35720,
"s": 34146,
"text": null
},
{
"code": null,
"e": 35722,
"s": 35720,
"text": "3"
},
{
"code": null,
"e": 35833,
"s": 35724,
"text": "Time Complexity: O(V+E), where V is the number of vertices and E is the set of edges.Auxiliary Space: O(V). "
},
{
"code": null,
"e": 35845,
"s": 35833,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35855,
"s": 35845,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 35865,
"s": 35855,
"text": "rutvik_56"
},
{
"code": null,
"e": 35877,
"s": 35865,
"text": "importantly"
},
{
"code": null,
"e": 35892,
"s": 35877,
"text": "adnanirshad158"
},
{
"code": null,
"e": 35908,
"s": 35892,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 35918,
"s": 35908,
"text": "connected"
},
{
"code": null,
"e": 35922,
"s": 35918,
"text": "DFS"
},
{
"code": null,
"e": 35933,
"s": 35922,
"text": "Algorithms"
},
{
"code": null,
"e": 35949,
"s": 35933,
"text": "Data Structures"
},
{
"code": null,
"e": 35961,
"s": 35949,
"text": "Game Theory"
},
{
"code": null,
"e": 35968,
"s": 35961,
"text": "Greedy"
},
{
"code": null,
"e": 35978,
"s": 35968,
"text": "Recursion"
},
{
"code": null,
"e": 35983,
"s": 35978,
"text": "Tree"
},
{
"code": null,
"e": 35999,
"s": 35983,
"text": "Data Structures"
},
{
"code": null,
"e": 36006,
"s": 35999,
"text": "Greedy"
},
{
"code": null,
"e": 36016,
"s": 36006,
"text": "Recursion"
},
{
"code": null,
"e": 36020,
"s": 36016,
"text": "DFS"
},
{
"code": null,
"e": 36032,
"s": 36020,
"text": "Game Theory"
},
{
"code": null,
"e": 36037,
"s": 36032,
"text": "Tree"
},
{
"code": null,
"e": 36048,
"s": 36037,
"text": "Algorithms"
},
{
"code": null,
"e": 36146,
"s": 36048,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36171,
"s": 36146,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36198,
"s": 36171,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 36251,
"s": 36198,
"text": "Difference between Algorithm, Pseudocode and Program"
},
{
"code": null,
"e": 36285,
"s": 36251,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 36352,
"s": 36285,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 36377,
"s": 36352,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36433,
"s": 36377,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 36460,
"s": 36433,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 36507,
"s": 36460,
"text": "Implementing a Linked List in Java using Class"
}
]
|
TreeMap floorKey() in Java with Examples - GeeksforGeeks | 17 Sep, 2018
Pre-requisite: TreeMap in Java
The floorKey() method is used to return the greatest key less than or equal to given key from the parameter.
Syntax:
public K floorKey(K key)
Parameter: This method accepts a mandatory parameter key which is the key to be matched.
Return Value: The method call returns the greatest key less than or equal to key, or null if there is no such key.
Exception: This method throws following exceptions:
ClassCastException: When the specified key cannot be compared with the key available in Map.
NullPointerException: When the specified key in map is null and it uses naturalordering which means, comparator does not permit null keys.
Below are examples to illustrate the use of floorKey() method:
Example 1:
// Java program to demonstrate floorKey() method import java.util.TreeMap; public class FloorKeyDemo { public static void main(String args[]) { // create an empty TreeMap TreeMap<Integer, String> numMap = new TreeMap<Integer, String>(); // Insert the values numMap.put(6, "Six"); numMap.put(1, "One"); numMap.put(5, "Five"); numMap.put(3, "Three"); numMap.put(8, "Eight"); numMap.put(10, "Ten"); // Print the Values of TreeMap System.out.println("TreeMap: " + numMap.toString()); // Get the greatest key mapping of the Map // As here 11 is not available it returns 10 // because ten is less than 11 System.out.print("Floor Entry of Element 11 is: "); System.out.println(numMap.floorKey(11)); // This will give null System.out.print("Floor Entry of Element 0 is: "); System.out.println(numMap.floorKey(0)); }}
TreeMap: {1=One, 3=Three, 5=Five, 6=Six, 8=Eight, 10=Ten}
Floor Entry of Element 11 is: 10
Floor Entry of Element 0 is: null
Example 2: To demonstrate NullPointerException
// Java program to demonstrate floorKey() method import java.util.TreeMap; public class FloorKeyDemo { public static void main(String args[]) { // create an empty TreeMap TreeMap<Integer, String> numMap = new TreeMap<Integer, String>(); // Insert the values numMap.put(6, "Six"); numMap.put(1, "One"); numMap.put(5, "Five"); numMap.put(3, "Three"); numMap.put(8, "Eight"); numMap.put(10, "Ten"); // Print the Values of TreeMap System.out.println("TreeMap: " + numMap.toString()); try { // Passing null as parameter to floorKey() // This will throw exception System.out.println(numMap.floorKey(null)); } catch (Exception e) { System.out.println("Exception: " + e); } }}
TreeMap: {1=One, 3=Three, 5=Five, 6=Six, 8=Eight, 10=Ten}
Exception: java.lang.NullPointerException
Java - util package
Java-Functions
java-TreeMap
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Interfaces in Java
Stream In Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Multithreading in Java | [
{
"code": null,
"e": 26053,
"s": 26025,
"text": "\n17 Sep, 2018"
},
{
"code": null,
"e": 26084,
"s": 26053,
"text": "Pre-requisite: TreeMap in Java"
},
{
"code": null,
"e": 26193,
"s": 26084,
"text": "The floorKey() method is used to return the greatest key less than or equal to given key from the parameter."
},
{
"code": null,
"e": 26201,
"s": 26193,
"text": "Syntax:"
},
{
"code": null,
"e": 26226,
"s": 26201,
"text": "public K floorKey(K key)"
},
{
"code": null,
"e": 26315,
"s": 26226,
"text": "Parameter: This method accepts a mandatory parameter key which is the key to be matched."
},
{
"code": null,
"e": 26430,
"s": 26315,
"text": "Return Value: The method call returns the greatest key less than or equal to key, or null if there is no such key."
},
{
"code": null,
"e": 26482,
"s": 26430,
"text": "Exception: This method throws following exceptions:"
},
{
"code": null,
"e": 26575,
"s": 26482,
"text": "ClassCastException: When the specified key cannot be compared with the key available in Map."
},
{
"code": null,
"e": 26714,
"s": 26575,
"text": "NullPointerException: When the specified key in map is null and it uses naturalordering which means, comparator does not permit null keys."
},
{
"code": null,
"e": 26777,
"s": 26714,
"text": "Below are examples to illustrate the use of floorKey() method:"
},
{
"code": null,
"e": 26788,
"s": 26777,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate floorKey() method import java.util.TreeMap; public class FloorKeyDemo { public static void main(String args[]) { // create an empty TreeMap TreeMap<Integer, String> numMap = new TreeMap<Integer, String>(); // Insert the values numMap.put(6, \"Six\"); numMap.put(1, \"One\"); numMap.put(5, \"Five\"); numMap.put(3, \"Three\"); numMap.put(8, \"Eight\"); numMap.put(10, \"Ten\"); // Print the Values of TreeMap System.out.println(\"TreeMap: \" + numMap.toString()); // Get the greatest key mapping of the Map // As here 11 is not available it returns 10 // because ten is less than 11 System.out.print(\"Floor Entry of Element 11 is: \"); System.out.println(numMap.floorKey(11)); // This will give null System.out.print(\"Floor Entry of Element 0 is: \"); System.out.println(numMap.floorKey(0)); }}",
"e": 27753,
"s": 26788,
"text": null
},
{
"code": null,
"e": 27879,
"s": 27753,
"text": "TreeMap: {1=One, 3=Three, 5=Five, 6=Six, 8=Eight, 10=Ten}\nFloor Entry of Element 11 is: 10\nFloor Entry of Element 0 is: null\n"
},
{
"code": null,
"e": 27926,
"s": 27879,
"text": "Example 2: To demonstrate NullPointerException"
},
{
"code": "// Java program to demonstrate floorKey() method import java.util.TreeMap; public class FloorKeyDemo { public static void main(String args[]) { // create an empty TreeMap TreeMap<Integer, String> numMap = new TreeMap<Integer, String>(); // Insert the values numMap.put(6, \"Six\"); numMap.put(1, \"One\"); numMap.put(5, \"Five\"); numMap.put(3, \"Three\"); numMap.put(8, \"Eight\"); numMap.put(10, \"Ten\"); // Print the Values of TreeMap System.out.println(\"TreeMap: \" + numMap.toString()); try { // Passing null as parameter to floorKey() // This will throw exception System.out.println(numMap.floorKey(null)); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}",
"e": 28774,
"s": 27926,
"text": null
},
{
"code": null,
"e": 28875,
"s": 28774,
"text": "TreeMap: {1=One, 3=Three, 5=Five, 6=Six, 8=Eight, 10=Ten}\nException: java.lang.NullPointerException\n"
},
{
"code": null,
"e": 28895,
"s": 28875,
"text": "Java - util package"
},
{
"code": null,
"e": 28910,
"s": 28895,
"text": "Java-Functions"
},
{
"code": null,
"e": 28923,
"s": 28910,
"text": "java-TreeMap"
},
{
"code": null,
"e": 28930,
"s": 28923,
"text": "Picked"
},
{
"code": null,
"e": 28935,
"s": 28930,
"text": "Java"
},
{
"code": null,
"e": 28940,
"s": 28935,
"text": "Java"
},
{
"code": null,
"e": 29038,
"s": 28940,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29068,
"s": 29038,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29087,
"s": 29068,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29102,
"s": 29087,
"text": "Stream In Java"
},
{
"code": null,
"e": 29120,
"s": 29102,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29152,
"s": 29120,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29172,
"s": 29152,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29204,
"s": 29172,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29228,
"s": 29204,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29240,
"s": 29228,
"text": "Set in Java"
}
]
|
Python Functools - lru_cache() - GeeksforGeeks | 26 Jun, 2020
The functools module in Python deals with higher-order functions, that is, functions operating on(taking as arguments) or returning functions and other such callable objects. The functools module provides a wide array of methods such as cached_property(func), cmp_to_key(func), lru_cache(func), wraps(func), etc. It is worth noting that these methods take functions as arguments.
lru_cache() is one such function in functools module which helps in reducing the execution time of the function by using memoization technique.
Syntax:@lru_cache(maxsize=128, typed=False)
Parameters:maxsize:This parameter sets the size of the cache, the cache can store upto maxsize most recent function calls, if maxsize is set to None, the LRU feature will be disabled and the cache can grow without any limitationstyped:If typed is set to True, function arguments of different types will be cached separately. For example, f(3) and f(3.0) will be treated as distinct calls with distinct results and they will be stored in two separate entries in the cache
Example:1
from functools import lru_cacheimport time # Function that computes Fibonacci # numbers without lru_cachedef fib_without_cache(n): if n < 2: return n return fib_without_cache(n-1) + fib_without_cache(n-2) # Execution start timebegin = time.time()fib_without_cache(30) # Execution end timeend = time.time() print("Time taken to execute the\function without lru_cache is", end-begin) # Function that computes Fibonacci# numbers with lru_cache@lru_cache(maxsize = 128)def fib_with_cache(n): if n < 2: return n return fib_with_cache(n-1) + fib_with_cache(n-2) begin = time.time()fib_with_cache(30)end = time.time() print("Time taken to execute the \function with lru_cache is", end-begin)
Output:
Time taken to execute the function without lru_cache is 0.4448213577270508Time taken to execute the function with lru_cache is 2.8371810913085938e-05
Example 2:
from functools import lru_cache @lru_cache(maxsize = 100)def count_vowels(sentence): sentence = sentence.casefold() return sum(sentence.count(vowel) for vowel in 'aeiou') print(count_vowels("Welcome to Geeksforgeeks"))
Output:
9
nidhi_biet
Python Decorators
Python functools-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25665,
"s": 25637,
"text": "\n26 Jun, 2020"
},
{
"code": null,
"e": 26045,
"s": 25665,
"text": "The functools module in Python deals with higher-order functions, that is, functions operating on(taking as arguments) or returning functions and other such callable objects. The functools module provides a wide array of methods such as cached_property(func), cmp_to_key(func), lru_cache(func), wraps(func), etc. It is worth noting that these methods take functions as arguments."
},
{
"code": null,
"e": 26189,
"s": 26045,
"text": "lru_cache() is one such function in functools module which helps in reducing the execution time of the function by using memoization technique."
},
{
"code": null,
"e": 26233,
"s": 26189,
"text": "Syntax:@lru_cache(maxsize=128, typed=False)"
},
{
"code": null,
"e": 26704,
"s": 26233,
"text": "Parameters:maxsize:This parameter sets the size of the cache, the cache can store upto maxsize most recent function calls, if maxsize is set to None, the LRU feature will be disabled and the cache can grow without any limitationstyped:If typed is set to True, function arguments of different types will be cached separately. For example, f(3) and f(3.0) will be treated as distinct calls with distinct results and they will be stored in two separate entries in the cache"
},
{
"code": null,
"e": 26714,
"s": 26704,
"text": "Example:1"
},
{
"code": "from functools import lru_cacheimport time # Function that computes Fibonacci # numbers without lru_cachedef fib_without_cache(n): if n < 2: return n return fib_without_cache(n-1) + fib_without_cache(n-2) # Execution start timebegin = time.time()fib_without_cache(30) # Execution end timeend = time.time() print(\"Time taken to execute the\\function without lru_cache is\", end-begin) # Function that computes Fibonacci# numbers with lru_cache@lru_cache(maxsize = 128)def fib_with_cache(n): if n < 2: return n return fib_with_cache(n-1) + fib_with_cache(n-2) begin = time.time()fib_with_cache(30)end = time.time() print(\"Time taken to execute the \\function with lru_cache is\", end-begin)",
"e": 27442,
"s": 26714,
"text": null
},
{
"code": null,
"e": 27450,
"s": 27442,
"text": "Output:"
},
{
"code": null,
"e": 27600,
"s": 27450,
"text": "Time taken to execute the function without lru_cache is 0.4448213577270508Time taken to execute the function with lru_cache is 2.8371810913085938e-05"
},
{
"code": null,
"e": 27611,
"s": 27600,
"text": "Example 2:"
},
{
"code": "from functools import lru_cache @lru_cache(maxsize = 100)def count_vowels(sentence): sentence = sentence.casefold() return sum(sentence.count(vowel) for vowel in 'aeiou') print(count_vowels(\"Welcome to Geeksforgeeks\"))",
"e": 27842,
"s": 27611,
"text": null
},
{
"code": null,
"e": 27850,
"s": 27842,
"text": "Output:"
},
{
"code": null,
"e": 27853,
"s": 27850,
"text": "9\n"
},
{
"code": null,
"e": 27864,
"s": 27853,
"text": "nidhi_biet"
},
{
"code": null,
"e": 27882,
"s": 27864,
"text": "Python Decorators"
},
{
"code": null,
"e": 27906,
"s": 27882,
"text": "Python functools-module"
},
{
"code": null,
"e": 27913,
"s": 27906,
"text": "Python"
},
{
"code": null,
"e": 28011,
"s": 27913,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28029,
"s": 28011,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28064,
"s": 28029,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28096,
"s": 28064,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28118,
"s": 28096,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28160,
"s": 28118,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28190,
"s": 28160,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28216,
"s": 28190,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28245,
"s": 28216,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28289,
"s": 28245,
"text": "Reading and Writing to text files in Python"
}
]
|
Logcheck Tool - Monitor Kali Linux System Log Activity - GeeksforGeeks | 18 May, 2021
Logcheck is a package or tool to check system log files for security violations and unusual activity, it utilizes the program called logtail remembering the last position is read from the log file. Analyzes security or unusual activity from syslog to monitor Apache log files for errors caused by PHP Scripts. Logcheck is used to detect problems automatically in logfiles and results are sent via e-mail. It runs as cronjob off the hour and after every reboot
The tool has three modes of filtering:
Server: Default level containing different daemons
Paranoid: High-security machines run as service in this level also it is verbose.
Workstation: Level for Sheltered machines, filtering messages.
The logcheck package/repository is already installed in Ubuntu/Debian distribution, just use the apt-get command to install Logcheck in Linux then it will automatically start the downloading process and dependencies.
$ apt-get install logcheck
An alternative method to install this is by downloading logcheck-1.1.12.tar.gz version and then installing the logcheck tool by using tar xvf command.
tar xvf logcheck-1.1.12.tar.gz
cd logcheck-1.1.12
make
make install
We can directly use the logcheck from the terminal without installation with the help of sudo or us by which we can change the user ID and also checks the logfiles without offset being updated.
Parameters used here are described as follows,
-u – syslog summary enabling
-o – STDOUT mode, not sending mail
-t – Testing mode does not update offset
$ sudo -u logcheck logcheck -o -t
Let’s now look at the configuration file logcheck.conf of logcheck located in /etc/logcheck directory and make the necessary changes in the file.
$ vim /etc/logcheck/logcheck.conf
Change the value for REPORTLEVEL of your choice of level for controlling level of filtering of logs, then change the value SENDMAILTO to your e-mail address, so you can receive the reports and logs on the E-mail ID as shown below.
Whenever a mail is generated by logcheck has different subject lines for different events which can also be modified to control the subject.
With the help of logfiles stored in /etc/logcheck/logcheck.logfiles for maintaining the list of logfiles that have to be monitored. For defining the list to use another file and in case stored in another location, so to define new PATH modify RULEDIR variable.
View the configuration files by navigating to /etc/logcheck/logcheck.logfiles or /etc/logcheck/logcheck.files directory for configuring the mail with respect to the report level given by you, these files contain a list of logfiles to be monitored.
# vim logcheck.logfiles
Logcheck works using the files /etc/logcheck/ignore.d.server where it will check for lines that do not match rules in ignore files and then it will include those irregularities in the report which is then sent to the user via e-mail, it also reports unusual activity in log files, hard disk errors, failed authentication attempts and kernel issues.
We know that logcheck sends mail only when any suspicious activity is found, but we can also get the reports immediately or on an hourly basis by executing the following command,
$ logcheck -m
Othe parameters to include for sending mail immediately,
-h – using this we can mention hostname to use it in the subject of the mail
-o – This option is used to send a report to stdout
If using a system user it should have valid alias for logcheck and the sender/mailer (mail,sendmail, sSMTP, Postfix) has to be installed,
$ vim /etc/aliases
As we know /etc/logcheck/logcheck.logfiles are used to configure, read and monitor the files. This behavior can also be changed and reading files stored in any different location other than the default location. To do so execute the following command,
$ logcheck -c /etc/logcheck/logcheck.conf
$ logcheck -L /etc/logcheck/logcheck.conf
$ logcheck -t
In the above command, Logtail is a utility command which has a record of positions the tool read from log files. in order to run the tool in testing mode, it can be done by using -t command and offsets will not be updated.
logcheck-test will test logcheck rules quickly and easily. It will parse logfiles to match the logs by single rule or rule file. The testing single rule against /var/log/syslog
$ logcheck-test -s "RULE"
Kali-Linux
Linux-Tools
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 26111,
"s": 25651,
"text": "Logcheck is a package or tool to check system log files for security violations and unusual activity, it utilizes the program called logtail remembering the last position is read from the log file. Analyzes security or unusual activity from syslog to monitor Apache log files for errors caused by PHP Scripts. Logcheck is used to detect problems automatically in logfiles and results are sent via e-mail. It runs as cronjob off the hour and after every reboot"
},
{
"code": null,
"e": 26150,
"s": 26111,
"text": "The tool has three modes of filtering:"
},
{
"code": null,
"e": 26201,
"s": 26150,
"text": "Server: Default level containing different daemons"
},
{
"code": null,
"e": 26283,
"s": 26201,
"text": "Paranoid: High-security machines run as service in this level also it is verbose."
},
{
"code": null,
"e": 26346,
"s": 26283,
"text": "Workstation: Level for Sheltered machines, filtering messages."
},
{
"code": null,
"e": 26564,
"s": 26346,
"text": "The logcheck package/repository is already installed in Ubuntu/Debian distribution, just use the apt-get command to install Logcheck in Linux then it will automatically start the downloading process and dependencies. "
},
{
"code": null,
"e": 26591,
"s": 26564,
"text": "$ apt-get install logcheck"
},
{
"code": null,
"e": 26742,
"s": 26591,
"text": "An alternative method to install this is by downloading logcheck-1.1.12.tar.gz version and then installing the logcheck tool by using tar xvf command."
},
{
"code": null,
"e": 26810,
"s": 26742,
"text": "tar xvf logcheck-1.1.12.tar.gz\ncd logcheck-1.1.12\nmake\nmake install"
},
{
"code": null,
"e": 27004,
"s": 26810,
"text": "We can directly use the logcheck from the terminal without installation with the help of sudo or us by which we can change the user ID and also checks the logfiles without offset being updated."
},
{
"code": null,
"e": 27051,
"s": 27004,
"text": "Parameters used here are described as follows,"
},
{
"code": null,
"e": 27081,
"s": 27051,
"text": "-u – syslog summary enabling "
},
{
"code": null,
"e": 27116,
"s": 27081,
"text": "-o – STDOUT mode, not sending mail"
},
{
"code": null,
"e": 27157,
"s": 27116,
"text": "-t – Testing mode does not update offset"
},
{
"code": null,
"e": 27191,
"s": 27157,
"text": "$ sudo -u logcheck logcheck -o -t"
},
{
"code": null,
"e": 27338,
"s": 27191,
"text": "Let’s now look at the configuration file logcheck.conf of logcheck located in /etc/logcheck directory and make the necessary changes in the file. "
},
{
"code": null,
"e": 27372,
"s": 27338,
"text": "$ vim /etc/logcheck/logcheck.conf"
},
{
"code": null,
"e": 27603,
"s": 27372,
"text": "Change the value for REPORTLEVEL of your choice of level for controlling level of filtering of logs, then change the value SENDMAILTO to your e-mail address, so you can receive the reports and logs on the E-mail ID as shown below."
},
{
"code": null,
"e": 27744,
"s": 27603,
"text": "Whenever a mail is generated by logcheck has different subject lines for different events which can also be modified to control the subject."
},
{
"code": null,
"e": 28006,
"s": 27744,
"text": "With the help of logfiles stored in /etc/logcheck/logcheck.logfiles for maintaining the list of logfiles that have to be monitored. For defining the list to use another file and in case stored in another location, so to define new PATH modify RULEDIR variable. "
},
{
"code": null,
"e": 28255,
"s": 28006,
"text": "View the configuration files by navigating to /etc/logcheck/logcheck.logfiles or /etc/logcheck/logcheck.files directory for configuring the mail with respect to the report level given by you, these files contain a list of logfiles to be monitored. "
},
{
"code": null,
"e": 28279,
"s": 28255,
"text": "# vim logcheck.logfiles"
},
{
"code": null,
"e": 28629,
"s": 28279,
"text": "Logcheck works using the files /etc/logcheck/ignore.d.server where it will check for lines that do not match rules in ignore files and then it will include those irregularities in the report which is then sent to the user via e-mail, it also reports unusual activity in log files, hard disk errors, failed authentication attempts and kernel issues. "
},
{
"code": null,
"e": 28808,
"s": 28629,
"text": "We know that logcheck sends mail only when any suspicious activity is found, but we can also get the reports immediately or on an hourly basis by executing the following command,"
},
{
"code": null,
"e": 28822,
"s": 28808,
"text": "$ logcheck -m"
},
{
"code": null,
"e": 28879,
"s": 28822,
"text": "Othe parameters to include for sending mail immediately,"
},
{
"code": null,
"e": 28956,
"s": 28879,
"text": "-h – using this we can mention hostname to use it in the subject of the mail"
},
{
"code": null,
"e": 29008,
"s": 28956,
"text": "-o – This option is used to send a report to stdout"
},
{
"code": null,
"e": 29146,
"s": 29008,
"text": "If using a system user it should have valid alias for logcheck and the sender/mailer (mail,sendmail, sSMTP, Postfix) has to be installed,"
},
{
"code": null,
"e": 29165,
"s": 29146,
"text": "$ vim /etc/aliases"
},
{
"code": null,
"e": 29417,
"s": 29165,
"text": "As we know /etc/logcheck/logcheck.logfiles are used to configure, read and monitor the files. This behavior can also be changed and reading files stored in any different location other than the default location. To do so execute the following command,"
},
{
"code": null,
"e": 29501,
"s": 29417,
"text": "$ logcheck -c /etc/logcheck/logcheck.conf\n$ logcheck -L /etc/logcheck/logcheck.conf"
},
{
"code": null,
"e": 29515,
"s": 29501,
"text": "$ logcheck -t"
},
{
"code": null,
"e": 29739,
"s": 29515,
"text": " In the above command, Logtail is a utility command which has a record of positions the tool read from log files. in order to run the tool in testing mode, it can be done by using -t command and offsets will not be updated."
},
{
"code": null,
"e": 29916,
"s": 29739,
"text": "logcheck-test will test logcheck rules quickly and easily. It will parse logfiles to match the logs by single rule or rule file. The testing single rule against /var/log/syslog"
},
{
"code": null,
"e": 29942,
"s": 29916,
"text": "$ logcheck-test -s \"RULE\""
},
{
"code": null,
"e": 29953,
"s": 29942,
"text": "Kali-Linux"
},
{
"code": null,
"e": 29965,
"s": 29953,
"text": "Linux-Tools"
},
{
"code": null,
"e": 29972,
"s": 29965,
"text": "Picked"
},
{
"code": null,
"e": 29983,
"s": 29972,
"text": "Linux-Unix"
},
{
"code": null,
"e": 30081,
"s": 29983,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30116,
"s": 30081,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 30150,
"s": 30116,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 30176,
"s": 30150,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 30205,
"s": 30176,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 30242,
"s": 30205,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 30279,
"s": 30242,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 30321,
"s": 30279,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 30347,
"s": 30321,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 30383,
"s": 30347,
"text": "uniq Command in LINUX with examples"
}
]
|
Maximum sum alternating subsequence - GeeksforGeeks | 08 Mar, 2022
Given an array, the task is to find sum of maximum sum alternating subsequence starting with first element. Here alternating sequence means first decreasing, then increasing, then decreasing, ... For example 10, 5, 14, 3 is an alternating sequence. Note that the reverse type of sequence (increasing – decreasing – increasing -...) is not considered alternating here.Examples:
Input : arr[] = {4, 3, 8, 5, 3, 8}
Output : 28
Explanation:
The alternating subsequence (starting with first element)
that has above maximum sum is {4, 3, 8, 5, 8}
Input : arr[] = {4, 8, 2, 5, 6, 8}
Output : 14
The alternating subsequence (starting with first element)
that has above maximum sum is {4, 2, 8}
This problem is similar to Longest Increasing Subsequence (LIS) problem. and can be solved using Dynamic Programming.
Create two empty array that store result of maximum
sum of alternate sub-sequence
inc[] : inc[i] stores results of maximum sum alternating
subsequence ending with arr[i] such that arr[i]
is greater than previous element of the subsequence
dec[] : dec[i] stores results of maximum sum alternating
subsequence ending with arr[i] such that arr[i]
is less than previous element of the subsequence
Include first element of 'arr' in both inc[] and dec[]
inc[0] = dec[0] = arr[0]
// Maintain a flag i.e. it will makes the greater
// elements count only if the first decreasing element
// is counted.
flag = 0
Traversal two loops
i goes from 1 to n-1
j goes 0 to i-1
IF arr[j] > arr[i]
dec[i] = max(dec[i], inc[j] + arr[i])
// Denotes first decreasing is found
flag = 1
ELSE IF arr[j] < arr[i] && flag == 1
inc[i] = max(inc[i], dec[j]+arr[i]);
Final Last Find maximum value inc[] and dec[] .
Below is implementation of above idea. Note:- For the case where the first element of the array is the smallest element in the array. The output will be the first element only. This is an edge case that need to be checked. Taking a variable and initializing it with the first value of the array and then comparing it with other values will find the min. Check if the min is equal to arr[0]. If it is true then arr[0] is to be returned, because there is no decreasing step available to find an alternating subsequence.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of maximum// sum alternating sequence starting with// first element.#include <bits/stdc++.h>using namespace std; // Return sum of maximum sum alternating// sequence starting with arr[0] and is first// decreasing.int maxAlternateSum(int arr[], int n){ if (n == 1) return arr[0]; // handling the edge case int min = arr[0]; for (int i = 1; i < n; i++) { if (min > arr[i]) min = arr[i]; } if (min == arr[0]) { return arr[0]; } // create two empty array that store result of // maximum sum of alternate sub-sequence // stores sum of decreasing and increasing // sub-sequence int dec[n]; memset(dec, 0, sizeof(dec)); // store sum of increasing and decreasing sub-sequence int inc[n]; memset(inc, 0, sizeof(inc)); // As per question, first element must be part // of solution. dec[0] = inc[0] = arr[0]; int flag = 0; // Traverse remaining elements of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // IF current sub-sequence is decreasing the // update dec[j] if needed. dec[i] by current // inc[j] + arr[i] if (arr[j] > arr[i]) { dec[i] = max(dec[i], inc[j] + arr[i]); // Revert the flag , if first decreasing // is found flag = 1; } // If next element is greater but flag should be // 1 i.e. this element should be counted after // the first decreasing element gets counted else if (arr[j] < arr[i] && flag == 1) // If current sub-sequence is increasing // then update inc[i] inc[i] = max(inc[i], dec[j] + arr[i]); } } // find maximum sum in b/w inc[] and dec[] int result = INT_MIN; for (int i = 0; i < n; i++) { if (result < inc[i]) result = inc[i]; if (result < dec[i]) result = dec[i]; } // return maximum sum alternate sub-sequence return result;} // Driver programint main(){ int arr[] = { 8, 2, 3, 5, 7, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum sum = " << maxAlternateSum(arr, n) << endl; return 0;}
// Java program to find sum of maximum// sum alternating sequence starting with// first element. public class GFG { // Return sum of maximum sum alternating // sequence starting with arr[0] and is first // decreasing. static int maxAlternateSum(int arr[], int n) { if (n == 1) return arr[0]; // handling the edge case int min = arr[0]; for (int i = 1; i < n; i++) { if (min > arr[i]) min = arr[i]; } if (min == arr[0]) { return arr[0]; } // create two empty array that store result of // maximum sum of alternate sub-sequence // stores sum of decreasing and increasing // sub-sequence int dec[] = new int[n]; // store sum of increasing and decreasing // sub-sequence int inc[] = new int[n]; // As per question, first element must be part // of solution. dec[0] = inc[0] = arr[0]; int flag = 0; // Traverse remaining elements of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // IF current sub-sequence is decreasing the // update dec[j] if needed. dec[i] by // current inc[j] + arr[i] if (arr[j] > arr[i]) { dec[i] = Math.max(dec[i], inc[j] + arr[i]); // Revert the flag , if first decreasing // is found flag = 1; } // If next element is greater but flag // should be 1 i.e. this element should be // counted after the first decreasing // element gets counted else if (arr[j] < arr[i] && flag == 1) // If current sub-sequence is increasing // then update inc[i] inc[i] = Math.max(inc[i], dec[j] + arr[i]); } } // find maximum sum in b/w inc[] and dec[] int result = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { if (result < inc[i]) result = inc[i]; if (result < dec[i]) result = dec[i]; } // return maximum sum alternate sub-sequence return result; } // Driver Method public static void main(String[] args) { int arr[] = { 8, 2, 3, 5, 7, 9, 10 }; System.out.println( "Maximum sum = " + maxAlternateSum(arr, arr.length)); }}
# Python3 program to find sum of maximum# sum alternating sequence starting with# first element. # Return sum of maximum sum alternating# sequence starting with arr[0] and is# first decreasing. def maxAlternateSum(arr, n): if (n == 1): return arr[0] min = arr[0] for i in range(1, n): if(min > arr[i]): min = arr[i] if(arr[0] == min): return arr[0] # Create two empty array that # store result of maximum sum # of alternate sub-sequence # Stores sum of decreasing and # increasing sub-sequence dec = [0 for i in range(n + 1)] # store sum of increasing and # decreasing sub-sequence inc = [0 for i in range(n + 1)] # As per question, first element # must be part of solution. dec[0] = inc[0] = arr[0] flag = 0 # Traverse remaining elements of array for i in range(1, n): for j in range(i): # IF current sub-sequence is decreasing the # update dec[j] if needed. dec[i] by current # inc[j] + arr[i] if (arr[j] > arr[i]): dec[i] = max(dec[i], inc[j] + arr[i]) # Revert the flag, if first # decreasing is found flag = 1 # If next element is greater but flag should be 1 # i.e. this element should be counted after the # first decreasing element gets counted else if (arr[j] < arr[i] and flag == 1): # If current sub-sequence is # increasing then update inc[i] inc[i] = max(inc[i], dec[j] + arr[i]) # Find maximum sum in b/w inc[] and dec[] result = -2147483648 for i in range(n): if (result < inc[i]): result = inc[i] if (result < dec[i]): result = dec[i] # Return maximum sum # alternate sub-sequence return result # Driver programarr = [8, 2, 3, 5, 7, 9, 10]n = len(arr)print("Maximum sum = ", maxAlternateSum(arr, n)) # This code is contributed by Anant Agarwal.
// C# program to find sum of maximum// sum alternating sequence starting with// first element.using System;class GFG { // Return sum of maximum // sum alternating // sequence starting with // arr[0] and is first // decreasing. static int maxAlternateSum(int[] arr, int n) { if (n == 1) return arr[0]; // handling the edge case int min = arr[0]; for (int i = 1; i < n; i++) { if (min > arr[i]) min = arr[i]; } if (min == arr[0]) { return arr[0]; } // create two empty array that // store result of maximum sum // of alternate sub-sequence // stores sum of decreasing // and increasing sub-sequence int[] dec = new int[n]; // store sum of increasing and // decreasing sub-sequence int[] inc = new int[n]; // As per question, first // element must be part // of solution. dec[0] = inc[0] = arr[0]; int flag = 0; // Traverse remaining elements of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // IF current sub-sequence // is decreasing the // update dec[j] if needed. // dec[i] by current // inc[j] + arr[i] if (arr[j] > arr[i]) { dec[i] = Math.Max(dec[i], inc[j] + arr[i]); // Revert the flag , if // first decreasing // is found flag = 1; } // If next element is greater // but flag should be 1 // i.e. this element should // be counted after the // first decreasing element // gets counted else if (arr[j] < arr[i] && flag == 1) // If current sub-sequence // is increasing then update // inc[i] inc[i] = Math.Max(inc[i], dec[j] + arr[i]); } } // find maximum sum in b/w // inc[] and dec[] int result = int.MinValue; for (int i = 0; i < n; i++) { if (result < inc[i]) result = inc[i]; if (result < dec[i]) result = dec[i]; } // return maximum sum // alternate sub-sequence return result; } // Driver Method public static void Main() { int[] arr = { 8, 2, 3, 5, 7, 9, 10 }; Console.Write("Maximum sum = " + maxAlternateSum(arr, arr.Length)); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to find sum of maximum// sum alternating sequence starting// with first element. // Return sum of maximum sum alternating// sequence starting with arr[0] and is// first decreasing.function maxAlternateSum($arr, $n){ if ($n == 1) return $arr[0]; $min = $arr[0]; for ($i = 1; $i < $n; $i++) { $min = max($min,$arr[$i]);} if($arr[0]==$min) return $arr[0]; // create two empty array that store result // of maximum sum of alternate sub-sequence // stores sum of decreasing and // increasing sub-sequence $dec = array_fill(0, $n, 0); // store sum of increasing and // decreasing sub-sequence $inc = array_fill(0, $n, 0); // As per question, first element // must be part of solution. $dec[0] = $inc[0] = $arr[0]; $flag = 0; // Traverse remaining elements of array for ($i = 1; $i < $n; $i++) { for ($j = 0; $j < $i; $j++) { // IF current sub-sequence is decreasing // the update dec[j] if needed. dec[i] // by current inc[j] + arr[i] if ($arr[$j] > $arr[$i]) { $dec[$i] = max($dec[$i], $inc[$j] + $arr[$i]); // Revert the flag , if first // decreasing is found $flag = 1; } // If next element is greater but flag // should be 1 i.e. this element should // be counted after the first decreasing // element gets counted else if ($arr[$j] < $arr[$i] && $flag == 1) // If current sub-sequence is increasing // then update inc[i] $inc[$i] = max($inc[$i], $dec[$j] + $arr[$i]); } } // find maximum sum in b/w inc[] and dec[] $result = -(PHP_INT_MAX - 1); for ($i = 0 ; $i < $n; $i++) { if ($result < $inc[$i]) $result = $inc[$i]; if ($result < $dec[$i]) $result = $dec[$i]; } // return maximum sum alternate sub-sequence return $result;} // Driver Code$arr = array(8, 2, 3, 5, 7, 9, 10);$n = sizeof($arr);echo "Maximum sum = ", maxAlternateSum($arr, $n ); // This code is contributed by Ryuga?>
<script> // JavaScript program to find sum of maximum // sum alternating sequence starting with // first element. // Return sum of maximum sum alternating // sequence starting with arr[0] and is first // decreasing. function maxAlternateSum(arr, n) { if (n == 1) return arr[0]; //handling the edge case int min = arr[0]; for (int i=1; i<n; i++){ if (min>arr[i]) min = arr[i]; } if (min==arr[0]){ return arr[0]; } // create two empty array that store result of // maximum sum of alternate sub-sequence // stores sum of decreasing and increasing // sub-sequence let dec = new Array(n); dec.fill(0); // store sum of increasing and decreasing sub-sequence let inc = new Array(n); inc.fill(0); // As per question, first element must be part // of solution. dec[0] = inc[0] = arr[0]; let flag = 0 ; // Traverse remaining elements of array for (let i=1; i<n; i++) { for (let j=0; j<i; j++) { // IF current sub-sequence is decreasing the // update dec[j] if needed. dec[i] by current // inc[j] + arr[i] if (arr[j] > arr[i]) { dec[i] = Math.max(dec[i], inc[j]+arr[i]); // Revert the flag , if first decreasing // is found flag = 1; } // If next element is greater but flag should be 1 // i.e. this element should be counted after the // first decreasing element gets counted else if (arr[j] < arr[i] && flag == 1) // If current sub-sequence is increasing // then update inc[i] inc[i] = Math.max(inc[i], dec[j]+arr[i]); } } // find maximum sum in b/w inc[] and dec[] let result = Number.MIN_VALUE; for (let i = 0 ; i < n; i++) { if (result < inc[i]) result = inc[i]; if (result < dec[i]) result = dec[i]; } // return maximum sum alternate sub-sequence return result; } let arr = [8, 2, 3, 5, 7, 9, 10]; document.write("Maximum sum = " + maxAlternateSum(arr , arr.length)); </script>
Maximum sum = 25
Time Complexity : O(n2) Auxiliary Space : O(n)This article is contributed by Sahil Chhabra(KILLER). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
ankthon
suthar_arun
divyeshrabadiya07
shreyasinghal2
simmytarika5
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Matrix Chain Multiplication | DP-8
Longest Palindromic Substring | Set 1
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Edit Distance | DP-5
Sieve of Eratosthenes
Overlapping Subproblems Property in Dynamic Programming | DP-1
Maximum size square sub-matrix with all 1s | [
{
"code": null,
"e": 26181,
"s": 26153,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 26560,
"s": 26181,
"text": "Given an array, the task is to find sum of maximum sum alternating subsequence starting with first element. Here alternating sequence means first decreasing, then increasing, then decreasing, ... For example 10, 5, 14, 3 is an alternating sequence. Note that the reverse type of sequence (increasing – decreasing – increasing -...) is not considered alternating here.Examples: "
},
{
"code": null,
"e": 26878,
"s": 26560,
"text": "Input : arr[] = {4, 3, 8, 5, 3, 8} \nOutput : 28\nExplanation:\nThe alternating subsequence (starting with first element) \nthat has above maximum sum is {4, 3, 8, 5, 8}\n\nInput : arr[] = {4, 8, 2, 5, 6, 8} \nOutput : 14\nThe alternating subsequence (starting with first element) \nthat has above maximum sum is {4, 2, 8}"
},
{
"code": null,
"e": 26999,
"s": 26880,
"text": "This problem is similar to Longest Increasing Subsequence (LIS) problem. and can be solved using Dynamic Programming. "
},
{
"code": null,
"e": 27992,
"s": 26999,
"text": "Create two empty array that store result of maximum\nsum of alternate sub-sequence\ninc[] : inc[i] stores results of maximum sum alternating\n subsequence ending with arr[i] such that arr[i]\n is greater than previous element of the subsequence \ndec[] : dec[i] stores results of maximum sum alternating\n subsequence ending with arr[i] such that arr[i]\n is less than previous element of the subsequence \n\nInclude first element of 'arr' in both inc[] and dec[] \ninc[0] = dec[0] = arr[0]\n\n// Maintain a flag i.e. it will makes the greater\n// elements count only if the first decreasing element\n// is counted.\nflag = 0 \n\nTraversal two loops\n i goes from 1 to n-1 \n j goes 0 to i-1\n IF arr[j] > arr[i]\n dec[i] = max(dec[i], inc[j] + arr[i])\n \n // Denotes first decreasing is found\n flag = 1 \n \n ELSE IF arr[j] < arr[i] && flag == 1 \n inc[i] = max(inc[i], dec[j]+arr[i]);\n \nFinal Last Find maximum value inc[] and dec[] ."
},
{
"code": null,
"e": 28510,
"s": 27992,
"text": "Below is implementation of above idea. Note:- For the case where the first element of the array is the smallest element in the array. The output will be the first element only. This is an edge case that need to be checked. Taking a variable and initializing it with the first value of the array and then comparing it with other values will find the min. Check if the min is equal to arr[0]. If it is true then arr[0] is to be returned, because there is no decreasing step available to find an alternating subsequence."
},
{
"code": null,
"e": 28514,
"s": 28510,
"text": "C++"
},
{
"code": null,
"e": 28519,
"s": 28514,
"text": "Java"
},
{
"code": null,
"e": 28527,
"s": 28519,
"text": "Python3"
},
{
"code": null,
"e": 28530,
"s": 28527,
"text": "C#"
},
{
"code": null,
"e": 28534,
"s": 28530,
"text": "PHP"
},
{
"code": null,
"e": 28545,
"s": 28534,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of maximum// sum alternating sequence starting with// first element.#include <bits/stdc++.h>using namespace std; // Return sum of maximum sum alternating// sequence starting with arr[0] and is first// decreasing.int maxAlternateSum(int arr[], int n){ if (n == 1) return arr[0]; // handling the edge case int min = arr[0]; for (int i = 1; i < n; i++) { if (min > arr[i]) min = arr[i]; } if (min == arr[0]) { return arr[0]; } // create two empty array that store result of // maximum sum of alternate sub-sequence // stores sum of decreasing and increasing // sub-sequence int dec[n]; memset(dec, 0, sizeof(dec)); // store sum of increasing and decreasing sub-sequence int inc[n]; memset(inc, 0, sizeof(inc)); // As per question, first element must be part // of solution. dec[0] = inc[0] = arr[0]; int flag = 0; // Traverse remaining elements of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // IF current sub-sequence is decreasing the // update dec[j] if needed. dec[i] by current // inc[j] + arr[i] if (arr[j] > arr[i]) { dec[i] = max(dec[i], inc[j] + arr[i]); // Revert the flag , if first decreasing // is found flag = 1; } // If next element is greater but flag should be // 1 i.e. this element should be counted after // the first decreasing element gets counted else if (arr[j] < arr[i] && flag == 1) // If current sub-sequence is increasing // then update inc[i] inc[i] = max(inc[i], dec[j] + arr[i]); } } // find maximum sum in b/w inc[] and dec[] int result = INT_MIN; for (int i = 0; i < n; i++) { if (result < inc[i]) result = inc[i]; if (result < dec[i]) result = dec[i]; } // return maximum sum alternate sub-sequence return result;} // Driver programint main(){ int arr[] = { 8, 2, 3, 5, 7, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum sum = \" << maxAlternateSum(arr, n) << endl; return 0;}",
"e": 30820,
"s": 28545,
"text": null
},
{
"code": "// Java program to find sum of maximum// sum alternating sequence starting with// first element. public class GFG { // Return sum of maximum sum alternating // sequence starting with arr[0] and is first // decreasing. static int maxAlternateSum(int arr[], int n) { if (n == 1) return arr[0]; // handling the edge case int min = arr[0]; for (int i = 1; i < n; i++) { if (min > arr[i]) min = arr[i]; } if (min == arr[0]) { return arr[0]; } // create two empty array that store result of // maximum sum of alternate sub-sequence // stores sum of decreasing and increasing // sub-sequence int dec[] = new int[n]; // store sum of increasing and decreasing // sub-sequence int inc[] = new int[n]; // As per question, first element must be part // of solution. dec[0] = inc[0] = arr[0]; int flag = 0; // Traverse remaining elements of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // IF current sub-sequence is decreasing the // update dec[j] if needed. dec[i] by // current inc[j] + arr[i] if (arr[j] > arr[i]) { dec[i] = Math.max(dec[i], inc[j] + arr[i]); // Revert the flag , if first decreasing // is found flag = 1; } // If next element is greater but flag // should be 1 i.e. this element should be // counted after the first decreasing // element gets counted else if (arr[j] < arr[i] && flag == 1) // If current sub-sequence is increasing // then update inc[i] inc[i] = Math.max(inc[i], dec[j] + arr[i]); } } // find maximum sum in b/w inc[] and dec[] int result = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { if (result < inc[i]) result = inc[i]; if (result < dec[i]) result = dec[i]; } // return maximum sum alternate sub-sequence return result; } // Driver Method public static void main(String[] args) { int arr[] = { 8, 2, 3, 5, 7, 9, 10 }; System.out.println( \"Maximum sum = \" + maxAlternateSum(arr, arr.length)); }}",
"e": 33392,
"s": 30820,
"text": null
},
{
"code": "# Python3 program to find sum of maximum# sum alternating sequence starting with# first element. # Return sum of maximum sum alternating# sequence starting with arr[0] and is# first decreasing. def maxAlternateSum(arr, n): if (n == 1): return arr[0] min = arr[0] for i in range(1, n): if(min > arr[i]): min = arr[i] if(arr[0] == min): return arr[0] # Create two empty array that # store result of maximum sum # of alternate sub-sequence # Stores sum of decreasing and # increasing sub-sequence dec = [0 for i in range(n + 1)] # store sum of increasing and # decreasing sub-sequence inc = [0 for i in range(n + 1)] # As per question, first element # must be part of solution. dec[0] = inc[0] = arr[0] flag = 0 # Traverse remaining elements of array for i in range(1, n): for j in range(i): # IF current sub-sequence is decreasing the # update dec[j] if needed. dec[i] by current # inc[j] + arr[i] if (arr[j] > arr[i]): dec[i] = max(dec[i], inc[j] + arr[i]) # Revert the flag, if first # decreasing is found flag = 1 # If next element is greater but flag should be 1 # i.e. this element should be counted after the # first decreasing element gets counted else if (arr[j] < arr[i] and flag == 1): # If current sub-sequence is # increasing then update inc[i] inc[i] = max(inc[i], dec[j] + arr[i]) # Find maximum sum in b/w inc[] and dec[] result = -2147483648 for i in range(n): if (result < inc[i]): result = inc[i] if (result < dec[i]): result = dec[i] # Return maximum sum # alternate sub-sequence return result # Driver programarr = [8, 2, 3, 5, 7, 9, 10]n = len(arr)print(\"Maximum sum = \", maxAlternateSum(arr, n)) # This code is contributed by Anant Agarwal.",
"e": 35418,
"s": 33392,
"text": null
},
{
"code": "// C# program to find sum of maximum// sum alternating sequence starting with// first element.using System;class GFG { // Return sum of maximum // sum alternating // sequence starting with // arr[0] and is first // decreasing. static int maxAlternateSum(int[] arr, int n) { if (n == 1) return arr[0]; // handling the edge case int min = arr[0]; for (int i = 1; i < n; i++) { if (min > arr[i]) min = arr[i]; } if (min == arr[0]) { return arr[0]; } // create two empty array that // store result of maximum sum // of alternate sub-sequence // stores sum of decreasing // and increasing sub-sequence int[] dec = new int[n]; // store sum of increasing and // decreasing sub-sequence int[] inc = new int[n]; // As per question, first // element must be part // of solution. dec[0] = inc[0] = arr[0]; int flag = 0; // Traverse remaining elements of array for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // IF current sub-sequence // is decreasing the // update dec[j] if needed. // dec[i] by current // inc[j] + arr[i] if (arr[j] > arr[i]) { dec[i] = Math.Max(dec[i], inc[j] + arr[i]); // Revert the flag , if // first decreasing // is found flag = 1; } // If next element is greater // but flag should be 1 // i.e. this element should // be counted after the // first decreasing element // gets counted else if (arr[j] < arr[i] && flag == 1) // If current sub-sequence // is increasing then update // inc[i] inc[i] = Math.Max(inc[i], dec[j] + arr[i]); } } // find maximum sum in b/w // inc[] and dec[] int result = int.MinValue; for (int i = 0; i < n; i++) { if (result < inc[i]) result = inc[i]; if (result < dec[i]) result = dec[i]; } // return maximum sum // alternate sub-sequence return result; } // Driver Method public static void Main() { int[] arr = { 8, 2, 3, 5, 7, 9, 10 }; Console.Write(\"Maximum sum = \" + maxAlternateSum(arr, arr.Length)); }} // This code is contributed by Nitin Mittal.",
"e": 38182,
"s": 35418,
"text": null
},
{
"code": "<?php// PHP program to find sum of maximum// sum alternating sequence starting// with first element. // Return sum of maximum sum alternating// sequence starting with arr[0] and is// first decreasing.function maxAlternateSum($arr, $n){ if ($n == 1) return $arr[0]; $min = $arr[0]; for ($i = 1; $i < $n; $i++) { $min = max($min,$arr[$i]);} if($arr[0]==$min) return $arr[0]; // create two empty array that store result // of maximum sum of alternate sub-sequence // stores sum of decreasing and // increasing sub-sequence $dec = array_fill(0, $n, 0); // store sum of increasing and // decreasing sub-sequence $inc = array_fill(0, $n, 0); // As per question, first element // must be part of solution. $dec[0] = $inc[0] = $arr[0]; $flag = 0; // Traverse remaining elements of array for ($i = 1; $i < $n; $i++) { for ($j = 0; $j < $i; $j++) { // IF current sub-sequence is decreasing // the update dec[j] if needed. dec[i] // by current inc[j] + arr[i] if ($arr[$j] > $arr[$i]) { $dec[$i] = max($dec[$i], $inc[$j] + $arr[$i]); // Revert the flag , if first // decreasing is found $flag = 1; } // If next element is greater but flag // should be 1 i.e. this element should // be counted after the first decreasing // element gets counted else if ($arr[$j] < $arr[$i] && $flag == 1) // If current sub-sequence is increasing // then update inc[i] $inc[$i] = max($inc[$i], $dec[$j] + $arr[$i]); } } // find maximum sum in b/w inc[] and dec[] $result = -(PHP_INT_MAX - 1); for ($i = 0 ; $i < $n; $i++) { if ($result < $inc[$i]) $result = $inc[$i]; if ($result < $dec[$i]) $result = $dec[$i]; } // return maximum sum alternate sub-sequence return $result;} // Driver Code$arr = array(8, 2, 3, 5, 7, 9, 10);$n = sizeof($arr);echo \"Maximum sum = \", maxAlternateSum($arr, $n ); // This code is contributed by Ryuga?>",
"e": 40459,
"s": 38182,
"text": null
},
{
"code": "<script> // JavaScript program to find sum of maximum // sum alternating sequence starting with // first element. // Return sum of maximum sum alternating // sequence starting with arr[0] and is first // decreasing. function maxAlternateSum(arr, n) { if (n == 1) return arr[0]; //handling the edge case int min = arr[0]; for (int i=1; i<n; i++){ if (min>arr[i]) min = arr[i]; } if (min==arr[0]){ return arr[0]; } // create two empty array that store result of // maximum sum of alternate sub-sequence // stores sum of decreasing and increasing // sub-sequence let dec = new Array(n); dec.fill(0); // store sum of increasing and decreasing sub-sequence let inc = new Array(n); inc.fill(0); // As per question, first element must be part // of solution. dec[0] = inc[0] = arr[0]; let flag = 0 ; // Traverse remaining elements of array for (let i=1; i<n; i++) { for (let j=0; j<i; j++) { // IF current sub-sequence is decreasing the // update dec[j] if needed. dec[i] by current // inc[j] + arr[i] if (arr[j] > arr[i]) { dec[i] = Math.max(dec[i], inc[j]+arr[i]); // Revert the flag , if first decreasing // is found flag = 1; } // If next element is greater but flag should be 1 // i.e. this element should be counted after the // first decreasing element gets counted else if (arr[j] < arr[i] && flag == 1) // If current sub-sequence is increasing // then update inc[i] inc[i] = Math.max(inc[i], dec[j]+arr[i]); } } // find maximum sum in b/w inc[] and dec[] let result = Number.MIN_VALUE; for (let i = 0 ; i < n; i++) { if (result < inc[i]) result = inc[i]; if (result < dec[i]) result = dec[i]; } // return maximum sum alternate sub-sequence return result; } let arr = [8, 2, 3, 5, 7, 9, 10]; document.write(\"Maximum sum = \" + maxAlternateSum(arr , arr.length)); </script>",
"e": 43031,
"s": 40459,
"text": null
},
{
"code": null,
"e": 43048,
"s": 43031,
"text": "Maximum sum = 25"
},
{
"code": null,
"e": 43524,
"s": 43048,
"text": "Time Complexity : O(n2) Auxiliary Space : O(n)This article is contributed by Sahil Chhabra(KILLER). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 43537,
"s": 43524,
"text": "nitin mittal"
},
{
"code": null,
"e": 43545,
"s": 43537,
"text": "ankthon"
},
{
"code": null,
"e": 43557,
"s": 43545,
"text": "suthar_arun"
},
{
"code": null,
"e": 43575,
"s": 43557,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 43590,
"s": 43575,
"text": "shreyasinghal2"
},
{
"code": null,
"e": 43603,
"s": 43590,
"text": "simmytarika5"
},
{
"code": null,
"e": 43623,
"s": 43603,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 43643,
"s": 43623,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 43741,
"s": 43643,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43772,
"s": 43741,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 43805,
"s": 43772,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 43832,
"s": 43805,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 43867,
"s": 43832,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 43905,
"s": 43867,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 43973,
"s": 43905,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 43994,
"s": 43973,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 44016,
"s": 43994,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 44079,
"s": 44016,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
}
]
|
What is Puppet Domain-Specific Language? - GeeksforGeeks | 01 Jun, 2020
Puppet is an open-source configuration management automation tool. Puppet permits system administrators to type in infrastructure as code, using the Puppet Descriptive Language rather than utilizing any customized and individual scripts to do so. This means in case the system administrator erroneously alters the state of the machine, at that point puppet can uphold the change and guarantee that the framework returns to the required state. A conventional approach would require the system administrator to login to each machine to perform framework organization assignments but that does not scale well.
Puppet uses the client/server model. The server is called a puppet master. The puppet master stores the recipes or manifests( code containing resources and desired states) for clients. The clients are called Puppet nodes and runs the puppet agent software. The node runs a puppet daemon(agent) to connect to the puppet master. These nodes will download the manifest assigned to the node from the puppet master and apply the configuration if needed.
A puppet run starts with the nodes and not the master. This run uses SSL services to pass data packets back and forth between the nodes and master. The nodes run the factor command to assemble information about the system. These facts are then sent to master.
Once the master receives the facts, it compiles a catalog that describes the state of each resource in the node. The master compares the host-name of each node and matches it to the specific node configuration or uses the default configuration if the node does not match. After the catalog is compiled, the puppet master sends it to the node. Puppet will apply the catalog on the node, ensuring the system is in the desired state.
Resources- Puppet has many built-in resources like file, user, package and service. The puppet language allows administrators to manage the system resources independently and ensure that the system is in the desired state. The example of the resources are package, service, notify, user, exec, and many more. The puppet resource_type command lists the available resource types on a Puppet host. The syntax for a resource_type is as follows:resource_type { 'resource_title':
attr1 => value1,
attr2 => value2,
attr3 => value3,
...
attrN => valueN,
}
The resource deceleration starts with declaring the type of the resource. Puppet has many built-in resource types like file, user, package, and service. The resource type is followed by curly brackets (braces) that include the resource title and the list of value/attribute pairs. The resource title is a sting enclosed within single quotes. A colon separator is used to separate the resource tile and the list of attribute/value pairs.Each resource has its attributes that are also called as parameters. For example, the file has attributes like path, owner, group, ensure, and mode. These attributes are defined as a value using => operator. For example, the owner can have a value of root or the user account that has created the file. As well as, the mode of the file can be 750 or 777 depending on what kind of permission is needed for the file.Resource TitleThe resource title should be defined with utmost care. The title informs the Puppet Compiler about the resource to be actioned on. Multiple similar “resource titles” may have the same attributes. In that case, they can be grouped together in a single resource definition. A similar example is shown belowfile { [ '/etc/firewalld',
'/etc/firewalld/helpers',
'/etc/firewalld/services',
'/etc/firewalld/ipsets' ]:
ensure => 'directory',
owner => 'root',
group => 'root',
mode => '750',
}
The following example shows the declaration for the firewalld service.service { 'httpd':
ensure => 'running',
enable => true,
}
Puppet Manifests– Puppet Manifests are the text documents written in Puppet DSL that describes the end state of the host system. It can be creates using any text editor and the extension of it .pp extension. The following noalice.pp will ensure that Puppet deletes an account called alice from the system.[root@master ~]# vim alice.pp
[root@master ~]# cat noalice.pp
user {'alice':
ensure => 'absent',
}
Puppet Classes- Puppet Classes helps to ensure that the Puppet resource definitions can be made more robust and reusable so that they can be applied to multiple hosts. A puppet class is usually used to define all the resources that are needed to implement a service or run an application. The following example demonstrates the syntax of the classclass class_name ($param = 'value') {
resource definitions...
}
The following example demonstrates a class called testclass test {
user { 'master':
ensure => 'present',
home => '/home/master',
shell => '/bin/bash',
}
file { '/home/master':
ensure => 'directory',
owner => 'master',
group => 'master',
mode => '0770',
require => User['master'],
}
package { 'httpd':
ensure => 'present',
}
service { 'httpd':
ensure => 'running',
enable => true,
require => Package['httpd'],
}
}
include test # include is a function that is used to call the class test in the manifest
The include command is used in a manifest to use a class. It is similar to calling a previously defined function in a programming languagePuppet Modules- Puppet module is a way of packaging puppet manifests and related files into a single file. The module is a tar archive that has an established hierarchy.Puppet module provides a standard, predictable directory structure for the puppet code and related files that they contain.Some of the essential or most frequently used directories in a module hierarchy are listed below:Manifests directory contains all of the puppet manifests defined in the module.File directory contains static fileslib/facter directory contains custom fact definitionsThe test directory contains manifests that are used to test the functionality provided by the module.Puppet DSL shorthandIn case an attribute in a resource definition block ends with a semicolon instead of a comma, then another title followed by a colon and a list of attribute/value pairs can be specified. The following example shows how that can be achieved.file {
'/etc/vmrc':
ensure => 'directory',
owner => 'root',
group => 'root',
mode => '755';
'/etc/rc.d/init.d':
ensure => 'directory',
owner => 'root',
group => 'root',
mode => '755';
}
Puppet FunctionsDuring the catalog compilation on the master, plugins called functions are called. When the puppet manifests calls a function, it returns a value or makes some changes that modify the catalog. The code in the function is written in Ruby, which performs a number of things to produce the final value. The functions perform the following tasks:Evaluating the templatesPerforming mathematical calculationsModifies the catalogPuppet includes many built-in functions. Custom functions can also be composed and used in the modules. Syntax used to built-in the customized functions is as below:function <MODULE NAME>::<NAME>(<PARAMETER LIST>) >> <RETURN TYPE> {
... body of function ...
final expression, which will be the returned value of the function
}
Some of the built in functions are template, alert, include, map and many more.Statement FunctionsStatement functions are a group of built in functions which are only used to modify the catalog. The built in statement functions are:Catalog Statements like include, require, contain and tagLogging statements like debug, info, notice, warning, err.Failure statements like fail.Function CallThe following syntax is used to call a function.function_name(argument, argument, ...) |$parameter, $parameter, ...| { code block }
The function_name is the full name of the function.An opening parentheses to include the list of the arguments. (Parentheses are not required while using the statement functions like include <class-name>). In all the other cases its needed. To understand what are the arguments required by a function, it can be checked in the documentation of that function. In case of an opening parentheses there should be a closing one.Code block or lambda in case the function needs one.In the given example, template, include and each are all functions. file {"/etc/smb.conf":
ensure => file,
content => template("smb/smb.conf.erb"), # function call; resolves to a string
}
include test # function call; modifies catalog
$binaries = [
"facter",
"hiera",
]
# function call with lambda; runs block of code several times
each($binaries) |$binary| {
file {"/usr/bin/$binary":
ensure => link,
target => "/opt/puppetlabs/bin/$binary",
}
}
My Personal Notes
arrow_drop_upSave
Resources- Puppet has many built-in resources like file, user, package and service. The puppet language allows administrators to manage the system resources independently and ensure that the system is in the desired state. The example of the resources are package, service, notify, user, exec, and many more. The puppet resource_type command lists the available resource types on a Puppet host. The syntax for a resource_type is as follows:resource_type { 'resource_title':
attr1 => value1,
attr2 => value2,
attr3 => value3,
...
attrN => valueN,
}
The resource deceleration starts with declaring the type of the resource. Puppet has many built-in resource types like file, user, package, and service. The resource type is followed by curly brackets (braces) that include the resource title and the list of value/attribute pairs. The resource title is a sting enclosed within single quotes. A colon separator is used to separate the resource tile and the list of attribute/value pairs.Each resource has its attributes that are also called as parameters. For example, the file has attributes like path, owner, group, ensure, and mode. These attributes are defined as a value using => operator. For example, the owner can have a value of root or the user account that has created the file. As well as, the mode of the file can be 750 or 777 depending on what kind of permission is needed for the file.Resource TitleThe resource title should be defined with utmost care. The title informs the Puppet Compiler about the resource to be actioned on. Multiple similar “resource titles” may have the same attributes. In that case, they can be grouped together in a single resource definition. A similar example is shown belowfile { [ '/etc/firewalld',
'/etc/firewalld/helpers',
'/etc/firewalld/services',
'/etc/firewalld/ipsets' ]:
ensure => 'directory',
owner => 'root',
group => 'root',
mode => '750',
}
The following example shows the declaration for the firewalld service.service { 'httpd':
ensure => 'running',
enable => true,
}
resource_type { 'resource_title':
attr1 => value1,
attr2 => value2,
attr3 => value3,
...
attrN => valueN,
}
The resource deceleration starts with declaring the type of the resource. Puppet has many built-in resource types like file, user, package, and service. The resource type is followed by curly brackets (braces) that include the resource title and the list of value/attribute pairs. The resource title is a sting enclosed within single quotes. A colon separator is used to separate the resource tile and the list of attribute/value pairs.
Each resource has its attributes that are also called as parameters. For example, the file has attributes like path, owner, group, ensure, and mode. These attributes are defined as a value using => operator. For example, the owner can have a value of root or the user account that has created the file. As well as, the mode of the file can be 750 or 777 depending on what kind of permission is needed for the file.
Resource Title
The resource title should be defined with utmost care. The title informs the Puppet Compiler about the resource to be actioned on. Multiple similar “resource titles” may have the same attributes. In that case, they can be grouped together in a single resource definition. A similar example is shown below
file { [ '/etc/firewalld',
'/etc/firewalld/helpers',
'/etc/firewalld/services',
'/etc/firewalld/ipsets' ]:
ensure => 'directory',
owner => 'root',
group => 'root',
mode => '750',
}
The following example shows the declaration for the firewalld service.
service { 'httpd':
ensure => 'running',
enable => true,
}
Puppet Manifests– Puppet Manifests are the text documents written in Puppet DSL that describes the end state of the host system. It can be creates using any text editor and the extension of it .pp extension. The following noalice.pp will ensure that Puppet deletes an account called alice from the system.[root@master ~]# vim alice.pp
[root@master ~]# cat noalice.pp
user {'alice':
ensure => 'absent',
}
[root@master ~]# vim alice.pp
[root@master ~]# cat noalice.pp
user {'alice':
ensure => 'absent',
}
Puppet Classes- Puppet Classes helps to ensure that the Puppet resource definitions can be made more robust and reusable so that they can be applied to multiple hosts. A puppet class is usually used to define all the resources that are needed to implement a service or run an application. The following example demonstrates the syntax of the classclass class_name ($param = 'value') {
resource definitions...
}
The following example demonstrates a class called testclass test {
user { 'master':
ensure => 'present',
home => '/home/master',
shell => '/bin/bash',
}
file { '/home/master':
ensure => 'directory',
owner => 'master',
group => 'master',
mode => '0770',
require => User['master'],
}
package { 'httpd':
ensure => 'present',
}
service { 'httpd':
ensure => 'running',
enable => true,
require => Package['httpd'],
}
}
include test # include is a function that is used to call the class test in the manifest
The include command is used in a manifest to use a class. It is similar to calling a previously defined function in a programming language
class class_name ($param = 'value') {
resource definitions...
}
The following example demonstrates a class called test
class test {
user { 'master':
ensure => 'present',
home => '/home/master',
shell => '/bin/bash',
}
file { '/home/master':
ensure => 'directory',
owner => 'master',
group => 'master',
mode => '0770',
require => User['master'],
}
package { 'httpd':
ensure => 'present',
}
service { 'httpd':
ensure => 'running',
enable => true,
require => Package['httpd'],
}
}
include test # include is a function that is used to call the class test in the manifest
The include command is used in a manifest to use a class. It is similar to calling a previously defined function in a programming language
Puppet Modules- Puppet module is a way of packaging puppet manifests and related files into a single file. The module is a tar archive that has an established hierarchy.Puppet module provides a standard, predictable directory structure for the puppet code and related files that they contain.Some of the essential or most frequently used directories in a module hierarchy are listed below:Manifests directory contains all of the puppet manifests defined in the module.File directory contains static fileslib/facter directory contains custom fact definitionsThe test directory contains manifests that are used to test the functionality provided by the module.Puppet DSL shorthandIn case an attribute in a resource definition block ends with a semicolon instead of a comma, then another title followed by a colon and a list of attribute/value pairs can be specified. The following example shows how that can be achieved.file {
'/etc/vmrc':
ensure => 'directory',
owner => 'root',
group => 'root',
mode => '755';
'/etc/rc.d/init.d':
ensure => 'directory',
owner => 'root',
group => 'root',
mode => '755';
}
Puppet FunctionsDuring the catalog compilation on the master, plugins called functions are called. When the puppet manifests calls a function, it returns a value or makes some changes that modify the catalog. The code in the function is written in Ruby, which performs a number of things to produce the final value. The functions perform the following tasks:Evaluating the templatesPerforming mathematical calculationsModifies the catalogPuppet includes many built-in functions. Custom functions can also be composed and used in the modules. Syntax used to built-in the customized functions is as below:function <MODULE NAME>::<NAME>(<PARAMETER LIST>) >> <RETURN TYPE> {
... body of function ...
final expression, which will be the returned value of the function
}
Some of the built in functions are template, alert, include, map and many more.Statement FunctionsStatement functions are a group of built in functions which are only used to modify the catalog. The built in statement functions are:Catalog Statements like include, require, contain and tagLogging statements like debug, info, notice, warning, err.Failure statements like fail.Function CallThe following syntax is used to call a function.function_name(argument, argument, ...) |$parameter, $parameter, ...| { code block }
The function_name is the full name of the function.An opening parentheses to include the list of the arguments. (Parentheses are not required while using the statement functions like include <class-name>). In all the other cases its needed. To understand what are the arguments required by a function, it can be checked in the documentation of that function. In case of an opening parentheses there should be a closing one.Code block or lambda in case the function needs one.In the given example, template, include and each are all functions. file {"/etc/smb.conf":
ensure => file,
content => template("smb/smb.conf.erb"), # function call; resolves to a string
}
include test # function call; modifies catalog
$binaries = [
"facter",
"hiera",
]
# function call with lambda; runs block of code several times
each($binaries) |$binary| {
file {"/usr/bin/$binary":
ensure => link,
target => "/opt/puppetlabs/bin/$binary",
}
}
My Personal Notes
arrow_drop_upSave
Manifests directory contains all of the puppet manifests defined in the module.
File directory contains static files
lib/facter directory contains custom fact definitions
The test directory contains manifests that are used to test the functionality provided by the module.
In case an attribute in a resource definition block ends with a semicolon instead of a comma, then another title followed by a colon and a list of attribute/value pairs can be specified. The following example shows how that can be achieved.
file {
'/etc/vmrc':
ensure => 'directory',
owner => 'root',
group => 'root',
mode => '755';
'/etc/rc.d/init.d':
ensure => 'directory',
owner => 'root',
group => 'root',
mode => '755';
}
During the catalog compilation on the master, plugins called functions are called. When the puppet manifests calls a function, it returns a value or makes some changes that modify the catalog.
The code in the function is written in Ruby, which performs a number of things to produce the final value. The functions perform the following tasks:
Evaluating the templates
Performing mathematical calculations
Modifies the catalog
Puppet includes many built-in functions. Custom functions can also be composed and used in the modules.
Syntax used to built-in the customized functions is as below:
function <MODULE NAME>::<NAME>(<PARAMETER LIST>) >> <RETURN TYPE> {
... body of function ...
final expression, which will be the returned value of the function
}
Some of the built in functions are template, alert, include, map and many more.
Statement Functions
Statement functions are a group of built in functions which are only used to modify the catalog. The built in statement functions are:
Catalog Statements like include, require, contain and tag
Logging statements like debug, info, notice, warning, err.
Failure statements like fail.
Function Call
The following syntax is used to call a function.
function_name(argument, argument, ...) |$parameter, $parameter, ...| { code block }
The function_name is the full name of the function.
An opening parentheses to include the list of the arguments. (Parentheses are not required while using the statement functions like include <class-name>). In all the other cases its needed. To understand what are the arguments required by a function, it can be checked in the documentation of that function. In case of an opening parentheses there should be a closing one.
Code block or lambda in case the function needs one.
In the given example, template, include and each are all functions.
file {"/etc/smb.conf":
ensure => file,
content => template("smb/smb.conf.erb"), # function call; resolves to a string
}
include test # function call; modifies catalog
$binaries = [
"facter",
"hiera",
]
# function call with lambda; runs block of code several times
each($binaries) |$binary| {
file {"/usr/bin/$binary":
ensure => link,
target => "/opt/puppetlabs/bin/$binary",
}
}
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
7 Things You Didn’t Know About Java
Introduction to Recurrent Neural Network
12 pip Commands For Python Developers
A Freshers Guide To Programming
ML | Underfitting and Overfitting
Virtualization In Cloud Computing and Types
What is web socket and how it is different from the HTTP?
Software Testing | Basics | [
{
"code": null,
"e": 26273,
"s": 26245,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 26880,
"s": 26273,
"text": "Puppet is an open-source configuration management automation tool. Puppet permits system administrators to type in infrastructure as code, using the Puppet Descriptive Language rather than utilizing any customized and individual scripts to do so. This means in case the system administrator erroneously alters the state of the machine, at that point puppet can uphold the change and guarantee that the framework returns to the required state. A conventional approach would require the system administrator to login to each machine to perform framework organization assignments but that does not scale well."
},
{
"code": null,
"e": 27329,
"s": 26880,
"text": "Puppet uses the client/server model. The server is called a puppet master. The puppet master stores the recipes or manifests( code containing resources and desired states) for clients. The clients are called Puppet nodes and runs the puppet agent software. The node runs a puppet daemon(agent) to connect to the puppet master. These nodes will download the manifest assigned to the node from the puppet master and apply the configuration if needed."
},
{
"code": null,
"e": 27589,
"s": 27329,
"text": "A puppet run starts with the nodes and not the master. This run uses SSL services to pass data packets back and forth between the nodes and master. The nodes run the factor command to assemble information about the system. These facts are then sent to master."
},
{
"code": null,
"e": 28020,
"s": 27589,
"text": "Once the master receives the facts, it compiles a catalog that describes the state of each resource in the node. The master compares the host-name of each node and matches it to the specific node configuration or uses the default configuration if the node does not match. After the catalog is compiled, the puppet master sends it to the node. Puppet will apply the catalog on the node, ensuring the system is in the desired state."
},
{
"code": null,
"e": 35069,
"s": 28020,
"text": "Resources- Puppet has many built-in resources like file, user, package and service. The puppet language allows administrators to manage the system resources independently and ensure that the system is in the desired state. The example of the resources are package, service, notify, user, exec, and many more. The puppet resource_type command lists the available resource types on a Puppet host. The syntax for a resource_type is as follows:resource_type { 'resource_title':\n attr1 => value1,\n attr2 => value2,\n attr3 => value3,\n ...\n attrN => valueN,\n}\nThe resource deceleration starts with declaring the type of the resource. Puppet has many built-in resource types like file, user, package, and service. The resource type is followed by curly brackets (braces) that include the resource title and the list of value/attribute pairs. The resource title is a sting enclosed within single quotes. A colon separator is used to separate the resource tile and the list of attribute/value pairs.Each resource has its attributes that are also called as parameters. For example, the file has attributes like path, owner, group, ensure, and mode. These attributes are defined as a value using => operator. For example, the owner can have a value of root or the user account that has created the file. As well as, the mode of the file can be 750 or 777 depending on what kind of permission is needed for the file.Resource TitleThe resource title should be defined with utmost care. The title informs the Puppet Compiler about the resource to be actioned on. Multiple similar “resource titles” may have the same attributes. In that case, they can be grouped together in a single resource definition. A similar example is shown belowfile { [ '/etc/firewalld',\n '/etc/firewalld/helpers',\n '/etc/firewalld/services',\n '/etc/firewalld/ipsets' ]:\n ensure => 'directory',\n owner => 'root',\n group => 'root',\n mode => '750',\n}\n\n\n\nThe following example shows the declaration for the firewalld service.service { 'httpd':\n ensure => 'running',\n enable => true,\n}\nPuppet Manifests– Puppet Manifests are the text documents written in Puppet DSL that describes the end state of the host system. It can be creates using any text editor and the extension of it .pp extension. The following noalice.pp will ensure that Puppet deletes an account called alice from the system.[root@master ~]# vim alice.pp\n[root@master ~]# cat noalice.pp\nuser {'alice':\n ensure => 'absent',\n}\nPuppet Classes- Puppet Classes helps to ensure that the Puppet resource definitions can be made more robust and reusable so that they can be applied to multiple hosts. A puppet class is usually used to define all the resources that are needed to implement a service or run an application. The following example demonstrates the syntax of the classclass class_name ($param = 'value') {\n resource definitions...\n}\nThe following example demonstrates a class called testclass test {\n user { 'master':\n ensure => 'present',\n home => '/home/master',\n shell => '/bin/bash',\n }\n\n file { '/home/master':\n ensure => 'directory',\n owner => 'master',\n group => 'master',\n mode => '0770',\n require => User['master'],\n }\n\n package { 'httpd':\n ensure => 'present',\n }\n\n service { 'httpd':\n ensure => 'running',\n enable => true,\n require => Package['httpd'],\n }\n\n}\ninclude test # include is a function that is used to call the class test in the manifest\nThe include command is used in a manifest to use a class. It is similar to calling a previously defined function in a programming languagePuppet Modules- Puppet module is a way of packaging puppet manifests and related files into a single file. The module is a tar archive that has an established hierarchy.Puppet module provides a standard, predictable directory structure for the puppet code and related files that they contain.Some of the essential or most frequently used directories in a module hierarchy are listed below:Manifests directory contains all of the puppet manifests defined in the module.File directory contains static fileslib/facter directory contains custom fact definitionsThe test directory contains manifests that are used to test the functionality provided by the module.Puppet DSL shorthandIn case an attribute in a resource definition block ends with a semicolon instead of a comma, then another title followed by a colon and a list of attribute/value pairs can be specified. The following example shows how that can be achieved.file {\n '/etc/vmrc':\n ensure => 'directory',\n owner => 'root',\n group => 'root',\n mode => '755';\n \n '/etc/rc.d/init.d':\n ensure => 'directory',\n owner => 'root',\n group => 'root',\n mode => '755';\n}\n\nPuppet FunctionsDuring the catalog compilation on the master, plugins called functions are called. When the puppet manifests calls a function, it returns a value or makes some changes that modify the catalog. The code in the function is written in Ruby, which performs a number of things to produce the final value. The functions perform the following tasks:Evaluating the templatesPerforming mathematical calculationsModifies the catalogPuppet includes many built-in functions. Custom functions can also be composed and used in the modules. Syntax used to built-in the customized functions is as below:function <MODULE NAME>::<NAME>(<PARAMETER LIST>) >> <RETURN TYPE> {\n ... body of function ...\n final expression, which will be the returned value of the function\n}\nSome of the built in functions are template, alert, include, map and many more.Statement FunctionsStatement functions are a group of built in functions which are only used to modify the catalog. The built in statement functions are:Catalog Statements like include, require, contain and tagLogging statements like debug, info, notice, warning, err.Failure statements like fail.Function CallThe following syntax is used to call a function.function_name(argument, argument, ...) |$parameter, $parameter, ...| { code block }\n\nThe function_name is the full name of the function.An opening parentheses to include the list of the arguments. (Parentheses are not required while using the statement functions like include <class-name>). In all the other cases its needed. To understand what are the arguments required by a function, it can be checked in the documentation of that function. In case of an opening parentheses there should be a closing one.Code block or lambda in case the function needs one.In the given example, template, include and each are all functions. file {\"/etc/smb.conf\":\n ensure => file,\n content => template(\"smb/smb.conf.erb\"), # function call; resolves to a string\n\n}\ninclude test # function call; modifies catalog\n$binaries = [\n \"facter\",\n \"hiera\",\n]\n\n# function call with lambda; runs block of code several times\neach($binaries) |$binary| {\n file {\"/usr/bin/$binary\":\n ensure => link,\n target => \"/opt/puppetlabs/bin/$binary\",\n }\n}\n\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 37151,
"s": 35069,
"text": "Resources- Puppet has many built-in resources like file, user, package and service. The puppet language allows administrators to manage the system resources independently and ensure that the system is in the desired state. The example of the resources are package, service, notify, user, exec, and many more. The puppet resource_type command lists the available resource types on a Puppet host. The syntax for a resource_type is as follows:resource_type { 'resource_title':\n attr1 => value1,\n attr2 => value2,\n attr3 => value3,\n ...\n attrN => valueN,\n}\nThe resource deceleration starts with declaring the type of the resource. Puppet has many built-in resource types like file, user, package, and service. The resource type is followed by curly brackets (braces) that include the resource title and the list of value/attribute pairs. The resource title is a sting enclosed within single quotes. A colon separator is used to separate the resource tile and the list of attribute/value pairs.Each resource has its attributes that are also called as parameters. For example, the file has attributes like path, owner, group, ensure, and mode. These attributes are defined as a value using => operator. For example, the owner can have a value of root or the user account that has created the file. As well as, the mode of the file can be 750 or 777 depending on what kind of permission is needed for the file.Resource TitleThe resource title should be defined with utmost care. The title informs the Puppet Compiler about the resource to be actioned on. Multiple similar “resource titles” may have the same attributes. In that case, they can be grouped together in a single resource definition. A similar example is shown belowfile { [ '/etc/firewalld',\n '/etc/firewalld/helpers',\n '/etc/firewalld/services',\n '/etc/firewalld/ipsets' ]:\n ensure => 'directory',\n owner => 'root',\n group => 'root',\n mode => '750',\n}\n\n\n\nThe following example shows the declaration for the firewalld service.service { 'httpd':\n ensure => 'running',\n enable => true,\n}\n"
},
{
"code": null,
"e": 37270,
"s": 37151,
"text": "resource_type { 'resource_title':\n attr1 => value1,\n attr2 => value2,\n attr3 => value3,\n ...\n attrN => valueN,\n}\n"
},
{
"code": null,
"e": 37707,
"s": 37270,
"text": "The resource deceleration starts with declaring the type of the resource. Puppet has many built-in resource types like file, user, package, and service. The resource type is followed by curly brackets (braces) that include the resource title and the list of value/attribute pairs. The resource title is a sting enclosed within single quotes. A colon separator is used to separate the resource tile and the list of attribute/value pairs."
},
{
"code": null,
"e": 38122,
"s": 37707,
"text": "Each resource has its attributes that are also called as parameters. For example, the file has attributes like path, owner, group, ensure, and mode. These attributes are defined as a value using => operator. For example, the owner can have a value of root or the user account that has created the file. As well as, the mode of the file can be 750 or 777 depending on what kind of permission is needed for the file."
},
{
"code": null,
"e": 38137,
"s": 38122,
"text": "Resource Title"
},
{
"code": null,
"e": 38442,
"s": 38137,
"text": "The resource title should be defined with utmost care. The title informs the Puppet Compiler about the resource to be actioned on. Multiple similar “resource titles” may have the same attributes. In that case, they can be grouped together in a single resource definition. A similar example is shown below"
},
{
"code": null,
"e": 38666,
"s": 38442,
"text": "file { [ '/etc/firewalld',\n '/etc/firewalld/helpers',\n '/etc/firewalld/services',\n '/etc/firewalld/ipsets' ]:\n ensure => 'directory',\n owner => 'root',\n group => 'root',\n mode => '750',\n}\n\n\n\n"
},
{
"code": null,
"e": 38737,
"s": 38666,
"text": "The following example shows the declaration for the firewalld service."
},
{
"code": null,
"e": 38800,
"s": 38737,
"text": "service { 'httpd':\n ensure => 'running',\n enable => true,\n}\n"
},
{
"code": null,
"e": 39207,
"s": 38800,
"text": "Puppet Manifests– Puppet Manifests are the text documents written in Puppet DSL that describes the end state of the host system. It can be creates using any text editor and the extension of it .pp extension. The following noalice.pp will ensure that Puppet deletes an account called alice from the system.[root@master ~]# vim alice.pp\n[root@master ~]# cat noalice.pp\nuser {'alice':\n ensure => 'absent',\n}\n"
},
{
"code": null,
"e": 39309,
"s": 39207,
"text": "[root@master ~]# vim alice.pp\n[root@master ~]# cat noalice.pp\nuser {'alice':\n ensure => 'absent',\n}\n"
},
{
"code": null,
"e": 40448,
"s": 39309,
"text": "Puppet Classes- Puppet Classes helps to ensure that the Puppet resource definitions can be made more robust and reusable so that they can be applied to multiple hosts. A puppet class is usually used to define all the resources that are needed to implement a service or run an application. The following example demonstrates the syntax of the classclass class_name ($param = 'value') {\n resource definitions...\n}\nThe following example demonstrates a class called testclass test {\n user { 'master':\n ensure => 'present',\n home => '/home/master',\n shell => '/bin/bash',\n }\n\n file { '/home/master':\n ensure => 'directory',\n owner => 'master',\n group => 'master',\n mode => '0770',\n require => User['master'],\n }\n\n package { 'httpd':\n ensure => 'present',\n }\n\n service { 'httpd':\n ensure => 'running',\n enable => true,\n require => Package['httpd'],\n }\n\n}\ninclude test # include is a function that is used to call the class test in the manifest\nThe include command is used in a manifest to use a class. It is similar to calling a previously defined function in a programming language"
},
{
"code": null,
"e": 40515,
"s": 40448,
"text": "class class_name ($param = 'value') {\n resource definitions...\n}\n"
},
{
"code": null,
"e": 40570,
"s": 40515,
"text": "The following example demonstrates a class called test"
},
{
"code": null,
"e": 41104,
"s": 40570,
"text": "class test {\n user { 'master':\n ensure => 'present',\n home => '/home/master',\n shell => '/bin/bash',\n }\n\n file { '/home/master':\n ensure => 'directory',\n owner => 'master',\n group => 'master',\n mode => '0770',\n require => User['master'],\n }\n\n package { 'httpd':\n ensure => 'present',\n }\n\n service { 'httpd':\n ensure => 'running',\n enable => true,\n require => Package['httpd'],\n }\n\n}\ninclude test # include is a function that is used to call the class test in the manifest\n"
},
{
"code": null,
"e": 41243,
"s": 41104,
"text": "The include command is used in a manifest to use a class. It is similar to calling a previously defined function in a programming language"
},
{
"code": null,
"e": 44667,
"s": 41243,
"text": "Puppet Modules- Puppet module is a way of packaging puppet manifests and related files into a single file. The module is a tar archive that has an established hierarchy.Puppet module provides a standard, predictable directory structure for the puppet code and related files that they contain.Some of the essential or most frequently used directories in a module hierarchy are listed below:Manifests directory contains all of the puppet manifests defined in the module.File directory contains static fileslib/facter directory contains custom fact definitionsThe test directory contains manifests that are used to test the functionality provided by the module.Puppet DSL shorthandIn case an attribute in a resource definition block ends with a semicolon instead of a comma, then another title followed by a colon and a list of attribute/value pairs can be specified. The following example shows how that can be achieved.file {\n '/etc/vmrc':\n ensure => 'directory',\n owner => 'root',\n group => 'root',\n mode => '755';\n \n '/etc/rc.d/init.d':\n ensure => 'directory',\n owner => 'root',\n group => 'root',\n mode => '755';\n}\n\nPuppet FunctionsDuring the catalog compilation on the master, plugins called functions are called. When the puppet manifests calls a function, it returns a value or makes some changes that modify the catalog. The code in the function is written in Ruby, which performs a number of things to produce the final value. The functions perform the following tasks:Evaluating the templatesPerforming mathematical calculationsModifies the catalogPuppet includes many built-in functions. Custom functions can also be composed and used in the modules. Syntax used to built-in the customized functions is as below:function <MODULE NAME>::<NAME>(<PARAMETER LIST>) >> <RETURN TYPE> {\n ... body of function ...\n final expression, which will be the returned value of the function\n}\nSome of the built in functions are template, alert, include, map and many more.Statement FunctionsStatement functions are a group of built in functions which are only used to modify the catalog. The built in statement functions are:Catalog Statements like include, require, contain and tagLogging statements like debug, info, notice, warning, err.Failure statements like fail.Function CallThe following syntax is used to call a function.function_name(argument, argument, ...) |$parameter, $parameter, ...| { code block }\n\nThe function_name is the full name of the function.An opening parentheses to include the list of the arguments. (Parentheses are not required while using the statement functions like include <class-name>). In all the other cases its needed. To understand what are the arguments required by a function, it can be checked in the documentation of that function. In case of an opening parentheses there should be a closing one.Code block or lambda in case the function needs one.In the given example, template, include and each are all functions. file {\"/etc/smb.conf\":\n ensure => file,\n content => template(\"smb/smb.conf.erb\"), # function call; resolves to a string\n\n}\ninclude test # function call; modifies catalog\n$binaries = [\n \"facter\",\n \"hiera\",\n]\n\n# function call with lambda; runs block of code several times\neach($binaries) |$binary| {\n file {\"/usr/bin/$binary\":\n ensure => link,\n target => \"/opt/puppetlabs/bin/$binary\",\n }\n}\n\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 44747,
"s": 44667,
"text": "Manifests directory contains all of the puppet manifests defined in the module."
},
{
"code": null,
"e": 44784,
"s": 44747,
"text": "File directory contains static files"
},
{
"code": null,
"e": 44838,
"s": 44784,
"text": "lib/facter directory contains custom fact definitions"
},
{
"code": null,
"e": 44940,
"s": 44838,
"text": "The test directory contains manifests that are used to test the functionality provided by the module."
},
{
"code": null,
"e": 45181,
"s": 44940,
"text": "In case an attribute in a resource definition block ends with a semicolon instead of a comma, then another title followed by a colon and a list of attribute/value pairs can be specified. The following example shows how that can be achieved."
},
{
"code": null,
"e": 45415,
"s": 45181,
"text": "file {\n '/etc/vmrc':\n ensure => 'directory',\n owner => 'root',\n group => 'root',\n mode => '755';\n \n '/etc/rc.d/init.d':\n ensure => 'directory',\n owner => 'root',\n group => 'root',\n mode => '755';\n}\n\n"
},
{
"code": null,
"e": 45609,
"s": 45415,
"text": "During the catalog compilation on the master, plugins called functions are called. When the puppet manifests calls a function, it returns a value or makes some changes that modify the catalog. "
},
{
"code": null,
"e": 45759,
"s": 45609,
"text": "The code in the function is written in Ruby, which performs a number of things to produce the final value. The functions perform the following tasks:"
},
{
"code": null,
"e": 45784,
"s": 45759,
"text": "Evaluating the templates"
},
{
"code": null,
"e": 45821,
"s": 45784,
"text": "Performing mathematical calculations"
},
{
"code": null,
"e": 45842,
"s": 45821,
"text": "Modifies the catalog"
},
{
"code": null,
"e": 45947,
"s": 45842,
"text": "Puppet includes many built-in functions. Custom functions can also be composed and used in the modules. "
},
{
"code": null,
"e": 46009,
"s": 45947,
"text": "Syntax used to built-in the customized functions is as below:"
},
{
"code": null,
"e": 46176,
"s": 46009,
"text": "function <MODULE NAME>::<NAME>(<PARAMETER LIST>) >> <RETURN TYPE> {\n ... body of function ...\n final expression, which will be the returned value of the function\n}\n"
},
{
"code": null,
"e": 46256,
"s": 46176,
"text": "Some of the built in functions are template, alert, include, map and many more."
},
{
"code": null,
"e": 46276,
"s": 46256,
"text": "Statement Functions"
},
{
"code": null,
"e": 46411,
"s": 46276,
"text": "Statement functions are a group of built in functions which are only used to modify the catalog. The built in statement functions are:"
},
{
"code": null,
"e": 46469,
"s": 46411,
"text": "Catalog Statements like include, require, contain and tag"
},
{
"code": null,
"e": 46528,
"s": 46469,
"text": "Logging statements like debug, info, notice, warning, err."
},
{
"code": null,
"e": 46558,
"s": 46528,
"text": "Failure statements like fail."
},
{
"code": null,
"e": 46572,
"s": 46558,
"text": "Function Call"
},
{
"code": null,
"e": 46621,
"s": 46572,
"text": "The following syntax is used to call a function."
},
{
"code": null,
"e": 46707,
"s": 46621,
"text": "function_name(argument, argument, ...) |$parameter, $parameter, ...| { code block }\n\n"
},
{
"code": null,
"e": 46759,
"s": 46707,
"text": "The function_name is the full name of the function."
},
{
"code": null,
"e": 47132,
"s": 46759,
"text": "An opening parentheses to include the list of the arguments. (Parentheses are not required while using the statement functions like include <class-name>). In all the other cases its needed. To understand what are the arguments required by a function, it can be checked in the documentation of that function. In case of an opening parentheses there should be a closing one."
},
{
"code": null,
"e": 47185,
"s": 47132,
"text": "Code block or lambda in case the function needs one."
},
{
"code": null,
"e": 47254,
"s": 47185,
"text": "In the given example, template, include and each are all functions. "
},
{
"code": null,
"e": 47658,
"s": 47254,
"text": "file {\"/etc/smb.conf\":\n ensure => file,\n content => template(\"smb/smb.conf.erb\"), # function call; resolves to a string\n\n}\ninclude test # function call; modifies catalog\n$binaries = [\n \"facter\",\n \"hiera\",\n]\n\n# function call with lambda; runs block of code several times\neach($binaries) |$binary| {\n file {\"/usr/bin/$binary\":\n ensure => link,\n target => \"/opt/puppetlabs/bin/$binary\",\n }\n}\n\n"
},
{
"code": null,
"e": 47664,
"s": 47658,
"text": "GBlog"
},
{
"code": null,
"e": 47762,
"s": 47664,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 47787,
"s": 47762,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 47814,
"s": 47787,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 47850,
"s": 47814,
"text": "7 Things You Didn’t Know About Java"
},
{
"code": null,
"e": 47891,
"s": 47850,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 47929,
"s": 47891,
"text": "12 pip Commands For Python Developers"
},
{
"code": null,
"e": 47961,
"s": 47929,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 47995,
"s": 47961,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 48039,
"s": 47995,
"text": "Virtualization In Cloud Computing and Types"
},
{
"code": null,
"e": 48097,
"s": 48039,
"text": "What is web socket and how it is different from the HTTP?"
}
]
|
stty command in Linux with Examples - GeeksforGeeks | 18 Feb, 2021
stty command in Linux is used to change and print terminal line settings. Basically, this command shows or changes terminal characteristics.
Syntax:
stty [-F DEVICE | --file=DEVICE] [SETTING]...
stty [-F DEVICE | --file=DEVICE] [-a|--all]
stty [-F DEVICE | --file=DEVICE] [-g|--save]
Example: It will display the characteristics of the terminal.
Options:
stty –all: This option print all current settings in human-readable form.stty --all
stty --all
stty -g: This option will print all current settings in a stty-readable form.stty -g
stty -g
stty -F : This option will open and use the specified DEVICE instead of stdin.Example:stty -F D/
Example:
stty -F D/
stty –help : This option will display this help and exit.stty --help
stty --help
stty –version: This option will show the version information and exit.stty --version
stty --version
YouTubeGeeksforGeeks507K subscribersLinux Tutorials | About the user and the terminal | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:002:04 / 2:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WnjofnvIIvg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Conditional Statements | Shell Script
Tail command in Linux with examples
scp command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
ps command in Linux with Examples
tr command in Unix/Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
mv command in Linux with examples | [
{
"code": null,
"e": 25533,
"s": 25505,
"text": "\n18 Feb, 2021"
},
{
"code": null,
"e": 25674,
"s": 25533,
"text": "stty command in Linux is used to change and print terminal line settings. Basically, this command shows or changes terminal characteristics."
},
{
"code": null,
"e": 25682,
"s": 25674,
"text": "Syntax:"
},
{
"code": null,
"e": 25818,
"s": 25682,
"text": "stty [-F DEVICE | --file=DEVICE] [SETTING]...\nstty [-F DEVICE | --file=DEVICE] [-a|--all]\nstty [-F DEVICE | --file=DEVICE] [-g|--save]\n"
},
{
"code": null,
"e": 25880,
"s": 25818,
"text": "Example: It will display the characteristics of the terminal."
},
{
"code": null,
"e": 25889,
"s": 25880,
"text": "Options:"
},
{
"code": null,
"e": 25973,
"s": 25889,
"text": "stty –all: This option print all current settings in human-readable form.stty --all"
},
{
"code": null,
"e": 25984,
"s": 25973,
"text": "stty --all"
},
{
"code": null,
"e": 26069,
"s": 25984,
"text": "stty -g: This option will print all current settings in a stty-readable form.stty -g"
},
{
"code": null,
"e": 26077,
"s": 26069,
"text": "stty -g"
},
{
"code": null,
"e": 26174,
"s": 26077,
"text": "stty -F : This option will open and use the specified DEVICE instead of stdin.Example:stty -F D/"
},
{
"code": null,
"e": 26183,
"s": 26174,
"text": "Example:"
},
{
"code": null,
"e": 26194,
"s": 26183,
"text": "stty -F D/"
},
{
"code": null,
"e": 26263,
"s": 26194,
"text": "stty –help : This option will display this help and exit.stty --help"
},
{
"code": null,
"e": 26275,
"s": 26263,
"text": "stty --help"
},
{
"code": null,
"e": 26360,
"s": 26275,
"text": "stty –version: This option will show the version information and exit.stty --version"
},
{
"code": null,
"e": 26375,
"s": 26360,
"text": "stty --version"
},
{
"code": null,
"e": 27223,
"s": 26375,
"text": "YouTubeGeeksforGeeks507K subscribersLinux Tutorials | About the user and the terminal | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:002:04 / 2:30•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=WnjofnvIIvg\" 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": 27237,
"s": 27223,
"text": "linux-command"
},
{
"code": null,
"e": 27257,
"s": 27237,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 27268,
"s": 27257,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27366,
"s": 27268,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27404,
"s": 27366,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 27440,
"s": 27404,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 27475,
"s": 27440,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27511,
"s": 27475,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 27530,
"s": 27511,
"text": "Compiling with g++"
},
{
"code": null,
"e": 27564,
"s": 27530,
"text": "ps command in Linux with Examples"
},
{
"code": null,
"e": 27603,
"s": 27564,
"text": "tr command in Unix/Linux with examples"
},
{
"code": null,
"e": 27629,
"s": 27603,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27658,
"s": 27629,
"text": "SED command in Linux | Set 2"
}
]
|
Batch Script - Calling a Function | A function is called in Batch Script by using the call command. Following is the syntax.
call :function_name
Following example shows how a function can be called from the main program.
@echo off
SETLOCAL
CALL :Display
EXIT /B %ERRORLEVEL%
:Display
SET /A index=2
echo The value of index is %index%
EXIT /B 0
One key thing to note when defining the main program is to ensure that the statement EXIT /B %ERRORLEVEL% is put in the main program to separate the code of the main program from the function.
The above command produces the following output.
The value of index is 2
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2258,
"s": 2169,
"text": "A function is called in Batch Script by using the call command. Following is the syntax."
},
{
"code": null,
"e": 2279,
"s": 2258,
"text": "call :function_name\n"
},
{
"code": null,
"e": 2355,
"s": 2279,
"text": "Following example shows how a function can be called from the main program."
},
{
"code": null,
"e": 2485,
"s": 2355,
"text": "@echo off \nSETLOCAL \nCALL :Display \nEXIT /B %ERRORLEVEL% \n:Display \nSET /A index=2 \necho The value of index is %index% \nEXIT /B 0"
},
{
"code": null,
"e": 2678,
"s": 2485,
"text": "One key thing to note when defining the main program is to ensure that the statement EXIT /B %ERRORLEVEL% is put in the main program to separate the code of the main program from the function."
},
{
"code": null,
"e": 2727,
"s": 2678,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 2752,
"s": 2727,
"text": "The value of index is 2\n"
},
{
"code": null,
"e": 2759,
"s": 2752,
"text": " Print"
},
{
"code": null,
"e": 2770,
"s": 2759,
"text": " Add Notes"
}
]
|
AngularJS - Expressions | Expressions are used to bind application data to HTML. Expressions are written inside double curly braces such as in {{ expression}}. Expressions behave similar to ngbind directives. AngularJS expressions are pure JavaScript expressions and output the data where they are used.
<p>Expense on Books : {{cost * quantity}} Rs</p>
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
<p>Roll No: {{student.rollno}}</p>
<p>Marks(Math): {{marks[3]}}</p>
The following example shows the use of all the above-mentioned expressions −
<html>
<head>
<title>AngularJS Expressions</title>
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "" ng-init = "quantity = 1;cost = 30;
student = {firstname:'Mahesh',lastname:'Parashar',rollno:101};
marks = [80,90,75,73,60]">
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
<p>Expense on Books : {{cost * quantity}} Rs</p>
<p>Roll No: {{student.rollno}}</p>
<p>Marks(Math): {{marks[3]}}</p>
</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</body>
</html>
Open the file testAngularJS.htm in a web browser and see the result.
Hello {{student.firstname + " " + student.lastname}}!
Expense on Books : {{cost * quantity}} Rs
Roll No: {{student.rollno}}
Marks(Math): {{marks[3]}}
16 Lectures
1.5 hours
Anadi Sharma
40 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2977,
"s": 2699,
"text": "Expressions are used to bind application data to HTML. Expressions are written inside double curly braces such as in {{ expression}}. Expressions behave similar to ngbind directives. AngularJS expressions are pure JavaScript expressions and output the data where they are used."
},
{
"code": null,
"e": 3027,
"s": 2977,
"text": "<p>Expense on Books : {{cost * quantity}} Rs</p>\n"
},
{
"code": null,
"e": 3089,
"s": 3027,
"text": "<p>Hello {{student.firstname + \" \" + student.lastname}}!</p>\n"
},
{
"code": null,
"e": 3125,
"s": 3089,
"text": "<p>Roll No: {{student.rollno}}</p>\n"
},
{
"code": null,
"e": 3159,
"s": 3125,
"text": "<p>Marks(Math): {{marks[3]}}</p>\n"
},
{
"code": null,
"e": 3236,
"s": 3159,
"text": "The following example shows the use of all the above-mentioned expressions −"
},
{
"code": null,
"e": 3898,
"s": 3236,
"text": "<html>\n <head>\n <title>AngularJS Expressions</title>\n </head>\n \n <body>\n <h1>Sample Application</h1>\n \n <div ng-app = \"\" ng-init = \"quantity = 1;cost = 30; \n student = {firstname:'Mahesh',lastname:'Parashar',rollno:101};\n marks = [80,90,75,73,60]\">\n <p>Hello {{student.firstname + \" \" + student.lastname}}!</p>\n <p>Expense on Books : {{cost * quantity}} Rs</p>\n <p>Roll No: {{student.rollno}}</p>\n <p>Marks(Math): {{marks[3]}}</p>\n </div>\n \n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\">\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3967,
"s": 3898,
"text": "Open the file testAngularJS.htm in a web browser and see the result."
},
{
"code": null,
"e": 4021,
"s": 3967,
"text": "Hello {{student.firstname + \" \" + student.lastname}}!"
},
{
"code": null,
"e": 4063,
"s": 4021,
"text": "Expense on Books : {{cost * quantity}} Rs"
},
{
"code": null,
"e": 4091,
"s": 4063,
"text": "Roll No: {{student.rollno}}"
},
{
"code": null,
"e": 4117,
"s": 4091,
"text": "Marks(Math): {{marks[3]}}"
},
{
"code": null,
"e": 4152,
"s": 4117,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4166,
"s": 4152,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4201,
"s": 4166,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4221,
"s": 4201,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 4228,
"s": 4221,
"text": " Print"
},
{
"code": null,
"e": 4239,
"s": 4228,
"text": " Add Notes"
}
]
|
Check for star graph - GeeksforGeeks | 07 Nov, 2021
You are given an n * n matrix which represents a graph with n-vertices, check whether the input matrix represents a star graph or not.Example:
Input : Mat[][] = {{0, 1, 0},
{1, 0, 1},
{0, 1, 0}}
Output : Star graph
Input : Mat[][] = {{0, 1, 0},
{1, 1, 1},
{0, 1, 0}}
Output : Not a Star graph
Star graph: Star graph is a special type of graph in which n-1 vertices have degree 1 and a single vertex have degree n – 1. This looks like n – 1 vertex is connected to a single central vertex. A star graph with total n – vertex is termed as Sn.Here is an illustration for the star graph :
Approach: Just traverse whole matrix and record the number of vertices having degree 1 and degree n-1. If number of vertices having degree 1 is n-1 and number of vertex having degree n-1 is 1 then our graph should be a star graph other-wise it should be not. Note:
For S1, there must be only one vertex with no edges.
For S2, there must be two vertices each with degree one or can say, both are connected by a single edge.
For Sn (n>2) simply check the above-explained criteria.
C++
Java
Python3
C#
PHP
Javascript
// CPP to find whether given graph is star or not#include<bits/stdc++.h>using namespace std; // define the size of incidence matrix#define size 4 // function to find star graphbool checkStar(int mat[][size]){ // initialize number of vertex // with deg 1 and n-1 int vertexD1 = 0, vertexDn_1 = 0; // check for S1 if (size == 1) return (mat[0][0] == 0); // check for S2 if (size == 2) return (mat[0][0] == 0 && mat[0][1] == 1 && mat[1][0] == 1 && mat[1][1] == 0 ); // check for Sn (n>2) for (int i = 0; i < size; i++) { int degreeI = 0; for (int j = 0; j < size; j++) if (mat[i][j]) degreeI++; if (degreeI == 1) vertexD1++; else if (degreeI == size-1) vertexDn_1++; } return (vertexD1 == (size-1) && vertexDn_1 == 1);} // driver codeint main(){ int mat[size][size] = { {0, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 0}, {1, 0, 0, 0}}; checkStar(mat) ? cout << "Star Graph" : cout << "Not a Star Graph"; return 0;}
// Java program to find whether // given graph is star or notimport java.io.*; class GFG{ // define the size of // incidence matrix static int size = 4; // function to find // star graph static boolean checkStar(int mat[][]) { // initialize number of // vertex with deg 1 and n-1 int vertexD1 = 0, vertexDn_1 = 0; // check for S1 if (size == 1) return (mat[0][0] == 0); // check for S2 if (size == 2) return (mat[0][0] == 0 && mat[0][1] == 1 && mat[1][0] == 1 && mat[1][1] == 0); // check for Sn (n>2) for (int i = 0; i < size; i++) { int degreeI = 0; for (int j = 0; j < size; j++) if (mat[i][j] == 1) degreeI++; if (degreeI == 1) vertexD1++; else if (degreeI == size - 1) vertexDn_1++; } return (vertexD1 == (size - 1) && vertexDn_1 == 1); } // Driver code public static void main(String args[]) { int mat[][] = {{0, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 0}, {1, 0, 0, 0}}; if (checkStar(mat)) System.out.print("Star Graph"); else System.out.print("Not a Star Graph"); }} // This code is contributed by // Manish Shaw(manishshaw1)
# Python to find whether # given graph is star# or not # define the size # of incidence matrixsize = 4 # def to # find star graphdef checkStar(mat) : global size # initialize number of # vertex with deg 1 and n-1 vertexD1 = 0 vertexDn_1 = 0 # check for S1 if (size == 1) : return (mat[0][0] == 0) # check for S2 if (size == 2) : return (mat[0][0] == 0 and mat[0][1] == 1 and mat[1][0] == 1 and mat[1][1] == 0) # check for Sn (n>2) for i in range(0, size) : degreeI = 0 for j in range(0, size) : if (mat[i][j]) : degreeI = degreeI + 1 if (degreeI == 1) : vertexD1 = vertexD1 + 1 elif (degreeI == size - 1): vertexDn_1 = vertexDn_1 + 1 return (vertexD1 == (size - 1) and vertexDn_1 == 1) # Driver codemat = [[0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]] if(checkStar(mat)) : print ("Star Graph")else : print ("Not a Star Graph") # This code is contributed by # Manish Shaw(manishshaw1)
// C# to find whether given// graph is star or notusing System; class GFG{ // define the size of // incidence matrix static int size = 4; // function to find // star graph static bool checkStar(int [,]mat) { // initialize number of // vertex with deg 1 and n-1 int vertexD1 = 0, vertexDn_1 = 0; // check for S1 if (size == 1) return (mat[0, 0] == 0); // check for S2 if (size == 2) return (mat[0, 0] == 0 && mat[0, 1] == 1 && mat[1, 0] == 1 && mat[1, 1] == 0); // check for Sn (n>2) for (int i = 0; i < size; i++) { int degreeI = 0; for (int j = 0; j < size; j++) if (mat[i, j] == 1) degreeI++; if (degreeI == 1) vertexD1++; else if (degreeI == size - 1) vertexDn_1++; } return (vertexD1 == (size - 1) && vertexDn_1 == 1); } // Driver code static void Main() { int [,]mat = new int[4, 4]{{0, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 0}, {1, 0, 0, 0}}; if (checkStar(mat)) Console.Write("Star Graph"); else Console.Write("Not a Star Graph"); }}// This code is contributed by // Manish Shaw(manishshaw1)
<?php// PHP to find whether // given graph is star// or not // define the size // of incidence matrix$size = 4; // function to // find star graphfunction checkStar($mat){ global $size; // initialize number of // vertex with deg 1 and n-1 $vertexD1 = 0; $vertexDn_1 = 0; // check for S1 if ($size == 1) return ($mat[0][0] == 0); // check for S2 if ($size == 2) return ($mat[0][0] == 0 && $mat[0][1] == 1 && $mat[1][0] == 1 && $mat[1][1] == 0 ); // check for Sn (n>2) for ($i = 0; $i < $size; $i++) { $degreeI = 0; for ($j = 0; $j < $size; $j++) if ($mat[$i][$j]) $degreeI++; if ($degreeI == 1) $vertexD1++; else if ($degreeI == $size - 1) $vertexDn_1++; } return ($vertexD1 == ($size - 1) && $vertexDn_1 == 1);} // Driver code$mat = array(array(0, 1, 1, 1), array(1, 0, 0, 0), array(1, 0, 0, 0), array(1, 0, 0, 0)); if(checkStar($mat)) echo ("Star Graph");else echo ("Not a Star Graph"); // This code is contributed by // Manish Shaw(manishshaw1)?>
<script> // Javascript to find whether given // graph is star or not // define the size of incidence matrixvar size = 4; // function to find star graphfunction checkStar( mat){ // initialize number of vertex // with deg 1 and n-1 var vertexD1 = 0, vertexDn_1 = 0; // check for S1 if (size == 1) return (mat[0][0] == 0); // check for S2 if (size == 2) return (mat[0][0] == 0 && mat[0][1] == 1 && mat[1][0] == 1 && mat[1][1] == 0 ); // check for Sn (n>2) for (var i = 0; i < size; i++) { var degreeI = 0; for (var j = 0; j < size; j++) if (mat[i][j]) degreeI++; if (degreeI == 1) vertexD1++; else if (degreeI == size-1) vertexDn_1++; } return (vertexD1 == (size-1) && vertexDn_1 == 1);} // driver codevar mat = [ [0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]];checkStar(mat) ? document.write( "Star Graph") : document.write( "Not a Star Graph"); </script>
Output:
Star Graph
manishshaw1
rutvik_56
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Bellman–Ford Algorithm | DP-23
Detect Cycle in a Directed Graph
Floyd Warshall Algorithm | DP-16
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Traveling Salesman Problem (TSP) Implementation
Ford-Fulkerson Algorithm for Maximum Flow Problem
Strongly Connected Components | [
{
"code": null,
"e": 25203,
"s": 25175,
"text": "\n07 Nov, 2021"
},
{
"code": null,
"e": 25348,
"s": 25203,
"text": "You are given an n * n matrix which represents a graph with n-vertices, check whether the input matrix represents a star graph or not.Example: "
},
{
"code": null,
"e": 25575,
"s": 25348,
"text": "Input : Mat[][] = {{0, 1, 0},\n {1, 0, 1},\n {0, 1, 0}}\nOutput : Star graph\n\nInput : Mat[][] = {{0, 1, 0},\n {1, 1, 1},\n {0, 1, 0}}\nOutput : Not a Star graph"
},
{
"code": null,
"e": 25870,
"s": 25577,
"text": "Star graph: Star graph is a special type of graph in which n-1 vertices have degree 1 and a single vertex have degree n – 1. This looks like n – 1 vertex is connected to a single central vertex. A star graph with total n – vertex is termed as Sn.Here is an illustration for the star graph : "
},
{
"code": null,
"e": 26135,
"s": 25870,
"text": "Approach: Just traverse whole matrix and record the number of vertices having degree 1 and degree n-1. If number of vertices having degree 1 is n-1 and number of vertex having degree n-1 is 1 then our graph should be a star graph other-wise it should be not. Note:"
},
{
"code": null,
"e": 26188,
"s": 26135,
"text": "For S1, there must be only one vertex with no edges."
},
{
"code": null,
"e": 26293,
"s": 26188,
"text": "For S2, there must be two vertices each with degree one or can say, both are connected by a single edge."
},
{
"code": null,
"e": 26349,
"s": 26293,
"text": "For Sn (n>2) simply check the above-explained criteria."
},
{
"code": null,
"e": 26355,
"s": 26351,
"text": "C++"
},
{
"code": null,
"e": 26360,
"s": 26355,
"text": "Java"
},
{
"code": null,
"e": 26368,
"s": 26360,
"text": "Python3"
},
{
"code": null,
"e": 26371,
"s": 26368,
"text": "C#"
},
{
"code": null,
"e": 26375,
"s": 26371,
"text": "PHP"
},
{
"code": null,
"e": 26386,
"s": 26375,
"text": "Javascript"
},
{
"code": "// CPP to find whether given graph is star or not#include<bits/stdc++.h>using namespace std; // define the size of incidence matrix#define size 4 // function to find star graphbool checkStar(int mat[][size]){ // initialize number of vertex // with deg 1 and n-1 int vertexD1 = 0, vertexDn_1 = 0; // check for S1 if (size == 1) return (mat[0][0] == 0); // check for S2 if (size == 2) return (mat[0][0] == 0 && mat[0][1] == 1 && mat[1][0] == 1 && mat[1][1] == 0 ); // check for Sn (n>2) for (int i = 0; i < size; i++) { int degreeI = 0; for (int j = 0; j < size; j++) if (mat[i][j]) degreeI++; if (degreeI == 1) vertexD1++; else if (degreeI == size-1) vertexDn_1++; } return (vertexD1 == (size-1) && vertexDn_1 == 1);} // driver codeint main(){ int mat[size][size] = { {0, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 0}, {1, 0, 0, 0}}; checkStar(mat) ? cout << \"Star Graph\" : cout << \"Not a Star Graph\"; return 0;}",
"e": 27579,
"s": 26386,
"text": null
},
{
"code": "// Java program to find whether // given graph is star or notimport java.io.*; class GFG{ // define the size of // incidence matrix static int size = 4; // function to find // star graph static boolean checkStar(int mat[][]) { // initialize number of // vertex with deg 1 and n-1 int vertexD1 = 0, vertexDn_1 = 0; // check for S1 if (size == 1) return (mat[0][0] == 0); // check for S2 if (size == 2) return (mat[0][0] == 0 && mat[0][1] == 1 && mat[1][0] == 1 && mat[1][1] == 0); // check for Sn (n>2) for (int i = 0; i < size; i++) { int degreeI = 0; for (int j = 0; j < size; j++) if (mat[i][j] == 1) degreeI++; if (degreeI == 1) vertexD1++; else if (degreeI == size - 1) vertexDn_1++; } return (vertexD1 == (size - 1) && vertexDn_1 == 1); } // Driver code public static void main(String args[]) { int mat[][] = {{0, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 0}, {1, 0, 0, 0}}; if (checkStar(mat)) System.out.print(\"Star Graph\"); else System.out.print(\"Not a Star Graph\"); }} // This code is contributed by // Manish Shaw(manishshaw1)",
"e": 29099,
"s": 27579,
"text": null
},
{
"code": "# Python to find whether # given graph is star# or not # define the size # of incidence matrixsize = 4 # def to # find star graphdef checkStar(mat) : global size # initialize number of # vertex with deg 1 and n-1 vertexD1 = 0 vertexDn_1 = 0 # check for S1 if (size == 1) : return (mat[0][0] == 0) # check for S2 if (size == 2) : return (mat[0][0] == 0 and mat[0][1] == 1 and mat[1][0] == 1 and mat[1][1] == 0) # check for Sn (n>2) for i in range(0, size) : degreeI = 0 for j in range(0, size) : if (mat[i][j]) : degreeI = degreeI + 1 if (degreeI == 1) : vertexD1 = vertexD1 + 1 elif (degreeI == size - 1): vertexDn_1 = vertexDn_1 + 1 return (vertexD1 == (size - 1) and vertexDn_1 == 1) # Driver codemat = [[0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]] if(checkStar(mat)) : print (\"Star Graph\")else : print (\"Not a Star Graph\") # This code is contributed by # Manish Shaw(manishshaw1)",
"e": 30244,
"s": 29099,
"text": null
},
{
"code": "// C# to find whether given// graph is star or notusing System; class GFG{ // define the size of // incidence matrix static int size = 4; // function to find // star graph static bool checkStar(int [,]mat) { // initialize number of // vertex with deg 1 and n-1 int vertexD1 = 0, vertexDn_1 = 0; // check for S1 if (size == 1) return (mat[0, 0] == 0); // check for S2 if (size == 2) return (mat[0, 0] == 0 && mat[0, 1] == 1 && mat[1, 0] == 1 && mat[1, 1] == 0); // check for Sn (n>2) for (int i = 0; i < size; i++) { int degreeI = 0; for (int j = 0; j < size; j++) if (mat[i, j] == 1) degreeI++; if (degreeI == 1) vertexD1++; else if (degreeI == size - 1) vertexDn_1++; } return (vertexD1 == (size - 1) && vertexDn_1 == 1); } // Driver code static void Main() { int [,]mat = new int[4, 4]{{0, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 0}, {1, 0, 0, 0}}; if (checkStar(mat)) Console.Write(\"Star Graph\"); else Console.Write(\"Not a Star Graph\"); }}// This code is contributed by // Manish Shaw(manishshaw1)",
"e": 31753,
"s": 30244,
"text": null
},
{
"code": "<?php// PHP to find whether // given graph is star// or not // define the size // of incidence matrix$size = 4; // function to // find star graphfunction checkStar($mat){ global $size; // initialize number of // vertex with deg 1 and n-1 $vertexD1 = 0; $vertexDn_1 = 0; // check for S1 if ($size == 1) return ($mat[0][0] == 0); // check for S2 if ($size == 2) return ($mat[0][0] == 0 && $mat[0][1] == 1 && $mat[1][0] == 1 && $mat[1][1] == 0 ); // check for Sn (n>2) for ($i = 0; $i < $size; $i++) { $degreeI = 0; for ($j = 0; $j < $size; $j++) if ($mat[$i][$j]) $degreeI++; if ($degreeI == 1) $vertexD1++; else if ($degreeI == $size - 1) $vertexDn_1++; } return ($vertexD1 == ($size - 1) && $vertexDn_1 == 1);} // Driver code$mat = array(array(0, 1, 1, 1), array(1, 0, 0, 0), array(1, 0, 0, 0), array(1, 0, 0, 0)); if(checkStar($mat)) echo (\"Star Graph\");else echo (\"Not a Star Graph\"); // This code is contributed by // Manish Shaw(manishshaw1)?>",
"e": 32954,
"s": 31753,
"text": null
},
{
"code": "<script> // Javascript to find whether given // graph is star or not // define the size of incidence matrixvar size = 4; // function to find star graphfunction checkStar( mat){ // initialize number of vertex // with deg 1 and n-1 var vertexD1 = 0, vertexDn_1 = 0; // check for S1 if (size == 1) return (mat[0][0] == 0); // check for S2 if (size == 2) return (mat[0][0] == 0 && mat[0][1] == 1 && mat[1][0] == 1 && mat[1][1] == 0 ); // check for Sn (n>2) for (var i = 0; i < size; i++) { var degreeI = 0; for (var j = 0; j < size; j++) if (mat[i][j]) degreeI++; if (degreeI == 1) vertexD1++; else if (degreeI == size-1) vertexDn_1++; } return (vertexD1 == (size-1) && vertexDn_1 == 1);} // driver codevar mat = [ [0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]];checkStar(mat) ? document.write( \"Star Graph\") : document.write( \"Not a Star Graph\"); </script>",
"e": 34082,
"s": 32954,
"text": null
},
{
"code": null,
"e": 34091,
"s": 34082,
"text": "Output: "
},
{
"code": null,
"e": 34102,
"s": 34091,
"text": "Star Graph"
},
{
"code": null,
"e": 34116,
"s": 34104,
"text": "manishshaw1"
},
{
"code": null,
"e": 34126,
"s": 34116,
"text": "rutvik_56"
},
{
"code": null,
"e": 34132,
"s": 34126,
"text": "Graph"
},
{
"code": null,
"e": 34138,
"s": 34132,
"text": "Graph"
},
{
"code": null,
"e": 34236,
"s": 34138,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34245,
"s": 34236,
"text": "Comments"
},
{
"code": null,
"e": 34258,
"s": 34245,
"text": "Old Comments"
},
{
"code": null,
"e": 34316,
"s": 34258,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 34336,
"s": 34316,
"text": "Topological Sorting"
},
{
"code": null,
"e": 34367,
"s": 34336,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 34400,
"s": 34367,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 34433,
"s": 34400,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 34501,
"s": 34433,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 34576,
"s": 34501,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 34624,
"s": 34576,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 34674,
"s": 34624,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
}
]
|
Deepnote: a Collaborative Framework for Your Python Notebooks | by Angelica Lo Duca | Towards Data Science | In my wandering around the various data science tools and frameworks, I discovered Deepnote, an online framework that allows you to create and run notebooks in Python.
Compared to the more famous Jupyterlab and Colab frameworks, Deepnote allows you to write Python notebooks collaboratively and in real time. Your collaborator may even comment your code!
Deepnote can be easily integrated with the most popular cloud services, such as Google Drive and Amazon S3, as well as the most popular databases, such as PostgresSQL and MongoDB.
In addition, projects can be integrated with Github and published over the Web, since Deepnote provides each user with a dedicated Web page, which can be used as a portfolio. Finally, a great community has been built around Deepnote, with currently more of 2,000 members.
A free version of Deepnote is available at this link.
In this article I will give an overview of the Deepnote features and a practical use-case, which shows some potentialities of the framework.
When you land to the Deepnote homepage, you can register for a new account, either using your Github account or through your Google Account. Once registered, you can start a new project, simply by clicking the New Project button:
A new unique Virtual Machine is associated to your project, which is unique for all the collaborators. This means that if you invite someone to collaborate with you to your project, they will see the same environment as yours.
The main page for a project is a dashboard, where the main page is similar to other popular notebooks, in the sense that it provides the classical cell-environment, where you can write and run blocks of code or blocks of texts:
The novelty of Deepnote compared to other notebooks is the presence of some tools, which facilitate the initialization and integration of the project with other systems.
The provided tools include:
Notebooks & Files — the filesystem directory, which permits to navigate through the project files easily, as well as to create new files or upload them both from local filesystem and from URL.
Environment — the parameters associated to the project virtual machine. In this section, you can configure the hardware parameters, the Python version and the initialization scripts for the environment.
Integrations — the space where you can easily configure the integration of the project with external services, such as Google Drive, Snoflake, SQL server and so on.
Github — configure the link to the Github repository, in order to use its code and commit changes.
Terminals— the terminal of your virtual machine.
Comments — the list of comments to your project.
History — the log of project actions. This aspect is very useful when working with other people, because it allows you to see who did what.
Publish Editor — the editor, which permits both to select the layout of the project for publication and to publish the project on the Web. Currently, two layouts are supported: article and dashboard.
Now that we have seen a general overview of Deepnote, we just have to try it with a practical example! :)
Deepnote permits to embed block cells wherever you want, provided that the hosting Web site allows the embedding option. This can be achieved by selecting the Share block option, located at the right of each block cell.
A new window opens, like the following one:
You can turn on block sharing and then copy the embedding url. As a result, you will see your integrated block, as the following one:
You can even share the output of a block, thus, for example, you can plot results directly from Deepnote!
As use-case, I exploit Deepnote to build a Linear Regression model for the diamond.csv dataset, available on Kaggle. The original dataset is provided as a zipped file, thus, in order to show the potentialities of Deepnote, I do not decompress it in advance. Once trained the model, I calculate some metrics and I save them as a json in Google Drive. Finally, I publish the project in my Web profile.
Firstly, I upload the compressed dataset to Deepnote. In the Notebook & Files menu item, I create a new directory, called source, and within it, I upload the dataset.
Before creating a new notebook, I create a new file, called requirements.txt, which will contain all the Python libraries, required for my project, one per line. In my case, there is only one required library, named zipfile36, which will be used to extract the CSV from the zipped file. I have discovered this interesting Python library, thanks to an interesting article written by Swathi Arun and entitled 10 Fantastic Python Packages. You can find other interesting Python libraries in my Python Libraries List.
In order to install the required library, I move to the Environment menu item and I select Python 3.8 as my Python version. In addition, I click on the init.ipynb notebook and I run it. This notebook installs all the libraries contained in the requirements.txt file.
Now I’m ready to write my notebook for Regression Analysis.
In the main directory of my working space, I create a new notebook and I name it Linear Regression Example.
Firstly, I extract the dataset through the zipfile36 library and I store it in the source directory:
Note that I have used the embed option of Deepnote :)
I run this cell and the diamond.csv file is created in the source directory. Now I can load it as a Pandas dataframe. Pandas is already installed in Deepnote, thus I do not have to include it in my requirements.txt file.
The datafame preview is formatted very well. There is even the possibility to perform some preliminary data exploration, by clicking the Visualize button, located in the top right of the dataframe preview:
The click on the Visualize button opens a little dashboard within the notebook, which permits to select two columns and show them in a graph (bar chart, line chart, area chart, point chart). The following figure shows an example of graph:
Now I can write the classical code to build a Linear Regression model. I exploit the scikit-learn library, which is already available in Deepnote.
The goal of this section is not to write the best model ever, but to illustrate the potentialities of Deepnote. For more information on how to build a complete model in scikit-learn, you can read my previous article entitled A complete Data Analysis workflow in Python and scikit-learn.
Firstly, I split the dataset in training and test sets:
Then, I build and train a Linear Regression model:
Finally, I evaluate it, by calculating some metrics:
I store the metrics in a dictionary, named metrics.
Finally, I save the results in Google Drive. In order to do it, firstly, I must connect the project to my Google Drive folder. I select the Integrations menu item and then Google Drive.
I click on the Add button and then Authorize Google Drive. I also select an integration name. In my case, I write output as integration name.
The classical Google Drive Authorization tab opens, I select my Google Account and then I proceed.
Finally, I click on the Create button. Google Drive is now connected to my project!
The Google Drive filesystem has been mounted in the /datasets/output directory, which can be used directly in my notebook.
I come back to my notebook and I save the metrics variable as a json file in Google Drive. I exploit the json library to perform such an operation. Note that the json library is already installed in Deepnote, thus there is no need to include it in the requirements.txt.
The file is saved in Google Drive. Looking at the Google Drive folder, where is my file placed? Indeed, since I do not have specified any specific directory, it is located in my Google Drive root directory.
Eventually I can publish my project in my public profile. The first time I try to publish a project, I must setup my public profile, by setting my username. Then I can select between two layouts: article or dashboard:
I click on the Publish button and my project is available under my profile. The full use-case illustrated in this article can be accessed in my public Deepnote profile.
I can even run the full notebook directly in Deepnote by clicking on the following button:
If I include some image in a markdown cell, Deepnote detects it and makes a thumbnail out of it on my public profile.
In this article I have described Deepnote, a Collaborative Framework for Python notebooks. In addition to the classical features, also provided by the classical notebook frameworks, such as Google Colab and Jupyterlab, Deepnote provides:
a real time collaborative environment, which permits you to work with your collaborators in a single runtime instance
an easy way to integrate external services, such as Google Drive
the possibility to setup your environment, with required libraries and hardware capabilities.
If you have read this far, for me it is already a lot for today. Thanks! You can read more about me in this article.
You could subscribe for few dollars per month and unlock unlimited articles — click here.
towardsdatascience.com
towardsdatascience.com
pub.towardsai.net
Deepnote permits to link a project either to a public or private Github repository. If you want to include a public repository, without pushing to it, you can create a new terminal and simply clone the repository in your current directory:
git clone <url>
In your Github profile, you can create a new private repository, called deepnote_test and you can copy its url:
https://github.com/<my_user_name>/deepnote_test.git
If you want to push to a Github repository, you have to link it. Thus you can open the Github menu item and type the repository url. Then, you can click on the Link to Github repository button. The first time you run this command, Deepnote proposes you to install the Github App.
While installing the Github App, you can select whether to give Deepnote the access to all your Github repositories or only to one.
After this installation, you can click again on the Link to Github repository button. This opens the Authorization tab. You can click on Authorize.
When this process is completed, Deeponote shows that the repository has been linked.
Then, you can open a new terminal and move to the Github repository directory:
cd deepnote_test
From this directory, you can run the classical git commands, including push, pull and commit.
Disclaimer: This is not a sponsored article. I don’t have any affiliation with Deepnote or its authors. The article shows an unbiased overview of the framework, aiming at making data science tools accessible to the broader people. | [
{
"code": null,
"e": 340,
"s": 172,
"text": "In my wandering around the various data science tools and frameworks, I discovered Deepnote, an online framework that allows you to create and run notebooks in Python."
},
{
"code": null,
"e": 527,
"s": 340,
"text": "Compared to the more famous Jupyterlab and Colab frameworks, Deepnote allows you to write Python notebooks collaboratively and in real time. Your collaborator may even comment your code!"
},
{
"code": null,
"e": 707,
"s": 527,
"text": "Deepnote can be easily integrated with the most popular cloud services, such as Google Drive and Amazon S3, as well as the most popular databases, such as PostgresSQL and MongoDB."
},
{
"code": null,
"e": 979,
"s": 707,
"text": "In addition, projects can be integrated with Github and published over the Web, since Deepnote provides each user with a dedicated Web page, which can be used as a portfolio. Finally, a great community has been built around Deepnote, with currently more of 2,000 members."
},
{
"code": null,
"e": 1033,
"s": 979,
"text": "A free version of Deepnote is available at this link."
},
{
"code": null,
"e": 1174,
"s": 1033,
"text": "In this article I will give an overview of the Deepnote features and a practical use-case, which shows some potentialities of the framework."
},
{
"code": null,
"e": 1404,
"s": 1174,
"text": "When you land to the Deepnote homepage, you can register for a new account, either using your Github account or through your Google Account. Once registered, you can start a new project, simply by clicking the New Project button:"
},
{
"code": null,
"e": 1631,
"s": 1404,
"text": "A new unique Virtual Machine is associated to your project, which is unique for all the collaborators. This means that if you invite someone to collaborate with you to your project, they will see the same environment as yours."
},
{
"code": null,
"e": 1859,
"s": 1631,
"text": "The main page for a project is a dashboard, where the main page is similar to other popular notebooks, in the sense that it provides the classical cell-environment, where you can write and run blocks of code or blocks of texts:"
},
{
"code": null,
"e": 2029,
"s": 1859,
"text": "The novelty of Deepnote compared to other notebooks is the presence of some tools, which facilitate the initialization and integration of the project with other systems."
},
{
"code": null,
"e": 2057,
"s": 2029,
"text": "The provided tools include:"
},
{
"code": null,
"e": 2250,
"s": 2057,
"text": "Notebooks & Files — the filesystem directory, which permits to navigate through the project files easily, as well as to create new files or upload them both from local filesystem and from URL."
},
{
"code": null,
"e": 2453,
"s": 2250,
"text": "Environment — the parameters associated to the project virtual machine. In this section, you can configure the hardware parameters, the Python version and the initialization scripts for the environment."
},
{
"code": null,
"e": 2618,
"s": 2453,
"text": "Integrations — the space where you can easily configure the integration of the project with external services, such as Google Drive, Snoflake, SQL server and so on."
},
{
"code": null,
"e": 2717,
"s": 2618,
"text": "Github — configure the link to the Github repository, in order to use its code and commit changes."
},
{
"code": null,
"e": 2766,
"s": 2717,
"text": "Terminals— the terminal of your virtual machine."
},
{
"code": null,
"e": 2815,
"s": 2766,
"text": "Comments — the list of comments to your project."
},
{
"code": null,
"e": 2955,
"s": 2815,
"text": "History — the log of project actions. This aspect is very useful when working with other people, because it allows you to see who did what."
},
{
"code": null,
"e": 3155,
"s": 2955,
"text": "Publish Editor — the editor, which permits both to select the layout of the project for publication and to publish the project on the Web. Currently, two layouts are supported: article and dashboard."
},
{
"code": null,
"e": 3261,
"s": 3155,
"text": "Now that we have seen a general overview of Deepnote, we just have to try it with a practical example! :)"
},
{
"code": null,
"e": 3481,
"s": 3261,
"text": "Deepnote permits to embed block cells wherever you want, provided that the hosting Web site allows the embedding option. This can be achieved by selecting the Share block option, located at the right of each block cell."
},
{
"code": null,
"e": 3525,
"s": 3481,
"text": "A new window opens, like the following one:"
},
{
"code": null,
"e": 3659,
"s": 3525,
"text": "You can turn on block sharing and then copy the embedding url. As a result, you will see your integrated block, as the following one:"
},
{
"code": null,
"e": 3765,
"s": 3659,
"text": "You can even share the output of a block, thus, for example, you can plot results directly from Deepnote!"
},
{
"code": null,
"e": 4165,
"s": 3765,
"text": "As use-case, I exploit Deepnote to build a Linear Regression model for the diamond.csv dataset, available on Kaggle. The original dataset is provided as a zipped file, thus, in order to show the potentialities of Deepnote, I do not decompress it in advance. Once trained the model, I calculate some metrics and I save them as a json in Google Drive. Finally, I publish the project in my Web profile."
},
{
"code": null,
"e": 4332,
"s": 4165,
"text": "Firstly, I upload the compressed dataset to Deepnote. In the Notebook & Files menu item, I create a new directory, called source, and within it, I upload the dataset."
},
{
"code": null,
"e": 4846,
"s": 4332,
"text": "Before creating a new notebook, I create a new file, called requirements.txt, which will contain all the Python libraries, required for my project, one per line. In my case, there is only one required library, named zipfile36, which will be used to extract the CSV from the zipped file. I have discovered this interesting Python library, thanks to an interesting article written by Swathi Arun and entitled 10 Fantastic Python Packages. You can find other interesting Python libraries in my Python Libraries List."
},
{
"code": null,
"e": 5113,
"s": 4846,
"text": "In order to install the required library, I move to the Environment menu item and I select Python 3.8 as my Python version. In addition, I click on the init.ipynb notebook and I run it. This notebook installs all the libraries contained in the requirements.txt file."
},
{
"code": null,
"e": 5173,
"s": 5113,
"text": "Now I’m ready to write my notebook for Regression Analysis."
},
{
"code": null,
"e": 5281,
"s": 5173,
"text": "In the main directory of my working space, I create a new notebook and I name it Linear Regression Example."
},
{
"code": null,
"e": 5382,
"s": 5281,
"text": "Firstly, I extract the dataset through the zipfile36 library and I store it in the source directory:"
},
{
"code": null,
"e": 5436,
"s": 5382,
"text": "Note that I have used the embed option of Deepnote :)"
},
{
"code": null,
"e": 5657,
"s": 5436,
"text": "I run this cell and the diamond.csv file is created in the source directory. Now I can load it as a Pandas dataframe. Pandas is already installed in Deepnote, thus I do not have to include it in my requirements.txt file."
},
{
"code": null,
"e": 5863,
"s": 5657,
"text": "The datafame preview is formatted very well. There is even the possibility to perform some preliminary data exploration, by clicking the Visualize button, located in the top right of the dataframe preview:"
},
{
"code": null,
"e": 6102,
"s": 5863,
"text": "The click on the Visualize button opens a little dashboard within the notebook, which permits to select two columns and show them in a graph (bar chart, line chart, area chart, point chart). The following figure shows an example of graph:"
},
{
"code": null,
"e": 6249,
"s": 6102,
"text": "Now I can write the classical code to build a Linear Regression model. I exploit the scikit-learn library, which is already available in Deepnote."
},
{
"code": null,
"e": 6536,
"s": 6249,
"text": "The goal of this section is not to write the best model ever, but to illustrate the potentialities of Deepnote. For more information on how to build a complete model in scikit-learn, you can read my previous article entitled A complete Data Analysis workflow in Python and scikit-learn."
},
{
"code": null,
"e": 6592,
"s": 6536,
"text": "Firstly, I split the dataset in training and test sets:"
},
{
"code": null,
"e": 6643,
"s": 6592,
"text": "Then, I build and train a Linear Regression model:"
},
{
"code": null,
"e": 6696,
"s": 6643,
"text": "Finally, I evaluate it, by calculating some metrics:"
},
{
"code": null,
"e": 6748,
"s": 6696,
"text": "I store the metrics in a dictionary, named metrics."
},
{
"code": null,
"e": 6934,
"s": 6748,
"text": "Finally, I save the results in Google Drive. In order to do it, firstly, I must connect the project to my Google Drive folder. I select the Integrations menu item and then Google Drive."
},
{
"code": null,
"e": 7076,
"s": 6934,
"text": "I click on the Add button and then Authorize Google Drive. I also select an integration name. In my case, I write output as integration name."
},
{
"code": null,
"e": 7175,
"s": 7076,
"text": "The classical Google Drive Authorization tab opens, I select my Google Account and then I proceed."
},
{
"code": null,
"e": 7259,
"s": 7175,
"text": "Finally, I click on the Create button. Google Drive is now connected to my project!"
},
{
"code": null,
"e": 7382,
"s": 7259,
"text": "The Google Drive filesystem has been mounted in the /datasets/output directory, which can be used directly in my notebook."
},
{
"code": null,
"e": 7652,
"s": 7382,
"text": "I come back to my notebook and I save the metrics variable as a json file in Google Drive. I exploit the json library to perform such an operation. Note that the json library is already installed in Deepnote, thus there is no need to include it in the requirements.txt."
},
{
"code": null,
"e": 7859,
"s": 7652,
"text": "The file is saved in Google Drive. Looking at the Google Drive folder, where is my file placed? Indeed, since I do not have specified any specific directory, it is located in my Google Drive root directory."
},
{
"code": null,
"e": 8077,
"s": 7859,
"text": "Eventually I can publish my project in my public profile. The first time I try to publish a project, I must setup my public profile, by setting my username. Then I can select between two layouts: article or dashboard:"
},
{
"code": null,
"e": 8246,
"s": 8077,
"text": "I click on the Publish button and my project is available under my profile. The full use-case illustrated in this article can be accessed in my public Deepnote profile."
},
{
"code": null,
"e": 8337,
"s": 8246,
"text": "I can even run the full notebook directly in Deepnote by clicking on the following button:"
},
{
"code": null,
"e": 8455,
"s": 8337,
"text": "If I include some image in a markdown cell, Deepnote detects it and makes a thumbnail out of it on my public profile."
},
{
"code": null,
"e": 8693,
"s": 8455,
"text": "In this article I have described Deepnote, a Collaborative Framework for Python notebooks. In addition to the classical features, also provided by the classical notebook frameworks, such as Google Colab and Jupyterlab, Deepnote provides:"
},
{
"code": null,
"e": 8811,
"s": 8693,
"text": "a real time collaborative environment, which permits you to work with your collaborators in a single runtime instance"
},
{
"code": null,
"e": 8876,
"s": 8811,
"text": "an easy way to integrate external services, such as Google Drive"
},
{
"code": null,
"e": 8970,
"s": 8876,
"text": "the possibility to setup your environment, with required libraries and hardware capabilities."
},
{
"code": null,
"e": 9087,
"s": 8970,
"text": "If you have read this far, for me it is already a lot for today. Thanks! You can read more about me in this article."
},
{
"code": null,
"e": 9177,
"s": 9087,
"text": "You could subscribe for few dollars per month and unlock unlimited articles — click here."
},
{
"code": null,
"e": 9200,
"s": 9177,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9223,
"s": 9200,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9241,
"s": 9223,
"text": "pub.towardsai.net"
},
{
"code": null,
"e": 9481,
"s": 9241,
"text": "Deepnote permits to link a project either to a public or private Github repository. If you want to include a public repository, without pushing to it, you can create a new terminal and simply clone the repository in your current directory:"
},
{
"code": null,
"e": 9497,
"s": 9481,
"text": "git clone <url>"
},
{
"code": null,
"e": 9609,
"s": 9497,
"text": "In your Github profile, you can create a new private repository, called deepnote_test and you can copy its url:"
},
{
"code": null,
"e": 9661,
"s": 9609,
"text": "https://github.com/<my_user_name>/deepnote_test.git"
},
{
"code": null,
"e": 9941,
"s": 9661,
"text": "If you want to push to a Github repository, you have to link it. Thus you can open the Github menu item and type the repository url. Then, you can click on the Link to Github repository button. The first time you run this command, Deepnote proposes you to install the Github App."
},
{
"code": null,
"e": 10073,
"s": 9941,
"text": "While installing the Github App, you can select whether to give Deepnote the access to all your Github repositories or only to one."
},
{
"code": null,
"e": 10221,
"s": 10073,
"text": "After this installation, you can click again on the Link to Github repository button. This opens the Authorization tab. You can click on Authorize."
},
{
"code": null,
"e": 10306,
"s": 10221,
"text": "When this process is completed, Deeponote shows that the repository has been linked."
},
{
"code": null,
"e": 10385,
"s": 10306,
"text": "Then, you can open a new terminal and move to the Github repository directory:"
},
{
"code": null,
"e": 10402,
"s": 10385,
"text": "cd deepnote_test"
},
{
"code": null,
"e": 10496,
"s": 10402,
"text": "From this directory, you can run the classical git commands, including push, pull and commit."
}
]
|
java.util.concurrent Package - GeeksforGeeks | 03 May, 2022
Java Concurrency package covers concurrency, multithreading, and parallelism on the Java platform. Concurrency is the ability to run several or multi programs or applications in parallel. The backbone of Java concurrency is threads (a lightweight process, which has its own files and stacks and can access the shared data from other threads in the same process). The throughput and the interactivity of the program can be improved by performing time-consuming tasks asynchronously or in parallel. Java 5 added a new package to the java platform ⇾ java.util.concurrent package. This package has a set of classes and interfaces that helps in developing concurrent applications (multithreading) in java. Before this package, one needs to make the utility classes of their need on their own.
ExecutorExecutorServiceScheduledExecutorServiceFutureCountDownLatchCyclicBarrierSemaphoreThreadFactoryBlockingQueueDelayQueueLockPhaser
Executor
ExecutorService
ScheduledExecutorService
Future
CountDownLatch
CyclicBarrier
Semaphore
ThreadFactory
BlockingQueue
DelayQueue
Lock
Phaser
Now let us discuss some of the most useful utilities from this package that are as follows:
Executor is a set of interfaces that represents an object whose implementation executes tasks. It depends on the implementation whether the task should be run on a new thread or on a current thread. Hence, we can decouple the task execution flow from the actual task execution mechanism, using this interface. The executor does not require the task execution to be asynchronous. The simplest of all is the executable interface.
public interface Executor {
void execute( Runnable command );
}
In order to create an executer instance, we need to create an invoker.
public class Invoker implements Executor {
@Override
public void execute(Runnable r) {
r.run();
}
}
Now, for the execution of the task, we can use this invoker.
public void execute() {
Executor exe = new Invoker();
exe.execute( () -> {
// task to be performed
});
}
If the executor can’t accept the task to be executed, it will throw RejectedExecutionException.
ExecutorService is an interface and only forces the underlying implementation to implement execute() method. It extends the Executor interface and adds a series of methods that execute threads that return a value. The methods to shut the thread pool as well as the ability to implement for the result of the execution of the task.
We need to create Runnable target to use the ExecutorService.
public class Task implements Runnable {
@Override
public void run() {
// task details
}
}
Now, we can create an object/instance of this class and assign the task. We need to specify the thread-pool size while creating an instance.
// 20 is the thread pool size
ExecutorService exec = Executors.newFixedThreadPool(20);
For the creation of a single-threaded ExecutorService instance, we can use newSingleThreadExecuter(ThreadFactory threadfactory) for creating the instance. After the executor is created, we can submit the task.
public void execute() {
executor.submit(new Task());
}
Also, we can create a Runnable instance for the submission of tasks.
executor.submit(() -> {
new Task();
});
Two out-of-the-box termination methods are listed as follows:
shutdown(): It waits till all the submitted tasks execution gets finished.shutdownNow(): It immediately terminates all the executing/pending tasks.
shutdown(): It waits till all the submitted tasks execution gets finished.
shutdownNow(): It immediately terminates all the executing/pending tasks.
There is one more method that is awaitTermination() which forcefully blocks until all tasks have completed execution after a shutdown event-triggered or execution-timeout occurred, or the execution thread itself is interrupted.
try {
exec.awaitTermination( 50l, TimeUnit.NANOSECONDS );
} catch (InterruptedException e) {
e.printStackTrace();
}
It is similar to ExecutorService. The difference is that this interface can perform tasks periodically. Both Runnable and Callable function is used to define the task.
public void execute() {
ScheduledExecutorService execServ
= Executors.newSingleThreadScheduledExecutor();
Future<String> future = executorService.schedule(() -> {
// ..
return "Hello world";
}, 1, TimeUnit.SECONDS);
ScheduledFuture<?> scheduledFuture = execServ.schedule(() -> {
// ..
}, 1, TimeUnit.SECONDS);
executorService.shutdown();
}
ScheduledExecutorService can also define a task after some fixed delay.
executorService.scheduleAtFixedRate(() -> {
// ..
}, 1, 20, TimeUnit.SECONDS);
executorService.scheduleWithFixedDelay(() -> {
// ..
}, 1, 20, TimeUnit.SECONDS);
Here,
scheduleAtFixedRate( Runnable command, long initialDelay, long period, TimeUnit unit): This method creates and executes a periodic action that is first invoked after the initial delay and subsequently with the given period until the service instance shutdowns.
scheduleWithFixedDelay( Runnable command, long initialDelay, long delay, TimeUnit unit): This method creates and executes a periodic action that is invoked firstly after the provided initial delay and repeatedly with the given delay between the termination of the executing one and the invocation f the next one.
It represents the result of an asynchronous operation. The methods in it check if the asynchronous operation is completed or not, get the completed result, etc. The cancel(boolean isInterruptRunning) API cancels the operation and releases the executing thread. On the value of isInterruptRunning value being true, the thread executing the task will be terminated instantly. Otherwise, all the in-progress tasks get completed.
Code snippet creates an instance of Future.
public void invoke() {
ExecutorService executorService = Executors.newFixedThreadPool(20);
Future<String> future = executorService.submit(() -> {
// ...
Thread.sleep(10000l);
return "Hello";
});
}
The code to check if the result of the future is ready or not and fetches the data when the computation is done.
if (future.isDone() && !future.isCancelled()) {
try {
str = future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
Timeout specification for a given operation. If the time taken is more than this time, then TimeoutException is thrown.
try {
future.get(20, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
}
It is a utility class that blocks a set of threads until some operations get completed. A CountDownLatch is initialized with a counter(which is of Integer type). This counter decrements as the execution of the dependent threads get completed. But once the counter decrements to zero, other threads get released.
CyclicBarrier is almost the same as CountDownLatch except that we can reuse it. It allows multiple threads to wait for each other using await() before invoking the final task and this feature is not in CountDownLatch.
We are required to create an instance of Runnable Task to initiate the barrier condition.
public class Task implements Runnable {
private CyclicBarrier barrier;
public Task(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
try {
LOG.info(Thread.currentThread().getName() +
" is waiting");
barrier.await();
LOG.info(Thread.currentThread().getName() +
" is released");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
Now, invoking a few threads to race the barrier condition:
public void start() {
CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {
// ..
LOG.info("All previous tasks completed");
});
Thread t11 = new Thread(new Task(cyclicBarrier), "T11");
Thread t12 = new Thread(new Task(cyclicBarrier), "T12");
Thread t13 = new Thread(new Task(cyclicBarrier), "T13");
if (!cyclicBarrier.isBroken()) {
t11.start();
t12.start();
t13.start();
}
}
In the above code, the isBroken() method checks if any of the threads got interrupted during the execution time.
It is used for blocking thread-level access to some part of the logical or physical resource. Semaphore contains a set of permits. Wherever the thread tries to enter the code part of a critical section, semaphore gives the permission whether the permit is available or not, which means the critical section is available or not. If the permit is not available, then the thread cannot enter the critical section.
It is basically a variable named counter which maintains the count of entering and leaving threads from the critical section. When the executing thread releases the critical section, the counter increases.
Below code is used for the implementation of Semaphore:
static Semaphore semaphore = new Semaphore(20);
public void execute() throws InterruptedException {
LOG.info("Available : " + semaphore.availablePermits());
LOG.info("No. of threads waiting to acquire: " +
semaphore.getQueueLength());
if (semaphore.tryAcquire()) {
try {
//
}
finally {
semaphore.release();
}
}
}
Semaphores can be used to implement a Mutex-like data structure.
It acts as a thread pool which creates a new thread on demand. ThreadFactory can be defined as:
public class GFGThreadFactory implements ThreadFactory {
private int threadId;
private String name;
public GFGThreadFactory(String name) {
threadId = 1;
this.name = name;
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, name + "-Thread_" + threadId);
LOG.info("created new thread with id : " + threadId +
" and name : " + t.getName());
threadId++;
return t;
}
}
BlockingQueue interface supports flow control (in addition to queue) by introducing blocking if either BlockingQueue is full or empty. A thread trying to enqueue an element in a full queue is blocked until some other thread makes space in the queue, either by dequeuing one or more elements or clearing the queue completely. Similarly, it blocks a thread trying to delete from an empty queue until some other threads insert an item. BlockingQueue does not accept a null value. If we try to enqueue the null item, then it throws NullPointerException.
DelayQueue is a specialized Priority Queue that orders elements based on their delay time. It means that only those elements can be taken from the queue whose time has expired. DelayQueue head contains the element that has expired in the least time. If no delay has expired, then there is no head and poll will return null. DelayQueue accepts only those elements that belong to a class of type Delayed. DelayQueue implements the getDelay() method to return the remaining delay time.
It is a utility for blocking other threads from accessing a certain segment of code. The difference between Lock and a Synchronized block is that we have Lock APIs lock() and unlock() operation in separate methods whereas a Synchronized block is fully contained in methods.
It is more flexible than CountDownLatch and CyclicBarrier. Phaser is used to act as a reusable barrier on which the dynamic number of threads needs to wait before the execution continues. Multiple phases of execution can be coordinated by reusing the instance of a Phaser for each program phase.
anikaseth98
solankimayank
Java-concurrent-package
Java-Packages
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java? | [
{
"code": null,
"e": 25373,
"s": 25345,
"text": "\n03 May, 2022"
},
{
"code": null,
"e": 26162,
"s": 25373,
"text": "Java Concurrency package covers concurrency, multithreading, and parallelism on the Java platform. Concurrency is the ability to run several or multi programs or applications in parallel. The backbone of Java concurrency is threads (a lightweight process, which has its own files and stacks and can access the shared data from other threads in the same process). The throughput and the interactivity of the program can be improved by performing time-consuming tasks asynchronously or in parallel. Java 5 added a new package to the java platform ⇾ java.util.concurrent package. This package has a set of classes and interfaces that helps in developing concurrent applications (multithreading) in java. Before this package, one needs to make the utility classes of their need on their own. "
},
{
"code": null,
"e": 26303,
"s": 26162,
"text": "ExecutorExecutorServiceScheduledExecutorServiceFutureCountDownLatchCyclicBarrierSemaphoreThreadFactoryBlockingQueueDelayQueueLockPhaser "
},
{
"code": null,
"e": 26312,
"s": 26303,
"text": "Executor"
},
{
"code": null,
"e": 26328,
"s": 26312,
"text": "ExecutorService"
},
{
"code": null,
"e": 26353,
"s": 26328,
"text": "ScheduledExecutorService"
},
{
"code": null,
"e": 26360,
"s": 26353,
"text": "Future"
},
{
"code": null,
"e": 26375,
"s": 26360,
"text": "CountDownLatch"
},
{
"code": null,
"e": 26389,
"s": 26375,
"text": "CyclicBarrier"
},
{
"code": null,
"e": 26399,
"s": 26389,
"text": "Semaphore"
},
{
"code": null,
"e": 26413,
"s": 26399,
"text": "ThreadFactory"
},
{
"code": null,
"e": 26427,
"s": 26413,
"text": "BlockingQueue"
},
{
"code": null,
"e": 26438,
"s": 26427,
"text": "DelayQueue"
},
{
"code": null,
"e": 26443,
"s": 26438,
"text": "Lock"
},
{
"code": null,
"e": 26455,
"s": 26443,
"text": "Phaser "
},
{
"code": null,
"e": 26548,
"s": 26455,
"text": "Now let us discuss some of the most useful utilities from this package that are as follows: "
},
{
"code": null,
"e": 26976,
"s": 26548,
"text": "Executor is a set of interfaces that represents an object whose implementation executes tasks. It depends on the implementation whether the task should be run on a new thread or on a current thread. Hence, we can decouple the task execution flow from the actual task execution mechanism, using this interface. The executor does not require the task execution to be asynchronous. The simplest of all is the executable interface."
},
{
"code": null,
"e": 27044,
"s": 26976,
"text": "public interface Executor {\n void execute( Runnable command );\n}"
},
{
"code": null,
"e": 27115,
"s": 27044,
"text": "In order to create an executer instance, we need to create an invoker."
},
{
"code": null,
"e": 27231,
"s": 27115,
"text": "public class Invoker implements Executor {\n @Override\n public void execute(Runnable r) {\n r.run();\n }\n}"
},
{
"code": null,
"e": 27292,
"s": 27231,
"text": "Now, for the execution of the task, we can use this invoker."
},
{
"code": null,
"e": 27413,
"s": 27292,
"text": "public void execute() {\n Executor exe = new Invoker();\n exe.execute( () -> {\n // task to be performed\n });\n}"
},
{
"code": null,
"e": 27509,
"s": 27413,
"text": "If the executor can’t accept the task to be executed, it will throw RejectedExecutionException."
},
{
"code": null,
"e": 27840,
"s": 27509,
"text": "ExecutorService is an interface and only forces the underlying implementation to implement execute() method. It extends the Executor interface and adds a series of methods that execute threads that return a value. The methods to shut the thread pool as well as the ability to implement for the result of the execution of the task."
},
{
"code": null,
"e": 27902,
"s": 27840,
"text": "We need to create Runnable target to use the ExecutorService."
},
{
"code": null,
"e": 28009,
"s": 27902,
"text": "public class Task implements Runnable {\n @Override\n public void run() {\n\n // task details\n }\n}"
},
{
"code": null,
"e": 28150,
"s": 28009,
"text": "Now, we can create an object/instance of this class and assign the task. We need to specify the thread-pool size while creating an instance."
},
{
"code": null,
"e": 28237,
"s": 28150,
"text": "// 20 is the thread pool size\nExecutorService exec = Executors.newFixedThreadPool(20);"
},
{
"code": null,
"e": 28447,
"s": 28237,
"text": "For the creation of a single-threaded ExecutorService instance, we can use newSingleThreadExecuter(ThreadFactory threadfactory) for creating the instance. After the executor is created, we can submit the task."
},
{
"code": null,
"e": 28505,
"s": 28447,
"text": "public void execute() {\n executor.submit(new Task());\n}"
},
{
"code": null,
"e": 28574,
"s": 28505,
"text": "Also, we can create a Runnable instance for the submission of tasks."
},
{
"code": null,
"e": 28617,
"s": 28574,
"text": "executor.submit(() -> {\n new Task();\n});"
},
{
"code": null,
"e": 28679,
"s": 28617,
"text": "Two out-of-the-box termination methods are listed as follows:"
},
{
"code": null,
"e": 28827,
"s": 28679,
"text": "shutdown(): It waits till all the submitted tasks execution gets finished.shutdownNow(): It immediately terminates all the executing/pending tasks."
},
{
"code": null,
"e": 28902,
"s": 28827,
"text": "shutdown(): It waits till all the submitted tasks execution gets finished."
},
{
"code": null,
"e": 28976,
"s": 28902,
"text": "shutdownNow(): It immediately terminates all the executing/pending tasks."
},
{
"code": null,
"e": 29204,
"s": 28976,
"text": "There is one more method that is awaitTermination() which forcefully blocks until all tasks have completed execution after a shutdown event-triggered or execution-timeout occurred, or the execution thread itself is interrupted."
},
{
"code": null,
"e": 29326,
"s": 29204,
"text": "try {\n exec.awaitTermination( 50l, TimeUnit.NANOSECONDS );\n} catch (InterruptedException e) {\n e.printStackTrace();\n}"
},
{
"code": null,
"e": 29494,
"s": 29326,
"text": "It is similar to ExecutorService. The difference is that this interface can perform tasks periodically. Both Runnable and Callable function is used to define the task."
},
{
"code": null,
"e": 29881,
"s": 29494,
"text": "public void execute() {\n ScheduledExecutorService execServ\n = Executors.newSingleThreadScheduledExecutor();\n\n Future<String> future = executorService.schedule(() -> {\n // ..\n return \"Hello world\";\n }, 1, TimeUnit.SECONDS);\n\n ScheduledFuture<?> scheduledFuture = execServ.schedule(() -> {\n // ..\n }, 1, TimeUnit.SECONDS);\n\n executorService.shutdown();\n}"
},
{
"code": null,
"e": 29953,
"s": 29881,
"text": "ScheduledExecutorService can also define a task after some fixed delay."
},
{
"code": null,
"e": 30121,
"s": 29953,
"text": "executorService.scheduleAtFixedRate(() -> {\n // ..\n}, 1, 20, TimeUnit.SECONDS);\n\nexecutorService.scheduleWithFixedDelay(() -> {\n // ..\n}, 1, 20, TimeUnit.SECONDS);"
},
{
"code": null,
"e": 30127,
"s": 30121,
"text": "Here,"
},
{
"code": null,
"e": 30388,
"s": 30127,
"text": "scheduleAtFixedRate( Runnable command, long initialDelay, long period, TimeUnit unit): This method creates and executes a periodic action that is first invoked after the initial delay and subsequently with the given period until the service instance shutdowns."
},
{
"code": null,
"e": 30701,
"s": 30388,
"text": "scheduleWithFixedDelay( Runnable command, long initialDelay, long delay, TimeUnit unit): This method creates and executes a periodic action that is invoked firstly after the provided initial delay and repeatedly with the given delay between the termination of the executing one and the invocation f the next one."
},
{
"code": null,
"e": 31127,
"s": 30701,
"text": "It represents the result of an asynchronous operation. The methods in it check if the asynchronous operation is completed or not, get the completed result, etc. The cancel(boolean isInterruptRunning) API cancels the operation and releases the executing thread. On the value of isInterruptRunning value being true, the thread executing the task will be terminated instantly. Otherwise, all the in-progress tasks get completed."
},
{
"code": null,
"e": 31171,
"s": 31127,
"text": "Code snippet creates an instance of Future."
},
{
"code": null,
"e": 31399,
"s": 31171,
"text": "public void invoke() {\n ExecutorService executorService = Executors.newFixedThreadPool(20);\n\n Future<String> future = executorService.submit(() -> {\n // ...\n Thread.sleep(10000l);\n return \"Hello\";\n });\n}"
},
{
"code": null,
"e": 31512,
"s": 31399,
"text": "The code to check if the result of the future is ready or not and fetches the data when the computation is done."
},
{
"code": null,
"e": 31690,
"s": 31512,
"text": "if (future.isDone() && !future.isCancelled()) {\n try {\n str = future.get();\n } catch (InterruptedException | ExecutionException e) {\n e.printStackTrace();\n }\n}"
},
{
"code": null,
"e": 31810,
"s": 31690,
"text": "Timeout specification for a given operation. If the time taken is more than this time, then TimeoutException is thrown."
},
{
"code": null,
"e": 31955,
"s": 31810,
"text": "try {\n future.get(20, TimeUnit.SECONDS);\n} catch (InterruptedException | ExecutionException | TimeoutException e) {\n e.printStackTrace();\n} "
},
{
"code": null,
"e": 32267,
"s": 31955,
"text": "It is a utility class that blocks a set of threads until some operations get completed. A CountDownLatch is initialized with a counter(which is of Integer type). This counter decrements as the execution of the dependent threads get completed. But once the counter decrements to zero, other threads get released."
},
{
"code": null,
"e": 32485,
"s": 32267,
"text": "CyclicBarrier is almost the same as CountDownLatch except that we can reuse it. It allows multiple threads to wait for each other using await() before invoking the final task and this feature is not in CountDownLatch."
},
{
"code": null,
"e": 32575,
"s": 32485,
"text": "We are required to create an instance of Runnable Task to initiate the barrier condition."
},
{
"code": null,
"e": 33090,
"s": 32575,
"text": "public class Task implements Runnable {\n\n private CyclicBarrier barrier;\n\n public Task(CyclicBarrier barrier) {\n this.barrier = barrier;\n }\n\n @Override\n public void run() {\n try {\n LOG.info(Thread.currentThread().getName() +\n \" is waiting\");\n barrier.await();\n LOG.info(Thread.currentThread().getName() +\n \" is released\");\n } catch (InterruptedException | BrokenBarrierException e) {\n e.printStackTrace();\n }\n }\n\n}"
},
{
"code": null,
"e": 33149,
"s": 33090,
"text": "Now, invoking a few threads to race the barrier condition:"
},
{
"code": null,
"e": 33588,
"s": 33149,
"text": "public void start() {\n\n CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {\n // ..\n LOG.info(\"All previous tasks completed\");\n });\n\n Thread t11 = new Thread(new Task(cyclicBarrier), \"T11\");\n Thread t12 = new Thread(new Task(cyclicBarrier), \"T12\");\n Thread t13 = new Thread(new Task(cyclicBarrier), \"T13\");\n\n if (!cyclicBarrier.isBroken()) {\n t11.start();\n t12.start();\n t13.start();\n }\n}"
},
{
"code": null,
"e": 33701,
"s": 33588,
"text": "In the above code, the isBroken() method checks if any of the threads got interrupted during the execution time."
},
{
"code": null,
"e": 34112,
"s": 33701,
"text": "It is used for blocking thread-level access to some part of the logical or physical resource. Semaphore contains a set of permits. Wherever the thread tries to enter the code part of a critical section, semaphore gives the permission whether the permit is available or not, which means the critical section is available or not. If the permit is not available, then the thread cannot enter the critical section."
},
{
"code": null,
"e": 34318,
"s": 34112,
"text": "It is basically a variable named counter which maintains the count of entering and leaving threads from the critical section. When the executing thread releases the critical section, the counter increases."
},
{
"code": null,
"e": 34374,
"s": 34318,
"text": "Below code is used for the implementation of Semaphore:"
},
{
"code": null,
"e": 34759,
"s": 34374,
"text": "static Semaphore semaphore = new Semaphore(20);\n\npublic void execute() throws InterruptedException {\n\n LOG.info(\"Available : \" + semaphore.availablePermits());\n LOG.info(\"No. of threads waiting to acquire: \" +\n semaphore.getQueueLength());\n\n if (semaphore.tryAcquire()) {\n try {\n // \n }\n finally {\n semaphore.release();\n }\n }\n\n}"
},
{
"code": null,
"e": 34824,
"s": 34759,
"text": "Semaphores can be used to implement a Mutex-like data structure."
},
{
"code": null,
"e": 34920,
"s": 34824,
"text": "It acts as a thread pool which creates a new thread on demand. ThreadFactory can be defined as:"
},
{
"code": null,
"e": 35384,
"s": 34920,
"text": "public class GFGThreadFactory implements ThreadFactory {\n private int threadId;\n private String name;\n\n public GFGThreadFactory(String name) {\n threadId = 1;\n this.name = name;\n }\n\n @Override\n public Thread newThread(Runnable r) {\n Thread t = new Thread(r, name + \"-Thread_\" + threadId);\n LOG.info(\"created new thread with id : \" + threadId +\n \" and name : \" + t.getName());\n threadId++;\n return t;\n }\n}"
},
{
"code": null,
"e": 35934,
"s": 35384,
"text": "BlockingQueue interface supports flow control (in addition to queue) by introducing blocking if either BlockingQueue is full or empty. A thread trying to enqueue an element in a full queue is blocked until some other thread makes space in the queue, either by dequeuing one or more elements or clearing the queue completely. Similarly, it blocks a thread trying to delete from an empty queue until some other threads insert an item. BlockingQueue does not accept a null value. If we try to enqueue the null item, then it throws NullPointerException."
},
{
"code": null,
"e": 36417,
"s": 35934,
"text": "DelayQueue is a specialized Priority Queue that orders elements based on their delay time. It means that only those elements can be taken from the queue whose time has expired. DelayQueue head contains the element that has expired in the least time. If no delay has expired, then there is no head and poll will return null. DelayQueue accepts only those elements that belong to a class of type Delayed. DelayQueue implements the getDelay() method to return the remaining delay time."
},
{
"code": null,
"e": 36691,
"s": 36417,
"text": "It is a utility for blocking other threads from accessing a certain segment of code. The difference between Lock and a Synchronized block is that we have Lock APIs lock() and unlock() operation in separate methods whereas a Synchronized block is fully contained in methods."
},
{
"code": null,
"e": 36987,
"s": 36691,
"text": "It is more flexible than CountDownLatch and CyclicBarrier. Phaser is used to act as a reusable barrier on which the dynamic number of threads needs to wait before the execution continues. Multiple phases of execution can be coordinated by reusing the instance of a Phaser for each program phase."
},
{
"code": null,
"e": 36999,
"s": 36987,
"text": "anikaseth98"
},
{
"code": null,
"e": 37013,
"s": 36999,
"text": "solankimayank"
},
{
"code": null,
"e": 37037,
"s": 37013,
"text": "Java-concurrent-package"
},
{
"code": null,
"e": 37051,
"s": 37037,
"text": "Java-Packages"
},
{
"code": null,
"e": 37056,
"s": 37051,
"text": "Java"
},
{
"code": null,
"e": 37061,
"s": 37056,
"text": "Java"
},
{
"code": null,
"e": 37159,
"s": 37061,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37174,
"s": 37159,
"text": "Stream In Java"
},
{
"code": null,
"e": 37195,
"s": 37174,
"text": "Constructors in Java"
},
{
"code": null,
"e": 37214,
"s": 37195,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 37244,
"s": 37214,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 37290,
"s": 37244,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 37307,
"s": 37290,
"text": "Generics in Java"
},
{
"code": null,
"e": 37328,
"s": 37307,
"text": "Introduction to Java"
},
{
"code": null,
"e": 37371,
"s": 37328,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 37393,
"s": 37371,
"text": "PriorityQueue in Java"
}
]
|
Python | Create a stopwatch using clock object in kivy using .kv file - GeeksforGeeks | 01 Feb, 2021
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications.
Kivy Tutorial – Learn Kivy with Examples.
Clock Object: The Clock object allows you to schedule a function call in the future; once or repeatedly at specified intervals. You can get the time elapsed between the scheduling and the calling of the callback via the dt argument:
Python3
# define callbackdef my_callback(dt): pass # clock.schedule_interval with time specifiedClock.schedule_interval(my_callback, 0.5) # clock.schedule_once with time specifiedClock.schedule_once(my_callback, 5) # call my_callback as soon as possible.Clock.schedule_once(my_callback)
Note: If the callback returns False, the schedule will be canceled and won’t repeat.
In this, we are going to create the kivy the stopwatch and we are creating 3 buttons in this which are the start, pause, resume.
It is good to use kivy inbuilt module while working with clock and: from kivy.clock import Clock
Basic Approach:
1) import kivy
2) import kivyApp
3) import Builder
4) import Boxlayout
5) Import clock
6) import kivy properties(only needed one)
7) Set minimum version(optional)
8) Create the .kv code:
1) Create Buttons
2) Add call to button
3) Add label
9) Create Layout class
10) Create App class
11) return Layout/widget/Class(according to requirement)
12) Run an instance of the class
# Implementation of the Approach:
Python3
'''Code of How to create Stopwatch''' # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Builder is responsible for creating# a Parser for parsing a kv filefrom kivy.lang import Builder # The Properties classes are used# when you create an EventDispatcher.from kivy.properties import NumericProperty # BoxLayout arranges children in a vertical or horizontal box.# or help to put the children at the desired location.from kivy.uix.boxlayout import BoxLayout # he Clock object allows you to# schedule a function call in the futurefrom kivy.clock import Clock # Create the .kv file and load it by using BuilderBuilder.load_string(''' <MainWidget>: # Assigning the alignment to buttons BoxLayout: orientation: 'vertical' # Create Button Button: text: 'start' on_press: root.start() Button: text: 'stop' on_press: root.stop() Button: text: 'Reset' on_press: root.number = 0 # Create the Label Label: text: str(round(root.number)) text_size: self.size halign: 'center' valign: 'middle'''') # Create the Layout classclass MainWidget(BoxLayout): number = NumericProperty() def __init__(self, **kwargs): # The super() builtin # returns a proxy object that # allows you to refer parent class by 'super'. super(MainWidget, self).__init__(**kwargs) # Create the clock and increment the time by .1 ie 1 second. Clock.schedule_interval(self.increment_time, .1) self.increment_time(0) # To increase the time / count def increment_time(self, interval): self.number += .1 # To start the count def start(self): Clock.unschedule(self.increment_time) Clock.schedule_interval(self.increment_time, .1) # To stop the count / time def stop(self): Clock.unschedule(self.increment_time) # Create the App classclass TimeApp(App): def build(self): return MainWidget() # Run the AppTimeApp().run()
Output:
Note:
In this when you press start count start, when press Restart it starts again and when pause it get paused.
abhigoya
Python-gui
Python-kivy
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()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Convert integer to string in Python | [
{
"code": null,
"e": 25765,
"s": 25737,
"text": "\n01 Feb, 2021"
},
{
"code": null,
"e": 26002,
"s": 25765,
"text": "Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. "
},
{
"code": null,
"e": 26045,
"s": 26002,
"text": " Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 26279,
"s": 26045,
"text": "Clock Object: The Clock object allows you to schedule a function call in the future; once or repeatedly at specified intervals. You can get the time elapsed between the scheduling and the calling of the callback via the dt argument: "
},
{
"code": null,
"e": 26287,
"s": 26279,
"text": "Python3"
},
{
"code": "# define callbackdef my_callback(dt): pass # clock.schedule_interval with time specifiedClock.schedule_interval(my_callback, 0.5) # clock.schedule_once with time specifiedClock.schedule_once(my_callback, 5) # call my_callback as soon as possible.Clock.schedule_once(my_callback)",
"e": 26569,
"s": 26287,
"text": null
},
{
"code": null,
"e": 26656,
"s": 26569,
"text": "Note: If the callback returns False, the schedule will be canceled and won’t repeat. "
},
{
"code": null,
"e": 26786,
"s": 26656,
"text": "In this, we are going to create the kivy the stopwatch and we are creating 3 buttons in this which are the start, pause, resume. "
},
{
"code": null,
"e": 26883,
"s": 26786,
"text": "It is good to use kivy inbuilt module while working with clock and: from kivy.clock import Clock"
},
{
"code": null,
"e": 27293,
"s": 26885,
"text": "Basic Approach: \n1) import kivy\n2) import kivyApp\n3) import Builder\n4) import Boxlayout\n5) Import clock\n6) import kivy properties(only needed one)\n7) Set minimum version(optional)\n8) Create the .kv code:\n 1) Create Buttons\n 2) Add call to button\n 3) Add label \n9) Create Layout class\n10) Create App class\n11) return Layout/widget/Class(according to requirement)\n12) Run an instance of the class"
},
{
"code": null,
"e": 27329,
"s": 27293,
"text": "# Implementation of the Approach: "
},
{
"code": null,
"e": 27337,
"s": 27329,
"text": "Python3"
},
{
"code": "'''Code of How to create Stopwatch''' # Program to Show how to create a switch# import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Builder is responsible for creating# a Parser for parsing a kv filefrom kivy.lang import Builder # The Properties classes are used# when you create an EventDispatcher.from kivy.properties import NumericProperty # BoxLayout arranges children in a vertical or horizontal box.# or help to put the children at the desired location.from kivy.uix.boxlayout import BoxLayout # he Clock object allows you to# schedule a function call in the futurefrom kivy.clock import Clock # Create the .kv file and load it by using BuilderBuilder.load_string(''' <MainWidget>: # Assigning the alignment to buttons BoxLayout: orientation: 'vertical' # Create Button Button: text: 'start' on_press: root.start() Button: text: 'stop' on_press: root.stop() Button: text: 'Reset' on_press: root.number = 0 # Create the Label Label: text: str(round(root.number)) text_size: self.size halign: 'center' valign: 'middle'''') # Create the Layout classclass MainWidget(BoxLayout): number = NumericProperty() def __init__(self, **kwargs): # The super() builtin # returns a proxy object that # allows you to refer parent class by 'super'. super(MainWidget, self).__init__(**kwargs) # Create the clock and increment the time by .1 ie 1 second. Clock.schedule_interval(self.increment_time, .1) self.increment_time(0) # To increase the time / count def increment_time(self, interval): self.number += .1 # To start the count def start(self): Clock.unschedule(self.increment_time) Clock.schedule_interval(self.increment_time, .1) # To stop the count / time def stop(self): Clock.unschedule(self.increment_time) # Create the App classclass TimeApp(App): def build(self): return MainWidget() # Run the AppTimeApp().run()",
"e": 29730,
"s": 27337,
"text": null
},
{
"code": null,
"e": 29739,
"s": 29730,
"text": "Output: "
},
{
"code": null,
"e": 29746,
"s": 29739,
"text": "Note: "
},
{
"code": null,
"e": 29853,
"s": 29746,
"text": "In this when you press start count start, when press Restart it starts again and when pause it get paused."
},
{
"code": null,
"e": 29862,
"s": 29853,
"text": "abhigoya"
},
{
"code": null,
"e": 29873,
"s": 29862,
"text": "Python-gui"
},
{
"code": null,
"e": 29885,
"s": 29873,
"text": "Python-kivy"
},
{
"code": null,
"e": 29892,
"s": 29885,
"text": "Python"
},
{
"code": null,
"e": 29990,
"s": 29892,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30008,
"s": 29990,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30040,
"s": 30008,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30062,
"s": 30040,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30104,
"s": 30062,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30130,
"s": 30104,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30174,
"s": 30130,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 30203,
"s": 30174,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30240,
"s": 30203,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 30282,
"s": 30240,
"text": "How To Convert Python Dictionary To JSON?"
}
]
|
How to load an image and show the image using Keras? | To load an image and show the image using Keras, we will use load_image() method to load an image and set the target size of the image to be shown.
Use load_img() method to load the figure.
Set the target size of the image.
To display the figure, use show() method.
from keras.preprocessing import image
img = image.load_img('bird.jpg', target_size=(350, 750))
img.show() | [
{
"code": null,
"e": 1210,
"s": 1062,
"text": "To load an image and show the image using Keras, we will use load_image() method to load an image and set the target size of the image to be shown."
},
{
"code": null,
"e": 1252,
"s": 1210,
"text": "Use load_img() method to load the figure."
},
{
"code": null,
"e": 1286,
"s": 1252,
"text": "Set the target size of the image."
},
{
"code": null,
"e": 1328,
"s": 1286,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1435,
"s": 1328,
"text": "from keras.preprocessing import image\nimg = image.load_img('bird.jpg', target_size=(350, 750))\n\nimg.show()"
}
]
|
WPF - Application Level | Defining a style on app level can make it accessible throughout the entire application. Let’s take the same example, but here, we will put the styles in app.xaml file to make it accessible throughout application. Here is the XAML code in app.xaml.
<Application x:Class = "Styles.App"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri = "MainWindow.xaml">
<Application.Resources>
<Style TargetType = "TextBlock">
<Setter Property = "FontSize" Value = "24" />
<Setter Property = "Margin" Value = "5" />
<Setter Property = "FontWeight" Value = "Bold" />
</Style>
<Style TargetType = "TextBox">
<Setter Property = "HorizontalAlignment" Value = "Left" />
<Setter Property = "FontSize" Value = "24" />
<Setter Property = "Margin" Value = "5" />
<Setter Property = "Width" Value = "200" />
<Setter Property = "Height" Value="40" />
</Style>
</Application.Resources>
</Application>
Here is the XAML code to create text blocks and text boxes.
<Window x:Class = "Styles.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height = "Auto" />
<RowDefinition Height = "Auto" />
<RowDefinition Height = "Auto" />
<RowDefinition Height = "*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width = "*" />
<ColumnDefinition Width = "2*" />
</Grid.ColumnDefinitions>
<TextBlock Text = "First Name: "/>
<TextBox Name = "FirstName" Grid.Column = "1" />
<TextBlock Text = "Last Name: " Grid.Row = "1" />
<TextBox Name = "LastName" Grid.Column = "1" Grid.Row = "1" />
<TextBlock Text = "Email: " Grid.Row = "2" />
<TextBox Name = "Email" Grid.Column = "1" Grid.Row = "2"/>
</Grid>
</Window>
When you compile and execute the above code, it will produce the following window.
We recommend that you execute the above code and try to insert more features into it.
31 Lectures
2.5 hours
Anadi Sharma
30 Lectures
2.5 hours
Taurius Litvinavicius
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2268,
"s": 2020,
"text": "Defining a style on app level can make it accessible throughout the entire application. Let’s take the same example, but here, we will put the styles in app.xaml file to make it accessible throughout application. Here is the XAML code in app.xaml."
},
{
"code": null,
"e": 3117,
"s": 2268,
"text": "<Application x:Class = \"Styles.App\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n StartupUri = \"MainWindow.xaml\"> \n\t\n <Application.Resources> \n <Style TargetType = \"TextBlock\"> \n <Setter Property = \"FontSize\" Value = \"24\" /> \n <Setter Property = \"Margin\" Value = \"5\" /> \n <Setter Property = \"FontWeight\" Value = \"Bold\" /> \n </Style> \n\t\t\n <Style TargetType = \"TextBox\">\n <Setter Property = \"HorizontalAlignment\" Value = \"Left\" /> \n <Setter Property = \"FontSize\" Value = \"24\" /> \n <Setter Property = \"Margin\" Value = \"5\" /> \n <Setter Property = \"Width\" Value = \"200\" /> \n <Setter Property = \"Height\" Value=\"40\" /> \n </Style> \n\t\t\n </Application.Resources>\n\t\n</Application>"
},
{
"code": null,
"e": 3177,
"s": 3117,
"text": "Here is the XAML code to create text blocks and text boxes."
},
{
"code": null,
"e": 4175,
"s": 3177,
"text": "<Window x:Class = \"Styles.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid> \n <Grid.RowDefinitions> \n <RowDefinition Height = \"Auto\" /> \n <RowDefinition Height = \"Auto\" /> \n <RowDefinition Height = \"Auto\" /> \n <RowDefinition Height = \"*\" /> \n </Grid.RowDefinitions> \n\t\t\n <Grid.ColumnDefinitions> \n <ColumnDefinition Width = \"*\" /> \n <ColumnDefinition Width = \"2*\" /> \n </Grid.ColumnDefinitions> \n\t\t\n <TextBlock Text = \"First Name: \"/> \n <TextBox Name = \"FirstName\" Grid.Column = \"1\" /> \n <TextBlock Text = \"Last Name: \" Grid.Row = \"1\" /> \n <TextBox Name = \"LastName\" Grid.Column = \"1\" Grid.Row = \"1\" /> \n <TextBlock Text = \"Email: \" Grid.Row = \"2\" /> \n <TextBox Name = \"Email\" Grid.Column = \"1\" Grid.Row = \"2\"/> \n </Grid> \n\t\n</Window>"
},
{
"code": null,
"e": 4258,
"s": 4175,
"text": "When you compile and execute the above code, it will produce the following window."
},
{
"code": null,
"e": 4344,
"s": 4258,
"text": "We recommend that you execute the above code and try to insert more features into it."
},
{
"code": null,
"e": 4379,
"s": 4344,
"text": "\n 31 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4393,
"s": 4379,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4428,
"s": 4393,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4451,
"s": 4428,
"text": " Taurius Litvinavicius"
},
{
"code": null,
"e": 4458,
"s": 4451,
"text": " Print"
},
{
"code": null,
"e": 4469,
"s": 4458,
"text": " Add Notes"
}
]
|
Breadth First Traversal in C | We shall not see the implementation of Breadth First Traversal (or Breadth First Search) in C programming language. For our reference purpose, we shall follow our example and take this as our graph model −
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 5
struct Vertex {
char label;
bool visited;
};
//queue variables
int queue[MAX];
int rear = -1;
int front = 0;
int queueItemCount = 0;
//graph variables
//array of vertices
struct Vertex* lstVertices[MAX];
//adjacency matrix
int adjMatrix[MAX][MAX];
//vertex count
int vertexCount = 0;
//queue functions
void insert(int data) {
queue[++rear] = data;
queueItemCount++;
}
int removeData() {
queueItemCount--;
return queue[front++];
}
bool isQueueEmpty() {
return queueItemCount == 0;
}
//graph functions
//add vertex to the vertex list
void addVertex(char label) {
struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));
vertex->label = label;
vertex->visited = false;
lstVertices[vertexCount++] = vertex;
}
//add edge to edge array
void addEdge(int start,int end) {
adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
}
//display the vertex
void displayVertex(int vertexIndex) {
printf("%c ",lstVertices[vertexIndex]->label);
}
//get the adjacent unvisited vertex
int getAdjUnvisitedVertex(int vertexIndex) {
int i;
for(i = 0; i<vertexCount; i++) {
if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false)
return i;
}
return -1;
}
void breadthFirstSearch() {
int i;
//mark first node as visited
lstVertices[0]->visited = true;
//display the vertex
displayVertex(0);
//insert vertex index in queue
insert(0);
int unvisitedVertex;
while(!isQueueEmpty()) {
//get the unvisited vertex of vertex which is at front of the queue
int tempVertex = removeData();
//no adjacent vertex found
while((unvisitedVertex = getAdjUnvisitedVertex(tempVertex)) != -1) {
lstVertices[unvisitedVertex]->visited = true;
displayVertex(unvisitedVertex);
insert(unvisitedVertex);
}
}
//queue is empty, search is complete, reset the visited flag
for(i = 0;i<vertexCount;i++) {
lstVertices[i]->visited = false;
}
}
int main() {
int i, j;
for(i = 0; i<MAX; i++) // set adjacency {
for(j = 0; j<MAX; j++) // matrix to 0
adjMatrix[i][j] = 0;
}
addVertex('S'); // 0
addVertex('A'); // 1
addVertex('B'); // 2
addVertex('C'); // 3
addVertex('D'); // 4
addEdge(0, 1); // S - A
addEdge(0, 2); // S - B
addEdge(0, 3); // S - C
addEdge(1, 4); // A - D
addEdge(2, 4); // B - D
addEdge(3, 4); // C - D
printf("\nBreadth First Search: ");
breadthFirstSearch();
return 0;
}
If we compile and run the above program, it will produce the following result −
Breadth First Search: S A B C D
42 Lectures
1.5 hours
Ravi Kiran
141 Lectures
13 hours
Arnab Chakraborty
26 Lectures
8.5 hours
Parth Panjabi
65 Lectures
6 hours
Arnab Chakraborty
75 Lectures
13 hours
Eduonix Learning Solutions
64 Lectures
10.5 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2786,
"s": 2580,
"text": "We shall not see the implementation of Breadth First Traversal (or Breadth First Search) in C programming language. For our reference purpose, we shall follow our example and take this as our graph model −"
},
{
"code": null,
"e": 5482,
"s": 2786,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\n#define MAX 5\n\nstruct Vertex {\n char label;\n bool visited;\n};\n\n//queue variables\n\nint queue[MAX];\nint rear = -1;\nint front = 0;\nint queueItemCount = 0;\n\n//graph variables\n\n//array of vertices\nstruct Vertex* lstVertices[MAX];\n\n//adjacency matrix\nint adjMatrix[MAX][MAX];\n\n//vertex count\nint vertexCount = 0;\n\n//queue functions\n\nvoid insert(int data) {\n queue[++rear] = data;\n queueItemCount++;\n}\n\nint removeData() {\n queueItemCount--;\n return queue[front++]; \n}\n\nbool isQueueEmpty() {\n return queueItemCount == 0;\n}\n\n//graph functions\n\n//add vertex to the vertex list\nvoid addVertex(char label) {\n struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));\n vertex->label = label; \n vertex->visited = false; \n lstVertices[vertexCount++] = vertex;\n}\n\n//add edge to edge array\nvoid addEdge(int start,int end) {\n adjMatrix[start][end] = 1;\n adjMatrix[end][start] = 1;\n}\n\n//display the vertex\nvoid displayVertex(int vertexIndex) {\n printf(\"%c \",lstVertices[vertexIndex]->label);\n} \n\n//get the adjacent unvisited vertex\nint getAdjUnvisitedVertex(int vertexIndex) {\n int i;\n\t\n for(i = 0; i<vertexCount; i++) {\n if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false)\n return i;\n }\n\t\n return -1;\n}\n\nvoid breadthFirstSearch() {\n int i;\n\n //mark first node as visited\n lstVertices[0]->visited = true;\n\n //display the vertex\n displayVertex(0); \n\n //insert vertex index in queue\n insert(0);\n int unvisitedVertex;\n\n while(!isQueueEmpty()) {\n //get the unvisited vertex of vertex which is at front of the queue\n int tempVertex = removeData(); \n\n //no adjacent vertex found\n while((unvisitedVertex = getAdjUnvisitedVertex(tempVertex)) != -1) { \n lstVertices[unvisitedVertex]->visited = true;\n displayVertex(unvisitedVertex);\n insert(unvisitedVertex); \n }\n\t\t\n } \n\n //queue is empty, search is complete, reset the visited flag \n for(i = 0;i<vertexCount;i++) {\n lstVertices[i]->visited = false;\n } \n}\n\nint main() {\n int i, j;\n\n for(i = 0; i<MAX; i++) // set adjacency {\n for(j = 0; j<MAX; j++) // matrix to 0\n adjMatrix[i][j] = 0;\n }\n\n addVertex('S'); // 0\n addVertex('A'); // 1\n addVertex('B'); // 2\n addVertex('C'); // 3\n addVertex('D'); // 4\n \n addEdge(0, 1); // S - A\n addEdge(0, 2); // S - B\n addEdge(0, 3); // S - C\n addEdge(1, 4); // A - D\n addEdge(2, 4); // B - D\n addEdge(3, 4); // C - D\n\t\n printf(\"\\nBreadth First Search: \");\n \n breadthFirstSearch();\n\n return 0;\n}"
},
{
"code": null,
"e": 5562,
"s": 5482,
"text": "If we compile and run the above program, it will produce the following result −"
},
{
"code": null,
"e": 5595,
"s": 5562,
"text": "Breadth First Search: S A B C D\n"
},
{
"code": null,
"e": 5630,
"s": 5595,
"text": "\n 42 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5642,
"s": 5630,
"text": " Ravi Kiran"
},
{
"code": null,
"e": 5677,
"s": 5642,
"text": "\n 141 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5696,
"s": 5677,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5731,
"s": 5696,
"text": "\n 26 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5746,
"s": 5731,
"text": " Parth Panjabi"
},
{
"code": null,
"e": 5779,
"s": 5746,
"text": "\n 65 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5798,
"s": 5779,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5832,
"s": 5798,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5860,
"s": 5832,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5896,
"s": 5860,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 5924,
"s": 5896,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5931,
"s": 5924,
"text": " Print"
},
{
"code": null,
"e": 5942,
"s": 5931,
"text": " Add Notes"
}
]
|
Remove object from array in MongoDB? | To remove object from an array in MongoDB, you can use $pull operator. The syntax is as follows:
db.yourCollectionName.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
{$pull:{"yourArrayName":{"yourArrayFieldName":yourValue}}},
false,true);
To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:
> db.removeObject.insertOne({"CustomerName":"Maxwell","CustomerAge":23,
... "CustomerDetails":[
... {
... "CustomerId":100,
... "CustomerProduct":"Product-1"
... },
... {
... "CustomerId":150,
... "CustomerProduct":"Product-2"
... },
... {
... "CustomerId":200,
... "CustomerProduct":"Product-3"
... }
... ]
... });
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ea036a0c51185aefbd14f")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.removeObject.find().pretty();
The following is the output:
{
"_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
"CustomerName" : "Maxwell",
"CustomerAge" : 23,
"CustomerDetails" : [
{
"CustomerId" : 100,
"CustomerProduct" : "Product-1"
},
{
"CustomerId" : 150,
"CustomerProduct" : "Product-2"
},
{
"CustomerId" : 200,
"CustomerProduct" : "Product-3"
}
]
}
Here is the query to remove object from an array in MongoDB:
> db.removeObject.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
... {$pull:{"CustomerDetails":{"CustomerId":150}}},
... false,true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Above, we have removed object from an array. Let us display document from the collection. The query is as follows:
> db.removeObject.find().pretty();
The following is the output:
{
"_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
"CustomerName" : "Maxwell",
"CustomerAge" : 23,
"CustomerDetails" : [
{
"CustomerId" : 100,
"CustomerProduct" : "Product-1"
},
{
"CustomerId" : 200,
"CustomerProduct" : "Product-3"
}
]
} | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To remove object from an array in MongoDB, you can use $pull operator. The syntax is as follows:"
},
{
"code": null,
"e": 1308,
"s": 1159,
"text": "db.yourCollectionName.update( {'_id':ObjectId(\"5c6ea036a0c51185aefbd14f\")},\n{$pull:{\"yourArrayName\":{\"yourArrayFieldName\":yourValue}}},\nfalse,true);"
},
{
"code": null,
"e": 1444,
"s": 1308,
"text": "To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:"
},
{
"code": null,
"e": 1845,
"s": 1444,
"text": "> db.removeObject.insertOne({\"CustomerName\":\"Maxwell\",\"CustomerAge\":23,\n... \"CustomerDetails\":[\n... {\n... \"CustomerId\":100,\n... \"CustomerProduct\":\"Product-1\"\n... },\n... {\n... \"CustomerId\":150,\n... \"CustomerProduct\":\"Product-2\"\n... },\n... {\n... \"CustomerId\":200,\n... \"CustomerProduct\":\"Product-3\"\n... }\n... ]\n... });\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ea036a0c51185aefbd14f\")\n}"
},
{
"code": null,
"e": 1942,
"s": 1845,
"text": "Display all documents from a collection with the help of find() method. The query is as follows:"
},
{
"code": null,
"e": 1977,
"s": 1942,
"text": "> db.removeObject.find().pretty();"
},
{
"code": null,
"e": 2006,
"s": 1977,
"text": "The following is the output:"
},
{
"code": null,
"e": 2403,
"s": 2006,
"text": "{\n \"_id\" : ObjectId(\"5c6ea036a0c51185aefbd14f\"),\n \"CustomerName\" : \"Maxwell\",\n \"CustomerAge\" : 23,\n \"CustomerDetails\" : [\n {\n \"CustomerId\" : 100,\n \"CustomerProduct\" : \"Product-1\"\n },\n {\n \"CustomerId\" : 150,\n \"CustomerProduct\" : \"Product-2\"\n },\n {\n \"CustomerId\" : 200,\n \"CustomerProduct\" : \"Product-3\"\n }\n ]\n}"
},
{
"code": null,
"e": 2464,
"s": 2403,
"text": "Here is the query to remove object from an array in MongoDB:"
},
{
"code": null,
"e": 2671,
"s": 2464,
"text": "> db.removeObject.update( {'_id':ObjectId(\"5c6ea036a0c51185aefbd14f\")},\n... {$pull:{\"CustomerDetails\":{\"CustomerId\":150}}},\n... false,true);\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 2786,
"s": 2671,
"text": "Above, we have removed object from an array. Let us display document from the collection. The query is as follows:"
},
{
"code": null,
"e": 2821,
"s": 2786,
"text": "> db.removeObject.find().pretty();"
},
{
"code": null,
"e": 2850,
"s": 2821,
"text": "The following is the output:"
},
{
"code": null,
"e": 3160,
"s": 2850,
"text": "{\n \"_id\" : ObjectId(\"5c6ea036a0c51185aefbd14f\"),\n \"CustomerName\" : \"Maxwell\",\n \"CustomerAge\" : 23,\n \"CustomerDetails\" : [\n {\n \"CustomerId\" : 100,\n \"CustomerProduct\" : \"Product-1\"\n },\n {\n \"CustomerId\" : 200,\n \"CustomerProduct\" : \"Product-3\"\n }\n ]\n}"
}
]
|
Learn Decision making under uncertainty — Part 1: Solve the problem with mean values | by Ramakrishna Thiruveedhi | Towards Data Science | Many decision-making problems can be solved as a linear system of equations. Handling uncertainty in the problem is not straightforward. In this series of articles, we will explore the concept of using Stochastic Programming on a simple business problem. This first article covers the basic approach of building a model that can solve the problem based on mean values. It is important to get the problem modeled this way before we can handle uncertainty. We will solve the problem in python using an open-source solver that has these algorithms under the hood.
In future articles, we will change this model to account for uncertainty and improve the solution we find here.
Linear equations
Probability, Expected value
Note: The news vendor problem is another problem used to learn this topic. There are several articles already on medium. This farmer problem gives a different perspective especially the decisions made after the future is revealed. This problem has been explained in textbooks (see references below) but getting solutions requires using linear programming software. Using Python makes it easier to experiment and visualize solutions without installing new software or obtaining licenses.
Solving system of linear equations in Python
Computing expected value of any solution especially the “Mean value solution” using Python
An intuitive explanation of solution (optional)
A farmer is planning her crops for the season this year. The crops produced will be used to feed cattle until next year. The remaining crops can be sold in the open market.
The farmer has to decide how many acres to plant for each crop. She has a total of 500 acres available on the farm. Planting costs per crop are shown in the table below. The average yield is given for each crop. In bad season yield is only 80% and in good season yield increases to120%. The probability of these scenarios is equal (33%). The average yield per crop is shown in the table below.
When the growing season ends farmer knows how much crop is produced from the farm based on the yield. To meet the consumption needs on the farm until next season, the farmer can also buy the crops (only wheat and corn) in the open market. Excess crops can be sold into the market. Please note that beans are not needed on the farm but can be grown for a good profit until 6000 Tons and a much-reduced price over 6000 Tons.
Do we have enough information to solve the problem? What are our yields? Let us assume our yield is average and try to plan acres allocated to each crop. This is a very reasonable approach since it accounts for both bad yields and good yields. Many linear and mixed inter programming models are being built to solve business problems using this approach.
We will solve this problem by using a system of linear equations. I would recommend running the notebook step by step to understand the following.
The farmer has several decisions to make. We can think of the decisions being made at two stages — before the yield is known and after the yield is known. Hence problem like this is called a Two-stage Stochastic Programming problem. However, for this problem just like the Newsvendor problem, the second stage decisions are trivial (do not buy more crops than what we need for cattle, sell all remaining amounts).
Acres to plant for each crop (First stage)
Amount to buy for Wheat and Corn (Second stage)
Amount to sell for Wheat, Corn, and Beans (Second stage)
Excess amount of beans to sell at a lower price (Second stage)
Objective:
The farmer wants us to maximize profit at end of the season. We get revenue from selling crops remaining at end of the season after cattle consumption. We incur costs from planting costs before the season and from buying wheat and corn to feed cattle.
Maximize Profit =
Revenue for crop sales at end of season — Cost of buying Wheat and Corn deficits — Cost of planting crops
M = LpProblem("Farmer", LpMaximize)M += lpSum( [ selling_prices[item] * var_tons_sold[item] for item in items ] + [ selling_price_excess_beans * var_excess_beans_sold] #excess beans + [ -1 * planting_costs[item] * var_acres_planted[item] for item in items ] + [ -1 * purchase_prices[item] * var_tons_purchased[item] for item in purchasable_items ] )
Farm Acres Available
Acres Planted for all crops ≤ 500
M += lpSum([var_acres_planted[item] for item in items]) <= total_acres
For Wheat and Corn:
Crops produced by planting + Crops purchased = Crops used for consumption + Crops sold to market
M += lpSum([yields[item] * var_acres_planted[item]] + [var_tons_purchased[item]] + [-1 * var_tons_sold[item]]) == consumption_feed[item]
For Beans:
Crops produced by planting - Crops sold to the market at regular price — Crops sold to the market at a lower price = Consumption for beans ( 0 for our farmer)
Crops sold to the market at regular price ≤ 6000 T
M += lpSum([yields[item] * var_acres_planted[item]] + [-1 * var_tons_sold[item]] + [-1 * var_excess_beans_sold]) == consumption_feed[item] M += lpSum([var_tons_sold[item]]) <= limit_on_beans_regular_price
The system of equations can be solved in any linear programming solver. Even though plugins are available for Excel, a modeling language is easier to use and is necessary for solving the stochastic version of this problem. Commerical solvers (IBM CPLEX, Gurobi, FICO Xpress, AMPL, etc.) can be used for this purpose but they need installation. Some commercial solvers have python APIs but they need licensing. Commercial solvers may be a better choice for production systems with better performance and customer support. For purpose of learning, I have chosen the open-source Python package PuLP to allow anyone to run the notebook with minimal installation.
The notebook can be found here. Please install PuLPusing conda or pip.
pip install pulp
We can run the solver and obtain an optimal solution and use python to compute the following table to compute costs, revenue, and profit. The solution is to plan beans to sell 6000 Tons at a higher price, produce enough corn to feed cattle and use the rest of the acres to produce wheat.
We already know the profit if yields are average (118600) from the optimal solution to mean value yields (see table above).
If yields are bad and we had already planted based on our solution from average yield we will realize the following results. (no real decisions to be made — we have to buy deficits 48 in this case and sell the remaining)
Similarly, we can compute profit if we realize good yields
If the farmer decides to implement our recommendation based on average yields she will get an optimal profit of 118600 33% of the time but also get profits of 55120 and 148000. Her expected profit, in the long run, can be computed as below (over 99 seasons he will realize each profit 33 times).
EV of mean value Solution = (55120+118600+148000)/3= $107240
Please note that this is lower than what we hoped ($118600). This is due to the fact we planned based on average yield — the profit we gain in good years does not make up for the loss of profit in bad years.
Use the notebook to explore how solutions will change in the following scenarios.
What are the optimal solutions if we use other yields instead of average yields? (Hint: Use the notebook to change yield).
If the farmer has an optimistic or pessimistic bias and wants us to use either of the optimal solutions found using BAD or GOOD yields, what will be the expected value of using those solutions? How do they compare to using the mean value solution? Crosscheck your answers with the table below. For this example, it looks like an optimistic farmer who wants to use our solution based on good yields will do better compared to using an average yield. Please note that our mean value solution is close.
Can we use all three optimal solutions simultaneously? Since we do not know which season will have which yield, we can do this only if we can hire an oracle or machine learning expert who can predict the yield with 100% accuracy. We can compute the expected value of this approach so that we can establish an upper bound for the profit. In this case it is 1/3(59950+118600+167666) = $115406. So our mean value solution is doing well ($107240) but there is room for improvement. If the farmer is not too excited about the $8166 increase, we do not need to invest more effort to improve our profit.
Is there a solution that maximizes our expected profit, not for a given yield but all three yields simultaneously? Yes, there is and that solution should have a profit between $107240 and $115406. We will cover that in the next article.
We have modeled business problem as a system of linear equations
We used Python and Pulp to obtain a solution based on the average scenario. This notebook can be used to evaluate tradeoffs between all parameters.
We know the expected value of this solution even if other scenarios were to happen. This will be the benchmark we will try to beat by adding stochastic elements to our linear program.
With the understanding of how different solutions will behave under the three different scenarios, we are ready to move from linear programming to stochastic programming.
I will limit my references to resources that explain basics and refer to this problem.
[1] J. Linderoth, Class Notes covering this problem. Additional notes
[2] J. Birge, F. Louveaux, Textbook: Introduction to Stochastic Programming — this problem is covered in chapter 1.
[3] Official site for PuLP solver in Python
Read this section only to get an intuition of tradeoffs. Methods like this will not guarantee optimality in the presence of complex constraints. Also, this method is not possible once we start doing stochastic programming.
Can we take a greedy approach by allocating each acre to a crop that gives us maximum profit until we hit a constraint?
Let's compute the profit per acre for each crop. Since we are planning for the average case, we will use average yields.
For Wheat it is 2.5 * 170 -150 = 275 $ per acreSimilarly, for corn, it is 220 and for beans, it is 460 (at regular price) and -60 (at a reduced price).
However for Wheat and Corn until we meet the farm needs the profit comes from cost savings the farmer gains from avoiding purchasing them at a much higher price. In other words, until he meets consumption needs he can increase his profit by selling to himself (at the buyer’s price). For Wheat, it is 2.5*238–150 = 445 and for Corn, it is 400. These numbers are important to consider until we can meet the farm’s consumption.
Sort the marginal profits in decreasing order: 460 (sell beans), 445 (produce wheat to meet needs), 400 (produce corn to meet needs), 275 (produce wheat to sell), 220 (produce corn to sell), -60 (produce beans to sell at a lower price)
Execute the steps for each profit margin until farm acres are consumed or until the margin disappears.
Produce beans using 300 acres until marginal profit disappears at 6000 units. Acres left = 200Produce wheat using 80 acres to meet the farm’s needs. Acres left = 120Produce corn using 80 acres to meet the farm’s needs. Acres left = 40Produce wheat using 40 acres to sell to the market. Acres left = 0
Produce beans using 300 acres until marginal profit disappears at 6000 units. Acres left = 200
Produce wheat using 80 acres to meet the farm’s needs. Acres left = 120
Produce corn using 80 acres to meet the farm’s needs. Acres left = 40
Produce wheat using 40 acres to sell to the market. Acres left = 0
This gives us the solution: Wheat 120 acres, Corn 80 acres, and Beans 300 acres.
It turns out our intuitive solution is indeed optimal since there are no other complex constraints.
Note: To understand the intuition behind this approach try changing the sale price of beans — both primary and secondary.
There are a couple of inflection points where the marginal profit of beans matches producing wheat and corn for consumption = 33 and 35.25 (Hint: you can compute these easily by solving simple equations). At a price lower than 33 we should produce wheat and corn before we produce beans for sale.
There are a couple of inflection points where the marginal profit of beans matches producing corn for sale at 24 and 26.75. At a price lower than 24 we should produce wheat and corn for consumption first, sale next, and then only we produce beans for sale.
Check out new articles on this topic at my medium profile. If you would like to contact me here is my LinkedIn. | [
{
"code": null,
"e": 732,
"s": 171,
"text": "Many decision-making problems can be solved as a linear system of equations. Handling uncertainty in the problem is not straightforward. In this series of articles, we will explore the concept of using Stochastic Programming on a simple business problem. This first article covers the basic approach of building a model that can solve the problem based on mean values. It is important to get the problem modeled this way before we can handle uncertainty. We will solve the problem in python using an open-source solver that has these algorithms under the hood."
},
{
"code": null,
"e": 844,
"s": 732,
"text": "In future articles, we will change this model to account for uncertainty and improve the solution we find here."
},
{
"code": null,
"e": 861,
"s": 844,
"text": "Linear equations"
},
{
"code": null,
"e": 889,
"s": 861,
"text": "Probability, Expected value"
},
{
"code": null,
"e": 1376,
"s": 889,
"text": "Note: The news vendor problem is another problem used to learn this topic. There are several articles already on medium. This farmer problem gives a different perspective especially the decisions made after the future is revealed. This problem has been explained in textbooks (see references below) but getting solutions requires using linear programming software. Using Python makes it easier to experiment and visualize solutions without installing new software or obtaining licenses."
},
{
"code": null,
"e": 1421,
"s": 1376,
"text": "Solving system of linear equations in Python"
},
{
"code": null,
"e": 1512,
"s": 1421,
"text": "Computing expected value of any solution especially the “Mean value solution” using Python"
},
{
"code": null,
"e": 1560,
"s": 1512,
"text": "An intuitive explanation of solution (optional)"
},
{
"code": null,
"e": 1733,
"s": 1560,
"text": "A farmer is planning her crops for the season this year. The crops produced will be used to feed cattle until next year. The remaining crops can be sold in the open market."
},
{
"code": null,
"e": 2127,
"s": 1733,
"text": "The farmer has to decide how many acres to plant for each crop. She has a total of 500 acres available on the farm. Planting costs per crop are shown in the table below. The average yield is given for each crop. In bad season yield is only 80% and in good season yield increases to120%. The probability of these scenarios is equal (33%). The average yield per crop is shown in the table below."
},
{
"code": null,
"e": 2550,
"s": 2127,
"text": "When the growing season ends farmer knows how much crop is produced from the farm based on the yield. To meet the consumption needs on the farm until next season, the farmer can also buy the crops (only wheat and corn) in the open market. Excess crops can be sold into the market. Please note that beans are not needed on the farm but can be grown for a good profit until 6000 Tons and a much-reduced price over 6000 Tons."
},
{
"code": null,
"e": 2905,
"s": 2550,
"text": "Do we have enough information to solve the problem? What are our yields? Let us assume our yield is average and try to plan acres allocated to each crop. This is a very reasonable approach since it accounts for both bad yields and good yields. Many linear and mixed inter programming models are being built to solve business problems using this approach."
},
{
"code": null,
"e": 3052,
"s": 2905,
"text": "We will solve this problem by using a system of linear equations. I would recommend running the notebook step by step to understand the following."
},
{
"code": null,
"e": 3466,
"s": 3052,
"text": "The farmer has several decisions to make. We can think of the decisions being made at two stages — before the yield is known and after the yield is known. Hence problem like this is called a Two-stage Stochastic Programming problem. However, for this problem just like the Newsvendor problem, the second stage decisions are trivial (do not buy more crops than what we need for cattle, sell all remaining amounts)."
},
{
"code": null,
"e": 3509,
"s": 3466,
"text": "Acres to plant for each crop (First stage)"
},
{
"code": null,
"e": 3557,
"s": 3509,
"text": "Amount to buy for Wheat and Corn (Second stage)"
},
{
"code": null,
"e": 3614,
"s": 3557,
"text": "Amount to sell for Wheat, Corn, and Beans (Second stage)"
},
{
"code": null,
"e": 3677,
"s": 3614,
"text": "Excess amount of beans to sell at a lower price (Second stage)"
},
{
"code": null,
"e": 3688,
"s": 3677,
"text": "Objective:"
},
{
"code": null,
"e": 3940,
"s": 3688,
"text": "The farmer wants us to maximize profit at end of the season. We get revenue from selling crops remaining at end of the season after cattle consumption. We incur costs from planting costs before the season and from buying wheat and corn to feed cattle."
},
{
"code": null,
"e": 3958,
"s": 3940,
"text": "Maximize Profit ="
},
{
"code": null,
"e": 4064,
"s": 3958,
"text": "Revenue for crop sales at end of season — Cost of buying Wheat and Corn deficits — Cost of planting crops"
},
{
"code": null,
"e": 4477,
"s": 4064,
"text": "M = LpProblem(\"Farmer\", LpMaximize)M += lpSum( [ selling_prices[item] * var_tons_sold[item] for item in items ] + [ selling_price_excess_beans * var_excess_beans_sold] #excess beans + [ -1 * planting_costs[item] * var_acres_planted[item] for item in items ] + [ -1 * purchase_prices[item] * var_tons_purchased[item] for item in purchasable_items ] )"
},
{
"code": null,
"e": 4498,
"s": 4477,
"text": "Farm Acres Available"
},
{
"code": null,
"e": 4532,
"s": 4498,
"text": "Acres Planted for all crops ≤ 500"
},
{
"code": null,
"e": 4603,
"s": 4532,
"text": "M += lpSum([var_acres_planted[item] for item in items]) <= total_acres"
},
{
"code": null,
"e": 4623,
"s": 4603,
"text": "For Wheat and Corn:"
},
{
"code": null,
"e": 4720,
"s": 4623,
"text": "Crops produced by planting + Crops purchased = Crops used for consumption + Crops sold to market"
},
{
"code": null,
"e": 4857,
"s": 4720,
"text": "M += lpSum([yields[item] * var_acres_planted[item]] + [var_tons_purchased[item]] + [-1 * var_tons_sold[item]]) == consumption_feed[item]"
},
{
"code": null,
"e": 4868,
"s": 4857,
"text": "For Beans:"
},
{
"code": null,
"e": 5027,
"s": 4868,
"text": "Crops produced by planting - Crops sold to the market at regular price — Crops sold to the market at a lower price = Consumption for beans ( 0 for our farmer)"
},
{
"code": null,
"e": 5078,
"s": 5027,
"text": "Crops sold to the market at regular price ≤ 6000 T"
},
{
"code": null,
"e": 5286,
"s": 5078,
"text": "M += lpSum([yields[item] * var_acres_planted[item]] + [-1 * var_tons_sold[item]] + [-1 * var_excess_beans_sold]) == consumption_feed[item] M += lpSum([var_tons_sold[item]]) <= limit_on_beans_regular_price"
},
{
"code": null,
"e": 5945,
"s": 5286,
"text": "The system of equations can be solved in any linear programming solver. Even though plugins are available for Excel, a modeling language is easier to use and is necessary for solving the stochastic version of this problem. Commerical solvers (IBM CPLEX, Gurobi, FICO Xpress, AMPL, etc.) can be used for this purpose but they need installation. Some commercial solvers have python APIs but they need licensing. Commercial solvers may be a better choice for production systems with better performance and customer support. For purpose of learning, I have chosen the open-source Python package PuLP to allow anyone to run the notebook with minimal installation."
},
{
"code": null,
"e": 6016,
"s": 5945,
"text": "The notebook can be found here. Please install PuLPusing conda or pip."
},
{
"code": null,
"e": 6033,
"s": 6016,
"text": "pip install pulp"
},
{
"code": null,
"e": 6321,
"s": 6033,
"text": "We can run the solver and obtain an optimal solution and use python to compute the following table to compute costs, revenue, and profit. The solution is to plan beans to sell 6000 Tons at a higher price, produce enough corn to feed cattle and use the rest of the acres to produce wheat."
},
{
"code": null,
"e": 6445,
"s": 6321,
"text": "We already know the profit if yields are average (118600) from the optimal solution to mean value yields (see table above)."
},
{
"code": null,
"e": 6666,
"s": 6445,
"text": "If yields are bad and we had already planted based on our solution from average yield we will realize the following results. (no real decisions to be made — we have to buy deficits 48 in this case and sell the remaining)"
},
{
"code": null,
"e": 6725,
"s": 6666,
"text": "Similarly, we can compute profit if we realize good yields"
},
{
"code": null,
"e": 7021,
"s": 6725,
"text": "If the farmer decides to implement our recommendation based on average yields she will get an optimal profit of 118600 33% of the time but also get profits of 55120 and 148000. Her expected profit, in the long run, can be computed as below (over 99 seasons he will realize each profit 33 times)."
},
{
"code": null,
"e": 7082,
"s": 7021,
"text": "EV of mean value Solution = (55120+118600+148000)/3= $107240"
},
{
"code": null,
"e": 7290,
"s": 7082,
"text": "Please note that this is lower than what we hoped ($118600). This is due to the fact we planned based on average yield — the profit we gain in good years does not make up for the loss of profit in bad years."
},
{
"code": null,
"e": 7372,
"s": 7290,
"text": "Use the notebook to explore how solutions will change in the following scenarios."
},
{
"code": null,
"e": 7495,
"s": 7372,
"text": "What are the optimal solutions if we use other yields instead of average yields? (Hint: Use the notebook to change yield)."
},
{
"code": null,
"e": 7995,
"s": 7495,
"text": "If the farmer has an optimistic or pessimistic bias and wants us to use either of the optimal solutions found using BAD or GOOD yields, what will be the expected value of using those solutions? How do they compare to using the mean value solution? Crosscheck your answers with the table below. For this example, it looks like an optimistic farmer who wants to use our solution based on good yields will do better compared to using an average yield. Please note that our mean value solution is close."
},
{
"code": null,
"e": 8592,
"s": 7995,
"text": "Can we use all three optimal solutions simultaneously? Since we do not know which season will have which yield, we can do this only if we can hire an oracle or machine learning expert who can predict the yield with 100% accuracy. We can compute the expected value of this approach so that we can establish an upper bound for the profit. In this case it is 1/3(59950+118600+167666) = $115406. So our mean value solution is doing well ($107240) but there is room for improvement. If the farmer is not too excited about the $8166 increase, we do not need to invest more effort to improve our profit."
},
{
"code": null,
"e": 8829,
"s": 8592,
"text": "Is there a solution that maximizes our expected profit, not for a given yield but all three yields simultaneously? Yes, there is and that solution should have a profit between $107240 and $115406. We will cover that in the next article."
},
{
"code": null,
"e": 8894,
"s": 8829,
"text": "We have modeled business problem as a system of linear equations"
},
{
"code": null,
"e": 9042,
"s": 8894,
"text": "We used Python and Pulp to obtain a solution based on the average scenario. This notebook can be used to evaluate tradeoffs between all parameters."
},
{
"code": null,
"e": 9226,
"s": 9042,
"text": "We know the expected value of this solution even if other scenarios were to happen. This will be the benchmark we will try to beat by adding stochastic elements to our linear program."
},
{
"code": null,
"e": 9397,
"s": 9226,
"text": "With the understanding of how different solutions will behave under the three different scenarios, we are ready to move from linear programming to stochastic programming."
},
{
"code": null,
"e": 9484,
"s": 9397,
"text": "I will limit my references to resources that explain basics and refer to this problem."
},
{
"code": null,
"e": 9554,
"s": 9484,
"text": "[1] J. Linderoth, Class Notes covering this problem. Additional notes"
},
{
"code": null,
"e": 9670,
"s": 9554,
"text": "[2] J. Birge, F. Louveaux, Textbook: Introduction to Stochastic Programming — this problem is covered in chapter 1."
},
{
"code": null,
"e": 9714,
"s": 9670,
"text": "[3] Official site for PuLP solver in Python"
},
{
"code": null,
"e": 9937,
"s": 9714,
"text": "Read this section only to get an intuition of tradeoffs. Methods like this will not guarantee optimality in the presence of complex constraints. Also, this method is not possible once we start doing stochastic programming."
},
{
"code": null,
"e": 10057,
"s": 9937,
"text": "Can we take a greedy approach by allocating each acre to a crop that gives us maximum profit until we hit a constraint?"
},
{
"code": null,
"e": 10178,
"s": 10057,
"text": "Let's compute the profit per acre for each crop. Since we are planning for the average case, we will use average yields."
},
{
"code": null,
"e": 10330,
"s": 10178,
"text": "For Wheat it is 2.5 * 170 -150 = 275 $ per acreSimilarly, for corn, it is 220 and for beans, it is 460 (at regular price) and -60 (at a reduced price)."
},
{
"code": null,
"e": 10756,
"s": 10330,
"text": "However for Wheat and Corn until we meet the farm needs the profit comes from cost savings the farmer gains from avoiding purchasing them at a much higher price. In other words, until he meets consumption needs he can increase his profit by selling to himself (at the buyer’s price). For Wheat, it is 2.5*238–150 = 445 and for Corn, it is 400. These numbers are important to consider until we can meet the farm’s consumption."
},
{
"code": null,
"e": 10992,
"s": 10756,
"text": "Sort the marginal profits in decreasing order: 460 (sell beans), 445 (produce wheat to meet needs), 400 (produce corn to meet needs), 275 (produce wheat to sell), 220 (produce corn to sell), -60 (produce beans to sell at a lower price)"
},
{
"code": null,
"e": 11095,
"s": 10992,
"text": "Execute the steps for each profit margin until farm acres are consumed or until the margin disappears."
},
{
"code": null,
"e": 11396,
"s": 11095,
"text": "Produce beans using 300 acres until marginal profit disappears at 6000 units. Acres left = 200Produce wheat using 80 acres to meet the farm’s needs. Acres left = 120Produce corn using 80 acres to meet the farm’s needs. Acres left = 40Produce wheat using 40 acres to sell to the market. Acres left = 0"
},
{
"code": null,
"e": 11491,
"s": 11396,
"text": "Produce beans using 300 acres until marginal profit disappears at 6000 units. Acres left = 200"
},
{
"code": null,
"e": 11563,
"s": 11491,
"text": "Produce wheat using 80 acres to meet the farm’s needs. Acres left = 120"
},
{
"code": null,
"e": 11633,
"s": 11563,
"text": "Produce corn using 80 acres to meet the farm’s needs. Acres left = 40"
},
{
"code": null,
"e": 11700,
"s": 11633,
"text": "Produce wheat using 40 acres to sell to the market. Acres left = 0"
},
{
"code": null,
"e": 11781,
"s": 11700,
"text": "This gives us the solution: Wheat 120 acres, Corn 80 acres, and Beans 300 acres."
},
{
"code": null,
"e": 11881,
"s": 11781,
"text": "It turns out our intuitive solution is indeed optimal since there are no other complex constraints."
},
{
"code": null,
"e": 12003,
"s": 11881,
"text": "Note: To understand the intuition behind this approach try changing the sale price of beans — both primary and secondary."
},
{
"code": null,
"e": 12300,
"s": 12003,
"text": "There are a couple of inflection points where the marginal profit of beans matches producing wheat and corn for consumption = 33 and 35.25 (Hint: you can compute these easily by solving simple equations). At a price lower than 33 we should produce wheat and corn before we produce beans for sale."
},
{
"code": null,
"e": 12557,
"s": 12300,
"text": "There are a couple of inflection points where the marginal profit of beans matches producing corn for sale at 24 and 26.75. At a price lower than 24 we should produce wheat and corn for consumption first, sale next, and then only we produce beans for sale."
}
]
|
Python - Calculate the median of column values of a Pandas DataFrame | To calculate the median of column values, use the median() method. At first, import the required Pandas library −
import pandas as pd
Now, create a DataFrame with two columns −
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90] }
)
Finding the median of a single column “Units” using median() −
print"Median of Units column from DataFrame1 = ",dataFrame1['Units'].median()
In the same way, we have calculated the median value from the 2nd DataFrame.
Following is the complete code −
import pandas as pd
# Create DataFrame1
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
print"DataFrame1 ...\n",dataFrame1
# Finding median of "Units" column values
print"Median of Units column from DataFrame1 = ",dataFrame1['Units'].median()
# Create DataFrame2
dataFrame2 = pd.DataFrame(
{
"Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD', 'SSD'],
"Price": [8000, 500, 3000, 1500, 3000, 4000]
}
)
print"\nDataFrame2 ...\n",dataFrame2
# Finding median of "Price" column values
print"Median of Price column from DataFrame2 = ",dataFrame2['Price'].median()
This will produce the following output −
DataFrame1 ...
Car Units
0 BMW 100
1 Lexus 150
2 Audi 110
3 Tesla 80
4 Bentley 110
5 Jaguar 90
Median of Units column from DataFrame1 = 105.0
DataFrame2 ...
Price Product
0 8000 TV
1 500 PenDrive
2 3000 HeadPhone
3 1500 EarPhone
4 3000 HDD
5 4000 SSD
Median of Price column from DataFrame2 = 3000.0 | [
{
"code": null,
"e": 1176,
"s": 1062,
"text": "To calculate the median of column values, use the median() method. At first, import the required Pandas library −"
},
{
"code": null,
"e": 1196,
"s": 1176,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1239,
"s": 1196,
"text": "Now, create a DataFrame with two columns −"
},
{
"code": null,
"e": 1388,
"s": 1239,
"text": "dataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90] }\n)"
},
{
"code": null,
"e": 1451,
"s": 1388,
"text": "Finding the median of a single column “Units” using median() −"
},
{
"code": null,
"e": 1531,
"s": 1451,
"text": "print\"Median of Units column from DataFrame1 = \",dataFrame1['Units'].median()\n\n"
},
{
"code": null,
"e": 1608,
"s": 1531,
"text": "In the same way, we have calculated the median value from the 2nd DataFrame."
},
{
"code": null,
"e": 1641,
"s": 1608,
"text": "Following is the complete code −"
},
{
"code": null,
"e": 2337,
"s": 1641,
"text": "import pandas as pd\n\n# Create DataFrame1\ndataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90]\n }\n)\n\nprint\"DataFrame1 ...\\n\",dataFrame1\n\n# Finding median of \"Units\" column values\nprint\"Median of Units column from DataFrame1 = \",dataFrame1['Units'].median()\n\n# Create DataFrame2\ndataFrame2 = pd.DataFrame(\n {\n \"Product\": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD', 'SSD'],\n \"Price\": [8000, 500, 3000, 1500, 3000, 4000]\n }\n)\n\nprint\"\\nDataFrame2 ...\\n\",dataFrame2\n\n# Finding median of \"Price\" column values\nprint\"Median of Price column from DataFrame2 = \",dataFrame2['Price'].median()"
},
{
"code": null,
"e": 2378,
"s": 2337,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2755,
"s": 2378,
"text": "DataFrame1 ...\n Car Units\n0 BMW 100\n1 Lexus 150\n2 Audi 110\n3 Tesla 80\n4 Bentley 110\n5 Jaguar 90\nMedian of Units column from DataFrame1 = 105.0\n\nDataFrame2 ...\n Price Product\n0 8000 TV\n1 500 PenDrive\n2 3000 HeadPhone\n3 1500 EarPhone\n4 3000 HDD\n5 4000 SSD\nMedian of Price column from DataFrame2 = 3000.0"
}
]
|
MongoDB - Deployment | When you are preparing a MongoDB deployment, you should try to understand how your application is going to hold up in production. It’s a good idea to develop a consistent, repeatable approach to managing your deployment environment so that you can minimize any surprises once you’re in production.
The best approach incorporates prototyping your set up, conducting load testing, monitoring key metrics, and using that information to scale your set up. The key part of the approach is to proactively monitor your entire system - this will help you understand how your production system will hold up before deploying, and determine where you will need to add capacity. Having insight into potential spikes in your memory usage, for example, could help put out a write-lock fire before it starts.
To monitor your deployment, MongoDB provides some of the following commands −
This command checks the status of all running mongod instances and return counters of database operations. These counters include inserts, queries, updates, deletes, and cursors. Command also shows when you’re hitting page faults, and showcase your lock percentage. This means that you're running low on memory, hitting write capacity or have some performance issue.
To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongostat.
D:\set up\mongodb\bin>mongostat
Following is the output of the command −
This command tracks and reports the read and write activity of MongoDB instance on a collection basis. By default, mongotop returns information in each second, which you can change it accordingly. You should check that this read and write activity matches your application intention, and you’re not firing too many writes to the database at a time, reading too frequently from a disk, or are exceeding your working set size.
To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongotop.
D:\set up\mongodb\bin>mongotop
Following is the output of the command −
To change mongotop command to return information less frequently, specify a specific number after the mongotop command.
D:\set up\mongodb\bin>mongotop 30
The above example will return values every 30 seconds.
Apart from the MongoDB tools, 10gen provides a free, hosted monitoring service, MongoDB Management Service (MMS), that provides a dashboard and gives you a view of the metrics from your entire cluster.
44 Lectures
3 hours
Arnab Chakraborty
54 Lectures
5.5 hours
Eduonix Learning Solutions
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
40 Lectures
2.5 hours
University Code
26 Lectures
8 hours
Bassir Jafarzadeh
70 Lectures
2.5 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2851,
"s": 2553,
"text": "When you are preparing a MongoDB deployment, you should try to understand how your application is going to hold up in production. It’s a good idea to develop a consistent, repeatable approach to managing your deployment environment so that you can minimize any surprises once you’re in production."
},
{
"code": null,
"e": 3347,
"s": 2851,
"text": "The best approach incorporates prototyping your set up, conducting load testing, monitoring key metrics, and using that information to scale your set up. The key part of the approach is to proactively monitor your entire system - this will help you understand how your production system will hold up before deploying, and determine where you will need to add capacity. Having insight into potential spikes in your memory usage, for example, could help put out a write-lock fire before it starts."
},
{
"code": null,
"e": 3425,
"s": 3347,
"text": "To monitor your deployment, MongoDB provides some of the following commands −"
},
{
"code": null,
"e": 3792,
"s": 3425,
"text": "This command checks the status of all running mongod instances and return counters of database operations. These counters include inserts, queries, updates, deletes, and cursors. Command also shows when you’re hitting page faults, and showcase your lock percentage. This means that you're running low on memory, hitting write capacity or have some performance issue."
},
{
"code": null,
"e": 3936,
"s": 3792,
"text": "To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongostat."
},
{
"code": null,
"e": 3969,
"s": 3936,
"text": "D:\\set up\\mongodb\\bin>mongostat\n"
},
{
"code": null,
"e": 4010,
"s": 3969,
"text": "Following is the output of the command −"
},
{
"code": null,
"e": 4435,
"s": 4010,
"text": "This command tracks and reports the read and write activity of MongoDB instance on a collection basis. By default, mongotop returns information in each second, which you can change it accordingly. You should check that this read and write activity matches your application intention, and you’re not firing too many writes to the database at a time, reading too frequently from a disk, or are exceeding your working set size."
},
{
"code": null,
"e": 4578,
"s": 4435,
"text": "To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongotop."
},
{
"code": null,
"e": 4610,
"s": 4578,
"text": "D:\\set up\\mongodb\\bin>mongotop\n"
},
{
"code": null,
"e": 4651,
"s": 4610,
"text": "Following is the output of the command −"
},
{
"code": null,
"e": 4771,
"s": 4651,
"text": "To change mongotop command to return information less frequently, specify a specific number after the mongotop command."
},
{
"code": null,
"e": 4806,
"s": 4771,
"text": "D:\\set up\\mongodb\\bin>mongotop 30\n"
},
{
"code": null,
"e": 4861,
"s": 4806,
"text": "The above example will return values every 30 seconds."
},
{
"code": null,
"e": 5063,
"s": 4861,
"text": "Apart from the MongoDB tools, 10gen provides a free, hosted monitoring service, MongoDB Management Service (MMS), that provides a dashboard and gives you a view of the metrics from your entire cluster."
},
{
"code": null,
"e": 5096,
"s": 5063,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5115,
"s": 5096,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5150,
"s": 5115,
"text": "\n 54 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5178,
"s": 5150,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5213,
"s": 5178,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5236,
"s": 5213,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 5271,
"s": 5236,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5288,
"s": 5271,
"text": " University Code"
},
{
"code": null,
"e": 5321,
"s": 5288,
"text": "\n 26 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5340,
"s": 5321,
"text": " Bassir Jafarzadeh"
},
{
"code": null,
"e": 5375,
"s": 5340,
"text": "\n 70 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5395,
"s": 5375,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5402,
"s": 5395,
"text": " Print"
},
{
"code": null,
"e": 5413,
"s": 5402,
"text": " Add Notes"
}
]
|
Chi-Square Test for Independence in Python with Examples from the IBM HR Analytics Dataset | by Dehao Zhang | Towards Data Science | Suppose you are exploring a dataset and you want to examine if two categorical variables are dependent on each other.
The motivation could be a better understanding of the relationship between an outcome variable and a predictor, identification of dependent predictors, etc.
In this case, a Chi-square test can be an effective statistical tool.
In this post, I will discuss how to do this test in Python (both from scratch and using SciPy) with examples on a popular HR analytics dataset — the IBM Employee Attrition & Performance dataset.
What is Chi-square test?What are the categorical variables that we want to examine?How to perform this test from scratch?Is there a shortcut to do this?What else can we do?What are the limitations?
What is Chi-square test?
What are the categorical variables that we want to examine?
How to perform this test from scratch?
Is there a shortcut to do this?
What else can we do?
What are the limitations?
Chi-square test is a statistical hypothesis test to perform when the test statistic is Chi-square distributed under the null hypothesis and particularly the Chi-square test for independence is often used to examine independence between two categorical variables [1].
The key assumptions associated with this test are: 1. random sample from the population. 2. each subject cannot be in more than 1 group in any variable.
To better illustrate this test, I have chosen the IBM HR dataset from Kaggle (link), which includes a sample of employee HR information regarding attrition, work satisfaction, performance, etc. People often use it to uncover insights about the relationship between employee attrition and other factors.
Note that this is a fictional data set created by IBM data scientists [2].
To see the full Python code, check out my Kaggle kernel.
Without further ado, let’s get to the details!
Let’s first check out the number of employees and the number of attributes:
data.shape--------------------------------------------------------------------(1470, 35)
There are 1470 employees and 35 attributes.
Next, we can check what these attributes are and see if there is any missing value associated with each of them:
data.isna().any()--------------------------------------------------------------------Age FalseAttrition FalseBusinessTravel FalseDailyRate FalseDepartment FalseDistanceFromHome FalseEducation FalseEducationField FalseEmployeeCount FalseEmployeeNumber FalseEnvironmentSatisfaction FalseGender FalseHourlyRate FalseJobInvolvement FalseJobLevel FalseJobRole FalseJobSatisfaction FalseMaritalStatus FalseMonthlyIncome FalseMonthlyRate FalseNumCompaniesWorked FalseOver18 FalseOverTime FalsePercentSalaryHike FalsePerformanceRating FalseRelationshipSatisfaction FalseStandardHours FalseStockOptionLevel FalseTotalWorkingYears FalseTrainingTimesLastYear FalseWorkLifeBalance FalseYearsAtCompany FalseYearsInCurrentRole FalseYearsSinceLastPromotion FalseYearsWithCurrManager Falsedtype: bool
Identify Categorical Variables
Suppose we want to examine if there is a relationship between ‘Attrition’ and ‘JobSatisfaction’.
Counts for the two categories of ‘Attrition’:
data['Attrition'].value_counts()--------------------------------------------------------------------No 1233Yes 237Name: Attrition, dtype: int64
Counts for the four categories of ‘JobSatisfaction’ ordered by frequency:
data['JobSatisfaction'].value_counts()--------------------------------------------------------------------4 4593 4421 2892 280Name: JobSatisfaction, dtype: int64
Note that for ‘JobSatisfaction’, 1 is ‘Low’, 2 is ‘Medium’, 3 is ‘High’, and 4 is ‘Very High’.
Null Hypothesis and Alternate Hypothesis
For our Chi-square test for independence here, the null hypothesis is that there is no significant relationship between ‘Attrition’ and ‘JobSatisfaction’.
The alternative hypothesis is that there is significant relationship between ‘Attrition’ and ‘JobSatisfaction’.
Contingency Table
In order to compute the Chi-square test statistic, we would need to construct a contingency table.
We can do that using the ‘crosstab’ function from pandas:
pd.crosstab(data.Attrition, data.JobSatisfaction, margins=True)
The numbers in this table represent frequencies. For example, the ‘46’ shown under both ‘2’ in ‘JobSatisfaction’ and ‘Yes’ in ‘Attrition’ means that out of the 1470 employees, 46 of them rated their job satisfaction as ‘Medium’ and they did leave the company.
Chi-square Statistic
The formula for calculating the Chi-square statistic (X2) is shown as follows:
X2 = sum of [(observed-expected)2 / expected]
The term ‘observed’ refers to the numbers we have seen in the contingency table, and the term ‘expected’ refers to the expected numbers when the null hypothesis is true.
Under the null hypothesis, there is no significant relationship between ‘Attrition’ and ‘JobSatisfaction’, which means the percentage of attrition should be consistent across the four categories of job satisfaction. As an example, the expected frequency for ‘4’ and ‘Attrition’ should be the number of employees that rate their job satisfactions as ‘Very High’ * (total attrition/total employee count), which is 459*237/1470, or about 74.
Let’s compute all the expected numbers and store them in a list called ‘exp’:
row_sum = ct.iloc[0:2,4].valuesexp = []for j in range(2): for val in ct.iloc[2,0:4].values: exp.append(val * row_sum[j] / ct.loc['All', 'All'])print(exp)--------------------------------------------------------------------[242.4061224489796, 234.85714285714286, 370.7387755102041, 384.99795918367346, 46.593877551020405, 45.142857142857146, 71.26122448979592, 74.00204081632653]
Note that the last term (74) verifies that our calculation is correct.
Now we can compute X2:
((obs - exp)**2/exp).sum()--------------------------------------------------------------------17.505077010348
Degree of Freedom
One parameter we need apart from X2 is the degree of freedom, which is computed as (number of categories in the first variable-1)*(number of categories in the second variable-1), and it is (2–1)*(4–1) in this case, or 3.
(len(row_sum)-1)*(len(ct.iloc[2,0:4].values)-1)--------------------------------------------------------------------3
Interpretation
With both X2 and degrees of freedom, we can use a Chi-square table/calculator to determine its corresponding p-value and conclude if there is a significant relationship given a specified significance level of alpha.
In another word, given the degrees of freedom, we know that the ‘observed’ should be close to ‘expected’ under the null hypothesis which means X2 should be reasonably small. When X2 is larger than a threshold, we know the p-value (probability of having a such as large X2 given the null hypothesis) is extremely low, and we would reject the null hypothesis.
In Python, we can compute the p-value as follows:
1 - stats.chi2.cdf(chi_sq_stats, dof)--------------------------------------------------------------------0.000556300451038716
Suppose the significance level is 0.05. We can conclude that there is a significant relationship between ‘Attrition’ and ‘JobSatisfaction’.
Using SciPy
There is a shortcut to perform this test in Python, which leverages the SciPy library (documentation).
obs = np.array([ct.iloc[0][0:4].values, ct.iloc[1][0:4].values])stats.chi2_contingency(obs)[0:3]--------------------------------------------------------------------(17.505077010348, 0.0005563004510387556, 3)
Note that the three terms are X2 statistic, p-value, and degree of freedom, respectively. These results are consistent with the ones we computed by hand earlier.
‘Attrition’ and ‘Education’
It is somewhat intuitive that whether the employee leaves the company is related to the job satisfaction. Now let’s look at another example where we examine if there is significant relationship between ‘Attrition’ and ‘Education’:
ct = pd.crosstab(data.Attrition, data.Education, margins=True)obs = np.array([ct.iloc[0][0:5].values, ct.iloc[1][0:5].values])stats.chi2_contingency(obs)[0:3]--------------------------------------------------------------------(3.0739613982367193, 0.5455253376565949, 4)
The p-value is over 0.5, so at the significance level of 0.05, we fail to reject that there is no relationship between ‘Attrition’ and ‘Education’.
Break Down the Analysis by Department
We can also check if a significant relationship exists breaking down by department. For example, we know there is a significant relationship between ‘Attrition’ and ‘WorkLifeBalance’ but we want to examine if that is agnostic to departments. First, let’s see what are the departments and the number of employees in each of them:
data['Department'].value_counts()--------------------------------------------------------------------Research & Development 961Sales 446Human Resources 63Name: Department, dtype: int64
To ensure enough samples for the Chi-square test, we will only focus on R&D and Sales in this analysis.
alpha = 0.05for i in dep_counts.index[0:2]: sub_data = data[data.Department == i] ct = pd.crosstab(sub_data.Attrition, sub_data.WorkLifeBalance, margins=True) obs = np.array([ct.iloc[0][0:4].values,ct.iloc[1][0:4].values]) print("For " + i + ": ") print(ct) print('With an alpha value of {}:'.format(alpha)) if stats.chi2_contingency(obs)[1] <= alpha: print("Dependent relationship between Attrition and Work Life Balance") else: print("Independent relationship between Attrition and Work Life Balance") print("")--------------------------------------------------------------------For Research & Development: WorkLifeBalance 1 2 3 4 AllAttrition No 41 203 507 77 828Yes 19 32 68 14 133All 60 235 575 91 961With an alpha value of 0.05:Dependent relationship between Attrition and Work Life BalanceFor Sales: WorkLifeBalance 1 2 3 4 AllAttrition No 10 78 226 40 354Yes 6 24 50 12 92All 16 102 276 52 446With an alpha value of 0.05:Independent relationship between Attrition and Work Life Balance
From these output, we can see that there is a significant relationship in the R&D department, but not in the Sales department.
There are a few caveats when conducting this analysis as well as some limitations of this test:
In order to draw a meaningful conclusion, the number of samples in each scenario needs to be sufficiently large, which might not be the case in reality.A significant relationship does not imply causality.The Chi-square test itself does not provide additional insights besides ‘significant relationship or not’. For example, the test does not inform that as job satisfaction increases, the proportion of employees who leave the company tends to decrease.
In order to draw a meaningful conclusion, the number of samples in each scenario needs to be sufficiently large, which might not be the case in reality.
A significant relationship does not imply causality.
The Chi-square test itself does not provide additional insights besides ‘significant relationship or not’. For example, the test does not inform that as job satisfaction increases, the proportion of employees who leave the company tends to decrease.
Let’s quickly recap.
We performed a Chi-square test for independence to examine the relationship between variables in the IBM HR Analytics dataset. We discussed two ways to do it in Python, both from scratch and using SciPy. Last, we showed that when a significant relationship exists, we can also stratify it and check if it is true for each level.
I hope you enjoyed this blog post and please share any thoughts that you may have :)
Check out my other post on building an image classification through Streamlit and PyTorch:
towardsdatascience.com
[1] https://en.wikipedia.org/wiki/Chi-squared_test[2] https://www.kaggle.com/pavansubhasht/ibm-hr-analytics-attrition-dataset | [
{
"code": null,
"e": 289,
"s": 171,
"text": "Suppose you are exploring a dataset and you want to examine if two categorical variables are dependent on each other."
},
{
"code": null,
"e": 446,
"s": 289,
"text": "The motivation could be a better understanding of the relationship between an outcome variable and a predictor, identification of dependent predictors, etc."
},
{
"code": null,
"e": 516,
"s": 446,
"text": "In this case, a Chi-square test can be an effective statistical tool."
},
{
"code": null,
"e": 711,
"s": 516,
"text": "In this post, I will discuss how to do this test in Python (both from scratch and using SciPy) with examples on a popular HR analytics dataset — the IBM Employee Attrition & Performance dataset."
},
{
"code": null,
"e": 909,
"s": 711,
"text": "What is Chi-square test?What are the categorical variables that we want to examine?How to perform this test from scratch?Is there a shortcut to do this?What else can we do?What are the limitations?"
},
{
"code": null,
"e": 934,
"s": 909,
"text": "What is Chi-square test?"
},
{
"code": null,
"e": 994,
"s": 934,
"text": "What are the categorical variables that we want to examine?"
},
{
"code": null,
"e": 1033,
"s": 994,
"text": "How to perform this test from scratch?"
},
{
"code": null,
"e": 1065,
"s": 1033,
"text": "Is there a shortcut to do this?"
},
{
"code": null,
"e": 1086,
"s": 1065,
"text": "What else can we do?"
},
{
"code": null,
"e": 1112,
"s": 1086,
"text": "What are the limitations?"
},
{
"code": null,
"e": 1379,
"s": 1112,
"text": "Chi-square test is a statistical hypothesis test to perform when the test statistic is Chi-square distributed under the null hypothesis and particularly the Chi-square test for independence is often used to examine independence between two categorical variables [1]."
},
{
"code": null,
"e": 1532,
"s": 1379,
"text": "The key assumptions associated with this test are: 1. random sample from the population. 2. each subject cannot be in more than 1 group in any variable."
},
{
"code": null,
"e": 1835,
"s": 1532,
"text": "To better illustrate this test, I have chosen the IBM HR dataset from Kaggle (link), which includes a sample of employee HR information regarding attrition, work satisfaction, performance, etc. People often use it to uncover insights about the relationship between employee attrition and other factors."
},
{
"code": null,
"e": 1910,
"s": 1835,
"text": "Note that this is a fictional data set created by IBM data scientists [2]."
},
{
"code": null,
"e": 1967,
"s": 1910,
"text": "To see the full Python code, check out my Kaggle kernel."
},
{
"code": null,
"e": 2014,
"s": 1967,
"text": "Without further ado, let’s get to the details!"
},
{
"code": null,
"e": 2090,
"s": 2014,
"text": "Let’s first check out the number of employees and the number of attributes:"
},
{
"code": null,
"e": 2179,
"s": 2090,
"text": "data.shape--------------------------------------------------------------------(1470, 35)"
},
{
"code": null,
"e": 2223,
"s": 2179,
"text": "There are 1470 employees and 35 attributes."
},
{
"code": null,
"e": 2336,
"s": 2223,
"text": "Next, we can check what these attributes are and see if there is any missing value associated with each of them:"
},
{
"code": null,
"e": 3588,
"s": 2336,
"text": "data.isna().any()--------------------------------------------------------------------Age FalseAttrition FalseBusinessTravel FalseDailyRate FalseDepartment FalseDistanceFromHome FalseEducation FalseEducationField FalseEmployeeCount FalseEmployeeNumber FalseEnvironmentSatisfaction FalseGender FalseHourlyRate FalseJobInvolvement FalseJobLevel FalseJobRole FalseJobSatisfaction FalseMaritalStatus FalseMonthlyIncome FalseMonthlyRate FalseNumCompaniesWorked FalseOver18 FalseOverTime FalsePercentSalaryHike FalsePerformanceRating FalseRelationshipSatisfaction FalseStandardHours FalseStockOptionLevel FalseTotalWorkingYears FalseTrainingTimesLastYear FalseWorkLifeBalance FalseYearsAtCompany FalseYearsInCurrentRole FalseYearsSinceLastPromotion FalseYearsWithCurrManager Falsedtype: bool"
},
{
"code": null,
"e": 3619,
"s": 3588,
"text": "Identify Categorical Variables"
},
{
"code": null,
"e": 3716,
"s": 3619,
"text": "Suppose we want to examine if there is a relationship between ‘Attrition’ and ‘JobSatisfaction’."
},
{
"code": null,
"e": 3762,
"s": 3716,
"text": "Counts for the two categories of ‘Attrition’:"
},
{
"code": null,
"e": 3914,
"s": 3762,
"text": "data['Attrition'].value_counts()--------------------------------------------------------------------No 1233Yes 237Name: Attrition, dtype: int64"
},
{
"code": null,
"e": 3988,
"s": 3914,
"text": "Counts for the four categories of ‘JobSatisfaction’ ordered by frequency:"
},
{
"code": null,
"e": 4162,
"s": 3988,
"text": "data['JobSatisfaction'].value_counts()--------------------------------------------------------------------4 4593 4421 2892 280Name: JobSatisfaction, dtype: int64"
},
{
"code": null,
"e": 4257,
"s": 4162,
"text": "Note that for ‘JobSatisfaction’, 1 is ‘Low’, 2 is ‘Medium’, 3 is ‘High’, and 4 is ‘Very High’."
},
{
"code": null,
"e": 4298,
"s": 4257,
"text": "Null Hypothesis and Alternate Hypothesis"
},
{
"code": null,
"e": 4453,
"s": 4298,
"text": "For our Chi-square test for independence here, the null hypothesis is that there is no significant relationship between ‘Attrition’ and ‘JobSatisfaction’."
},
{
"code": null,
"e": 4565,
"s": 4453,
"text": "The alternative hypothesis is that there is significant relationship between ‘Attrition’ and ‘JobSatisfaction’."
},
{
"code": null,
"e": 4583,
"s": 4565,
"text": "Contingency Table"
},
{
"code": null,
"e": 4682,
"s": 4583,
"text": "In order to compute the Chi-square test statistic, we would need to construct a contingency table."
},
{
"code": null,
"e": 4740,
"s": 4682,
"text": "We can do that using the ‘crosstab’ function from pandas:"
},
{
"code": null,
"e": 4804,
"s": 4740,
"text": "pd.crosstab(data.Attrition, data.JobSatisfaction, margins=True)"
},
{
"code": null,
"e": 5064,
"s": 4804,
"text": "The numbers in this table represent frequencies. For example, the ‘46’ shown under both ‘2’ in ‘JobSatisfaction’ and ‘Yes’ in ‘Attrition’ means that out of the 1470 employees, 46 of them rated their job satisfaction as ‘Medium’ and they did leave the company."
},
{
"code": null,
"e": 5085,
"s": 5064,
"text": "Chi-square Statistic"
},
{
"code": null,
"e": 5164,
"s": 5085,
"text": "The formula for calculating the Chi-square statistic (X2) is shown as follows:"
},
{
"code": null,
"e": 5210,
"s": 5164,
"text": "X2 = sum of [(observed-expected)2 / expected]"
},
{
"code": null,
"e": 5380,
"s": 5210,
"text": "The term ‘observed’ refers to the numbers we have seen in the contingency table, and the term ‘expected’ refers to the expected numbers when the null hypothesis is true."
},
{
"code": null,
"e": 5819,
"s": 5380,
"text": "Under the null hypothesis, there is no significant relationship between ‘Attrition’ and ‘JobSatisfaction’, which means the percentage of attrition should be consistent across the four categories of job satisfaction. As an example, the expected frequency for ‘4’ and ‘Attrition’ should be the number of employees that rate their job satisfactions as ‘Very High’ * (total attrition/total employee count), which is 459*237/1470, or about 74."
},
{
"code": null,
"e": 5897,
"s": 5819,
"text": "Let’s compute all the expected numbers and store them in a list called ‘exp’:"
},
{
"code": null,
"e": 6285,
"s": 5897,
"text": "row_sum = ct.iloc[0:2,4].valuesexp = []for j in range(2): for val in ct.iloc[2,0:4].values: exp.append(val * row_sum[j] / ct.loc['All', 'All'])print(exp)--------------------------------------------------------------------[242.4061224489796, 234.85714285714286, 370.7387755102041, 384.99795918367346, 46.593877551020405, 45.142857142857146, 71.26122448979592, 74.00204081632653]"
},
{
"code": null,
"e": 6356,
"s": 6285,
"text": "Note that the last term (74) verifies that our calculation is correct."
},
{
"code": null,
"e": 6379,
"s": 6356,
"text": "Now we can compute X2:"
},
{
"code": null,
"e": 6489,
"s": 6379,
"text": "((obs - exp)**2/exp).sum()--------------------------------------------------------------------17.505077010348"
},
{
"code": null,
"e": 6507,
"s": 6489,
"text": "Degree of Freedom"
},
{
"code": null,
"e": 6728,
"s": 6507,
"text": "One parameter we need apart from X2 is the degree of freedom, which is computed as (number of categories in the first variable-1)*(number of categories in the second variable-1), and it is (2–1)*(4–1) in this case, or 3."
},
{
"code": null,
"e": 6845,
"s": 6728,
"text": "(len(row_sum)-1)*(len(ct.iloc[2,0:4].values)-1)--------------------------------------------------------------------3"
},
{
"code": null,
"e": 6860,
"s": 6845,
"text": "Interpretation"
},
{
"code": null,
"e": 7076,
"s": 6860,
"text": "With both X2 and degrees of freedom, we can use a Chi-square table/calculator to determine its corresponding p-value and conclude if there is a significant relationship given a specified significance level of alpha."
},
{
"code": null,
"e": 7434,
"s": 7076,
"text": "In another word, given the degrees of freedom, we know that the ‘observed’ should be close to ‘expected’ under the null hypothesis which means X2 should be reasonably small. When X2 is larger than a threshold, we know the p-value (probability of having a such as large X2 given the null hypothesis) is extremely low, and we would reject the null hypothesis."
},
{
"code": null,
"e": 7484,
"s": 7434,
"text": "In Python, we can compute the p-value as follows:"
},
{
"code": null,
"e": 7610,
"s": 7484,
"text": "1 - stats.chi2.cdf(chi_sq_stats, dof)--------------------------------------------------------------------0.000556300451038716"
},
{
"code": null,
"e": 7750,
"s": 7610,
"text": "Suppose the significance level is 0.05. We can conclude that there is a significant relationship between ‘Attrition’ and ‘JobSatisfaction’."
},
{
"code": null,
"e": 7762,
"s": 7750,
"text": "Using SciPy"
},
{
"code": null,
"e": 7865,
"s": 7762,
"text": "There is a shortcut to perform this test in Python, which leverages the SciPy library (documentation)."
},
{
"code": null,
"e": 8090,
"s": 7865,
"text": "obs = np.array([ct.iloc[0][0:4].values, ct.iloc[1][0:4].values])stats.chi2_contingency(obs)[0:3]--------------------------------------------------------------------(17.505077010348, 0.0005563004510387556, 3)"
},
{
"code": null,
"e": 8252,
"s": 8090,
"text": "Note that the three terms are X2 statistic, p-value, and degree of freedom, respectively. These results are consistent with the ones we computed by hand earlier."
},
{
"code": null,
"e": 8280,
"s": 8252,
"text": "‘Attrition’ and ‘Education’"
},
{
"code": null,
"e": 8511,
"s": 8280,
"text": "It is somewhat intuitive that whether the employee leaves the company is related to the job satisfaction. Now let’s look at another example where we examine if there is significant relationship between ‘Attrition’ and ‘Education’:"
},
{
"code": null,
"e": 8798,
"s": 8511,
"text": "ct = pd.crosstab(data.Attrition, data.Education, margins=True)obs = np.array([ct.iloc[0][0:5].values, ct.iloc[1][0:5].values])stats.chi2_contingency(obs)[0:3]--------------------------------------------------------------------(3.0739613982367193, 0.5455253376565949, 4)"
},
{
"code": null,
"e": 8946,
"s": 8798,
"text": "The p-value is over 0.5, so at the significance level of 0.05, we fail to reject that there is no relationship between ‘Attrition’ and ‘Education’."
},
{
"code": null,
"e": 8984,
"s": 8946,
"text": "Break Down the Analysis by Department"
},
{
"code": null,
"e": 9313,
"s": 8984,
"text": "We can also check if a significant relationship exists breaking down by department. For example, we know there is a significant relationship between ‘Attrition’ and ‘WorkLifeBalance’ but we want to examine if that is agnostic to departments. First, let’s see what are the departments and the number of employees in each of them:"
},
{
"code": null,
"e": 9532,
"s": 9313,
"text": "data['Department'].value_counts()--------------------------------------------------------------------Research & Development 961Sales 446Human Resources 63Name: Department, dtype: int64"
},
{
"code": null,
"e": 9636,
"s": 9532,
"text": "To ensure enough samples for the Chi-square test, we will only focus on R&D and Sales in this analysis."
},
{
"code": null,
"e": 10860,
"s": 9636,
"text": "alpha = 0.05for i in dep_counts.index[0:2]: sub_data = data[data.Department == i] ct = pd.crosstab(sub_data.Attrition, sub_data.WorkLifeBalance, margins=True) obs = np.array([ct.iloc[0][0:4].values,ct.iloc[1][0:4].values]) print(\"For \" + i + \": \") print(ct) print('With an alpha value of {}:'.format(alpha)) if stats.chi2_contingency(obs)[1] <= alpha: print(\"Dependent relationship between Attrition and Work Life Balance\") else: print(\"Independent relationship between Attrition and Work Life Balance\") print(\"\")--------------------------------------------------------------------For Research & Development: WorkLifeBalance 1 2 3 4 AllAttrition No 41 203 507 77 828Yes 19 32 68 14 133All 60 235 575 91 961With an alpha value of 0.05:Dependent relationship between Attrition and Work Life BalanceFor Sales: WorkLifeBalance 1 2 3 4 AllAttrition No 10 78 226 40 354Yes 6 24 50 12 92All 16 102 276 52 446With an alpha value of 0.05:Independent relationship between Attrition and Work Life Balance"
},
{
"code": null,
"e": 10987,
"s": 10860,
"text": "From these output, we can see that there is a significant relationship in the R&D department, but not in the Sales department."
},
{
"code": null,
"e": 11083,
"s": 10987,
"text": "There are a few caveats when conducting this analysis as well as some limitations of this test:"
},
{
"code": null,
"e": 11537,
"s": 11083,
"text": "In order to draw a meaningful conclusion, the number of samples in each scenario needs to be sufficiently large, which might not be the case in reality.A significant relationship does not imply causality.The Chi-square test itself does not provide additional insights besides ‘significant relationship or not’. For example, the test does not inform that as job satisfaction increases, the proportion of employees who leave the company tends to decrease."
},
{
"code": null,
"e": 11690,
"s": 11537,
"text": "In order to draw a meaningful conclusion, the number of samples in each scenario needs to be sufficiently large, which might not be the case in reality."
},
{
"code": null,
"e": 11743,
"s": 11690,
"text": "A significant relationship does not imply causality."
},
{
"code": null,
"e": 11993,
"s": 11743,
"text": "The Chi-square test itself does not provide additional insights besides ‘significant relationship or not’. For example, the test does not inform that as job satisfaction increases, the proportion of employees who leave the company tends to decrease."
},
{
"code": null,
"e": 12014,
"s": 11993,
"text": "Let’s quickly recap."
},
{
"code": null,
"e": 12343,
"s": 12014,
"text": "We performed a Chi-square test for independence to examine the relationship between variables in the IBM HR Analytics dataset. We discussed two ways to do it in Python, both from scratch and using SciPy. Last, we showed that when a significant relationship exists, we can also stratify it and check if it is true for each level."
},
{
"code": null,
"e": 12428,
"s": 12343,
"text": "I hope you enjoyed this blog post and please share any thoughts that you may have :)"
},
{
"code": null,
"e": 12519,
"s": 12428,
"text": "Check out my other post on building an image classification through Streamlit and PyTorch:"
},
{
"code": null,
"e": 12542,
"s": 12519,
"text": "towardsdatascience.com"
}
]
|
Exceptionally odd | Practice | GeeksforGeeks | Given an array of N positive integers where all numbers occur even number of times except one number which occurs odd number of times. Find the exceptional number.
Example 1:
Input:
N = 7
Arr[] = {1, 2, 3, 2, 3, 1, 3}
Output: 3
Example 2:
Input:
N = 7
Arr[] = {5, 7, 2, 7, 5, 2, 5}
Output: 5
Your Task:
You don't need to read input or print anything. Your task is to complete the function getOddOccurrence() which takes arr[] and n as input parameters and returns the exceptional number.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 105
1 ≤ arr[i] ≤ 106
0
rahulvishwas26022 days ago
sort(arr,arr+n); int count=1; for(int i=0;i<n;i++){ if(arr[i]==arr[i+1]){ count++; } else{ if(count%2==0){ count=1; continue; } else { return arr[i]; } } }
0
mehraparthak02 days ago
int getOddOccurence(int arr[],int n) {
int xorsum=0;
for(int i=0;i<n;i++){
xorsum=xorsum^arr[i];
}
return xorsum;
}
+1
harshscode5 days ago
map<int,int> m; for(int i=0;i<n;i++) m[arr[i]]++; for(auto i:m) if((i.second%2!=0)) return i.first;
0
yadavashish8828441 week ago
Fast and Easy Bit Manipulation
int xor = 0; for(int i : arr){ xor = xor ^ i; } return xor;
0
kerim21 week ago
Javascript - fast solution 0.33sTime Complexity: O(n)
getOddOccurrence(arr,n){
//code here
var hashMap = {};
for(let i = 0; i < n; i++){
hashMap[arr[i]]? delete hashMap[arr[i]] : hashMap[arr[i]]=1;
}
return Object.keys(hashMap)[0];
}
0
atif836142 weeks ago
JAVA SOLUTION :
class Solution {
int getOddOccurrence(int[] arr, int n) {
if(n==0){
return 0;
}
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<n;i++){
if(map.containsKey(arr[i])){
int val=map.get(arr[i]);
map.put(arr[i],val+1);
}
else{
map.put(arr[i],1);
}
}
for(Integer a: map.keySet()){
if(map.get(a)%2!=0){
return a;
}
}
return -1;
}
}
+1
harshneolia3 weeks ago
class Solution{ public: int getOddOccurrence(int arr[], int n) { int x=0; for(int i=0; i<n;++i) { x = x^arr[i]; } return x; }};
+1
mohitsalvi1 month ago
class Solution{ public: int getOddOccurrence(int arr[], int n) { unordered_map<int,int> mp; for(int i=0;i<n;i++){ mp[arr[i]]++; } for(int i=0;i<n;i++){ if(mp[arr[i]]%2!=0){ return arr[i]; } } }};
0
dabhideep441 month ago
// 0.9 seconds
int getOddOccurrence(int[] arr, int n) { Arrays.sort(arr); for (int i = 0; i < n; i++) { if (i < n - 1) { if (arr[i] != arr[i + 1]) { return arr[i]; } else { i++; } } else { return arr[n - 1]; } } return -1; }
0
hasnainraza1998hr1 month ago
int getOddOccurrence(int arr[], int n) { int oddValue = 0; for(int i=0;i<n;i++){ oddValue ^= arr[i]; } return oddValue; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 402,
"s": 238,
"text": "Given an array of N positive integers where all numbers occur even number of times except one number which occurs odd number of times. Find the exceptional number."
},
{
"code": null,
"e": 413,
"s": 402,
"text": "Example 1:"
},
{
"code": null,
"e": 468,
"s": 413,
"text": "Input:\nN = 7\nArr[] = {1, 2, 3, 2, 3, 1, 3}\nOutput: 3\n\n"
},
{
"code": null,
"e": 479,
"s": 468,
"text": "Example 2:"
},
{
"code": null,
"e": 534,
"s": 479,
"text": "Input:\nN = 7\nArr[] = {5, 7, 2, 7, 5, 2, 5}\nOutput: 5\n\n"
},
{
"code": null,
"e": 730,
"s": 534,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function getOddOccurrence() which takes arr[] and n as input parameters and returns the exceptional number."
},
{
"code": null,
"e": 793,
"s": 730,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 836,
"s": 793,
"text": "\nConstraints:\n1 ≤ N ≤ 105\n1 ≤ arr[i] ≤ 106"
},
{
"code": null,
"e": 840,
"s": 838,
"text": "0"
},
{
"code": null,
"e": 867,
"s": 840,
"text": "rahulvishwas26022 days ago"
},
{
"code": null,
"e": 1229,
"s": 867,
"text": " sort(arr,arr+n); int count=1; for(int i=0;i<n;i++){ if(arr[i]==arr[i+1]){ count++; } else{ if(count%2==0){ count=1; continue; } else { return arr[i]; } } } "
},
{
"code": null,
"e": 1231,
"s": 1229,
"text": "0"
},
{
"code": null,
"e": 1255,
"s": 1231,
"text": "mehraparthak02 days ago"
},
{
"code": null,
"e": 1294,
"s": 1255,
"text": "int getOddOccurence(int arr[],int n) {"
},
{
"code": null,
"e": 1308,
"s": 1294,
"text": "int xorsum=0;"
},
{
"code": null,
"e": 1330,
"s": 1308,
"text": "for(int i=0;i<n;i++){"
},
{
"code": null,
"e": 1352,
"s": 1330,
"text": "xorsum=xorsum^arr[i];"
},
{
"code": null,
"e": 1354,
"s": 1352,
"text": "}"
},
{
"code": null,
"e": 1369,
"s": 1354,
"text": "return xorsum;"
},
{
"code": null,
"e": 1371,
"s": 1369,
"text": "}"
},
{
"code": null,
"e": 1374,
"s": 1371,
"text": "+1"
},
{
"code": null,
"e": 1395,
"s": 1374,
"text": "harshscode5 days ago"
},
{
"code": null,
"e": 1532,
"s": 1395,
"text": " map<int,int> m; for(int i=0;i<n;i++) m[arr[i]]++; for(auto i:m) if((i.second%2!=0)) return i.first;"
},
{
"code": null,
"e": 1534,
"s": 1532,
"text": "0"
},
{
"code": null,
"e": 1562,
"s": 1534,
"text": "yadavashish8828441 week ago"
},
{
"code": null,
"e": 1593,
"s": 1562,
"text": "Fast and Easy Bit Manipulation"
},
{
"code": null,
"e": 1681,
"s": 1593,
"text": "int xor = 0; for(int i : arr){ xor = xor ^ i; } return xor;"
},
{
"code": null,
"e": 1683,
"s": 1681,
"text": "0"
},
{
"code": null,
"e": 1700,
"s": 1683,
"text": "kerim21 week ago"
},
{
"code": null,
"e": 1754,
"s": 1700,
"text": "Javascript - fast solution 0.33sTime Complexity: O(n)"
},
{
"code": null,
"e": 1958,
"s": 1756,
"text": "getOddOccurrence(arr,n){\n //code here\n var hashMap = {};\n for(let i = 0; i < n; i++){\n hashMap[arr[i]]? delete hashMap[arr[i]] : hashMap[arr[i]]=1;\n }\n return Object.keys(hashMap)[0];\n}"
},
{
"code": null,
"e": 1960,
"s": 1958,
"text": "0"
},
{
"code": null,
"e": 1981,
"s": 1960,
"text": "atif836142 weeks ago"
},
{
"code": null,
"e": 1997,
"s": 1981,
"text": "JAVA SOLUTION :"
},
{
"code": null,
"e": 2553,
"s": 1997,
"text": "class Solution {\n int getOddOccurrence(int[] arr, int n) {\n if(n==0){\n return 0;\n }\n HashMap<Integer,Integer> map=new HashMap<>();\n for(int i=0;i<n;i++){\n if(map.containsKey(arr[i])){\n int val=map.get(arr[i]);\n map.put(arr[i],val+1);\n }\n else{\n map.put(arr[i],1);\n }\n }\n for(Integer a: map.keySet()){\n if(map.get(a)%2!=0){\n return a;\n }\n }\n return -1;\n }\n}"
},
{
"code": null,
"e": 2556,
"s": 2553,
"text": "+1"
},
{
"code": null,
"e": 2579,
"s": 2556,
"text": "harshneolia3 weeks ago"
},
{
"code": null,
"e": 2762,
"s": 2579,
"text": "class Solution{ public: int getOddOccurrence(int arr[], int n) { int x=0; for(int i=0; i<n;++i) { x = x^arr[i]; } return x; }};"
},
{
"code": null,
"e": 2765,
"s": 2762,
"text": "+1"
},
{
"code": null,
"e": 2787,
"s": 2765,
"text": "mohitsalvi1 month ago"
},
{
"code": null,
"e": 3077,
"s": 2787,
"text": "class Solution{ public: int getOddOccurrence(int arr[], int n) { unordered_map<int,int> mp; for(int i=0;i<n;i++){ mp[arr[i]]++; } for(int i=0;i<n;i++){ if(mp[arr[i]]%2!=0){ return arr[i]; } } }};"
},
{
"code": null,
"e": 3079,
"s": 3077,
"text": "0"
},
{
"code": null,
"e": 3102,
"s": 3079,
"text": "dabhideep441 month ago"
},
{
"code": null,
"e": 3117,
"s": 3102,
"text": "// 0.9 seconds"
},
{
"code": null,
"e": 3475,
"s": 3117,
"text": "int getOddOccurrence(int[] arr, int n) { Arrays.sort(arr); for (int i = 0; i < n; i++) { if (i < n - 1) { if (arr[i] != arr[i + 1]) { return arr[i]; } else { i++; } } else { return arr[n - 1]; } } return -1; }"
},
{
"code": null,
"e": 3477,
"s": 3475,
"text": "0"
},
{
"code": null,
"e": 3506,
"s": 3477,
"text": "hasnainraza1998hr1 month ago"
},
{
"code": null,
"e": 3664,
"s": 3506,
"text": "int getOddOccurrence(int arr[], int n) { int oddValue = 0; for(int i=0;i<n;i++){ oddValue ^= arr[i]; } return oddValue; }"
},
{
"code": null,
"e": 3810,
"s": 3664,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 3846,
"s": 3810,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3856,
"s": 3846,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3866,
"s": 3856,
"text": "\nContest\n"
},
{
"code": null,
"e": 3929,
"s": 3866,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4077,
"s": 3929,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 4285,
"s": 4077,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 4391,
"s": 4285,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Escape sequences in Java | A character preceded by a backslash (\) is an escape sequence and has a special meaning to the compiler.
The following table shows the Java escape sequences.
Let us see an example of Character Escape Sequences in Java.
Live Demo
public class Demo {
public static void main(String[] args) {
char ch = '\u039A';
System.out.println(ch);
}
}
K | [
{
"code": null,
"e": 1167,
"s": 1062,
"text": "A character preceded by a backslash (\\) is an escape sequence and has a special meaning to the compiler."
},
{
"code": null,
"e": 1220,
"s": 1167,
"text": "The following table shows the Java escape sequences."
},
{
"code": null,
"e": 1281,
"s": 1220,
"text": "Let us see an example of Character Escape Sequences in Java."
},
{
"code": null,
"e": 1292,
"s": 1281,
"text": " Live Demo"
},
{
"code": null,
"e": 1419,
"s": 1292,
"text": "public class Demo {\n public static void main(String[] args) {\n char ch = '\\u039A';\n System.out.println(ch);\n }\n}"
},
{
"code": null,
"e": 1421,
"s": 1419,
"text": "K"
}
]
|
Bootstrap 3 truncate long text inside rows of a table in a responsive way with HTML | To truncate long texts inside rows of a table, use the following CSS −
.table td.demo {
max-width: 177px;
}
.table td.demo span {
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
white-space: nowrap;
max-width: 100%;
}
The following is the HTML −
<td class = "demo">
<span>This is demo text and we have made it a long text for a demo.</span>
</td> | [
{
"code": null,
"e": 1133,
"s": 1062,
"text": "To truncate long texts inside rows of a table, use the following CSS −"
},
{
"code": null,
"e": 1316,
"s": 1133,
"text": ".table td.demo {\n max-width: 177px;\n}\n.table td.demo span {\n overflow: hidden;\n text-overflow: ellipsis;\n display: inline-block;\n white-space: nowrap;\n max-width: 100%;\n}"
},
{
"code": null,
"e": 1344,
"s": 1316,
"text": "The following is the HTML −"
},
{
"code": null,
"e": 1448,
"s": 1344,
"text": "<td class = \"demo\">\n <span>This is demo text and we have made it a long text for a demo.</span>\n</td>"
}
]
|
MySQL: How to Write a Query That Returns the Top Records in a Group | by Casey McMullen | Towards Data Science | This article will show you a simple query example in MySQL 5.7 (along with an example using the rank() function in MySQL 8.0) that will return the top 3 orders per month out of an orders table.
If you’ve ever wanted to write a query that returns the top n number of records out of a group or category, you’ve come to the right place. Over time I’ve needed this type of query every once in a while, and I always wind up with either an overly complex multi-query union effort, or just iterate through a result set in code. Both methods are highly inefficient and (now in retrospect) silly.
In my quest to learn new database query techniques I’ve come across the rank() function in MySQL 8.0 which makes this effort incredibly simple. But there’s an equally simple technique you can use in MySQL 5.7 and earlier that provides a solution to this common conundrum.
Let’s jump right into the example.
First we’re going to build a sample database table for our example. It’s a simple orders table that spans three different customers over four months. It includes an ordered GUID as the primary key and contains an order number, customer number, customer name, order date and order amount.
We’ll use this same table in both of our MySQL version examples:
CREATE TABLE orders( id BINARY(16), order_number INT, customer_number INT, customer_name VARCHAR(90), order_date DATE, order_amount DECIMAL(13,2), PRIMARY KEY (`id`)); INSERT INTO orders VALUES (UNHEX(‘11E92BDEA738CEB7B78E0242AC110002’), 100, 5001, ‘Wayne Enterprises’, ‘2018–11–14’, 100.00), (UNHEX(‘11E92BDEA73910BBB78E0242AC110002’), 101, 6002, ‘Star Labs’, ‘2018–11–15’, 200.00), (UNHEX(‘11E92BDEA7395C95B78E0242AC110002’), 102, 7003, ‘Daily Planet’, ‘2018–11–15’, 150.00), (UNHEX(‘11E92BDEA739A057B78E0242AC110002’), 103, 5001, ‘Wayne Enterprises’, ‘2018–11–21’, 110.00), (UNHEX(‘11E92BDEA739F892B78E0242AC110002’), 104, 6002, ‘Star Labs’, ‘2018–11–22’, 175.00), (UNHEX(‘11E92BE00BADD97CB78E0242AC110002’), 105, 6002, ‘Star Labs’, ‘2018–11–23’, 117.00), (UNHEX(‘11E92BE00BAE15ACB78E0242AC110002’), 106, 7003, ‘Daily Planet’, ‘2018–11–24’, 255.00), (UNHEX(‘11E92BE00BAE59FEB78E0242AC110002’), 107, 5001, ‘Wayne Enterprises’, ‘2018–12–07’, 321.00), (UNHEX(‘11E92BE00BAE9D7EB78E0242AC110002’), 108, 6002, ‘Star Labs’, ‘2018–12–14’, 55.00), (UNHEX(‘11E92BE00BAED1A4B78E0242AC110002’), 109, 7003, ‘Daily Planet’, ‘2018–12–15’, 127.00), (UNHEX(‘11E92BE021E2DF22B78E0242AC110002’), 110, 6002, ‘Star Labs’, ‘2018–12–15’, 133.00), (UNHEX(‘11E92BE021E31638B78E0242AC110002’), 111, 5001, ‘Wayne Enterprises’, ‘2018–12–17’, 145.00), (UNHEX(‘11E92BE021E35474B78E0242AC110002’), 112, 7003, ‘Daily Planet’, ‘2018–12–21’, 111.00), (UNHEX(‘11E92BE021E39950B78E0242AC110002’), 113, 6002, ‘Star Labs’, ‘2018–12–31’, 321.00), (UNHEX(‘11E92BE021E3CEC5B78E0242AC110002’), 114, 6002, ‘Star Labs’, ‘2019–01–03’, 223.00), (UNHEX(‘11E92BE035EF4BE5B78E0242AC110002’), 115, 6002, ‘Star Labs’, ‘2019–01–05’, 179.00), (UNHEX(‘11E92BE035EF970DB78E0242AC110002’), 116, 5001, ‘Wayne Enterprises’, ‘2019–01–14’, 180.00), (UNHEX(‘11E92BE035EFD540B78E0242AC110002’), 117, 7003, ‘Daily Planet’, ‘2019–01–21’, 162.00), (UNHEX(‘11E92BE035F01B8AB78E0242AC110002’), 118, 5001, ‘Wayne Enterprises’, ‘2019–02–02’, 133.00), (UNHEX(‘11E92BE035F05EF0B78E0242AC110002’), 119, 7003, ‘Daily Planet’, ‘2019–02–05’, 55.00), (UNHEX(‘11E92BE0480B3CBAB78E0242AC110002’), 120, 5001, ‘Wayne Enterprises’, ‘2019–02–08’, 25.00), (UNHEX(‘11E92BE25A9A3D6DB78E0242AC110002’), 121, 6002, ‘Star Labs’, ‘2019–02–08’, 222.00);
The rank() function is pretty cool, but it’s not available prior to MySQL 8.0. Therefore we’ll need to write a creative nested query to rank our records and provide the results.
We’re going to start by writing a query that ranks all of the records in our table in order of year, month and order amount in descending sequence (so that the largest orders get the lowest scores).
SELECT order_number, customer_number, customer_name, order_date, YEAR(order_date) AS order_year, MONTH(order_date) AS order_month, order_amount, @order_rank := IF(@current_month = MONTH(order_date), @order_rank + 1, 1) AS order_rank, @current_month := MONTH(order_date) FROM ordersORDER BY order_year, order_month, order_amount DESC;
In our example SELECT statement we’re getting all the fields from the table along with getting the YEAR from the order date as well as the MONTH. Since our goal is to rank the orders by month I’m creating a temporary MySQL variable called @current_month that will keep track of each month. On every change of month we reset the @order_rank variable to one, otherwise we increment by one.
** Note ** using the := operand allows us to create a variable on the fly without requiring the SET command.
** 2nd Note ** keep in mind this SELECT statement will rank all of the records in our table. Normally you’d want to have a WHERE clause that limits the size of the result set. Perhaps by customer or date range.
The query above produces a result set that looks like this:
You can see that the orders are sorted by year and month and then by order amount in descending sequence. The new order_rank column is included that ranks every order in 1–2–3 sequence by month.
Now we can include this query as a subquery to a SELECT that only pulls the top 3 orders out of every group. That final query looks like this:
SELECT customer_number, customer_name, order_number, order_date, order_amount FROM (SELECT order_number, customer_number, customer_name, order_date, YEAR(order_date) AS order_year, MONTH(order_date) AS order_month, order_amount, @order_rank := IF(@current_month = MONTH(order_date), @order_rank + 1, 1) AS order_rank, @current_month := MONTH(order_date) FROM orders ORDER BY order_year, order_month, order_amount DESC) ranked_orders WHERE order_rank <= 3;
With our ranking query as the subquery, we only need to pull out the final fields that we need for reporting. A WHERE clause is added that only pulls records with a rank of 3 or less. Our final result set is shown below:
You can see in the results that we got the top 3 orders out of every month.
MySQL 8.0 introduces a rank() function that adds some additional functionality for ranking records in a result set. With the rank() function the result set is partitioned by a value that you specify, then a rank is assigned to each row within each partition. Ties are given the same rank and the subsequent new number is given a rank of one plus the number of ranked records before it.
Our ranking query with this new feature looks like this:
SELECT order_number, customer_number, customer_name, order_date, YEAR(order_date) AS order_year, MONTH(order_date) AS order_month, order_amount, RANK() OVER ( PARTITION BY YEAR(order_date), MONTH(order_date)ORDER BY YEAR(order_date), MONTH(order_date), order_amount DESC) order_value_rankFROM orders;
This produces a result that looks like the following:
In this example you can see that in December the two greatest orders had the same amount of $321.00. The rank() function gives these two records the same rank of 1 and the subsequent record gets a rank of 3 and so on.
Like before, this ranking query is used as a subquery for our final query:
WITH ranked_orders AS ( SELECT order_number, customer_number, customer_name, order_date, YEAR(order_date) AS order_year, MONTH(order_date) AS order_month, order_amount, RANK() OVER ( PARTITION BY YEAR(order_date), MONTH(order_date) ORDER BY YEAR(order_date), MONTH(order_date), order_amount DESC) order_rank FROM orders)SELECT customer_number, customer_name, order_number, order_date, order_amount FROM ranked_ordersWHERE order_rank <= 3;
The final query is very similar to our MySQL 5.7 example, but uses some MySQL 8.0 goodness (like the availability of the WITH statement) along with more ranking capabilities that you can research in the MySQL 8.0 documentation. The final results to this query are identical to our MySQL 5.7 results in the example above.
I hope these two examples gives you some help the next time you’re wanting to get the top results out of a group.
Make sure to check out my other articles here to learn more about setting up your PHP development environment on your Mac and other coding tips and examples. | [
{
"code": null,
"e": 366,
"s": 172,
"text": "This article will show you a simple query example in MySQL 5.7 (along with an example using the rank() function in MySQL 8.0) that will return the top 3 orders per month out of an orders table."
},
{
"code": null,
"e": 760,
"s": 366,
"text": "If you’ve ever wanted to write a query that returns the top n number of records out of a group or category, you’ve come to the right place. Over time I’ve needed this type of query every once in a while, and I always wind up with either an overly complex multi-query union effort, or just iterate through a result set in code. Both methods are highly inefficient and (now in retrospect) silly."
},
{
"code": null,
"e": 1032,
"s": 760,
"text": "In my quest to learn new database query techniques I’ve come across the rank() function in MySQL 8.0 which makes this effort incredibly simple. But there’s an equally simple technique you can use in MySQL 5.7 and earlier that provides a solution to this common conundrum."
},
{
"code": null,
"e": 1067,
"s": 1032,
"text": "Let’s jump right into the example."
},
{
"code": null,
"e": 1355,
"s": 1067,
"text": "First we’re going to build a sample database table for our example. It’s a simple orders table that spans three different customers over four months. It includes an ordered GUID as the primary key and contains an order number, customer number, customer name, order date and order amount."
},
{
"code": null,
"e": 1420,
"s": 1355,
"text": "We’ll use this same table in both of our MySQL version examples:"
},
{
"code": null,
"e": 3717,
"s": 1420,
"text": "CREATE TABLE orders( id BINARY(16), order_number INT, customer_number INT, customer_name VARCHAR(90), order_date DATE, order_amount DECIMAL(13,2), PRIMARY KEY (`id`)); INSERT INTO orders VALUES (UNHEX(‘11E92BDEA738CEB7B78E0242AC110002’), 100, 5001, ‘Wayne Enterprises’, ‘2018–11–14’, 100.00), (UNHEX(‘11E92BDEA73910BBB78E0242AC110002’), 101, 6002, ‘Star Labs’, ‘2018–11–15’, 200.00), (UNHEX(‘11E92BDEA7395C95B78E0242AC110002’), 102, 7003, ‘Daily Planet’, ‘2018–11–15’, 150.00), (UNHEX(‘11E92BDEA739A057B78E0242AC110002’), 103, 5001, ‘Wayne Enterprises’, ‘2018–11–21’, 110.00), (UNHEX(‘11E92BDEA739F892B78E0242AC110002’), 104, 6002, ‘Star Labs’, ‘2018–11–22’, 175.00), (UNHEX(‘11E92BE00BADD97CB78E0242AC110002’), 105, 6002, ‘Star Labs’, ‘2018–11–23’, 117.00), (UNHEX(‘11E92BE00BAE15ACB78E0242AC110002’), 106, 7003, ‘Daily Planet’, ‘2018–11–24’, 255.00), (UNHEX(‘11E92BE00BAE59FEB78E0242AC110002’), 107, 5001, ‘Wayne Enterprises’, ‘2018–12–07’, 321.00), (UNHEX(‘11E92BE00BAE9D7EB78E0242AC110002’), 108, 6002, ‘Star Labs’, ‘2018–12–14’, 55.00), (UNHEX(‘11E92BE00BAED1A4B78E0242AC110002’), 109, 7003, ‘Daily Planet’, ‘2018–12–15’, 127.00), (UNHEX(‘11E92BE021E2DF22B78E0242AC110002’), 110, 6002, ‘Star Labs’, ‘2018–12–15’, 133.00), (UNHEX(‘11E92BE021E31638B78E0242AC110002’), 111, 5001, ‘Wayne Enterprises’, ‘2018–12–17’, 145.00), (UNHEX(‘11E92BE021E35474B78E0242AC110002’), 112, 7003, ‘Daily Planet’, ‘2018–12–21’, 111.00), (UNHEX(‘11E92BE021E39950B78E0242AC110002’), 113, 6002, ‘Star Labs’, ‘2018–12–31’, 321.00), (UNHEX(‘11E92BE021E3CEC5B78E0242AC110002’), 114, 6002, ‘Star Labs’, ‘2019–01–03’, 223.00), (UNHEX(‘11E92BE035EF4BE5B78E0242AC110002’), 115, 6002, ‘Star Labs’, ‘2019–01–05’, 179.00), (UNHEX(‘11E92BE035EF970DB78E0242AC110002’), 116, 5001, ‘Wayne Enterprises’, ‘2019–01–14’, 180.00), (UNHEX(‘11E92BE035EFD540B78E0242AC110002’), 117, 7003, ‘Daily Planet’, ‘2019–01–21’, 162.00), (UNHEX(‘11E92BE035F01B8AB78E0242AC110002’), 118, 5001, ‘Wayne Enterprises’, ‘2019–02–02’, 133.00), (UNHEX(‘11E92BE035F05EF0B78E0242AC110002’), 119, 7003, ‘Daily Planet’, ‘2019–02–05’, 55.00), (UNHEX(‘11E92BE0480B3CBAB78E0242AC110002’), 120, 5001, ‘Wayne Enterprises’, ‘2019–02–08’, 25.00), (UNHEX(‘11E92BE25A9A3D6DB78E0242AC110002’), 121, 6002, ‘Star Labs’, ‘2019–02–08’, 222.00);"
},
{
"code": null,
"e": 3895,
"s": 3717,
"text": "The rank() function is pretty cool, but it’s not available prior to MySQL 8.0. Therefore we’ll need to write a creative nested query to rank our records and provide the results."
},
{
"code": null,
"e": 4094,
"s": 3895,
"text": "We’re going to start by writing a query that ranks all of the records in our table in order of year, month and order amount in descending sequence (so that the largest orders get the lowest scores)."
},
{
"code": null,
"e": 4437,
"s": 4094,
"text": "SELECT order_number, customer_number, customer_name, order_date, YEAR(order_date) AS order_year, MONTH(order_date) AS order_month, order_amount, @order_rank := IF(@current_month = MONTH(order_date), @order_rank + 1, 1) AS order_rank, @current_month := MONTH(order_date) FROM ordersORDER BY order_year, order_month, order_amount DESC;"
},
{
"code": null,
"e": 4825,
"s": 4437,
"text": "In our example SELECT statement we’re getting all the fields from the table along with getting the YEAR from the order date as well as the MONTH. Since our goal is to rank the orders by month I’m creating a temporary MySQL variable called @current_month that will keep track of each month. On every change of month we reset the @order_rank variable to one, otherwise we increment by one."
},
{
"code": null,
"e": 4934,
"s": 4825,
"text": "** Note ** using the := operand allows us to create a variable on the fly without requiring the SET command."
},
{
"code": null,
"e": 5145,
"s": 4934,
"text": "** 2nd Note ** keep in mind this SELECT statement will rank all of the records in our table. Normally you’d want to have a WHERE clause that limits the size of the result set. Perhaps by customer or date range."
},
{
"code": null,
"e": 5205,
"s": 5145,
"text": "The query above produces a result set that looks like this:"
},
{
"code": null,
"e": 5400,
"s": 5205,
"text": "You can see that the orders are sorted by year and month and then by order amount in descending sequence. The new order_rank column is included that ranks every order in 1–2–3 sequence by month."
},
{
"code": null,
"e": 5543,
"s": 5400,
"text": "Now we can include this query as a subquery to a SELECT that only pulls the top 3 orders out of every group. That final query looks like this:"
},
{
"code": null,
"e": 6027,
"s": 5543,
"text": "SELECT customer_number, customer_name, order_number, order_date, order_amount FROM (SELECT order_number, customer_number, customer_name, order_date, YEAR(order_date) AS order_year, MONTH(order_date) AS order_month, order_amount, @order_rank := IF(@current_month = MONTH(order_date), @order_rank + 1, 1) AS order_rank, @current_month := MONTH(order_date) FROM orders ORDER BY order_year, order_month, order_amount DESC) ranked_orders WHERE order_rank <= 3;"
},
{
"code": null,
"e": 6248,
"s": 6027,
"text": "With our ranking query as the subquery, we only need to pull out the final fields that we need for reporting. A WHERE clause is added that only pulls records with a rank of 3 or less. Our final result set is shown below:"
},
{
"code": null,
"e": 6324,
"s": 6248,
"text": "You can see in the results that we got the top 3 orders out of every month."
},
{
"code": null,
"e": 6710,
"s": 6324,
"text": "MySQL 8.0 introduces a rank() function that adds some additional functionality for ranking records in a result set. With the rank() function the result set is partitioned by a value that you specify, then a rank is assigned to each row within each partition. Ties are given the same rank and the subsequent new number is given a rank of one plus the number of ranked records before it."
},
{
"code": null,
"e": 6767,
"s": 6710,
"text": "Our ranking query with this new feature looks like this:"
},
{
"code": null,
"e": 7070,
"s": 6767,
"text": "SELECT order_number, customer_number, customer_name, order_date, YEAR(order_date) AS order_year, MONTH(order_date) AS order_month, order_amount, RANK() OVER ( PARTITION BY YEAR(order_date), MONTH(order_date)ORDER BY YEAR(order_date), MONTH(order_date), order_amount DESC) order_value_rankFROM orders;"
},
{
"code": null,
"e": 7124,
"s": 7070,
"text": "This produces a result that looks like the following:"
},
{
"code": null,
"e": 7342,
"s": 7124,
"text": "In this example you can see that in December the two greatest orders had the same amount of $321.00. The rank() function gives these two records the same rank of 1 and the subsequent record gets a rank of 3 and so on."
},
{
"code": null,
"e": 7417,
"s": 7342,
"text": "Like before, this ranking query is used as a subquery for our final query:"
},
{
"code": null,
"e": 7859,
"s": 7417,
"text": "WITH ranked_orders AS ( SELECT order_number, customer_number, customer_name, order_date, YEAR(order_date) AS order_year, MONTH(order_date) AS order_month, order_amount, RANK() OVER ( PARTITION BY YEAR(order_date), MONTH(order_date) ORDER BY YEAR(order_date), MONTH(order_date), order_amount DESC) order_rank FROM orders)SELECT customer_number, customer_name, order_number, order_date, order_amount FROM ranked_ordersWHERE order_rank <= 3;"
},
{
"code": null,
"e": 8180,
"s": 7859,
"text": "The final query is very similar to our MySQL 5.7 example, but uses some MySQL 8.0 goodness (like the availability of the WITH statement) along with more ranking capabilities that you can research in the MySQL 8.0 documentation. The final results to this query are identical to our MySQL 5.7 results in the example above."
},
{
"code": null,
"e": 8294,
"s": 8180,
"text": "I hope these two examples gives you some help the next time you’re wanting to get the top results out of a group."
}
]
|
Python | How to Parse Command-Line Options | 12 Jun, 2019
In this article, we will discuss how to write a Python program to parse options supplied on the command line (found in sys.argv). The argparse module can be used to parse command-line options.
Code #1 : Using argparse module
'''Hypothetical command-line tool for searching a collection of files for one or more text patterns.'''import argparse parser = argparse.ArgumentParser(description ='Search some files') parser.add_argument(dest ='filenames', metavar ='filename', nargs ='*')parser.add_argument('-p', '--pat', metavar ='pattern', required = True, dest ='patterns', action ='append', help ='text pattern to search for') parser.add_argument('-v', dest ='verbose', action ='store_true', help ='verbose mode')parser.add_argument('-o', dest ='outfile', action ='store', help ='output file')parser.add_argument('--speed', dest ='speed', action ='store', choices = {'slow', 'fast'}, default ='slow', help ='search speed')args = parser.parse_args()
The program mentioned above defines a command-line parser with the following usage –
bash % python3 search.py -h
usage: search.py [-h] [-p pattern] [-v] [-o OUTFILE]
[--speed {slow, fast}] [filename [filename ...]]
Search some files
positional arguments:
filename
optional arguments:
-h, --help show this help message and exit
-p pattern, --pat pattern
text pattern to search for
-v verbose mode
-o OUTFILE output file
--speed {slow, fast} search speed
Observe the output of the print() statements.
Code: The following session shows how data shows up in the program.
bash % python3 search.py foo.txt bar.txt
usage: search.py [-h] -p pattern [-v] [-o OUTFILE]
[--speed {fast, slow}] [filename [filename ...]]
search.py: error: the following arguments are required: -p/--pat
bash % python3 search.py -v -p spam --pat = eggs
foo.txt bar.txt
filenames = ['foo.txt', 'bar.txt']
patterns = ['spam', 'eggs']
verbose = True
outfile = None
speed = slow
bash % python3 search.py -v -p spam --pat = eggs
foo.txt bar.txt -o results
filenames = ['foo.txt', 'bar.txt']
patterns = ['spam', 'eggs']
verbose = True
outfile = results
speed = slow
bash % python3 search.py -v -p spam --pat = eggs
foo.txt bar.txt -o results \--speed = fast
filenames = ['foo.txt', 'bar.txt']
patterns = ['spam', 'eggs']
verbose = True
outfile = results
speed = fast
The argparse module is one of the largest modules in the standard library, and has a huge number of configuration options. This codes above show an essential subset that can be used and extended to get started.
To parse options, you first create an ArgumentParser instance and add declarations for the options you want to support it using the add_argument() method.
In each add_argument() call, the dest argument specifies the name of an attribute where the result of parsing will be placed.
The metavar argument is used when generating help messages.
The action argument specifies the processing associated with the argument and is often store for storing a value or append for collecting multiple argument values into a list.
Code : Argument collects all of the extra command-line arguments into a list. It’s being used to make a list of filenames
parser.add_argument(dest = 'filenames', metavar = 'filename', nargs = '*')
Code : Argument sets a Boolean flag depending on whether or not the argument was provided
parser.add_argument('-v', dest = 'verbose', action = 'store_true', help = 'verbose mode')
Code : Argument takes a single value and stores it as a string
parser.add_argument('-o', dest = 'outfile', action = 'store', help = 'output file')
The following argument specification allows an argument to be repeated multiple times and all of the values append into a list. The required flag means that the argument must be supplied at least once.
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jun, 2019"
},
{
"code": null,
"e": 221,
"s": 28,
"text": "In this article, we will discuss how to write a Python program to parse options supplied on the command line (found in sys.argv). The argparse module can be used to parse command-line options."
},
{
"code": null,
"e": 253,
"s": 221,
"text": "Code #1 : Using argparse module"
},
{
"code": "'''Hypothetical command-line tool for searching a collection of files for one or more text patterns.'''import argparse parser = argparse.ArgumentParser(description ='Search some files') parser.add_argument(dest ='filenames', metavar ='filename', nargs ='*')parser.add_argument('-p', '--pat', metavar ='pattern', required = True, dest ='patterns', action ='append', help ='text pattern to search for') parser.add_argument('-v', dest ='verbose', action ='store_true', help ='verbose mode')parser.add_argument('-o', dest ='outfile', action ='store', help ='output file')parser.add_argument('--speed', dest ='speed', action ='store', choices = {'slow', 'fast'}, default ='slow', help ='search speed')args = parser.parse_args()",
"e": 1117,
"s": 253,
"text": null
},
{
"code": null,
"e": 1202,
"s": 1117,
"text": "The program mentioned above defines a command-line parser with the following usage –"
},
{
"code": null,
"e": 1645,
"s": 1202,
"text": "bash % python3 search.py -h\nusage: search.py [-h] [-p pattern] [-v] [-o OUTFILE] \n [--speed {slow, fast}] [filename [filename ...]]\n\nSearch some files\n\npositional arguments:\n filename\n\noptional arguments:\n-h, --help show this help message and exit\n-p pattern, --pat pattern\n text pattern to search for\n-v verbose mode\n-o OUTFILE output file\n--speed {slow, fast} search speed"
},
{
"code": null,
"e": 1691,
"s": 1645,
"text": "Observe the output of the print() statements."
},
{
"code": null,
"e": 1759,
"s": 1691,
"text": "Code: The following session shows how data shows up in the program."
},
{
"code": null,
"e": 2151,
"s": 1759,
"text": "bash % python3 search.py foo.txt bar.txt\nusage: search.py [-h] -p pattern [-v] [-o OUTFILE]\n [--speed {fast, slow}] [filename [filename ...]]\n\nsearch.py: error: the following arguments are required: -p/--pat\nbash % python3 search.py -v -p spam --pat = eggs \n foo.txt bar.txt\nfilenames = ['foo.txt', 'bar.txt']\npatterns = ['spam', 'eggs']\nverbose = True\noutfile = None\nspeed = slow"
},
{
"code": null,
"e": 2354,
"s": 2151,
"text": "bash % python3 search.py -v -p spam --pat = eggs \n foo.txt bar.txt -o results\nfilenames = ['foo.txt', 'bar.txt']\npatterns = ['spam', 'eggs']\nverbose = True\noutfile = results\nspeed = slow"
},
{
"code": null,
"e": 2568,
"s": 2354,
"text": "bash % python3 search.py -v -p spam --pat = eggs \n foo.txt bar.txt -o results \\--speed = fast\nfilenames = ['foo.txt', 'bar.txt']\npatterns = ['spam', 'eggs']\nverbose = True\noutfile = results\nspeed = fast"
},
{
"code": null,
"e": 2779,
"s": 2568,
"text": "The argparse module is one of the largest modules in the standard library, and has a huge number of configuration options. This codes above show an essential subset that can be used and extended to get started."
},
{
"code": null,
"e": 2934,
"s": 2779,
"text": "To parse options, you first create an ArgumentParser instance and add declarations for the options you want to support it using the add_argument() method."
},
{
"code": null,
"e": 3060,
"s": 2934,
"text": "In each add_argument() call, the dest argument specifies the name of an attribute where the result of parsing will be placed."
},
{
"code": null,
"e": 3120,
"s": 3060,
"text": "The metavar argument is used when generating help messages."
},
{
"code": null,
"e": 3296,
"s": 3120,
"text": "The action argument specifies the processing associated with the argument and is often store for storing a value or append for collecting multiple argument values into a list."
},
{
"code": null,
"e": 3418,
"s": 3296,
"text": "Code : Argument collects all of the extra command-line arguments into a list. It’s being used to make a list of filenames"
},
{
"code": "parser.add_argument(dest = 'filenames', metavar = 'filename', nargs = '*')",
"e": 3512,
"s": 3418,
"text": null
},
{
"code": null,
"e": 3603,
"s": 3512,
"text": " Code : Argument sets a Boolean flag depending on whether or not the argument was provided"
},
{
"code": "parser.add_argument('-v', dest = 'verbose', action = 'store_true', help = 'verbose mode')",
"e": 3733,
"s": 3603,
"text": null
},
{
"code": null,
"e": 3797,
"s": 3733,
"text": " Code : Argument takes a single value and stores it as a string"
},
{
"code": "parser.add_argument('-o', dest = 'outfile', action = 'store', help = 'output file')",
"e": 3901,
"s": 3797,
"text": null
},
{
"code": null,
"e": 4103,
"s": 3901,
"text": "The following argument specification allows an argument to be repeated multiple times and all of the values append into a list. The required flag means that the argument must be supplied at least once."
},
{
"code": null,
"e": 4118,
"s": 4103,
"text": "python-utility"
},
{
"code": null,
"e": 4125,
"s": 4118,
"text": "Python"
}
]
|
Scala - Variables | Variables are nothing but reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory.
Based on the data type of a variable, the compiler allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.
Scala has a different syntax for declaring variables. They can be defined as value, i.e., constant or a variable. Here, myVar is declared using the keyword var. It is a variable that can change value and this is called mutable variable. Following is the syntax to define a variable using var keyword −
var myVar : String = "Foo"
Here, myVal is declared using the keyword val. This means that it is a variable that cannot be changed and this is called immutable variable. Following is the syntax to define a variable using val keyword −
val myVal : String = "Foo"
The type of a variable is specified after the variable name and before equals sign. You can define any type of Scala variable by mentioning its data type as follows −
val or val VariableName : DataType = [Initial Value]
If you do not assign any initial value to a variable, then it is valid as follows −
var myVar :Int;
val myVal :String;
When you assign an initial value to a variable, the Scala compiler can figure out the type of the variable based on the value assigned to it. This is called variable type inference. Therefore, you could write these variable declarations like this −
var myVar = 10;
val myVal = "Hello, Scala!";
Here, by default, myVar will be Int type and myVal will become String type variable.
Scala supports multiple assignments. If a code block or method returns a Tuple (Tuple − Holds collection of Objects of different types), the Tuple can be assigned to a val variable. [Note − We will study Tuples in subsequent chapters.]
val (myVar1: Int, myVar2: String) = Pair(40, "Foo")
And the type inference gets it right −
val (myVar1, myVar2) = Pair(40, "Foo")
The following is an example program that explains the process of variable declaration in Scala. This program declares four variables — two variables are defined with type declaration and remaining two are without type declaration.
object Demo {
def main(args: Array[String]) {
var myVar :Int = 10;
val myVal :String = "Hello Scala with datatype declaration.";
var myVar1 = 20;
val myVal1 = "Hello Scala new without datatype declaration.";
println(myVar); println(myVal); println(myVar1);
println(myVal1);
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo
10
Hello Scala with datatype declaration.
20
Hello Scala without datatype declaration.
Variables in Scala can have three different scopes depending on the place where they are being used. They can exist as fields, as method parameters and as local variables. Below are the details about each type of scope.
Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object depending on what access modifiers the field is declared with. Object fields can be both mutable and immutable types and can be defined using either var or val.
Method parameters are variables, which are used to pass the value inside a method, when the method is called. Method parameters are only accessible from inside the method but the objects passed in may be accessible from the outside, if you have a reference to the object from outside the method. Method parameters are always immutable which are defined by val keyword.
Local variables are variables declared inside a method. Local variables are only accessible from inside the method, but the objects you create may escape the method if you return them from the method. Local variables can be both mutable and immutable types and can be defined using either var or val. | [
{
"code": null,
"e": 2279,
"s": 2132,
"text": "Variables are nothing but reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory."
},
{
"code": null,
"e": 2529,
"s": 2279,
"text": "Based on the data type of a variable, the compiler allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables."
},
{
"code": null,
"e": 2831,
"s": 2529,
"text": "Scala has a different syntax for declaring variables. They can be defined as value, i.e., constant or a variable. Here, myVar is declared using the keyword var. It is a variable that can change value and this is called mutable variable. Following is the syntax to define a variable using var keyword −"
},
{
"code": null,
"e": 2859,
"s": 2831,
"text": "var myVar : String = \"Foo\"\n"
},
{
"code": null,
"e": 3066,
"s": 2859,
"text": "Here, myVal is declared using the keyword val. This means that it is a variable that cannot be changed and this is called immutable variable. Following is the syntax to define a variable using val keyword −"
},
{
"code": null,
"e": 3094,
"s": 3066,
"text": "val myVal : String = \"Foo\"\n"
},
{
"code": null,
"e": 3261,
"s": 3094,
"text": "The type of a variable is specified after the variable name and before equals sign. You can define any type of Scala variable by mentioning its data type as follows −"
},
{
"code": null,
"e": 3315,
"s": 3261,
"text": "val or val VariableName : DataType = [Initial Value]\n"
},
{
"code": null,
"e": 3399,
"s": 3315,
"text": "If you do not assign any initial value to a variable, then it is valid as follows −"
},
{
"code": null,
"e": 3435,
"s": 3399,
"text": "var myVar :Int;\nval myVal :String;\n"
},
{
"code": null,
"e": 3684,
"s": 3435,
"text": "When you assign an initial value to a variable, the Scala compiler can figure out the type of the variable based on the value assigned to it. This is called variable type inference. Therefore, you could write these variable declarations like this −"
},
{
"code": null,
"e": 3730,
"s": 3684,
"text": "var myVar = 10;\nval myVal = \"Hello, Scala!\";\n"
},
{
"code": null,
"e": 3815,
"s": 3730,
"text": "Here, by default, myVar will be Int type and myVal will become String type variable."
},
{
"code": null,
"e": 4051,
"s": 3815,
"text": "Scala supports multiple assignments. If a code block or method returns a Tuple (Tuple − Holds collection of Objects of different types), the Tuple can be assigned to a val variable. [Note − We will study Tuples in subsequent chapters.]"
},
{
"code": null,
"e": 4104,
"s": 4051,
"text": "val (myVar1: Int, myVar2: String) = Pair(40, \"Foo\")\n"
},
{
"code": null,
"e": 4143,
"s": 4104,
"text": "And the type inference gets it right −"
},
{
"code": null,
"e": 4183,
"s": 4143,
"text": "val (myVar1, myVar2) = Pair(40, \"Foo\")\n"
},
{
"code": null,
"e": 4414,
"s": 4183,
"text": "The following is an example program that explains the process of variable declaration in Scala. This program declares four variables — two variables are defined with type declaration and remaining two are without type declaration."
},
{
"code": null,
"e": 4742,
"s": 4414,
"text": "object Demo {\n def main(args: Array[String]) {\n var myVar :Int = 10;\n val myVal :String = \"Hello Scala with datatype declaration.\";\n var myVar1 = 20;\n val myVal1 = \"Hello Scala new without datatype declaration.\";\n \n println(myVar); println(myVal); println(myVar1); \n println(myVal1);\n }\n}"
},
{
"code": null,
"e": 4849,
"s": 4742,
"text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program."
},
{
"code": null,
"e": 4883,
"s": 4849,
"text": "\\>scalac Demo.scala\n\\>scala Demo\n"
},
{
"code": null,
"e": 4971,
"s": 4883,
"text": "10\nHello Scala with datatype declaration.\n20\nHello Scala without datatype declaration.\n"
},
{
"code": null,
"e": 5191,
"s": 4971,
"text": "Variables in Scala can have three different scopes depending on the place where they are being used. They can exist as fields, as method parameters and as local variables. Below are the details about each type of scope."
},
{
"code": null,
"e": 5514,
"s": 5191,
"text": "Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object depending on what access modifiers the field is declared with. Object fields can be both mutable and immutable types and can be defined using either var or val."
},
{
"code": null,
"e": 5883,
"s": 5514,
"text": "Method parameters are variables, which are used to pass the value inside a method, when the method is called. Method parameters are only accessible from inside the method but the objects passed in may be accessible from the outside, if you have a reference to the object from outside the method. Method parameters are always immutable which are defined by val keyword."
}
]
|
LIFO (Last-In-First-Out) approach in Programming | 21 Jun, 2022
Prerequisites – FIFO (First-In-First-Out) approach in Programming, FIFO vs LIFO approach in Programming LIFO is an abbreviation for last in, first out. It is a method for handling data structures where the first element is processed last and the last element is processed first.Real-life example:
In this example, following things are to be considered:
There is a bucket that holds balls.
Different types of balls are entered into the bucket.
The ball to enter the bucket last will be taken out first.
The ball entering the bucket next to last will be taken out after the ball above it (the newer one).
In this way, the ball entering the bucket first will leave the bucket last.
Therefore, the Last ball (Blue) to enter the bucket gets removed first and the First ball (Red) to enter the bucket gets removed last.
This is known as Last-In-First-Out approach or LIFO.Where is LIFO used:
Data Structures – Certain data structures like Stacks and other variants of Stacks use LIFO approach for processing data. Extracting latest information – Sometimes computers use LIFO when data is extracted from an array or data buffer. When it is required to get the most recent information entered, the LIFO approach is used.
Data Structures – Certain data structures like Stacks and other variants of Stacks use LIFO approach for processing data.
Extracting latest information – Sometimes computers use LIFO when data is extracted from an array or data buffer. When it is required to get the most recent information entered, the LIFO approach is used.
Program Examples for LIFO – Using Stack data structure:
C++
Java
Python3
C#
Javascript
// C++ program to demonstrate// working of LIFO// using stack in C++#include<bits/stdc++.h>using namespace std; // Pushing element on the top of the stackstack<int> stack_push(stack<int> stack){ for (int i = 0; i < 5; i++) { stack.push(i); } return stack;} // Popping element from the top of the stackstack<int> stack_pop(stack<int> stack){ cout << "Pop :"; for (int i = 0; i < 5; i++) { int y = (int)stack.top(); stack.pop(); cout << (y) << endl; } return stack;} // Displaying element on the top of the stackvoid stack_peek(stack<int> stack){ int element = (int)stack.top(); cout << "Element on stack top : " << element << endl;} // Searching element in the stackvoid stack_search(stack<int> stack, int element){ int pos = -1,co = 0; while(stack.size() > 0) { co++; if(stack.top() == element) { pos = co; break; } stack.pop(); } if (pos == -1) cout << "Element not found" << endl; else cout << "Element is found at position " << pos << endl;} // Driver codeint main(){ stack<int> stack ; stack = stack_push(stack); stack = stack_pop(stack); stack = stack_push(stack); stack_peek(stack); stack_search(stack, 2); stack_search(stack, 6); return 0;} // This code is contributed by Arnab Kundu
// Java program to demonstrate// working of LIFO// using Stack in Java import java.io.*;import java.util.*; class GFG { // Pushing element on the top of the stack static void stack_push(Stack<Integer> stack) { for (int i = 0; i < 5; i++) { stack.push(i); } } // Popping element from the top of the stack static void stack_pop(Stack<Integer> stack) { System.out.println("Pop :"); for (int i = 0; i < 5; i++) { Integer y = (Integer)stack.pop(); System.out.println(y); } } // Displaying element on the top of the stack static void stack_peek(Stack<Integer> stack) { Integer element = (Integer)stack.peek(); System.out.println("Element on stack top : " + element); } // Searching element in the stack static void stack_search(Stack<Integer> stack, int element) { Integer pos = (Integer)stack.search(element); if (pos == -1) System.out.println("Element not found"); else System.out.println("Element is found at position " + pos); } public static void main(String[] args) { Stack<Integer> stack = new Stack<Integer>(); stack_push(stack); stack_pop(stack); stack_push(stack); stack_peek(stack); stack_search(stack, 2); stack_search(stack, 6); }}
# Python3 program to demonstrate working of LIFO # Pushing element on the top of the stackdef stack_push(stack): for i in range(5): stack.append(i) return stack # Popping element from the top of the stackdef stack_pop(stack): print("Pop :") for i in range(5): y = stack[-1] stack.pop() print(y) return stack # Displaying element on the top of the stackdef stack_peek(stack): element = stack[-1] print("Element on stack top :", element) # Searching element in the stackdef stack_search(stack, element): pos = -1 co = 0 while(len(stack) > 0): co+=1 if(stack[-1] == element): pos = co break stack.pop() if (pos == -1): print( "Element not found") else: print("Element is found at position", pos) stack = []stack_push(stack)stack_pop(stack)stack_push(stack)stack_peek(stack)stack_search(stack, 2)stack_search(stack, 6) # This code is contributed by rameshtravel07.
// C# program to demonstrate// working of LIFO// using Stack in C#using System;using System.Collections.Generic; class GFG{ // Pushing element on the top of the stack static void stack_push(Stack<int> stack) { for (int i = 0; i < 5; i++) { stack.Push(i); } } // Popping element from the top of the stack static void stack_pop(Stack<int> stack) { Console.WriteLine("Pop :"); for (int i = 0; i < 5; i++) { int y = (int)stack.Pop(); Console.WriteLine(y); } } // Displaying element on the top of the stack static void stack_peek(Stack<int> stack) { int element = (int)stack.Peek(); Console.WriteLine("Element on stack top : " + element); } // Searching element in the stack static void stack_search(Stack<int> stack, int element) { bool pos = stack.Contains(element); if (pos == false) Console.WriteLine("Element not found"); else Console.WriteLine("Element is found at position " + pos); } // Driver code public static void Main(String[] args) { Stack<int> stack = new Stack<int>(); stack_push(stack); stack_pop(stack); stack_push(stack); stack_peek(stack); stack_search(stack, 2); stack_search(stack, 6); }} // This code contributed by Rajput-Ji
<script> // JavaScript program to demonstrate// working of LIFO // Pushing element on the top of the stackfunction stack_push(stack){ for (var i = 0; i < 5; i++) { stack.push(i); } return stack;} // Popping element from the top of the stackfunction stack_pop(stack){ document.write( "Pop :<br>"); for (var i = 0; i < 5; i++) { var y = parseInt(stack[stack.length-1]); stack.pop(); document.write( y + "<br>"); } return stack;} // Displaying element on the top of the stackfunction stack_peek(stack){ var element = parseInt(stack[stack.length-1]); document.write( "Element on stack top : " + element + "<br>");} // Searching element in the stackfunction stack_search( stack, element){ var pos = -1,co = 0; while(stack.length > 0) { co++; if(stack[stack.length-1] == element) { pos = co; break; } stack.pop(); } if (pos == -1) document.write( "Element not found" + "<br>"); else document.write("Element is found at position " + pos + "<br>");} stack=[] ; stack = stack_push(stack); stack = stack_pop(stack); stack = stack_push(stack); stack_peek(stack); stack_search(stack, 2); stack_search(stack, 6); // This code is contributed by SoumikMondal </script>
Output:
Pop:
4
3
2
1
0
Element on stack top : 4
Element is found at position 3
Element not found
Time Complexity: O(n)
Auxiliary Space: O(n)
andrew1234
Rajput-Ji
SoumikMondal
rameshtravel07
geekygirl2001
Data Structures-Stack
Stack
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 351,
"s": 53,
"text": "Prerequisites – FIFO (First-In-First-Out) approach in Programming, FIFO vs LIFO approach in Programming LIFO is an abbreviation for last in, first out. It is a method for handling data structures where the first element is processed last and the last element is processed first.Real-life example: "
},
{
"code": null,
"e": 409,
"s": 351,
"text": "In this example, following things are to be considered: "
},
{
"code": null,
"e": 445,
"s": 409,
"text": "There is a bucket that holds balls."
},
{
"code": null,
"e": 499,
"s": 445,
"text": "Different types of balls are entered into the bucket."
},
{
"code": null,
"e": 558,
"s": 499,
"text": "The ball to enter the bucket last will be taken out first."
},
{
"code": null,
"e": 659,
"s": 558,
"text": "The ball entering the bucket next to last will be taken out after the ball above it (the newer one)."
},
{
"code": null,
"e": 735,
"s": 659,
"text": "In this way, the ball entering the bucket first will leave the bucket last."
},
{
"code": null,
"e": 870,
"s": 735,
"text": "Therefore, the Last ball (Blue) to enter the bucket gets removed first and the First ball (Red) to enter the bucket gets removed last."
},
{
"code": null,
"e": 943,
"s": 870,
"text": "This is known as Last-In-First-Out approach or LIFO.Where is LIFO used: "
},
{
"code": null,
"e": 1272,
"s": 943,
"text": "Data Structures – Certain data structures like Stacks and other variants of Stacks use LIFO approach for processing data. Extracting latest information – Sometimes computers use LIFO when data is extracted from an array or data buffer. When it is required to get the most recent information entered, the LIFO approach is used. "
},
{
"code": null,
"e": 1395,
"s": 1272,
"text": "Data Structures – Certain data structures like Stacks and other variants of Stacks use LIFO approach for processing data. "
},
{
"code": null,
"e": 1602,
"s": 1395,
"text": "Extracting latest information – Sometimes computers use LIFO when data is extracted from an array or data buffer. When it is required to get the most recent information entered, the LIFO approach is used. "
},
{
"code": null,
"e": 1660,
"s": 1602,
"text": "Program Examples for LIFO – Using Stack data structure: "
},
{
"code": null,
"e": 1664,
"s": 1660,
"text": "C++"
},
{
"code": null,
"e": 1669,
"s": 1664,
"text": "Java"
},
{
"code": null,
"e": 1677,
"s": 1669,
"text": "Python3"
},
{
"code": null,
"e": 1680,
"s": 1677,
"text": "C#"
},
{
"code": null,
"e": 1691,
"s": 1680,
"text": "Javascript"
},
{
"code": "// C++ program to demonstrate// working of LIFO// using stack in C++#include<bits/stdc++.h>using namespace std; // Pushing element on the top of the stackstack<int> stack_push(stack<int> stack){ for (int i = 0; i < 5; i++) { stack.push(i); } return stack;} // Popping element from the top of the stackstack<int> stack_pop(stack<int> stack){ cout << \"Pop :\"; for (int i = 0; i < 5; i++) { int y = (int)stack.top(); stack.pop(); cout << (y) << endl; } return stack;} // Displaying element on the top of the stackvoid stack_peek(stack<int> stack){ int element = (int)stack.top(); cout << \"Element on stack top : \" << element << endl;} // Searching element in the stackvoid stack_search(stack<int> stack, int element){ int pos = -1,co = 0; while(stack.size() > 0) { co++; if(stack.top() == element) { pos = co; break; } stack.pop(); } if (pos == -1) cout << \"Element not found\" << endl; else cout << \"Element is found at position \" << pos << endl;} // Driver codeint main(){ stack<int> stack ; stack = stack_push(stack); stack = stack_pop(stack); stack = stack_push(stack); stack_peek(stack); stack_search(stack, 2); stack_search(stack, 6); return 0;} // This code is contributed by Arnab Kundu",
"e": 3063,
"s": 1691,
"text": null
},
{
"code": "// Java program to demonstrate// working of LIFO// using Stack in Java import java.io.*;import java.util.*; class GFG { // Pushing element on the top of the stack static void stack_push(Stack<Integer> stack) { for (int i = 0; i < 5; i++) { stack.push(i); } } // Popping element from the top of the stack static void stack_pop(Stack<Integer> stack) { System.out.println(\"Pop :\"); for (int i = 0; i < 5; i++) { Integer y = (Integer)stack.pop(); System.out.println(y); } } // Displaying element on the top of the stack static void stack_peek(Stack<Integer> stack) { Integer element = (Integer)stack.peek(); System.out.println(\"Element on stack top : \" + element); } // Searching element in the stack static void stack_search(Stack<Integer> stack, int element) { Integer pos = (Integer)stack.search(element); if (pos == -1) System.out.println(\"Element not found\"); else System.out.println(\"Element is found at position \" + pos); } public static void main(String[] args) { Stack<Integer> stack = new Stack<Integer>(); stack_push(stack); stack_pop(stack); stack_push(stack); stack_peek(stack); stack_search(stack, 2); stack_search(stack, 6); }}",
"e": 4440,
"s": 3063,
"text": null
},
{
"code": "# Python3 program to demonstrate working of LIFO # Pushing element on the top of the stackdef stack_push(stack): for i in range(5): stack.append(i) return stack # Popping element from the top of the stackdef stack_pop(stack): print(\"Pop :\") for i in range(5): y = stack[-1] stack.pop() print(y) return stack # Displaying element on the top of the stackdef stack_peek(stack): element = stack[-1] print(\"Element on stack top :\", element) # Searching element in the stackdef stack_search(stack, element): pos = -1 co = 0 while(len(stack) > 0): co+=1 if(stack[-1] == element): pos = co break stack.pop() if (pos == -1): print( \"Element not found\") else: print(\"Element is found at position\", pos) stack = []stack_push(stack)stack_pop(stack)stack_push(stack)stack_peek(stack)stack_search(stack, 2)stack_search(stack, 6) # This code is contributed by rameshtravel07.",
"e": 5429,
"s": 4440,
"text": null
},
{
"code": "// C# program to demonstrate// working of LIFO// using Stack in C#using System;using System.Collections.Generic; class GFG{ // Pushing element on the top of the stack static void stack_push(Stack<int> stack) { for (int i = 0; i < 5; i++) { stack.Push(i); } } // Popping element from the top of the stack static void stack_pop(Stack<int> stack) { Console.WriteLine(\"Pop :\"); for (int i = 0; i < 5; i++) { int y = (int)stack.Pop(); Console.WriteLine(y); } } // Displaying element on the top of the stack static void stack_peek(Stack<int> stack) { int element = (int)stack.Peek(); Console.WriteLine(\"Element on stack top : \" + element); } // Searching element in the stack static void stack_search(Stack<int> stack, int element) { bool pos = stack.Contains(element); if (pos == false) Console.WriteLine(\"Element not found\"); else Console.WriteLine(\"Element is found at position \" + pos); } // Driver code public static void Main(String[] args) { Stack<int> stack = new Stack<int>(); stack_push(stack); stack_pop(stack); stack_push(stack); stack_peek(stack); stack_search(stack, 2); stack_search(stack, 6); }} // This code contributed by Rajput-Ji",
"e": 6828,
"s": 5429,
"text": null
},
{
"code": "<script> // JavaScript program to demonstrate// working of LIFO // Pushing element on the top of the stackfunction stack_push(stack){ for (var i = 0; i < 5; i++) { stack.push(i); } return stack;} // Popping element from the top of the stackfunction stack_pop(stack){ document.write( \"Pop :<br>\"); for (var i = 0; i < 5; i++) { var y = parseInt(stack[stack.length-1]); stack.pop(); document.write( y + \"<br>\"); } return stack;} // Displaying element on the top of the stackfunction stack_peek(stack){ var element = parseInt(stack[stack.length-1]); document.write( \"Element on stack top : \" + element + \"<br>\");} // Searching element in the stackfunction stack_search( stack, element){ var pos = -1,co = 0; while(stack.length > 0) { co++; if(stack[stack.length-1] == element) { pos = co; break; } stack.pop(); } if (pos == -1) document.write( \"Element not found\" + \"<br>\"); else document.write(\"Element is found at position \" + pos + \"<br>\");} stack=[] ; stack = stack_push(stack); stack = stack_pop(stack); stack = stack_push(stack); stack_peek(stack); stack_search(stack, 2); stack_search(stack, 6); // This code is contributed by SoumikMondal </script>",
"e": 8175,
"s": 6828,
"text": null
},
{
"code": null,
"e": 8185,
"s": 8175,
"text": "Output: "
},
{
"code": null,
"e": 8275,
"s": 8185,
"text": "Pop:\n4\n3\n2\n1\n0\nElement on stack top : 4\nElement is found at position 3\nElement not found "
},
{
"code": null,
"e": 8297,
"s": 8275,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 8320,
"s": 8297,
"text": "Auxiliary Space: O(n) "
},
{
"code": null,
"e": 8331,
"s": 8320,
"text": "andrew1234"
},
{
"code": null,
"e": 8341,
"s": 8331,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8354,
"s": 8341,
"text": "SoumikMondal"
},
{
"code": null,
"e": 8369,
"s": 8354,
"text": "rameshtravel07"
},
{
"code": null,
"e": 8383,
"s": 8369,
"text": "geekygirl2001"
},
{
"code": null,
"e": 8405,
"s": 8383,
"text": "Data Structures-Stack"
},
{
"code": null,
"e": 8411,
"s": 8405,
"text": "Stack"
},
{
"code": null,
"e": 8417,
"s": 8411,
"text": "Stack"
}
]
|
Passing and Returning Objects in C++ | 17 Mar, 2021
In C++ we can pass class’s objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required to do so.
To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables.Syntax:
function_name(object_name);
Example: In this Example there is a class which has an integer variable ‘a’ and a function ‘add’ which takes an object as argument. The function is called by one object and takes another as an argument. Inside the function, the integer value of the argument object is added to that on which the ‘add’ function is called. In this method, we can pass objects as an argument and alter them.
CPP
// C++ program to show passing// of objects to a function #include <bits/stdc++.h>using namespace std; class Example {public: int a; // This function will take // an object as an argument void add(Example E) { a = a + E.a; }}; // Driver Codeint main(){ // Create objects Example E1, E2; // Values are initialized for both objects E1.a = 50; E2.a = 100; cout << "Initial Values \n"; cout << "Value of object 1: " << E1.a << "\n& object 2: " << E2.a << "\n\n"; // Passing object as an argument // to function add() E2.add(E1); // Changed values after passing // object as argument cout << "New values \n"; cout << "Value of object 1: " << E1.a << "\n& object 2: " << E2.a << "\n\n"; return 0;}
Initial Values
Value of object 1: 50
& object 2: 100
New values
Value of object 1: 50
& object 2: 150
Syntax:
object = return object_name;
Example: In the above example we can see that the add function does not return any value since its return-type is void. In the following program the add function returns an object of type ‘Example'(i.e., class name) whose value is stored in E3. In this example, we can see both the things that are how we can pass the objects as well as return them. When the object E3 calls the add function it passes the other two objects namely E1 & E2 as arguments. Inside the function, another object is declared which calculates the sum of all the three variables and returns it to E3. This code and the above code is almost the same, the only difference is that this time the add function returns an object whose value is stored in another object of the same class ‘Example’ E3. Here the value of E1 is displayed by object1, the value of E2 by object2 and value of E3 by object3.
CPP
// C++ program to show passing// of objects to a function #include <bits/stdc++.h>using namespace std; class Example {public: int a; // This function will take // object as arguments and // return object Example add(Example Ea, Example Eb) { Example Ec; Ec.a = Ea.a + Eb.a; // returning the object return Ec; }};int main(){ Example E1, E2, E3; // Values are initialized // for both objects E1.a = 50; E2.a = 100; E3.a = 0; cout << "Initial Values \n"; cout << "Value of object 1: " << E1.a << ", \nobject 2: " << E2.a << ", \nobject 3: " << E3.a << "\n"; // Passing object as an argument // to function add() E3 = E3.add(E1, E2); // Changed values after // passing object as an argument cout << "New values \n"; cout << "Value of object 1: " << E1.a << ", \nobject 2: " << E2.a << ", \nobject 3: " << E3.a << "\n"; return 0;}
Initial Values
Value of object 1: 50,
object 2: 100,
object 3: 0
New values
Value of object 1: 50,
object 2: 100,
object 3: 150
aniket173000
jeevanyasa
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 245,
"s": 54,
"text": "In C++ we can pass class’s objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required to do so. "
},
{
"code": null,
"e": 398,
"s": 245,
"text": "To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables.Syntax: "
},
{
"code": null,
"e": 426,
"s": 398,
"text": "function_name(object_name);"
},
{
"code": null,
"e": 816,
"s": 426,
"text": "Example: In this Example there is a class which has an integer variable ‘a’ and a function ‘add’ which takes an object as argument. The function is called by one object and takes another as an argument. Inside the function, the integer value of the argument object is added to that on which the ‘add’ function is called. In this method, we can pass objects as an argument and alter them. "
},
{
"code": null,
"e": 820,
"s": 816,
"text": "CPP"
},
{
"code": "// C++ program to show passing// of objects to a function #include <bits/stdc++.h>using namespace std; class Example {public: int a; // This function will take // an object as an argument void add(Example E) { a = a + E.a; }}; // Driver Codeint main(){ // Create objects Example E1, E2; // Values are initialized for both objects E1.a = 50; E2.a = 100; cout << \"Initial Values \\n\"; cout << \"Value of object 1: \" << E1.a << \"\\n& object 2: \" << E2.a << \"\\n\\n\"; // Passing object as an argument // to function add() E2.add(E1); // Changed values after passing // object as argument cout << \"New values \\n\"; cout << \"Value of object 1: \" << E1.a << \"\\n& object 2: \" << E2.a << \"\\n\\n\"; return 0;}",
"e": 1621,
"s": 820,
"text": null
},
{
"code": null,
"e": 1726,
"s": 1621,
"text": "Initial Values \nValue of object 1: 50\n& object 2: 100\n\nNew values \nValue of object 1: 50\n& object 2: 150"
},
{
"code": null,
"e": 1735,
"s": 1726,
"text": "Syntax: "
},
{
"code": null,
"e": 1764,
"s": 1735,
"text": "object = return object_name;"
},
{
"code": null,
"e": 2634,
"s": 1764,
"text": "Example: In the above example we can see that the add function does not return any value since its return-type is void. In the following program the add function returns an object of type ‘Example'(i.e., class name) whose value is stored in E3. In this example, we can see both the things that are how we can pass the objects as well as return them. When the object E3 calls the add function it passes the other two objects namely E1 & E2 as arguments. Inside the function, another object is declared which calculates the sum of all the three variables and returns it to E3. This code and the above code is almost the same, the only difference is that this time the add function returns an object whose value is stored in another object of the same class ‘Example’ E3. Here the value of E1 is displayed by object1, the value of E2 by object2 and value of E3 by object3."
},
{
"code": null,
"e": 2638,
"s": 2634,
"text": "CPP"
},
{
"code": "// C++ program to show passing// of objects to a function #include <bits/stdc++.h>using namespace std; class Example {public: int a; // This function will take // object as arguments and // return object Example add(Example Ea, Example Eb) { Example Ec; Ec.a = Ea.a + Eb.a; // returning the object return Ec; }};int main(){ Example E1, E2, E3; // Values are initialized // for both objects E1.a = 50; E2.a = 100; E3.a = 0; cout << \"Initial Values \\n\"; cout << \"Value of object 1: \" << E1.a << \", \\nobject 2: \" << E2.a << \", \\nobject 3: \" << E3.a << \"\\n\"; // Passing object as an argument // to function add() E3 = E3.add(E1, E2); // Changed values after // passing object as an argument cout << \"New values \\n\"; cout << \"Value of object 1: \" << E1.a << \", \\nobject 2: \" << E2.a << \", \\nobject 3: \" << E3.a << \"\\n\"; return 0;}",
"e": 3616,
"s": 2638,
"text": null
},
{
"code": null,
"e": 3750,
"s": 3616,
"text": "Initial Values \nValue of object 1: 50, \nobject 2: 100, \nobject 3: 0\nNew values \nValue of object 1: 50, \nobject 2: 100, \nobject 3: 150"
},
{
"code": null,
"e": 3763,
"s": 3750,
"text": "aniket173000"
},
{
"code": null,
"e": 3774,
"s": 3763,
"text": "jeevanyasa"
},
{
"code": null,
"e": 3778,
"s": 3774,
"text": "C++"
},
{
"code": null,
"e": 3791,
"s": 3778,
"text": "C++ Programs"
},
{
"code": null,
"e": 3795,
"s": 3791,
"text": "CPP"
},
{
"code": null,
"e": 3893,
"s": 3795,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3917,
"s": 3893,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3937,
"s": 3917,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3981,
"s": 3937,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4014,
"s": 3981,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 4039,
"s": 4014,
"text": "std::string class in C++"
},
{
"code": null,
"e": 4074,
"s": 4039,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 4108,
"s": 4074,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 4152,
"s": 4108,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 4211,
"s": 4152,
"text": "How to return multiple values from a function in C or C++?"
}
]
|
List BinarySearch() Method in C# | 02 Sep, 2021
List<T>.BinarySearch() Method uses a binary search algorithm to locate a specific element in the sorted List<T> or a portion of it. There are 3 methods in the overload list of this method as follows:
BinarySearch(T)
BinarySearch(T, IComparer<T>)
BinarySearch(Int32, Int32, T, IComparer<T>)
This method searches for an element in the entire sorted List<T> using the default comparer and returns the zero-based index of the searched element.
Syntax:
public int BinarySearch (T item);
Here, item is the object which is to be locate and the value of item can be null or reference type.
Return Type: If the item is found, then this method returns the zero-based index of the element to be searched for and if not found, then a negative number that is the bitwise complement of the index of the next element will be return and the complement is larger than that item. If there is no larger element, the bitwise complement of Count will be return.
Exception: This method will give InvalidOperationException if the default comparer Default cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T.
Below programs illustrate the use of above-discussed method:
Example 1:
C#
// C# program to illustrate the// List<T>.BinarySearch(T) Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // List creation List<string> Geek = new List<string>(); // List elements Geek.Add("ABCD"); Geek.Add("QRST"); Geek.Add("XYZ"); Geek.Add("IJKL"); Console.WriteLine("The Original List is:"); foreach(string g in Geek) { // prints original List Console.WriteLine(g); } Console.WriteLine("\nThe List in Sorted form"); // sort the List Geek.Sort(); Console.WriteLine(); foreach(string g in Geek) { // prints the sorted List Console.WriteLine(g); } Console.WriteLine("\nInsert EFGH :"); // insert "EFGH" in the List //"EFGH" insert into its original // position when the List is sorted int index = Geek.BinarySearch("EFGH"); if (index < 0) { Geek.Insert(~index, "EFGH"); } Console.WriteLine(); foreach(string g in Geek) { // prints the sorted list // after inserting "EFGH" Console.WriteLine(g); } }}
The Original List is:
ABCD
QRST
XYZ
IJKL
The List in Sorted form
ABCD
IJKL
QRST
XYZ
Insert EFGH :
ABCD
EFGH
IJKL
QRST
XYZ
Example 2: In this example, the List is created with some integer values and to insert a new integer using BinarySearch(T) method in the List by using a user define function.
C#
// C# program to illustrate the// List<T>.BinarySearch(T) Methodusing System;using System.Collections.Generic; class GFG { // method for inserting "3"public void binarySearch(List<int> Geek){ // insert "3" in the List Console.WriteLine("\nInsert 3 :"); // "3" insert into its original // position when the List is // sorted int index = Geek.BinarySearch(3); if (index < 0) { Geek.Insert(~index, 3); } foreach(int g in Geek) { // prints the sorted list // after inserting "3" Console.WriteLine(g); }}} // Driver Classpublic class search { public static void Main() { // List creation GFG gg = new GFG(); List<int> Geek = new List<int>() { 5, 6, 1, 9}; Console.WriteLine("Original List"); foreach(int g in Geek) { Console.WriteLine(g); // prints original List } Console.WriteLine("\nList in Sorted form"); Geek.Sort(); foreach(int g in Geek) { Console.WriteLine(g); // prints the sorted List } // calling the method "binarySearch" gg.binarySearch(Geek); }}
Original List
5
6
1
9
List in Sorted form
1
5
6
9
Insert 3 :
1
3
5
6
9
This method searches for an element in the entire sorted List using the specified comparer and returns the zero-based index of the searched element.
Syntax:
public int BinarySearch (T item, System.Collections.Generic.IComparer<T> comparer);
Parameters:
item : It is the item to locate and the value of the item can be null for reference types.
comparer : It is the IComparer<T> implementation to use when comparing elements.
Return Value: If the item founds, then this method returns the zero-based index of the element to be searched for and if not found, then a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.
Exception: This method will give InvalidOperationException if the comparer is null, and the default comparer Default cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T.
Below programs illustrate the use of the above-discussed method:
Example 1:
C#
// C# program to demonstrate the// List<T>.BinarySearch(T,// IComparer<T>) Methodusing System;using System.Collections.Generic; class GFG : IComparer<string> { public int Compare(string x, string y) { if (x == null || y == null) { return 0; } return x.CompareTo(y); //"CompareTo()" method }} // Driver Classclass geek { // Main Method public static void Main() { // list creation List<string> list1 = new List<string>(); // list elements list1.Add("B"); list1.Add("C"); list1.Add("E"); list1.Add("A"); // prints Original list Console.WriteLine("Original string"); foreach(string g in list1) { Console.WriteLine(g); } GFG gg = new GFG(); // sort the list list1.Sort(gg); // prints the sorted form of original list Console.WriteLine("\nList in sorted form"); foreach(string g in list1) { Console.WriteLine(g); } //"D" is going to insert //"gg" is the IComparer int index = list1.BinarySearch("D", gg); if (index < 0) { list1.Insert(~index, "D"); } // prints the final List Console.WriteLine("\nAfter inserting \"D\" in the List"); foreach(string g in list1) { Console.WriteLine(g); } }}
Output:
Original string
B
C
E
A
List in sorted form
A
B
C
E
After inserting "D" in the List
A
B
C
D
E
Example 2: In this example, the List is created with some integer values and to insert a new integer using BinarySearch(T, Comparer <T>) method in the List by using a user defined function.
C#
// C# program to demonstrate the// List<T>.BinarySearch(T,// IComparer<T>) Methodusing System;using System.Collections.Generic; class GFG : IComparer<int> { public int Compare(int x, int y) { if (x == 0 || y == 0) { return 0; } return x.CompareTo(y); }} // Driver Classclass geek { // Main Method public static void Main() { // list creation List<int> list1 = new List<int>() { 5, 6, 1, 9}; // prints Original list Console.WriteLine("Original string"); foreach(int g in list1) { Console.WriteLine(g); } // creating object of class GFG GFG gg = new GFG(); // sort the list list1.Sort(gg); // prints the sorted form // of original list Console.WriteLine("\nList in sorted form"); foreach(int g in list1) { Console.WriteLine(g); } bSearch b = new bSearch(); b.binarySearch(list1); }} class bSearch { public void binarySearch(List<int> list1) { // creating object of class GFG GFG gg = new GFG(); // "3" is going to insert // "gg" is the IComparer int index = list1.BinarySearch(3, gg); if (index < 0) { list1.Insert(~index, 3); } // prints the final List Console.WriteLine("\nAfter inserting \"3\" in the List"); foreach(int g in list1) { Console.WriteLine(g); } }}
Original string
5
6
1
9
List in sorted form
1
5
6
9
After inserting "3" in the List
1
3
5
6
9
This method is used to search a range of elements in the sorted List<T> for an element using the specified comparer and returns the zero-based index of the element.
Syntax:
public int BinarySearch (int index, int count, T item, System.Collections.Generic.IComparer<T> comparer);
Parameters:
index: It is the zero-based starting index of the range to search.count: It is the length of the range to search.item: It is the object to locate. The value can be null for the reference type.comparer: It is the IComparer implementation to use when comparing elements, or null to use the default comparer Default.
Return Value: It returns the zero-based index of item in the sorted List<T>, if the item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.
Exceptions:
ArgumentOutOfRangeException: If the index is less than 0 or count is less than 0.
ArgumentException: If the index and count do not represent a valid range.
InvalidOperationException: If the comparer is null.
Example:
C#
// C# program to demonstrate the// List<T>.BinarySearch(Int32,// Int32, T, Comparer <T>) methodusing System;using System.Collections.Generic; class GFG : IComparer<int>{public int Compare(int x, int y){ if (x == 0 || y == 0) { return 0; } return x.CompareTo(y);}} class search { // "binarySearch" functionpublic void binarySearch(List<int> list1, int i){ Console.WriteLine("\nBinarySearch a "+ "range and Insert 3"); // "gg" is the object of class GFG GFG gg = new GFG(); // binary search int index = list1.BinarySearch(0, i, 3, gg); if (index < 0) { // insert "3" list1.Insert(~index, 3); i++; } Display(list1);} // "Display" functionpublic void Display(List<int> list){ foreach( int g in list ) { Console.WriteLine(g); }}} // Driver Classclass geek{ // Main Method public static void Main() { List<int> list1 = new List<int>() { // list elements 15,4,2,9,5,7,6,8,10 }; int i = 7; Console.WriteLine("Original List"); // "d" is the object of // the class "search" search d = new search(); // prints Original list d.Display(list1); // "gg" is the object // of class GFG GFG gg = new GFG(); Console.WriteLine("\nSort a range with "+ "the alternate comparer"); // sort is happens between // index 1 to 7 list1.Sort(1, i, gg); // prints sorted list d.Display(list1); // call "binarySearch" function d.binarySearch(list1,i); }}
Original List
15
4
2
9
5
7
6
8
10
Sort a range with the alternate comparer
15
2
4
5
6
7
8
9
10
BinarySearch a range and Insert 3
15
2
3
4
5
6
7
8
9
10
Note:
If the List<T> contains more than one element with the same value, the method returns only one of the occurrences, and it might return any one of the occurrences, not necessarily the first one.
The List<T> must already be sorted according to the comparer implementation; otherwise, the result is incorrect.
This method is an O(log n) operation, where n is the number of elements in the range.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.binarysearch?view=netframework-4.7.2
surinderdawra388
rajeev0719singh
CSharp-Generic-List
CSharp-Generic-Namespace
CSharp-method
Picked
Technical Scripter 2018
C#
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Method Overriding
C# | Data Types
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 228,
"s": 28,
"text": "List<T>.BinarySearch() Method uses a binary search algorithm to locate a specific element in the sorted List<T> or a portion of it. There are 3 methods in the overload list of this method as follows:"
},
{
"code": null,
"e": 244,
"s": 228,
"text": "BinarySearch(T)"
},
{
"code": null,
"e": 274,
"s": 244,
"text": "BinarySearch(T, IComparer<T>)"
},
{
"code": null,
"e": 319,
"s": 274,
"text": "BinarySearch(Int32, Int32, T, IComparer<T>) "
},
{
"code": null,
"e": 470,
"s": 319,
"text": "This method searches for an element in the entire sorted List<T> using the default comparer and returns the zero-based index of the searched element. "
},
{
"code": null,
"e": 479,
"s": 470,
"text": "Syntax: "
},
{
"code": null,
"e": 513,
"s": 479,
"text": "public int BinarySearch (T item);"
},
{
"code": null,
"e": 613,
"s": 513,
"text": "Here, item is the object which is to be locate and the value of item can be null or reference type."
},
{
"code": null,
"e": 972,
"s": 613,
"text": "Return Type: If the item is found, then this method returns the zero-based index of the element to be searched for and if not found, then a negative number that is the bitwise complement of the index of the next element will be return and the complement is larger than that item. If there is no larger element, the bitwise complement of Count will be return."
},
{
"code": null,
"e": 1174,
"s": 972,
"text": "Exception: This method will give InvalidOperationException if the default comparer Default cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T."
},
{
"code": null,
"e": 1235,
"s": 1174,
"text": "Below programs illustrate the use of above-discussed method:"
},
{
"code": null,
"e": 1247,
"s": 1235,
"text": "Example 1: "
},
{
"code": null,
"e": 1250,
"s": 1247,
"text": "C#"
},
{
"code": "// C# program to illustrate the// List<T>.BinarySearch(T) Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // List creation List<string> Geek = new List<string>(); // List elements Geek.Add(\"ABCD\"); Geek.Add(\"QRST\"); Geek.Add(\"XYZ\"); Geek.Add(\"IJKL\"); Console.WriteLine(\"The Original List is:\"); foreach(string g in Geek) { // prints original List Console.WriteLine(g); } Console.WriteLine(\"\\nThe List in Sorted form\"); // sort the List Geek.Sort(); Console.WriteLine(); foreach(string g in Geek) { // prints the sorted List Console.WriteLine(g); } Console.WriteLine(\"\\nInsert EFGH :\"); // insert \"EFGH\" in the List //\"EFGH\" insert into its original // position when the List is sorted int index = Geek.BinarySearch(\"EFGH\"); if (index < 0) { Geek.Insert(~index, \"EFGH\"); } Console.WriteLine(); foreach(string g in Geek) { // prints the sorted list // after inserting \"EFGH\" Console.WriteLine(g); } }}",
"e": 2639,
"s": 1250,
"text": null
},
{
"code": null,
"e": 2765,
"s": 2639,
"text": "The Original List is:\nABCD\nQRST\nXYZ\nIJKL\n\nThe List in Sorted form\n\nABCD\nIJKL\nQRST\nXYZ\n\nInsert EFGH :\n\nABCD\nEFGH\nIJKL\nQRST\nXYZ"
},
{
"code": null,
"e": 2942,
"s": 2767,
"text": "Example 2: In this example, the List is created with some integer values and to insert a new integer using BinarySearch(T) method in the List by using a user define function."
},
{
"code": null,
"e": 2945,
"s": 2942,
"text": "C#"
},
{
"code": "// C# program to illustrate the// List<T>.BinarySearch(T) Methodusing System;using System.Collections.Generic; class GFG { // method for inserting \"3\"public void binarySearch(List<int> Geek){ // insert \"3\" in the List Console.WriteLine(\"\\nInsert 3 :\"); // \"3\" insert into its original // position when the List is // sorted int index = Geek.BinarySearch(3); if (index < 0) { Geek.Insert(~index, 3); } foreach(int g in Geek) { // prints the sorted list // after inserting \"3\" Console.WriteLine(g); }}} // Driver Classpublic class search { public static void Main() { // List creation GFG gg = new GFG(); List<int> Geek = new List<int>() { 5, 6, 1, 9}; Console.WriteLine(\"Original List\"); foreach(int g in Geek) { Console.WriteLine(g); // prints original List } Console.WriteLine(\"\\nList in Sorted form\"); Geek.Sort(); foreach(int g in Geek) { Console.WriteLine(g); // prints the sorted List } // calling the method \"binarySearch\" gg.binarySearch(Geek); }}",
"e": 4253,
"s": 2945,
"text": null
},
{
"code": null,
"e": 4326,
"s": 4253,
"text": "Original List\n5\n6\n1\n9\n\nList in Sorted form\n1\n5\n6\n9\n\nInsert 3 :\n1\n3\n5\n6\n9"
},
{
"code": null,
"e": 4478,
"s": 4328,
"text": "This method searches for an element in the entire sorted List using the specified comparer and returns the zero-based index of the searched element. "
},
{
"code": null,
"e": 4487,
"s": 4478,
"text": "Syntax: "
},
{
"code": null,
"e": 4573,
"s": 4487,
"text": "public int BinarySearch (T item, System.Collections.Generic.IComparer<T> comparer); "
},
{
"code": null,
"e": 4586,
"s": 4573,
"text": "Parameters: "
},
{
"code": null,
"e": 4677,
"s": 4586,
"text": "item : It is the item to locate and the value of the item can be null for reference types."
},
{
"code": null,
"e": 4758,
"s": 4677,
"text": "comparer : It is the IComparer<T> implementation to use when comparing elements."
},
{
"code": null,
"e": 5070,
"s": 4758,
"text": "Return Value: If the item founds, then this method returns the zero-based index of the element to be searched for and if not found, then a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count."
},
{
"code": null,
"e": 5298,
"s": 5070,
"text": "Exception: This method will give InvalidOperationException if the comparer is null, and the default comparer Default cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T."
},
{
"code": null,
"e": 5363,
"s": 5298,
"text": "Below programs illustrate the use of the above-discussed method:"
},
{
"code": null,
"e": 5375,
"s": 5363,
"text": "Example 1: "
},
{
"code": null,
"e": 5378,
"s": 5375,
"text": "C#"
},
{
"code": "// C# program to demonstrate the// List<T>.BinarySearch(T,// IComparer<T>) Methodusing System;using System.Collections.Generic; class GFG : IComparer<string> { public int Compare(string x, string y) { if (x == null || y == null) { return 0; } return x.CompareTo(y); //\"CompareTo()\" method }} // Driver Classclass geek { // Main Method public static void Main() { // list creation List<string> list1 = new List<string>(); // list elements list1.Add(\"B\"); list1.Add(\"C\"); list1.Add(\"E\"); list1.Add(\"A\"); // prints Original list Console.WriteLine(\"Original string\"); foreach(string g in list1) { Console.WriteLine(g); } GFG gg = new GFG(); // sort the list list1.Sort(gg); // prints the sorted form of original list Console.WriteLine(\"\\nList in sorted form\"); foreach(string g in list1) { Console.WriteLine(g); } //\"D\" is going to insert //\"gg\" is the IComparer int index = list1.BinarySearch(\"D\", gg); if (index < 0) { list1.Insert(~index, \"D\"); } // prints the final List Console.WriteLine(\"\\nAfter inserting \\\"D\\\" in the List\"); foreach(string g in list1) { Console.WriteLine(g); } }}",
"e": 6827,
"s": 5378,
"text": null
},
{
"code": null,
"e": 6835,
"s": 6827,
"text": "Output:"
},
{
"code": null,
"e": 6931,
"s": 6835,
"text": "Original string\nB\nC\nE\nA\n\nList in sorted form\nA\nB\nC\nE\n\nAfter inserting \"D\" in the List\nA\nB\nC\nD\nE"
},
{
"code": null,
"e": 7122,
"s": 6931,
"text": "Example 2: In this example, the List is created with some integer values and to insert a new integer using BinarySearch(T, Comparer <T>) method in the List by using a user defined function. "
},
{
"code": null,
"e": 7125,
"s": 7122,
"text": "C#"
},
{
"code": "// C# program to demonstrate the// List<T>.BinarySearch(T,// IComparer<T>) Methodusing System;using System.Collections.Generic; class GFG : IComparer<int> { public int Compare(int x, int y) { if (x == 0 || y == 0) { return 0; } return x.CompareTo(y); }} // Driver Classclass geek { // Main Method public static void Main() { // list creation List<int> list1 = new List<int>() { 5, 6, 1, 9}; // prints Original list Console.WriteLine(\"Original string\"); foreach(int g in list1) { Console.WriteLine(g); } // creating object of class GFG GFG gg = new GFG(); // sort the list list1.Sort(gg); // prints the sorted form // of original list Console.WriteLine(\"\\nList in sorted form\"); foreach(int g in list1) { Console.WriteLine(g); } bSearch b = new bSearch(); b.binarySearch(list1); }} class bSearch { public void binarySearch(List<int> list1) { // creating object of class GFG GFG gg = new GFG(); // \"3\" is going to insert // \"gg\" is the IComparer int index = list1.BinarySearch(3, gg); if (index < 0) { list1.Insert(~index, 3); } // prints the final List Console.WriteLine(\"\\nAfter inserting \\\"3\\\" in the List\"); foreach(int g in list1) { Console.WriteLine(g); } }}",
"e": 8698,
"s": 7125,
"text": null
},
{
"code": null,
"e": 8794,
"s": 8698,
"text": "Original string\n5\n6\n1\n9\n\nList in sorted form\n1\n5\n6\n9\n\nAfter inserting \"3\" in the List\n1\n3\n5\n6\n9"
},
{
"code": null,
"e": 8961,
"s": 8796,
"text": "This method is used to search a range of elements in the sorted List<T> for an element using the specified comparer and returns the zero-based index of the element."
},
{
"code": null,
"e": 8970,
"s": 8961,
"text": "Syntax: "
},
{
"code": null,
"e": 9076,
"s": 8970,
"text": "public int BinarySearch (int index, int count, T item, System.Collections.Generic.IComparer<T> comparer);"
},
{
"code": null,
"e": 9089,
"s": 9076,
"text": "Parameters: "
},
{
"code": null,
"e": 9405,
"s": 9089,
"text": "index: It is the zero-based starting index of the range to search.count: It is the length of the range to search.item: It is the object to locate. The value can be null for the reference type.comparer: It is the IComparer implementation to use when comparing elements, or null to use the default comparer Default. "
},
{
"code": null,
"e": 9690,
"s": 9405,
"text": "Return Value: It returns the zero-based index of item in the sorted List<T>, if the item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count."
},
{
"code": null,
"e": 9703,
"s": 9690,
"text": "Exceptions: "
},
{
"code": null,
"e": 9785,
"s": 9703,
"text": "ArgumentOutOfRangeException: If the index is less than 0 or count is less than 0."
},
{
"code": null,
"e": 9859,
"s": 9785,
"text": "ArgumentException: If the index and count do not represent a valid range."
},
{
"code": null,
"e": 9911,
"s": 9859,
"text": "InvalidOperationException: If the comparer is null."
},
{
"code": null,
"e": 9921,
"s": 9911,
"text": "Example: "
},
{
"code": null,
"e": 9924,
"s": 9921,
"text": "C#"
},
{
"code": "// C# program to demonstrate the// List<T>.BinarySearch(Int32,// Int32, T, Comparer <T>) methodusing System;using System.Collections.Generic; class GFG : IComparer<int>{public int Compare(int x, int y){ if (x == 0 || y == 0) { return 0; } return x.CompareTo(y);}} class search { // \"binarySearch\" functionpublic void binarySearch(List<int> list1, int i){ Console.WriteLine(\"\\nBinarySearch a \"+ \"range and Insert 3\"); // \"gg\" is the object of class GFG GFG gg = new GFG(); // binary search int index = list1.BinarySearch(0, i, 3, gg); if (index < 0) { // insert \"3\" list1.Insert(~index, 3); i++; } Display(list1);} // \"Display\" functionpublic void Display(List<int> list){ foreach( int g in list ) { Console.WriteLine(g); }}} // Driver Classclass geek{ // Main Method public static void Main() { List<int> list1 = new List<int>() { // list elements 15,4,2,9,5,7,6,8,10 }; int i = 7; Console.WriteLine(\"Original List\"); // \"d\" is the object of // the class \"search\" search d = new search(); // prints Original list d.Display(list1); // \"gg\" is the object // of class GFG GFG gg = new GFG(); Console.WriteLine(\"\\nSort a range with \"+ \"the alternate comparer\"); // sort is happens between // index 1 to 7 list1.Sort(1, i, gg); // prints sorted list d.Display(list1); // call \"binarySearch\" function d.binarySearch(list1,i); }}",
"e": 11753,
"s": 9924,
"text": null
},
{
"code": null,
"e": 11906,
"s": 11753,
"text": "Original List\n15\n4\n2\n9\n5\n7\n6\n8\n10\n\nSort a range with the alternate comparer\n15\n2\n4\n5\n6\n7\n8\n9\n10\n\nBinarySearch a range and Insert 3\n15\n2\n3\n4\n5\n6\n7\n8\n9\n10"
},
{
"code": null,
"e": 11914,
"s": 11908,
"text": "Note:"
},
{
"code": null,
"e": 12108,
"s": 11914,
"text": "If the List<T> contains more than one element with the same value, the method returns only one of the occurrences, and it might return any one of the occurrences, not necessarily the first one."
},
{
"code": null,
"e": 12221,
"s": 12108,
"text": "The List<T> must already be sorted according to the comparer implementation; otherwise, the result is incorrect."
},
{
"code": null,
"e": 12307,
"s": 12221,
"text": "This method is an O(log n) operation, where n is the number of elements in the range."
},
{
"code": null,
"e": 12320,
"s": 12307,
"text": "Reference: "
},
{
"code": null,
"e": 12435,
"s": 12320,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.binarysearch?view=netframework-4.7.2"
},
{
"code": null,
"e": 12454,
"s": 12437,
"text": "surinderdawra388"
},
{
"code": null,
"e": 12470,
"s": 12454,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 12490,
"s": 12470,
"text": "CSharp-Generic-List"
},
{
"code": null,
"e": 12515,
"s": 12490,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 12529,
"s": 12515,
"text": "CSharp-method"
},
{
"code": null,
"e": 12536,
"s": 12529,
"text": "Picked"
},
{
"code": null,
"e": 12560,
"s": 12536,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 12563,
"s": 12560,
"text": "C#"
},
{
"code": null,
"e": 12582,
"s": 12563,
"text": "Technical Scripter"
},
{
"code": null,
"e": 12680,
"s": 12582,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12708,
"s": 12680,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 12739,
"s": 12708,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 12754,
"s": 12739,
"text": "C# | Delegates"
},
{
"code": null,
"e": 12797,
"s": 12754,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 12846,
"s": 12797,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 12869,
"s": 12846,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 12885,
"s": 12869,
"text": "C# | Data Types"
},
{
"code": null,
"e": 12903,
"s": 12885,
"text": "C# | Constructors"
},
{
"code": null,
"e": 12943,
"s": 12903,
"text": "C# | String.IndexOf( ) Method | Set - 1"
}
]
|
MapReduce – Understanding With Real-Life Example | 30 Jul, 2020
MapReduce is a programming model used to perform distributed processing in parallel in a Hadoop cluster, which Makes Hadoop working so fast. When you are dealing with Big Data, serial processing is no more of any use. MapReduce has mainly two tasks which are divided phase-wise:
Map Task
Reduce Task
Let us understand it with a real-time example, and the example helps you understand Mapreduce Programming Model in a story manner:
Suppose the Indian government has assigned you the task to count the population of India. You can demand all the resources you want, but you have to do this task in 4 months. Calculating the population of such a large country is not an easy task for a single person(you). So what will be your approach?.
One of the ways to solve this problem is to divide the country by states and assign individual in-charge to each state to count the population of that state.
Task Of Each Individual: Each Individual has to visit every home present in the state and need to keep a record of each house members as:State_Name Member_House1
State_Name Member_House2
State_Name Member_House3
.
.
State_Name Member_House n
.
.
State_Name Member_House1
State_Name Member_House2
State_Name Member_House3
.
.
State_Name Member_House n
.
.
For Simplicity, we have taken only three states.
This is a simple Divide and Conquer approach and will be followed by each individual to count people in his/her state.
Once they have counted each house member in their respective state. Now they need to sum up their results and need to send it to the Head-quarter at New Delhi.
We have a trained officer at the Head-quarter to receive all the results from each state and aggregate them by each state to get the population of that entire state. and Now, with this approach, you are easily able to count the population of India by summing up the results obtained at Head-quarter.
The Indian Govt. is happy with your work and the next year they asked you to do the same job in 2 months instead of 4 months. Again you will be provided with all the resources you want.
Since the Govt. has provided you with all the resources, you will simply double the number of assigned individual in-charge for each state from one to two. For that divide each state in 2 division and assigned different in-charge for these two divisions as:State_Name_Incharge_division1
State_Name_Incharge_division2
State_Name_Incharge_division1
State_Name_Incharge_division2
Similarly, each individual in charge of its division will gather the information about members from each house and keep its record.
We can also do the same thing at the Head-quarters, so let’s also divide the Head-quarter in two division as:Head-qurter_Division1
Head-qurter_Division2
Head-qurter_Division1
Head-qurter_Division2
Now with this approach, you can find the population of India in two months. But there is a small problem with this, we never want the divisions of the same state to send their result at different Head-quarters then, in that case, we have the partial population of that state in Head-quarter_Division1 and Head-quarter_Division2 which is inconsistent because we want consolidated population by the state, not the partial counting.
One easy way to solve is that we can instruct all individuals of a state to either send there result to Head-quarter_Division1 or Head-quarter_Division2. Similarly, for all the states.
Our problem has been solved, and you successfully did it in two months.
Now, if they ask you to do this process in a month, you know how to approach the solution.
Great, now we have a good scalable model that works so well. The model we have seen in this example is like the MapReduce Programming model. so now you must be aware that MapReduce is a programming model, not a programming language.
Now let’s discuss the phases and important things involved in our model.
1. Map Phase: The Phase where the individual in-charges are collecting the population of each house in their division is Map Phase.
Mapper: Involved individual in-charge for calculating population
Input Splits: The state or the division of the state
Key-Value Pair: Output from each individual Mapper like the key is Rajasthan and value is 2
2. Reduce Phase: The Phase where you are aggregating your result
Reducers: Individuals who are aggregating the actual result. Here in our example, the trained-officers. Each Reducer produce the output as a key-value pair
3. Shuffle Phase: The Phase where the data is copied from Mappers to Reducers is Shuffler’s Phase. It comes in between Map and Reduces phase. Now the Map Phase, Reduce Phase, and Shuffler Phase our the three main Phases of our Mapreduce.
Hadoop
MapReduce
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Hadoop and Spark
Hadoop Streaming Using Python - Word Count Problem
Architecture of HBase
Hadoop - Different Modes of Operation
What is Big Data?
Architecture and Working of Hive
How to Create Table in Hive?
Applications of Big Data
Introduction to Apache Pig
Anatomy of File Read and Write in HDFS | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jul, 2020"
},
{
"code": null,
"e": 333,
"s": 54,
"text": "MapReduce is a programming model used to perform distributed processing in parallel in a Hadoop cluster, which Makes Hadoop working so fast. When you are dealing with Big Data, serial processing is no more of any use. MapReduce has mainly two tasks which are divided phase-wise:"
},
{
"code": null,
"e": 342,
"s": 333,
"text": "Map Task"
},
{
"code": null,
"e": 354,
"s": 342,
"text": "Reduce Task"
},
{
"code": null,
"e": 485,
"s": 354,
"text": "Let us understand it with a real-time example, and the example helps you understand Mapreduce Programming Model in a story manner:"
},
{
"code": null,
"e": 789,
"s": 485,
"text": "Suppose the Indian government has assigned you the task to count the population of India. You can demand all the resources you want, but you have to do this task in 4 months. Calculating the population of such a large country is not an easy task for a single person(you). So what will be your approach?."
},
{
"code": null,
"e": 947,
"s": 789,
"text": "One of the ways to solve this problem is to divide the country by states and assign individual in-charge to each state to count the population of that state."
},
{
"code": null,
"e": 1202,
"s": 947,
"text": "Task Of Each Individual: Each Individual has to visit every home present in the state and need to keep a record of each house members as:State_Name Member_House1 \nState_Name Member_House2\nState_Name Member_House3\n\n.\n.\nState_Name Member_House n \n.\n.\n"
},
{
"code": null,
"e": 1320,
"s": 1202,
"text": "State_Name Member_House1 \nState_Name Member_House2\nState_Name Member_House3\n\n.\n.\nState_Name Member_House n \n.\n.\n"
},
{
"code": null,
"e": 1369,
"s": 1320,
"text": "For Simplicity, we have taken only three states."
},
{
"code": null,
"e": 1488,
"s": 1369,
"text": "This is a simple Divide and Conquer approach and will be followed by each individual to count people in his/her state."
},
{
"code": null,
"e": 1648,
"s": 1488,
"text": "Once they have counted each house member in their respective state. Now they need to sum up their results and need to send it to the Head-quarter at New Delhi."
},
{
"code": null,
"e": 1948,
"s": 1648,
"text": "We have a trained officer at the Head-quarter to receive all the results from each state and aggregate them by each state to get the population of that entire state. and Now, with this approach, you are easily able to count the population of India by summing up the results obtained at Head-quarter."
},
{
"code": null,
"e": 2134,
"s": 1948,
"text": "The Indian Govt. is happy with your work and the next year they asked you to do the same job in 2 months instead of 4 months. Again you will be provided with all the resources you want."
},
{
"code": null,
"e": 2452,
"s": 2134,
"text": "Since the Govt. has provided you with all the resources, you will simply double the number of assigned individual in-charge for each state from one to two. For that divide each state in 2 division and assigned different in-charge for these two divisions as:State_Name_Incharge_division1\nState_Name_Incharge_division2\n"
},
{
"code": null,
"e": 2513,
"s": 2452,
"text": "State_Name_Incharge_division1\nState_Name_Incharge_division2\n"
},
{
"code": null,
"e": 2645,
"s": 2513,
"text": "Similarly, each individual in charge of its division will gather the information about members from each house and keep its record."
},
{
"code": null,
"e": 2799,
"s": 2645,
"text": "We can also do the same thing at the Head-quarters, so let’s also divide the Head-quarter in two division as:Head-qurter_Division1\nHead-qurter_Division2\n"
},
{
"code": null,
"e": 2844,
"s": 2799,
"text": "Head-qurter_Division1\nHead-qurter_Division2\n"
},
{
"code": null,
"e": 3274,
"s": 2844,
"text": "Now with this approach, you can find the population of India in two months. But there is a small problem with this, we never want the divisions of the same state to send their result at different Head-quarters then, in that case, we have the partial population of that state in Head-quarter_Division1 and Head-quarter_Division2 which is inconsistent because we want consolidated population by the state, not the partial counting."
},
{
"code": null,
"e": 3459,
"s": 3274,
"text": "One easy way to solve is that we can instruct all individuals of a state to either send there result to Head-quarter_Division1 or Head-quarter_Division2. Similarly, for all the states."
},
{
"code": null,
"e": 3531,
"s": 3459,
"text": "Our problem has been solved, and you successfully did it in two months."
},
{
"code": null,
"e": 3622,
"s": 3531,
"text": "Now, if they ask you to do this process in a month, you know how to approach the solution."
},
{
"code": null,
"e": 3855,
"s": 3622,
"text": "Great, now we have a good scalable model that works so well. The model we have seen in this example is like the MapReduce Programming model. so now you must be aware that MapReduce is a programming model, not a programming language."
},
{
"code": null,
"e": 3928,
"s": 3855,
"text": "Now let’s discuss the phases and important things involved in our model."
},
{
"code": null,
"e": 4060,
"s": 3928,
"text": "1. Map Phase: The Phase where the individual in-charges are collecting the population of each house in their division is Map Phase."
},
{
"code": null,
"e": 4125,
"s": 4060,
"text": "Mapper: Involved individual in-charge for calculating population"
},
{
"code": null,
"e": 4178,
"s": 4125,
"text": "Input Splits: The state or the division of the state"
},
{
"code": null,
"e": 4270,
"s": 4178,
"text": "Key-Value Pair: Output from each individual Mapper like the key is Rajasthan and value is 2"
},
{
"code": null,
"e": 4335,
"s": 4270,
"text": "2. Reduce Phase: The Phase where you are aggregating your result"
},
{
"code": null,
"e": 4491,
"s": 4335,
"text": "Reducers: Individuals who are aggregating the actual result. Here in our example, the trained-officers. Each Reducer produce the output as a key-value pair"
},
{
"code": null,
"e": 4729,
"s": 4491,
"text": "3. Shuffle Phase: The Phase where the data is copied from Mappers to Reducers is Shuffler’s Phase. It comes in between Map and Reduces phase. Now the Map Phase, Reduce Phase, and Shuffler Phase our the three main Phases of our Mapreduce."
},
{
"code": null,
"e": 4736,
"s": 4729,
"text": "Hadoop"
},
{
"code": null,
"e": 4746,
"s": 4736,
"text": "MapReduce"
},
{
"code": null,
"e": 4753,
"s": 4746,
"text": "Hadoop"
},
{
"code": null,
"e": 4760,
"s": 4753,
"text": "Hadoop"
},
{
"code": null,
"e": 4858,
"s": 4760,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4894,
"s": 4858,
"text": "Difference Between Hadoop and Spark"
},
{
"code": null,
"e": 4945,
"s": 4894,
"text": "Hadoop Streaming Using Python - Word Count Problem"
},
{
"code": null,
"e": 4967,
"s": 4945,
"text": "Architecture of HBase"
},
{
"code": null,
"e": 5005,
"s": 4967,
"text": "Hadoop - Different Modes of Operation"
},
{
"code": null,
"e": 5023,
"s": 5005,
"text": "What is Big Data?"
},
{
"code": null,
"e": 5056,
"s": 5023,
"text": "Architecture and Working of Hive"
},
{
"code": null,
"e": 5085,
"s": 5056,
"text": "How to Create Table in Hive?"
},
{
"code": null,
"e": 5110,
"s": 5085,
"text": "Applications of Big Data"
},
{
"code": null,
"e": 5137,
"s": 5110,
"text": "Introduction to Apache Pig"
}
]
|
PHP | DateTime format() Function | 10 Oct, 2019
The DateTime::format() function is an inbuilt function in PHP which is used to return the new formatted date according to the specified format.
Syntax:
Object oriented stylestring DateTime::format( string $format )orstring DateTimeImmutable::format( string $format )orstring DateTimeInterface::format( string $format )
string DateTime::format( string $format )
or
string DateTimeImmutable::format( string $format )
or
string DateTimeInterface::format( string $format )
Procedural stylestring date_format( DateTimeInterface $object, string $format )
string date_format( DateTimeInterface $object, string $format )
Parameters: This function uses two parameters as mentioned above and described below:
$object: This parameter holds the DateTime object.
$format: This parameter holds the format accepted by date() function.
Return Value: This function return the new formatted date string on success or False on failure.
Below programs illustrate the DateTime::format() function in PHP:
Program 1:
<?php // Initialising the DateTime() object with a date$datetime = new DateTime('2019-09-30'); // Calling the format() function with a // specified format 'd-m-Y'echo $datetime->format('d-m-Y'); ?>
30-09-2019
Program 2:
<?php // Initialising the DateTime() object with a date$datetime = new DateTime('2019-09-30'); // Calling the format() function with a // specified format 'd-m-Y H:i:s'echo $datetime->format('d-m-Y H:i:s'); ?>
30-09-2019 00:00:00
Reference: https://www.php.net/manual/en/datetime.format.php
PHP-date-time
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Oct, 2019"
},
{
"code": null,
"e": 172,
"s": 28,
"text": "The DateTime::format() function is an inbuilt function in PHP which is used to return the new formatted date according to the specified format."
},
{
"code": null,
"e": 180,
"s": 172,
"text": "Syntax:"
},
{
"code": null,
"e": 347,
"s": 180,
"text": "Object oriented stylestring DateTime::format( string $format )orstring DateTimeImmutable::format( string $format )orstring DateTimeInterface::format( string $format )"
},
{
"code": null,
"e": 389,
"s": 347,
"text": "string DateTime::format( string $format )"
},
{
"code": null,
"e": 392,
"s": 389,
"text": "or"
},
{
"code": null,
"e": 443,
"s": 392,
"text": "string DateTimeImmutable::format( string $format )"
},
{
"code": null,
"e": 446,
"s": 443,
"text": "or"
},
{
"code": null,
"e": 497,
"s": 446,
"text": "string DateTimeInterface::format( string $format )"
},
{
"code": null,
"e": 577,
"s": 497,
"text": "Procedural stylestring date_format( DateTimeInterface $object, string $format )"
},
{
"code": null,
"e": 641,
"s": 577,
"text": "string date_format( DateTimeInterface $object, string $format )"
},
{
"code": null,
"e": 727,
"s": 641,
"text": "Parameters: This function uses two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 778,
"s": 727,
"text": "$object: This parameter holds the DateTime object."
},
{
"code": null,
"e": 848,
"s": 778,
"text": "$format: This parameter holds the format accepted by date() function."
},
{
"code": null,
"e": 945,
"s": 848,
"text": "Return Value: This function return the new formatted date string on success or False on failure."
},
{
"code": null,
"e": 1011,
"s": 945,
"text": "Below programs illustrate the DateTime::format() function in PHP:"
},
{
"code": null,
"e": 1022,
"s": 1011,
"text": "Program 1:"
},
{
"code": "<?php // Initialising the DateTime() object with a date$datetime = new DateTime('2019-09-30'); // Calling the format() function with a // specified format 'd-m-Y'echo $datetime->format('d-m-Y'); ?>",
"e": 1223,
"s": 1022,
"text": null
},
{
"code": null,
"e": 1235,
"s": 1223,
"text": "30-09-2019\n"
},
{
"code": null,
"e": 1246,
"s": 1235,
"text": "Program 2:"
},
{
"code": "<?php // Initialising the DateTime() object with a date$datetime = new DateTime('2019-09-30'); // Calling the format() function with a // specified format 'd-m-Y H:i:s'echo $datetime->format('d-m-Y H:i:s'); ?>",
"e": 1459,
"s": 1246,
"text": null
},
{
"code": null,
"e": 1480,
"s": 1459,
"text": "30-09-2019 00:00:00\n"
},
{
"code": null,
"e": 1541,
"s": 1480,
"text": "Reference: https://www.php.net/manual/en/datetime.format.php"
},
{
"code": null,
"e": 1555,
"s": 1541,
"text": "PHP-date-time"
},
{
"code": null,
"e": 1568,
"s": 1555,
"text": "PHP-function"
},
{
"code": null,
"e": 1572,
"s": 1568,
"text": "PHP"
},
{
"code": null,
"e": 1589,
"s": 1572,
"text": "Web Technologies"
},
{
"code": null,
"e": 1593,
"s": 1589,
"text": "PHP"
}
]
|
Y Fractal tree in Python using Turtle | 02 Jul, 2020
A fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Driven by recursion, fractals are images of dynamic systems – the pictures of Chaos.
In this article, we will draw a colorful Y fractal tree using a recursive technique in Python.
Examples:
Output for depth level: (a) 14 (b) 12
turtle: turtle library enables users to draw picture or shapes using commands, providing them with a virtual canvas. turtle comes with Python’s Standard Library. It needs a version of Python with Tk support, as it uses tkinter for the graphics.
Functions used:
fd(x) : draw the cursor forward by x pixels.
rt(x), lt(x) : rotates the facing direction of the cursor by x degrees to the right and left respectively.
colormode(): to change the colour mode to rgb.
pencolor(r, g, b): to set the colour of the turtle pen.
speed(): to set the speed of the turtle.
Approach :
We start by drawing a single ‘Y’ shape for the base(level 1) tree. Then both the branches of the ‘Y’ serve as the base of other two ‘Y’s(level 2).
This process is repeated recursively and size of the Y decreases as level increases.
Colouring of the tree is done level wise: darkest in the base level to lightest in the topmost.
In the implementation below, we will draw a tree of size 80 and level 7.
from turtle import * speed('fastest') # turning the turtle to face upwardsrt(-90) # the acute angle between# the base and branch of the Yangle = 30 # function to plot a Ydef y(sz, level): if level > 0: colormode(255) # splitting the rgb range for green # into equal intervals for each level # setting the colour according # to the current level pencolor(0, 255//level, 0) # drawing the base fd(sz) rt(angle) # recursive call for # the right subtree y(0.8 * sz, level-1) pencolor(0, 255//level, 0) lt( 2 * angle ) # recursive call for # the left subtree y(0.8 * sz, level-1) pencolor(0, 255//level, 0) rt(angle) fd(-sz) # tree of size 80 and level 7y(80, 7)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jul, 2020"
},
{
"code": null,
"e": 328,
"s": 28,
"text": "A fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Driven by recursion, fractals are images of dynamic systems – the pictures of Chaos."
},
{
"code": null,
"e": 423,
"s": 328,
"text": "In this article, we will draw a colorful Y fractal tree using a recursive technique in Python."
},
{
"code": null,
"e": 433,
"s": 423,
"text": "Examples:"
},
{
"code": null,
"e": 471,
"s": 433,
"text": "Output for depth level: (a) 14 (b) 12"
},
{
"code": null,
"e": 716,
"s": 471,
"text": "turtle: turtle library enables users to draw picture or shapes using commands, providing them with a virtual canvas. turtle comes with Python’s Standard Library. It needs a version of Python with Tk support, as it uses tkinter for the graphics."
},
{
"code": null,
"e": 732,
"s": 716,
"text": "Functions used:"
},
{
"code": null,
"e": 777,
"s": 732,
"text": "fd(x) : draw the cursor forward by x pixels."
},
{
"code": null,
"e": 884,
"s": 777,
"text": "rt(x), lt(x) : rotates the facing direction of the cursor by x degrees to the right and left respectively."
},
{
"code": null,
"e": 931,
"s": 884,
"text": "colormode(): to change the colour mode to rgb."
},
{
"code": null,
"e": 987,
"s": 931,
"text": "pencolor(r, g, b): to set the colour of the turtle pen."
},
{
"code": null,
"e": 1028,
"s": 987,
"text": "speed(): to set the speed of the turtle."
},
{
"code": null,
"e": 1039,
"s": 1028,
"text": "Approach :"
},
{
"code": null,
"e": 1186,
"s": 1039,
"text": "We start by drawing a single ‘Y’ shape for the base(level 1) tree. Then both the branches of the ‘Y’ serve as the base of other two ‘Y’s(level 2)."
},
{
"code": null,
"e": 1271,
"s": 1186,
"text": "This process is repeated recursively and size of the Y decreases as level increases."
},
{
"code": null,
"e": 1367,
"s": 1271,
"text": "Colouring of the tree is done level wise: darkest in the base level to lightest in the topmost."
},
{
"code": null,
"e": 1440,
"s": 1367,
"text": "In the implementation below, we will draw a tree of size 80 and level 7."
},
{
"code": "from turtle import * speed('fastest') # turning the turtle to face upwardsrt(-90) # the acute angle between# the base and branch of the Yangle = 30 # function to plot a Ydef y(sz, level): if level > 0: colormode(255) # splitting the rgb range for green # into equal intervals for each level # setting the colour according # to the current level pencolor(0, 255//level, 0) # drawing the base fd(sz) rt(angle) # recursive call for # the right subtree y(0.8 * sz, level-1) pencolor(0, 255//level, 0) lt( 2 * angle ) # recursive call for # the left subtree y(0.8 * sz, level-1) pencolor(0, 255//level, 0) rt(angle) fd(-sz) # tree of size 80 and level 7y(80, 7)",
"e": 2337,
"s": 1440,
"text": null
},
{
"code": null,
"e": 2346,
"s": 2337,
"text": "Output :"
},
{
"code": null,
"e": 2360,
"s": 2346,
"text": "Python-turtle"
},
{
"code": null,
"e": 2367,
"s": 2360,
"text": "Python"
}
]
|
A Shell program To Find The GCD | Linux | 18 Jan, 2021
The given problem asked in fico placement interview round. Find the gcd of two given numbers using shell scripting We are given two numbers A and B and now task is to find the Greatest Common divisor (gcd) of two given number using shell scripting .Asked in interview : FICOExample:
Input
25 15
Output
5
CPP
// Script for finding gcd of two number// echo is for printing the message echo Enter two numbers with space in between // read for scanningread a b // Assigning the value of a to mm = $a // Condition checking if b greater than m// If yes the replace the value of m assign a new valueif [ $b -lt $m ]thenm = $bfi // In do while loop we are checking the gcdwhile [ $m -ne 0 ]dox = `expr $a % $m`y = `expr $b % $m` // If x and y both are 0 then we complete over// process and we print the gcdif [ $x -eq 0 -a $y -eq 0 ]then // Printing the greatest gcd of two given numberecho gcd of $a and $b is $mbreakfim = `expr $m - 1` done
The shell script for the above code is :
echo Enter two numbers with space in between
read a b
//reads numbers
m=$a
if [ $b -lt $m ]
then
m=$b
fi
while [ $m -ne 0 ]
do
x=`expr $a % $m`
y=`expr $b % $m`
if [ $x -eq 0 -a $y -eq 0 ]
then
echo gcd of $a and $b is $m
break
fi
m=`expr $m - 1`
done
This article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
prachi21
FICO
Articles
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
Time complexities of different data structures
Difference Between Object And Class
SQL | DROP, TRUNCATE
Implementation of LinkedList in Javascript
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
cp command in Linux with examples | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 337,
"s": 52,
"text": "The given problem asked in fico placement interview round. Find the gcd of two given numbers using shell scripting We are given two numbers A and B and now task is to find the Greatest Common divisor (gcd) of two given number using shell scripting .Asked in interview : FICOExample: "
},
{
"code": null,
"e": 360,
"s": 337,
"text": "Input\n 25 15\nOutput\n 5"
},
{
"code": null,
"e": 366,
"s": 362,
"text": "CPP"
},
{
"code": "// Script for finding gcd of two number// echo is for printing the message echo Enter two numbers with space in between // read for scanningread a b // Assigning the value of a to mm = $a // Condition checking if b greater than m// If yes the replace the value of m assign a new valueif [ $b -lt $m ]thenm = $bfi // In do while loop we are checking the gcdwhile [ $m -ne 0 ]dox = `expr $a % $m`y = `expr $b % $m` // If x and y both are 0 then we complete over// process and we print the gcdif [ $x -eq 0 -a $y -eq 0 ]then // Printing the greatest gcd of two given numberecho gcd of $a and $b is $mbreakfim = `expr $m - 1` done",
"e": 995,
"s": 366,
"text": null
},
{
"code": null,
"e": 1036,
"s": 995,
"text": "The shell script for the above code is :"
},
{
"code": null,
"e": 1288,
"s": 1036,
"text": "echo Enter two numbers with space in between\nread a b\n//reads numbers\nm=$a\nif [ $b -lt $m ]\nthen\nm=$b\nfi\nwhile [ $m -ne 0 ]\ndo\nx=`expr $a % $m`\ny=`expr $b % $m`\nif [ $x -eq 0 -a $y -eq 0 ]\nthen\necho gcd of $a and $b is $m\nbreak\nfi\nm=`expr $m - 1`\ndone"
},
{
"code": null,
"e": 1710,
"s": 1288,
"text": "This article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 1719,
"s": 1710,
"text": "prachi21"
},
{
"code": null,
"e": 1724,
"s": 1719,
"text": "FICO"
},
{
"code": null,
"e": 1733,
"s": 1724,
"text": "Articles"
},
{
"code": null,
"e": 1744,
"s": 1733,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1842,
"s": 1744,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1868,
"s": 1842,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1915,
"s": 1868,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 1951,
"s": 1915,
"text": "Difference Between Object And Class"
},
{
"code": null,
"e": 1972,
"s": 1951,
"text": "SQL | DROP, TRUNCATE"
},
{
"code": null,
"e": 2015,
"s": 1972,
"text": "Implementation of LinkedList in Javascript"
},
{
"code": null,
"e": 2055,
"s": 2015,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 2095,
"s": 2055,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 2122,
"s": 2095,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 2157,
"s": 2122,
"text": "cut command in Linux with examples"
}
]
|
JavaScript | Iterator | 29 Jan, 2020
It’s an object or pattern that allows us to traverse over a list or collection. Iterators define the sequences and implement the iterator protocol that returns an object by using a next() method that contains the value and done. The value contains the next value of iterator sequence and the done is the boolean value true or false if the last value of the sequence has been consumed then it’s true else false. We can check if any entity is by default iterable or not
We can check its prototype and can see if it is having a method Symbol(Symbol.iterator) or not. In Array.prototype you will find Symbol(Symbol.iterator): ƒ values() method. Array is by default iterable. Also, String, Map & Set are built-in iterables because their prototype objects all have a Symbol.iterator() method.
Program:<script> const array = ['a', 'b', 'c']; const it = array[Symbol.iterator](); // and on this iterator method we have ‘next’ method document.write(JSON.stringify(it.next()));//{ value: "a", done: false } document.write(JSON.stringify(it.next()));//{ value: "b", done: false } document.write(JSON.stringify(it.next()));//{ value: "c", done: false } document.write(JSON.stringify(it.next()));/* Actual it.next() will be { value: undefined, done: true } but here you will get{done: true} output because of JSON.stringify as it omits undefined values*/ </script>
<script> const array = ['a', 'b', 'c']; const it = array[Symbol.iterator](); // and on this iterator method we have ‘next’ method document.write(JSON.stringify(it.next()));//{ value: "a", done: false } document.write(JSON.stringify(it.next()));//{ value: "b", done: false } document.write(JSON.stringify(it.next()));//{ value: "c", done: false } document.write(JSON.stringify(it.next()));/* Actual it.next() will be { value: undefined, done: true } but here you will get{done: true} output because of JSON.stringify as it omits undefined values*/ </script>
Output:{"value":"a","done":false}{"value":"b","done":false}
{"value":"c","done":false}{"done":true}
{"value":"a","done":false}{"value":"b","done":false}
{"value":"c","done":false}{"done":true}
Using for.of loop, we can iterate over any entity (for eg: object) which follows iterable protocol. The for.of loop is going to pull out the value that gets a return by calling the next() method each time.
Program:<script> const array = ['a', 'b', 'c']; const it = array[Symbol.iterator](); for (let value of it) {document.write(value)} </script>
<script> const array = ['a', 'b', 'c']; const it = array[Symbol.iterator](); for (let value of it) {document.write(value)} </script>
Output:abc
abc
Iterable protocol: The object must define a method with ‘Symbol.iterator’ the key which returns an object which itself follows iterator protocol. The object must define ‘next’ method which returns an object having two properties ‘value’ and ‘done’
Syntax:{value: 'item value', done: boolean}
{value: 'item value', done: boolean}
Error scenario:var newIt = arr[Symbol.iterator]
newIt()
//Because it does not properly bind
Uncaught TypeError: Cannot convert undefined or null to object
//How we can fix this
//var newIt = arr[Symbol.iterator].bind(arr);
newIt()
Array Iterator { }
var newIt = arr[Symbol.iterator]
newIt()
//Because it does not properly bind
Uncaught TypeError: Cannot convert undefined or null to object
//How we can fix this
//var newIt = arr[Symbol.iterator].bind(arr);
newIt()
Array Iterator { }
Create our own iterable object:
<script>var iterable = { i: 0, [Symbol.iterator]() { var that = this; return { next() { if (that.i < 5) { return { value: that.i++, done: false } } else { return { value: undefined, done: true } } } } }} for(let value of iterable){document.write(value)}</script>
<script>var iterable = { i: 0, [Symbol.iterator]() { var that = this; return { next() { if (that.i < 5) { return { value: that.i++, done: false } } else { return { value: undefined, done: true } } } } }} for(let value of iterable){document.write(value)}</script>
Output:0 1 2 3 4
0 1 2 3 4
javascript-functions
JavaScript-Misc
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jan, 2020"
},
{
"code": null,
"e": 496,
"s": 28,
"text": "It’s an object or pattern that allows us to traverse over a list or collection. Iterators define the sequences and implement the iterator protocol that returns an object by using a next() method that contains the value and done. The value contains the next value of iterator sequence and the done is the boolean value true or false if the last value of the sequence has been consumed then it’s true else false. We can check if any entity is by default iterable or not"
},
{
"code": null,
"e": 815,
"s": 496,
"text": "We can check its prototype and can see if it is having a method Symbol(Symbol.iterator) or not. In Array.prototype you will find Symbol(Symbol.iterator): ƒ values() method. Array is by default iterable. Also, String, Map & Set are built-in iterables because their prototype objects all have a Symbol.iterator() method."
},
{
"code": null,
"e": 1410,
"s": 815,
"text": "Program:<script> const array = ['a', 'b', 'c']; const it = array[Symbol.iterator](); // and on this iterator method we have ‘next’ method document.write(JSON.stringify(it.next()));//{ value: \"a\", done: false } document.write(JSON.stringify(it.next()));//{ value: \"b\", done: false } document.write(JSON.stringify(it.next()));//{ value: \"c\", done: false } document.write(JSON.stringify(it.next()));/* Actual it.next() will be { value: undefined, done: true } but here you will get{done: true} output because of JSON.stringify as it omits undefined values*/ </script> "
},
{
"code": "<script> const array = ['a', 'b', 'c']; const it = array[Symbol.iterator](); // and on this iterator method we have ‘next’ method document.write(JSON.stringify(it.next()));//{ value: \"a\", done: false } document.write(JSON.stringify(it.next()));//{ value: \"b\", done: false } document.write(JSON.stringify(it.next()));//{ value: \"c\", done: false } document.write(JSON.stringify(it.next()));/* Actual it.next() will be { value: undefined, done: true } but here you will get{done: true} output because of JSON.stringify as it omits undefined values*/ </script> ",
"e": 1997,
"s": 1410,
"text": null
},
{
"code": null,
"e": 2097,
"s": 1997,
"text": "Output:{\"value\":\"a\",\"done\":false}{\"value\":\"b\",\"done\":false}\n{\"value\":\"c\",\"done\":false}{\"done\":true}"
},
{
"code": null,
"e": 2190,
"s": 2097,
"text": "{\"value\":\"a\",\"done\":false}{\"value\":\"b\",\"done\":false}\n{\"value\":\"c\",\"done\":false}{\"done\":true}"
},
{
"code": null,
"e": 2396,
"s": 2190,
"text": "Using for.of loop, we can iterate over any entity (for eg: object) which follows iterable protocol. The for.of loop is going to pull out the value that gets a return by calling the next() method each time."
},
{
"code": null,
"e": 2561,
"s": 2396,
"text": "Program:<script> const array = ['a', 'b', 'c']; const it = array[Symbol.iterator](); for (let value of it) {document.write(value)} </script> "
},
{
"code": "<script> const array = ['a', 'b', 'c']; const it = array[Symbol.iterator](); for (let value of it) {document.write(value)} </script> ",
"e": 2718,
"s": 2561,
"text": null
},
{
"code": null,
"e": 2729,
"s": 2718,
"text": "Output:abc"
},
{
"code": null,
"e": 2733,
"s": 2729,
"text": "abc"
},
{
"code": null,
"e": 2981,
"s": 2733,
"text": "Iterable protocol: The object must define a method with ‘Symbol.iterator’ the key which returns an object which itself follows iterator protocol. The object must define ‘next’ method which returns an object having two properties ‘value’ and ‘done’"
},
{
"code": null,
"e": 3025,
"s": 2981,
"text": "Syntax:{value: 'item value', done: boolean}"
},
{
"code": null,
"e": 3062,
"s": 3025,
"text": "{value: 'item value', done: boolean}"
},
{
"code": null,
"e": 3319,
"s": 3062,
"text": "Error scenario:var newIt = arr[Symbol.iterator]\n\nnewIt()\n\n//Because it does not properly bind\nUncaught TypeError: Cannot convert undefined or null to object \n//How we can fix this \n//var newIt = arr[Symbol.iterator].bind(arr); \n\nnewIt()\nArray Iterator { }\n"
},
{
"code": null,
"e": 3561,
"s": 3319,
"text": "var newIt = arr[Symbol.iterator]\n\nnewIt()\n\n//Because it does not properly bind\nUncaught TypeError: Cannot convert undefined or null to object \n//How we can fix this \n//var newIt = arr[Symbol.iterator].bind(arr); \n\nnewIt()\nArray Iterator { }\n"
},
{
"code": null,
"e": 3593,
"s": 3561,
"text": "Create our own iterable object:"
},
{
"code": null,
"e": 3918,
"s": 3593,
"text": "<script>var iterable = { i: 0, [Symbol.iterator]() { var that = this; return { next() { if (that.i < 5) { return { value: that.i++, done: false } } else { return { value: undefined, done: true } } } } }} for(let value of iterable){document.write(value)}</script>"
},
{
"code": "<script>var iterable = { i: 0, [Symbol.iterator]() { var that = this; return { next() { if (that.i < 5) { return { value: that.i++, done: false } } else { return { value: undefined, done: true } } } } }} for(let value of iterable){document.write(value)}</script>",
"e": 4243,
"s": 3918,
"text": null
},
{
"code": null,
"e": 4260,
"s": 4243,
"text": "Output:0 1 2 3 4"
},
{
"code": null,
"e": 4270,
"s": 4260,
"text": "0 1 2 3 4"
},
{
"code": null,
"e": 4291,
"s": 4270,
"text": "javascript-functions"
},
{
"code": null,
"e": 4307,
"s": 4291,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 4318,
"s": 4307,
"text": "JavaScript"
}
]
|
How to set or get the config variables in Codeigniter ? | 28 Nov, 2021
Config Class: The Config class provides means to retrieve configuration preferences. The config items in Codeigniter can be set and get in the environment. The config value $this->config can be used to get and set items in the environment. The config items are contained within an array, namely, $config. The config file is stored at “application/config/config.php“, which may provide opportunities to add new items or create a separate entity of configuration items.
CodeIgniter by default loads the primary config file (application/config/config.php), whereas the custom files need to be externally loaded.
Setting config variable value: The config variable in CodeIgniter can be set in the environment using the following two methods. The config class method set_item() is used to set the value of a variable in Codeigniter. The set_item() can be used to dynamically set a config item or modify an existing one.
Syntax:
$this->config->set_item('item_name', 'item_value');
Arguments:
item_name: $config array item name to be changed.
item_value: The value to be changed.
PHP
<?php // Setting the value of config variable $this->config->set_item('str', "Hello GFG!"); echo($this->config->item('str'));?>
Output:
[1] "Hello GFG!"
The config item can also be modified or initialized using the key-value pair defined in the $config variable. The item value of the config variable can also be set using the key-value pair in CodeIgniter.
PHP
<?php $config['str'] = "Hello GFG!"; echo($this->config->item('str'));?>
Output:
[1] "Hello GFG!"
Getting config variable value: The config items can also be easily fetched from the CodeIgniter environment. The config class function item() is used to get the value of a config variable in Codeigniter.
Syntax:
$this->config->item('item_name');
Arguments:
item_name: $config array index to be retrieved.
Return Value: This function returns a value of the array index key specified, or NULL if no such key exists.
PHP
<?php // Getting the value of config variable $this->config->item('str');?>
Output:
[1] "Hello GFG!"
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
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": "\n28 Nov, 2021"
},
{
"code": null,
"e": 496,
"s": 28,
"text": "Config Class: The Config class provides means to retrieve configuration preferences. The config items in Codeigniter can be set and get in the environment. The config value $this->config can be used to get and set items in the environment. The config items are contained within an array, namely, $config. The config file is stored at “application/config/config.php“, which may provide opportunities to add new items or create a separate entity of configuration items."
},
{
"code": null,
"e": 637,
"s": 496,
"text": "CodeIgniter by default loads the primary config file (application/config/config.php), whereas the custom files need to be externally loaded."
},
{
"code": null,
"e": 943,
"s": 637,
"text": "Setting config variable value: The config variable in CodeIgniter can be set in the environment using the following two methods. The config class method set_item() is used to set the value of a variable in Codeigniter. The set_item() can be used to dynamically set a config item or modify an existing one."
},
{
"code": null,
"e": 951,
"s": 943,
"text": "Syntax:"
},
{
"code": null,
"e": 1003,
"s": 951,
"text": "$this->config->set_item('item_name', 'item_value');"
},
{
"code": null,
"e": 1016,
"s": 1005,
"text": "Arguments:"
},
{
"code": null,
"e": 1066,
"s": 1016,
"text": "item_name: $config array item name to be changed."
},
{
"code": null,
"e": 1103,
"s": 1066,
"text": "item_value: The value to be changed."
},
{
"code": null,
"e": 1107,
"s": 1103,
"text": "PHP"
},
{
"code": "<?php // Setting the value of config variable $this->config->set_item('str', \"Hello GFG!\"); echo($this->config->item('str'));?>",
"e": 1238,
"s": 1107,
"text": null
},
{
"code": null,
"e": 1246,
"s": 1238,
"text": "Output:"
},
{
"code": null,
"e": 1263,
"s": 1246,
"text": "[1] \"Hello GFG!\""
},
{
"code": null,
"e": 1468,
"s": 1263,
"text": "The config item can also be modified or initialized using the key-value pair defined in the $config variable. The item value of the config variable can also be set using the key-value pair in CodeIgniter."
},
{
"code": null,
"e": 1472,
"s": 1468,
"text": "PHP"
},
{
"code": "<?php $config['str'] = \"Hello GFG!\"; echo($this->config->item('str'));?>",
"e": 1547,
"s": 1472,
"text": null
},
{
"code": null,
"e": 1555,
"s": 1547,
"text": "Output:"
},
{
"code": null,
"e": 1572,
"s": 1555,
"text": "[1] \"Hello GFG!\""
},
{
"code": null,
"e": 1777,
"s": 1572,
"text": "Getting config variable value: The config items can also be easily fetched from the CodeIgniter environment. The config class function item() is used to get the value of a config variable in Codeigniter."
},
{
"code": null,
"e": 1785,
"s": 1777,
"text": "Syntax:"
},
{
"code": null,
"e": 1819,
"s": 1785,
"text": "$this->config->item('item_name');"
},
{
"code": null,
"e": 1830,
"s": 1819,
"text": "Arguments:"
},
{
"code": null,
"e": 1878,
"s": 1830,
"text": "item_name: $config array index to be retrieved."
},
{
"code": null,
"e": 1987,
"s": 1878,
"text": "Return Value: This function returns a value of the array index key specified, or NULL if no such key exists."
},
{
"code": null,
"e": 1991,
"s": 1987,
"text": "PHP"
},
{
"code": "<?php // Getting the value of config variable $this->config->item('str');?>",
"e": 2069,
"s": 1991,
"text": null
},
{
"code": null,
"e": 2077,
"s": 2069,
"text": "Output:"
},
{
"code": null,
"e": 2094,
"s": 2077,
"text": "[1] \"Hello GFG!\""
},
{
"code": null,
"e": 2108,
"s": 2094,
"text": "PHP-Questions"
},
{
"code": null,
"e": 2115,
"s": 2108,
"text": "Picked"
},
{
"code": null,
"e": 2119,
"s": 2115,
"text": "PHP"
},
{
"code": null,
"e": 2136,
"s": 2119,
"text": "Web Technologies"
},
{
"code": null,
"e": 2140,
"s": 2136,
"text": "PHP"
},
{
"code": null,
"e": 2238,
"s": 2140,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2320,
"s": 2238,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 2365,
"s": 2320,
"text": "Difference between HTTP GET and POST Methods"
},
{
"code": null,
"e": 2416,
"s": 2365,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 2446,
"s": 2416,
"text": "PHP | file_exists( ) Function"
},
{
"code": null,
"e": 2469,
"s": 2446,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 2502,
"s": 2469,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2564,
"s": 2502,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2625,
"s": 2564,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2675,
"s": 2625,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Angular ng Bootstrap Toast Component | 06 Jul, 2021
Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.In this article, we will see how to use Toast in angular ng bootstrap. The Toast component is used to make a component that will provide feedback messages to the user.
Installation syntax:
ng add @ng-bootstrap/ng-bootstrap
Approach:
First, install the angular ng bootstrap using the above-mentioned command.
Add the following script in index.html<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>
<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>
Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';
imports: [
NgbModule
]
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
imports: [
NgbModule
]
In app.component.html make a toast component.
Serve the app using ng serve.
Example 1: In this example, we are making a basic example of toast.
app.component.html
<ngb-toast [autohide]="false" id='gfg'> GeeksforGeeks Angular ng bootstrap</ngb-toast>
app.module.ts
import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }
app.component.css
#gfg { margin:40px}
Output:
Example 2: In this example, we are making a toast with header.
app.component.html
<ngb-toast [autohide]="false" id='gfg' header='GeeksforGeeks'> Angular ng bootstrap</ngb-toast>
app.module.ts
import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }
app.component.css
#gfg { margin:40px}
Output:
Reference: https://ng-bootstrap.github.io/#/components/toast/overview
Angular-ng-bootstrap
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
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": "\n06 Jul, 2021"
},
{
"code": null,
"e": 379,
"s": 28,
"text": "Angular ng bootstrap is a bootstrap framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites.In this article, we will see how to use Toast in angular ng bootstrap. The Toast component is used to make a component that will provide feedback messages to the user."
},
{
"code": null,
"e": 400,
"s": 379,
"text": "Installation syntax:"
},
{
"code": null,
"e": 434,
"s": 400,
"text": "ng add @ng-bootstrap/ng-bootstrap"
},
{
"code": null,
"e": 444,
"s": 434,
"text": "Approach:"
},
{
"code": null,
"e": 519,
"s": 444,
"text": "First, install the angular ng bootstrap using the above-mentioned command."
},
{
"code": null,
"e": 658,
"s": 519,
"text": "Add the following script in index.html<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>"
},
{
"code": null,
"e": 759,
"s": 658,
"text": "<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” rel=”stylesheet”>"
},
{
"code": null,
"e": 883,
"s": 759,
"text": "Import ng bootstrap module in module.tsimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimports: [ \n NgbModule\n]\n"
},
{
"code": null,
"e": 968,
"s": 883,
"text": "import { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimports: [ \n NgbModule\n]\n"
},
{
"code": null,
"e": 1014,
"s": 968,
"text": "In app.component.html make a toast component."
},
{
"code": null,
"e": 1044,
"s": 1014,
"text": "Serve the app using ng serve."
},
{
"code": null,
"e": 1114,
"s": 1046,
"text": "Example 1: In this example, we are making a basic example of toast."
},
{
"code": null,
"e": 1133,
"s": 1114,
"text": "app.component.html"
},
{
"code": "<ngb-toast [autohide]=\"false\" id='gfg'> GeeksforGeeks Angular ng bootstrap</ngb-toast>",
"e": 1223,
"s": 1133,
"text": null
},
{
"code": null,
"e": 1237,
"s": 1223,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }",
"e": 1841,
"s": 1237,
"text": null
},
{
"code": null,
"e": 1859,
"s": 1841,
"text": "app.component.css"
},
{
"code": "#gfg { margin:40px}",
"e": 1882,
"s": 1859,
"text": null
},
{
"code": null,
"e": 1890,
"s": 1882,
"text": "Output:"
},
{
"code": null,
"e": 1953,
"s": 1890,
"text": "Example 2: In this example, we are making a toast with header."
},
{
"code": null,
"e": 1972,
"s": 1953,
"text": "app.component.html"
},
{
"code": "<ngb-toast [autohide]=\"false\" id='gfg' header='GeeksforGeeks'> Angular ng bootstrap</ngb-toast>",
"e": 2071,
"s": 1972,
"text": null
},
{
"code": null,
"e": 2085,
"s": 2071,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule }from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule }from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { NgbModule }from '@ng-bootstrap/ng-bootstrap'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, NgbModule ]})export class AppModule { }",
"e": 2688,
"s": 2085,
"text": null
},
{
"code": null,
"e": 2706,
"s": 2688,
"text": "app.component.css"
},
{
"code": "#gfg { margin:40px}",
"e": 2729,
"s": 2706,
"text": null
},
{
"code": null,
"e": 2737,
"s": 2729,
"text": "Output:"
},
{
"code": null,
"e": 2807,
"s": 2737,
"text": "Reference: https://ng-bootstrap.github.io/#/components/toast/overview"
},
{
"code": null,
"e": 2828,
"s": 2807,
"text": "Angular-ng-bootstrap"
},
{
"code": null,
"e": 2838,
"s": 2828,
"text": "AngularJS"
},
{
"code": null,
"e": 2855,
"s": 2838,
"text": "Web Technologies"
},
{
"code": null,
"e": 2953,
"s": 2855,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2977,
"s": 2953,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 3012,
"s": 2977,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 3036,
"s": 3012,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 3089,
"s": 3036,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 3138,
"s": 3089,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 3171,
"s": 3138,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3233,
"s": 3171,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3294,
"s": 3233,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3344,
"s": 3294,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
GATE | GATE CS 2020 | Question 43 | 01 Sep, 2021
Consider the productions A → PQ and A → XY. Each of the five non-terminals A,P,Q,X, and Y has two attributes: s is a synthesized attribute, and i is an inherited attribute. Consider the following rules.
Rule 1: P.i=A.i+2, Q.i=P.i+A.i, and A.s=P.s+Q.s
Rule 2: X.i=A.i+Y.s and Y.i=X.s+A.i
Which one of the following is TRUE ?(A) Both Rule 1 and Rule 2 are L-attributed(B) Only Rule 1 is L-attributed(C) Only Rule 2 is L-attributed(D) Neither Rule 1 nor Rule 2 is L-attributedAnswer: (B)Explanation: According to L-attributed SDT:
If an SDT uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT.Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner.Semantic actions are placed anywhere in RHS.
If an SDT uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT.
Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner.
Semantic actions are placed anywhere in RHS.
Therefore,
Rule 1: P.i=A.i+2, Q.i=P.i+A.i, and A.s=P.s+Q.s
Rule 1 is L-attributed by definition.
However,
Rule 2: X.i=A.i+Y.s and Y.i=X.s+A.i
Rule 2 is not L-attributed because this expression (X. Rule 2: i = A.i + Y.s) fails to satisfy the definition of L-attributed.It is failed for X.i =A.i +Y.s since X take value from its sibling which is present of its right, i.e., (A → XY).
Option (B) is correct.
PYQ - Parsing and SDT with Joyojyoti Acharya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersPYQ - Parsing and SDT with Joyojyoti Acharya | GeeksforGeeks GATEWatch 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:0026:51 / 47:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=3PBTUHdAonk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 231,
"s": 28,
"text": "Consider the productions A → PQ and A → XY. Each of the five non-terminals A,P,Q,X, and Y has two attributes: s is a synthesized attribute, and i is an inherited attribute. Consider the following rules."
},
{
"code": null,
"e": 316,
"s": 231,
"text": "Rule 1: P.i=A.i+2, Q.i=P.i+A.i, and A.s=P.s+Q.s\nRule 2: X.i=A.i+Y.s and Y.i=X.s+A.i "
},
{
"code": null,
"e": 557,
"s": 316,
"text": "Which one of the following is TRUE ?(A) Both Rule 1 and Rule 2 are L-attributed(B) Only Rule 1 is L-attributed(C) Only Rule 2 is L-attributed(D) Neither Rule 1 nor Rule 2 is L-attributedAnswer: (B)Explanation: According to L-attributed SDT:"
},
{
"code": null,
"e": 885,
"s": 557,
"text": "If an SDT uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT.Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner.Semantic actions are placed anywhere in RHS."
},
{
"code": null,
"e": 1075,
"s": 885,
"text": "If an SDT uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT."
},
{
"code": null,
"e": 1170,
"s": 1075,
"text": "Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner."
},
{
"code": null,
"e": 1215,
"s": 1170,
"text": "Semantic actions are placed anywhere in RHS."
},
{
"code": null,
"e": 1226,
"s": 1215,
"text": "Therefore,"
},
{
"code": null,
"e": 1275,
"s": 1226,
"text": "Rule 1: P.i=A.i+2, Q.i=P.i+A.i, and A.s=P.s+Q.s "
},
{
"code": null,
"e": 1313,
"s": 1275,
"text": "Rule 1 is L-attributed by definition."
},
{
"code": null,
"e": 1322,
"s": 1313,
"text": "However,"
},
{
"code": null,
"e": 1359,
"s": 1322,
"text": "Rule 2: X.i=A.i+Y.s and Y.i=X.s+A.i "
},
{
"code": null,
"e": 1599,
"s": 1359,
"text": "Rule 2 is not L-attributed because this expression (X. Rule 2: i = A.i + Y.s) fails to satisfy the definition of L-attributed.It is failed for X.i =A.i +Y.s since X take value from its sibling which is present of its right, i.e., (A → XY)."
},
{
"code": null,
"e": 1622,
"s": 1599,
"text": "Option (B) is correct."
},
{
"code": null,
"e": 2584,
"s": 1622,
"text": "PYQ - Parsing and SDT with Joyojyoti Acharya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersPYQ - Parsing and SDT with Joyojyoti Acharya | GeeksforGeeks GATEWatch 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:0026:51 / 47:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=3PBTUHdAonk\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 2589,
"s": 2584,
"text": "GATE"
},
{
"code": null,
"e": 2687,
"s": 2589,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2729,
"s": 2687,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 2791,
"s": 2729,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 2833,
"s": 2791,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 20"
},
{
"code": null,
"e": 2867,
"s": 2833,
"text": "GATE | GATE CS 2008 | Question 40"
},
{
"code": null,
"e": 2901,
"s": 2867,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 2943,
"s": 2901,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 2985,
"s": 2943,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 3019,
"s": 2985,
"text": "GATE | GATE CS 2011 | Question 49"
},
{
"code": null,
"e": 3053,
"s": 3019,
"text": "GATE | GATE CS 1996 | Question 38"
}
]
|
Python | String Split including spaces | 01 May, 2019
The problems and at the same time applications of list splitting is quite common while working with python strings. The spaces are usually tend to ignore in the use cases. But sometimes, we might not need to omit the spaces but include them in our programming output. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using split() + list comprehension
This kind of operation can be performed using the split function and list comprehension. The main difference in not omitting the space is that we specifically add the spaces that we might have omitted in the process, after each element.
# Python3 code to demonstrate# String Split including spaces# using list comprehension + split() # initializing stringtest_string = "GfG is Best" # printing original stringprint("The original string : " + str(test_string)) # using list comprehension + split()# String Split including spacesres = [i for j in test_string.split() for i in (j, ' ')][:-1] # print resultprint("The list without omitting spaces : " + str(res))
The original string : GfG is Best
The list without omitting spaces : ['GfG', ' ', 'is', ' ', 'Best']
Method #2 : Using zip() + chain() + cycle()
This particular task can also be performed using the combination of above 3 functions. The zip function can be used to bind the logic, chain and cycle function perform the task of inserting the space at appropriate position.
# Python3 code to demonstrate# String Split including spaces# using zip() + chain() + cycle()from itertools import chain, cycle # initializing stringtest_string = "GfG is Best" # printing original stringprint("The original string : " + str(test_string)) # using zip() + chain() + cycle()# String Split including spacesres = list(chain(*zip(test_string.split(), cycle(' '))))[:-1] # print resultprint("The list without omitting spaces : " + str(res))
The original string : GfG is Best
The list without omitting spaces : ['GfG', ' ', 'is', ' ', 'Best']
Python list-programs
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
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 May, 2019"
},
{
"code": null,
"e": 384,
"s": 52,
"text": "The problems and at the same time applications of list splitting is quite common while working with python strings. The spaces are usually tend to ignore in the use cases. But sometimes, we might not need to omit the spaces but include them in our programming output. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 431,
"s": 384,
"text": "Method #1 : Using split() + list comprehension"
},
{
"code": null,
"e": 668,
"s": 431,
"text": "This kind of operation can be performed using the split function and list comprehension. The main difference in not omitting the space is that we specifically add the spaces that we might have omitted in the process, after each element."
},
{
"code": "# Python3 code to demonstrate# String Split including spaces# using list comprehension + split() # initializing stringtest_string = \"GfG is Best\" # printing original stringprint(\"The original string : \" + str(test_string)) # using list comprehension + split()# String Split including spacesres = [i for j in test_string.split() for i in (j, ' ')][:-1] # print resultprint(\"The list without omitting spaces : \" + str(res))",
"e": 1094,
"s": 668,
"text": null
},
{
"code": null,
"e": 1196,
"s": 1094,
"text": "The original string : GfG is Best\nThe list without omitting spaces : ['GfG', ' ', 'is', ' ', 'Best']\n"
},
{
"code": null,
"e": 1242,
"s": 1198,
"text": "Method #2 : Using zip() + chain() + cycle()"
},
{
"code": null,
"e": 1467,
"s": 1242,
"text": "This particular task can also be performed using the combination of above 3 functions. The zip function can be used to bind the logic, chain and cycle function perform the task of inserting the space at appropriate position."
},
{
"code": "# Python3 code to demonstrate# String Split including spaces# using zip() + chain() + cycle()from itertools import chain, cycle # initializing stringtest_string = \"GfG is Best\" # printing original stringprint(\"The original string : \" + str(test_string)) # using zip() + chain() + cycle()# String Split including spacesres = list(chain(*zip(test_string.split(), cycle(' '))))[:-1] # print resultprint(\"The list without omitting spaces : \" + str(res))",
"e": 1921,
"s": 1467,
"text": null
},
{
"code": null,
"e": 2023,
"s": 1921,
"text": "The original string : GfG is Best\nThe list without omitting spaces : ['GfG', ' ', 'is', ' ', 'Best']\n"
},
{
"code": null,
"e": 2044,
"s": 2023,
"text": "Python list-programs"
},
{
"code": null,
"e": 2067,
"s": 2044,
"text": "Python string-programs"
},
{
"code": null,
"e": 2074,
"s": 2067,
"text": "Python"
},
{
"code": null,
"e": 2090,
"s": 2074,
"text": "Python Programs"
},
{
"code": null,
"e": 2188,
"s": 2090,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2206,
"s": 2188,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2248,
"s": 2206,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2270,
"s": 2248,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2296,
"s": 2270,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2328,
"s": 2296,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2350,
"s": 2328,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2389,
"s": 2350,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2427,
"s": 2389,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2464,
"s": 2427,
"text": "Python Program for Fibonacci numbers"
}
]
|
Python PIL | Image.transpose() method | 17 Jun, 2021
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.Image.transpose() Transpose image (flip or rotate in 90 degree steps)
Syntax: Transpose image (flip or rotate in 90 degree steps)Parameters: method – One of PIL.Image.FLIP_LEFT_RIGHT, PIL.Image.FLIP_TOP_BOTTOM, PIL.Image.ROTATE_90, PIL.Image.ROTATE_180, PIL.Image.ROTATE_270 or PIL.Image.TRANSPOSE.Returns type: An Image object.
Image Used:
Python3
# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"C:\Users\System-Pc\Desktop\new.jpg") # Size of the image in pixels (size of original image)# (This is not mandatory)width, height = im.size # Setting the points for cropped imageleft = 6top = height / 4right = 174bottom = 3 * height / 4 # Cropped image of above dimension# (It will not change original image)im1 = im.crop((left, top, right, bottom))newsize = (200, 200)im1 = im1.transpose(Image.FLIP_LEFT_RIGHT)# Shows the image in image viewerim1.show()
Output:
Another example:Here the transform parameter are changed. Image Used
Python3
# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"C:\Users\System-Pc\Desktop\flower1.jpg") # Size of the image in pixels (size of original image)# (This is not mandatory)width, height = im.size # Setting the points for cropped imageleft = 3top = height / 2right = 164bottom = 3 * height / 2 # Cropped image of above dimension# (It will not change original image)im1 = im.crop((left, top, right, bottom))newsize = (1800, 1800)im1 = im1.transpose(Image.FLIP_TOP_BOTTOM)# Shows the image in image viewerim1.show()
Output:
simranarora5sos
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": "\n17 Jun, 2021"
},
{
"code": null,
"e": 425,
"s": 28,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.Image.transpose() Transpose image (flip or rotate in 90 degree steps) "
},
{
"code": null,
"e": 685,
"s": 425,
"text": "Syntax: Transpose image (flip or rotate in 90 degree steps)Parameters: method – One of PIL.Image.FLIP_LEFT_RIGHT, PIL.Image.FLIP_TOP_BOTTOM, PIL.Image.ROTATE_90, PIL.Image.ROTATE_180, PIL.Image.ROTATE_270 or PIL.Image.TRANSPOSE.Returns type: An Image object. "
},
{
"code": null,
"e": 699,
"s": 685,
"text": "Image Used: "
},
{
"code": null,
"e": 709,
"s": 701,
"text": "Python3"
},
{
"code": "# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\new.jpg\") # Size of the image in pixels (size of original image)# (This is not mandatory)width, height = im.size # Setting the points for cropped imageleft = 6top = height / 4right = 174bottom = 3 * height / 4 # Cropped image of above dimension# (It will not change original image)im1 = im.crop((left, top, right, bottom))newsize = (200, 200)im1 = im1.transpose(Image.FLIP_LEFT_RIGHT)# Shows the image in image viewerim1.show()",
"e": 1270,
"s": 709,
"text": null
},
{
"code": null,
"e": 1280,
"s": 1270,
"text": "Output: "
},
{
"code": null,
"e": 1351,
"s": 1280,
"text": "Another example:Here the transform parameter are changed. Image Used "
},
{
"code": null,
"e": 1361,
"s": 1353,
"text": "Python3"
},
{
"code": "# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\flower1.jpg\") # Size of the image in pixels (size of original image)# (This is not mandatory)width, height = im.size # Setting the points for cropped imageleft = 3top = height / 2right = 164bottom = 3 * height / 2 # Cropped image of above dimension# (It will not change original image)im1 = im.crop((left, top, right, bottom))newsize = (1800, 1800)im1 = im1.transpose(Image.FLIP_TOP_BOTTOM)# Shows the image in image viewerim1.show()",
"e": 1928,
"s": 1361,
"text": null
},
{
"code": null,
"e": 1938,
"s": 1928,
"text": "Output: "
},
{
"code": null,
"e": 1956,
"s": 1940,
"text": "simranarora5sos"
},
{
"code": null,
"e": 1967,
"s": 1956,
"text": "Python-pil"
},
{
"code": null,
"e": 1974,
"s": 1967,
"text": "Python"
}
]
|
Find floor and ceil in an unsorted array | 08 Jul, 2022
Given an unsorted array arr[] and an element x, find floor and ceiling of x in arr[0..n-1].Floor of x is the largest element which is smaller than or equal to x. Floor of x doesn’t exist if x is smaller than smallest element of arr[].Ceil of x is the smallest element which is greater than or equal to x. Ceil of x doesn’t exist if x is greater than greates element of arr[].
Examples:
Input : arr[] = {5, 6, 8, 9, 6, 5, 5, 6}
x = 7
Output : Floor = 6
Ceiling = 8
Input : arr[] = {5, 6, 8, 9, 6, 5, 5, 6}
x = 6
Output : Floor = 6
Ceiling = 6
Input : arr[] = {5, 6, 8, 9, 6, 5, 5, 6}
x = 10
Output : Floor = 9
Ceiling doesn't exist.
Method 1 (Use Sorting):
Sort input array. Use binary search to find floor and ceiling of x. Refer this and this for implementation of floor and ceiling in a sorted array.
Sort input array.
Use binary search to find floor and ceiling of x. Refer this and this for implementation of floor and ceiling in a sorted array.
Time Complexity : O(n log n) Auxiliary Space : O(1)
This solution is works well if there are multiple queries of floor and ceiling on a static array. We can sort the array once and answer the queries in O(Log n) time.
Method 2 (Use Linear Search:
The idea is to traverse array and keep track of two distances with respect to x.
Minimum distance of element greater than or equal to x. Minimum distance of element smaller than or equal to x.
Minimum distance of element greater than or equal to x.
Minimum distance of element smaller than or equal to x.
Finally print elements with minimum distances.
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to find floor and ceiling in an// unsorted array.#include<bits/stdc++.h>using namespace std; // Function to floor and ceiling of x in arr[]void floorAndCeil(int arr[], int n, int x){ // Indexes of floor and ceiling int fInd, cInd; // Distances of current floor and ceiling int fDist = INT_MAX, cDist = INT_MAX; for (int i=0; i<n; i++) { // If current element is closer than // previous ceiling. if (arr[i] >= x && cDist > (arr[i] - x)) { cInd = i; cDist = arr[i] - x; } // If current element is closer than // previous floor. if (arr[i] <= x && fDist > (x - arr[i])) { fInd = i; fDist = x - arr[i]; } } if (fDist == INT_MAX) cout << "Floor doesn't exist " << endl; else cout << "Floor is " << arr[fInd] << endl; if (cDist == INT_MAX) cout << "Ceil doesn't exist " << endl; else cout << "Ceil is " << arr[cInd] << endl;} // Driver codeint main(){ int arr[] = {5, 6, 8, 9, 6, 5, 5, 6}; int n = sizeof(arr)/sizeof(int); int x = 7; floorAndCeil(arr, n, x); return 0;}
// Java program to find floor and ceiling in an// unsorted array.import java.io.*; class GFG{ // Function to floor and ceiling of x in arr[] public static void floorAndCeil(int arr[], int x) { int n = arr.length; // Indexes of floor and ceiling int fInd = -1, cInd = -1; // Distances of current floor and ceiling int fDist = Integer.MAX_VALUE, cDist = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { // If current element is closer than // previous ceiling. if (arr[i] >= x && cDist > (arr[i] - x)) { cInd = i; cDist = arr[i] - x; } // If current element is closer than // previous floor. if (arr[i] <= x && fDist > (x - arr[i])) { fInd = i; fDist = x - arr[i]; } } if(fDist == Integer.MAX_VALUE) System.out.println("Floor doesn't exist " ); else System.out.println("Floor is " + arr[fInd]); if(cDist == Integer.MAX_VALUE) System.out.println("Ceil doesn't exist "); else System.out.println("Ceil is " + arr[cInd]); } public static void main (String[] args) { int arr[] = {5, 6, 8, 9, 6, 5, 5, 6}; int x = 7; floorAndCeil(arr, x); }}
# Python 3 program to find# floor and ceiling in an# unsorted array. import sys # Function to floor and# ceiling of x in arr[]def floorAndCeil(arr, n, x): # Distances of current # floor and ceiling fDist = sys.maxsize cDist = sys.maxsize for i in range(n): # If current element is closer # than previous ceiling. if (arr[i] >= x and cDist > (arr[i] - x)): cInd = i cDist = arr[i] - x # If current element is closer # than previous floor. if (arr[i] <= x and fDist > (x - arr[i])): fInd = i fDist = x - arr[i] if (fDist == sys.maxsize): print("Floor doesn't exist ") else: print("Floor is " + str(arr[fInd])) if (cDist == sys.maxsize): print( "Ceil doesn't exist ") else: print("Ceil is " + str(arr[cInd])) # Driver codeif __name__ == "__main__": arr = [5, 6, 8, 9, 6, 5, 5, 6] n = len(arr) x = 7 floorAndCeil(arr, n, x) # This code is contributed# by ChitraNayal
// C# program to find floor and ceiling in an// unsorted array.using System; class GFG { // Function to floor and ceiling of x in arr[] public static void floorAndCeil(int []arr, int x) { int n = arr.Length; // Indexes of floor and ceiling int fInd = -1, cInd = -1; // Distances of current floor and ceiling int fDist = int.MaxValue, cDist =int.MaxValue; for (int i = 0; i < n; i++) { // If current element is closer than // previous ceiling. if (arr[i] >= x && cDist > (arr[i] - x)) { cInd = i; cDist = arr[i] - x; } // If current element is closer than // previous floor. if (arr[i] <= x && fDist > (x - arr[i])) { fInd = i; fDist = x - arr[i]; } } if(fDist == int.MaxValue) Console.Write("Floor doesn't exist " ); else Console.WriteLine("Floor is " + arr[fInd]); if(cDist == int.MaxValue) Console.Write("Ceil doesn't exist "); else Console.Write("Ceil is " + arr[cInd]); } // Driver code public static void Main () { int []arr = {5, 6, 8, 9, 6, 5, 5, 6}; int x = 7; floorAndCeil(arr, x); }} // This code is contributed by nitin mittal.
<?php// PHP program to find// floor and ceiling in// an unsorted array. // Function to floor and// ceiling of x in arr[]function floorAndCeil($arr, $n, $x){ // Indexes of floor // and ceiling $fInd = 0; $cInd = 0; // Distances of current // floor and ceiling $fDist = 999999; $cDist = 999999; for ($i = 0; $i < $n; $i++) { // If current element // is closer than // previous ceiling. if ($arr[$i] >= $x && $cDist > ($arr[$i] - $x)) { $cInd = $i; $cDist = $arr[$i] - $x; } // If current element // is closer than // previous floor. if ($arr[$i] <= $x && $fDist > ($x - $arr[$i])) { $fInd = $i; $fDist = $x - $arr[$i]; } } if ($fDist == 999999) echo "Floor doesn't ". "exist " . "\n" ; else echo "Floor is " . $arr[$fInd] . "\n"; if ($cDist == 999999) echo "Ceil doesn't " . "exist " . "\n"; else echo "Ceil is " . $arr[$cInd] . "\n";} // Driver code$arr = array(5, 6, 8, 9, 6, 5, 5, 6);$n = count($arr);$x = 7;floorAndCeil($arr, $n, $x); // This code is contributed// by Sam007?>
<script>// Javascript program to find floor and ceiling in an// unsorted array. // Function to floor and ceiling of x in arr[] function floorAndCeil(arr,x) { let n = arr.length; // Indexes of floor and ceiling let fInd = -1, cInd = -1; // Distances of current floor and ceiling let fDist = Number.MAX_VALUE, cDist = Number.MAX_VALUE; for (let i = 0; i < n; i++) { // If current element is closer than // previous ceiling. if (arr[i] >= x && cDist > (arr[i] - x)) { cInd = i; cDist = arr[i] - x; } // If current element is closer than // previous floor. if (arr[i] <= x && fDist > (x - arr[i])) { fInd = i; fDist = x - arr[i]; } } if(fDist == Number.MAX_VALUE) document.write("Floor doesn't exist <br>" ); else document.write("Floor is " + arr[fInd]+"<br>"); if(cDist == Number.MAX_VALUE) document.write("Ceil doesn't exist <br>"); else document.write("Ceil is " + arr[cInd]+"<br>"); } let arr=[5, 6, 8, 9, 6, 5, 5, 6]; let x = 7; floorAndCeil(arr, x); // This code is contributed by rag2127</script>
Floor is 6
Ceil is 8
Time Complexity : O(n) Auxiliary Space : O(1)
Related Articles : Ceiling in a sorted array Floor in a sorted array
This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
nitin mittal
Sam007
ukasp
rag2127
hardikkoriintern
Arrays
Matrix
Arrays
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 428,
"s": 52,
"text": "Given an unsorted array arr[] and an element x, find floor and ceiling of x in arr[0..n-1].Floor of x is the largest element which is smaller than or equal to x. Floor of x doesn’t exist if x is smaller than smallest element of arr[].Ceil of x is the smallest element which is greater than or equal to x. Ceil of x doesn’t exist if x is greater than greates element of arr[]."
},
{
"code": null,
"e": 439,
"s": 428,
"text": "Examples: "
},
{
"code": null,
"e": 756,
"s": 439,
"text": "Input : arr[] = {5, 6, 8, 9, 6, 5, 5, 6} \n x = 7\nOutput : Floor = 6\n Ceiling = 8\n\nInput : arr[] = {5, 6, 8, 9, 6, 5, 5, 6} \n x = 6\nOutput : Floor = 6\n Ceiling = 6\n\nInput : arr[] = {5, 6, 8, 9, 6, 5, 5, 6} \n x = 10\nOutput : Floor = 9\n Ceiling doesn't exist."
},
{
"code": null,
"e": 780,
"s": 756,
"text": "Method 1 (Use Sorting):"
},
{
"code": null,
"e": 927,
"s": 780,
"text": "Sort input array. Use binary search to find floor and ceiling of x. Refer this and this for implementation of floor and ceiling in a sorted array."
},
{
"code": null,
"e": 946,
"s": 927,
"text": "Sort input array. "
},
{
"code": null,
"e": 1075,
"s": 946,
"text": "Use binary search to find floor and ceiling of x. Refer this and this for implementation of floor and ceiling in a sorted array."
},
{
"code": null,
"e": 1127,
"s": 1075,
"text": "Time Complexity : O(n log n) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 1293,
"s": 1127,
"text": "This solution is works well if there are multiple queries of floor and ceiling on a static array. We can sort the array once and answer the queries in O(Log n) time."
},
{
"code": null,
"e": 1322,
"s": 1293,
"text": "Method 2 (Use Linear Search:"
},
{
"code": null,
"e": 1404,
"s": 1322,
"text": "The idea is to traverse array and keep track of two distances with respect to x. "
},
{
"code": null,
"e": 1516,
"s": 1404,
"text": "Minimum distance of element greater than or equal to x. Minimum distance of element smaller than or equal to x."
},
{
"code": null,
"e": 1573,
"s": 1516,
"text": "Minimum distance of element greater than or equal to x. "
},
{
"code": null,
"e": 1629,
"s": 1573,
"text": "Minimum distance of element smaller than or equal to x."
},
{
"code": null,
"e": 1677,
"s": 1629,
"text": "Finally print elements with minimum distances. "
},
{
"code": null,
"e": 1681,
"s": 1677,
"text": "C++"
},
{
"code": null,
"e": 1686,
"s": 1681,
"text": "Java"
},
{
"code": null,
"e": 1695,
"s": 1686,
"text": "Python 3"
},
{
"code": null,
"e": 1698,
"s": 1695,
"text": "C#"
},
{
"code": null,
"e": 1702,
"s": 1698,
"text": "PHP"
},
{
"code": null,
"e": 1713,
"s": 1702,
"text": "Javascript"
},
{
"code": "// C++ program to find floor and ceiling in an// unsorted array.#include<bits/stdc++.h>using namespace std; // Function to floor and ceiling of x in arr[]void floorAndCeil(int arr[], int n, int x){ // Indexes of floor and ceiling int fInd, cInd; // Distances of current floor and ceiling int fDist = INT_MAX, cDist = INT_MAX; for (int i=0; i<n; i++) { // If current element is closer than // previous ceiling. if (arr[i] >= x && cDist > (arr[i] - x)) { cInd = i; cDist = arr[i] - x; } // If current element is closer than // previous floor. if (arr[i] <= x && fDist > (x - arr[i])) { fInd = i; fDist = x - arr[i]; } } if (fDist == INT_MAX) cout << \"Floor doesn't exist \" << endl; else cout << \"Floor is \" << arr[fInd] << endl; if (cDist == INT_MAX) cout << \"Ceil doesn't exist \" << endl; else cout << \"Ceil is \" << arr[cInd] << endl;} // Driver codeint main(){ int arr[] = {5, 6, 8, 9, 6, 5, 5, 6}; int n = sizeof(arr)/sizeof(int); int x = 7; floorAndCeil(arr, n, x); return 0;}",
"e": 2855,
"s": 1713,
"text": null
},
{
"code": "// Java program to find floor and ceiling in an// unsorted array.import java.io.*; class GFG{ // Function to floor and ceiling of x in arr[] public static void floorAndCeil(int arr[], int x) { int n = arr.length; // Indexes of floor and ceiling int fInd = -1, cInd = -1; // Distances of current floor and ceiling int fDist = Integer.MAX_VALUE, cDist = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { // If current element is closer than // previous ceiling. if (arr[i] >= x && cDist > (arr[i] - x)) { cInd = i; cDist = arr[i] - x; } // If current element is closer than // previous floor. if (arr[i] <= x && fDist > (x - arr[i])) { fInd = i; fDist = x - arr[i]; } } if(fDist == Integer.MAX_VALUE) System.out.println(\"Floor doesn't exist \" ); else System.out.println(\"Floor is \" + arr[fInd]); if(cDist == Integer.MAX_VALUE) System.out.println(\"Ceil doesn't exist \"); else System.out.println(\"Ceil is \" + arr[cInd]); } public static void main (String[] args) { int arr[] = {5, 6, 8, 9, 6, 5, 5, 6}; int x = 7; floorAndCeil(arr, x); }}",
"e": 4256,
"s": 2855,
"text": null
},
{
"code": "# Python 3 program to find# floor and ceiling in an# unsorted array. import sys # Function to floor and# ceiling of x in arr[]def floorAndCeil(arr, n, x): # Distances of current # floor and ceiling fDist = sys.maxsize cDist = sys.maxsize for i in range(n): # If current element is closer # than previous ceiling. if (arr[i] >= x and cDist > (arr[i] - x)): cInd = i cDist = arr[i] - x # If current element is closer # than previous floor. if (arr[i] <= x and fDist > (x - arr[i])): fInd = i fDist = x - arr[i] if (fDist == sys.maxsize): print(\"Floor doesn't exist \") else: print(\"Floor is \" + str(arr[fInd])) if (cDist == sys.maxsize): print( \"Ceil doesn't exist \") else: print(\"Ceil is \" + str(arr[cInd])) # Driver codeif __name__ == \"__main__\": arr = [5, 6, 8, 9, 6, 5, 5, 6] n = len(arr) x = 7 floorAndCeil(arr, n, x) # This code is contributed# by ChitraNayal",
"e": 5311,
"s": 4256,
"text": null
},
{
"code": "// C# program to find floor and ceiling in an// unsorted array.using System; class GFG { // Function to floor and ceiling of x in arr[] public static void floorAndCeil(int []arr, int x) { int n = arr.Length; // Indexes of floor and ceiling int fInd = -1, cInd = -1; // Distances of current floor and ceiling int fDist = int.MaxValue, cDist =int.MaxValue; for (int i = 0; i < n; i++) { // If current element is closer than // previous ceiling. if (arr[i] >= x && cDist > (arr[i] - x)) { cInd = i; cDist = arr[i] - x; } // If current element is closer than // previous floor. if (arr[i] <= x && fDist > (x - arr[i])) { fInd = i; fDist = x - arr[i]; } } if(fDist == int.MaxValue) Console.Write(\"Floor doesn't exist \" ); else Console.WriteLine(\"Floor is \" + arr[fInd]); if(cDist == int.MaxValue) Console.Write(\"Ceil doesn't exist \"); else Console.Write(\"Ceil is \" + arr[cInd]); } // Driver code public static void Main () { int []arr = {5, 6, 8, 9, 6, 5, 5, 6}; int x = 7; floorAndCeil(arr, x); }} // This code is contributed by nitin mittal.",
"e": 6758,
"s": 5311,
"text": null
},
{
"code": "<?php// PHP program to find// floor and ceiling in// an unsorted array. // Function to floor and// ceiling of x in arr[]function floorAndCeil($arr, $n, $x){ // Indexes of floor // and ceiling $fInd = 0; $cInd = 0; // Distances of current // floor and ceiling $fDist = 999999; $cDist = 999999; for ($i = 0; $i < $n; $i++) { // If current element // is closer than // previous ceiling. if ($arr[$i] >= $x && $cDist > ($arr[$i] - $x)) { $cInd = $i; $cDist = $arr[$i] - $x; } // If current element // is closer than // previous floor. if ($arr[$i] <= $x && $fDist > ($x - $arr[$i])) { $fInd = $i; $fDist = $x - $arr[$i]; } } if ($fDist == 999999) echo \"Floor doesn't \". \"exist \" . \"\\n\" ; else echo \"Floor is \" . $arr[$fInd] . \"\\n\"; if ($cDist == 999999) echo \"Ceil doesn't \" . \"exist \" . \"\\n\"; else echo \"Ceil is \" . $arr[$cInd] . \"\\n\";} // Driver code$arr = array(5, 6, 8, 9, 6, 5, 5, 6);$n = count($arr);$x = 7;floorAndCeil($arr, $n, $x); // This code is contributed// by Sam007?>",
"e": 8047,
"s": 6758,
"text": null
},
{
"code": "<script>// Javascript program to find floor and ceiling in an// unsorted array. // Function to floor and ceiling of x in arr[] function floorAndCeil(arr,x) { let n = arr.length; // Indexes of floor and ceiling let fInd = -1, cInd = -1; // Distances of current floor and ceiling let fDist = Number.MAX_VALUE, cDist = Number.MAX_VALUE; for (let i = 0; i < n; i++) { // If current element is closer than // previous ceiling. if (arr[i] >= x && cDist > (arr[i] - x)) { cInd = i; cDist = arr[i] - x; } // If current element is closer than // previous floor. if (arr[i] <= x && fDist > (x - arr[i])) { fInd = i; fDist = x - arr[i]; } } if(fDist == Number.MAX_VALUE) document.write(\"Floor doesn't exist <br>\" ); else document.write(\"Floor is \" + arr[fInd]+\"<br>\"); if(cDist == Number.MAX_VALUE) document.write(\"Ceil doesn't exist <br>\"); else document.write(\"Ceil is \" + arr[cInd]+\"<br>\"); } let arr=[5, 6, 8, 9, 6, 5, 5, 6]; let x = 7; floorAndCeil(arr, x); // This code is contributed by rag2127</script>",
"e": 9417,
"s": 8047,
"text": null
},
{
"code": null,
"e": 9439,
"s": 9417,
"text": "Floor is 6\nCeil is 8\n"
},
{
"code": null,
"e": 9485,
"s": 9439,
"text": "Time Complexity : O(n) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 9554,
"s": 9485,
"text": "Related Articles : Ceiling in a sorted array Floor in a sorted array"
},
{
"code": null,
"e": 9849,
"s": 9554,
"text": "This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 9862,
"s": 9849,
"text": "nitin mittal"
},
{
"code": null,
"e": 9869,
"s": 9862,
"text": "Sam007"
},
{
"code": null,
"e": 9875,
"s": 9869,
"text": "ukasp"
},
{
"code": null,
"e": 9883,
"s": 9875,
"text": "rag2127"
},
{
"code": null,
"e": 9900,
"s": 9883,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 9907,
"s": 9900,
"text": "Arrays"
},
{
"code": null,
"e": 9914,
"s": 9907,
"text": "Matrix"
},
{
"code": null,
"e": 9921,
"s": 9914,
"text": "Arrays"
},
{
"code": null,
"e": 9928,
"s": 9921,
"text": "Matrix"
}
]
|
Scala | Either | 17 Apr, 2019
In Scala Either, functions exactly similar to an Option. The only dissimilarity is that with Either it is practicable to return a string which can explicate the instructions about the error that appeared. The Either has two children which are named as Right and Left where, Right is similar to the Some class and Left is same as None class. Left is utilized for the failure where, we can return the error occurred inside the child Left of the Either and Right is utilized for Success.Example:
Either[String, Int]
Here, the String is utilized for the Left child of Either as its the left argument of an Either and Int is utilized for the Right child as its the right argument of an Either. Now, let’s discuss it in details with the help of some examples.
Example :// Scala program of Either // Creating object and inheriting// main method of the trait Appobject GfG extends App{ // Defining a method and applying // Either def Name(name: String): Either[String, String] = { if (name.isEmpty) // Left child for failure Left("There is no name.") else // Right child for success Right(name) } // Displays this if name is // not empty println(Name("GeeksforGeeks")) // Displays the String present // in the Left child println(Name(""))}Output:Right(GeeksforGeeks)
Left(There is no name.)
Here, isEmpty method checks if the field of name is empty or filled, if its empty then Left child will return the String inside itself and if this field is not empty then the Right child will return the name stated.
// Scala program of Either // Creating object and inheriting// main method of the trait Appobject GfG extends App{ // Defining a method and applying // Either def Name(name: String): Either[String, String] = { if (name.isEmpty) // Left child for failure Left("There is no name.") else // Right child for success Right(name) } // Displays this if name is // not empty println(Name("GeeksforGeeks")) // Displays the String present // in the Left child println(Name(""))}
Right(GeeksforGeeks)
Left(There is no name.)
Here, isEmpty method checks if the field of name is empty or filled, if its empty then Left child will return the String inside itself and if this field is not empty then the Right child will return the name stated.
Example :// Scala program of Either with// Pattern matching // Creating object and inheriting// main method of the trait Appobject either extends App{ // Defining a method and applying // Either def Division(q: Int, r: Int): Either[String, Int] = { if (q == 0) // Left child for failure Left("Division not possible.") else // Right child for success Right(q / r) } // Assigning values val x = Division(4, 2) // Applying pattern matching x match { case Left(l) => // Displays this if the division // is not possible println("Left: " + l) case Right(r) => // Displays this if division // is possible println("Right: " + r) }}Output:Right: 2
Here, the division is possible which implies success so, Right returns 2. Here, we have utilized Pattern Matching in this example of Either.
// Scala program of Either with// Pattern matching // Creating object and inheriting// main method of the trait Appobject either extends App{ // Defining a method and applying // Either def Division(q: Int, r: Int): Either[String, Int] = { if (q == 0) // Left child for failure Left("Division not possible.") else // Right child for success Right(q / r) } // Assigning values val x = Division(4, 2) // Applying pattern matching x match { case Left(l) => // Displays this if the division // is not possible println("Left: " + l) case Right(r) => // Displays this if division // is possible println("Right: " + r) }}
Right: 2
Here, the division is possible which implies success so, Right returns 2. Here, we have utilized Pattern Matching in this example of Either.
Picked
Scala
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Apr, 2019"
},
{
"code": null,
"e": 521,
"s": 28,
"text": "In Scala Either, functions exactly similar to an Option. The only dissimilarity is that with Either it is practicable to return a string which can explicate the instructions about the error that appeared. The Either has two children which are named as Right and Left where, Right is similar to the Some class and Left is same as None class. Left is utilized for the failure where, we can return the error occurred inside the child Left of the Either and Right is utilized for Success.Example:"
},
{
"code": null,
"e": 542,
"s": 521,
"text": " Either[String, Int]"
},
{
"code": null,
"e": 783,
"s": 542,
"text": "Here, the String is utilized for the Left child of Either as its the left argument of an Either and Int is utilized for the Right child as its the right argument of an Either. Now, let’s discuss it in details with the help of some examples."
},
{
"code": null,
"e": 1642,
"s": 783,
"text": "Example :// Scala program of Either // Creating object and inheriting// main method of the trait Appobject GfG extends App{ // Defining a method and applying // Either def Name(name: String): Either[String, String] = { if (name.isEmpty) // Left child for failure Left(\"There is no name.\") else // Right child for success Right(name) } // Displays this if name is // not empty println(Name(\"GeeksforGeeks\")) // Displays the String present // in the Left child println(Name(\"\"))}Output:Right(GeeksforGeeks)\nLeft(There is no name.)\nHere, isEmpty method checks if the field of name is empty or filled, if its empty then Left child will return the String inside itself and if this field is not empty then the Right child will return the name stated."
},
{
"code": "// Scala program of Either // Creating object and inheriting// main method of the trait Appobject GfG extends App{ // Defining a method and applying // Either def Name(name: String): Either[String, String] = { if (name.isEmpty) // Left child for failure Left(\"There is no name.\") else // Right child for success Right(name) } // Displays this if name is // not empty println(Name(\"GeeksforGeeks\")) // Displays the String present // in the Left child println(Name(\"\"))}",
"e": 2225,
"s": 1642,
"text": null
},
{
"code": null,
"e": 2271,
"s": 2225,
"text": "Right(GeeksforGeeks)\nLeft(There is no name.)\n"
},
{
"code": null,
"e": 2487,
"s": 2271,
"text": "Here, isEmpty method checks if the field of name is empty or filled, if its empty then Left child will return the String inside itself and if this field is not empty then the Right child will return the name stated."
},
{
"code": null,
"e": 3446,
"s": 2487,
"text": "Example :// Scala program of Either with// Pattern matching // Creating object and inheriting// main method of the trait Appobject either extends App{ // Defining a method and applying // Either def Division(q: Int, r: Int): Either[String, Int] = { if (q == 0) // Left child for failure Left(\"Division not possible.\") else // Right child for success Right(q / r) } // Assigning values val x = Division(4, 2) // Applying pattern matching x match { case Left(l) => // Displays this if the division // is not possible println(\"Left: \" + l) case Right(r) => // Displays this if division // is possible println(\"Right: \" + r) }}Output:Right: 2\nHere, the division is possible which implies success so, Right returns 2. Here, we have utilized Pattern Matching in this example of Either."
},
{
"code": "// Scala program of Either with// Pattern matching // Creating object and inheriting// main method of the trait Appobject either extends App{ // Defining a method and applying // Either def Division(q: Int, r: Int): Either[String, Int] = { if (q == 0) // Left child for failure Left(\"Division not possible.\") else // Right child for success Right(q / r) } // Assigning values val x = Division(4, 2) // Applying pattern matching x match { case Left(l) => // Displays this if the division // is not possible println(\"Left: \" + l) case Right(r) => // Displays this if division // is possible println(\"Right: \" + r) }}",
"e": 4240,
"s": 3446,
"text": null
},
{
"code": null,
"e": 4250,
"s": 4240,
"text": "Right: 2\n"
},
{
"code": null,
"e": 4391,
"s": 4250,
"text": "Here, the division is possible which implies success so, Right returns 2. Here, we have utilized Pattern Matching in this example of Either."
},
{
"code": null,
"e": 4398,
"s": 4391,
"text": "Picked"
},
{
"code": null,
"e": 4404,
"s": 4398,
"text": "Scala"
},
{
"code": null,
"e": 4410,
"s": 4404,
"text": "Scala"
}
]
|
SQL NOT NULL Constraint | 22 Sep, 2021
In SQL, constraints are some set of rules that are applied to the data type of the specified table. Or we can say that using constraints we can apply limits on the type of data that can be stored in the particular column of the table. Constraints are typically placed specified along with CREATE statement. By default, a column can hold null values.
Example:
If you don’t want to have a null column or a null value you need to define constraints like NOT NULL. NOT NULL constraints make sure that a column does not hold null values, or in other words, NOT NULL constraint make sure that you cannot insert a new record or update a record without entering a value to the specified column(i.e., NOT NULL column). It prevents for acceptance of NULL values. It can be applied for column-level constraints.
Syntax:
CREATE TABLE table_Name
(
column1 data_type(size) NOT NULL,
column2 data_type(size) NOT NULL,
....
);
In SQL, we can add NOT NULL constraints while creating a table. For example, the “EMPID”, “EName” will not accept NULL values when the EMPLOYEES table is created because NOT NULL constraints are used with these columns.
CREATE TABLE EMPLOYEES(
EMPID INTEGER NOT NULL,
EName VARCHAR2(10) NOT NULL,
DOJ DATE);
We can also add a NOT NULL constraint in the existing table using the ALTER statement. For example, if the EMPLOYEES table has already been created then add NOT NULL constraints to the “DOJ” column use ALTER statements in SQL as follows:
ALTER TABLE EMPLOYEES modify DOJ DATE NOT NULL;
Blogathon-2021
Picked
Blogathon
Class 12
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 378,
"s": 28,
"text": "In SQL, constraints are some set of rules that are applied to the data type of the specified table. Or we can say that using constraints we can apply limits on the type of data that can be stored in the particular column of the table. Constraints are typically placed specified along with CREATE statement. By default, a column can hold null values."
},
{
"code": null,
"e": 387,
"s": 378,
"text": "Example:"
},
{
"code": null,
"e": 830,
"s": 387,
"text": "If you don’t want to have a null column or a null value you need to define constraints like NOT NULL. NOT NULL constraints make sure that a column does not hold null values, or in other words, NOT NULL constraint make sure that you cannot insert a new record or update a record without entering a value to the specified column(i.e., NOT NULL column). It prevents for acceptance of NULL values. It can be applied for column-level constraints. "
},
{
"code": null,
"e": 838,
"s": 830,
"text": "Syntax:"
},
{
"code": null,
"e": 940,
"s": 838,
"text": "CREATE TABLE table_Name\n(\ncolumn1 data_type(size) NOT NULL,\ncolumn2 data_type(size) NOT NULL,\n....\n);"
},
{
"code": null,
"e": 1160,
"s": 940,
"text": "In SQL, we can add NOT NULL constraints while creating a table. For example, the “EMPID”, “EName” will not accept NULL values when the EMPLOYEES table is created because NOT NULL constraints are used with these columns."
},
{
"code": null,
"e": 1248,
"s": 1160,
"text": "CREATE TABLE EMPLOYEES(\nEMPID INTEGER NOT NULL,\nEName VARCHAR2(10) NOT NULL,\nDOJ DATE);"
},
{
"code": null,
"e": 1486,
"s": 1248,
"text": "We can also add a NOT NULL constraint in the existing table using the ALTER statement. For example, if the EMPLOYEES table has already been created then add NOT NULL constraints to the “DOJ” column use ALTER statements in SQL as follows:"
},
{
"code": null,
"e": 1534,
"s": 1486,
"text": "ALTER TABLE EMPLOYEES modify DOJ DATE NOT NULL;"
},
{
"code": null,
"e": 1549,
"s": 1534,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 1556,
"s": 1549,
"text": "Picked"
},
{
"code": null,
"e": 1566,
"s": 1556,
"text": "Blogathon"
},
{
"code": null,
"e": 1575,
"s": 1566,
"text": "Class 12"
},
{
"code": null,
"e": 1591,
"s": 1575,
"text": "School Learning"
},
{
"code": null,
"e": 1610,
"s": 1591,
"text": "School Programming"
}
]
|
How to check whether a form or a control is touched or not in Angular 10 ? | 03 Jun, 2021
In this article, we are going to check whether a form is touched or not in Angular 10. The touched property is used to report that the control or the form is touched or not.
Syntax:
form.touched
Return Value:
boolean: the boolean value to check whether a form is touched or not.
NgModule: Module used by the touched property is:
FormsModule
Approach:
Create the Angular app to be used.
In app.component.html make a form using ngForm directive.
In app.component.ts get the information using the touched property.
Serve the angular app using ng serve to see the output.
Example:
app.component.ts
import { Component } from '@angular/core';import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html'}) export class AppComponent { form = new FormGroup({ name: new FormControl( ), rollno: new FormControl() }); get name(): any { return this.form.get('name'); } onSubmit(): void { console.log("Form is touched : ",this.form.touched); }}
app.component.html
<form [formGroup]="form" (ngSubmit)="onSubmit()"> <input formControlName="name" placeholder="Name"> <br> <button type='submit'>Submit</button> <br><br></form>
Output:
Reference: https://angular.io/api/forms/AbstractControlDirective#touched
AngularJS-Basics
AngularJS-Questions
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 202,
"s": 28,
"text": "In this article, we are going to check whether a form is touched or not in Angular 10. The touched property is used to report that the control or the form is touched or not."
},
{
"code": null,
"e": 210,
"s": 202,
"text": "Syntax:"
},
{
"code": null,
"e": 223,
"s": 210,
"text": "form.touched"
},
{
"code": null,
"e": 237,
"s": 223,
"text": "Return Value:"
},
{
"code": null,
"e": 307,
"s": 237,
"text": "boolean: the boolean value to check whether a form is touched or not."
},
{
"code": null,
"e": 357,
"s": 307,
"text": "NgModule: Module used by the touched property is:"
},
{
"code": null,
"e": 369,
"s": 357,
"text": "FormsModule"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "Approach: "
},
{
"code": null,
"e": 417,
"s": 382,
"text": "Create the Angular app to be used."
},
{
"code": null,
"e": 475,
"s": 417,
"text": "In app.component.html make a form using ngForm directive."
},
{
"code": null,
"e": 543,
"s": 475,
"text": "In app.component.ts get the information using the touched property."
},
{
"code": null,
"e": 599,
"s": 543,
"text": "Serve the angular app using ng serve to see the output."
},
{
"code": null,
"e": 608,
"s": 599,
"text": "Example:"
},
{
"code": null,
"e": 625,
"s": 608,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core';import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html'}) export class AppComponent { form = new FormGroup({ name: new FormControl( ), rollno: new FormControl() }); get name(): any { return this.form.get('name'); } onSubmit(): void { console.log(\"Form is touched : \",this.form.touched); }}",
"e": 1089,
"s": 625,
"text": null
},
{
"code": null,
"e": 1108,
"s": 1089,
"text": "app.component.html"
},
{
"code": "<form [formGroup]=\"form\" (ngSubmit)=\"onSubmit()\"> <input formControlName=\"name\" placeholder=\"Name\"> <br> <button type='submit'>Submit</button> <br><br></form>",
"e": 1275,
"s": 1108,
"text": null
},
{
"code": null,
"e": 1283,
"s": 1275,
"text": "Output:"
},
{
"code": null,
"e": 1356,
"s": 1283,
"text": "Reference: https://angular.io/api/forms/AbstractControlDirective#touched"
},
{
"code": null,
"e": 1373,
"s": 1356,
"text": "AngularJS-Basics"
},
{
"code": null,
"e": 1393,
"s": 1373,
"text": "AngularJS-Questions"
},
{
"code": null,
"e": 1403,
"s": 1393,
"text": "AngularJS"
},
{
"code": null,
"e": 1420,
"s": 1403,
"text": "Web Technologies"
}
]
|
Python | Program to print duplicates from a list of integers | 30 Jun, 2022
Given a list of integers with duplicate elements in it. The task to generate another list, which contains only the duplicate elements. In simple words, the new list should contain the elements which appear more than one.
Examples :
Input : list = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20]
Output : output_list = [20, 30, -20, 60]
Input : list = [-1, 1, -1, 8]
Output : output_list = [-1]
Python3
# Python program to print# duplicates from a list# of integersdef Repeat(x): _size = len(x) repeated = [] for i in range(_size): k = i + 1 for j in range(k, _size): if x[i] == x[j] and x[i] not in repeated: repeated.append(x[i]) return repeated # Driver Codelist1 = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20]print (Repeat(list1)) # This code is contributed# by Sandeep_anand
[20, 30, -20, 60]
Python3
from collections import Counter l1 = [1,2,1,2,3,4,5,1,1,2,5,6,7,8,9,9]d = Counter(l1)print(d) new_list = list([item for item in d if d[item]>1])print(new_list)
Counter({1: 4, 2: 3, 5: 2, 9: 2, 3: 1, 4: 1, 6: 1, 7: 1, 8: 1})
[1, 2, 5, 9]
Python3
# program to print duplicate numbers in a given list# provided inputlist = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9] new = [] # defining output list # condition for reviewing every# element of given input listfor a in list: # checking the occurrence of elements n = list.count(a) # if the occurrence is more than # one we add it to the output list if n > 1: if new.count(a) == 0: # condition to check new.append(a) print(new) # This code is contributed by Himanshu Khune
[1, 2, 5, 9]
Python3
def duplicate(input_list): return list(set([x for x in input_list if input_list.count(x) > 1])) if __name__ == '__main__': input_list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9] print(duplicate(input_list)) # This code is contributed by saikot
[1, 2, 5, 9]
Python3
def duplicate(input_list): new_dict, new_list = {}, [] for i in input_list: if not i in new_dict: new_dict[i] = 1 else: new_dict[i] += 1 for key, values in new_dict.items(): if values > 1: new_list.append(key) return new_list if __name__ == '__main__': input_list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9] print(duplicate(input_list)) # This code is contributed by saikot
[1, 2, 5, 9]
Python3
lis = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]x = []y = []for i in lis: if i not in x: x.append(i)for i in x: if lis.count(i) > 1: y.append(i)print(y)
[1, 2, 5, 9]
sandeep_anand
pragya gupta 1
himanshukhune3
saikot
kogantibhavya
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 273,
"s": 52,
"text": "Given a list of integers with duplicate elements in it. The task to generate another list, which contains only the duplicate elements. In simple words, the new list should contain the elements which appear more than one."
},
{
"code": null,
"e": 285,
"s": 273,
"text": "Examples : "
},
{
"code": null,
"e": 458,
"s": 285,
"text": "Input : list = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20]\nOutput : output_list = [20, 30, -20, 60]\n\n\nInput : list = [-1, 1, -1, 8]\nOutput : output_list = [-1]"
},
{
"code": null,
"e": 466,
"s": 458,
"text": "Python3"
},
{
"code": "# Python program to print# duplicates from a list# of integersdef Repeat(x): _size = len(x) repeated = [] for i in range(_size): k = i + 1 for j in range(k, _size): if x[i] == x[j] and x[i] not in repeated: repeated.append(x[i]) return repeated # Driver Codelist1 = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20]print (Repeat(list1)) # This code is contributed# by Sandeep_anand",
"e": 918,
"s": 466,
"text": null
},
{
"code": null,
"e": 937,
"s": 918,
"text": "[20, 30, -20, 60]\n"
},
{
"code": null,
"e": 945,
"s": 937,
"text": "Python3"
},
{
"code": "from collections import Counter l1 = [1,2,1,2,3,4,5,1,1,2,5,6,7,8,9,9]d = Counter(l1)print(d) new_list = list([item for item in d if d[item]>1])print(new_list)",
"e": 1105,
"s": 945,
"text": null
},
{
"code": null,
"e": 1183,
"s": 1105,
"text": "Counter({1: 4, 2: 3, 5: 2, 9: 2, 3: 1, 4: 1, 6: 1, 7: 1, 8: 1})\n[1, 2, 5, 9]\n"
},
{
"code": null,
"e": 1191,
"s": 1183,
"text": "Python3"
},
{
"code": "# program to print duplicate numbers in a given list# provided inputlist = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9] new = [] # defining output list # condition for reviewing every# element of given input listfor a in list: # checking the occurrence of elements n = list.count(a) # if the occurrence is more than # one we add it to the output list if n > 1: if new.count(a) == 0: # condition to check new.append(a) print(new) # This code is contributed by Himanshu Khune",
"e": 1709,
"s": 1191,
"text": null
},
{
"code": null,
"e": 1723,
"s": 1709,
"text": "[1, 2, 5, 9]\n"
},
{
"code": null,
"e": 1731,
"s": 1723,
"text": "Python3"
},
{
"code": "def duplicate(input_list): return list(set([x for x in input_list if input_list.count(x) > 1])) if __name__ == '__main__': input_list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9] print(duplicate(input_list)) # This code is contributed by saikot",
"e": 1991,
"s": 1731,
"text": null
},
{
"code": null,
"e": 2005,
"s": 1991,
"text": "[1, 2, 5, 9]\n"
},
{
"code": null,
"e": 2013,
"s": 2005,
"text": "Python3"
},
{
"code": "def duplicate(input_list): new_dict, new_list = {}, [] for i in input_list: if not i in new_dict: new_dict[i] = 1 else: new_dict[i] += 1 for key, values in new_dict.items(): if values > 1: new_list.append(key) return new_list if __name__ == '__main__': input_list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9] print(duplicate(input_list)) # This code is contributed by saikot",
"e": 2469,
"s": 2013,
"text": null
},
{
"code": null,
"e": 2483,
"s": 2469,
"text": "[1, 2, 5, 9]\n"
},
{
"code": null,
"e": 2491,
"s": 2483,
"text": "Python3"
},
{
"code": "lis = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]x = []y = []for i in lis: if i not in x: x.append(i)for i in x: if lis.count(i) > 1: y.append(i)print(y)",
"e": 2670,
"s": 2491,
"text": null
},
{
"code": null,
"e": 2684,
"s": 2670,
"text": "[1, 2, 5, 9]\n"
},
{
"code": null,
"e": 2698,
"s": 2684,
"text": "sandeep_anand"
},
{
"code": null,
"e": 2713,
"s": 2698,
"text": "pragya gupta 1"
},
{
"code": null,
"e": 2728,
"s": 2713,
"text": "himanshukhune3"
},
{
"code": null,
"e": 2735,
"s": 2728,
"text": "saikot"
},
{
"code": null,
"e": 2749,
"s": 2735,
"text": "kogantibhavya"
},
{
"code": null,
"e": 2770,
"s": 2749,
"text": "Python list-programs"
},
{
"code": null,
"e": 2782,
"s": 2770,
"text": "python-list"
},
{
"code": null,
"e": 2789,
"s": 2782,
"text": "Python"
},
{
"code": null,
"e": 2805,
"s": 2789,
"text": "Python Programs"
},
{
"code": null,
"e": 2817,
"s": 2805,
"text": "python-list"
}
]
|
Python | Pandas Series.to_csv() | 24 Jun, 2020
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.to_csv() function write the given series object to a comma-separated values (csv) file/format.
Syntax: Series.to_csv(*args, **kwargs)
Parameter :path_or_buf : File path or object, if None is provided the result is returned as a string.sep : String of length 1. Field delimiter for the output file.na_rep : Missing data representation.float_format : Format string for floating point numbers.columns : Columns to writeheader : If a list of strings is given it is assumed to be aliases for the column names.index : Write row names (index).index_label : Column label for index column(s) if desired. If None is given, and header and index are True, then the index names are used.mode : Python write mode, default ‘w’.encoding : A string representing the encoding to use in the output file.compression : Compression mode among the following possible values: {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}.quoting : Defaults to csv.QUOTE_MINIMAL.quotechar : String of length 1. Character used to quote fields.
Returns : None or str
Example #1: Use Series.to_csv() function to convert the given series object to csv format.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe / Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)
Output :
Now we will use Series.to_csv() function to convert the given Series object into a comma separated format.
# convert to comma-separatedsr.to_csv()
Output :
As we can see in the output, the Series.to_csv() function has converted the given Series object into a comma-separated format. Example #2: Use Series.to_csv() function to convert the given series object to csv format.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None]) # Print the seriesprint(sr)
Output :
Now we will use Series.to_csv() function to convert the given Series object into a comma separated format.
# convert to comma-separatedsr.to_csv()
Output :
As we can see in the output, the Series.to_csv() function has converted the given Series object into a comma-separated format.
nidhi_biet
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jun, 2020"
},
{
"code": null,
"e": 311,
"s": 54,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 420,
"s": 311,
"text": "Pandas Series.to_csv() function write the given series object to a comma-separated values (csv) file/format."
},
{
"code": null,
"e": 459,
"s": 420,
"text": "Syntax: Series.to_csv(*args, **kwargs)"
},
{
"code": null,
"e": 1325,
"s": 459,
"text": "Parameter :path_or_buf : File path or object, if None is provided the result is returned as a string.sep : String of length 1. Field delimiter for the output file.na_rep : Missing data representation.float_format : Format string for floating point numbers.columns : Columns to writeheader : If a list of strings is given it is assumed to be aliases for the column names.index : Write row names (index).index_label : Column label for index column(s) if desired. If None is given, and header and index are True, then the index names are used.mode : Python write mode, default ‘w’.encoding : A string representing the encoding to use in the output file.compression : Compression mode among the following possible values: {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}.quoting : Defaults to csv.QUOTE_MINIMAL.quotechar : String of length 1. Character used to quote fields."
},
{
"code": null,
"e": 1347,
"s": 1325,
"text": "Returns : None or str"
},
{
"code": null,
"e": 1438,
"s": 1347,
"text": "Example #1: Use Series.to_csv() function to convert the given series object to csv format."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe / Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)",
"e": 1792,
"s": 1438,
"text": null
},
{
"code": null,
"e": 1801,
"s": 1792,
"text": "Output :"
},
{
"code": null,
"e": 1908,
"s": 1801,
"text": "Now we will use Series.to_csv() function to convert the given Series object into a comma separated format."
},
{
"code": "# convert to comma-separatedsr.to_csv()",
"e": 1948,
"s": 1908,
"text": null
},
{
"code": null,
"e": 1957,
"s": 1948,
"text": "Output :"
},
{
"code": null,
"e": 2175,
"s": 1957,
"text": "As we can see in the output, the Series.to_csv() function has converted the given Series object into a comma-separated format. Example #2: Use Series.to_csv() function to convert the given series object to csv format."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None]) # Print the seriesprint(sr)",
"e": 2347,
"s": 2175,
"text": null
},
{
"code": null,
"e": 2356,
"s": 2347,
"text": "Output :"
},
{
"code": null,
"e": 2463,
"s": 2356,
"text": "Now we will use Series.to_csv() function to convert the given Series object into a comma separated format."
},
{
"code": "# convert to comma-separatedsr.to_csv()",
"e": 2503,
"s": 2463,
"text": null
},
{
"code": null,
"e": 2512,
"s": 2503,
"text": "Output :"
},
{
"code": null,
"e": 2639,
"s": 2512,
"text": "As we can see in the output, the Series.to_csv() function has converted the given Series object into a comma-separated format."
},
{
"code": null,
"e": 2650,
"s": 2639,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2671,
"s": 2650,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2700,
"s": 2671,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2714,
"s": 2700,
"text": "Python-pandas"
},
{
"code": null,
"e": 2721,
"s": 2714,
"text": "Python"
}
]
|
int keyword in C | 15 Jun, 2022
In the C programming language, the keyword ‘int’ is used in a type declaration to give a variable an integer type. However, the fact that the type represents integers does not mean it can represent all integers. The size of an int variable is fixed and determined by the C implementation you use. The C Standard dictates that an int must have a range of at least -32768 to +32767. The C implementation can, and very often do, have a much larger range than this. The range of the int type on a particular C implementation can be obtained via the INT_MAX and INT_MIN variables defined in the header <limits.h>:
C
#include <limits.h>#include <stdio.h> int main(){ printf("minimum int value = %d\n" "maximum int value = %d\n" "size of int in bytes = %zu\n" "size of int in bits = %zu", INT_MIN, INT_MAX, sizeof(int), sizeof(int) * CHAR_BIT);}
minimum int value = -2147483648
maximum int value = 2147483647
size of int in bytes = 4
size of int in bits = 32
Do keep in mind though that not all C implementations are the same, and they don’t all have the same ranges for integer types.
SIGNED INTEGER
The int type in C is a signed integer, which means it can represent both negative and positive numbers. This is in contrast to an unsigned integer (which can be used by declaring a variable unsigned int), which can only represent positive numbers.
Attempting to assign a signed integer type with a value that is outside of its range of representable values (from INT_MIN to INT_MAX) will result in undefined behavior.
Signed integers commonly use two’s complement on all modern machines, and in the upcoming (as of Jan 2022) C23 standard, two’s complement is the only valid way of representing signed integers. You can read more about how signed numbers are represented in binary and why two’s complement is the most common representation in this article.
UNSIGNED INTEGER
In the case of an unsigned integer, only positive numbers can be stored. In this data type, all of the bits in the integer are used to store a positive value, rather than having some reserved for sign information. This means the magnitude of the maximum representable value in an unsigned integer is greater than that of a signed integer with the same number of bits.
In the case of an unsigned int value, the maximum value is specified by the UINT_MAX macro, defined in <limits.h>, and the minimum value is 0. As per the C standard, unsigned arithmetic can never overflow, rather it is performed modulo the maximum value of the unsigned type + 1, so for unsigned int, arithmetic is performed modulo UINT_MAX + 1 such that UINT_MAX + 1 is 0, and UINT_MAX + 2 is 1, and so on:
C
#include <limits.h>#include <stdio.h> int main(){ printf("UINT_MAX + 1 = %u", UINT_MAX + 1);}
UINT_MAX + 1 = 0
tijinabet
tanwarsinghvaibhav
lennymclennington
sagar0719kumar
sumitgumber28
sonaliparkhe9
C Basics
C-Data Types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 661,
"s": 52,
"text": "In the C programming language, the keyword ‘int’ is used in a type declaration to give a variable an integer type. However, the fact that the type represents integers does not mean it can represent all integers. The size of an int variable is fixed and determined by the C implementation you use. The C Standard dictates that an int must have a range of at least -32768 to +32767. The C implementation can, and very often do, have a much larger range than this. The range of the int type on a particular C implementation can be obtained via the INT_MAX and INT_MIN variables defined in the header <limits.h>:"
},
{
"code": null,
"e": 663,
"s": 661,
"text": "C"
},
{
"code": "#include <limits.h>#include <stdio.h> int main(){ printf(\"minimum int value = %d\\n\" \"maximum int value = %d\\n\" \"size of int in bytes = %zu\\n\" \"size of int in bits = %zu\", INT_MIN, INT_MAX, sizeof(int), sizeof(int) * CHAR_BIT);}",
"e": 944,
"s": 663,
"text": null
},
{
"code": null,
"e": 1057,
"s": 944,
"text": "minimum int value = -2147483648\nmaximum int value = 2147483647\nsize of int in bytes = 4\nsize of int in bits = 32"
},
{
"code": null,
"e": 1184,
"s": 1057,
"text": "Do keep in mind though that not all C implementations are the same, and they don’t all have the same ranges for integer types."
},
{
"code": null,
"e": 1199,
"s": 1184,
"text": "SIGNED INTEGER"
},
{
"code": null,
"e": 1447,
"s": 1199,
"text": "The int type in C is a signed integer, which means it can represent both negative and positive numbers. This is in contrast to an unsigned integer (which can be used by declaring a variable unsigned int), which can only represent positive numbers."
},
{
"code": null,
"e": 1617,
"s": 1447,
"text": "Attempting to assign a signed integer type with a value that is outside of its range of representable values (from INT_MIN to INT_MAX) will result in undefined behavior."
},
{
"code": null,
"e": 1955,
"s": 1617,
"text": "Signed integers commonly use two’s complement on all modern machines, and in the upcoming (as of Jan 2022) C23 standard, two’s complement is the only valid way of representing signed integers. You can read more about how signed numbers are represented in binary and why two’s complement is the most common representation in this article."
},
{
"code": null,
"e": 1972,
"s": 1955,
"text": "UNSIGNED INTEGER"
},
{
"code": null,
"e": 2340,
"s": 1972,
"text": "In the case of an unsigned integer, only positive numbers can be stored. In this data type, all of the bits in the integer are used to store a positive value, rather than having some reserved for sign information. This means the magnitude of the maximum representable value in an unsigned integer is greater than that of a signed integer with the same number of bits."
},
{
"code": null,
"e": 2748,
"s": 2340,
"text": "In the case of an unsigned int value, the maximum value is specified by the UINT_MAX macro, defined in <limits.h>, and the minimum value is 0. As per the C standard, unsigned arithmetic can never overflow, rather it is performed modulo the maximum value of the unsigned type + 1, so for unsigned int, arithmetic is performed modulo UINT_MAX + 1 such that UINT_MAX + 1 is 0, and UINT_MAX + 2 is 1, and so on:"
},
{
"code": null,
"e": 2750,
"s": 2748,
"text": "C"
},
{
"code": "#include <limits.h>#include <stdio.h> int main(){ printf(\"UINT_MAX + 1 = %u\", UINT_MAX + 1);}",
"e": 2847,
"s": 2750,
"text": null
},
{
"code": null,
"e": 2864,
"s": 2847,
"text": "UINT_MAX + 1 = 0"
},
{
"code": null,
"e": 2874,
"s": 2864,
"text": "tijinabet"
},
{
"code": null,
"e": 2893,
"s": 2874,
"text": "tanwarsinghvaibhav"
},
{
"code": null,
"e": 2911,
"s": 2893,
"text": "lennymclennington"
},
{
"code": null,
"e": 2926,
"s": 2911,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2940,
"s": 2926,
"text": "sumitgumber28"
},
{
"code": null,
"e": 2954,
"s": 2940,
"text": "sonaliparkhe9"
},
{
"code": null,
"e": 2963,
"s": 2954,
"text": "C Basics"
},
{
"code": null,
"e": 2976,
"s": 2963,
"text": "C-Data Types"
},
{
"code": null,
"e": 2987,
"s": 2976,
"text": "C Language"
}
]
|
Find all distinct palindromic sub-strings of a given string | 14 Jul, 2022
Given a string of lowercase ASCII characters, find all distinct continuous palindromic sub-strings of it.
Examples:
Input: str = "abaaa"
Output: Below are 5 palindrome sub-strings
a
aa
aaa
aba
b
Input: str = "geek"
Output: Below are 4 palindrome sub-strings
e
ee
g
k
Method 1:
Step 1: Finding all palindromes using modified Manacher’s algorithm: Considering each character as a pivot, expand on both sides to find the length of both even and odd length palindromes centered at the pivot character under consideration and store the length in the 2 arrays (odd & even). Time complexity for this step is O(n^2)
Step 2: Inserting all the found palindromes in a HashMap: Insert all the palindromes found from the previous step into a HashMap. Also insert all the individual characters from the string into the HashMap (to generate distinct single letter palindromic sub-strings). Time complexity of this step is O(n^3) assuming that the hash insert search takes O(1) time. Note that there can be at most O(n^2) palindrome sub-strings of a string. In below C++ code ordered hashmap is used where the time complexity of insert and search is O(Logn). In C++, ordered hashmap is implemented using Red Black Tree.
Step 3: Printing the distinct palindromes and number of such distinct palindromes: The last step is to print all values stored in the HashMap (only distinct elements will be hashed due to the property of HashMap). The size of the map gives the number of distinct palindromic continuous sub-strings.
Below is the implementation of the above idea.
C++
Java
Python3
C#
Javascript
// C++ program to find all distinct palindrome sub-strings// of a given string#include <iostream>#include <map>using namespace std; // Function to print all distinct palindrome sub-strings of svoid palindromeSubStrs(string s){ map<string, int> m; int n = s.size(); // table for storing results (2 rows for odd- // and even-length palindromes int R[2][n+1]; // Find all sub-string palindromes from the given input // string insert 'guards' to iterate easily over s s = "@" + s + "#"; for (int j = 0; j <= 1; j++) { int rp = 0; // length of 'palindrome radius' R[j][0] = 0; int i = 1; while (i <= n) { // Attempt to expand palindrome centered at i while (s[i - rp - 1] == s[i + j + rp]) rp++; // Incrementing the length of palindromic // radius as and when we find valid palindrome // Assigning the found palindromic length to odd/even // length array R[j][i] = rp; int k = 1; while ((R[j][i - k] != rp - k) && (k < rp)) { R[j][i + k] = min(R[j][i - k],rp - k); k++; } rp = max(rp - k,0); i += k; } } // remove 'guards' s = s.substr(1, n); // Put all obtained palindromes in a hash map to // find only distinct palindromess m[string(1, s[0])]=1; for (int i = 1; i <= n; i++) { for (int j = 0; j <= 1; j++) for (int rp = R[j][i]; rp > 0; rp--) m[s.substr(i - rp - 1, 2 * rp + j)]=1; m[string(1, s[i])]=1; } //printing all distinct palindromes from hash map cout << "Below are " << m.size()-1 << " palindrome sub-strings"; map<string, int>::iterator ii; for (ii = m.begin(); ii!=m.end(); ++ii) cout << (*ii).first << endl;} // Driver programint main(){ palindromeSubStrs("abaaa"); return 0;}
// Java program to find all distinct palindrome// sub-strings of a given stringimport java.util.Map;import java.util.TreeMap; public class GFG{ // Function to print all distinct palindrome // sub-strings of s static void palindromeSubStrs(String s) { //map<string, int> m; TreeMap<String , Integer> m = new TreeMap<>(); int n = s.length(); // table for storing results (2 rows for odd- // and even-length palindromes int[][] R = new int[2][n+1]; // Find all sub-string palindromes from the // given input string insert 'guards' to // iterate easily over s s = "@" + s + "#"; for (int j = 0; j <= 1; j++) { int rp = 0; // length of 'palindrome radius' R[j][0] = 0; int i = 1; while (i <= n) { // Attempt to expand palindrome centered // at i while (s.charAt(i - rp - 1) == s.charAt(i + j + rp)) rp++; // Incrementing the length of // palindromic radius as and // when we find valid palindrome // Assigning the found palindromic length // to odd/even length array R[j][i] = rp; int k = 1; while ((R[j][i - k] != rp - k) && (k < rp)) { R[j][i + k] = Math.min(R[j][i - k], rp - k); k++; } rp = Math.max(rp - k,0); i += k; } } // remove 'guards' s = s.substring(1, s.length()-1); // Put all obtained palindromes in a hash map to // find only distinct palindromess m.put(s.substring(0,1), 1); for (int i = 1; i < n; i++) { for (int j = 0; j <= 1; j++) for (int rp = R[j][i]; rp > 0; rp--) m.put(s.substring(i - rp - 1, i - rp - 1 + 2 * rp + j), 1); m.put(s.substring(i, i + 1), 1); } // printing all distinct palindromes from // hash map System.out.println("Below are " + (m.size()) + " palindrome sub-strings"); for (Map.Entry<String, Integer> ii:m.entrySet()) System.out.println(ii.getKey()); } // Driver program public static void main(String args[]) { palindromeSubStrs("abaaa"); }}// This code is contributed by Sumit Ghosh
# Python program Find all distinct palindromic sub-strings# of a given string # Function to print all distinct palindrome sub-strings of sdef palindromeSubStrs(s): m = dict() n = len(s) # table for storing results (2 rows for odd- # and even-length palindromes R = [[0 for x in range(n+1)] for x in range(2)] # Find all sub-string palindromes from the given input # string insert 'guards' to iterate easily over s s = "@" + s + "#" for j in range(2): rp = 0 # length of 'palindrome radius' R[j][0] = 0 i = 1 while i <= n: # Attempt to expand palindrome centered at i while s[i - rp - 1] == s[i + j + rp]: rp += 1 # Incrementing the length of palindromic # radius as and when we find valid palindrome # Assigning the found palindromic length to odd/even # length array R[j][i] = rp k = 1 while (R[j][i - k] != rp - k) and (k < rp): R[j][i+k] = min(R[j][i-k], rp - k) k += 1 rp = max(rp - k, 0) i += k # remove guards s = s[1:len(s)-1] # Put all obtained palindromes in a hash map to # find only distinct palindrome m[s[0]] = 1 for i in range(1,n): for j in range(2): for rp in range(R[j][i],0,-1): m[s[i - rp - 1 : i - rp - 1 + 2 * rp + j]] = 1 m[s[i]] = 1 # printing all distinct palindromes from hash map print ("Below are " + str(len(m)) + " pali sub-strings") for i in m: print (i) # Driver programpalindromeSubStrs("abaaa")# This code is contributed by BHAVYA JAIN and ROHIT SIKKA
// C# program to find all distinct palindrome// sub-strings of a given stringusing System;using System.Collections.Generic; class GFG{ // Function to print all distinct palindrome // sub-strings of s public static void palindromeSubStrs(string s) { //map<string, int> m; Dictionary < string, int > m = new Dictionary < string, int > (); int n = s.Length; // table for storing results (2 rows for odd- // and even-length palindromes int[, ] R = new int[2, n + 1]; // Find all sub-string palindromes from the // given input string insert 'guards' to // iterate easily over s s = "@" + s + "#"; for (int j = 0; j <= 1; j++) { int rp = 0; // length of 'palindrome radius' R[j, 0] = 0; int i = 1; while (i <= n) { // Attempt to expand palindrome centered // at i while (s[i - rp - 1] == s[i + j + rp]) // Incrementing the length of // palindromic radius as and // when we find valid palindrome rp++; // Assigning the found palindromic length // to odd/even length array R[j, i] = rp; int k = 1; while ((R[j, i - k] != rp - k) && k < rp) { R[j, i + k] = Math.Min(R[j, i - k], rp - k); k++; } rp = Math.Max(rp - k, 0); i += k; } } // remove 'guards' s = s.Substring(1); // Put all obtained palindromes in a hash map to // find only distinct palindromess if (!m.ContainsKey(s.Substring(0, 1))) m.Add(s.Substring(0, 1), 1); else m[s.Substring(0, 1)]++; for (int i = 1; i < n; i++) { for (int j = 0; j <= 1; j++) for (int rp = R[j, i]; rp > 0; rp--) { if (!m.ContainsKey(s.Substring(i - rp - 1, 2 * rp + j))) m.Add(s.Substring(i - rp - 1, 2 * rp + j), 1); else m[s.Substring(i - rp - 1, 2 * rp + j)]++; } if (!m.ContainsKey(s.Substring(i, 1))) m.Add(s.Substring(i, 1), 1); else m[s.Substring(i, 1)]++; } // printing all distinct palindromes from // hash map Console.WriteLine("Below are " + (m.Count)); foreach(KeyValuePair < string, int > ii in m) Console.WriteLine(ii.Key); } // Driver Code public static void Main(string[] args) { palindromeSubStrs("abaaa"); }} // This code is contributed by// sanjeev2552
<script> // JavaScript program to find all distinct palindrome sub-strings// of a given string // Function to print all distinct palindrome sub-strings of sfunction palindromeSubStrs(s){ let m = new Map(); let n = s.length; // table for storing results (2 rows for odd- // and even-length palindromes let R = new Array(2); for(let i = 0; i < 2; i++) R[i] = new Array(n + 1); // Find all sub-string palindromes from the given input // string insert 'guards' to iterate easily over s s = "@" + s + "#"; for (let j = 0; j <= 1; j++) { let rp = 0; // length of 'palindrome radius' R[j][0] = 0; let i = 1; while (i <= n) { // Attempt to expand palindrome centered at i while (s[i - rp - 1] == s[i + j + rp]) rp++; // Incrementing the length of palindromic // radius as and when we find valid palindrome // Assigning the found palindromic length to odd/even // length array R[j][i] = rp; let k = 1; while ((R[j][i - k] != rp - k) && (k < rp)) { R[j][i + k] = Math.min(R[j][i - k],rp - k); k++; } rp = Math.max(rp - k,0); i += k; } } // remove 'guards' s = s.substring(1, n+1); // Put all obtained palindromes in a hash map to // find only distinct palindromes m.set(`${s[0]}`,1); for (let i = 1; i < n; i++) { for (let j = 0; j <= 1; j++){ for (let rp = R[j][i]; rp > 0; rp--){ m.set(s.substring(i - rp - 1, i + rp + j-1),1); } } m.set(`${s[i]}`,1); } // printing all distinct palindromes from hash map document.write(`Below are ${m.size} palindrome sub-strings`,"</br>"); for(let [x, y] of m) document.write(x,"</br>");} // Driver programpalindromeSubStrs("abaaa"); // This code is contributed by shinjanpatra</script>
Output:
Below are 5 palindrome sub-strings
a
aa
aaa
aba
b
Method 2 :
String length – N
Step 1 : Find all the palindromic sub-strings
First for every sub-string check if it is palindrome or not using dynamic programming like this – https://www.geeksforgeeks.org/count-palindrome-sub-strings-string/
Time complexity – O(N2) and Space complexity – O(N2)
Step 2 : Remove duplicate palindromes
For every index starting from index 0 we will use KMP algorithm and check if prefix and suffix is same and is palindrome then we will put 0 the dp array for that suffix sub-string
Time complexity O(N2) and Space complexity O(N) for KMP array
Step 3 : Print the distinct palindromes and number of such palindromes
For every sub-string check if it is present in dp array (i.e dp[i][j] == true) and print it.
Time complexity O(N2) and Space complexity O(N)
Overall Time complexity – O(N2)
Overall Space complexity – O(N2)
Below is the implementation of the above idea.
C++
// C++ program to find all distinct palindrome sub-strings// of a given string#include <iostream>#include <vector>using namespace std; int solve(string s){ int n = s.size(); // dp array to store whether a substring is palindrome // or not using dynamic programming we can solve this // in O(N^2) // dp[i][j] will be true (1) if substring (i, j) is // palindrome else false (0) vector<vector<bool> > dp(n, vector<bool>(n, false)); for (int i = 0; i < n; i++) { // base case every char is palindrome dp[i][i] = 1; // check for every substring of length 2 if (i < n && s[i] == s[i + 1]) { dp[i][i + 1] = 1; } } // check every substring of length greater than 2 for // palindrome for (int len = 3; len <= n; len++) { for (int i = 0; i + len - 1 < n; i++) { if (s[i] == s[i + (len - 1)] && dp[i + 1][i + (len - 1) - 1]) { dp[i][i + (len - 1)] = true; } } } //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* // here we will apply kmp algorithm for substrings // starting from i = 0 to n-1 when we will find prefix // and suffix of a substring to be equal and it is // palindrome we will make dp[i][j] for that suffix to be // false which means it is already added in the prefix // and we should not count it anymore. vector<int> kmp(n, 0); for (int i = 0; i < n; i++) { // starting kmp for every i form 0 to n-1 int j = 0, k = 1; while (k + i < n) { if (s[j + i] == s[k + i]) { // make suffix to be false // if this suffix is palindrome then it is // already included in prefix dp[k + i - j][k + i] = false; kmp[k++] = ++j; } else if (j > 0) { j = kmp[j - 1]; } else { kmp[k++] = 0; } } } //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* int count = 0; for (int i = 0; i < n; i++) { string str; for (int j = i; j < n; j++) { str += s[j]; if (dp[i][j]) { // count number of resultant distinct // substrings and print that substring count++; cout << str << '\n'; } } } cout << "Total number of distinct palindromes is " << count << '\n';} // Driver code starts// This code is contributed by Aditya Anandint main(){ string s1 = "abaaa", s2 = "aaaaaaaaaa"; solve(s1); solve(s2); return 0;}// Driver code ends
a
aba
b
aa
aaa
Total number of distinct palindromes is 5
a
aa
aaa
aaaa
aaaaa
aaaaaa
aaaaaaa
aaaaaaaa
aaaaaaaaa
aaaaaaaaaa
Total number of distinct palindromes is 10
Similar Problem: Count All Palindrome Sub-Strings in a StringThis article is contributed by Vignesh Narayanan and Sowmya Sampath. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
utkarshver
sanjeev2552
kapoorsagar226
amartyaghoshgfg
adityaanand12017
shinjanpatra
sumitgumber28
sweetyty
mitalibhola94
Linkedin
MakeMyTrip
Ola Cabs
palindrome
SAP Labs
STL
Dynamic Programming
Strings
MakeMyTrip
Ola Cabs
SAP Labs
Linkedin
Strings
Dynamic Programming
palindrome
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jul, 2022"
},
{
"code": null,
"e": 159,
"s": 52,
"text": "Given a string of lowercase ASCII characters, find all distinct continuous palindromic sub-strings of it. "
},
{
"code": null,
"e": 170,
"s": 159,
"text": "Examples: "
},
{
"code": null,
"e": 325,
"s": 170,
"text": "Input: str = \"abaaa\"\nOutput: Below are 5 palindrome sub-strings\na\naa\naaa\naba\nb\n\n\nInput: str = \"geek\"\nOutput: Below are 4 palindrome sub-strings\ne\nee\ng\nk"
},
{
"code": null,
"e": 335,
"s": 325,
"text": "Method 1:"
},
{
"code": null,
"e": 666,
"s": 335,
"text": "Step 1: Finding all palindromes using modified Manacher’s algorithm: Considering each character as a pivot, expand on both sides to find the length of both even and odd length palindromes centered at the pivot character under consideration and store the length in the 2 arrays (odd & even). Time complexity for this step is O(n^2)"
},
{
"code": null,
"e": 1262,
"s": 666,
"text": "Step 2: Inserting all the found palindromes in a HashMap: Insert all the palindromes found from the previous step into a HashMap. Also insert all the individual characters from the string into the HashMap (to generate distinct single letter palindromic sub-strings). Time complexity of this step is O(n^3) assuming that the hash insert search takes O(1) time. Note that there can be at most O(n^2) palindrome sub-strings of a string. In below C++ code ordered hashmap is used where the time complexity of insert and search is O(Logn). In C++, ordered hashmap is implemented using Red Black Tree."
},
{
"code": null,
"e": 1561,
"s": 1262,
"text": "Step 3: Printing the distinct palindromes and number of such distinct palindromes: The last step is to print all values stored in the HashMap (only distinct elements will be hashed due to the property of HashMap). The size of the map gives the number of distinct palindromic continuous sub-strings."
},
{
"code": null,
"e": 1608,
"s": 1561,
"text": "Below is the implementation of the above idea."
},
{
"code": null,
"e": 1612,
"s": 1608,
"text": "C++"
},
{
"code": null,
"e": 1617,
"s": 1612,
"text": "Java"
},
{
"code": null,
"e": 1625,
"s": 1617,
"text": "Python3"
},
{
"code": null,
"e": 1628,
"s": 1625,
"text": "C#"
},
{
"code": null,
"e": 1639,
"s": 1628,
"text": "Javascript"
},
{
"code": "// C++ program to find all distinct palindrome sub-strings// of a given string#include <iostream>#include <map>using namespace std; // Function to print all distinct palindrome sub-strings of svoid palindromeSubStrs(string s){ map<string, int> m; int n = s.size(); // table for storing results (2 rows for odd- // and even-length palindromes int R[2][n+1]; // Find all sub-string palindromes from the given input // string insert 'guards' to iterate easily over s s = \"@\" + s + \"#\"; for (int j = 0; j <= 1; j++) { int rp = 0; // length of 'palindrome radius' R[j][0] = 0; int i = 1; while (i <= n) { // Attempt to expand palindrome centered at i while (s[i - rp - 1] == s[i + j + rp]) rp++; // Incrementing the length of palindromic // radius as and when we find valid palindrome // Assigning the found palindromic length to odd/even // length array R[j][i] = rp; int k = 1; while ((R[j][i - k] != rp - k) && (k < rp)) { R[j][i + k] = min(R[j][i - k],rp - k); k++; } rp = max(rp - k,0); i += k; } } // remove 'guards' s = s.substr(1, n); // Put all obtained palindromes in a hash map to // find only distinct palindromess m[string(1, s[0])]=1; for (int i = 1; i <= n; i++) { for (int j = 0; j <= 1; j++) for (int rp = R[j][i]; rp > 0; rp--) m[s.substr(i - rp - 1, 2 * rp + j)]=1; m[string(1, s[i])]=1; } //printing all distinct palindromes from hash map cout << \"Below are \" << m.size()-1 << \" palindrome sub-strings\"; map<string, int>::iterator ii; for (ii = m.begin(); ii!=m.end(); ++ii) cout << (*ii).first << endl;} // Driver programint main(){ palindromeSubStrs(\"abaaa\"); return 0;}",
"e": 3612,
"s": 1639,
"text": null
},
{
"code": "// Java program to find all distinct palindrome// sub-strings of a given stringimport java.util.Map;import java.util.TreeMap; public class GFG{ // Function to print all distinct palindrome // sub-strings of s static void palindromeSubStrs(String s) { //map<string, int> m; TreeMap<String , Integer> m = new TreeMap<>(); int n = s.length(); // table for storing results (2 rows for odd- // and even-length palindromes int[][] R = new int[2][n+1]; // Find all sub-string palindromes from the // given input string insert 'guards' to // iterate easily over s s = \"@\" + s + \"#\"; for (int j = 0; j <= 1; j++) { int rp = 0; // length of 'palindrome radius' R[j][0] = 0; int i = 1; while (i <= n) { // Attempt to expand palindrome centered // at i while (s.charAt(i - rp - 1) == s.charAt(i + j + rp)) rp++; // Incrementing the length of // palindromic radius as and // when we find valid palindrome // Assigning the found palindromic length // to odd/even length array R[j][i] = rp; int k = 1; while ((R[j][i - k] != rp - k) && (k < rp)) { R[j][i + k] = Math.min(R[j][i - k], rp - k); k++; } rp = Math.max(rp - k,0); i += k; } } // remove 'guards' s = s.substring(1, s.length()-1); // Put all obtained palindromes in a hash map to // find only distinct palindromess m.put(s.substring(0,1), 1); for (int i = 1; i < n; i++) { for (int j = 0; j <= 1; j++) for (int rp = R[j][i]; rp > 0; rp--) m.put(s.substring(i - rp - 1, i - rp - 1 + 2 * rp + j), 1); m.put(s.substring(i, i + 1), 1); } // printing all distinct palindromes from // hash map System.out.println(\"Below are \" + (m.size()) + \" palindrome sub-strings\"); for (Map.Entry<String, Integer> ii:m.entrySet()) System.out.println(ii.getKey()); } // Driver program public static void main(String args[]) { palindromeSubStrs(\"abaaa\"); }}// This code is contributed by Sumit Ghosh",
"e": 6288,
"s": 3612,
"text": null
},
{
"code": "# Python program Find all distinct palindromic sub-strings# of a given string # Function to print all distinct palindrome sub-strings of sdef palindromeSubStrs(s): m = dict() n = len(s) # table for storing results (2 rows for odd- # and even-length palindromes R = [[0 for x in range(n+1)] for x in range(2)] # Find all sub-string palindromes from the given input # string insert 'guards' to iterate easily over s s = \"@\" + s + \"#\" for j in range(2): rp = 0 # length of 'palindrome radius' R[j][0] = 0 i = 1 while i <= n: # Attempt to expand palindrome centered at i while s[i - rp - 1] == s[i + j + rp]: rp += 1 # Incrementing the length of palindromic # radius as and when we find valid palindrome # Assigning the found palindromic length to odd/even # length array R[j][i] = rp k = 1 while (R[j][i - k] != rp - k) and (k < rp): R[j][i+k] = min(R[j][i-k], rp - k) k += 1 rp = max(rp - k, 0) i += k # remove guards s = s[1:len(s)-1] # Put all obtained palindromes in a hash map to # find only distinct palindrome m[s[0]] = 1 for i in range(1,n): for j in range(2): for rp in range(R[j][i],0,-1): m[s[i - rp - 1 : i - rp - 1 + 2 * rp + j]] = 1 m[s[i]] = 1 # printing all distinct palindromes from hash map print (\"Below are \" + str(len(m)) + \" pali sub-strings\") for i in m: print (i) # Driver programpalindromeSubStrs(\"abaaa\")# This code is contributed by BHAVYA JAIN and ROHIT SIKKA",
"e": 7981,
"s": 6288,
"text": null
},
{
"code": "// C# program to find all distinct palindrome// sub-strings of a given stringusing System;using System.Collections.Generic; class GFG{ // Function to print all distinct palindrome // sub-strings of s public static void palindromeSubStrs(string s) { //map<string, int> m; Dictionary < string, int > m = new Dictionary < string, int > (); int n = s.Length; // table for storing results (2 rows for odd- // and even-length palindromes int[, ] R = new int[2, n + 1]; // Find all sub-string palindromes from the // given input string insert 'guards' to // iterate easily over s s = \"@\" + s + \"#\"; for (int j = 0; j <= 1; j++) { int rp = 0; // length of 'palindrome radius' R[j, 0] = 0; int i = 1; while (i <= n) { // Attempt to expand palindrome centered // at i while (s[i - rp - 1] == s[i + j + rp]) // Incrementing the length of // palindromic radius as and // when we find valid palindrome rp++; // Assigning the found palindromic length // to odd/even length array R[j, i] = rp; int k = 1; while ((R[j, i - k] != rp - k) && k < rp) { R[j, i + k] = Math.Min(R[j, i - k], rp - k); k++; } rp = Math.Max(rp - k, 0); i += k; } } // remove 'guards' s = s.Substring(1); // Put all obtained palindromes in a hash map to // find only distinct palindromess if (!m.ContainsKey(s.Substring(0, 1))) m.Add(s.Substring(0, 1), 1); else m[s.Substring(0, 1)]++; for (int i = 1; i < n; i++) { for (int j = 0; j <= 1; j++) for (int rp = R[j, i]; rp > 0; rp--) { if (!m.ContainsKey(s.Substring(i - rp - 1, 2 * rp + j))) m.Add(s.Substring(i - rp - 1, 2 * rp + j), 1); else m[s.Substring(i - rp - 1, 2 * rp + j)]++; } if (!m.ContainsKey(s.Substring(i, 1))) m.Add(s.Substring(i, 1), 1); else m[s.Substring(i, 1)]++; } // printing all distinct palindromes from // hash map Console.WriteLine(\"Below are \" + (m.Count)); foreach(KeyValuePair < string, int > ii in m) Console.WriteLine(ii.Key); } // Driver Code public static void Main(string[] args) { palindromeSubStrs(\"abaaa\"); }} // This code is contributed by// sanjeev2552",
"e": 10777,
"s": 7981,
"text": null
},
{
"code": "<script> // JavaScript program to find all distinct palindrome sub-strings// of a given string // Function to print all distinct palindrome sub-strings of sfunction palindromeSubStrs(s){ let m = new Map(); let n = s.length; // table for storing results (2 rows for odd- // and even-length palindromes let R = new Array(2); for(let i = 0; i < 2; i++) R[i] = new Array(n + 1); // Find all sub-string palindromes from the given input // string insert 'guards' to iterate easily over s s = \"@\" + s + \"#\"; for (let j = 0; j <= 1; j++) { let rp = 0; // length of 'palindrome radius' R[j][0] = 0; let i = 1; while (i <= n) { // Attempt to expand palindrome centered at i while (s[i - rp - 1] == s[i + j + rp]) rp++; // Incrementing the length of palindromic // radius as and when we find valid palindrome // Assigning the found palindromic length to odd/even // length array R[j][i] = rp; let k = 1; while ((R[j][i - k] != rp - k) && (k < rp)) { R[j][i + k] = Math.min(R[j][i - k],rp - k); k++; } rp = Math.max(rp - k,0); i += k; } } // remove 'guards' s = s.substring(1, n+1); // Put all obtained palindromes in a hash map to // find only distinct palindromes m.set(`${s[0]}`,1); for (let i = 1; i < n; i++) { for (let j = 0; j <= 1; j++){ for (let rp = R[j][i]; rp > 0; rp--){ m.set(s.substring(i - rp - 1, i + rp + j-1),1); } } m.set(`${s[i]}`,1); } // printing all distinct palindromes from hash map document.write(`Below are ${m.size} palindrome sub-strings`,\"</br>\"); for(let [x, y] of m) document.write(x,\"</br>\");} // Driver programpalindromeSubStrs(\"abaaa\"); // This code is contributed by shinjanpatra</script>",
"e": 12796,
"s": 10777,
"text": null
},
{
"code": null,
"e": 12805,
"s": 12796,
"text": "Output: "
},
{
"code": null,
"e": 12857,
"s": 12805,
"text": " Below are 5 palindrome sub-strings\na\naa\naaa\naba\nb "
},
{
"code": null,
"e": 12868,
"s": 12857,
"text": "Method 2 :"
},
{
"code": null,
"e": 12886,
"s": 12868,
"text": "String length – N"
},
{
"code": null,
"e": 12932,
"s": 12886,
"text": "Step 1 : Find all the palindromic sub-strings"
},
{
"code": null,
"e": 13105,
"s": 12932,
"text": " First for every sub-string check if it is palindrome or not using dynamic programming like this – https://www.geeksforgeeks.org/count-palindrome-sub-strings-string/"
},
{
"code": null,
"e": 13170,
"s": 13105,
"text": " Time complexity – O(N2) and Space complexity – O(N2)"
},
{
"code": null,
"e": 13208,
"s": 13170,
"text": "Step 2 : Remove duplicate palindromes"
},
{
"code": null,
"e": 13396,
"s": 13208,
"text": " For every index starting from index 0 we will use KMP algorithm and check if prefix and suffix is same and is palindrome then we will put 0 the dp array for that suffix sub-string"
},
{
"code": null,
"e": 13471,
"s": 13396,
"text": " Time complexity O(N2) and Space complexity O(N) for KMP array"
},
{
"code": null,
"e": 13542,
"s": 13471,
"text": "Step 3 : Print the distinct palindromes and number of such palindromes"
},
{
"code": null,
"e": 13643,
"s": 13542,
"text": " For every sub-string check if it is present in dp array (i.e dp[i][j] == true) and print it."
},
{
"code": null,
"e": 13704,
"s": 13643,
"text": " Time complexity O(N2) and Space complexity O(N)"
},
{
"code": null,
"e": 13736,
"s": 13704,
"text": "Overall Time complexity – O(N2)"
},
{
"code": null,
"e": 13769,
"s": 13736,
"text": "Overall Space complexity – O(N2)"
},
{
"code": null,
"e": 13816,
"s": 13769,
"text": "Below is the implementation of the above idea."
},
{
"code": null,
"e": 13820,
"s": 13816,
"text": "C++"
},
{
"code": "// C++ program to find all distinct palindrome sub-strings// of a given string#include <iostream>#include <vector>using namespace std; int solve(string s){ int n = s.size(); // dp array to store whether a substring is palindrome // or not using dynamic programming we can solve this // in O(N^2) // dp[i][j] will be true (1) if substring (i, j) is // palindrome else false (0) vector<vector<bool> > dp(n, vector<bool>(n, false)); for (int i = 0; i < n; i++) { // base case every char is palindrome dp[i][i] = 1; // check for every substring of length 2 if (i < n && s[i] == s[i + 1]) { dp[i][i + 1] = 1; } } // check every substring of length greater than 2 for // palindrome for (int len = 3; len <= n; len++) { for (int i = 0; i + len - 1 < n; i++) { if (s[i] == s[i + (len - 1)] && dp[i + 1][i + (len - 1) - 1]) { dp[i][i + (len - 1)] = true; } } } //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* // here we will apply kmp algorithm for substrings // starting from i = 0 to n-1 when we will find prefix // and suffix of a substring to be equal and it is // palindrome we will make dp[i][j] for that suffix to be // false which means it is already added in the prefix // and we should not count it anymore. vector<int> kmp(n, 0); for (int i = 0; i < n; i++) { // starting kmp for every i form 0 to n-1 int j = 0, k = 1; while (k + i < n) { if (s[j + i] == s[k + i]) { // make suffix to be false // if this suffix is palindrome then it is // already included in prefix dp[k + i - j][k + i] = false; kmp[k++] = ++j; } else if (j > 0) { j = kmp[j - 1]; } else { kmp[k++] = 0; } } } //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* int count = 0; for (int i = 0; i < n; i++) { string str; for (int j = i; j < n; j++) { str += s[j]; if (dp[i][j]) { // count number of resultant distinct // substrings and print that substring count++; cout << str << '\\n'; } } } cout << \"Total number of distinct palindromes is \" << count << '\\n';} // Driver code starts// This code is contributed by Aditya Anandint main(){ string s1 = \"abaaa\", s2 = \"aaaaaaaaaa\"; solve(s1); solve(s2); return 0;}// Driver code ends",
"e": 16489,
"s": 13820,
"text": null
},
{
"code": null,
"e": 16654,
"s": 16489,
"text": "a\naba\nb\naa\naaa\nTotal number of distinct palindromes is 5\na\naa\naaa\naaaa\naaaaa\naaaaaa\naaaaaaa\naaaaaaaa\naaaaaaaaa\naaaaaaaaaa\nTotal number of distinct palindromes is 10"
},
{
"code": null,
"e": 16910,
"s": 16654,
"text": "Similar Problem: Count All Palindrome Sub-Strings in a StringThis article is contributed by Vignesh Narayanan and Sowmya Sampath. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 16921,
"s": 16910,
"text": "utkarshver"
},
{
"code": null,
"e": 16933,
"s": 16921,
"text": "sanjeev2552"
},
{
"code": null,
"e": 16948,
"s": 16933,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 16964,
"s": 16948,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 16981,
"s": 16964,
"text": "adityaanand12017"
},
{
"code": null,
"e": 16994,
"s": 16981,
"text": "shinjanpatra"
},
{
"code": null,
"e": 17008,
"s": 16994,
"text": "sumitgumber28"
},
{
"code": null,
"e": 17017,
"s": 17008,
"text": "sweetyty"
},
{
"code": null,
"e": 17031,
"s": 17017,
"text": "mitalibhola94"
},
{
"code": null,
"e": 17040,
"s": 17031,
"text": "Linkedin"
},
{
"code": null,
"e": 17051,
"s": 17040,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 17060,
"s": 17051,
"text": "Ola Cabs"
},
{
"code": null,
"e": 17071,
"s": 17060,
"text": "palindrome"
},
{
"code": null,
"e": 17080,
"s": 17071,
"text": "SAP Labs"
},
{
"code": null,
"e": 17084,
"s": 17080,
"text": "STL"
},
{
"code": null,
"e": 17104,
"s": 17084,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 17112,
"s": 17104,
"text": "Strings"
},
{
"code": null,
"e": 17123,
"s": 17112,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 17132,
"s": 17123,
"text": "Ola Cabs"
},
{
"code": null,
"e": 17141,
"s": 17132,
"text": "SAP Labs"
},
{
"code": null,
"e": 17150,
"s": 17141,
"text": "Linkedin"
},
{
"code": null,
"e": 17158,
"s": 17150,
"text": "Strings"
},
{
"code": null,
"e": 17178,
"s": 17158,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 17189,
"s": 17178,
"text": "palindrome"
},
{
"code": null,
"e": 17193,
"s": 17189,
"text": "STL"
}
]
|
How to remove array element in MongoDB? | To remove array element in MongoDB, you can use pullandin operator. The syntax is as follows:
db.yourCollectionName.update({},
{$pull:{yourFirstArrayName:{$in:["yourValue"]},yourSecondArrayName:"yourValue"}},
{multi:true}
);
To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:
>db.removeArrayElement.insertOne({"StudentName":"Larry","StudentCoreSubject":["MongoD
B","MySQL","SQL Server","Java"],"StudentFavouriteTeacher":["John","Marry","Carol"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ec9c46fd07954a4890688")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.removeArrayElement.find().pretty();
The following is the output:
{
"_id" : ObjectId("5c6ec9c46fd07954a4890688"),
"StudentName" : "Larry",
"StudentCoreSubject" : [
"MongoDB",
"MySQL",
"SQL Server",
"Java"
],
"StudentFavouriteTeacher" : [
"John",
"Marry",
"Carol"
]
}
Here is the query to remove array element in MongoDB:
> db.removeArrayElement.update({},
... {$pull:{StudentCoreSubject:{$in:["Java"]},StudentFavouriteTeacher:"Marry"}},
... {multi:true}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
We have “Java” element from first array(“StudentCoreSubject”) above and the second value “Marry” element from second array(“StudentFavouriteTeacher”).
Let us display documents from a collection once again to check the two elements have been removed or not. The query is as follows:
> db.removeArrayElement.find().pretty();
The following is the output:
{
"_id" : ObjectId("5c6ec9c46fd07954a4890688"),
"StudentName" : "Larry",
"StudentCoreSubject" : [
"MongoDB",
"MySQL",
"SQL Server"
],
"StudentFavouriteTeacher" : [
"John",
"Carol"
]
}
Look at the above sample output, there is no “Java” element in the first array(“StudentCoreSubject”) and no “Marry” element in second array(“StudentFavouriteTeacher”). Therefore, we have successfully removed them from the collection. | [
{
"code": null,
"e": 1156,
"s": 1062,
"text": "To remove array element in MongoDB, you can use pullandin operator. The syntax is as follows:"
},
{
"code": null,
"e": 1293,
"s": 1156,
"text": "db.yourCollectionName.update({},\n {$pull:{yourFirstArrayName:{$in:[\"yourValue\"]},yourSecondArrayName:\"yourValue\"}},\n {multi:true}\n);"
},
{
"code": null,
"e": 1429,
"s": 1293,
"text": "To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:"
},
{
"code": null,
"e": 1686,
"s": 1429,
"text": ">db.removeArrayElement.insertOne({\"StudentName\":\"Larry\",\"StudentCoreSubject\":[\"MongoD\nB\",\"MySQL\",\"SQL Server\",\"Java\"],\"StudentFavouriteTeacher\":[\"John\",\"Marry\",\"Carol\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ec9c46fd07954a4890688\")\n}"
},
{
"code": null,
"e": 1783,
"s": 1686,
"text": "Display all documents from a collection with the help of find() method. The query is as follows:"
},
{
"code": null,
"e": 1824,
"s": 1783,
"text": "> db.removeArrayElement.find().pretty();"
},
{
"code": null,
"e": 1853,
"s": 1824,
"text": "The following is the output:"
},
{
"code": null,
"e": 2114,
"s": 1853,
"text": "{\n \"_id\" : ObjectId(\"5c6ec9c46fd07954a4890688\"),\n \"StudentName\" : \"Larry\",\n \"StudentCoreSubject\" : [\n \"MongoDB\",\n \"MySQL\",\n \"SQL Server\",\n \"Java\"\n ],\n \"StudentFavouriteTeacher\" : [\n \"John\",\n \"Marry\",\n \"Carol\"\n ]\n}"
},
{
"code": null,
"e": 2168,
"s": 2114,
"text": "Here is the query to remove array element in MongoDB:"
},
{
"code": null,
"e": 2374,
"s": 2168,
"text": "> db.removeArrayElement.update({},\n... {$pull:{StudentCoreSubject:{$in:[\"Java\"]},StudentFavouriteTeacher:\"Marry\"}},\n... {multi:true}\n... );\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 2525,
"s": 2374,
"text": "We have “Java” element from first array(“StudentCoreSubject”) above and the second value “Marry” element from second array(“StudentFavouriteTeacher”)."
},
{
"code": null,
"e": 2656,
"s": 2525,
"text": "Let us display documents from a collection once again to check the two elements have been removed or not. The query is as follows:"
},
{
"code": null,
"e": 2697,
"s": 2656,
"text": "> db.removeArrayElement.find().pretty();"
},
{
"code": null,
"e": 2726,
"s": 2697,
"text": "The following is the output:"
},
{
"code": null,
"e": 2958,
"s": 2726,
"text": "{\n \"_id\" : ObjectId(\"5c6ec9c46fd07954a4890688\"),\n \"StudentName\" : \"Larry\",\n \"StudentCoreSubject\" : [\n \"MongoDB\",\n \"MySQL\",\n \"SQL Server\"\n ],\n \"StudentFavouriteTeacher\" : [\n \"John\",\n \"Carol\"\n ]\n}"
},
{
"code": null,
"e": 3192,
"s": 2958,
"text": "Look at the above sample output, there is no “Java” element in the first array(“StudentCoreSubject”) and no “Marry” element in second array(“StudentFavouriteTeacher”). Therefore, we have successfully removed them from the collection."
}
]
|
TestNG - Run JUnit Tests | Now that you have understood TestNG and its various tests, you must be worried by now as to how to refactor your existing JUnit code. There's no need to worry, as TestNG provides a way to shift from JUnit to TestNG at your own pace. You can execute your existing JUnit test cases using TestNG.
TestNG can automatically recognize and run JUnit tests, so that you can use TestNG as a runner for all your existing tests and write new tests using TestNG. All you have to do is to put JUnit library on the TestNG classpath, so it can find and use JUnit classes, change your test runner from JUnit to TestNG in Ant, and then run TestNG in "mixed" mode. This way, you can have all your tests in the same project, even in the same package, and start using TestNG. This approach also allows you to convert your existing JUnit tests to TestNG incrementally.
Let us have an example to demonstrate this amazing ability of TestNG.
Create a java class, which is a JUnit test class, TestJunit.java in /work/testng/src.
import org.junit.Test;
import static org.testng.AssertJUnit.*;
public class TestJunit {
@Test
public void testAdd() {
String str = "Junit testing using TestNG";
assertEquals("Junit testing using TestNG",str);
}
}
Now, let's write the testng.xml in /work/testng/src, which would contain the <suite> tag as follows −
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "Converted JUnit suite" >
<test name = "JUnitTests" junit="true">
<classes>
<class name = "TestJunit" />
</classes>
</test>
</suite>
To execute the JUnit test cases, define the property junit="true" as in the xml above. The JUnit test case class TestJunit is defined in class name.
For JUnit 4, TestNG will use the org.junit.runner.JUnitCore runner to run your tests.
Compile all java classes using javac.
/work/testng/src$ javac TestJunit.java
Now, run testng.xml, which will run the JUnit test case as TestNG.
/work/testng/src$java -cp "/work/testng/src/junit-4.13.2.jar:/work/testng/src/hamcrest-core-1.3.jar" org.testng.TestNG testng.xml
Here, we have placed the dependent JAR files junit-4.13.2.jar and hamcrest-core-1.3.jar under /work/testng/src/.
Verify the output.
===============================================
Converted JUnit suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================
38 Lectures
4.5 hours
Lets Kode It
15 Lectures
1.5 hours
Quaatso Learning
28 Lectures
3 hours
Dezlearn Education
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2354,
"s": 2060,
"text": "Now that you have understood TestNG and its various tests, you must be worried by now as to how to refactor your existing JUnit code. There's no need to worry, as TestNG provides a way to shift from JUnit to TestNG at your own pace. You can execute your existing JUnit test cases using TestNG."
},
{
"code": null,
"e": 2908,
"s": 2354,
"text": "TestNG can automatically recognize and run JUnit tests, so that you can use TestNG as a runner for all your existing tests and write new tests using TestNG. All you have to do is to put JUnit library on the TestNG classpath, so it can find and use JUnit classes, change your test runner from JUnit to TestNG in Ant, and then run TestNG in \"mixed\" mode. This way, you can have all your tests in the same project, even in the same package, and start using TestNG. This approach also allows you to convert your existing JUnit tests to TestNG incrementally."
},
{
"code": null,
"e": 2978,
"s": 2908,
"text": "Let us have an example to demonstrate this amazing ability of TestNG."
},
{
"code": null,
"e": 3064,
"s": 2978,
"text": "Create a java class, which is a JUnit test class, TestJunit.java in /work/testng/src."
},
{
"code": null,
"e": 3317,
"s": 3064,
"text": " import org.junit.Test;\n import static org.testng.AssertJUnit.*;\n\n public class TestJunit {\n @Test\n public void testAdd() {\n String str = \"Junit testing using TestNG\";\n assertEquals(\"Junit testing using TestNG\",str);\n }\n }"
},
{
"code": null,
"e": 3419,
"s": 3317,
"text": "Now, let's write the testng.xml in /work/testng/src, which would contain the <suite> tag as follows −"
},
{
"code": null,
"e": 3696,
"s": 3419,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\">\n\n<suite name = \"Converted JUnit suite\" >\n <test name = \"JUnitTests\" junit=\"true\">\n <classes>\n <class name = \"TestJunit\" />\n </classes>\n </test>\n</suite>"
},
{
"code": null,
"e": 3845,
"s": 3696,
"text": "To execute the JUnit test cases, define the property junit=\"true\" as in the xml above. The JUnit test case class TestJunit is defined in class name."
},
{
"code": null,
"e": 3931,
"s": 3845,
"text": "For JUnit 4, TestNG will use the org.junit.runner.JUnitCore runner to run your tests."
},
{
"code": null,
"e": 3969,
"s": 3931,
"text": "Compile all java classes using javac."
},
{
"code": null,
"e": 4009,
"s": 3969,
"text": "/work/testng/src$ javac TestJunit.java\n"
},
{
"code": null,
"e": 4076,
"s": 4009,
"text": "Now, run testng.xml, which will run the JUnit test case as TestNG."
},
{
"code": null,
"e": 4207,
"s": 4076,
"text": "/work/testng/src$java -cp \"/work/testng/src/junit-4.13.2.jar:/work/testng/src/hamcrest-core-1.3.jar\" org.testng.TestNG testng.xml\n"
},
{
"code": null,
"e": 4320,
"s": 4207,
"text": "Here, we have placed the dependent JAR files junit-4.13.2.jar and hamcrest-core-1.3.jar under /work/testng/src/."
},
{
"code": null,
"e": 4339,
"s": 4320,
"text": "Verify the output."
},
{
"code": null,
"e": 4519,
"s": 4339,
"text": " ===============================================\n Converted JUnit suite\n Total tests run: 1, Passes: 1, Failures: 0, Skips: 0\n ===============================================\n"
},
{
"code": null,
"e": 4554,
"s": 4519,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4568,
"s": 4554,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4603,
"s": 4568,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4621,
"s": 4603,
"text": " Quaatso Learning"
},
{
"code": null,
"e": 4654,
"s": 4621,
"text": "\n 28 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4674,
"s": 4654,
"text": " Dezlearn Education"
},
{
"code": null,
"e": 4681,
"s": 4674,
"text": " Print"
},
{
"code": null,
"e": 4692,
"s": 4681,
"text": " Add Notes"
}
]
|
Replace the odd positioned elements with their cubes and even positioned elements with their squares - GeeksforGeeks | 09 Dec, 2021
Given an array arr[] of n elements, the task is to replace all the odd positioned elements with their cubes and even positioned elements with their squares i.e. the resultant array must be {arr[0]3, arr[1]2, arr[2]3, arr[3]2, ...}.Examples:
Input: arr[]= {2, 3, 4, 5} Output: 8 9 64 25 Updated array will be {23, 32, 43, 52} -> {8, 9, 64, 25}Input: arr[] = {3, 4, 5, 2} Output: 27 16 125 4
Approach: For any element of the array arr[i], it is odd positioned only if (i + 1) is odd as the indexing starts from 0. Now, traverse the array and replace all the odd positioned elements with their cubes and even positioned elements with their squares.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Utility function to print// the contents of an arrayvoid printArr(ll arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Function to update the arrayvoid updateArr(ll arr[], int n){ for (int i = 0; i < n; i++) { // In case of even positioned element if ((i + 1) % 2 == 0) arr[i] = (ll)pow(arr[i], 2); // Odd positioned element else arr[i] = (ll)pow(arr[i], 3); } // Print the updated array printArr(arr, n);} // Driver codeint main(){ ll arr[] = { 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); updateArr(arr, n); return 0;}
// Java implementation of the approachimport java.lang.Math; class GFG{ // Utility function to print// the contents of an arraystatic void printArr(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");} // Function to update the arraystatic void updateArr(int arr[], int n){ for (int i = 0; i < n; i++) { // In case of even positioned element if ((i + 1) % 2 == 0) arr[i] = (int)Math.pow(arr[i], 2); // Odd positioned element else arr[i] = (int)Math.pow(arr[i], 3); } // Print the updated array printArr(arr, n);} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 3, 4, 5, 6 }; int n = arr.length; updateArr(arr, n);}} // This code is contributed// by Code_Mech.
# Python3 implementation of the approach # Utility function to print# the contents of an arraydef printArr(arr,n): for i in range(n): print(arr[i], end = " ") # Function to update the arraydef updateArr(arr, n): for i in range(n): # In case of even positioned element if ((i + 1) % 2 == 0): arr[i] = pow(arr[i], 2) # Odd positioned element else: arr[i] = pow(arr[i], 3) # Print the updated array printArr(arr, n) # Driver codearr = [ 2, 3, 4, 5, 6 ]n = len(arr) updateArr(arr, n) # This code is contributed# by mohit kumar
// C# implementation of the approachusing System; class GFG{ // Utility function to print// the contents of an arraystatic void printArr(int []arr, int n){ for (int i = 0; i < n; i++) Console.Write(arr[i] + " ");} // Function to update the arraystatic void updateArr(int []arr, int n){ for (int i = 0; i < n; i++) { // In case of even positioned element if ((i + 1) % 2 == 0) arr[i] = (int)Math.Pow(arr[i], 2); // Odd positioned element else arr[i] = (int)Math.Pow(arr[i], 3); } // Print the updated array printArr(arr, n);} // Driver codepublic static void Main(String[] args){ int []arr = { 2, 3, 4, 5, 6 }; int n = arr.Length; updateArr(arr, n);}} /* This code contributed by PrinciRaj1992 */
<?php// PHP implementation of the approach // Utility function to print// the contents of an arrayfunction printArr($arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i] . " ";} // Function to update the arrayfunction updateArr($arr, $n){ for ($i = 0; $i < $n; $i++) { // In case of even positioned element if (($i + 1) % 2 == 0) $arr[$i] = pow($arr[$i], 2); // Odd positioned element else $arr[$i] = pow($arr[$i], 3); } // Print the updated array printArr($arr, $n);} // Driver code$arr = array( 2, 3, 4, 5, 6 );$n = count($arr); updateArr($arr, $n); // This code is contributed by mits?>
<script>// javascript implementation of the approach // Utility function to print // the contents of an array function printArr(arr , n) { for (i = 0; i < n; i++) document.write(arr[i] + " "); } // Function to update the array function updateArr(arr , n) { for (i = 0; i < n; i++) { // In case of even positioned element if ((i + 1) % 2 == 0) arr[i] = parseInt( Math.pow(arr[i], 2)); // Odd positioned element else arr[i] = parseInt( Math.pow(arr[i], 3)); } // Print the updated array printArr(arr, n); } // Driver code var arr = [ 2, 3, 4, 5, 6 ]; var n = arr.length; updateArr(arr, n); // This code contributed by gauravrajput1</script>
8 9 64 25 216
Time Complexity: O(n)
Auxiliary Space: O(1)
mohit kumar 29
Code_Mech
princiraj1992
Mithun Kumar
subham348
GauravRajput1
simranarora5sos
school-programming
Arrays
C++ Programs
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Header files in C/C++ and its uses
C++ Program for QuickSort
How to return multiple values from a function in C or C++?
Program to print ASCII Value of a character
C++ program for hashing with chaining | [
{
"code": null,
"e": 24405,
"s": 24377,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 24647,
"s": 24405,
"text": "Given an array arr[] of n elements, the task is to replace all the odd positioned elements with their cubes and even positioned elements with their squares i.e. the resultant array must be {arr[0]3, arr[1]2, arr[2]3, arr[3]2, ...}.Examples: "
},
{
"code": null,
"e": 24798,
"s": 24647,
"text": "Input: arr[]= {2, 3, 4, 5} Output: 8 9 64 25 Updated array will be {23, 32, 43, 52} -> {8, 9, 64, 25}Input: arr[] = {3, 4, 5, 2} Output: 27 16 125 4 "
},
{
"code": null,
"e": 25106,
"s": 24798,
"text": "Approach: For any element of the array arr[i], it is odd positioned only if (i + 1) is odd as the indexing starts from 0. Now, traverse the array and replace all the odd positioned elements with their cubes and even positioned elements with their squares.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25110,
"s": 25106,
"text": "C++"
},
{
"code": null,
"e": 25115,
"s": 25110,
"text": "Java"
},
{
"code": null,
"e": 25123,
"s": 25115,
"text": "Python3"
},
{
"code": null,
"e": 25126,
"s": 25123,
"text": "C#"
},
{
"code": null,
"e": 25130,
"s": 25126,
"text": "PHP"
},
{
"code": null,
"e": 25141,
"s": 25130,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int // Utility function to print// the contents of an arrayvoid printArr(ll arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Function to update the arrayvoid updateArr(ll arr[], int n){ for (int i = 0; i < n; i++) { // In case of even positioned element if ((i + 1) % 2 == 0) arr[i] = (ll)pow(arr[i], 2); // Odd positioned element else arr[i] = (ll)pow(arr[i], 3); } // Print the updated array printArr(arr, n);} // Driver codeint main(){ ll arr[] = { 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); updateArr(arr, n); return 0;}",
"e": 25890,
"s": 25141,
"text": null
},
{
"code": "// Java implementation of the approachimport java.lang.Math; class GFG{ // Utility function to print// the contents of an arraystatic void printArr(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \");} // Function to update the arraystatic void updateArr(int arr[], int n){ for (int i = 0; i < n; i++) { // In case of even positioned element if ((i + 1) % 2 == 0) arr[i] = (int)Math.pow(arr[i], 2); // Odd positioned element else arr[i] = (int)Math.pow(arr[i], 3); } // Print the updated array printArr(arr, n);} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 3, 4, 5, 6 }; int n = arr.length; updateArr(arr, n);}} // This code is contributed// by Code_Mech.",
"e": 26691,
"s": 25890,
"text": null
},
{
"code": "# Python3 implementation of the approach # Utility function to print# the contents of an arraydef printArr(arr,n): for i in range(n): print(arr[i], end = \" \") # Function to update the arraydef updateArr(arr, n): for i in range(n): # In case of even positioned element if ((i + 1) % 2 == 0): arr[i] = pow(arr[i], 2) # Odd positioned element else: arr[i] = pow(arr[i], 3) # Print the updated array printArr(arr, n) # Driver codearr = [ 2, 3, 4, 5, 6 ]n = len(arr) updateArr(arr, n) # This code is contributed# by mohit kumar",
"e": 27290,
"s": 26691,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Utility function to print// the contents of an arraystatic void printArr(int []arr, int n){ for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \");} // Function to update the arraystatic void updateArr(int []arr, int n){ for (int i = 0; i < n; i++) { // In case of even positioned element if ((i + 1) % 2 == 0) arr[i] = (int)Math.Pow(arr[i], 2); // Odd positioned element else arr[i] = (int)Math.Pow(arr[i], 3); } // Print the updated array printArr(arr, n);} // Driver codepublic static void Main(String[] args){ int []arr = { 2, 3, 4, 5, 6 }; int n = arr.Length; updateArr(arr, n);}} /* This code contributed by PrinciRaj1992 */",
"e": 28082,
"s": 27290,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Utility function to print// the contents of an arrayfunction printArr($arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \";} // Function to update the arrayfunction updateArr($arr, $n){ for ($i = 0; $i < $n; $i++) { // In case of even positioned element if (($i + 1) % 2 == 0) $arr[$i] = pow($arr[$i], 2); // Odd positioned element else $arr[$i] = pow($arr[$i], 3); } // Print the updated array printArr($arr, $n);} // Driver code$arr = array( 2, 3, 4, 5, 6 );$n = count($arr); updateArr($arr, $n); // This code is contributed by mits?>",
"e": 28749,
"s": 28082,
"text": null
},
{
"code": "<script>// javascript implementation of the approach // Utility function to print // the contents of an array function printArr(arr , n) { for (i = 0; i < n; i++) document.write(arr[i] + \" \"); } // Function to update the array function updateArr(arr , n) { for (i = 0; i < n; i++) { // In case of even positioned element if ((i + 1) % 2 == 0) arr[i] = parseInt( Math.pow(arr[i], 2)); // Odd positioned element else arr[i] = parseInt( Math.pow(arr[i], 3)); } // Print the updated array printArr(arr, n); } // Driver code var arr = [ 2, 3, 4, 5, 6 ]; var n = arr.length; updateArr(arr, n); // This code contributed by gauravrajput1</script>",
"e": 29565,
"s": 28749,
"text": null
},
{
"code": null,
"e": 29579,
"s": 29565,
"text": "8 9 64 25 216"
},
{
"code": null,
"e": 29603,
"s": 29581,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 29625,
"s": 29603,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 29640,
"s": 29625,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 29650,
"s": 29640,
"text": "Code_Mech"
},
{
"code": null,
"e": 29664,
"s": 29650,
"text": "princiraj1992"
},
{
"code": null,
"e": 29677,
"s": 29664,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 29687,
"s": 29677,
"text": "subham348"
},
{
"code": null,
"e": 29701,
"s": 29687,
"text": "GauravRajput1"
},
{
"code": null,
"e": 29717,
"s": 29701,
"text": "simranarora5sos"
},
{
"code": null,
"e": 29736,
"s": 29717,
"text": "school-programming"
},
{
"code": null,
"e": 29743,
"s": 29736,
"text": "Arrays"
},
{
"code": null,
"e": 29756,
"s": 29743,
"text": "C++ Programs"
},
{
"code": null,
"e": 29763,
"s": 29756,
"text": "Arrays"
},
{
"code": null,
"e": 29861,
"s": 29763,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29870,
"s": 29861,
"text": "Comments"
},
{
"code": null,
"e": 29883,
"s": 29870,
"text": "Old Comments"
},
{
"code": null,
"e": 29904,
"s": 29883,
"text": "Next Greater Element"
},
{
"code": null,
"e": 29929,
"s": 29904,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 29956,
"s": 29929,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 30005,
"s": 29956,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 30043,
"s": 30005,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 30078,
"s": 30043,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 30104,
"s": 30078,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 30163,
"s": 30104,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 30207,
"s": 30163,
"text": "Program to print ASCII Value of a character"
}
]
|
Tryit Editor v3.6 - Show Python | f = open("demofile.txt", "r")
for x in f: | [
{
"code": null,
"e": 30,
"s": 0,
"text": "f = open(\"demofile.txt\", \"r\")"
}
]
|
Coding a production ready API - part 1: implementing an ORM | by Mike Huls | Towards Data Science | Imagine going to a restaurant. You sit down, look at the menu and select some dishes. Then you walk to the kitchen, tell the chef what you want to eat and wait for him to finish before taking your meal back to your table. What’s going on in this weird restaurant?
An application without an API is much like a restaurant without waiters. In restaurants you don’t have to communicate with the kitchen and wait for your order to enjoy a meal. In the same way a website doesn’t have to know how to communicate with your database for example. Like a waiter, our API receives an order from our website: ‘I’d like some user statistics with a side of meta data”. The API then checks the order (are you allowed to have that data?), convinces our database (the chef) to cook him up some tasty information, waits for the database to finish and finally returns the data to the website.
We’ll use an ORM to create a fully functioning, fast and secure API for a real-world application we’re building called BeerSnob; a site that’s specially made for drinkers of fine beers. It allows users to share reviews about beers they drank at specific venues; rating both the venue and the beer while providing information about it’s price and taste. At the end of this article you’ll have a working API with an ORM with a migration model to op it off! First we get into why we would create an API or an ORM, then we start coding.
Our goal is to create an API for BeerSnob that will receive user-created data packages from the website. Based on the required action it then retrieves data from the database or inserts the data package into the database. The data package may contain information for multiple tables and it’s the API’s job to make sure the right information ends up in the right table.
If you click on ‘my friends’ on the Facebook website or in the app, you’ll send a request for information to an API. This piece of software translates your request, checks if you are allowed make the request, collects all the data and response with your data package. This is great for a couple of reasons:
Keeps our code nice and tidy
Secures access to our database (website is decoupled from our database e.g.: no need for our website to have database credentials)
Checks user access to data (I can only change my profile, not someone else’s)
ORM stands for Object-Relational Mapping, it is a technique that allows you to query and manipulate data from a database using objects. You don’t have have to write queries anymore, you can use objects to retrieve data. Example in pseudocode: song_list = SongTable.query(artist="Snoop dogg"). The advantages:
There’s no need to write SQL
A lot of things are done automatically
Prevents SQL injection
Let’s code!
Before the API can handle database data we’ll need a database to actually work with. In this article we use migrations to create all tables, associations, associations and indices. Whether you’re using the migrations or not, the article also contains a very nice diagram of BeerSnob’s database structure.
We’ll build the API on the migration model that we’ve built in this article. If you want to code along then git clone the code from here. First let’s build an ORM and then implement our API.
The ORM is the translation between an object we can use in our API and the data in our database. In order to translate database data to an object it uses ‘models’. In our BeerSnob example we’d like to do something along the lines of foundbeers = BeerTable.Get(ID=2). In this example BeerTable is a model that is able to connect to our Beers Table in the database and perform actions on it like retrieving data and inserting new records.
Let’s create our first model; countries. This model handles data in our countries table. Create a new file in the “models” directory called countries.js with the following content:
This simple file allows us to create a model. Creating a model and understanding how it works is not hard. The important things are defined below.
in the tableModel (line 5) we’ve added the modelName. I’ve decided to keep our tablenames plural (the countries table contains many records for countries) and the modelsNames’s singular (a model describes just one country).
The models associates with another model (line 11). We tell our ORM that if we delete a country, a city should be deleted to. Also we define the foreignKey on the country table (CountryId).
in Init we define some information about columns. The ORM needs to know the datatypes and the names of the columns in the database.
timestamps: false (line 24). If this is set to true the ORM adds additional columns that keep track of created and modified timestamps (we handled those manually but the ORM could do it for you too).
When defining associations between models there are several options. I’ve already used some in this project so far but we’ll get into them more in-depth in the next part. I’ve created models for the other tables as well. Check out the repository for more information.
Before we can start creating creating the API we need to install some dependencies and prepare a few things.
Go to your root folder and:
npm install --save express body-parsernpm install --save-dev nodemon
This will install packages that our API requires. Express is a webserver, body-parser allows us to parse the bodies of requests sent through that webserver. Then we install a dev-dependency; these are only used to build our application and are generally just for developing. Nodemon will reload our webserver every time we change our code. My f5 button is very thankful for this.
Open package.json, a file in your root folder. Adjust the ‘scripts’ part to reflect the following:
"scripts": { "start": "node server.js", "dev": "nodemon server.js" },
This will allow us to either call npm run start in production environments or npm run dev to run our app with nodemon, allowing the restart.
Create two folders in your root directory: “routes” and “service”.
It’s time to put those models to work! With the API we’ll be able to receive requests and use the models to retrieve data from the database. We first design our server that will catch all requests and pass them through to a route. The route will then check the request and communicate with the database.
With the script below we’ll have a server up and running.
Here’s what happens:
We import some packages and also the loggingService. This service helps us debugging, we do so on line 13.
On line 9 we create our app that will pass through requests.
Line 24; we tell the app that we want to use bodyParser; this way we can receive e.g. json data.
Line 29: we set the rules of the API.
Line 41 till 46: we catch some URL paths and pass them to our routes.
Line 59: create a server for our app and tell it to listen to port 5000 on localhost
Now that our server is up and running it’s time to pass requests to the routes that we’ve defined on line 41 until 46. I’ll show an example of handling a route below. I’ve implemented the other routes in exactly the same way; you’ll be able to find in our repository.
In the code above you see how the ORM works when handling a route. Lets walk through the first route (line 11 until 39).
line 11: we define the route. /searchmeans in our case localhost:5000/api/beers/search
Line 14: we get data from our url. req.query retrieves url parameters (the bold part in https://mikehuls.medium.com/?source=twitter. We store the value of parameter q in a variable that’s also called q (for query). In the url localhost:5000/api/beers/search?q=ale the value for key q is ‘ale’.
Line 20: Do nothing if q is too short
Line 23 until 30: return all beers that contain q (case insensitive)
Line 33 res.retun is what our API returns. It will return an object with one key: ‘beers’ and an array of all the beers we’ve found in our database. We return with status code 200 (success).
Line 36: if anything goes wrong in the try-block we let the client know by returning an error (we use the errorService for this).
As you see we don’t have to write a line of SQL ourself; we can just call our models that translate our request and communicate with our database. It not only is very convenient, it also prevents SQL injection.
Let’s test our beers route! In beers there are three different paths:
a GET for /search This route uses our ORM to query the Beers table. You are able to pass a searchword (q) like localhost:5000/api/beers/search?q=heine. It will then look for beers that are like the q (‘heine’).a GET for / This route takes the optional query parameter Id and tries to find a record if the Id is provided. Else it returns all beers. Try localhost:5000/api/beers or localhost:5000/api/beers?id=1a POST for / This route accepts a body which it will catch on line 72 (req.body). Try to POST the json below to localhost:5000/api/beers and you’ll see a new record appear in the database.
a GET for /search This route uses our ORM to query the Beers table. You are able to pass a searchword (q) like localhost:5000/api/beers/search?q=heine. It will then look for beers that are like the q (‘heine’).
a GET for / This route takes the optional query parameter Id and tries to find a record if the Id is provided. Else it returns all beers. Try localhost:5000/api/beers or localhost:5000/api/beers?id=1
a POST for / This route accepts a body which it will catch on line 72 (req.body). Try to POST the json below to localhost:5000/api/beers and you’ll see a new record appear in the database.
{ "Name": "Bud Light", "Type": "Beer flavored water"}
This API provides some nice basic functionalities for our app! Using our ORM we are now able to use our API to search for, get and create countries, cities, venues, beers, users and reports. In the next part we’ll flesh out our API even more:
We’ll add more in-depth associations (return all beers user X submitted or return all users that visited venue X and reported beer Y).
Implement more functionalities for example: users want to update their password
We’ll add security; I can only edit my own password, not someone else’s.
This was a long article; I hope you made until here and that my explanations wee clear enough. If the weren’t please let me know where I can improve myself. Follow me to stay tuned! | [
{
"code": null,
"e": 436,
"s": 172,
"text": "Imagine going to a restaurant. You sit down, look at the menu and select some dishes. Then you walk to the kitchen, tell the chef what you want to eat and wait for him to finish before taking your meal back to your table. What’s going on in this weird restaurant?"
},
{
"code": null,
"e": 1046,
"s": 436,
"text": "An application without an API is much like a restaurant without waiters. In restaurants you don’t have to communicate with the kitchen and wait for your order to enjoy a meal. In the same way a website doesn’t have to know how to communicate with your database for example. Like a waiter, our API receives an order from our website: ‘I’d like some user statistics with a side of meta data”. The API then checks the order (are you allowed to have that data?), convinces our database (the chef) to cook him up some tasty information, waits for the database to finish and finally returns the data to the website."
},
{
"code": null,
"e": 1579,
"s": 1046,
"text": "We’ll use an ORM to create a fully functioning, fast and secure API for a real-world application we’re building called BeerSnob; a site that’s specially made for drinkers of fine beers. It allows users to share reviews about beers they drank at specific venues; rating both the venue and the beer while providing information about it’s price and taste. At the end of this article you’ll have a working API with an ORM with a migration model to op it off! First we get into why we would create an API or an ORM, then we start coding."
},
{
"code": null,
"e": 1948,
"s": 1579,
"text": "Our goal is to create an API for BeerSnob that will receive user-created data packages from the website. Based on the required action it then retrieves data from the database or inserts the data package into the database. The data package may contain information for multiple tables and it’s the API’s job to make sure the right information ends up in the right table."
},
{
"code": null,
"e": 2255,
"s": 1948,
"text": "If you click on ‘my friends’ on the Facebook website or in the app, you’ll send a request for information to an API. This piece of software translates your request, checks if you are allowed make the request, collects all the data and response with your data package. This is great for a couple of reasons:"
},
{
"code": null,
"e": 2284,
"s": 2255,
"text": "Keeps our code nice and tidy"
},
{
"code": null,
"e": 2415,
"s": 2284,
"text": "Secures access to our database (website is decoupled from our database e.g.: no need for our website to have database credentials)"
},
{
"code": null,
"e": 2493,
"s": 2415,
"text": "Checks user access to data (I can only change my profile, not someone else’s)"
},
{
"code": null,
"e": 2802,
"s": 2493,
"text": "ORM stands for Object-Relational Mapping, it is a technique that allows you to query and manipulate data from a database using objects. You don’t have have to write queries anymore, you can use objects to retrieve data. Example in pseudocode: song_list = SongTable.query(artist=\"Snoop dogg\"). The advantages:"
},
{
"code": null,
"e": 2831,
"s": 2802,
"text": "There’s no need to write SQL"
},
{
"code": null,
"e": 2870,
"s": 2831,
"text": "A lot of things are done automatically"
},
{
"code": null,
"e": 2893,
"s": 2870,
"text": "Prevents SQL injection"
},
{
"code": null,
"e": 2905,
"s": 2893,
"text": "Let’s code!"
},
{
"code": null,
"e": 3210,
"s": 2905,
"text": "Before the API can handle database data we’ll need a database to actually work with. In this article we use migrations to create all tables, associations, associations and indices. Whether you’re using the migrations or not, the article also contains a very nice diagram of BeerSnob’s database structure."
},
{
"code": null,
"e": 3401,
"s": 3210,
"text": "We’ll build the API on the migration model that we’ve built in this article. If you want to code along then git clone the code from here. First let’s build an ORM and then implement our API."
},
{
"code": null,
"e": 3838,
"s": 3401,
"text": "The ORM is the translation between an object we can use in our API and the data in our database. In order to translate database data to an object it uses ‘models’. In our BeerSnob example we’d like to do something along the lines of foundbeers = BeerTable.Get(ID=2). In this example BeerTable is a model that is able to connect to our Beers Table in the database and perform actions on it like retrieving data and inserting new records."
},
{
"code": null,
"e": 4019,
"s": 3838,
"text": "Let’s create our first model; countries. This model handles data in our countries table. Create a new file in the “models” directory called countries.js with the following content:"
},
{
"code": null,
"e": 4166,
"s": 4019,
"text": "This simple file allows us to create a model. Creating a model and understanding how it works is not hard. The important things are defined below."
},
{
"code": null,
"e": 4390,
"s": 4166,
"text": "in the tableModel (line 5) we’ve added the modelName. I’ve decided to keep our tablenames plural (the countries table contains many records for countries) and the modelsNames’s singular (a model describes just one country)."
},
{
"code": null,
"e": 4580,
"s": 4390,
"text": "The models associates with another model (line 11). We tell our ORM that if we delete a country, a city should be deleted to. Also we define the foreignKey on the country table (CountryId)."
},
{
"code": null,
"e": 4712,
"s": 4580,
"text": "in Init we define some information about columns. The ORM needs to know the datatypes and the names of the columns in the database."
},
{
"code": null,
"e": 4912,
"s": 4712,
"text": "timestamps: false (line 24). If this is set to true the ORM adds additional columns that keep track of created and modified timestamps (we handled those manually but the ORM could do it for you too)."
},
{
"code": null,
"e": 5180,
"s": 4912,
"text": "When defining associations between models there are several options. I’ve already used some in this project so far but we’ll get into them more in-depth in the next part. I’ve created models for the other tables as well. Check out the repository for more information."
},
{
"code": null,
"e": 5289,
"s": 5180,
"text": "Before we can start creating creating the API we need to install some dependencies and prepare a few things."
},
{
"code": null,
"e": 5317,
"s": 5289,
"text": "Go to your root folder and:"
},
{
"code": null,
"e": 5386,
"s": 5317,
"text": "npm install --save express body-parsernpm install --save-dev nodemon"
},
{
"code": null,
"e": 5766,
"s": 5386,
"text": "This will install packages that our API requires. Express is a webserver, body-parser allows us to parse the bodies of requests sent through that webserver. Then we install a dev-dependency; these are only used to build our application and are generally just for developing. Nodemon will reload our webserver every time we change our code. My f5 button is very thankful for this."
},
{
"code": null,
"e": 5865,
"s": 5766,
"text": "Open package.json, a file in your root folder. Adjust the ‘scripts’ part to reflect the following:"
},
{
"code": null,
"e": 5942,
"s": 5865,
"text": "\"scripts\": { \"start\": \"node server.js\", \"dev\": \"nodemon server.js\" },"
},
{
"code": null,
"e": 6083,
"s": 5942,
"text": "This will allow us to either call npm run start in production environments or npm run dev to run our app with nodemon, allowing the restart."
},
{
"code": null,
"e": 6150,
"s": 6083,
"text": "Create two folders in your root directory: “routes” and “service”."
},
{
"code": null,
"e": 6454,
"s": 6150,
"text": "It’s time to put those models to work! With the API we’ll be able to receive requests and use the models to retrieve data from the database. We first design our server that will catch all requests and pass them through to a route. The route will then check the request and communicate with the database."
},
{
"code": null,
"e": 6512,
"s": 6454,
"text": "With the script below we’ll have a server up and running."
},
{
"code": null,
"e": 6533,
"s": 6512,
"text": "Here’s what happens:"
},
{
"code": null,
"e": 6640,
"s": 6533,
"text": "We import some packages and also the loggingService. This service helps us debugging, we do so on line 13."
},
{
"code": null,
"e": 6701,
"s": 6640,
"text": "On line 9 we create our app that will pass through requests."
},
{
"code": null,
"e": 6798,
"s": 6701,
"text": "Line 24; we tell the app that we want to use bodyParser; this way we can receive e.g. json data."
},
{
"code": null,
"e": 6836,
"s": 6798,
"text": "Line 29: we set the rules of the API."
},
{
"code": null,
"e": 6906,
"s": 6836,
"text": "Line 41 till 46: we catch some URL paths and pass them to our routes."
},
{
"code": null,
"e": 6991,
"s": 6906,
"text": "Line 59: create a server for our app and tell it to listen to port 5000 on localhost"
},
{
"code": null,
"e": 7259,
"s": 6991,
"text": "Now that our server is up and running it’s time to pass requests to the routes that we’ve defined on line 41 until 46. I’ll show an example of handling a route below. I’ve implemented the other routes in exactly the same way; you’ll be able to find in our repository."
},
{
"code": null,
"e": 7380,
"s": 7259,
"text": "In the code above you see how the ORM works when handling a route. Lets walk through the first route (line 11 until 39)."
},
{
"code": null,
"e": 7467,
"s": 7380,
"text": "line 11: we define the route. /searchmeans in our case localhost:5000/api/beers/search"
},
{
"code": null,
"e": 7761,
"s": 7467,
"text": "Line 14: we get data from our url. req.query retrieves url parameters (the bold part in https://mikehuls.medium.com/?source=twitter. We store the value of parameter q in a variable that’s also called q (for query). In the url localhost:5000/api/beers/search?q=ale the value for key q is ‘ale’."
},
{
"code": null,
"e": 7799,
"s": 7761,
"text": "Line 20: Do nothing if q is too short"
},
{
"code": null,
"e": 7868,
"s": 7799,
"text": "Line 23 until 30: return all beers that contain q (case insensitive)"
},
{
"code": null,
"e": 8059,
"s": 7868,
"text": "Line 33 res.retun is what our API returns. It will return an object with one key: ‘beers’ and an array of all the beers we’ve found in our database. We return with status code 200 (success)."
},
{
"code": null,
"e": 8189,
"s": 8059,
"text": "Line 36: if anything goes wrong in the try-block we let the client know by returning an error (we use the errorService for this)."
},
{
"code": null,
"e": 8400,
"s": 8189,
"text": "As you see we don’t have to write a line of SQL ourself; we can just call our models that translate our request and communicate with our database. It not only is very convenient, it also prevents SQL injection."
},
{
"code": null,
"e": 8470,
"s": 8400,
"text": "Let’s test our beers route! In beers there are three different paths:"
},
{
"code": null,
"e": 9068,
"s": 8470,
"text": "a GET for /search This route uses our ORM to query the Beers table. You are able to pass a searchword (q) like localhost:5000/api/beers/search?q=heine. It will then look for beers that are like the q (‘heine’).a GET for / This route takes the optional query parameter Id and tries to find a record if the Id is provided. Else it returns all beers. Try localhost:5000/api/beers or localhost:5000/api/beers?id=1a POST for / This route accepts a body which it will catch on line 72 (req.body). Try to POST the json below to localhost:5000/api/beers and you’ll see a new record appear in the database."
},
{
"code": null,
"e": 9279,
"s": 9068,
"text": "a GET for /search This route uses our ORM to query the Beers table. You are able to pass a searchword (q) like localhost:5000/api/beers/search?q=heine. It will then look for beers that are like the q (‘heine’)."
},
{
"code": null,
"e": 9479,
"s": 9279,
"text": "a GET for / This route takes the optional query parameter Id and tries to find a record if the Id is provided. Else it returns all beers. Try localhost:5000/api/beers or localhost:5000/api/beers?id=1"
},
{
"code": null,
"e": 9668,
"s": 9479,
"text": "a POST for / This route accepts a body which it will catch on line 72 (req.body). Try to POST the json below to localhost:5000/api/beers and you’ll see a new record appear in the database."
},
{
"code": null,
"e": 9728,
"s": 9668,
"text": "{ \"Name\": \"Bud Light\", \"Type\": \"Beer flavored water\"}"
},
{
"code": null,
"e": 9971,
"s": 9728,
"text": "This API provides some nice basic functionalities for our app! Using our ORM we are now able to use our API to search for, get and create countries, cities, venues, beers, users and reports. In the next part we’ll flesh out our API even more:"
},
{
"code": null,
"e": 10106,
"s": 9971,
"text": "We’ll add more in-depth associations (return all beers user X submitted or return all users that visited venue X and reported beer Y)."
},
{
"code": null,
"e": 10186,
"s": 10106,
"text": "Implement more functionalities for example: users want to update their password"
},
{
"code": null,
"e": 10259,
"s": 10186,
"text": "We’ll add security; I can only edit my own password, not someone else’s."
}
]
|
How to change the href value of <a> tag after click on button using JavaScript ? - GeeksforGeeks | 27 Apr, 2020
JavaScript is a high-level, interpreted, dynamically-typed and client-side scripting language. HTML is used to create static web pages. JavaScript enables interactive web pages when used along with HTML and CSS. Document Object Manipulation (DOM) is a programming interface for HTML and XML documents. DOM acts as an interface between JavaScript and HTML combined with CSS. The DOM represents the document as nodes and objects i.e. the browser turns every HTML tag into a JavaScript object that we can manipulate. DOM is an object-oriented representation of the web page, that can be modified with a scripting language such as JavaScript. To manipulate objects inside the document we need to select it and then manipulate.
Selecting an element can be done in five ways:
document.querySelector() Method: It returns the first element that matches the query.
document.querySelectorAll() Method: It returns all the elements that matches the query.
document.getElementById() Method: It returns the one element that matches the id.
document.getElementsByClassName() Method: It returns all the elements that matches the class.
document.getElementsByTagName() Method: It returns a list of the elements that matches the tag name.
DOM allows attribute manipulation. Attributes control the HTML tag’s behavior or provide additional information about the tag. JavaScript provides several methods for manipulating an HTML element attribute.
The following methods are used to manipulate the attributes:
getAttribute() method: It returns the current value of an attribute on the element and returns null if the specified attribute does not exist on the element.
setAttribute() method: It updates the value of an already existing attribute on the specified element else a new attribute is added with the specified name and value.
removeAttribute() method: It is used to remove an attribute of the specified element.
The below code demonstrates the attribute manipulation where the href attribute of <a> tag changes on button click. A function is called on button click which updates the attribute value. The function myFunction() is a JavaScript function and it makes the HTML code more interactive by making runtime modifications.
Example 1:
<!DOCTYPE html><html> <head> <title> How to change the href attribute dynamically using JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green"> GeeksforGeeks </h1> <h3> Change the href attribute value<br> dynamically using JavaScript </h3> <a href="https://www.google.com"> Go to Google </a> <br><br> <button onclick="myFunction()"> Click Here! </button> <script type="text/javascript"> function myFunction() { var link = document.querySelector("a"); link.getAttribute("href"); link.setAttribute("href", "https://www.geeksforgeeks.org"); link.textContent = "Go to GeeksforGeeks"; } </script></body> </html>
Output:
Explanation: The link opens https://www.google.com before the button is clicked. when the button is clicked then the function myFunction() is called which selects the href attribute of <a> tag and updates its value to https://www.geeksforgeeks.org, Since there is only one <a> tag in the HTML document and we aim to change its attribute value, we use querySelector() and the attribute is updated using setAttribute() method.
Example 2:
<!DOCTYPE html><html> <head> <title> How to change the href attribute dynamically using JavaScript? </title></head> <body style="text-align:center;"> <h1 style="color:green"> GeeksforGeeks </h1> <h3> Change the href attribute value<br> dynamically using JavaScript </h3> <a href="https://www.google.com" id="myLink"> Go to Google </a> <br><br> <button onclick="myFunction()"> Click Here! </button> <script type="text/javascript"> function myFunction() { document.getElementById('myLink').href ="https://www.geeksforgeeks.org"; document.getElementById("myLink") .textContent = "Go to GeeksforGeeks"; } </script></body> </html>
Output:
Explanation: The link opens https://www.google.com before the button is clicked. When the button is clicked the function myFunction() is called which selects the href attribute of <a> tag and updates its value to https://www.geeksforgeeks.org. In this approach, the getElementById() method is used to select the element whose destination URL is to be changed.
CSS-Misc
HTML-Misc
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.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Set the value of an input field in JavaScript
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25080,
"s": 25052,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 25803,
"s": 25080,
"text": "JavaScript is a high-level, interpreted, dynamically-typed and client-side scripting language. HTML is used to create static web pages. JavaScript enables interactive web pages when used along with HTML and CSS. Document Object Manipulation (DOM) is a programming interface for HTML and XML documents. DOM acts as an interface between JavaScript and HTML combined with CSS. The DOM represents the document as nodes and objects i.e. the browser turns every HTML tag into a JavaScript object that we can manipulate. DOM is an object-oriented representation of the web page, that can be modified with a scripting language such as JavaScript. To manipulate objects inside the document we need to select it and then manipulate."
},
{
"code": null,
"e": 25850,
"s": 25803,
"text": "Selecting an element can be done in five ways:"
},
{
"code": null,
"e": 25936,
"s": 25850,
"text": "document.querySelector() Method: It returns the first element that matches the query."
},
{
"code": null,
"e": 26024,
"s": 25936,
"text": "document.querySelectorAll() Method: It returns all the elements that matches the query."
},
{
"code": null,
"e": 26106,
"s": 26024,
"text": "document.getElementById() Method: It returns the one element that matches the id."
},
{
"code": null,
"e": 26200,
"s": 26106,
"text": "document.getElementsByClassName() Method: It returns all the elements that matches the class."
},
{
"code": null,
"e": 26301,
"s": 26200,
"text": "document.getElementsByTagName() Method: It returns a list of the elements that matches the tag name."
},
{
"code": null,
"e": 26508,
"s": 26301,
"text": "DOM allows attribute manipulation. Attributes control the HTML tag’s behavior or provide additional information about the tag. JavaScript provides several methods for manipulating an HTML element attribute."
},
{
"code": null,
"e": 26569,
"s": 26508,
"text": "The following methods are used to manipulate the attributes:"
},
{
"code": null,
"e": 26727,
"s": 26569,
"text": "getAttribute() method: It returns the current value of an attribute on the element and returns null if the specified attribute does not exist on the element."
},
{
"code": null,
"e": 26894,
"s": 26727,
"text": "setAttribute() method: It updates the value of an already existing attribute on the specified element else a new attribute is added with the specified name and value."
},
{
"code": null,
"e": 26980,
"s": 26894,
"text": "removeAttribute() method: It is used to remove an attribute of the specified element."
},
{
"code": null,
"e": 27296,
"s": 26980,
"text": "The below code demonstrates the attribute manipulation where the href attribute of <a> tag changes on button click. A function is called on button click which updates the attribute value. The function myFunction() is a JavaScript function and it makes the HTML code more interactive by making runtime modifications."
},
{
"code": null,
"e": 27307,
"s": 27296,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to change the href attribute dynamically using JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h3> Change the href attribute value<br> dynamically using JavaScript </h3> <a href=\"https://www.google.com\"> Go to Google </a> <br><br> <button onclick=\"myFunction()\"> Click Here! </button> <script type=\"text/javascript\"> function myFunction() { var link = document.querySelector(\"a\"); link.getAttribute(\"href\"); link.setAttribute(\"href\", \"https://www.geeksforgeeks.org\"); link.textContent = \"Go to GeeksforGeeks\"; } </script></body> </html>",
"e": 28146,
"s": 27307,
"text": null
},
{
"code": null,
"e": 28154,
"s": 28146,
"text": "Output:"
},
{
"code": null,
"e": 28579,
"s": 28154,
"text": "Explanation: The link opens https://www.google.com before the button is clicked. when the button is clicked then the function myFunction() is called which selects the href attribute of <a> tag and updates its value to https://www.geeksforgeeks.org, Since there is only one <a> tag in the HTML document and we aim to change its attribute value, we use querySelector() and the attribute is updated using setAttribute() method."
},
{
"code": null,
"e": 28590,
"s": 28579,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to change the href attribute dynamically using JavaScript? </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h3> Change the href attribute value<br> dynamically using JavaScript </h3> <a href=\"https://www.google.com\" id=\"myLink\"> Go to Google </a> <br><br> <button onclick=\"myFunction()\"> Click Here! </button> <script type=\"text/javascript\"> function myFunction() { document.getElementById('myLink').href =\"https://www.geeksforgeeks.org\"; document.getElementById(\"myLink\") .textContent = \"Go to GeeksforGeeks\"; } </script></body> </html>",
"e": 29428,
"s": 28590,
"text": null
},
{
"code": null,
"e": 29436,
"s": 29428,
"text": "Output:"
},
{
"code": null,
"e": 29796,
"s": 29436,
"text": "Explanation: The link opens https://www.google.com before the button is clicked. When the button is clicked the function myFunction() is called which selects the href attribute of <a> tag and updates its value to https://www.geeksforgeeks.org. In this approach, the getElementById() method is used to select the element whose destination URL is to be changed."
},
{
"code": null,
"e": 29805,
"s": 29796,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29815,
"s": 29805,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29831,
"s": 29815,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29838,
"s": 29831,
"text": "Picked"
},
{
"code": null,
"e": 29849,
"s": 29838,
"text": "JavaScript"
},
{
"code": null,
"e": 29866,
"s": 29849,
"text": "Web Technologies"
},
{
"code": null,
"e": 29893,
"s": 29866,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29991,
"s": 29893,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30000,
"s": 29991,
"text": "Comments"
},
{
"code": null,
"e": 30013,
"s": 30000,
"text": "Old Comments"
},
{
"code": null,
"e": 30074,
"s": 30013,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30146,
"s": 30074,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30191,
"s": 30146,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30237,
"s": 30191,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 30278,
"s": 30237,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30311,
"s": 30278,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30353,
"s": 30311,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30396,
"s": 30353,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30458,
"s": 30396,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
Python Program for Common Divisors of Two Numbers | In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given two integers, we need to display the common divisors of two numbers
Here we are computing the minimum of the two numbers we take as input. A loop to
calculate the divisors by computed by dividing each value from 1 to the minimum computed
Each time the condition is evaluated to be true counter is incremented by one.
Now let’s observe the concept in the implementation below−
Live Demo
a = 5
b = 45
count = 0
for i in range(1, min(a, b)+1):
if a%i==0 and b%i==0:
count+=1
print(count)
2
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about the python program to find the common divisors of two numbers. | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In this article, we will learn about the solution to the problem statement given below."
},
{
"code": null,
"e": 1251,
"s": 1150,
"text": "Problem statement − We are given two integers, we need to display the common divisors of two numbers"
},
{
"code": null,
"e": 1421,
"s": 1251,
"text": "Here we are computing the minimum of the two numbers we take as input. A loop to\ncalculate the divisors by computed by dividing each value from 1 to the minimum computed"
},
{
"code": null,
"e": 1500,
"s": 1421,
"text": "Each time the condition is evaluated to be true counter is incremented by one."
},
{
"code": null,
"e": 1559,
"s": 1500,
"text": "Now let’s observe the concept in the implementation below−"
},
{
"code": null,
"e": 1570,
"s": 1559,
"text": " Live Demo"
},
{
"code": null,
"e": 1678,
"s": 1570,
"text": "a = 5\nb = 45\ncount = 0\nfor i in range(1, min(a, b)+1):\n if a%i==0 and b%i==0:\n count+=1\nprint(count)"
},
{
"code": null,
"e": 1680,
"s": 1678,
"text": "2"
},
{
"code": null,
"e": 1781,
"s": 1680,
"text": "All the variables are declared in the local scope and their references are seen in the figure above."
},
{
"code": null,
"e": 1883,
"s": 1781,
"text": "In this article, we have learned about the python program to find the common divisors of two numbers."
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.